Skip to content

Interlinker0115/Rust-substrate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

My_Learning_Substrate

Substrate logo

Learn everything about Polkadot, Kusama chains, Substrate Pallets, ink! etc.

About

  • History:

    • Started as Parity Technologies & now called as Polkadot Foundation.
  • Substrate FRAME version (current): 3.0.0

  • Substrate ink! version (current): 4.0.0

  • Layer-0 i.e. L0

  • Polkadot can have a TPS of 100k to 1M considering the parachains (around 100).

  • chains (mainnet or testnet):

    • Relay chain
      • main/central chain
      • validators (297 approx.) ensuring the security of the network i.e. Polkadot
      • does not support SC (smart contract). It needs to have at least 1 parachain.
    • Parachains (100 max.)
      • the chains (L1 chains like Ethereum) that are connected to the relay chain. They can have SC.
        • The max. number of parachains is 100 supposedly, although this number is not confirmed as not tested yet. But, then it can be worked upon. There can be more parachains if the relay chain is upgraded based on the runtime logic.
      • collators (5 approx.)
      • they need to stake some auction fee in DOT (held every 6 months) to register a parachain on the relay chain. So, it's a weighted-fee.
      • slots
        • parachain slot (limited)
        • parachain bridge slot
        • parathread slot
  • Token details:

    • symbol: DOT
    • decimal: 10 (formerly it was 12 before 21-aug-2020)

      The DOT redenomination took place on 21 August 2020, known as Denomination Day, at block number 1_248_328. Source

    • lowest unit: Plancks. 1 DOT = 1e10 Plancks

    So, in block explorer, if the balance of an account is 1.1529 MUNIT, then it's 1.1529 * 1e6 UNIT i.e. 1.1529 * 1e6 DOT i.e. 1.1529 * 1e6 * 1e10 Plancks (including decimals).

  • Consensus Algorithm (NPoS):

    • voter/nominator:
      • Anyone who has min. 10 DOT on Polkadot (0.1 KSM on Kusama).
      • Max. 50,000 nominators allowed for electing the validators.
      • Max. 16 validators on Polkadot (24 on Kusama) can be nominated by a nominator.
      • The staked amount 100 DOT (say) is divided among the selected validators (say 16 or 6) equally i.e. 6.25 DOT each.
      • A voter can nominate less than 16 validators as well. But, the chances of validators getting selected are less. Also, the rewards are less.
      • Only the top 256 nominators for a specific validator get paid.
      • Cons:
        • One might loose their DOT in case of electing a malicious validator.
        • One might not gain any rewards
          • if none of the selected validator is elected.
          • if very few validators are elected. So, it's recommended to nominate max. 16 validators. Hence, one needs to do proper research.
    • validator:
      • Anyone who has min. 'x' (dynamic, changes over time) DOT on Polkadot to become active validator.
      • They need to stake their DOTs to get elected as a validator.
      • They can lose their staked DOTs, if they turn out to be malicious.
      • One has to verify their decentralized identity on Polkadot. Hence, would get โœ… mark on their profile. The ones whose identity is under verification would get โ˜‘๏ธ (grey color) mark.
      • One can be very popular if they are oversubscribed by the nominators.

    Best Practices for Nominating

    How do I know which validators to choose?

  • Mainnet:

    • relaychains:
      • Kusama (new feature launched here 1st),
      • Polkadot (at stable stage after feature launched on Kusama)
  • Testnet:

    • relaychain: Rococo
      • faucet: Rococo Faucet
      • parachain: Canvas, Contracts (by Parity)
  • There are 2 ways to develop dApp on a substrate chain:

    • M-1: write SC on native parachain/parathread using ink! (ink! is a Rust-based eDSL for writing Wasm smart contracts)
    • M-2: write SC on EVM supported parachain/parathread using solidity (solidity is a high-level language for implementing smart contracts)
  • pay fee with DOT for 2 different types of chains:

    • Parachain: weighted fee.
    • Parathread: participate on per use i.e. block basis or essentially pay-as-you-go.
  • Parachain vs Parathread:

Parachain Parathread
1. Parachain is always connected. 1. Parathread is not always connected.
2. DOT staked, hence weight-fee model 2. pay per block basis or pay-as-you-go or gas-metering model
3. supports SC 3. supports SC
  • If you think about Polkadot as a giant computer, parachains are like applications that are in physical memory and highly available. Parathreads are like applications that are on disk and can be copied into memory when needed. For those already familiar with how Bitcoin and Ethereum work, users bid to enter a parathread block into the relay chain similar to how users bid to include a transaction in a Bitcoin or Ethereum block.

  • Parathreads are ideal for three types of applications:

    • applications seeking an on-ramp to Polkadot,
    • applications worried about losing parachain slots, and
    • applications that have more reads than writes.
  • Parathreads increases the number of applications that can operate on Polkadot by pooling them to share parachain slots. This will allow more infrastructure chains and improve composability."

Parachains require 20,000 DOT tokens to be staked in order to secure a slot. And these projects don't have enough budget can use Parathreads so that they can come back to the parachain slot auction later.

graph LR
Parachain --when less budget--> ParaThread --when more budget--> Parachain
Loading
  • Polkadot vs SC: "Polkadot does not use a gas-metering model, but a weight-fee model, meaning Parachains do not have a gas-metered model in their logic. Parachains can implement powerful programming languages. Better put, parachains try to be proactive, while smart contract platforms are event-driven."

  • EVM vs WASM:

EVM WASM
it isnโ€™t as fast as it should be and directly impact network efficiency it expands the supported languages that a developer can write a smart contract in, such as Rust, C/C++, C#, and Typescript.
it uses opcodes that are not optimized for different hardware platforms. it is is highly performant.
The support and reach for developing smart contracts are limited. it is optimized for different hardware platforms.
  • Pallet: module that trigger functionality on a parachain. Typically like system contracts on a L1 Blockchain.

Installation

Quickstart

Parachains

  • People interacting with parachains via smart contracts won't have to have DOT tokens to pay for fees. Instead, they'll pay in the native token of the parachain. So, with this feature user would not need to have DOT tokens in order to make any transaction on parachain. This is a huge step towards mass adoption because it would be easier for the user to interact with the parachain rather than having to buy DOT tokens.
  • In order to reserve limited parachain slots, parachains must stake DOT tokens. The more DOT tokens staked, the higher the parachain's priority in the auction. Although their is a minimum DOT tokens (say 1M) to be staked.
  • Now, the concern is to how to arrange that much amount of DOT tokens.
    1. One can buy DOT tokens from the market or already held DOT tokens.
    2. Ask the investor to stake DOT tokens as loan on your behalf. There is a guarantee of getting the money back as it would happen on-chain via pallets.
    3. Ask the community to stake DOT tokens via crowdloan on your behalf. There is a guarantee of getting the money back as it would happen on-chain via pallets.

Astar

Has partnered with Alchemy

Acala

Hub for DeFi in Polkadot, Kusama.

  • Acala is on Polkadot
  • Karura is on Kusama

Moonbeam

EVM โœ…

Centrifuge

Block Explorer

Switch to any L0, parachain, parathread network.

  • Subscan
    • Beautiful looking UI/UX for viewing txns, blocks, accounts for Polkadot, Kusama, Rococo relaychain & parachains & testnets.
  • Polkadot.js
  • Polkascan
    • available for only Polkadot, Kusama, no local node support
  • IPFS based Polkadot.js
    • relatively slow

Wallet

These are the wallets (like Metamask):

URL: https://wiki.polkadot.network/docs/build-wallets


Browser extension: https://chrome.google.com/webstore/detail/polkadot%7Bjs%7D-extension/mopnmbcafieddcagagdcbnhejhlodfdd/related


Mobile wallets: https://polkawallet.io/

Development

  • Substrate allows the different features of Polkadot as it allows a modular design with pallets. Using different pallets like balance, account, transaction, block, consensus one can create own parachain.
  • Substrate (by default) has a WASM runtime but it also allows to create a custom runtime like EVM using pallet programming. So, if someone wants to create a EVM runtime for running EVM SCs, then a set of pallet (account, balance, consensus, etc.) has to be created in order to join them together & form the required runtime for a parachain with that runtime.
  • FRAME is the library which is used to build DApps.

There are different FRAME pallets to choose from in order to add into runtime.

Another way to look at it:

For networking, substrate use libp2p protocol (developed by IPFS creators).

Using this template, we can start a chain locally. repo.

Using the front-end template, we can view the information on a website. repo.

Substrate pallets:

The development workflow to pallet:

where, sp: substrate primitive, sc: substrate client

Auction

In Polkadot, in order to secure a slot, a project/parachain has to bid in the auction. This auction has no end time. The winning is completely based on the highest amounts in terms of ranking.

This auction is similar to Candle auction in 16th century.

There is also a feature of crowdloan where anyone holding DOT can lend to project/parachain. And after the auction period is over, the DOTs are returned back to the owners permissionlessly.

Tools

Packages

All web3 packages here:

Polkadot vs Kusama

  • All the new features are deployed on Kusama 1st & then it gets deployed on Polkadot.
  • There are plans to brige both these relay chains

Interoperability

There are message protocols which are used for communicating b/w chains. E.g. XCM, XCMP

  • XCM: Cross Consensus Message format
  • XCMP: Cross Chain Messaging Protocol

Network architecture

The collators give the proof (parachains' block when reached finality i.e. 'proof of validity') to the validators who then add to the relay chain.

Each parachain has 2 options of adding blocks into the relay chain:

  • slot (stake DOT & secure position)
  • parathread pool (pay-as-you-go model)

State transition

It stays in merkle tree.

Here, only the nodes which have been changed in terms of data, those gets added in hash. The figure above shows the transition state.

Proof of Validity

Validation process

A receipt is used to put into the blocks of relay chain

Upgrades

There is a set_code function which allows to upgrade the network.

It shows comparo b/w legacy & polkadot blockchains.

Repositories

By ParityTech:

By others:

Troubleshooting

1. 1010: Invalid Transaction: Transaction has a bad signature

Raised a question over stackexchange.

  • Cause: Doesn't perform as expected. Seen this error on Polkadot JS Apps UI.
  • Solution: Just reload the page. Use cmd + r to reload the App.

2. error[E0275]: overflow evaluating the requirement <Runtime as pallet_voting::Config>::MaxProposalLength == _

  • Cause: This error is seen when we try to run the cargo check -p node-template-runtime command or cargo build -r command.
  • Solution: We need to remove Self in the code like this:

Before:

parameter_types! {
 pub const MaxProposalLength: u32 = 100;
 pub const MinProposalLength: u32 = 5;
}

/// Configure the pallet-voting in pallets/voting.
impl pallet_voting::Config for Runtime {
 type RuntimeEvent = RuntimeEvent;
 type MaxProposalLength = Self::MaxProposalLength;
 type MinProposalLength = Self::MinProposalLength;
}

After:

parameter_types! {
 pub const MaxProposalLength: u32 = 100;
 pub const MinProposalLength: u32 = 5;
}

/// Configure the pallet-voting in pallets/voting.
impl pallet_voting::Config for Runtime {
 type RuntimeEvent = RuntimeEvent;
 type MaxProposalLength = MaxProposalLength;
 type MinProposalLength = MinProposalLength;
}

3. error: no rules expected the token =

  • Cause: This error is seen during runtime build as there is no type annotation used the variables.

    307 |     pub const MaxProposalLength = 100;
          |                                 ^ no rules expected this token in macro call
  • Solution: We need to add type annotation to the variables like this:

Before:

// runtime/src/lib.rs
parameter_types! {
 pub const MaxProposalLength = 100;
 pub const MinProposalLength = 5;
}

After:

// runtime/src/lib.rs
parameter_types! {
 pub const MaxProposalLength: u32 = 100;
 pub const MinProposalLength: u32 = 5;
}

4. How to fix parity_scale_codec::MaxEncodedLen is not implemented for T?

  • Cause: The compiler thinks that T must also be bounded by MaxEncodedLen, even though T itself is not being used in the actual types.

  • Solution:

    • M-1: Add #[codec(mel_bound())] to the type definition:

      // Struct for holding Kitty information.
      #[derive(Clone, Encode, Decode, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
      #[scale_info(skip_type_params(T))]
      #[codec(mel_bound())] // <---------------- Here
      pub struct Kitty<T: Config> {
          pub dna: [u8; 16],   // Using 16 bytes to represent a kitty DNA
          pub price: Option<BalanceOf<T>>,
          pub gender: Gender,
          pub owner: AccountOf<T>,
      }
    • M-2: Add generic type to the type definition:

      // Struct for holding Kitty information.
      #[derive(Clone, Encode, Decode, PartialEq, RuntimeDebug, TypeInfo, MaxEncodedLen)]
      pub struct Kitty<Account, Balance> {
        pub dna: [u8; 16],   // Using 16 bytes to represent a kitty DNA
        pub price: Option<Balance>,
        pub gender: Gender,
        pub owner: Account,
      }

      Sources: 1, 2

5. type mismatch resolving <Test as Config>::AccountData == AccountData<u128>

  • Cause: Didn't use pallet_balances in impl block of frame_system for Test runtime
  • Solution: Add pallet_balances in impl block of frame_system for Test runtime.

-type AccountData = ();
+type AccountData = pallet_balances::AccountData<u128>;

6. running 1 test thread 'tests::open_fd' panicked at 'get_version_1 called outside of an Externalities-provided environment.'

  • Cause: Didn't use new_test_ext().execute_with(|| {}); inside the test function
  • Solution: Add new_test_ext().execute_with(|| {}); inside the test function

Before:

#[test]
fn test_something() {
    // Test code
}

After:

#[test]
fn test_something() {
    new_test_ext().execute_with(|| {
        // Test code
    });
}

7. error: the wasm32-unknown-unknown target is not supported by default, you may need to enable the "js" feature. For more information see: https://docs.rs/getrandom/#webassembly-support

Details:

|
  235 | /         compile_error!("the wasm32-unknown-unknown target is not supported by \
  236 | |                         default, you may need to enable the \"js\" feature. \
  237 | |                         For more information see: \
  238 | |                         https://docs.rs/getrandom/#webassembly-support");
      | |________________________________________________________________________^

  error[E0433]: failed to resolve: use of undeclared crate or module `imp`
     --> /Users/jackson/.cargo/registry/src/github.com-1ecc6299db9ec823/getrandom-0.2.7/src/lib.rs:262:5
      |
  262 |     imp::getrandom_inner(dest)
      |     ^^^ use of undeclared crate or module `imp`
  • Cause: it looks like one of your dependencies tries to generate random numbers.
  • Solution: Insert default-feature = false into one of your dependency in `Cargo.toml

    You can enable the default features in [dev-dependencies] i.e. default-features = true or remove it altogether as implemented by default, but you should not enable that in [dependencies] as it might trigger randomization.

// Cargo.toml

[dependencies]
- sp-core = { version = "7.0.0", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" }
+ sp-core = { version = "7.0.0", default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.42" }

8. Error: error[E0463]: can't find crate for std

Error details:
Rust WASM toolchain not installed, please install it!

  Further error information:
  ------------------------------------------------------------
     Compiling wasm-test v1.0.0 (/var/folders/cw/dc7mkcsd6yx76lscv6w1hpcw0000gn/T/.tmp3NWr2N)
  error[E0463]: can't find crate for `std`
    |
    = note: the `wasm32-unknown-unknown` target may not be installed
    = help: consider downloading the target with `rustup target add wasm32-unknown-unknown`

  error: requires `sized` lang_item

  libunwind: malformed __unwind_info at 0x18AC83CA8 bad second level page
  error: cannot find macro `println` in this scope
   --> src/main.rs:3:5
    |
  3 |                 println!("{}", env!("RUSTC_VERSION"));
    |                 ^^^^^^^

  For more information about this error, try `rustc --explain E0463`.
  libunwind: malformed __unwind_info at 0x18AC83CA8 bad second level page
  error: could not compile `wasm-test` (lib) due to 2 previous errors
  warning: build failed, waiting for other jobs to finish...
  error: could not compile `wasm-test` (bin "wasm-test") due to 3 previous errors
  ------------------------------------------------------------

warning: build failed, waiting for other jobs to finish...
  • Cause: wasm32-unknown-unknown target is not installed or may be it's installed but due to switching of channels, it's not supported anymore.
  • Solution: If the error is popping up even after doing $ rustup target add wasm32-unknown-unknown & $ rustup target install wasm32-unknown-unknown then just uninstall rustup entirely and then reinstall. Build again. It would be fixed now.

References

Official

flowchart
    parity[paritytech.github.io] --> devhub[polkadot_sdk_docs]

    devhub --> polkadot_sdk
    devhub --> reference_docs
    devhub --> tutorial

    polkadot_sdk --> substrate
    polkadot_sdk --> frame
    polkadot_sdk --> cumulus
    polkadot_sdk --> polkadot
    polkadot_sdk --> xcm
Loading

Unofficial

Blogs

Videos

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published