From b6c92facf772fd4cb2ccf4af6585e4b316bd9c47 Mon Sep 17 00:00:00 2001 From: Shawn Tabrizi Date: Tue, 6 Aug 2024 18:36:26 -0400 Subject: [PATCH] make intro a simple starting paragraph --- steps/0/README.md | 65 +------------ steps/1/README.md | 123 ++++++++---------------- steps/1/gitorial_metadata.json | 4 +- steps/1/src/impls.rs | 9 -- steps/1/src/lib.rs | 37 -------- steps/10/README.md | 65 +++++++++---- steps/10/gitorial_metadata.json | 4 +- steps/10/src/lib.rs | 6 -- steps/11/README.md | 29 +++++- steps/11/gitorial_metadata.json | 2 +- steps/11/src/lib.rs | 7 +- steps/12/README.md | 52 +---------- steps/12/gitorial_metadata.json | 4 +- steps/12/src/impls.rs | 6 -- steps/13/README.md | 52 ++++++++++- steps/13/gitorial_metadata.json | 2 +- steps/13/src/impls.rs | 9 +- steps/14/README.md | 142 +--------------------------- steps/14/gitorial_metadata.json | 2 +- steps/14/src/impls.rs | 1 - steps/14/src/lib.rs | 6 +- steps/15/README.md | 142 +++++++++++++++++++++++++++- steps/15/gitorial_metadata.json | 2 +- steps/15/src/impls.rs | 3 +- steps/15/src/lib.rs | 4 +- steps/16/README.md | 82 +--------------- steps/16/gitorial_metadata.json | 2 +- steps/16/src/impls.rs | 2 - steps/16/src/lib.rs | 1 - steps/17/README.md | 82 +++++++++++++++- steps/17/gitorial_metadata.json | 2 +- steps/17/src/impls.rs | 6 +- steps/17/src/lib.rs | 3 +- steps/18/README.md | 77 +--------------- steps/18/gitorial_metadata.json | 4 +- steps/18/src/lib.rs | 7 -- steps/19/README.md | 77 +++++++++++++++- steps/19/gitorial_metadata.json | 2 +- steps/19/src/lib.rs | 8 +- steps/2/README.md | 128 ++++++++++++++++--------- steps/2/gitorial_metadata.json | 2 +- steps/20/README.md | 48 +--------- steps/20/gitorial_metadata.json | 4 +- steps/20/src/impls.rs | 2 - steps/20/src/lib.rs | 4 - steps/21/README.md | 48 +++++++++- steps/21/gitorial_metadata.json | 2 +- steps/21/src/impls.rs | 5 +- steps/21/src/lib.rs | 7 +- steps/22/README.md | 45 +-------- steps/22/gitorial_metadata.json | 2 +- steps/22/src/impls.rs | 4 - steps/22/src/lib.rs | 1 - steps/23/README.md | 45 ++++++++- steps/23/gitorial_metadata.json | 2 +- steps/23/src/impls.rs | 7 +- steps/23/src/lib.rs | 2 +- steps/24/README.md | 6 +- steps/24/gitorial_metadata.json | 2 +- steps/25/README.md | 92 +----------------- steps/25/gitorial_metadata.json | 2 +- steps/25/src/lib.rs | 8 -- steps/26/README.md | 92 +++++++++++++++++- steps/26/gitorial_metadata.json | 2 +- steps/26/src/lib.rs | 12 ++- steps/27/README.md | 131 +------------------------- steps/27/gitorial_metadata.json | 2 +- steps/27/src/impls.rs | 5 - steps/27/src/lib.rs | 5 - steps/28/README.md | 131 +++++++++++++++++++++++++- steps/28/gitorial_metadata.json | 2 +- steps/28/src/impls.rs | 8 +- steps/28/src/lib.rs | 9 +- steps/29/README.md | 53 +---------- steps/29/gitorial_metadata.json | 2 +- steps/29/src/impls.rs | 12 --- steps/29/src/lib.rs | 1 - steps/3/README.md | 115 ++++++++--------------- steps/3/gitorial_metadata.json | 2 +- steps/3/src/lib.rs | 1 - steps/30/README.md | 53 ++++++++++- steps/30/gitorial_metadata.json | 2 +- steps/30/src/impls.rs | 26 +++--- steps/30/src/lib.rs | 3 +- steps/31/README.md | 97 +------------------ steps/31/gitorial_metadata.json | 2 +- steps/31/src/impls.rs | 3 - steps/31/src/lib.rs | 6 -- steps/32/README.md | 97 ++++++++++++++++++- steps/32/gitorial_metadata.json | 2 +- steps/32/src/impls.rs | 4 +- steps/32/src/lib.rs | 9 +- steps/33/README.md | 70 +------------- steps/33/gitorial_metadata.json | 2 +- steps/33/src/impls.rs | 3 - steps/33/src/lib.rs | 9 +- steps/34/README.md | 70 +++++++++++++- steps/34/gitorial_metadata.json | 2 +- steps/34/src/impls.rs | 6 +- steps/34/src/lib.rs | 5 +- steps/35/README.md | 11 +-- steps/35/gitorial_metadata.json | 2 +- steps/36/README.md | 35 ++----- steps/36/gitorial_metadata.json | 2 +- steps/36/src/impls.rs | 11 --- steps/36/src/lib.rs | 18 ---- steps/37/README.md | 32 ++++++- steps/37/gitorial_metadata.json | 2 +- steps/37/src/impls.rs | 14 ++- steps/37/src/lib.rs | 27 ++++-- steps/38/README.md | 66 +------------ steps/38/gitorial_metadata.json | 2 +- steps/38/src/impls.rs | 23 ----- steps/38/src/lib.rs | 5 - steps/39/README.md | 66 ++++++++++++- steps/39/gitorial_metadata.json | 2 +- steps/39/src/impls.rs | 39 ++++---- steps/39/src/lib.rs | 8 +- steps/4/README.md | 108 +++++++++++++++++----- steps/4/gitorial_metadata.json | 2 +- steps/4/src/lib.rs | 2 +- steps/40/README.md | 119 +----------------------- steps/40/gitorial_metadata.json | 4 +- steps/40/src/lib.rs | 9 -- steps/41/README.md | 4 +- steps/41/gitorial_metadata.json | 2 +- steps/41/src/lib.rs | 12 ++- steps/42/README.md | 159 ++++++++++++++------------------ steps/42/gitorial_metadata.json | 2 +- steps/42/src/impls.rs | 1 - steps/42/src/lib.rs | 9 -- steps/43/README.md | 140 +++++++++++++++++++++++++++- steps/43/gitorial_metadata.json | 2 +- steps/43/src/impls.rs | 3 +- steps/43/src/lib.rs | 12 ++- steps/44/README.md | 24 +---- steps/44/gitorial_metadata.json | 4 +- steps/44/src/impls.rs | 11 --- steps/44/src/lib.rs | 17 ---- steps/45/README.md | 24 ++++- steps/45/gitorial_metadata.json | 2 +- steps/45/src/impls.rs | 18 ++-- steps/45/src/lib.rs | 26 ++++-- steps/46/README.md | 12 +-- steps/46/gitorial_metadata.json | 2 +- steps/46/src/impls.rs | 8 -- steps/47/README.md | 12 ++- steps/47/gitorial_metadata.json | 2 +- steps/47/src/impls.rs | 11 ++- steps/48/README.md | 40 +------- steps/48/gitorial_metadata.json | 2 +- steps/48/src/impls.rs | 11 --- steps/48/src/lib.rs | 17 ---- steps/49/README.md | 40 +++++++- steps/49/gitorial_metadata.json | 2 +- steps/49/src/impls.rs | 18 ++-- steps/49/src/lib.rs | 26 ++++-- steps/5/README.md | 77 +++++----------- steps/5/gitorial_metadata.json | 2 +- steps/5/src/impls.rs | 1 - steps/5/src/lib.rs | 2 +- steps/50/README.md | 113 +---------------------- steps/50/gitorial_metadata.json | 2 +- steps/50/src/impls.rs | 16 ---- steps/50/src/lib.rs | 4 - steps/51/README.md | 113 ++++++++++++++++++++++- steps/51/gitorial_metadata.json | 2 +- steps/51/src/impls.rs | 22 +++-- steps/51/src/lib.rs | 6 +- steps/52/README.md | 56 +---------- steps/52/gitorial_metadata.json | 4 +- steps/53/.gitignore | 5 + steps/{1 => 53}/Cargo.lock | 0 steps/{1 => 53}/Cargo.toml | 0 steps/53/README.md | 55 +++++++++++ steps/53/gitorial_metadata.json | 4 + steps/{1 => 53}/rustfmt.toml | 0 steps/53/src/impls.rs | 91 ++++++++++++++++++ steps/53/src/lib.rs | 112 ++++++++++++++++++++++ steps/6/README.md | 85 ++++++++++------- steps/6/gitorial_metadata.json | 2 +- steps/6/src/impls.rs | 2 +- steps/6/src/lib.rs | 2 +- steps/7/README.md | 90 ++++++------------ steps/7/gitorial_metadata.json | 2 +- steps/7/src/impls.rs | 1 + steps/7/src/lib.rs | 2 +- steps/8/README.md | 95 +++++++++++-------- steps/8/gitorial_metadata.json | 2 +- steps/8/src/lib.rs | 2 +- steps/9/README.md | 80 ++++++++-------- steps/9/gitorial_metadata.json | 2 +- steps/9/src/lib.rs | 1 + 193 files changed, 2506 insertions(+), 2490 deletions(-) delete mode 100644 steps/1/src/impls.rs delete mode 100644 steps/1/src/lib.rs create mode 100644 steps/53/.gitignore rename steps/{1 => 53}/Cargo.lock (100%) rename steps/{1 => 53}/Cargo.toml (100%) create mode 100644 steps/53/README.md create mode 100644 steps/53/gitorial_metadata.json rename steps/{1 => 53}/rustfmt.toml (100%) create mode 100644 steps/53/src/impls.rs create mode 100644 steps/53/src/lib.rs diff --git a/steps/0/README.md b/steps/0/README.md index 345ec7a7..10c0a3f1 100644 --- a/steps/0/README.md +++ b/steps/0/README.md @@ -1,66 +1,9 @@ # Introduction -Welcome to the new Substrate Collectables Workshop. +Welcome to the Substrate Collectables Workshop. -The goal of this tutorial is to **teach by experience** various entry level concepts around developing on [Polkadot](https://polkadot.network/). +The goal of this tutorial is to **teach by experience** various entry level concepts around developing with the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk). -Before we get started writing code, we will need to cover some basics. +This tutorial will walk you through the steps of building an NFT Marketplace, themed around collectable digital pets called Substrate Kitties! -## Prerequisites - -The tutorial is designed to be completed by anyone with basic familiarity with [Rust](https://www.rust-lang.org/), and little to no familiarity with the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk). - -If you do not feel comfortable with the level of Rust used in this tutorial, we recommend you first check out the [`rust-state-machine`](https://github.com/shawntabrizi/rust-state-machine) tutorial. - -## Tutorial Structure - -This tutorial is broken up into small steps with documentation and code. - -Documentation should teach you all the concepts needed to complete the tutorial, while the code will ensure that you can actually execute on the knowledge gained. - -The code in each step should have comments marked `TODO`, which indicate the actions you need to take in order to complete the step successfully. - -At each step, we include a `diff` view so that you can see what has changed from the last step (new action items), and what should change to complete the step (the solution). - -At the end of each step, you should be able to run all the following commands without any errors or warnings: - -- `cargo +nightly fmt` -- `cargo +nightly clippy` -- `cargo test` - -We recommend you run these during each step in the tutorial to confirm you are doing everything correctly. - -## Clone the Starting Template - -The best way to follow this tutorial is to clone the starting template, and follow the steps of the tutorial locally. - -Run the following: - -```bash -git clone https://github.com/shawntabrizi/substrate-collectables-workshop/ -b starting-template --single-branch -cd substrate-collectables-workshop -``` - -Or access the template directly here: - -[https://github.com/shawntabrizi/substrate-collectables-workshop/releases/tag/starting-template](https://github.com/shawntabrizi/substrate-collectables-workshop/releases/tag/starting-template) - -The starting template includes a `README` with instructions to setup your working environment. Follow those instructions. - -Make sure you are able to run the following checks on this starting template without warnings or errors: - -```bash -cargo +nightly fmt -cargo +nightly clippy -cargo test -``` - -It may take a while for this to complete based on how powerful your computer is. - -Feel free to move onto the next steps while these checks are compiling. - -## Contribute - -This tutorial is completely free to use, modify, and distribute in any way you see fit. - -If you catch any problems with the tutorial or have ideas on how it can be improved, open an [issue](https://github.com/shawntabrizi/substrate-collectables-workshop/issues) or a [pull request](https://github.com/shawntabrizi/substrate-collectables-workshop/pulls). +Let's get started! diff --git a/steps/1/README.md b/steps/1/README.md index a35ffcbe..dfce3e91 100644 --- a/steps/1/README.md +++ b/steps/1/README.md @@ -1,113 +1,64 @@ -# Polkadot-SDK +# Setup -Our starting template for this tutorial uses the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk). +Before we start writing code, we will need to setup your computer for this tutorial. -This is the same technology stack used to build and power the [Polkadot Network](https://polkadot.network/). +## Prerequisites -To better understand what you will be doing in this tutorial, we need to start with a high level overview of blockchains. +The tutorial is designed to be completed by anyone with basic familiarity with [Rust](https://www.rust-lang.org/), and little to no familiarity with the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk). -## Blockchain +If you do not feel comfortable with the level of Rust used in this tutorial, we recommend you first check out the [`rust-state-machine`](https://github.com/shawntabrizi/rust-state-machine) tutorial. -Blockchains are the foundation of building Web3 technologies. +## Tutorial Structure -Web3 is a promise toward a world with less trust, and more truth. +This tutorial is broken up into small steps with documentation and code. -Through blockchain technology, we are able to develop and deploy software that are decentralized, open, permissionless, censorship resistant, and independently verifiable. +Documentation should teach you all the concepts needed to complete the tutorial, while the code will ensure that you can actually execute on the knowledge gained. -The main purpose of a blockchain node is to come to consensus with other nodes on the decentralized network. +The code in each step should have comments marked `TODO`, which indicate the actions you need to take in order to complete the step successfully. -
+At each step, we include a `diff` view so that you can see what has changed from the last step (new action items), and what should change to complete the step (the solution). -Deep Dive +At the end of each step, you should be able to run all the following commands without any errors or warnings: -If you want to learn more about blockchains, check out the following video from the Polkadot Blockchain Academy: +- `cargo +nightly fmt` +- `cargo +nightly clippy` +- `cargo test` - +We recommend you run these during each step in the tutorial to confirm you are doing everything correctly. -
+## Clone the Starting Template -## Runtime +The best way to follow this tutorial is to clone the starting template, and follow the steps of the tutorial locally. -At the heart of a blockchain is a [state transition function](https://en.wikipedia.org/wiki/Finite-state_machine) (STF). +Run the following: -This is the logic of the blockchain, and defines all the ways a blockchain is allowed to manipulate the blockchain state. +```bash +git clone https://github.com/shawntabrizi/substrate-collectables-workshop/ -b starting-template --single-branch +cd substrate-collectables-workshop +``` -In the `polkadot-sdk` we refer to this logic as the blockchain's runtime. +Or access the template directly here: -All nodes on a blockchain network have and use the same runtime, allowing them to come to consensus about changes to a blockchain. +[https://github.com/shawntabrizi/substrate-collectables-workshop/releases/tag/starting-template](https://github.com/shawntabrizi/substrate-collectables-workshop/releases/tag/starting-template) -
+### Install Dependencies -Deep Dive +The starting template includes a `README` with instructions to setup your working environment. Follow those instructions. -To learn more about the runtime, and its role inside of the `polkadot-sdk`, check out this video from the Polkadot Blockchain Academy: +Make sure you are able to run the following checks on this starting template without warnings or errors: - +```bash +cargo +nightly fmt +cargo +nightly clippy +cargo test +``` -
+It may take a while for this to complete based on how powerful your computer is. -## FRAME +Feel free to move onto the next steps while these checks are compiling. -The `polkadot-sdk` provides a developer framework called FRAME. +## Contribute -FRAME is an opinionated framework on how one should quickly and easily build and maintain a blockchain's runtime. +This tutorial is completely free to use, modify, and distribute in any way you see fit. -> NOTE: It is important to clarify that FRAME is not the only way you can develop a runtime for the `polkadot-sdk`, but it is the one that the Polkadot Network uses and is most supported by the ecosystem. - -You can see in our project, nearly all of our dependencies come from a single crate named [`frame`](https://docs.rs/polkadot-sdk-frame/0.6.0/polkadot_sdk_frame/index.html). - -This crate is really just a convenience wrapper around other smaller crates, all exposed through [`frame::deps`](https://docs.rs/polkadot-sdk-frame/0.6.0/polkadot_sdk_frame/deps/index.html). - -For our tutorial, most of the types and traits we need access to are automatically brought into scope through [`frame::prelude::*`](https://docs.rs/polkadot-sdk-frame/0.6.0/polkadot_sdk_frame/prelude/index.html), however once in a while, we will need to import something more specific from [`frame::primitives`](https://docs.rs/polkadot-sdk-frame/0.6.0/polkadot_sdk_frame/primitives/index.html) or [`frame::traits`](https://docs.rs/polkadot-sdk-frame/0.6.0/polkadot_sdk_frame/traits/index.html). - -## Pallets - -FRAME's key decision is to break apart the blockchain runtime into separate logical pieces that can choose to interact with one another. - -These logical pieces are called Pallets. - -TODO: Add images. - -You can think of different Pallets as different applications or functions that your blockchain exposes. - -You can also think of Pallets very similar to traditional blockchain smart contracts, however Pallets are more powerful and execute much faster than smart contracts. - -
- -Deep Dive - -To learn more about FRAME and Pallets, check out this video from the Polkadot Blockchain Academy: - - - -
- -## NFTs - -Non-Fungible Tokens (NFTs) are a type of token which can be created and traded on a blockchain. - -As their name indicated, each NFT is totally unique, and therefore non-fungible with one another. - -NFTs can be used for many things, for example: - -- Representing real world assets - - Ownership Rights - - Access Rights -- Digital assets - - Music - - Images - - Skins - - Characters -- and much more... - -## Starting Template - -The template for this project is a minimal starting point for developing a custom Pallet. - -In this tutorial, we will create a Pallet which allows us to create and manage a collection of NFTs. - -Our NFTs will represent kitties, which will be a digital pet that can be created, traded, and more. - -This Pallet could then be included into a `polkadot-sdk` project and used to launch a Web3 application on the Polkadot Network. - -TODO: need to create and link to a tutorial creating and launching a runtime with omninode. +If you catch any problems with the tutorial or have ideas on how it can be improved, open an [issue](https://github.com/shawntabrizi/substrate-collectables-workshop/issues) or a [pull request](https://github.com/shawntabrizi/substrate-collectables-workshop/pulls). diff --git a/steps/1/gitorial_metadata.json b/steps/1/gitorial_metadata.json index 9440095b..c7ae8fe8 100644 --- a/steps/1/gitorial_metadata.json +++ b/steps/1/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "action: learn about the polkadot sdk" -} \ No newline at end of file + "commitMessage": "action: setup" +} diff --git a/steps/1/src/impls.rs b/steps/1/src/impls.rs deleted file mode 100644 index 03abf99e..00000000 --- a/steps/1/src/impls.rs +++ /dev/null @@ -1,9 +0,0 @@ -use super::*; -use frame::prelude::*; - -impl Pallet { - pub fn mint(owner: T::AccountId) -> DispatchResult { - Self::deposit_event(Event::::Created { owner }); - Ok(()) - } -} diff --git a/steps/1/src/lib.rs b/steps/1/src/lib.rs deleted file mode 100644 index 7b6c6a21..00000000 --- a/steps/1/src/lib.rs +++ /dev/null @@ -1,37 +0,0 @@ -#![cfg_attr(not(feature = "std"), no_std)] - -mod impls; - -use frame::prelude::*; -pub use pallet::*; - -#[frame::pallet(dev_mode)] -pub mod pallet { - use super::*; - - #[pallet::pallet] - pub struct Pallet(core::marker::PhantomData); - - #[pallet::config] - pub trait Config: frame_system::Config { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; - } - - #[pallet::event] - #[pallet::generate_deposit(pub(super) fn deposit_event)] - pub enum Event { - Created { owner: T::AccountId }, - } - - #[pallet::error] - pub enum Error {} - - #[pallet::call] - impl Pallet { - pub fn create_kitty(origin: OriginFor) -> DispatchResult { - let who = ensure_signed(origin)?; - Self::mint(who)?; - Ok(()) - } - } -} diff --git a/steps/10/README.md b/steps/10/README.md index 22b856b5..0f3623b8 100644 --- a/steps/10/README.md +++ b/steps/10/README.md @@ -1,28 +1,61 @@ -# Storage Values +# Storage Basics -The most basic storage type for a blockchain is a single `StorageValue`. +Now that we have covered the basics of Pallets, and gone through all of the template code, we can start writing some code ourselves. -A `StorageValue` is used to place a single object into the blockchain storage. +In this section you will learn the basics of creating and using storage in your Pallet. -A single object can be as simple as a single type like a `u32`, or more complex structures, or even vectors. +But before we can start coding, we need to learn some basics about blockchains. -What is most important to understand is that a `StorageValue` places a single entry into the merkle trie. So when you read data, you read all of it. When you write data, you write all of it. This is in contrast to a `StorageMap`, which you will learn about next. +## Hash Functions -## Construction +Hash functions are an important tool throughout blockchain development. -We constructed a simple `StorageValue` for you in the code, but let's break it down: +A hash function takes an arbitrary sized input and returns a fixed-size string of bytes. -```rust -#[pallet::storage] -pub(super) type CountForKitties = StorageValue; -``` +This output, usually called a hash, is unique to each unique input. Even a small change to the input creates a dramatic change to the output. -As you can see, our storage is a type alias for a new instance of `StorageValue`. +Hash functions have several key properties: -Our storage value has a parameter `Value` where we can define the type we want to place in storage. In this case, it is a simple `u32`. +- Deterministic: The same input always produces the same output. +- Pre-image Resistant: It is difficult to derive the original input from its hash value. +- Collision Resistant: It’s hard to find two different inputs that produce the same hash output. -You will also notice `CountForKitties` is generic over ``. All of our storage must be generic over `` even if we are not using it directly. Macros use this generic parameter to fill in behind the scene details to make the `StorageValue` work. Think about all the code behind the scenes which actually sticks this storage into a merkle trie in the database of our blockchain. +These properties make hash functions key for ensuring data integrity and uniqueness in blockchain technology. -Visibility of the type is up to you and your needs, but you need to remember that blockchains are public databases. So `pub` in this case is only about Rust, and allowing other modules to access this storage and its APIs directly. +## Hash Fingerprint -You cannot make storage on a blockchain "private", and even if you make this storage without `pub`, there are low level ways to manipulate the storage in the database. +Due to the properties of a Hash, it is often referred to as a fingerprint. + +For context, a 32-byte hash has 2^32 different possible outputs. This nearly as many atoms as there are in the whole universe! + +This uniqueness property helps blockchain nodes come to consensus with one another. + +Rather than needing to compare all the data in their blockchain database with one another, they can simply share the hash of that database, and know in a single small comparison if all data in that database is the same. + +Remember, if there were any small differences between their databases, even just one bit in a multi-terabyte database being different, the resulting hash would dramatically change, and they would know their databases are not the same. + +## Merkle Trie + +A merkle trie is a data structure which is constructed using a hash function. + +Rather than hashing the whole database into a single hash, we create a tree of hashes. + +For example, we take pairs of data, combine them, then hash them to generate a new output. Then we take pairs of hashes, combine them, then hash them to generate another new output. + +We can repeat this process until we are left with a single hash called the "root hash". This process literally creates a tree of hashes. + +Just like before, we can use a single hash to represent the integrity of all data underneath it, but now we can efficiently represent specific pieces of data in the database using the path down the trie to that data. + +It is called a merkle "trie" because the trie data structure is used to reduce the amount of redundant data stored in the tree. + +### Complexity + +The reason we go into this much detail about merkle tries is that they increase the complexity in reading and writing to the blockchain database. + +Whereas reading and writing to a database could be considered `O(1)`, a merklized database has read and write complexity of `O(log N)`, where `N` is the total number of items stored in the database. + +This additional complexity means that designing storage for a blockchain is an extremely important and sensitive operation. + +The primary advantage of using a merkle trie is that proving specific data exists inside the database is much more efficient! Whereas you would normally need to share the whole database to prove that some data exists, with a merklized database, you only need to share `O(log N)` amount of data. + +In this next section, and throughout the tutorial, we will start to explore some of those decisions. diff --git a/steps/10/gitorial_metadata.json b/steps/10/gitorial_metadata.json index 75704d70..d75bd3e0 100644 --- a/steps/10/gitorial_metadata.json +++ b/steps/10/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: learn about storage value" -} + "commitMessage": "section: storage basics" +} \ No newline at end of file diff --git a/steps/10/src/lib.rs b/steps/10/src/lib.rs index ef502702..7b6c6a21 100644 --- a/steps/10/src/lib.rs +++ b/steps/10/src/lib.rs @@ -17,12 +17,6 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; } - /* 🚧 TODO 🚧: - - Create a new `StorageValue` named `CountForKitties`. - - `CountForKitties` should be generic over ``. - - Set `Value` to `u32` to store that type. - */ - #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { diff --git a/steps/11/README.md b/steps/11/README.md index 857d540c..22b856b5 100644 --- a/steps/11/README.md +++ b/steps/11/README.md @@ -1,3 +1,28 @@ -# Solution +# Storage Values -Here you will find the solution for the previous step. +The most basic storage type for a blockchain is a single `StorageValue`. + +A `StorageValue` is used to place a single object into the blockchain storage. + +A single object can be as simple as a single type like a `u32`, or more complex structures, or even vectors. + +What is most important to understand is that a `StorageValue` places a single entry into the merkle trie. So when you read data, you read all of it. When you write data, you write all of it. This is in contrast to a `StorageMap`, which you will learn about next. + +## Construction + +We constructed a simple `StorageValue` for you in the code, but let's break it down: + +```rust +#[pallet::storage] +pub(super) type CountForKitties = StorageValue; +``` + +As you can see, our storage is a type alias for a new instance of `StorageValue`. + +Our storage value has a parameter `Value` where we can define the type we want to place in storage. In this case, it is a simple `u32`. + +You will also notice `CountForKitties` is generic over ``. All of our storage must be generic over `` even if we are not using it directly. Macros use this generic parameter to fill in behind the scene details to make the `StorageValue` work. Think about all the code behind the scenes which actually sticks this storage into a merkle trie in the database of our blockchain. + +Visibility of the type is up to you and your needs, but you need to remember that blockchains are public databases. So `pub` in this case is only about Rust, and allowing other modules to access this storage and its APIs directly. + +You cannot make storage on a blockchain "private", and even if you make this storage without `pub`, there are low level ways to manipulate the storage in the database. diff --git a/steps/11/gitorial_metadata.json b/steps/11/gitorial_metadata.json index 4c0cbc71..75704d70 100644 --- a/steps/11/gitorial_metadata.json +++ b/steps/11/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: learn about storage value" + "commitMessage": "template: learn about storage value" } diff --git a/steps/11/src/lib.rs b/steps/11/src/lib.rs index ebaf109c..ef502702 100644 --- a/steps/11/src/lib.rs +++ b/steps/11/src/lib.rs @@ -17,8 +17,11 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; } - #[pallet::storage] - pub(super) type CountForKitties = StorageValue; + /* 🚧 TODO 🚧: + - Create a new `StorageValue` named `CountForKitties`. + - `CountForKitties` should be generic over ``. + - Set `Value` to `u32` to store that type. + */ #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] diff --git a/steps/12/README.md b/steps/12/README.md index 006a360c..857d540c 100644 --- a/steps/12/README.md +++ b/steps/12/README.md @@ -1,51 +1,3 @@ -# Kitty Counter +# Solution -Let's now learn how to use our new `StorageValue`. - -## Basic APIs - -This tutorial will only go over just the basic APIs needed to build our Pallet. - -Check out the [`StorageValue` documentation](https://docs.rs/frame-support/37.0.0/frame_support/storage/types/struct.StorageValue.html) if you want to see the full APIs. - -### Reading Storage - -To read the current value of a `StorageValue`, you can simply call the `get` API: - -```rust -let maybe_count: Option = CountForKitties::::get(); -``` - -A few things to note here. - -The most obvious one is that `get` returns an `Option`, rather than the type itself. - -In fact, all storage in a blockchain is an `Option`: either there is some data in the database or there isn't. - -In this context, when there is no value in storage for the `CountForKitties`, we probably mean that the `CountForKitties` is zero. - -So we can write the following to handle this ergonomically: - -```rust -let current_count: u32 = CountForKitties::::get().unwrap_or(0); -``` - -Now, whenever `CountForKitties` returns `Some(count)`, we will simply unwrap that count and directly access the `u32`. If it returns `None`, we will simply return `0u32` instead. - -The other thing to note is the generic `` that we need to include. You better get used to this, we will be using `` everywhere! But remember, in our definition of `CountForKitties`, it was a type generic over ``, and thus we need to include `` to access any of the APIs. - -### Writing Storage - -To set the current value of a `StorageValue`, you can simply call the `set` API: - -```rust -CountForKitties::::set(Some(1u32)); -``` - -This storage API cannot fail, so there is no error handling needed. You just set the value directly in storage. Note that `set` will also happily replace any existing value there, so you will need to use other APIs like `exists` or `get` to check if a value is already in storage. - -If you `set` the storage to `None`, it is the same as deleting the storage item. - -## Your Turn - -Now that you know the basics of reading and writing to storage, add the logic needed to increment the `CountForKitties` storage whenever we call `mint`. +Here you will find the solution for the previous step. diff --git a/steps/12/gitorial_metadata.json b/steps/12/gitorial_metadata.json index 4d202543..4c0cbc71 100644 --- a/steps/12/gitorial_metadata.json +++ b/steps/12/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: counter logic" -} \ No newline at end of file + "commitMessage": "solution: learn about storage value" +} diff --git a/steps/12/src/impls.rs b/steps/12/src/impls.rs index b396f986..03abf99e 100644 --- a/steps/12/src/impls.rs +++ b/steps/12/src/impls.rs @@ -3,12 +3,6 @@ use frame::prelude::*; impl Pallet { pub fn mint(owner: T::AccountId) -> DispatchResult { - /* 🚧 TODO 🚧: - - `get` the `current_count` of kitties. - - `unwrap_or` set the count to `0`. - - Create `new_count` by adding one to the `current_count`. - - `set` the `new_count` of kitties. - */ Self::deposit_event(Event::::Created { owner }); Ok(()) } diff --git a/steps/13/README.md b/steps/13/README.md index 857d540c..006a360c 100644 --- a/steps/13/README.md +++ b/steps/13/README.md @@ -1,3 +1,51 @@ -# Solution +# Kitty Counter -Here you will find the solution for the previous step. +Let's now learn how to use our new `StorageValue`. + +## Basic APIs + +This tutorial will only go over just the basic APIs needed to build our Pallet. + +Check out the [`StorageValue` documentation](https://docs.rs/frame-support/37.0.0/frame_support/storage/types/struct.StorageValue.html) if you want to see the full APIs. + +### Reading Storage + +To read the current value of a `StorageValue`, you can simply call the `get` API: + +```rust +let maybe_count: Option = CountForKitties::::get(); +``` + +A few things to note here. + +The most obvious one is that `get` returns an `Option`, rather than the type itself. + +In fact, all storage in a blockchain is an `Option`: either there is some data in the database or there isn't. + +In this context, when there is no value in storage for the `CountForKitties`, we probably mean that the `CountForKitties` is zero. + +So we can write the following to handle this ergonomically: + +```rust +let current_count: u32 = CountForKitties::::get().unwrap_or(0); +``` + +Now, whenever `CountForKitties` returns `Some(count)`, we will simply unwrap that count and directly access the `u32`. If it returns `None`, we will simply return `0u32` instead. + +The other thing to note is the generic `` that we need to include. You better get used to this, we will be using `` everywhere! But remember, in our definition of `CountForKitties`, it was a type generic over ``, and thus we need to include `` to access any of the APIs. + +### Writing Storage + +To set the current value of a `StorageValue`, you can simply call the `set` API: + +```rust +CountForKitties::::set(Some(1u32)); +``` + +This storage API cannot fail, so there is no error handling needed. You just set the value directly in storage. Note that `set` will also happily replace any existing value there, so you will need to use other APIs like `exists` or `get` to check if a value is already in storage. + +If you `set` the storage to `None`, it is the same as deleting the storage item. + +## Your Turn + +Now that you know the basics of reading and writing to storage, add the logic needed to increment the `CountForKitties` storage whenever we call `mint`. diff --git a/steps/13/gitorial_metadata.json b/steps/13/gitorial_metadata.json index 5997151a..4d202543 100644 --- a/steps/13/gitorial_metadata.json +++ b/steps/13/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: counter logic" + "commitMessage": "template: counter logic" } \ No newline at end of file diff --git a/steps/13/src/impls.rs b/steps/13/src/impls.rs index 97393307..b396f986 100644 --- a/steps/13/src/impls.rs +++ b/steps/13/src/impls.rs @@ -3,9 +3,12 @@ use frame::prelude::*; impl Pallet { pub fn mint(owner: T::AccountId) -> DispatchResult { - let current_count: u32 = CountForKitties::::get().unwrap_or(0); - let new_count = current_count + 1; - CountForKitties::::set(Some(new_count)); + /* 🚧 TODO 🚧: + - `get` the `current_count` of kitties. + - `unwrap_or` set the count to `0`. + - Create `new_count` by adding one to the `current_count`. + - `set` the `new_count` of kitties. + */ Self::deposit_event(Event::::Created { owner }); Ok(()) } diff --git a/steps/14/README.md b/steps/14/README.md index 1f5ef74a..857d540c 100644 --- a/steps/14/README.md +++ b/steps/14/README.md @@ -1,141 +1,3 @@ -# Safety First +# Solution -If you look into the history of "hacks" and "bugs" that happen in the blockchain world, a lot of it is associated with some kind of "unsafe" code. - -Keeping our blockchain logic safe, and Rust is designed to handle it well. - -## Errors - -When talking about handling safe math, we will start to introduce and use errors. - -### Do Not Panic! - -If there is only one thing you remember after this whole tutorial, it should be this fact: - -**You cannot panic inside the runtime.** - -As a runtime developer, you are building logic in the low level parts of your blockchain. - -A smart contract system must be able to handle malicious developers, but this comes at a performance cost. - -When you program directly in the runtime, you get the highest performance possible, but you are also expected to be a competent developer and a good actor. - -In short, if you introduce a panic in your code, you make your blockchain vulnerable to DDoS attacks. - -But there is no reason you would ever need to panic because Rust has a great error handling system that we take advantage of in FRAME. - -### Pallet Errors - -All of our callable functions use the `DispatchResult` type. This means that we can always propagate up any errors that our Pallet runs into, and handle them properly, versus needing to panic. - -The [`DispatchResult`](https://docs.rs/frame-support/37.0.0/frame_support/dispatch/type.DispatchResult.html) type expects either `Ok(())` or `Err(DispatchError)`. - -The [`DispatchError`](https://docs.rs/frame-support/37.0.0/frame_support/pallet_prelude/enum.DispatchError.html) type has a few variants that you can easily construct / use. - -For example, if you want to be a little lazy, you can simply return a `&'static str`: - -```rust -fn always_error() -> DispatchResult { - return Err("this function always errors".into()) -} -``` - -But the better option is to return a custom Pallet Error: - -```rust -fn custom_error() -> DispatchResult { - return Err(Error::::CustomPalletError.into()) -} -``` - -Notice in both of these cases we had to call `into()` to convert our input type into the `DispatchError` type. - -To create `CustomPalletError` or whatever error you want, you simply add a new variants to the `enum Error` type. - -```rust -#[pallet::error] -pub enum Error { - /// This is a description for the error. - /// - /// This description can be shown to the user in UIs, so make it descriptive. - CustomPalletError, -} -``` - -We will show you the common ergonomic ways to use Pallet Errors going forward. - -## Math - -### Unsafe Math - -The basic math operators in Rust are **unsafe**. - -Imagine our `CountForKitties` was already at the limit of `u32::MAX`. What would happen if we tried to call `mint` one more time? - -We would get an overflow! - -In tests `u32::MAX + 1` will actually trigger a panic, but in a `release` build, this overflow will happen silently... - -And this would be really bad. Now our count would be back to 0, and if we had any logic which depended on this count being accurate, that logic would be broken. - -In blockchain systems, these can literally be billion dollar bugs, so let's look at how we can do math safely. - -### Checked Math - -The first choice for doing safe math is to use `checked_*` APIs, for example [`checked_add`](https://docs.rs/num/latest/num/trait.CheckedAdd.html). - -The checked math APIs will check if there are any underflows or overflows, and return `None` in those cases. Otherwise, if the math operation is calculated without error, it returns `Some(result)`. - -Here is a verbose way you could handle checked math in a Pallet: - -```rust -let final_result: u32 = match value_a.checked_add(value_b) { - Some(result) => result, - None => return Err(Error::::CustomPalletError.into()), -}; -``` - -You can see how we can directly assign the `u32` value to `final_result`, otherwise it will return an error. - -We can also do this as a one-liner, which is more ergonomic and preferred: - -```rust -let final_result: u32 = value_a.checked_add(value_b).ok_or(Error::::CustomPalletError)?; -``` - -This is exactly how you should be writing all the safe math inside your Pallet. - -Note that we didn't need to call `.into()` in this case, because `?` already does this! - -### Saturating Math - -The other option for safe math is to use `saturating_*` APIs, for example [`saturating_add`](https://docs.rs/num/latest/num/traits/trait.SaturatingAdd.html). - -This option is useful because it is safe and does NOT return an `Option`. - -Instead, it performs the math operations and keeps the value at the numerical limits, rather than overflowing. For example: - -```rust -let value_a: u32 = 1; -let value_b: u32 = u32::MAX; -let result: u32 = value_a.saturating_add(value_b); -assert!(result == u32::MAX); -``` - -This generally is NOT the preferred API to use because usually you want to handle situations where an overflow would occur. Overflows and underflows usually indicate something "bad" is happening. - -However, there are times where you need to do math inside of functions where you cannot return a Result, and for that, saturating math might make sense. - -There are also times where you might want to perform the operation no matter that an underflow / overflow would occur. For example, imagine you made a function `slash` which slashes the balance of a malicious user. Your slash function may have some input parameter `amount` which says how much we should slash from the user. - -In a situation like this, it would make sense to use `saturating_sub` because we definitely want to slash as much as we can, even if we intended to slash more. The alternative would be returning an error, and not slashing anything! - -Anyway, every bone in your body should generally prefer to use the `checked_*` APIs, and handle all errors explicitly, but this is yet another tool in your pocket when it makes sense to use it. - -## Your Turn - -We covered a lot in this section, but the concepts here are super important. - -Feel fre to reach this section again right now, and again at the end of the tutorial. - -Now that you know how to ergonomically do safe math, update your Pallet to handle the `mint` logic safely and return a custom Pallet Error if an overflow would occur. +Here you will find the solution for the previous step. diff --git a/steps/14/gitorial_metadata.json b/steps/14/gitorial_metadata.json index 81184b9b..5997151a 100644 --- a/steps/14/gitorial_metadata.json +++ b/steps/14/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: safe math and errors" + "commitMessage": "solution: counter logic" } \ No newline at end of file diff --git a/steps/14/src/impls.rs b/steps/14/src/impls.rs index c550bc8d..97393307 100644 --- a/steps/14/src/impls.rs +++ b/steps/14/src/impls.rs @@ -4,7 +4,6 @@ use frame::prelude::*; impl Pallet { pub fn mint(owner: T::AccountId) -> DispatchResult { let current_count: u32 = CountForKitties::::get().unwrap_or(0); - /* 🚧 TODO 🚧: Update this logic to use safe math. */ let new_count = current_count + 1; CountForKitties::::set(Some(new_count)); Self::deposit_event(Event::::Created { owner }); diff --git a/steps/14/src/lib.rs b/steps/14/src/lib.rs index e68500da..ebaf109c 100644 --- a/steps/14/src/lib.rs +++ b/steps/14/src/lib.rs @@ -27,11 +27,7 @@ pub mod pallet { } #[pallet::error] - pub enum Error { - /* 🚧 TODO 🚧: - - Introduce a new error `TooManyKitties`. - */ - } + pub enum Error {} #[pallet::call] impl Pallet { diff --git a/steps/15/README.md b/steps/15/README.md index 857d540c..1f5ef74a 100644 --- a/steps/15/README.md +++ b/steps/15/README.md @@ -1,3 +1,141 @@ -# Solution +# Safety First -Here you will find the solution for the previous step. +If you look into the history of "hacks" and "bugs" that happen in the blockchain world, a lot of it is associated with some kind of "unsafe" code. + +Keeping our blockchain logic safe, and Rust is designed to handle it well. + +## Errors + +When talking about handling safe math, we will start to introduce and use errors. + +### Do Not Panic! + +If there is only one thing you remember after this whole tutorial, it should be this fact: + +**You cannot panic inside the runtime.** + +As a runtime developer, you are building logic in the low level parts of your blockchain. + +A smart contract system must be able to handle malicious developers, but this comes at a performance cost. + +When you program directly in the runtime, you get the highest performance possible, but you are also expected to be a competent developer and a good actor. + +In short, if you introduce a panic in your code, you make your blockchain vulnerable to DDoS attacks. + +But there is no reason you would ever need to panic because Rust has a great error handling system that we take advantage of in FRAME. + +### Pallet Errors + +All of our callable functions use the `DispatchResult` type. This means that we can always propagate up any errors that our Pallet runs into, and handle them properly, versus needing to panic. + +The [`DispatchResult`](https://docs.rs/frame-support/37.0.0/frame_support/dispatch/type.DispatchResult.html) type expects either `Ok(())` or `Err(DispatchError)`. + +The [`DispatchError`](https://docs.rs/frame-support/37.0.0/frame_support/pallet_prelude/enum.DispatchError.html) type has a few variants that you can easily construct / use. + +For example, if you want to be a little lazy, you can simply return a `&'static str`: + +```rust +fn always_error() -> DispatchResult { + return Err("this function always errors".into()) +} +``` + +But the better option is to return a custom Pallet Error: + +```rust +fn custom_error() -> DispatchResult { + return Err(Error::::CustomPalletError.into()) +} +``` + +Notice in both of these cases we had to call `into()` to convert our input type into the `DispatchError` type. + +To create `CustomPalletError` or whatever error you want, you simply add a new variants to the `enum Error` type. + +```rust +#[pallet::error] +pub enum Error { + /// This is a description for the error. + /// + /// This description can be shown to the user in UIs, so make it descriptive. + CustomPalletError, +} +``` + +We will show you the common ergonomic ways to use Pallet Errors going forward. + +## Math + +### Unsafe Math + +The basic math operators in Rust are **unsafe**. + +Imagine our `CountForKitties` was already at the limit of `u32::MAX`. What would happen if we tried to call `mint` one more time? + +We would get an overflow! + +In tests `u32::MAX + 1` will actually trigger a panic, but in a `release` build, this overflow will happen silently... + +And this would be really bad. Now our count would be back to 0, and if we had any logic which depended on this count being accurate, that logic would be broken. + +In blockchain systems, these can literally be billion dollar bugs, so let's look at how we can do math safely. + +### Checked Math + +The first choice for doing safe math is to use `checked_*` APIs, for example [`checked_add`](https://docs.rs/num/latest/num/trait.CheckedAdd.html). + +The checked math APIs will check if there are any underflows or overflows, and return `None` in those cases. Otherwise, if the math operation is calculated without error, it returns `Some(result)`. + +Here is a verbose way you could handle checked math in a Pallet: + +```rust +let final_result: u32 = match value_a.checked_add(value_b) { + Some(result) => result, + None => return Err(Error::::CustomPalletError.into()), +}; +``` + +You can see how we can directly assign the `u32` value to `final_result`, otherwise it will return an error. + +We can also do this as a one-liner, which is more ergonomic and preferred: + +```rust +let final_result: u32 = value_a.checked_add(value_b).ok_or(Error::::CustomPalletError)?; +``` + +This is exactly how you should be writing all the safe math inside your Pallet. + +Note that we didn't need to call `.into()` in this case, because `?` already does this! + +### Saturating Math + +The other option for safe math is to use `saturating_*` APIs, for example [`saturating_add`](https://docs.rs/num/latest/num/traits/trait.SaturatingAdd.html). + +This option is useful because it is safe and does NOT return an `Option`. + +Instead, it performs the math operations and keeps the value at the numerical limits, rather than overflowing. For example: + +```rust +let value_a: u32 = 1; +let value_b: u32 = u32::MAX; +let result: u32 = value_a.saturating_add(value_b); +assert!(result == u32::MAX); +``` + +This generally is NOT the preferred API to use because usually you want to handle situations where an overflow would occur. Overflows and underflows usually indicate something "bad" is happening. + +However, there are times where you need to do math inside of functions where you cannot return a Result, and for that, saturating math might make sense. + +There are also times where you might want to perform the operation no matter that an underflow / overflow would occur. For example, imagine you made a function `slash` which slashes the balance of a malicious user. Your slash function may have some input parameter `amount` which says how much we should slash from the user. + +In a situation like this, it would make sense to use `saturating_sub` because we definitely want to slash as much as we can, even if we intended to slash more. The alternative would be returning an error, and not slashing anything! + +Anyway, every bone in your body should generally prefer to use the `checked_*` APIs, and handle all errors explicitly, but this is yet another tool in your pocket when it makes sense to use it. + +## Your Turn + +We covered a lot in this section, but the concepts here are super important. + +Feel fre to reach this section again right now, and again at the end of the tutorial. + +Now that you know how to ergonomically do safe math, update your Pallet to handle the `mint` logic safely and return a custom Pallet Error if an overflow would occur. diff --git a/steps/15/gitorial_metadata.json b/steps/15/gitorial_metadata.json index 59611028..81184b9b 100644 --- a/steps/15/gitorial_metadata.json +++ b/steps/15/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: safe math and errors" + "commitMessage": "template: safe math and errors" } \ No newline at end of file diff --git a/steps/15/src/impls.rs b/steps/15/src/impls.rs index 7277e367..c550bc8d 100644 --- a/steps/15/src/impls.rs +++ b/steps/15/src/impls.rs @@ -4,7 +4,8 @@ use frame::prelude::*; impl Pallet { pub fn mint(owner: T::AccountId) -> DispatchResult { let current_count: u32 = CountForKitties::::get().unwrap_or(0); - let new_count = current_count.checked_add(1).ok_or(Error::::TooManyKitties)?; + /* 🚧 TODO 🚧: Update this logic to use safe math. */ + let new_count = current_count + 1; CountForKitties::::set(Some(new_count)); Self::deposit_event(Event::::Created { owner }); Ok(()) diff --git a/steps/15/src/lib.rs b/steps/15/src/lib.rs index a9139976..e68500da 100644 --- a/steps/15/src/lib.rs +++ b/steps/15/src/lib.rs @@ -28,7 +28,9 @@ pub mod pallet { #[pallet::error] pub enum Error { - TooManyKitties, + /* 🚧 TODO 🚧: + - Introduce a new error `TooManyKitties`. + */ } #[pallet::call] diff --git a/steps/16/README.md b/steps/16/README.md index 57769467..857d540c 100644 --- a/steps/16/README.md +++ b/steps/16/README.md @@ -1,81 +1,3 @@ -# Value Query +# Solution -When we originally introduced the `StorageValue`, we only exposed to you one field which you could manipulate, which is the `Value` type, which defines the type that will be stored. - -But there are actually more ways you can configure the `StorageValue` to increase developer ergonomics. - -## Storage Value Definition - -Let's look at the definition of a [`StorageValue`](https://docs.rs/frame-support/37.0.0/frame_support/storage/types/struct.StorageValue.html): - -```rust -pub struct StorageValue< - Prefix, - Value, - QueryKind = OptionQuery, - OnEmpty = GetDefault ->(_); -``` - -You can see the `StorageValue` expects 4 different generic parameters, two of which have default implementations, which means you don't need to define them unless you want to change the configuration. - -### Prefix - -We have been able to hide the `Prefix` type from you so far because the `#[pallet::storage]` macro implements this for us auto-magically. - -We won't go into detail about what exactly `Prefix` does, but the high level idea is that it contains metadata needed to be able to correctly, uniquely, and consistently read and write data into the merkle trie. - -Those details are pretty low level, and something we can automatically implement for you with the macros. You should never need to do anything with `Prefix`, else you are probably doing something wrong. - -### Value - -You already know how to use and implement `Value` for `StorageValue`, so we won't go into too much detail here. - -I will note that not literally every object can be placed in storage. It must satisfy some traits, which we will learn later in the tutorial. - -### Query Kind - -You can see the `QueryKind` parameter defaults to `OptionQuery`. - -This is why when we query storage, we get an `Option` returned to us. - -Now as we stated before, Runtime storage is ALWAYS an `Option`. It is always possible that some storage does not exist / is not set when we first try to query it. But as we showed in our Pallet so far, there is logic we can write to "hide" that fact from the user, like `unwrap_or(0)`. - -We can do this even more ergonomically by changing the `QueryKind` to `ValueQuery`. - -```rust -#[pallet::storage] -pub(super) type CountForKitties = StorageValue; -``` - -In this case, all of our APIs change. - -Now when you call `get`, you will directly return a value, and when you call `set`, you just need to pass the value, not an option. - -Now you might ask: "What value do you get when you call `get` and there is no value stored?". - -That is controlled by the `OnEmpty` type. - -### On Empty - -As we noted above, the `OnEmpty` type defines the behavior of the `QueryKind` type. - -When you call `get`, and the storage is empty, the `OnEmpty` configuration kicks in. - -The default configuration for `OnEmpty` is `GetDefault`. This of course requires that the `Value` type must implement `Default`. But if it does, then you will get the following behavior: - -```rust -assert!(CountForKitties::::get() == u32::default()); -``` - -For numbers, this value is normally zero, so simply setting `QueryKind = ValueQuery` gives you exactly the same behavior as what we programmed in our Pallet so far. - -If your type does not implement `Default`, you can't use `ValueQuery`. A common example of this is the `T::AccountId` type, which purposefully has no default value, and thus is not compatible out of the box with `ValueQuery`. - -You CAN modify `OnEmpty` to return a custom value, rather than `Default`, but we won't cover that here. Feel free to explore this idea on your own. - -## Your Turn - -Update your `CountForKitties` to use `QueryKind = ValueQuery`. - -This will affect the APIs for `get` and `set`, so also update your code to reflect those changes. +Here you will find the solution for the previous step. diff --git a/steps/16/gitorial_metadata.json b/steps/16/gitorial_metadata.json index cc4bdf21..59611028 100644 --- a/steps/16/gitorial_metadata.json +++ b/steps/16/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: learn about value query" + "commitMessage": "solution: safe math and errors" } \ No newline at end of file diff --git a/steps/16/src/impls.rs b/steps/16/src/impls.rs index b9b5548a..7277e367 100644 --- a/steps/16/src/impls.rs +++ b/steps/16/src/impls.rs @@ -3,10 +3,8 @@ use frame::prelude::*; impl Pallet { pub fn mint(owner: T::AccountId) -> DispatchResult { - /* 🚧 TODO 🚧: Remove the `unwrap_or` which is not needed when using `ValueQuery`. */ let current_count: u32 = CountForKitties::::get().unwrap_or(0); let new_count = current_count.checked_add(1).ok_or(Error::::TooManyKitties)?; - /* 🚧 TODO 🚧: Remove the `Option` wrapper when setting the `new_count`. */ CountForKitties::::set(Some(new_count)); Self::deposit_event(Event::::Created { owner }); Ok(()) diff --git a/steps/16/src/lib.rs b/steps/16/src/lib.rs index 322eeeef..a9139976 100644 --- a/steps/16/src/lib.rs +++ b/steps/16/src/lib.rs @@ -18,7 +18,6 @@ pub mod pallet { } #[pallet::storage] - /* 🚧 TODO 🚧: Update this storage to use a `QueryKind` of `ValueQuery`. */ pub(super) type CountForKitties = StorageValue; #[pallet::event] diff --git a/steps/17/README.md b/steps/17/README.md index 857d540c..57769467 100644 --- a/steps/17/README.md +++ b/steps/17/README.md @@ -1,3 +1,81 @@ -# Solution +# Value Query -Here you will find the solution for the previous step. +When we originally introduced the `StorageValue`, we only exposed to you one field which you could manipulate, which is the `Value` type, which defines the type that will be stored. + +But there are actually more ways you can configure the `StorageValue` to increase developer ergonomics. + +## Storage Value Definition + +Let's look at the definition of a [`StorageValue`](https://docs.rs/frame-support/37.0.0/frame_support/storage/types/struct.StorageValue.html): + +```rust +pub struct StorageValue< + Prefix, + Value, + QueryKind = OptionQuery, + OnEmpty = GetDefault +>(_); +``` + +You can see the `StorageValue` expects 4 different generic parameters, two of which have default implementations, which means you don't need to define them unless you want to change the configuration. + +### Prefix + +We have been able to hide the `Prefix` type from you so far because the `#[pallet::storage]` macro implements this for us auto-magically. + +We won't go into detail about what exactly `Prefix` does, but the high level idea is that it contains metadata needed to be able to correctly, uniquely, and consistently read and write data into the merkle trie. + +Those details are pretty low level, and something we can automatically implement for you with the macros. You should never need to do anything with `Prefix`, else you are probably doing something wrong. + +### Value + +You already know how to use and implement `Value` for `StorageValue`, so we won't go into too much detail here. + +I will note that not literally every object can be placed in storage. It must satisfy some traits, which we will learn later in the tutorial. + +### Query Kind + +You can see the `QueryKind` parameter defaults to `OptionQuery`. + +This is why when we query storage, we get an `Option` returned to us. + +Now as we stated before, Runtime storage is ALWAYS an `Option`. It is always possible that some storage does not exist / is not set when we first try to query it. But as we showed in our Pallet so far, there is logic we can write to "hide" that fact from the user, like `unwrap_or(0)`. + +We can do this even more ergonomically by changing the `QueryKind` to `ValueQuery`. + +```rust +#[pallet::storage] +pub(super) type CountForKitties = StorageValue; +``` + +In this case, all of our APIs change. + +Now when you call `get`, you will directly return a value, and when you call `set`, you just need to pass the value, not an option. + +Now you might ask: "What value do you get when you call `get` and there is no value stored?". + +That is controlled by the `OnEmpty` type. + +### On Empty + +As we noted above, the `OnEmpty` type defines the behavior of the `QueryKind` type. + +When you call `get`, and the storage is empty, the `OnEmpty` configuration kicks in. + +The default configuration for `OnEmpty` is `GetDefault`. This of course requires that the `Value` type must implement `Default`. But if it does, then you will get the following behavior: + +```rust +assert!(CountForKitties::::get() == u32::default()); +``` + +For numbers, this value is normally zero, so simply setting `QueryKind = ValueQuery` gives you exactly the same behavior as what we programmed in our Pallet so far. + +If your type does not implement `Default`, you can't use `ValueQuery`. A common example of this is the `T::AccountId` type, which purposefully has no default value, and thus is not compatible out of the box with `ValueQuery`. + +You CAN modify `OnEmpty` to return a custom value, rather than `Default`, but we won't cover that here. Feel free to explore this idea on your own. + +## Your Turn + +Update your `CountForKitties` to use `QueryKind = ValueQuery`. + +This will affect the APIs for `get` and `set`, so also update your code to reflect those changes. diff --git a/steps/17/gitorial_metadata.json b/steps/17/gitorial_metadata.json index 99ab37a0..cc4bdf21 100644 --- a/steps/17/gitorial_metadata.json +++ b/steps/17/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: learn about value query" + "commitMessage": "template: learn about value query" } \ No newline at end of file diff --git a/steps/17/src/impls.rs b/steps/17/src/impls.rs index d283fd6b..b9b5548a 100644 --- a/steps/17/src/impls.rs +++ b/steps/17/src/impls.rs @@ -3,9 +3,11 @@ use frame::prelude::*; impl Pallet { pub fn mint(owner: T::AccountId) -> DispatchResult { - let current_count: u32 = CountForKitties::::get(); + /* 🚧 TODO 🚧: Remove the `unwrap_or` which is not needed when using `ValueQuery`. */ + let current_count: u32 = CountForKitties::::get().unwrap_or(0); let new_count = current_count.checked_add(1).ok_or(Error::::TooManyKitties)?; - CountForKitties::::set(new_count); + /* 🚧 TODO 🚧: Remove the `Option` wrapper when setting the `new_count`. */ + CountForKitties::::set(Some(new_count)); Self::deposit_event(Event::::Created { owner }); Ok(()) } diff --git a/steps/17/src/lib.rs b/steps/17/src/lib.rs index 52b2dba9..322eeeef 100644 --- a/steps/17/src/lib.rs +++ b/steps/17/src/lib.rs @@ -18,7 +18,8 @@ pub mod pallet { } #[pallet::storage] - pub(super) type CountForKitties = StorageValue; + /* 🚧 TODO 🚧: Update this storage to use a `QueryKind` of `ValueQuery`. */ + pub(super) type CountForKitties = StorageValue; #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] diff --git a/steps/18/README.md b/steps/18/README.md index 532e7dfe..857d540c 100644 --- a/steps/18/README.md +++ b/steps/18/README.md @@ -1,76 +1,3 @@ -# Storage Maps +# Solution -Now that you have learned everything you need to know about `StorageValue`s, it is time to move on to `StorageMap`s. - -`StorageMap`s are key / value storage items designed for Pallet development. - -## Syntax - -Declaring a new [`StorageMap`](https://docs.rs/frame-support/37.0.0/frame_support/storage/types/struct.StorageMap.html) is very similar to a `StorageValue`: - -```rust -#[pallet::storage] -pub(super) type Kitties = StorageMap; -``` - -Nearly everything is the same, except you need to define a `Key` and `Value`. - -Each `Key` can store a separate `Value`, which makes maps super useful. - -In this case `[u8; 32]` represents some unique identifier for each Kitty we will store, and `()` is simply a placeholder type for now. - -## Conceptual - -The key difference between a `StorageValue` and a `StorageMap` is: - -- A `StorageValue` stores a single value into a single key in the Merkle Trie. -- A `StorageMap` stores multiple values under different storage keys, all into different places in the Merkle Trie. - -Let's clarify further. - -Rust has a type `BTreeMap`, which is also a key/value map. - -So what would be the difference between: - -```rust -#[pallet::storage] -pub(super) type MyValueMap = StorageValue>; -``` - -and - -```rust -#[pallet::storage] -pub(super) type MyMap = StorageMap; -``` - -They both can store the same data, but the `StorageValue` puts all of the data into a single object and stores that all into a single key in the Merkle Trie. - -This means if we want to read just a single key / value pair, we must read ALL data in the whole map, and parse out just the single value we want. - -In a `StorageMap`, each value is stored in its own spot in the Merkle Trie, so you are able to read just one key / value on its own. This can be way more efficient for reading just a single item. - -However, trying to read multiple items from a `StorageMap` is extremely expensive. - -So there is no perfect kind of storage, just tradeoffs. - -## Use Cases - -`StorageMap`s are really great when we need to store some unique information about a bunch of different things. - -The most common example would be trying to store the token balance of all users in your blockchain. In this case, each user has their own `T::AccountId`, and that maps to some balance amount. - -In our pallet, we use the `StorageMap` to store unique information about each `Kitty` in our pallet. - -These use cases make sense because all the logic in our pallet typically touches only one key at a time. - -- when you mint a kitty, we create one key / value. -- when you transfer a kitty, we mutate one key / value. -- when you put your kitty for sale, you mutate one key / value. -- etc... - -And with the `StorageMap`, we can store a nearly infinite number of different kitties, or at least as many as there are unique keys. - -## Your Turn - -Add the `Kitties` storage map to your project as shown in the template. +Here you will find the solution for the previous step. diff --git a/steps/18/gitorial_metadata.json b/steps/18/gitorial_metadata.json index 16097026..99ab37a0 100644 --- a/steps/18/gitorial_metadata.json +++ b/steps/18/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: learn about storage maps" -} + "commitMessage": "solution: learn about value query" +} \ No newline at end of file diff --git a/steps/18/src/lib.rs b/steps/18/src/lib.rs index be05ddb9..52b2dba9 100644 --- a/steps/18/src/lib.rs +++ b/steps/18/src/lib.rs @@ -20,13 +20,6 @@ pub mod pallet { #[pallet::storage] pub(super) type CountForKitties = StorageValue; - /* 🚧 TODO 🚧: - - Create a new `StorageMap` named `Kitties`. - - `Kitties` should be generic over ``. - - Set `Key` to `[u8; 32]` to use the kitty id as the key. - - Set `Value` to `()` as a placeholder for now. - */ - #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { diff --git a/steps/19/README.md b/steps/19/README.md index 857d540c..532e7dfe 100644 --- a/steps/19/README.md +++ b/steps/19/README.md @@ -1,3 +1,76 @@ -# Solution +# Storage Maps -Here you will find the solution for the previous step. +Now that you have learned everything you need to know about `StorageValue`s, it is time to move on to `StorageMap`s. + +`StorageMap`s are key / value storage items designed for Pallet development. + +## Syntax + +Declaring a new [`StorageMap`](https://docs.rs/frame-support/37.0.0/frame_support/storage/types/struct.StorageMap.html) is very similar to a `StorageValue`: + +```rust +#[pallet::storage] +pub(super) type Kitties = StorageMap; +``` + +Nearly everything is the same, except you need to define a `Key` and `Value`. + +Each `Key` can store a separate `Value`, which makes maps super useful. + +In this case `[u8; 32]` represents some unique identifier for each Kitty we will store, and `()` is simply a placeholder type for now. + +## Conceptual + +The key difference between a `StorageValue` and a `StorageMap` is: + +- A `StorageValue` stores a single value into a single key in the Merkle Trie. +- A `StorageMap` stores multiple values under different storage keys, all into different places in the Merkle Trie. + +Let's clarify further. + +Rust has a type `BTreeMap`, which is also a key/value map. + +So what would be the difference between: + +```rust +#[pallet::storage] +pub(super) type MyValueMap = StorageValue>; +``` + +and + +```rust +#[pallet::storage] +pub(super) type MyMap = StorageMap; +``` + +They both can store the same data, but the `StorageValue` puts all of the data into a single object and stores that all into a single key in the Merkle Trie. + +This means if we want to read just a single key / value pair, we must read ALL data in the whole map, and parse out just the single value we want. + +In a `StorageMap`, each value is stored in its own spot in the Merkle Trie, so you are able to read just one key / value on its own. This can be way more efficient for reading just a single item. + +However, trying to read multiple items from a `StorageMap` is extremely expensive. + +So there is no perfect kind of storage, just tradeoffs. + +## Use Cases + +`StorageMap`s are really great when we need to store some unique information about a bunch of different things. + +The most common example would be trying to store the token balance of all users in your blockchain. In this case, each user has their own `T::AccountId`, and that maps to some balance amount. + +In our pallet, we use the `StorageMap` to store unique information about each `Kitty` in our pallet. + +These use cases make sense because all the logic in our pallet typically touches only one key at a time. + +- when you mint a kitty, we create one key / value. +- when you transfer a kitty, we mutate one key / value. +- when you put your kitty for sale, you mutate one key / value. +- etc... + +And with the `StorageMap`, we can store a nearly infinite number of different kitties, or at least as many as there are unique keys. + +## Your Turn + +Add the `Kitties` storage map to your project as shown in the template. diff --git a/steps/19/gitorial_metadata.json b/steps/19/gitorial_metadata.json index f09bddca..16097026 100644 --- a/steps/19/gitorial_metadata.json +++ b/steps/19/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: learn about storage maps" + "commitMessage": "template: learn about storage maps" } diff --git a/steps/19/src/lib.rs b/steps/19/src/lib.rs index d4e9d017..be05ddb9 100644 --- a/steps/19/src/lib.rs +++ b/steps/19/src/lib.rs @@ -20,8 +20,12 @@ pub mod pallet { #[pallet::storage] pub(super) type CountForKitties = StorageValue; - #[pallet::storage] - pub(super) type Kitties = StorageMap; + /* 🚧 TODO 🚧: + - Create a new `StorageMap` named `Kitties`. + - `Kitties` should be generic over ``. + - Set `Key` to `[u8; 32]` to use the kitty id as the key. + - Set `Value` to `()` as a placeholder for now. + */ #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] diff --git a/steps/2/README.md b/steps/2/README.md index f7625391..5ee371e9 100644 --- a/steps/2/README.md +++ b/steps/2/README.md @@ -1,69 +1,113 @@ -# Substrate Collectables Workshop: Starting Template +# Polkadot-SDK -This is the starting template for: https://github.com/shawntabrizi/substrate-collectables-workshop +Our starting template for this tutorial uses the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk). -## Setup +This is the same technology stack used to build and power the [Polkadot Network](https://polkadot.network/). -Follow [these installation instructions](https://docs.substrate.io/install/) to set up your development environment to work with the `polkadot-sdk`. +To better understand what you will be doing in this tutorial, we need to start with a high level overview of blockchains. -### test +## Blockchain -To check that your code compiles successfully at each step, you can run: +Blockchains are the foundation of building Web3 technologies. -```bash -cargo test -``` +Web3 is a promise toward a world with less trust, and more truth. -You should run this now to make sure this starting template is compiling successfully for you. +Through blockchain technology, we are able to develop and deploy software that are decentralized, open, permissionless, censorship resistant, and independently verifiable. -At the beginning and end of every step, you should be able to run `cargo test` without warning or errors. If you have either, you should learn from them and fix them! +The main purpose of a blockchain node is to come to consensus with other nodes on the decentralized network. -### rustfmt +
-To keep your code clean and easy to read, we use a tool called [`rustfmt`](https://github.com/rust-lang/rustfmt). To access all the latest features of `rustfmt` we specifically use the `nightly` toolchain. +Deep Dive -To install `rustfmt` for `nightly`: +If you want to learn more about blockchains, check out the following video from the Polkadot Blockchain Academy: -```bash -rustup component add rustfmt --toolchain nightly -``` + -To configure the behavior of `rustfmt`, we have included a `rustfmt.toml` file. +
-Try running: +## Runtime -```bash -cargo +nightly fmt -``` +At the heart of a blockchain is a [state transition function](https://en.wikipedia.org/wiki/Finite-state_machine) (STF). -You shouldn't see any changes this time around, but as you write more code, you will be able to see `cargo +nightly fmt` make everything look pretty, consistent, and easy to read. +This is the logic of the blockchain, and defines all the ways a blockchain is allowed to manipulate the blockchain state. -> We recommend you run `cargo +nightly fmt` after every step! +In the `polkadot-sdk` we refer to this logic as the blockchain's runtime. -### clippy +All nodes on a blockchain network have and use the same runtime, allowing them to come to consensus about changes to a blockchain. -[Clippy](https://github.com/rust-lang/rust-clippy) is a collection of lints to catch common mistakes and improve your Rust code. We also use the `nightly` toolchain here to gain access to the latest features. +
-To install `clippy` for `nightly`: +Deep Dive -```bash -rustup component add clippy -``` +To learn more about the runtime, and its role inside of the `polkadot-sdk`, check out this video from the Polkadot Blockchain Academy: -Try running: + -```bash -cargo +nightly clippy -``` +
-Again, you shouldn't see any errors here, but as you write code for this tutorial, `clippy` can be used to help improve the quality of your code. +## FRAME -## Cheat Sheet +The `polkadot-sdk` provides a developer framework called FRAME. -You should run these 3 commands at the end of every step without any errors or warnings. +FRAME is an opinionated framework on how one should quickly and easily build and maintain a blockchain's runtime. -```bash -cargo +nightly fmt -cargo +nightly clippy -cargo test -``` +> NOTE: It is important to clarify that FRAME is not the only way you can develop a runtime for the `polkadot-sdk`, but it is the one that the Polkadot Network uses and is most supported by the ecosystem. + +You can see in our project, nearly all of our dependencies come from a single crate named [`frame`](https://docs.rs/polkadot-sdk-frame/0.6.0/polkadot_sdk_frame/index.html). + +This crate is really just a convenience wrapper around other smaller crates, all exposed through [`frame::deps`](https://docs.rs/polkadot-sdk-frame/0.6.0/polkadot_sdk_frame/deps/index.html). + +For our tutorial, most of the types and traits we need access to are automatically brought into scope through [`frame::prelude::*`](https://docs.rs/polkadot-sdk-frame/0.6.0/polkadot_sdk_frame/prelude/index.html), however once in a while, we will need to import something more specific from [`frame::primitives`](https://docs.rs/polkadot-sdk-frame/0.6.0/polkadot_sdk_frame/primitives/index.html) or [`frame::traits`](https://docs.rs/polkadot-sdk-frame/0.6.0/polkadot_sdk_frame/traits/index.html). + +### Pallets + +FRAME's key decision is to break apart the blockchain runtime into separate logical pieces that can choose to interact with one another. + +These logical pieces are called Pallets. + +TODO: Add images. + +You can think of different Pallets as different applications or functions that your blockchain exposes. + +You can also think of Pallets very similar to traditional blockchain smart contracts, however Pallets are more powerful and execute much faster than smart contracts. + +
+ +Deep Dive + +To learn more about FRAME and Pallets, check out this video from the Polkadot Blockchain Academy: + + + +
+ +## NFTs + +Non-Fungible Tokens (NFTs) are a type of token which can be created and traded on a blockchain. + +As their name indicated, each NFT is totally unique, and therefore non-fungible with one another. + +NFTs can be used for many things, for example: + +- Representing real world assets + - Ownership Rights + - Access Rights +- Digital assets + - Music + - Images + - Skins + - Characters +- and much more... + +## Starting Template + +The template for this project is a minimal starting point for developing a custom Pallet. + +In this tutorial, we will create a Pallet which allows us to create and manage a collection of NFTs. + +Our NFTs will represent kitties, which will be a digital pet that can be created, traded, and more. + +This Pallet could then be included into a `polkadot-sdk` project and used to launch a Web3 application on the Polkadot Network. + +TODO: need to create and link to a tutorial creating and launching a runtime with omninode. diff --git a/steps/2/gitorial_metadata.json b/steps/2/gitorial_metadata.json index 14c2c7bc..9440095b 100644 --- a/steps/2/gitorial_metadata.json +++ b/steps/2/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "starting-template" + "commitMessage": "action: learn about the polkadot sdk" } \ No newline at end of file diff --git a/steps/20/README.md b/steps/20/README.md index 15924acf..857d540c 100644 --- a/steps/20/README.md +++ b/steps/20/README.md @@ -1,47 +1,3 @@ -# Kitties Map +# Solution -Now let's learn to interact with our `Kitties` storage map, and update the map when we `mint` new kitties. - -## Basic APIs - -This tutorial will only go over just the basic APIs needed to build our Pallet. - -Check out the [`StorageMap` documentation](https://docs.rs/frame-support/37.0.0/frame_support/storage/types/struct.StorageMap.html) if you want to see the full APIs. - -### Reading Storage - -To read the current value of a key in a `StorageMap`, you can simply call the [`get(key)`](https://docs.rs/frame-support/37.0.0/frame_support/storage/types/struct.StorageMap.html#method.get) API: - -```rust -let my_key: [u8; 32] = [0u8; 32]; -let maybe_value: Option<()> = Kitties::::get(my_key); -``` - -Just as the `StorageValue`, you can see this query returns an `Option`, indicating whether there is actually a value under the key. - -Just as before, the most ergonomic way to read a kitty, or throw an error when there is no kitty is to write the following: - -```rust -let kitty: () = Kitties::::get(my_key).ok_or(Error::::NoKitty)?; -``` - -### Writing Storage - -To add a new value to the `StorageMap`, you can simply call the `insert` API: - -```rust -let my_key: [u8; 32] = [0u8; 32]; -Kitties::::insert(my_key, ()); -``` - -The same behaviors apply to `StorageMap` as a `StorageValue`. - -The [`insert`](https://docs.rs/frame-support/37.0.0/frame_support/storage/types/struct.StorageMap.html#method.insert) API cannot fail. If a value already exists in the map, under the key, we will simply overwrite that value. If you want to check if a value already exists in the map under a key, the most efficient way is to call [`contains_key(key)`](https://docs.rs/frame-support/37.0.0/frame_support/storage/types/struct.StorageMap.html#method.contains_key). - -## Your Turn - -`StorageMap`s are easy! - -Update the logic in your pallet to insert a new kitty into your `Kitties` map when we call `mint`. - -For this, you will need to add a second parameter to the `mint` function to pass the unique identifier for the kitty. +Here you will find the solution for the previous step. diff --git a/steps/20/gitorial_metadata.json b/steps/20/gitorial_metadata.json index dc116597..f09bddca 100644 --- a/steps/20/gitorial_metadata.json +++ b/steps/20/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: use kitties map" -} \ No newline at end of file + "commitMessage": "solution: learn about storage maps" +} diff --git a/steps/20/src/impls.rs b/steps/20/src/impls.rs index 89c7306a..d283fd6b 100644 --- a/steps/20/src/impls.rs +++ b/steps/20/src/impls.rs @@ -2,11 +2,9 @@ use super::*; use frame::prelude::*; impl Pallet { - /* 🚧 TODO 🚧: Update this function signature to include `id` which is type `[u8; 32]`. */ pub fn mint(owner: T::AccountId) -> DispatchResult { let current_count: u32 = CountForKitties::::get(); let new_count = current_count.checked_add(1).ok_or(Error::::TooManyKitties)?; - /* 🚧 TODO 🚧: In the `Kitties` map, under the key `id`, insert `()`. */ CountForKitties::::set(new_count); Self::deposit_event(Event::::Created { owner }); Ok(()) diff --git a/steps/20/src/lib.rs b/steps/20/src/lib.rs index 3e32e756..d4e9d017 100644 --- a/steps/20/src/lib.rs +++ b/steps/20/src/lib.rs @@ -38,10 +38,6 @@ pub mod pallet { impl Pallet { pub fn create_kitty(origin: OriginFor) -> DispatchResult { let who = ensure_signed(origin)?; - /* 🚧 TODO 🚧: - - Create `const default_id`, which type `[u8; 32]` and has value `[0u8; 32]`. - - Pass `default_id` to the `mint` function as a second parameter. - */ Self::mint(who)?; Ok(()) } diff --git a/steps/21/README.md b/steps/21/README.md index 857d540c..15924acf 100644 --- a/steps/21/README.md +++ b/steps/21/README.md @@ -1,3 +1,47 @@ -# Solution +# Kitties Map -Here you will find the solution for the previous step. +Now let's learn to interact with our `Kitties` storage map, and update the map when we `mint` new kitties. + +## Basic APIs + +This tutorial will only go over just the basic APIs needed to build our Pallet. + +Check out the [`StorageMap` documentation](https://docs.rs/frame-support/37.0.0/frame_support/storage/types/struct.StorageMap.html) if you want to see the full APIs. + +### Reading Storage + +To read the current value of a key in a `StorageMap`, you can simply call the [`get(key)`](https://docs.rs/frame-support/37.0.0/frame_support/storage/types/struct.StorageMap.html#method.get) API: + +```rust +let my_key: [u8; 32] = [0u8; 32]; +let maybe_value: Option<()> = Kitties::::get(my_key); +``` + +Just as the `StorageValue`, you can see this query returns an `Option`, indicating whether there is actually a value under the key. + +Just as before, the most ergonomic way to read a kitty, or throw an error when there is no kitty is to write the following: + +```rust +let kitty: () = Kitties::::get(my_key).ok_or(Error::::NoKitty)?; +``` + +### Writing Storage + +To add a new value to the `StorageMap`, you can simply call the `insert` API: + +```rust +let my_key: [u8; 32] = [0u8; 32]; +Kitties::::insert(my_key, ()); +``` + +The same behaviors apply to `StorageMap` as a `StorageValue`. + +The [`insert`](https://docs.rs/frame-support/37.0.0/frame_support/storage/types/struct.StorageMap.html#method.insert) API cannot fail. If a value already exists in the map, under the key, we will simply overwrite that value. If you want to check if a value already exists in the map under a key, the most efficient way is to call [`contains_key(key)`](https://docs.rs/frame-support/37.0.0/frame_support/storage/types/struct.StorageMap.html#method.contains_key). + +## Your Turn + +`StorageMap`s are easy! + +Update the logic in your pallet to insert a new kitty into your `Kitties` map when we call `mint`. + +For this, you will need to add a second parameter to the `mint` function to pass the unique identifier for the kitty. diff --git a/steps/21/gitorial_metadata.json b/steps/21/gitorial_metadata.json index 8641d1b6..dc116597 100644 --- a/steps/21/gitorial_metadata.json +++ b/steps/21/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: use kitties map" + "commitMessage": "template: use kitties map" } \ No newline at end of file diff --git a/steps/21/src/impls.rs b/steps/21/src/impls.rs index 363f5e49..89c7306a 100644 --- a/steps/21/src/impls.rs +++ b/steps/21/src/impls.rs @@ -2,10 +2,11 @@ use super::*; use frame::prelude::*; impl Pallet { - pub fn mint(owner: T::AccountId, dna: [u8; 32]) -> DispatchResult { + /* 🚧 TODO 🚧: Update this function signature to include `id` which is type `[u8; 32]`. */ + pub fn mint(owner: T::AccountId) -> DispatchResult { let current_count: u32 = CountForKitties::::get(); let new_count = current_count.checked_add(1).ok_or(Error::::TooManyKitties)?; - Kitties::::insert(dna, ()); + /* 🚧 TODO 🚧: In the `Kitties` map, under the key `id`, insert `()`. */ CountForKitties::::set(new_count); Self::deposit_event(Event::::Created { owner }); Ok(()) diff --git a/steps/21/src/lib.rs b/steps/21/src/lib.rs index c216fa6e..3e32e756 100644 --- a/steps/21/src/lib.rs +++ b/steps/21/src/lib.rs @@ -38,8 +38,11 @@ pub mod pallet { impl Pallet { pub fn create_kitty(origin: OriginFor) -> DispatchResult { let who = ensure_signed(origin)?; - let dna = [0u8; 32]; - Self::mint(who, dna)?; + /* 🚧 TODO 🚧: + - Create `const default_id`, which type `[u8; 32]` and has value `[0u8; 32]`. + - Pass `default_id` to the `mint` function as a second parameter. + */ + Self::mint(who)?; Ok(()) } } diff --git a/steps/22/README.md b/steps/22/README.md index 2e516c98..857d540c 100644 --- a/steps/22/README.md +++ b/steps/22/README.md @@ -1,44 +1,3 @@ -# Duplicate Kitty Check +# Solution -To make sure your state transition function behaves as expected, you must check everything that could go wrong, and return an error in those cases. - -## Contains Key - -As we mentioned in the previous section, the `insert` API will simply overwrite any existing data which is already there. We want to prevent this, else we risk overwriting data about a kitty that already exists and is already owned by someone. - -To prevent this, we can call the `contains_key(key)` API, which will return `true` if there is already a value in storage, or `false` if there isn't. - -You might ask: Why do we call `contains_key` rather than call `get` and checking the `Option`? - -Well, there are two reasons: - -1. Just like `StorageValue`, you can set a `StorageMap` with `QueryKind = ValueQuery`, thus we would no longer return an `Option` for you to check, and we would "hide" the fact that the map is empty at that key. So this API is the only way to check if the value ACTUALLY exists or not. -2. The `contains_key` API is strictly more efficient than the `get` API. The `get` API returns the value, which means we need to go into the database, read the bits, serialize it to a Rust type, pass that back to the Pallet, and assign it to the variable. - - On the other hand, `contains_key` can simply check if the value exists in the database, and only return back the boolean result. No need to serialize all the bytes, store the variable, or any of that. - -This same trick applies to `StorageValue` too. Rather than calling `get`, you can call `exists`, which provides the same api as `contains_key`. - -## Ensure - -To do simple duplication checks and return an error, we can write the following: - -```rust -if (Kitties::::contains_key(my_key)) { - return Err(Error::::DuplicateKitty.into()); -} -``` - -But that is pretty verbose. We have a macro which can do this for you in a single line: - -```rust -ensure!(!Kitties::::contains_key(my_key), Error::::DuplicateKitty); -``` - -`ensure!` is a macro, which basically expands into the same verbose code shown above, except checking the opposite condition. That is to say, we `ensure!` that `Kitties` does NOT `contains_key`, else we return the error specified. - -There really is no difference here, so use whatever makes you comfortable. - -## Your Turn - -Now that you know how to efficiently check for an existing kitty, put that check into the `mint` function to ensure that we do not mint a duplicate kitty in the `Kitties` storage map. +Here you will find the solution for the previous step. diff --git a/steps/22/gitorial_metadata.json b/steps/22/gitorial_metadata.json index c7df4568..8641d1b6 100644 --- a/steps/22/gitorial_metadata.json +++ b/steps/22/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: add duplicate kitty check" + "commitMessage": "solution: use kitties map" } \ No newline at end of file diff --git a/steps/22/src/impls.rs b/steps/22/src/impls.rs index 292909e1..363f5e49 100644 --- a/steps/22/src/impls.rs +++ b/steps/22/src/impls.rs @@ -3,10 +3,6 @@ use frame::prelude::*; impl Pallet { pub fn mint(owner: T::AccountId, dna: [u8; 32]) -> DispatchResult { - /* 🚧 TODO 🚧: - - `ensure!` that `Kitties` map does not `contains_key` for `dna`. - - If it does, return `Error::::DuplicateKitty`. - */ let current_count: u32 = CountForKitties::::get(); let new_count = current_count.checked_add(1).ok_or(Error::::TooManyKitties)?; Kitties::::insert(dna, ()); diff --git a/steps/22/src/lib.rs b/steps/22/src/lib.rs index 972ee059..c216fa6e 100644 --- a/steps/22/src/lib.rs +++ b/steps/22/src/lib.rs @@ -32,7 +32,6 @@ pub mod pallet { #[pallet::error] pub enum Error { TooManyKitties, - /* 🚧 TODO 🚧: Create a new error `DuplicateKitty`. */ } #[pallet::call] diff --git a/steps/23/README.md b/steps/23/README.md index 857d540c..2e516c98 100644 --- a/steps/23/README.md +++ b/steps/23/README.md @@ -1,3 +1,44 @@ -# Solution +# Duplicate Kitty Check -Here you will find the solution for the previous step. +To make sure your state transition function behaves as expected, you must check everything that could go wrong, and return an error in those cases. + +## Contains Key + +As we mentioned in the previous section, the `insert` API will simply overwrite any existing data which is already there. We want to prevent this, else we risk overwriting data about a kitty that already exists and is already owned by someone. + +To prevent this, we can call the `contains_key(key)` API, which will return `true` if there is already a value in storage, or `false` if there isn't. + +You might ask: Why do we call `contains_key` rather than call `get` and checking the `Option`? + +Well, there are two reasons: + +1. Just like `StorageValue`, you can set a `StorageMap` with `QueryKind = ValueQuery`, thus we would no longer return an `Option` for you to check, and we would "hide" the fact that the map is empty at that key. So this API is the only way to check if the value ACTUALLY exists or not. +2. The `contains_key` API is strictly more efficient than the `get` API. The `get` API returns the value, which means we need to go into the database, read the bits, serialize it to a Rust type, pass that back to the Pallet, and assign it to the variable. + + On the other hand, `contains_key` can simply check if the value exists in the database, and only return back the boolean result. No need to serialize all the bytes, store the variable, or any of that. + +This same trick applies to `StorageValue` too. Rather than calling `get`, you can call `exists`, which provides the same api as `contains_key`. + +## Ensure + +To do simple duplication checks and return an error, we can write the following: + +```rust +if (Kitties::::contains_key(my_key)) { + return Err(Error::::DuplicateKitty.into()); +} +``` + +But that is pretty verbose. We have a macro which can do this for you in a single line: + +```rust +ensure!(!Kitties::::contains_key(my_key), Error::::DuplicateKitty); +``` + +`ensure!` is a macro, which basically expands into the same verbose code shown above, except checking the opposite condition. That is to say, we `ensure!` that `Kitties` does NOT `contains_key`, else we return the error specified. + +There really is no difference here, so use whatever makes you comfortable. + +## Your Turn + +Now that you know how to efficiently check for an existing kitty, put that check into the `mint` function to ensure that we do not mint a duplicate kitty in the `Kitties` storage map. diff --git a/steps/23/gitorial_metadata.json b/steps/23/gitorial_metadata.json index bb13b08f..c7df4568 100644 --- a/steps/23/gitorial_metadata.json +++ b/steps/23/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: add duplicate kitty check" + "commitMessage": "template: add duplicate kitty check" } \ No newline at end of file diff --git a/steps/23/src/impls.rs b/steps/23/src/impls.rs index c0e7cb27..292909e1 100644 --- a/steps/23/src/impls.rs +++ b/steps/23/src/impls.rs @@ -3,9 +3,10 @@ use frame::prelude::*; impl Pallet { pub fn mint(owner: T::AccountId, dna: [u8; 32]) -> DispatchResult { - // Check if the kitty does not already exist in our storage map - ensure!(!Kitties::::contains_key(dna), Error::::DuplicateKitty); - + /* 🚧 TODO 🚧: + - `ensure!` that `Kitties` map does not `contains_key` for `dna`. + - If it does, return `Error::::DuplicateKitty`. + */ let current_count: u32 = CountForKitties::::get(); let new_count = current_count.checked_add(1).ok_or(Error::::TooManyKitties)?; Kitties::::insert(dna, ()); diff --git a/steps/23/src/lib.rs b/steps/23/src/lib.rs index d57b0509..972ee059 100644 --- a/steps/23/src/lib.rs +++ b/steps/23/src/lib.rs @@ -32,7 +32,7 @@ pub mod pallet { #[pallet::error] pub enum Error { TooManyKitties, - DuplicateKitty, + /* 🚧 TODO 🚧: Create a new error `DuplicateKitty`. */ } #[pallet::call] diff --git a/steps/24/README.md b/steps/24/README.md index 9aca9aa8..857d540c 100644 --- a/steps/24/README.md +++ b/steps/24/README.md @@ -1,5 +1,3 @@ -# Storing Objects +# Solution -In this section, you will learn how to store more complex objects in storage. - -TODO: more +Here you will find the solution for the previous step. diff --git a/steps/24/gitorial_metadata.json b/steps/24/gitorial_metadata.json index 7a638b34..bb13b08f 100644 --- a/steps/24/gitorial_metadata.json +++ b/steps/24/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "section: storing objects" + "commitMessage": "solution: add duplicate kitty check" } \ No newline at end of file diff --git a/steps/25/README.md b/steps/25/README.md index 62f37332..9aca9aa8 100644 --- a/steps/25/README.md +++ b/steps/25/README.md @@ -1,91 +1,5 @@ -# Kitty Struct +# Storing Objects -In this step, we will create a new struct which is generic over ``. This step will just be using basic Rust, so no macro-magic or Pallet specific stuff is happening here. +In this section, you will learn how to store more complex objects in storage. -## Creating a Struct - -Creating a new struct in Rust is pretty straight forward. - -```rust -pub struct Kitty { - dna: [u8; 32], - owner: u32, -} -``` - -One important detail for creating a struct to be used in a Pallet is that the struct should be marked `pub`. The compiler will complain if you try to use an object in your pallet without marking it `pub`, because it will be used across other modules in your blockchain. - -Creating a new instance of this struct is easy: - -```rust -let kitty = Kitty { - dna: [0u8; 32], - owner: 0u32, -} -``` - -## Creating a Generic Struct - -We will often want to access our Pallet specific types and store them. To do this, we need to make a struct which is generic over those types. - -The example we will use here is wanting to store the account of the owner of the kitty. - -There are actually two ways we can do this, and we will show you both. - -### Generic Over Each Type - -The first, and most verbose option in our situation is to make the struct generic over each type we want to use. - -```rust -pub struct Kitty { - dna: [u8; 32], - owner: AccountId, -} -``` - -If we want to use multiple generic types, we could just keep extending this pattern: - -```rust -pub struct Kitty { - dna: [u8; 32], - owner: AccountId, - created: BlockNumber, -} -``` - -When you reference this type, you will need to mention the generics that it is using: - -```rust -pub type MyAlias = Kitty; -``` - -The problem with this approach is that as you use more and more types, everything will just become excessively verbose. - -### Generic Over `T` - -The more common option is to make a struct generic over `` instead of the individual types. Through `T` you will then be able to access ALL the types from our blockchain. This is exactly why we created `T` to begin with! - -Let's look how that might look like: - -```rust -pub struct Kitty { - dna: [u8; 32], - owner: T::AccountId, -} -``` - -In this context, you can see you can access any of the runtime types by doing `T::Type`. - -It also becomes a lot easier to reference this type, no matter how many different runtime types you are using: - -```rust -pub type MyAlias = Kitty; -``` - -I want to be clear, in the final compiled binary, both options for creating a generic struct are exactly the same. There are some nuanced advantages to both options, but these details are really at a much lower level than we will go over in this tutorial. - -## Your Turn - -Now that you know how to create a generic struct, create a new `Kitty` struct which is generic over ``. It should have fields for the `dna` of the kitty and the `owner` of the kitty. - -In our next step, we will learn how we can actually use this struct in runtime storage. +TODO: more diff --git a/steps/25/gitorial_metadata.json b/steps/25/gitorial_metadata.json index e03c9676..7a638b34 100644 --- a/steps/25/gitorial_metadata.json +++ b/steps/25/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: create a kitty struct" + "commitMessage": "section: storing objects" } \ No newline at end of file diff --git a/steps/25/src/lib.rs b/steps/25/src/lib.rs index 0708f660..d57b0509 100644 --- a/steps/25/src/lib.rs +++ b/steps/25/src/lib.rs @@ -17,14 +17,6 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; } - /* 🚧 TODO 🚧: - - Create a new `struct` called `Kitty`. - - Make `Kitty` generic over `T` where `T: Config`. - - Add two fields to `Kitty`: - - `dna` which is type `[u8; 32]`. - - `owner` which is type `T::AccountId`. - */ - #[pallet::storage] pub(super) type CountForKitties = StorageValue; diff --git a/steps/26/README.md b/steps/26/README.md index 857d540c..62f37332 100644 --- a/steps/26/README.md +++ b/steps/26/README.md @@ -1,3 +1,91 @@ -# Solution +# Kitty Struct -Here you will find the solution for the previous step. +In this step, we will create a new struct which is generic over ``. This step will just be using basic Rust, so no macro-magic or Pallet specific stuff is happening here. + +## Creating a Struct + +Creating a new struct in Rust is pretty straight forward. + +```rust +pub struct Kitty { + dna: [u8; 32], + owner: u32, +} +``` + +One important detail for creating a struct to be used in a Pallet is that the struct should be marked `pub`. The compiler will complain if you try to use an object in your pallet without marking it `pub`, because it will be used across other modules in your blockchain. + +Creating a new instance of this struct is easy: + +```rust +let kitty = Kitty { + dna: [0u8; 32], + owner: 0u32, +} +``` + +## Creating a Generic Struct + +We will often want to access our Pallet specific types and store them. To do this, we need to make a struct which is generic over those types. + +The example we will use here is wanting to store the account of the owner of the kitty. + +There are actually two ways we can do this, and we will show you both. + +### Generic Over Each Type + +The first, and most verbose option in our situation is to make the struct generic over each type we want to use. + +```rust +pub struct Kitty { + dna: [u8; 32], + owner: AccountId, +} +``` + +If we want to use multiple generic types, we could just keep extending this pattern: + +```rust +pub struct Kitty { + dna: [u8; 32], + owner: AccountId, + created: BlockNumber, +} +``` + +When you reference this type, you will need to mention the generics that it is using: + +```rust +pub type MyAlias = Kitty; +``` + +The problem with this approach is that as you use more and more types, everything will just become excessively verbose. + +### Generic Over `T` + +The more common option is to make a struct generic over `` instead of the individual types. Through `T` you will then be able to access ALL the types from our blockchain. This is exactly why we created `T` to begin with! + +Let's look how that might look like: + +```rust +pub struct Kitty { + dna: [u8; 32], + owner: T::AccountId, +} +``` + +In this context, you can see you can access any of the runtime types by doing `T::Type`. + +It also becomes a lot easier to reference this type, no matter how many different runtime types you are using: + +```rust +pub type MyAlias = Kitty; +``` + +I want to be clear, in the final compiled binary, both options for creating a generic struct are exactly the same. There are some nuanced advantages to both options, but these details are really at a much lower level than we will go over in this tutorial. + +## Your Turn + +Now that you know how to create a generic struct, create a new `Kitty` struct which is generic over ``. It should have fields for the `dna` of the kitty and the `owner` of the kitty. + +In our next step, we will learn how we can actually use this struct in runtime storage. diff --git a/steps/26/gitorial_metadata.json b/steps/26/gitorial_metadata.json index 972532f0..e03c9676 100644 --- a/steps/26/gitorial_metadata.json +++ b/steps/26/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: create a kitty struct" + "commitMessage": "template: create a kitty struct" } \ No newline at end of file diff --git a/steps/26/src/lib.rs b/steps/26/src/lib.rs index 51b70acf..0708f660 100644 --- a/steps/26/src/lib.rs +++ b/steps/26/src/lib.rs @@ -17,11 +17,13 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; } - pub struct Kitty { - // Using 32 bytes to represent a kitty DNA - pub dna: [u8; 32], - pub owner: T::AccountId, - } + /* 🚧 TODO 🚧: + - Create a new `struct` called `Kitty`. + - Make `Kitty` generic over `T` where `T: Config`. + - Add two fields to `Kitty`: + - `dna` which is type `[u8; 32]`. + - `owner` which is type `T::AccountId`. + */ #[pallet::storage] pub(super) type CountForKitties = StorageValue; diff --git a/steps/27/README.md b/steps/27/README.md index 387d3040..857d540c 100644 --- a/steps/27/README.md +++ b/steps/27/README.md @@ -1,130 +1,3 @@ -# Storing a Struct +# Solution -We have successfully created a generic struct for our pallet. Now we need to actually use it in our runtime. - -## Derive Macros - -One of the powerful tools you get from vanilla Rust is the `#[derive(...)]` macros. - -In the spirit of Rust macros, derive macros help reduce boiler plate code which can be automatically generated for you. In this case, the derive macros generate trait implementations for the objects they are applied on. - -The most simple example might be `Default`. - -The verbose way of implementing `Default` would be: - -```rust -pub struct MyObject { - field_0: u32, - field_1: u64, -} - -impl Default for MyObject { - fn default() -> Self { - Self { - field_0: Default::default(), - field_1: Default::default(), - } - } -} -``` - -You can see here that we can simply say the default for `MyObject` is taking the default of each field in `MyObject` and constructing the struct. - -We can do the exact same thing with `#[derive(Default)]`: - -```rust -#[derive(Default)] -pub struct MyObject { - field_0: u32, - field_1: u64, -} -``` - -As long as all the fields inside `MyObject` implement `Default`, then the derive macro will handle all the magic. - -> Remember that `T::AccountId` explicitly chooses not to implement `Default`, so you cannot implement `Default` on the `Kitty` struct. - -## Traits Required for Storage - -For an object to be placed inside runtime storage, we require it to have a number of traits implemented: - -- `Encode`: The object must be encodable to bytes using `parity_scale_codec`. -- `Decode`: The object must be decodable from bytes using `parity_scale_codec`. -- `MaxEncodedLen`: When the object is encoded, it must have an upper limit to its size. -- `TypeInfo`: The object must be able to generate metadata describing the object. - -All of these things are pretty specific to the requirements of using the Polkadot-SDK for building a blockchain. - -### Parity SCALE Codec - -Parity SCALE Codec is a custom encoding and decoding library used in the `polkadot-sdk`. - -The first question we are always asked when talking about SCALE, is why don't we use `` instead? - -Well, SCALE is: - -- Simple to define. -- Not Rust-specific (but happens to work great in Rust). - - Easy to derive codec logic: `#[derive(Encode, Decode)]` - - Viable and useful for APIs like: `MaxEncodedLen` and `TypeInfo` - - It does not use Rust `std`, and thus can compile to Wasm `no_std`. -- Consensus critical / bijective; one value will always encode to one blob and that blob will only decode to that value. -- Supports a copy-free decode for basic types on LE architectures (like Wasm). -- It is about as thin and lightweight as can be. - -What you need to know about SCALE is that it defines how every object in the `polkadot-sdk` is represented in bytes. - -### Max Encoded Length - -Now that we have the tools to define the way objects should be encoded, we are able to create a trait which tracks the maximum encoded length of an object: `MaxEncodedLen`. - -We then use that information to predict in the worst case scenario how much data will be used when we store it. - -- For a `u8`, the `max_encoded_len()` is always the same: 1 byte. -- For a `u64`, the `max_encoded_len()` is always the same: 8 bytes. -- For a basic `enum`, it is also just 1 byte, since an enum can represent up to 256 variants. -- For a `struct`, the `max_encoded_len()` will be the sum of the `max_encoded_len()` of all items in the `struct`. - -We need to be able to predict the size of items in our storage because it affects nearly all the constraints of our blockchain: storage size, memory usage, network bandwidth, and even execution time for encoding and decoding. - -### Type Info - -The last required trait for any storage item is `TypeInfo`. - -This trait is key for off-chain interactions with your blockchain. It is used to generate metadata for all the objects and types in your blockchain. - -Metadata exposes all the details of your blockchain to the outside world, allowing us to dynamically construct APIs to interact with the blockchain. This is super relevant since the `polkadot-sdk` is a framework for modular and upgradable blockchains. - -We won't really use this in this tutorial, but it is super relevant to learn about once you start getting ready to actually use your blockchain. - -#### Skip Type Params - -One nasty thing about the `TypeInfo` derive macro, is that it isn't very "smart". - -As I mentioned, the whole point of `TypeInfo` is to generate relevant metadata about the types used in your blockchain. However, part of our `Kitty` type is the generic parameter `T`, and it really does not make any sense to generate `TypeInfo` for `T`. - -To make `TypeInfo` work while we have `T`, we need to include the additional line: - -```rust -#[scale_info(skip_type_params(T))] -``` - -This tells the `TypeInfo` derive macro to simply "skip" the `T` type parameter when generating its code. The best thing for you to do is try compiling your code without this additional line, look at the errors that are generated, then see them disappear with the `skip_type_params`. - -Then in the future, if you run into this error again, you will know what to do. - -## Your Turn - -Now that you know all about the various traits required for runtime development, derive them on the `Kitty` struct. - -Don't forget to include the `skip_type_params(T)`. - -After that, update your `Kitties` map to use `Value = Kitty`. - -Finally, update the logic in `mint` to create and insert this object into storage. - -## Learn More - -To get a primer on Parity SCALE Codec, check out this video from the Polkadot Blockchain Academy: - - +Here you will find the solution for the previous step. diff --git a/steps/27/gitorial_metadata.json b/steps/27/gitorial_metadata.json index 605a7443..972532f0 100644 --- a/steps/27/gitorial_metadata.json +++ b/steps/27/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: put struct in storage" + "commitMessage": "solution: create a kitty struct" } \ No newline at end of file diff --git a/steps/27/src/impls.rs b/steps/27/src/impls.rs index 741a6ffd..c0e7cb27 100644 --- a/steps/27/src/impls.rs +++ b/steps/27/src/impls.rs @@ -3,16 +3,11 @@ use frame::prelude::*; impl Pallet { pub fn mint(owner: T::AccountId, dna: [u8; 32]) -> DispatchResult { - /* 🚧 TODO 🚧: - - Create a new variable `kitty` which is a `Kitty` struct with `dna` and `owner`. - */ - // Check if the kitty does not already exist in our storage map ensure!(!Kitties::::contains_key(dna), Error::::DuplicateKitty); let current_count: u32 = CountForKitties::::get(); let new_count = current_count.checked_add(1).ok_or(Error::::TooManyKitties)?; - /* 🚧 TODO 🚧: Insert `kitty`into the map instead of `()`. */ Kitties::::insert(dna, ()); CountForKitties::::set(new_count); Self::deposit_event(Event::::Created { owner }); diff --git a/steps/27/src/lib.rs b/steps/27/src/lib.rs index 21ad6d91..51b70acf 100644 --- a/steps/27/src/lib.rs +++ b/steps/27/src/lib.rs @@ -17,10 +17,6 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; } - /* 🚧 TODO 🚧: - - Add the derive macros needed for putting a struct in storage. - - Add `#[scale_info(skip_type_params(T))]` to ignore the generic `T`. - */ pub struct Kitty { // Using 32 bytes to represent a kitty DNA pub dna: [u8; 32], @@ -31,7 +27,6 @@ pub mod pallet { pub(super) type CountForKitties = StorageValue; #[pallet::storage] - /* 🚧 TODO 🚧: Update the `Value` to be type `Kitty` instead of (). */ pub(super) type Kitties = StorageMap; #[pallet::event] diff --git a/steps/28/README.md b/steps/28/README.md index 857d540c..387d3040 100644 --- a/steps/28/README.md +++ b/steps/28/README.md @@ -1,3 +1,130 @@ -# Solution +# Storing a Struct -Here you will find the solution for the previous step. +We have successfully created a generic struct for our pallet. Now we need to actually use it in our runtime. + +## Derive Macros + +One of the powerful tools you get from vanilla Rust is the `#[derive(...)]` macros. + +In the spirit of Rust macros, derive macros help reduce boiler plate code which can be automatically generated for you. In this case, the derive macros generate trait implementations for the objects they are applied on. + +The most simple example might be `Default`. + +The verbose way of implementing `Default` would be: + +```rust +pub struct MyObject { + field_0: u32, + field_1: u64, +} + +impl Default for MyObject { + fn default() -> Self { + Self { + field_0: Default::default(), + field_1: Default::default(), + } + } +} +``` + +You can see here that we can simply say the default for `MyObject` is taking the default of each field in `MyObject` and constructing the struct. + +We can do the exact same thing with `#[derive(Default)]`: + +```rust +#[derive(Default)] +pub struct MyObject { + field_0: u32, + field_1: u64, +} +``` + +As long as all the fields inside `MyObject` implement `Default`, then the derive macro will handle all the magic. + +> Remember that `T::AccountId` explicitly chooses not to implement `Default`, so you cannot implement `Default` on the `Kitty` struct. + +## Traits Required for Storage + +For an object to be placed inside runtime storage, we require it to have a number of traits implemented: + +- `Encode`: The object must be encodable to bytes using `parity_scale_codec`. +- `Decode`: The object must be decodable from bytes using `parity_scale_codec`. +- `MaxEncodedLen`: When the object is encoded, it must have an upper limit to its size. +- `TypeInfo`: The object must be able to generate metadata describing the object. + +All of these things are pretty specific to the requirements of using the Polkadot-SDK for building a blockchain. + +### Parity SCALE Codec + +Parity SCALE Codec is a custom encoding and decoding library used in the `polkadot-sdk`. + +The first question we are always asked when talking about SCALE, is why don't we use `` instead? + +Well, SCALE is: + +- Simple to define. +- Not Rust-specific (but happens to work great in Rust). + - Easy to derive codec logic: `#[derive(Encode, Decode)]` + - Viable and useful for APIs like: `MaxEncodedLen` and `TypeInfo` + - It does not use Rust `std`, and thus can compile to Wasm `no_std`. +- Consensus critical / bijective; one value will always encode to one blob and that blob will only decode to that value. +- Supports a copy-free decode for basic types on LE architectures (like Wasm). +- It is about as thin and lightweight as can be. + +What you need to know about SCALE is that it defines how every object in the `polkadot-sdk` is represented in bytes. + +### Max Encoded Length + +Now that we have the tools to define the way objects should be encoded, we are able to create a trait which tracks the maximum encoded length of an object: `MaxEncodedLen`. + +We then use that information to predict in the worst case scenario how much data will be used when we store it. + +- For a `u8`, the `max_encoded_len()` is always the same: 1 byte. +- For a `u64`, the `max_encoded_len()` is always the same: 8 bytes. +- For a basic `enum`, it is also just 1 byte, since an enum can represent up to 256 variants. +- For a `struct`, the `max_encoded_len()` will be the sum of the `max_encoded_len()` of all items in the `struct`. + +We need to be able to predict the size of items in our storage because it affects nearly all the constraints of our blockchain: storage size, memory usage, network bandwidth, and even execution time for encoding and decoding. + +### Type Info + +The last required trait for any storage item is `TypeInfo`. + +This trait is key for off-chain interactions with your blockchain. It is used to generate metadata for all the objects and types in your blockchain. + +Metadata exposes all the details of your blockchain to the outside world, allowing us to dynamically construct APIs to interact with the blockchain. This is super relevant since the `polkadot-sdk` is a framework for modular and upgradable blockchains. + +We won't really use this in this tutorial, but it is super relevant to learn about once you start getting ready to actually use your blockchain. + +#### Skip Type Params + +One nasty thing about the `TypeInfo` derive macro, is that it isn't very "smart". + +As I mentioned, the whole point of `TypeInfo` is to generate relevant metadata about the types used in your blockchain. However, part of our `Kitty` type is the generic parameter `T`, and it really does not make any sense to generate `TypeInfo` for `T`. + +To make `TypeInfo` work while we have `T`, we need to include the additional line: + +```rust +#[scale_info(skip_type_params(T))] +``` + +This tells the `TypeInfo` derive macro to simply "skip" the `T` type parameter when generating its code. The best thing for you to do is try compiling your code without this additional line, look at the errors that are generated, then see them disappear with the `skip_type_params`. + +Then in the future, if you run into this error again, you will know what to do. + +## Your Turn + +Now that you know all about the various traits required for runtime development, derive them on the `Kitty` struct. + +Don't forget to include the `skip_type_params(T)`. + +After that, update your `Kitties` map to use `Value = Kitty`. + +Finally, update the logic in `mint` to create and insert this object into storage. + +## Learn More + +To get a primer on Parity SCALE Codec, check out this video from the Polkadot Blockchain Academy: + + diff --git a/steps/28/gitorial_metadata.json b/steps/28/gitorial_metadata.json index 95a47817..605a7443 100644 --- a/steps/28/gitorial_metadata.json +++ b/steps/28/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: put struct in storage" + "commitMessage": "template: put struct in storage" } \ No newline at end of file diff --git a/steps/28/src/impls.rs b/steps/28/src/impls.rs index 5d3c1046..741a6ffd 100644 --- a/steps/28/src/impls.rs +++ b/steps/28/src/impls.rs @@ -3,13 +3,17 @@ use frame::prelude::*; impl Pallet { pub fn mint(owner: T::AccountId, dna: [u8; 32]) -> DispatchResult { - let kitty = Kitty { dna, owner: owner.clone() }; + /* 🚧 TODO 🚧: + - Create a new variable `kitty` which is a `Kitty` struct with `dna` and `owner`. + */ + // Check if the kitty does not already exist in our storage map ensure!(!Kitties::::contains_key(dna), Error::::DuplicateKitty); let current_count: u32 = CountForKitties::::get(); let new_count = current_count.checked_add(1).ok_or(Error::::TooManyKitties)?; - Kitties::::insert(dna, kitty); + /* 🚧 TODO 🚧: Insert `kitty`into the map instead of `()`. */ + Kitties::::insert(dna, ()); CountForKitties::::set(new_count); Self::deposit_event(Event::::Created { owner }); Ok(()) diff --git a/steps/28/src/lib.rs b/steps/28/src/lib.rs index 8b073f8c..21ad6d91 100644 --- a/steps/28/src/lib.rs +++ b/steps/28/src/lib.rs @@ -17,8 +17,10 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; } - #[derive(Encode, Decode, TypeInfo, MaxEncodedLen)] - #[scale_info(skip_type_params(T))] + /* 🚧 TODO 🚧: + - Add the derive macros needed for putting a struct in storage. + - Add `#[scale_info(skip_type_params(T))]` to ignore the generic `T`. + */ pub struct Kitty { // Using 32 bytes to represent a kitty DNA pub dna: [u8; 32], @@ -29,7 +31,8 @@ pub mod pallet { pub(super) type CountForKitties = StorageValue; #[pallet::storage] - pub(super) type Kitties = StorageMap>; + /* 🚧 TODO 🚧: Update the `Value` to be type `Kitty` instead of (). */ + pub(super) type Kitties = StorageMap; #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] diff --git a/steps/29/README.md b/steps/29/README.md index cf64a574..857d540c 100644 --- a/steps/29/README.md +++ b/steps/29/README.md @@ -1,52 +1,3 @@ -# Generate Unique DNA +# Solution -In this step, we will show how to generate uniqueness using information from the blockchain. - -## Randomness - -Ideally, we would give every kitty we mint a randomly generated DNA. - -However generating randomness on a blockchain is extremely difficult because we must come to consensus over all logic and data used on the blockchain. Any kind of randomness function must generate exactly the same randomness for all nodes. And if that is the case, it is still possible to influence randomness as a block producer by choosing NOT to build a block with a randomness you do not like. - -Polkadot does provide access to a verifiable random function (VRF), but exactly the properties of this VRF and how to use it is beyond the scope of this tutorial. Not to mention we are also iteratively improving the VRF provided by Polkadot. - -## Uniqueness - -So rather than using true randomness, we will instead try to generate uniqueness. - -There are different levels of uniqueness we can achieve using data from our blockchain. - -- `frame_system::Pallet::::parent_hash()`: The hash of the previous block. This will ensure uniqueness for every fork of the blockchain. -- `frame_system::Pallet::::block_number()`: The number of the current block. This will obviously be unique for each block. -- `frame_system::Pallet::::extrinsic_index()`: The number of the extrinsic in the block that is being executed. This will be unique for each extrinsic in a block. -- `CountForKitties::::get()`: The number of kitties in our blockchain. - -If we combine all of these things together, we can ensure that every kitty we mint will be unique, no matter: - -- Which block it comes in. -- How many extrinsics are in a block. -- Or even if a single extrinsic mints multiple kitties. - -## Hash - -Obviously our uniqueness inputs are not super useful as is. But we can convert these inputs into a unique set of bytes with fixed length using a Hash function like [`frame::primitives::BlakeTwo256`](https://docs.rs/polkadot-sdk-frame/0.6.0/polkadot_sdk_frame/primitives/struct.BlakeTwo256.html). - -```rust -// Collect our unique inputs into a single object. -let unique_payload = (item1, item2, item3); -// To use the `hash_of` API, we need to bring the `Hash` trait into scope. -use frame::traits::Hash; -// Hash that object to get a unique identifier. -let hash: [u8; 32] = BlakeTwo256::hash_of(&unique_payload).into(). -``` - -The `hash_of` API comes from the `Hash` trait and takes any `encode`-able object, and returns a `H256`, which is a 256-bit hash. As you can see in the code above, it is easy to convert that to a `[u8; 32]` by just calling `.into()`, since these two types are equivalent. - -Another nice thing about using a hash is you get some sense of pseudo-randomness between the input and output. This means that two kitties which are minted right after one another could have totally different DNA, which could be useful if you want to associate unique attributes to the different parts of their DNA. πŸ€” - - -## Your Turn - -Now that you know how to acquire uniqueness from your blockchain, and how to hash those items, create a new function called `fn gen_dna() -> [u8; 32];` which does these steps to create unique DNA for each kitty that is minted. - -Update your `create_kitty` extrinsic to generate and use this unique DNA. +Here you will find the solution for the previous step. diff --git a/steps/29/gitorial_metadata.json b/steps/29/gitorial_metadata.json index 0bf31dbc..95a47817 100644 --- a/steps/29/gitorial_metadata.json +++ b/steps/29/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: generate unique dna" + "commitMessage": "solution: put struct in storage" } \ No newline at end of file diff --git a/steps/29/src/impls.rs b/steps/29/src/impls.rs index bfd7fdb2..5d3c1046 100644 --- a/steps/29/src/impls.rs +++ b/steps/29/src/impls.rs @@ -1,19 +1,7 @@ use super::*; use frame::prelude::*; -/* 🚧 TODO 🚧: Import `frame::primtives::BlakeTwo256`. */ -/* 🚧 TODO 🚧: Import `frame::traits::Hash`. */ impl Pallet { - /* 🚧 TODO 🚧: Create a function `gen_dna` which returns a `[u8; 32]`. - - Create a `unique_payload` which contains data from `frame_system::Pallet::`: - - `parent_hash` - - `block_number` - - `extrinsic_index` - - `CountForKitties::::get()` - - Use `BlakeTwo256` to calculate the `hash_of` the unique payload. - - Return the hash as a `[u8; 32]`. - */ - pub fn mint(owner: T::AccountId, dna: [u8; 32]) -> DispatchResult { let kitty = Kitty { dna, owner: owner.clone() }; // Check if the kitty does not already exist in our storage map diff --git a/steps/29/src/lib.rs b/steps/29/src/lib.rs index 8e2b3f65..8b073f8c 100644 --- a/steps/29/src/lib.rs +++ b/steps/29/src/lib.rs @@ -47,7 +47,6 @@ pub mod pallet { impl Pallet { pub fn create_kitty(origin: OriginFor) -> DispatchResult { let who = ensure_signed(origin)?; - /* 🚧 TODO 🚧: Use the `Self::gen_dna()` function to generate a unique Kitty. */ let dna = [0u8; 32]; Self::mint(who, dna)?; Ok(()) diff --git a/steps/3/README.md b/steps/3/README.md index 908016e1..f7625391 100644 --- a/steps/3/README.md +++ b/steps/3/README.md @@ -1,108 +1,69 @@ -# FRAME Macros +# Substrate Collectables Workshop: Starting Template -Rust allows you to write [macros](https://doc.rust-lang.org/book/ch19-06-macros.html), which is code that generates code. +This is the starting template for: https://github.com/shawntabrizi/substrate-collectables-workshop -FRAME uses Macros to simplify the development of Pallets, while keeping all of the benefits of using Rust. +## Setup -You can identify most macros in one of two forms: +Follow [these installation instructions](https://docs.substrate.io/install/) to set up your development environment to work with the `polkadot-sdk`. -- `#[macro_name]`: Attribute macros, which are applied on top of valid rust syntax. -- `macro_name!(...)`: Declarative macros, which can define their own internal syntax. +### test -## The Power of Macros +To check that your code compiles successfully at each step, you can run: -We can see a direct example of how much smaller we can make a Rust project by using macros to replace boilerplate code: - -- `wc -l` will show the number of lines of a file. -- `cargo expand` will expand the macros to "pure" Rust. - -```sh -➜ substrate git:(master) βœ— wc -l frame/sudo/src/lib.rs - 310 frame/sudo/src/lib.rs - -➜ substrate git:(master) βœ— cargo expand -p pallet-sudo | wc -l - 2210 +```bash +cargo test ``` -So this shows that a Pallet written with macros can be 7 times smaller than a Pallet which isn't. - -## The Risk of Macros - -One of the risks of using macros is the creation of "macro magic". This is slang for when macros do so much code generation, that the user is not even sure what is happening. - -Especially with declarative macros, where users can basically create a new programming language within the macros. - -The goal of FRAME macros is to stay as close to Rust as possible, but also remove all the boilerplate code that would otherwise be annoying to write. +You should run this now to make sure this starting template is compiling successfully for you. -We will call out such cases of macro magic in the next chapters. +At the beginning and end of every step, you should be able to run `cargo test` without warning or errors. If you have either, you should learn from them and fix them! -## Macros in Our Template +### rustfmt -Our starting template includes all the basic macros used for developing a FRAME pallet. +To keep your code clean and easy to read, we use a tool called [`rustfmt`](https://github.com/rust-lang/rustfmt). To access all the latest features of `rustfmt` we specifically use the `nightly` toolchain. -### Pallet Macro Entrypoint +To install `rustfmt` for `nightly`: -The entrypoint for all the FRAME macros is can be seen here: - -```rust -#[frame::pallet(dev_mode)] -pub mod pallet { - // -- snip -- -} +```bash +rustup component add rustfmt --toolchain nightly ``` -You will notice we wrap all of our Pallet code inside of this entrypoint, which allows our macros to have context of all the details inside. - -More simply explained, if we had: +To configure the behavior of `rustfmt`, we have included a `rustfmt.toml` file. -```rust -#[macro_1] -pub struct ItemOne; +Try running: -#[macro_2] -pub struct ItemTwo; +```bash +cargo +nightly fmt ``` -There would be no way for `#[macro_1]` and `#[macro_2]` to communicate information to one another. However, with a design like: +You shouldn't see any changes this time around, but as you write more code, you will be able to see `cargo +nightly fmt` make everything look pretty, consistent, and easy to read. -```rust -#[macro_entrypoint] -pub mod pallet { - #[macro_1] - pub struct ItemOne; +> We recommend you run `cargo +nightly fmt` after every step! - #[macro_2] - pub struct ItemTwo; -} -``` +### clippy -We can now design the `#[macro_entrypoint]` to keep track of all data inside of the `mod pallet` container, and that means we can now design `#[macro_1]` and `#[macro_2]` to have context of one another, and interact with each other too. +[Clippy](https://github.com/rust-lang/rust-clippy) is a collection of lints to catch common mistakes and improve your Rust code. We also use the `nightly` toolchain here to gain access to the latest features. -The unfortunate limitation here is that wherever we want to use FRAME macros, we must basically do it in a single file and all enclosed by the `#[frame::pallet]` macro entrypoint. +To install `clippy` for `nightly`: -We will go over each of the FRAME macros throughout this tutorial +```bash +rustup component add clippy +``` -### Basic Pallet Structure +Try running: -While the template is already very minimal, you can mentally break it down like: +```bash +cargo +nightly clippy +``` -```rust -use frame::prelude::*; -pub use pallet::*; +Again, you shouldn't see any errors here, but as you write code for this tutorial, `clippy` can be used to help improve the quality of your code. -#[frame::pallet] -pub mod pallet { - use super::*; +## Cheat Sheet - #[pallet::pallet] - pub struct Pallet(core::marker::PhantomData); +You should run these 3 commands at the end of every step without any errors or warnings. - #[pallet::config] // snip - #[pallet::event] // snip - #[pallet::error] // snip - #[pallet::storage] // snip - #[pallet::call] // snip -} +```bash +cargo +nightly fmt +cargo +nightly clippy +cargo test ``` - -Let's explore this further. diff --git a/steps/3/gitorial_metadata.json b/steps/3/gitorial_metadata.json index 4c7f9c85..14c2c7bc 100644 --- a/steps/3/gitorial_metadata.json +++ b/steps/3/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "action: learn about macros" + "commitMessage": "starting-template" } \ No newline at end of file diff --git a/steps/3/src/lib.rs b/steps/3/src/lib.rs index 8aa7c5b2..7b6c6a21 100644 --- a/steps/3/src/lib.rs +++ b/steps/3/src/lib.rs @@ -5,7 +5,6 @@ mod impls; use frame::prelude::*; pub use pallet::*; -/* 🚧 TODO 🚧: Learn about macros used in the `polkadot-sdk`, making pallet development easier. */ #[frame::pallet(dev_mode)] pub mod pallet { use super::*; diff --git a/steps/30/README.md b/steps/30/README.md index 857d540c..cf64a574 100644 --- a/steps/30/README.md +++ b/steps/30/README.md @@ -1,3 +1,52 @@ -# Solution +# Generate Unique DNA -Here you will find the solution for the previous step. +In this step, we will show how to generate uniqueness using information from the blockchain. + +## Randomness + +Ideally, we would give every kitty we mint a randomly generated DNA. + +However generating randomness on a blockchain is extremely difficult because we must come to consensus over all logic and data used on the blockchain. Any kind of randomness function must generate exactly the same randomness for all nodes. And if that is the case, it is still possible to influence randomness as a block producer by choosing NOT to build a block with a randomness you do not like. + +Polkadot does provide access to a verifiable random function (VRF), but exactly the properties of this VRF and how to use it is beyond the scope of this tutorial. Not to mention we are also iteratively improving the VRF provided by Polkadot. + +## Uniqueness + +So rather than using true randomness, we will instead try to generate uniqueness. + +There are different levels of uniqueness we can achieve using data from our blockchain. + +- `frame_system::Pallet::::parent_hash()`: The hash of the previous block. This will ensure uniqueness for every fork of the blockchain. +- `frame_system::Pallet::::block_number()`: The number of the current block. This will obviously be unique for each block. +- `frame_system::Pallet::::extrinsic_index()`: The number of the extrinsic in the block that is being executed. This will be unique for each extrinsic in a block. +- `CountForKitties::::get()`: The number of kitties in our blockchain. + +If we combine all of these things together, we can ensure that every kitty we mint will be unique, no matter: + +- Which block it comes in. +- How many extrinsics are in a block. +- Or even if a single extrinsic mints multiple kitties. + +## Hash + +Obviously our uniqueness inputs are not super useful as is. But we can convert these inputs into a unique set of bytes with fixed length using a Hash function like [`frame::primitives::BlakeTwo256`](https://docs.rs/polkadot-sdk-frame/0.6.0/polkadot_sdk_frame/primitives/struct.BlakeTwo256.html). + +```rust +// Collect our unique inputs into a single object. +let unique_payload = (item1, item2, item3); +// To use the `hash_of` API, we need to bring the `Hash` trait into scope. +use frame::traits::Hash; +// Hash that object to get a unique identifier. +let hash: [u8; 32] = BlakeTwo256::hash_of(&unique_payload).into(). +``` + +The `hash_of` API comes from the `Hash` trait and takes any `encode`-able object, and returns a `H256`, which is a 256-bit hash. As you can see in the code above, it is easy to convert that to a `[u8; 32]` by just calling `.into()`, since these two types are equivalent. + +Another nice thing about using a hash is you get some sense of pseudo-randomness between the input and output. This means that two kitties which are minted right after one another could have totally different DNA, which could be useful if you want to associate unique attributes to the different parts of their DNA. πŸ€” + + +## Your Turn + +Now that you know how to acquire uniqueness from your blockchain, and how to hash those items, create a new function called `fn gen_dna() -> [u8; 32];` which does these steps to create unique DNA for each kitty that is minted. + +Update your `create_kitty` extrinsic to generate and use this unique DNA. diff --git a/steps/30/gitorial_metadata.json b/steps/30/gitorial_metadata.json index 911c9f5b..0bf31dbc 100644 --- a/steps/30/gitorial_metadata.json +++ b/steps/30/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: generate unique dna" + "commitMessage": "template: generate unique dna" } \ No newline at end of file diff --git a/steps/30/src/impls.rs b/steps/30/src/impls.rs index 470eb783..bfd7fdb2 100644 --- a/steps/30/src/impls.rs +++ b/steps/30/src/impls.rs @@ -1,22 +1,18 @@ use super::*; use frame::prelude::*; -use frame::primitives::BlakeTwo256; -use frame::traits::Hash; +/* 🚧 TODO 🚧: Import `frame::primtives::BlakeTwo256`. */ +/* 🚧 TODO 🚧: Import `frame::traits::Hash`. */ impl Pallet { - // Generates and returns DNA and Sex - pub fn gen_dna() -> [u8; 32] { - // Create randomness payload. Multiple kitties can be generated in the same block, - // retaining uniqueness. - let unique_payload = ( - frame_system::Pallet::::parent_hash(), - frame_system::Pallet::::block_number(), - frame_system::Pallet::::extrinsic_index(), - CountForKitties::::get(), - ); - - BlakeTwo256::hash_of(&unique_payload).into() - } + /* 🚧 TODO 🚧: Create a function `gen_dna` which returns a `[u8; 32]`. + - Create a `unique_payload` which contains data from `frame_system::Pallet::`: + - `parent_hash` + - `block_number` + - `extrinsic_index` + - `CountForKitties::::get()` + - Use `BlakeTwo256` to calculate the `hash_of` the unique payload. + - Return the hash as a `[u8; 32]`. + */ pub fn mint(owner: T::AccountId, dna: [u8; 32]) -> DispatchResult { let kitty = Kitty { dna, owner: owner.clone() }; diff --git a/steps/30/src/lib.rs b/steps/30/src/lib.rs index 7ed39985..8e2b3f65 100644 --- a/steps/30/src/lib.rs +++ b/steps/30/src/lib.rs @@ -47,7 +47,8 @@ pub mod pallet { impl Pallet { pub fn create_kitty(origin: OriginFor) -> DispatchResult { let who = ensure_signed(origin)?; - let dna = Self::gen_dna(); + /* 🚧 TODO 🚧: Use the `Self::gen_dna()` function to generate a unique Kitty. */ + let dna = [0u8; 32]; Self::mint(who, dna)?; Ok(()) } diff --git a/steps/31/README.md b/steps/31/README.md index 728b6af1..857d540c 100644 --- a/steps/31/README.md +++ b/steps/31/README.md @@ -1,96 +1,3 @@ -# Track Owned Kitties +# Solution -Now that we can generate unique kitties, we need to consider all the ways we need to store and track those kitties. - -## Redundant Storage - -As a rule, you only want to store data in your blockchain which is necessary for consensus. Blockchains are extremely slow, low powered, and expensive. Blockchains are extremely good at one thing: achieving agreement among a decentralized and untrusted set of individuals. - -When building a blockchain, you need to think about the various constraints: - -- Execution Constraints -- Memory Constraints -- Storage Constraints -- Bandwidth Constrains -- etc... - -In the case of adding redundant storage, all of these constraints come into play! So let's talk about that a bit. - -### Iteration - -It is common when writing code that you might want to perform iteration over items stored in your blockchain. - -In general iteration should be avoided where possible, but if unavoidable it is critical that iteration be bounded in size. - -We literally cannot allow code on our blockchain which would do unbounded iteration, else that would stall our blockchain, which needs to produce a new block on a regular time interval. - -#### Maps - -When you store and iterate over a map, you need to make two considerations: - -1. That the map may not have a bounded upper limit. -2. That each access to the map is very expensive to the blockchain (each is a unique read to the merkle trie). - -If you want to do iteration, probably you do NOT want to use a map for exactly these reasons. - -Maps are great instead for when you need to access or manipulate a single item at a time. - -#### Vec - -When you store and iterate over a vector, the only real consideration you need to have is how large that vector is. - -Accessing large files from the database is going to be slower than accessing small files. - -Once you access the vector, iterating over it and manipulating it is relatively cheap compared to any kind of storage map (but not zero, complexity about vector access still applies). - -If you want to do iteration, you definitely would prefer to use a vector. - -#### Middle Ground - -But sometimes you need to iterate over data, and store a lot of data. This is where we can do a middle ground. - -While it is not great for your Storage Constraints to store redundant data, it can be much better for all your other constraints. - -Let's say we want to answer the question: Give me all the kitties owned by Shawn. - -If all the kitties are stored just in the map, then we would need to iterate over all of them to find which ones are owned by Shawn. - -However, if we ALSO store a vector of kitties owned by Shawn in another storage, yes we would have redundant information in our database, but we will also be able to answer this question much more efficiently. - -A key part of designing your storage is making it efficient for the tasks your code will need to execute. Similarly, you will need to design your code to be efficient for the storage constraints you have. - -Honestly, its a lose / lose situation most times, but it is part of what we need to do when designing blockchain systems. - -## Storage Optimizations - -Storing vectors is a pretty normal part of Pallet development, and there are ways we can optimize adding items to a vector. - -Let's look at a naive way to add a new item to the vector: - -```rust -let mut owned_kitties: Vec<[u8; 32]> = KittiesOwned::::get(owner); -owned_kitties.append(new_kitty); -KittiesOwned::::insert(owner, owned_kitties); -``` - -The first call we need to make is `get` which returns to us all the data in the vector, and all that data is stored in a merkle trie in a database that is really expensive to read from. - -Then we add the item to the vector, and then write the whole new item back into storage. - -But this is way more inefficient than we need! We don't actually need to know what is inside the vector to add a new item to it, we can just say "add this item". - -So we can convert the whole logic to: - -```rust -KittiesOwned::::append(owner, new_kitty); -``` - -In this case, we use our own storage abstractions to avoid needing to read the whole vector in our runtime logic to simply add a new item to it. - -Fun fact, this optimization actually lead to a 95% performance increase for the `polkadot-sdk` back before Polkadot launched and we were benchmarking it! - -## Your Turn - -Now that you understand the tradeoffs associated with creating redundant storage, let's make a new `StorageMap` called `KittiesOwned` which can help us more easily find what kitties an account is the owner of. - -Then let's update the `mint` function to `append` the kitty's DNA to the `KittiesOwned` vector for the `owner`. +Here you will find the solution for the previous step. diff --git a/steps/31/gitorial_metadata.json b/steps/31/gitorial_metadata.json index f8eb7a05..911c9f5b 100644 --- a/steps/31/gitorial_metadata.json +++ b/steps/31/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: create kitties owned map" + "commitMessage": "solution: generate unique dna" } \ No newline at end of file diff --git a/steps/31/src/impls.rs b/steps/31/src/impls.rs index 71b538b6..470eb783 100644 --- a/steps/31/src/impls.rs +++ b/steps/31/src/impls.rs @@ -25,9 +25,6 @@ impl Pallet { let current_count: u32 = CountForKitties::::get(); let new_count = current_count.checked_add(1).ok_or(Error::::TooManyKitties)?; - - /* 🚧 TODO 🚧: `append` the `dna` to the `KittiesOwned` storage for the `owner`. */ - Kitties::::insert(dna, kitty); CountForKitties::::set(new_count); Self::deposit_event(Event::::Created { owner }); diff --git a/steps/31/src/lib.rs b/steps/31/src/lib.rs index 8b79da7a..7ed39985 100644 --- a/steps/31/src/lib.rs +++ b/steps/31/src/lib.rs @@ -31,12 +31,6 @@ pub mod pallet { #[pallet::storage] pub(super) type Kitties = StorageMap>; - /* 🚧 TODO 🚧: Create a new `StorageMap` called `KittiesOwned`. - - The `Key` of this map is `T::AccountId`. - - The `Value` of this map is `Vec<[u8; 32]>`. - - The `QueryKind` should be set to `ValueQuery`. - */ - #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { diff --git a/steps/32/README.md b/steps/32/README.md index 857d540c..728b6af1 100644 --- a/steps/32/README.md +++ b/steps/32/README.md @@ -1,3 +1,96 @@ -# Solution +# Track Owned Kitties -Here you will find the solution for the previous step. +Now that we can generate unique kitties, we need to consider all the ways we need to store and track those kitties. + +## Redundant Storage + +As a rule, you only want to store data in your blockchain which is necessary for consensus. Blockchains are extremely slow, low powered, and expensive. Blockchains are extremely good at one thing: achieving agreement among a decentralized and untrusted set of individuals. + +When building a blockchain, you need to think about the various constraints: + +- Execution Constraints +- Memory Constraints +- Storage Constraints +- Bandwidth Constrains +- etc... + +In the case of adding redundant storage, all of these constraints come into play! So let's talk about that a bit. + +### Iteration + +It is common when writing code that you might want to perform iteration over items stored in your blockchain. + +In general iteration should be avoided where possible, but if unavoidable it is critical that iteration be bounded in size. + +We literally cannot allow code on our blockchain which would do unbounded iteration, else that would stall our blockchain, which needs to produce a new block on a regular time interval. + +#### Maps + +When you store and iterate over a map, you need to make two considerations: + +1. That the map may not have a bounded upper limit. +2. That each access to the map is very expensive to the blockchain (each is a unique read to the merkle trie). + +If you want to do iteration, probably you do NOT want to use a map for exactly these reasons. + +Maps are great instead for when you need to access or manipulate a single item at a time. + +#### Vec + +When you store and iterate over a vector, the only real consideration you need to have is how large that vector is. + +Accessing large files from the database is going to be slower than accessing small files. + +Once you access the vector, iterating over it and manipulating it is relatively cheap compared to any kind of storage map (but not zero, complexity about vector access still applies). + +If you want to do iteration, you definitely would prefer to use a vector. + +#### Middle Ground + +But sometimes you need to iterate over data, and store a lot of data. This is where we can do a middle ground. + +While it is not great for your Storage Constraints to store redundant data, it can be much better for all your other constraints. + +Let's say we want to answer the question: Give me all the kitties owned by Shawn. + +If all the kitties are stored just in the map, then we would need to iterate over all of them to find which ones are owned by Shawn. + +However, if we ALSO store a vector of kitties owned by Shawn in another storage, yes we would have redundant information in our database, but we will also be able to answer this question much more efficiently. + +A key part of designing your storage is making it efficient for the tasks your code will need to execute. Similarly, you will need to design your code to be efficient for the storage constraints you have. + +Honestly, its a lose / lose situation most times, but it is part of what we need to do when designing blockchain systems. + +## Storage Optimizations + +Storing vectors is a pretty normal part of Pallet development, and there are ways we can optimize adding items to a vector. + +Let's look at a naive way to add a new item to the vector: + +```rust +let mut owned_kitties: Vec<[u8; 32]> = KittiesOwned::::get(owner); +owned_kitties.append(new_kitty); +KittiesOwned::::insert(owner, owned_kitties); +``` + +The first call we need to make is `get` which returns to us all the data in the vector, and all that data is stored in a merkle trie in a database that is really expensive to read from. + +Then we add the item to the vector, and then write the whole new item back into storage. + +But this is way more inefficient than we need! We don't actually need to know what is inside the vector to add a new item to it, we can just say "add this item". + +So we can convert the whole logic to: + +```rust +KittiesOwned::::append(owner, new_kitty); +``` + +In this case, we use our own storage abstractions to avoid needing to read the whole vector in our runtime logic to simply add a new item to it. + +Fun fact, this optimization actually lead to a 95% performance increase for the `polkadot-sdk` back before Polkadot launched and we were benchmarking it! + +## Your Turn + +Now that you understand the tradeoffs associated with creating redundant storage, let's make a new `StorageMap` called `KittiesOwned` which can help us more easily find what kitties an account is the owner of. + +Then let's update the `mint` function to `append` the kitty's DNA to the `KittiesOwned` vector for the `owner`. diff --git a/steps/32/gitorial_metadata.json b/steps/32/gitorial_metadata.json index a9f4dd0e..f8eb7a05 100644 --- a/steps/32/gitorial_metadata.json +++ b/steps/32/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: create kitties owned map" + "commitMessage": "template: create kitties owned map" } \ No newline at end of file diff --git a/steps/32/src/impls.rs b/steps/32/src/impls.rs index b680830e..71b538b6 100644 --- a/steps/32/src/impls.rs +++ b/steps/32/src/impls.rs @@ -26,10 +26,10 @@ impl Pallet { let current_count: u32 = CountForKitties::::get(); let new_count = current_count.checked_add(1).ok_or(Error::::TooManyKitties)?; - KittiesOwned::::append(&owner, dna); + /* 🚧 TODO 🚧: `append` the `dna` to the `KittiesOwned` storage for the `owner`. */ + Kitties::::insert(dna, kitty); CountForKitties::::set(new_count); - Self::deposit_event(Event::::Created { owner }); Ok(()) } diff --git a/steps/32/src/lib.rs b/steps/32/src/lib.rs index aa56e6d3..8b79da7a 100644 --- a/steps/32/src/lib.rs +++ b/steps/32/src/lib.rs @@ -31,10 +31,11 @@ pub mod pallet { #[pallet::storage] pub(super) type Kitties = StorageMap>; - /// Track the kitties owned by each account. - #[pallet::storage] - pub(super) type KittiesOwned = - StorageMap, QueryKind = ValueQuery>; + /* 🚧 TODO 🚧: Create a new `StorageMap` called `KittiesOwned`. + - The `Key` of this map is `T::AccountId`. + - The `Value` of this map is `Vec<[u8; 32]>`. + - The `QueryKind` should be set to `ValueQuery`. + */ #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] diff --git a/steps/33/README.md b/steps/33/README.md index 1b2de11a..857d540c 100644 --- a/steps/33/README.md +++ b/steps/33/README.md @@ -1,69 +1,3 @@ -# Bounded Vectors +# Solution -We placed a vector in storage in the last step. This is okay for initial development, but this is NOT okay for a production Pallet. Instead we need to use objects which have a `MaxEncodedLen`, and for that, we have the `BoundedVec` type. - -## Max Encoded Length - -We mentioned earlier that we require all blockchain storage to have a maximum upper limit to the encoded length of that object. For that, we use the `MaxEncodedLen` trait. - -But what is the `max_encoded_len()` of a `Vec`? - -One answer might be: approximately `T * 2^32`; but this is not a reasonable answer. :) - -In fact, we do not implement `MaxEncodedLen` on `Vec` because the answer is so unreasonable. - -So we need to create a new structure which can act like a `Vec`, but also have reasonable bounds as to how many items are inside of it. - -Hence the `BoundedVec` was born. - -## Construction - -The `BoundedVec` type is a zero-overhead abstraction over the `Vec` type allowing us to control the maximum number of item in the vector. - -To create a new `BoundedVec` with a maximum of 100 `u8`s, you can do the following: - -```rust -let my_bounded_vec = BoundedVec::>::new(); -``` - -The syntax here is very similar to creating a `Vec`, however we include a second generic parameter which tells us the bound. The easiest way to set this bound is using the `ConstU32` type. - -There are other ways to define the bound, and even make it configurable, but that is beyond the scope of this tutorial. Add it to the list of things to follow up on after you have completed this tutorial. - -## Basic APIs - -The `BoundedVec` type has almost all the same APIs as a `Vec`. You can find the full list of APIs in the [`BoundedVec` documentation](https://docs.rs/frame-support/37.0.0/frame_support/struct.BoundedVec.html). - -The main difference is the fact that a `BoundedVec` cannot always accept a new item. - -So rather than having `push`, `append`, `extend`, `insert`, and so on, you have `try_push`, `try_append`, `try_extend`, `try_insert`, etc... - -These functions have the same parameters as their `Vec` equivalent, but can return a `Result` rather than being infallible. - -So converting the logic of a `Vec` to a `BoundedVec` can be as easy as: - -```rust -// Append to a normal vec. -vec.append(item); -// Try append to a bounded vec, handling the error. -bounded_vec.try_append(item).map_err(|_| Error::::TooManyOwned)?; -``` - -## Storage Optimizations - -Just like for `Vec`, our `BoundedVec` also has an optimized `try_append` API for trying to append a new item to the `BoundedVec` without having to read the whole vector in the runtime. - -The change to use this API also looks pretty much the same as above: - -```rust -// Append to a normal vec. -KittiesOwned::::append(item); -// Try append to a bounded vec, handling the error. -KittiesOwned::::try_append(item).map_err(|_| Error::::TooManyOwned)?; -``` - -## Your Turn - -Update the `KittiesOwned` storage map to use `Value = BoundedVec` with up to 100 items. - -You will need to update the logic for the `mint` function to handle the case where we cannot mint a new kitty for an `owner`. For that, we will need to introduce a new error `TooManyOwned`. +Here you will find the solution for the previous step. diff --git a/steps/33/gitorial_metadata.json b/steps/33/gitorial_metadata.json index f2ca41e3..a9f4dd0e 100644 --- a/steps/33/gitorial_metadata.json +++ b/steps/33/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: introduce bounded vec" + "commitMessage": "solution: create kitties owned map" } \ No newline at end of file diff --git a/steps/33/src/impls.rs b/steps/33/src/impls.rs index 9e79118b..b680830e 100644 --- a/steps/33/src/impls.rs +++ b/steps/33/src/impls.rs @@ -26,9 +26,6 @@ impl Pallet { let current_count: u32 = CountForKitties::::get(); let new_count = current_count.checked_add(1).ok_or(Error::::TooManyKitties)?; - /* 🚧 TODO 🚧: - - Update `append` to `try_append` and `map_err` to `Error::::TooManyOwned`. - */ KittiesOwned::::append(&owner, dna); Kitties::::insert(dna, kitty); CountForKitties::::set(new_count); diff --git a/steps/33/src/lib.rs b/steps/33/src/lib.rs index d24ffdce..aa56e6d3 100644 --- a/steps/33/src/lib.rs +++ b/steps/33/src/lib.rs @@ -33,12 +33,8 @@ pub mod pallet { /// Track the kitties owned by each account. #[pallet::storage] - pub(super) type KittiesOwned = StorageMap< - Key = T::AccountId, - /* 🚧 TODO 🚧: Turn this into a `BoundedVec` with a limit of `ConstU32<100>`. */ - Value = Vec<[u8; 32]>, - QueryKind = ValueQuery, - >; + pub(super) type KittiesOwned = + StorageMap, QueryKind = ValueQuery>; #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] @@ -50,7 +46,6 @@ pub mod pallet { pub enum Error { TooManyKitties, DuplicateKitty, - /* 🚧 TODO 🚧: Add a new `Error` named `TooManyOwned` */ } #[pallet::call] diff --git a/steps/34/README.md b/steps/34/README.md index 857d540c..1b2de11a 100644 --- a/steps/34/README.md +++ b/steps/34/README.md @@ -1,3 +1,69 @@ -# Solution +# Bounded Vectors -Here you will find the solution for the previous step. +We placed a vector in storage in the last step. This is okay for initial development, but this is NOT okay for a production Pallet. Instead we need to use objects which have a `MaxEncodedLen`, and for that, we have the `BoundedVec` type. + +## Max Encoded Length + +We mentioned earlier that we require all blockchain storage to have a maximum upper limit to the encoded length of that object. For that, we use the `MaxEncodedLen` trait. + +But what is the `max_encoded_len()` of a `Vec`? + +One answer might be: approximately `T * 2^32`; but this is not a reasonable answer. :) + +In fact, we do not implement `MaxEncodedLen` on `Vec` because the answer is so unreasonable. + +So we need to create a new structure which can act like a `Vec`, but also have reasonable bounds as to how many items are inside of it. + +Hence the `BoundedVec` was born. + +## Construction + +The `BoundedVec` type is a zero-overhead abstraction over the `Vec` type allowing us to control the maximum number of item in the vector. + +To create a new `BoundedVec` with a maximum of 100 `u8`s, you can do the following: + +```rust +let my_bounded_vec = BoundedVec::>::new(); +``` + +The syntax here is very similar to creating a `Vec`, however we include a second generic parameter which tells us the bound. The easiest way to set this bound is using the `ConstU32` type. + +There are other ways to define the bound, and even make it configurable, but that is beyond the scope of this tutorial. Add it to the list of things to follow up on after you have completed this tutorial. + +## Basic APIs + +The `BoundedVec` type has almost all the same APIs as a `Vec`. You can find the full list of APIs in the [`BoundedVec` documentation](https://docs.rs/frame-support/37.0.0/frame_support/struct.BoundedVec.html). + +The main difference is the fact that a `BoundedVec` cannot always accept a new item. + +So rather than having `push`, `append`, `extend`, `insert`, and so on, you have `try_push`, `try_append`, `try_extend`, `try_insert`, etc... + +These functions have the same parameters as their `Vec` equivalent, but can return a `Result` rather than being infallible. + +So converting the logic of a `Vec` to a `BoundedVec` can be as easy as: + +```rust +// Append to a normal vec. +vec.append(item); +// Try append to a bounded vec, handling the error. +bounded_vec.try_append(item).map_err(|_| Error::::TooManyOwned)?; +``` + +## Storage Optimizations + +Just like for `Vec`, our `BoundedVec` also has an optimized `try_append` API for trying to append a new item to the `BoundedVec` without having to read the whole vector in the runtime. + +The change to use this API also looks pretty much the same as above: + +```rust +// Append to a normal vec. +KittiesOwned::::append(item); +// Try append to a bounded vec, handling the error. +KittiesOwned::::try_append(item).map_err(|_| Error::::TooManyOwned)?; +``` + +## Your Turn + +Update the `KittiesOwned` storage map to use `Value = BoundedVec` with up to 100 items. + +You will need to update the logic for the `mint` function to handle the case where we cannot mint a new kitty for an `owner`. For that, we will need to introduce a new error `TooManyOwned`. diff --git a/steps/34/gitorial_metadata.json b/steps/34/gitorial_metadata.json index e2e020bf..f2ca41e3 100644 --- a/steps/34/gitorial_metadata.json +++ b/steps/34/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: introduce bounded vec" + "commitMessage": "template: introduce bounded vec" } \ No newline at end of file diff --git a/steps/34/src/impls.rs b/steps/34/src/impls.rs index e9dcca6b..9e79118b 100644 --- a/steps/34/src/impls.rs +++ b/steps/34/src/impls.rs @@ -3,7 +3,6 @@ use frame::prelude::*; use frame::primitives::BlakeTwo256; use frame::traits::Hash; -// Learn about internal functions. impl Pallet { // Generates and returns DNA and Sex pub fn gen_dna() -> [u8; 32] { @@ -27,7 +26,10 @@ impl Pallet { let current_count: u32 = CountForKitties::::get(); let new_count = current_count.checked_add(1).ok_or(Error::::TooManyKitties)?; - KittiesOwned::::try_append(&owner, dna).map_err(|_| Error::::TooManyOwned)?; + /* 🚧 TODO 🚧: + - Update `append` to `try_append` and `map_err` to `Error::::TooManyOwned`. + */ + KittiesOwned::::append(&owner, dna); Kitties::::insert(dna, kitty); CountForKitties::::set(new_count); diff --git a/steps/34/src/lib.rs b/steps/34/src/lib.rs index 33390653..d24ffdce 100644 --- a/steps/34/src/lib.rs +++ b/steps/34/src/lib.rs @@ -35,7 +35,8 @@ pub mod pallet { #[pallet::storage] pub(super) type KittiesOwned = StorageMap< Key = T::AccountId, - Value = BoundedVec<[u8; 32], ConstU32<100>>, + /* 🚧 TODO 🚧: Turn this into a `BoundedVec` with a limit of `ConstU32<100>`. */ + Value = Vec<[u8; 32]>, QueryKind = ValueQuery, >; @@ -49,7 +50,7 @@ pub mod pallet { pub enum Error { TooManyKitties, DuplicateKitty, - TooManyOwned, + /* 🚧 TODO 🚧: Add a new `Error` named `TooManyOwned` */ } #[pallet::call] diff --git a/steps/35/README.md b/steps/35/README.md index 578035ff..857d540c 100644 --- a/steps/35/README.md +++ b/steps/35/README.md @@ -1,10 +1,3 @@ -# Kitty Marketplace +# Solution -We have completed all the logic needed to create new kitties in our Pallet. - -In this section, we will add logic to our pallet, enabling a marketplace for Kitties. - -You will be able to: - - Transfer kitties. - - Set a price to sell your kitty. - - Buy a kitty that is for sale. +Here you will find the solution for the previous step. diff --git a/steps/35/gitorial_metadata.json b/steps/35/gitorial_metadata.json index 8b9d929e..e2e020bf 100644 --- a/steps/35/gitorial_metadata.json +++ b/steps/35/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "section: kitty marketplace" + "commitMessage": "solution: introduce bounded vec" } \ No newline at end of file diff --git a/steps/36/README.md b/steps/36/README.md index 96ec63e7..578035ff 100644 --- a/steps/36/README.md +++ b/steps/36/README.md @@ -1,31 +1,10 @@ -# Transfer Extrinsic +# Kitty Marketplace -We will build the `transfer` extrinsic over two steps. In this step, we will just step up the skeleton of the extrinsic, the internal function, and the event that will be emitted at the end of the extrinsic. +We have completed all the logic needed to create new kitties in our Pallet. -## Clean Code +In this section, we will add logic to our pallet, enabling a marketplace for Kitties. -It's been a while since we started programming using the initial template provided by this tutorial. - -In that template, we already scaffolded for you the `create_kitty` extrinsic, the `mint` internal function, and the `Created` event. - -In this step, we will be doing the same thing, but for a new extrinsic `transfer`. - -To keep our code clean, we put a minimal amount of logic inside the `transfer` extrinsic, and instead push most of our logic into a `do_transfer` internal function. - -Remember that things which rely on the `#[pallet::*]` macros must be in the same file. - -But if you look closely, all of the "internal" functions like `gen_dna`, `mint`, and soon `do_transfer`, do not depend on the `#[pallet::*]` macros at all! - -So you could actually move all of this logic into its own file, and that would lead to much cleaner code. The same thing can be said for the definition of the `Kitty` struct and any other custom types you might use in your Pallet. - -However, for the purposes of this tutorial, keeping everything in one file makes things a bit easier to teach. - -## Your Turn - -There is nothing in this step that you are not already familiar with. - -Follow the `TODO`s in the template to: - -- Create a `transfer` extrinsic. -- Create a `do_transfer` internal function. -- Create a `Transferred` event. +You will be able to: + - Transfer kitties. + - Set a price to sell your kitty. + - Buy a kitty that is for sale. diff --git a/steps/36/gitorial_metadata.json b/steps/36/gitorial_metadata.json index 5fafb3d0..8b9d929e 100644 --- a/steps/36/gitorial_metadata.json +++ b/steps/36/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: transfer extrinsic" + "commitMessage": "section: kitty marketplace" } \ No newline at end of file diff --git a/steps/36/src/impls.rs b/steps/36/src/impls.rs index 34eae393..e9dcca6b 100644 --- a/steps/36/src/impls.rs +++ b/steps/36/src/impls.rs @@ -34,15 +34,4 @@ impl Pallet { Self::deposit_event(Event::::Created { owner }); Ok(()) } - - /* 🚧 TODO 🚧: Create an internal function called `do_transfer`: - - It has inputs: - - `from` which is `T::AccountId`. - - `to` which is `T::AccountId`. - - `kitty_id` which is `[u8; 32]`. - - It returns a `DispatchResult` - - The inner logic for now is: - - Call `Self::dispatch_event` on and emit `Event:::Transferred` with params. - - Return `Ok(())`. - */ } diff --git a/steps/36/src/lib.rs b/steps/36/src/lib.rs index 8325820c..33390653 100644 --- a/steps/36/src/lib.rs +++ b/steps/36/src/lib.rs @@ -43,12 +43,6 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { Created { owner: T::AccountId }, - /* 🚧 TODO 🚧: Create a new event called `Transferred`: - - Parameters are: - - `from` which is `T::AccountId`. - - `to` which is `T::AccountId`. - - `kitty_id` which is `[u8; 32]`. - */ } #[pallet::error] @@ -66,17 +60,5 @@ pub mod pallet { Self::mint(who, dna)?; Ok(()) } - - /* 🚧 TODO 🚧: Make a new extrinsic called `transfer`. - - Input parameters are: - - `origin` which is `OriginFor`. - - `to` which is `T::AccountId`. - - `kitty_id` which is `[u8; 32]`. - - Returns a `DispatchResult`. - - The inner logic should be: - - Get the caller `who` from `ensure_signed`. - - Call `Self::do_transfer`, and propagate the result. - - End with Ok(()). - */ } } diff --git a/steps/37/README.md b/steps/37/README.md index 857d540c..96ec63e7 100644 --- a/steps/37/README.md +++ b/steps/37/README.md @@ -1,3 +1,31 @@ -# Solution +# Transfer Extrinsic -Here you will find the solution for the previous step. +We will build the `transfer` extrinsic over two steps. In this step, we will just step up the skeleton of the extrinsic, the internal function, and the event that will be emitted at the end of the extrinsic. + +## Clean Code + +It's been a while since we started programming using the initial template provided by this tutorial. + +In that template, we already scaffolded for you the `create_kitty` extrinsic, the `mint` internal function, and the `Created` event. + +In this step, we will be doing the same thing, but for a new extrinsic `transfer`. + +To keep our code clean, we put a minimal amount of logic inside the `transfer` extrinsic, and instead push most of our logic into a `do_transfer` internal function. + +Remember that things which rely on the `#[pallet::*]` macros must be in the same file. + +But if you look closely, all of the "internal" functions like `gen_dna`, `mint`, and soon `do_transfer`, do not depend on the `#[pallet::*]` macros at all! + +So you could actually move all of this logic into its own file, and that would lead to much cleaner code. The same thing can be said for the definition of the `Kitty` struct and any other custom types you might use in your Pallet. + +However, for the purposes of this tutorial, keeping everything in one file makes things a bit easier to teach. + +## Your Turn + +There is nothing in this step that you are not already familiar with. + +Follow the `TODO`s in the template to: + +- Create a `transfer` extrinsic. +- Create a `do_transfer` internal function. +- Create a `Transferred` event. diff --git a/steps/37/gitorial_metadata.json b/steps/37/gitorial_metadata.json index 30147636..5fafb3d0 100644 --- a/steps/37/gitorial_metadata.json +++ b/steps/37/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: transfer extrinsic" + "commitMessage": "template: transfer extrinsic" } \ No newline at end of file diff --git a/steps/37/src/impls.rs b/steps/37/src/impls.rs index 3428acb3..34eae393 100644 --- a/steps/37/src/impls.rs +++ b/steps/37/src/impls.rs @@ -35,8 +35,14 @@ impl Pallet { Ok(()) } - pub fn do_transfer(from: T::AccountId, to: T::AccountId, kitty_id: [u8; 32]) -> DispatchResult { - Self::deposit_event(Event::::Transferred { from, to, kitty_id }); - Ok(()) - } + /* 🚧 TODO 🚧: Create an internal function called `do_transfer`: + - It has inputs: + - `from` which is `T::AccountId`. + - `to` which is `T::AccountId`. + - `kitty_id` which is `[u8; 32]`. + - It returns a `DispatchResult` + - The inner logic for now is: + - Call `Self::dispatch_event` on and emit `Event:::Transferred` with params. + - Return `Ok(())`. + */ } diff --git a/steps/37/src/lib.rs b/steps/37/src/lib.rs index 977f88d8..8325820c 100644 --- a/steps/37/src/lib.rs +++ b/steps/37/src/lib.rs @@ -43,7 +43,12 @@ pub mod pallet { #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { Created { owner: T::AccountId }, - Transferred { from: T::AccountId, to: T::AccountId, kitty_id: [u8; 32] }, + /* 🚧 TODO 🚧: Create a new event called `Transferred`: + - Parameters are: + - `from` which is `T::AccountId`. + - `to` which is `T::AccountId`. + - `kitty_id` which is `[u8; 32]`. + */ } #[pallet::error] @@ -62,14 +67,16 @@ pub mod pallet { Ok(()) } - pub fn transfer( - origin: OriginFor, - to: T::AccountId, - kitty_id: [u8; 32], - ) -> DispatchResult { - let who = ensure_signed(origin)?; - Self::do_transfer(who, to, kitty_id)?; - Ok(()) - } + /* 🚧 TODO 🚧: Make a new extrinsic called `transfer`. + - Input parameters are: + - `origin` which is `OriginFor`. + - `to` which is `T::AccountId`. + - `kitty_id` which is `[u8; 32]`. + - Returns a `DispatchResult`. + - The inner logic should be: + - Get the caller `who` from `ensure_signed`. + - Call `Self::do_transfer`, and propagate the result. + - End with Ok(()). + */ } } diff --git a/steps/38/README.md b/steps/38/README.md index 09214e5f..857d540c 100644 --- a/steps/38/README.md +++ b/steps/38/README.md @@ -1,65 +1,3 @@ -# Transfer Logic +# Solution -Now that we scaffolded the `transfer` extrinsic, we can actually populate the appropriate logic to actually do a transfer. - -## Sanity Checks - -Before we should write any logic which actually transfers a kitty, we should sanity check that all the conditions are met for us to be able to actually execute the transfer. - -### Don't Transfer to Yourself - -The `do_transfer` logic has a `from` and `to` account. If they are the same, well we wouldn't really be doing a transfer. - -As the developer, you can treat this as a `noop`, and return early, or as an error and return an error. In our pallet, we are choosing to emit an error. - -This should be the first check you do because it takes no additional logic to make this check. You already have access to `from` and `to`, so checking equality is about the lightest amount of logic you could do. - -Subsequent sanity checks will require us to read storage, and this is much more expensive to execute. If we can error early and without doing that storage read, that is way better for the blockchain. - -So remember, error early, error fast. - -### Does the Kitty Exist? - -The input to the `transfer` extrinsic allows the sender to submit any `[u8; 32]` identifier to transfer, but we shouldn't assume that kitty actually exists in storage. - -If the sender is trying to send a kitty which doesn't exist, we should emit an error. - -That should be easy to write with something like: - -```rust -let kitty = Kitties::::get(kitty_id).ok_or(Error::::NoKitty)?; -``` - -### Correct Owner? - -This is an important one. - -It could be super simple to really mess up your blockchain if you do not check that the right owner is the one who is actually initiating the transfer. - -Now that we have the `kitty` object, we want to make sure the `from` account matches the `kitty.owner` account, else someone is trying to transfer the kitty who is not allowed to! - -## Updating the Owner - -At this point, we have done all of the sanity checks, and we can actually update the owner of the kitty. Based on our storage, we need to do this in three places: - -- Update the `Kitty` object so that `kitty.owner` is set to `to`. -- Add the `kitty_id` from the vector of `KittiesOwned` for `to`. -- Remove the `kitty_id` from the vector of `KittiesOwned` for `from`. - -This is really an exercise in writing Rust logic and using vector APIs. Unfortunately, we don't have any low level storage optimizations for such tasks, so you really just have to read both vectors and mutate them both. - -There are still optimizations you can make by following the principle of fail early and fail fast. For example, it is probably better to try and add a new item to the `to_owned` bounded vector first to check that their vector isn't full. If it is full, we wouldn't be able to do the transfer anyway, so we could fail early and fast. - -On the other hand, removing an item from a bounded vector can never fail, and since we already checked that `kitty.owner == from`, removing the `kitty_id` from `from_owned` should be infallible, unless there is really a big issue in the pallet logic. So the chances of an error here is much lower. - -## Update Storage - -Now that we have mutated the appropriate storage values, all that is left is to write those updated values back into storage. - -No magic tricks here, just call the `insert` API. - -The most important thing is to not forget to update everything! - -## Your Turn - -Follow the `TODO`s included in the template to flesh out the logic required to complete the `transfer` extrinsic. +Here you will find the solution for the previous step. diff --git a/steps/38/gitorial_metadata.json b/steps/38/gitorial_metadata.json index 1406053b..30147636 100644 --- a/steps/38/gitorial_metadata.json +++ b/steps/38/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: add do transfer logic" + "commitMessage": "solution: transfer extrinsic" } \ No newline at end of file diff --git a/steps/38/src/impls.rs b/steps/38/src/impls.rs index 749b40c3..3428acb3 100644 --- a/steps/38/src/impls.rs +++ b/steps/38/src/impls.rs @@ -36,29 +36,6 @@ impl Pallet { } pub fn do_transfer(from: T::AccountId, to: T::AccountId, kitty_id: [u8; 32]) -> DispatchResult { - /* 🚧 TODO 🚧: Sanity check the transfer is allowed: - - First `ensure!` that `from` and `to` are not equal, else return `Error::::TransferToSelf`. - - Get the `kitty` from `Kitties` using `kitty_id`, else return `Error::::NoKitty`. - - Check the `kitty.owner` is equal to `from`, else return `NotOwner`. - */ - - /* 🚧 TODO 🚧: Update the owner of the kitty: - - Update `kitty.owner` to `to`. - - Update the `KittiesOwned` of `from` and `to: - - Create a mutable `to_owned` by querying `KittiesOwned` for `to`. - - `try_push` the `kitty_id` to the `to_owned` vector. - - If the vector is full, `map_err` and return `Error::::TooManyOwned`. - - Create a mutable `from_owned` by querying `KittiesOwned` for `from`. - - Write logic to `swap_remove` the item from the `from_owned` vector. - - If you cannot find the kitty in the vector, return `Error::::NoKitty`. - */ - - /* 🚧 TODO 🚧: Update the final storage. - - Insert into `Kitties` under `kitty_id` the modified `kitty` struct. - - Insert into `KittiesOwned` under `to` the modified `to_owned` vector. - - Insert into `KittiesOwned` under `from` the modified `from_owned` vector. - */ - Self::deposit_event(Event::::Transferred { from, to, kitty_id }); Ok(()) } diff --git a/steps/38/src/lib.rs b/steps/38/src/lib.rs index 6d3301b0..977f88d8 100644 --- a/steps/38/src/lib.rs +++ b/steps/38/src/lib.rs @@ -51,11 +51,6 @@ pub mod pallet { TooManyKitties, DuplicateKitty, TooManyOwned, - /* 🚧 TODO 🚧: Add new `Error` variants needed for `do_transfer`: - - `TransferToSelf`: for when the `from` and `to` of the transfer is the same. - - `NoKitty`: for when a transfer involves a kitty that does not exist. - - `NotOwner`: for when a transfer is initiated by someone who is not the current owner. - */ } #[pallet::call] diff --git a/steps/39/README.md b/steps/39/README.md index 857d540c..09214e5f 100644 --- a/steps/39/README.md +++ b/steps/39/README.md @@ -1,3 +1,65 @@ -# Solution +# Transfer Logic -Here you will find the solution for the previous step. +Now that we scaffolded the `transfer` extrinsic, we can actually populate the appropriate logic to actually do a transfer. + +## Sanity Checks + +Before we should write any logic which actually transfers a kitty, we should sanity check that all the conditions are met for us to be able to actually execute the transfer. + +### Don't Transfer to Yourself + +The `do_transfer` logic has a `from` and `to` account. If they are the same, well we wouldn't really be doing a transfer. + +As the developer, you can treat this as a `noop`, and return early, or as an error and return an error. In our pallet, we are choosing to emit an error. + +This should be the first check you do because it takes no additional logic to make this check. You already have access to `from` and `to`, so checking equality is about the lightest amount of logic you could do. + +Subsequent sanity checks will require us to read storage, and this is much more expensive to execute. If we can error early and without doing that storage read, that is way better for the blockchain. + +So remember, error early, error fast. + +### Does the Kitty Exist? + +The input to the `transfer` extrinsic allows the sender to submit any `[u8; 32]` identifier to transfer, but we shouldn't assume that kitty actually exists in storage. + +If the sender is trying to send a kitty which doesn't exist, we should emit an error. + +That should be easy to write with something like: + +```rust +let kitty = Kitties::::get(kitty_id).ok_or(Error::::NoKitty)?; +``` + +### Correct Owner? + +This is an important one. + +It could be super simple to really mess up your blockchain if you do not check that the right owner is the one who is actually initiating the transfer. + +Now that we have the `kitty` object, we want to make sure the `from` account matches the `kitty.owner` account, else someone is trying to transfer the kitty who is not allowed to! + +## Updating the Owner + +At this point, we have done all of the sanity checks, and we can actually update the owner of the kitty. Based on our storage, we need to do this in three places: + +- Update the `Kitty` object so that `kitty.owner` is set to `to`. +- Add the `kitty_id` from the vector of `KittiesOwned` for `to`. +- Remove the `kitty_id` from the vector of `KittiesOwned` for `from`. + +This is really an exercise in writing Rust logic and using vector APIs. Unfortunately, we don't have any low level storage optimizations for such tasks, so you really just have to read both vectors and mutate them both. + +There are still optimizations you can make by following the principle of fail early and fail fast. For example, it is probably better to try and add a new item to the `to_owned` bounded vector first to check that their vector isn't full. If it is full, we wouldn't be able to do the transfer anyway, so we could fail early and fast. + +On the other hand, removing an item from a bounded vector can never fail, and since we already checked that `kitty.owner == from`, removing the `kitty_id` from `from_owned` should be infallible, unless there is really a big issue in the pallet logic. So the chances of an error here is much lower. + +## Update Storage + +Now that we have mutated the appropriate storage values, all that is left is to write those updated values back into storage. + +No magic tricks here, just call the `insert` API. + +The most important thing is to not forget to update everything! + +## Your Turn + +Follow the `TODO`s included in the template to flesh out the logic required to complete the `transfer` extrinsic. diff --git a/steps/39/gitorial_metadata.json b/steps/39/gitorial_metadata.json index a7d0c46b..1406053b 100644 --- a/steps/39/gitorial_metadata.json +++ b/steps/39/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: add do transfer logic" + "commitMessage": "template: add do transfer logic" } \ No newline at end of file diff --git a/steps/39/src/impls.rs b/steps/39/src/impls.rs index a638a8c0..749b40c3 100644 --- a/steps/39/src/impls.rs +++ b/steps/39/src/impls.rs @@ -36,23 +36,28 @@ impl Pallet { } pub fn do_transfer(from: T::AccountId, to: T::AccountId, kitty_id: [u8; 32]) -> DispatchResult { - ensure!(from != to, Error::::TransferToSelf); - let mut kitty = Kitties::::get(kitty_id).ok_or(Error::::NoKitty)?; - ensure!(kitty.owner == from, Error::::NotOwner); - kitty.owner = to.clone(); - - let mut to_owned = KittiesOwned::::get(&to); - to_owned.try_push(kitty_id).map_err(|_| Error::::TooManyOwned)?; - let mut from_owned = KittiesOwned::::get(&from); - if let Some(ind) = from_owned.iter().position(|&id| id == kitty_id) { - from_owned.swap_remove(ind); - } else { - return Err(Error::::NoKitty.into()) - } - - Kitties::::insert(kitty_id, kitty); - KittiesOwned::::insert(&to, to_owned); - KittiesOwned::::insert(&from, from_owned); + /* 🚧 TODO 🚧: Sanity check the transfer is allowed: + - First `ensure!` that `from` and `to` are not equal, else return `Error::::TransferToSelf`. + - Get the `kitty` from `Kitties` using `kitty_id`, else return `Error::::NoKitty`. + - Check the `kitty.owner` is equal to `from`, else return `NotOwner`. + */ + + /* 🚧 TODO 🚧: Update the owner of the kitty: + - Update `kitty.owner` to `to`. + - Update the `KittiesOwned` of `from` and `to: + - Create a mutable `to_owned` by querying `KittiesOwned` for `to`. + - `try_push` the `kitty_id` to the `to_owned` vector. + - If the vector is full, `map_err` and return `Error::::TooManyOwned`. + - Create a mutable `from_owned` by querying `KittiesOwned` for `from`. + - Write logic to `swap_remove` the item from the `from_owned` vector. + - If you cannot find the kitty in the vector, return `Error::::NoKitty`. + */ + + /* 🚧 TODO 🚧: Update the final storage. + - Insert into `Kitties` under `kitty_id` the modified `kitty` struct. + - Insert into `KittiesOwned` under `to` the modified `to_owned` vector. + - Insert into `KittiesOwned` under `from` the modified `from_owned` vector. + */ Self::deposit_event(Event::::Transferred { from, to, kitty_id }); Ok(()) diff --git a/steps/39/src/lib.rs b/steps/39/src/lib.rs index dd5161fb..6d3301b0 100644 --- a/steps/39/src/lib.rs +++ b/steps/39/src/lib.rs @@ -51,9 +51,11 @@ pub mod pallet { TooManyKitties, DuplicateKitty, TooManyOwned, - TransferToSelf, - NoKitty, - NotOwner, + /* 🚧 TODO 🚧: Add new `Error` variants needed for `do_transfer`: + - `TransferToSelf`: for when the `from` and `to` of the transfer is the same. + - `NoKitty`: for when a transfer involves a kitty that does not exist. + - `NotOwner`: for when a transfer is initiated by someone who is not the current owner. + */ } #[pallet::call] diff --git a/steps/4/README.md b/steps/4/README.md index 95ef7a44..908016e1 100644 --- a/steps/4/README.md +++ b/steps/4/README.md @@ -1,50 +1,108 @@ -# Pallet Struct +# FRAME Macros -The `Pallet` struct is the anchor on which we implement all logic and traits for our Pallet. +Rust allows you to write [macros](https://doc.rust-lang.org/book/ch19-06-macros.html), which is code that generates code. -```rust -#[pallet::pallet] -pub struct Pallet(core::marker::PhantomData); +FRAME uses Macros to simplify the development of Pallets, while keeping all of the benefits of using Rust. + +You can identify most macros in one of two forms: + +- `#[macro_name]`: Attribute macros, which are applied on top of valid rust syntax. +- `macro_name!(...)`: Declarative macros, which can define their own internal syntax. + +## The Power of Macros + +We can see a direct example of how much smaller we can make a Rust project by using macros to replace boilerplate code: + +- `wc -l` will show the number of lines of a file. +- `cargo expand` will expand the macros to "pure" Rust. + +```sh +➜ substrate git:(master) βœ— wc -l frame/sudo/src/lib.rs + 310 frame/sudo/src/lib.rs + +➜ substrate git:(master) βœ— cargo expand -p pallet-sudo | wc -l + 2210 ``` -## Function Implementations +So this shows that a Pallet written with macros can be 7 times smaller than a Pallet which isn't. + +## The Risk of Macros + +One of the risks of using macros is the creation of "macro magic". This is slang for when macros do so much code generation, that the user is not even sure what is happening. + +Especially with declarative macros, where users can basically create a new programming language within the macros. + +The goal of FRAME macros is to stay as close to Rust as possible, but also remove all the boilerplate code that would otherwise be annoying to write. + +We will call out such cases of macro magic in the next chapters. + +## Macros in Our Template -For example, when you look more at the template, you will see code like: +Our starting template includes all the basic macros used for developing a FRAME pallet. + +### Pallet Macro Entrypoint + +The entrypoint for all the FRAME macros is can be seen here: ```rust -impl Pallet { +#[frame::pallet(dev_mode)] +pub mod pallet { // -- snip -- } ``` -This is just regular Rust and how you would implement functions on a struct. +You will notice we wrap all of our Pallet code inside of this entrypoint, which allows our macros to have context of all the details inside. -## Trait Implementations - -Imagine we had a trait `Hooks` we wanted to implement, we would also use the `Pallet` struct to to that: +More simply explained, if we had: ```rust -impl Hooks for Pallet { - fn on_finalize() { - // -- snip -- - } -} +#[macro_1] +pub struct ItemOne; + +#[macro_2] +pub struct ItemTwo; ``` -And then we could access that those functions like: +There would be no way for `#[macro_1]` and `#[macro_2]` to communicate information to one another. However, with a design like: ```rust -pallet_kitties::Pallet::::on_finalize(); +#[macro_entrypoint] +pub mod pallet { + #[macro_1] + pub struct ItemOne; + + #[macro_2] + pub struct ItemTwo; +} ``` -In fact, many traits are automatically implemented on top of `Pallet` and are accessible thanks to the `#[pallet::pallet]` attribute macro. +We can now design the `#[macro_entrypoint]` to keep track of all data inside of the `mod pallet` container, and that means we can now design `#[macro_1]` and `#[macro_2]` to have context of one another, and interact with each other too. -### FRAME Traits +The unfortunate limitation here is that wherever we want to use FRAME macros, we must basically do it in a single file and all enclosed by the `#[frame::pallet]` macro entrypoint. -You can see all the different traits implemented on `Pallet` by looking at the [autogenerated Rust docs](https://docs.rs/pallet-sudo/latest/pallet_sudo/pallet/struct.Pallet.html#trait-implementations). +We will go over each of the FRAME macros throughout this tutorial -One simple example is the trait [`PalletInfoAccess`](https://docs.rs/frame-support/37.0.0/frame_support/traits/trait.PalletInfoAccess.html). +### Basic Pallet Structure -With this trait, you can do things like call `pallet_kitties::Pallet::::module_name()` which will return to you the name of the rust module, in this case `pallet_kitties`. Information like this is used mostly between other macros, which is why we hide it all from you behind the macros. +While the template is already very minimal, you can mentally break it down like: + +```rust +use frame::prelude::*; +pub use pallet::*; + +#[frame::pallet] +pub mod pallet { + use super::*; + + #[pallet::pallet] + pub struct Pallet(core::marker::PhantomData); + + #[pallet::config] // snip + #[pallet::event] // snip + #[pallet::error] // snip + #[pallet::storage] // snip + #[pallet::call] // snip +} +``` -In this tutorial, you will not interact with any of these automatically generated traits, but knowing that they exist can allow you to investigate further after learning the basics. +Let's explore this further. diff --git a/steps/4/gitorial_metadata.json b/steps/4/gitorial_metadata.json index 1cba1e02..4c7f9c85 100644 --- a/steps/4/gitorial_metadata.json +++ b/steps/4/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "action: learn about pallet struct" + "commitMessage": "action: learn about macros" } \ No newline at end of file diff --git a/steps/4/src/lib.rs b/steps/4/src/lib.rs index 95dc3a4e..8aa7c5b2 100644 --- a/steps/4/src/lib.rs +++ b/steps/4/src/lib.rs @@ -5,11 +5,11 @@ mod impls; use frame::prelude::*; pub use pallet::*; +/* 🚧 TODO 🚧: Learn about macros used in the `polkadot-sdk`, making pallet development easier. */ #[frame::pallet(dev_mode)] pub mod pallet { use super::*; - /* 🚧 TODO 🚧: Learn about the Pallet struct. */ #[pallet::pallet] pub struct Pallet(core::marker::PhantomData); diff --git a/steps/40/README.md b/steps/40/README.md index ef655bbf..857d540c 100644 --- a/steps/40/README.md +++ b/steps/40/README.md @@ -1,118 +1,3 @@ -# Native Balances +# Solution -In our next steps, we will introduce a marketplace for buying and selling kitties. - -For that, we will need to access a user's blockchain balance in addition to the logic in our pallet. - -## The Balances Pallet - -Every blockchain has a cryptocurrency associated with it. Bitcoin has BTC. Ethereum as ETH. - -For Polkadot, that native token is the DOT token. - -Polkadot is built using FRAME and Pallets just like you have been building so far. Included in the `polkadot-sdk` is [`pallet_balances`](https://docs.rs/pallet-balances/38.0.0/pallet_balances/index.html). - -This is a Pallet designed specifically to manage the native balance for users. - -It has the ability to: - -- Mint new tokens. -- Transfer tokens between users. -- Apply freezes and holds for users. -- Slash tokens from accounts. -- and much more... - -Basically everything you could expect to want or need when working with the native balance of a blockchain. - -## Pallet Coupling - -The `polkadot-sdk` is designed to be a flexible and modular blockchain development SDK. - -Part of that flexibility comes through the use of Rust traits to allow two pallets to interact with one another. We call this pallet coupling, and there are two forms of it we will briefly explain next. - -### Tight Coupling - -We have already been using tight coupling throughout this tutorial to give our custom Kitties pallet access to the `frame_system` pallet: - -```rust -#[pallet::config] -pub trait Config: frame_system::Config { - // Through supertraits, we are tightly coupled to `frame_system`. -} -``` - -You can see our Pallet's `Config` is tightly coupled to the `frame_system::Config`. This is why we have been able to use the types coming from `frame_system` (like `T::AccountId`) and why we have been able to use functions directly from `frame_system` (like `frame_system::Pallet::::block_number()`). - -In fact, every Pallet built with FRAME is required to be tightly coupled to `frame_system`. But if we wanted, we could tightly couple to other pallets too! - -```rust -#[pallet::config] -pub trait Config: frame_system::Config + pallet_balances:: Config { - // Here you can see we can also tightly couple to `pallet_balances`. -} -``` - -The upside to tight coupling is gaining direct access to the pallet's Rust module, and all the functions, types, storage, and everything else that is included in that pallet. - -With tight coupling, we are able to access the `pallet_balances` APIs like: - -```rust -let total_issuance = pallet_balances::Pallet::::total_issuance(); -let alice_balance = pallet_balances::Pallet::::total_balance(alice); -pallet_balances::Pallet::::mint_into(alice, amount)?; -pallet_balances::Pallet::::transfer(alice, bob, amount, Preserve)?; -``` - -The downside however, is that you make your pallet very rigid, forcing everyone who wants to use your pallet to use a specific version of `pallet_balances` which you import into your crate. - -### Loose Coupling - -Loose coupling is the more flexible approach to accessing another pallet, and will be our way of integrating the Balances Pallet in our project. - -Loose coupling involves using the interface of a `trait` to access the APIs of another Pallet. - -In the case of accessing the Balances Pallet, it looks exactly like this: - -```rust -#[pallet::config] -pub trait Config: frame_system::Config { - type RuntimeEvent: From> + IsType<::RuntimeEvent>; - - /// Access the balances pallet through the associated type `NativeBalance`. - /// The `NativeBalance` type must implement `Inspect` and `Mutate`. - /// Both of these traits are generic over the `AccountId` type. - type NativeBalance: Inspect + Mutate; -} -``` - -You can see we introduce a new associated type called `NativeBalance`. We then require that this type must implement two traits: - -- [`fungible::Inspect`](https://docs.rs/frame-support/37.0.0/frame_support/traits/tokens/fungible/trait.Inspect.html): A trait allowing us to read data about a fungible token. -- [`fungible::Mutate`](https://docs.rs/frame-support/37.0.0/frame_support/traits/tokens/fungible/trait.Mutate.html): A trait allowing us to write data about a fungible token. - -So with this, we are able to access our native balance using APIs like: - -```rust -// Example APIs coming from `Inspect`. -let total_issuance = T::NativeBalance::total_issuance(); -let alice_balance = T::NativeBalance::total_balance(alice); -// Example APIs coming from `Mutate`. -T::NativeBalance::mint_into(alice, amount)?; -T::NativeBalance::transfer(alice, bob, amount, Preserve)?; -``` - -The key difference here is that we do NOT assume that these APIs must from from specifically `pallet_balances`. If you wanted to use another pallet in the `polkadot-sdk` ecosystem which provides these same functions, you can use it! Our pallet is NOT tightly coupled to which pallet provides access to the `NativeBalance`, it only requires that there is something implementing the `Inspect` and `Mutate` traits. - -The power of loose coupling may not be immediately obvious, but as you get deeper into developing in the Polkadot ecosystem, you will start to realize how powerful this approach can be. - -## Your Turn - -Import the `Inspect` and `Mutate` traits from `frame::traits::fungible`. - -Introduce the `NativeBalance` associated type to your `trait Config` using these traits. - -## Learn More - -To continue learning about Pallet Coupling, check out the following video from the Polkadot Blockchain Academy: - - +Here you will find the solution for the previous step. diff --git a/steps/40/gitorial_metadata.json b/steps/40/gitorial_metadata.json index 0599b5a8..a7d0c46b 100644 --- a/steps/40/gitorial_metadata.json +++ b/steps/40/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: introduce native balances" -} + "commitMessage": "solution: add do transfer logic" +} \ No newline at end of file diff --git a/steps/40/src/lib.rs b/steps/40/src/lib.rs index 629c78da..dd5161fb 100644 --- a/steps/40/src/lib.rs +++ b/steps/40/src/lib.rs @@ -3,8 +3,6 @@ mod impls; use frame::prelude::*; -/* 🚧 TODO 🚧: Import `frame::traits::fungible::Inspect`. */ -/* 🚧 TODO 🚧: Import `frame::traits::fungible::Mutate`. */ pub use pallet::*; #[frame::pallet(dev_mode)] @@ -17,13 +15,6 @@ pub mod pallet { #[pallet::config] pub trait Config: frame_system::Config { type RuntimeEvent: From> + IsType<::RuntimeEvent>; - - /* 🚧 TODO 🚧: - - Create a new associated type named `NativeBalance`. - - Require that `NativeBalance` implements the following traits: - - `Inspect` which is generic over `Self::AccountId`. - - `Mutate` which is also generic over `Self::AccountId`. - */ } #[derive(Encode, Decode, TypeInfo, MaxEncodedLen)] diff --git a/steps/41/README.md b/steps/41/README.md index 99a410dd..ef655bbf 100644 --- a/steps/41/README.md +++ b/steps/41/README.md @@ -10,7 +10,7 @@ Every blockchain has a cryptocurrency associated with it. Bitcoin has BTC. Ether For Polkadot, that native token is the DOT token. -Polkadot is built using FRAME and Pallets just like you have been building so far. Included in the `polkadot-sdk` is `pallet_balances`. +Polkadot is built using FRAME and Pallets just like you have been building so far. Included in the `polkadot-sdk` is [`pallet_balances`](https://docs.rs/pallet-balances/38.0.0/pallet_balances/index.html). This is a Pallet designed specifically to manage the native balance for users. @@ -85,7 +85,7 @@ pub trait Config: frame_system::Config { } ``` -You can see we introduce a new associated type called `NativeBalance`. We then require that this type must implment two traits: +You can see we introduce a new associated type called `NativeBalance`. We then require that this type must implement two traits: - [`fungible::Inspect`](https://docs.rs/frame-support/37.0.0/frame_support/traits/tokens/fungible/trait.Inspect.html): A trait allowing us to read data about a fungible token. - [`fungible::Mutate`](https://docs.rs/frame-support/37.0.0/frame_support/traits/tokens/fungible/trait.Mutate.html): A trait allowing us to write data about a fungible token. diff --git a/steps/41/gitorial_metadata.json b/steps/41/gitorial_metadata.json index 0f853111..0599b5a8 100644 --- a/steps/41/gitorial_metadata.json +++ b/steps/41/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: introduce native balances" + "commitMessage": "template: introduce native balances" } diff --git a/steps/41/src/lib.rs b/steps/41/src/lib.rs index 7305ab62..629c78da 100644 --- a/steps/41/src/lib.rs +++ b/steps/41/src/lib.rs @@ -3,8 +3,8 @@ mod impls; use frame::prelude::*; -use frame::traits::fungible::Inspect; -use frame::traits::fungible::Mutate; +/* 🚧 TODO 🚧: Import `frame::traits::fungible::Inspect`. */ +/* 🚧 TODO 🚧: Import `frame::traits::fungible::Mutate`. */ pub use pallet::*; #[frame::pallet(dev_mode)] @@ -18,8 +18,12 @@ pub mod pallet { pub trait Config: frame_system::Config { type RuntimeEvent: From> + IsType<::RuntimeEvent>; - /// The Fungible handler for the kitties pallet. - type NativeBalance: Inspect + Mutate; + /* 🚧 TODO 🚧: + - Create a new associated type named `NativeBalance`. + - Require that `NativeBalance` implements the following traits: + - `Inspect` which is generic over `Self::AccountId`. + - `Mutate` which is also generic over `Self::AccountId`. + */ } #[derive(Encode, Decode, TypeInfo, MaxEncodedLen)] diff --git a/steps/42/README.md b/steps/42/README.md index dc9f337d..99a410dd 100644 --- a/steps/42/README.md +++ b/steps/42/README.md @@ -1,139 +1,118 @@ -# Native Balance Type +# Native Balances -One of the most challenging parts of using the `polkadot-sdk` is using generic types. +In our next steps, we will introduce a marketplace for buying and selling kitties. -Hopefully, things like `T::AccountId` have been easy enough to use, but using the `Balance` type coming from `NativeBalance` can be a little tricky. +For that, we will need to access a user's blockchain balance in addition to the logic in our pallet. -## Generic Types +## The Balances Pallet -The ability to use generic types in Rust is extremely powerful, but it can be hard to easily understand for those new to the `polkadot-sdk`. Not to mention that `polkadot-sdk` uses a lot of generic types. +Every blockchain has a cryptocurrency associated with it. Bitcoin has BTC. Ethereum as ETH. -The key thing to remember is that all of these generic types eventually become a concrete type. So while we are not sure while we write our pallet if `T::AccountId` is `[u8; 20]`, `[u8; 32]`, or maybe even a `String`, we know that eventually it must be one of these primitive types. +For Polkadot, that native token is the DOT token. -In this situation, the same can be said for the `Balance` type coming from `NativeBalance`. Depending on the configuration of your blockchain, and the required traits that `Balance` needs to satisfy, it is perfectly valid for your `Balance` type to be `u32`, `u64`, or `u128`. +Polkadot is built using FRAME and Pallets just like you have been building so far. Included in the `polkadot-sdk` is `pallet_balances`. -But it can only concretely be one of those, and the weird thing is that we don't know which one it is as we program our Kitties pallet! +This is a Pallet designed specifically to manage the native balance for users. -Let's look at how we would interact with this generic type, and solve many of the issues you might encounter when trying to use it. +It has the ability to: -## Balance Type +- Mint new tokens. +- Transfer tokens between users. +- Apply freezes and holds for users. +- Slash tokens from accounts. +- and much more... -The `Balance` type is ultimately configured inside `pallet_balances`, and remember, we don't have direct access to that pallet because we used loose coupling. +Basically everything you could expect to want or need when working with the native balance of a blockchain. -The way we can access the `Balance` type is through the `Inspect` trait of the `NativeBalance` associated type. Accessing it kind of funny, which is why we commonly introduce a `BalanceOf` alias type like so: +## Pallet Coupling -```rust -// Allows easy access our Pallet's `Balance` type. Comes from `Fungible` interface. -pub type BalanceOf = - <::NativeBalance as Inspect<::AccountId>>::Balance; +The `polkadot-sdk` is designed to be a flexible and modular blockchain development SDK. -``` +Part of that flexibility comes through the use of Rust traits to allow two pallets to interact with one another. We call this pallet coupling, and there are two forms of it we will briefly explain next. -This is kind of a crazy line of code, so let's break it down: - -- At the very end, there is a `Balance` type. This is what we want to access and alias. - ```rust - Balance - ``` -- This `Balance` type is part of the `Inspect` trait. - ```rust - Inspect::Balance - ``` -- The `Inspect` trait is generic over `AccountId`, so we need to include that. - ```rust - Inspect::Balance - ``` -- The `AccountId` type comes from `T`, through `frame_system::Config`, where the type is defined. - ```rust - Inspect<::AccountId>::Balance - ``` -- The `Inspect` is accessible through the `NativeBalance` associated type. - ```rust - ::AccountId>>::Balance - ``` -- The `NativeBalance` type also comes from `T`, but though our pallet's own `Config`. - ```rust - <::NativeBalance as Inspect<::AccountId>>::Balance - ``` -- Finally, we assign this to a new alias `BalanceOf` which is generic over ``. - ```rust - pub type BalanceOf = <::NativeBalance as Inspect<::AccountId>>::Balance - ``` - -Phew! Did you get all that? If not, don't worry too much. You can review these Rust concepts after you complete the tutorial, but there is nothing here which is specific to the `polkadot-sdk`. - -Why do we need this `BalanceOf` alias? - -So that we can change this: +### Tight Coupling + +We have already been using tight coupling throughout this tutorial to give our custom Kitties pallet access to the `frame_system` pallet: ```rust -fn set_price(id: [u8; 32], price: <::NativeBalance as Inspect<::AccountId>>::Balance) { - // -- snip -- +#[pallet::config] +pub trait Config: frame_system::Config { + // Through supertraits, we are tightly coupled to `frame_system`. } ``` -To this: +You can see our Pallet's `Config` is tightly coupled to the `frame_system::Config`. This is why we have been able to use the types coming from `frame_system` (like `T::AccountId`) and why we have been able to use functions directly from `frame_system` (like `frame_system::Pallet::::block_number()`). + +In fact, every Pallet built with FRAME is required to be tightly coupled to `frame_system`. But if we wanted, we could tightly couple to other pallets too! ```rust -fn set_price(id: [u8; 32], price: BalanceOf) { - // -- snip -- +#[pallet::config] +pub trait Config: frame_system::Config + pallet_balances:: Config { + // Here you can see we can also tightly couple to `pallet_balances`. } ``` -The second is way better right? This type alias handles extracting the `Balance` type out of the `NativeBalance` associated type every time, and all we need to do is pass the generic parameter `T`. - -## Basic API - -Let's learn how we can use the `BalanceOf` type in our code. - -### Interacting with Primitive Numbers +The upside to tight coupling is gaining direct access to the pallet's Rust module, and all the functions, types, storage, and everything else that is included in that pallet. -I will repeat again: Because the `BalanceOf` type is generic, we cannot know what underlying type it is. This means we CANNOT write the following: +With tight coupling, we are able to access the `pallet_balances` APIs like: ```rust -// This code doesn't work -fn add_one(input: BalanceOf) -> BalanceOf { - input + 1u128 -} +let total_issuance = pallet_balances::Pallet::::total_issuance(); +let alice_balance = pallet_balances::Pallet::::total_balance(alice); +pallet_balances::Pallet::::mint_into(alice, amount)?; +pallet_balances::Pallet::::transfer(alice, bob, amount, Preserve)?; ``` -Even if we don't include `u128`, we cannot write the line above. This is because that line assumes that `input` must be some specific number type, and in that code, it is simply generic. +The downside however, is that you make your pallet very rigid, forcing everyone who wants to use your pallet to use a specific version of `pallet_balances` which you import into your crate. + +### Loose Coupling -However, `BalanceOf` [does have traits](https://docs.rs/frame-support/37.0.0/frame_support/traits/tokens/trait.Balance.html) that we can use to interact with it. The key one being [`AtLeast32BitUnsigned`](https://docs.rs/polkadot-sdk-frame/0.6.0/polkadot_sdk_frame/arithmetic/trait.AtLeast32BitUnsigned.html). +Loose coupling is the more flexible approach to accessing another pallet, and will be our way of integrating the Balances Pallet in our project. -This means our `BalanceOf` must be an unsigned integer, and must be at least `u32`. So it could be `u32`, `u64`, `u128`, or even bigger if you import other crates with those larger unsigned types. +Loose coupling involves using the interface of a `trait` to access the APIs of another Pallet. -This also means we **would** be able to write the following: +In the case of accessing the Balances Pallet, it looks exactly like this: ```rust -// This code does work -fn add_one(input: BalanceOf) -> BalanceOf { - input + 1u32.into() +#[pallet::config] +pub trait Config: frame_system::Config { + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + + /// Access the balances pallet through the associated type `NativeBalance`. + /// The `NativeBalance` type must implement `Inspect` and `Mutate`. + /// Both of these traits are generic over the `AccountId` type. + type NativeBalance: Inspect + Mutate; } ``` -We can convert any `u32` into the `BalanceOf` type because we know at a minimum `BalanceOf` is `AtLeast32BitUnsigned`. - -### Interacting with Itself +You can see we introduce a new associated type called `NativeBalance`. We then require that this type must implment two traits: -Interacting between two `BalanceOf` types will act just like two normal numbers of the same type. +- [`fungible::Inspect`](https://docs.rs/frame-support/37.0.0/frame_support/traits/tokens/fungible/trait.Inspect.html): A trait allowing us to read data about a fungible token. +- [`fungible::Mutate`](https://docs.rs/frame-support/37.0.0/frame_support/traits/tokens/fungible/trait.Mutate.html): A trait allowing us to write data about a fungible token. -You can add them, subtract them, multiply them, divide them, and even better, do safe math operations on all of them. +So with this, we are able to access our native balance using APIs like: ```rust -let total_balance: BalanceOf = balance_1.checked_add(balance_2).ok_or(ArithmeticError::Overflow)?; +// Example APIs coming from `Inspect`. +let total_issuance = T::NativeBalance::total_issuance(); +let alice_balance = T::NativeBalance::total_balance(alice); +// Example APIs coming from `Mutate`. +T::NativeBalance::mint_into(alice, amount)?; +T::NativeBalance::transfer(alice, bob, amount, Preserve)?; ``` -## Price Field +The key difference here is that we do NOT assume that these APIs must from from specifically `pallet_balances`. If you wanted to use another pallet in the `polkadot-sdk` ecosystem which provides these same functions, you can use it! Our pallet is NOT tightly coupled to which pallet provides access to the `NativeBalance`, it only requires that there is something implementing the `Inspect` and `Mutate` traits. -We are going to use `BalanceOf` in the `Kitty` struct to keep track if it is for sale, and the price the owner wants. - -For this we can use an `Option>`, where `None` denotes that a kitty is not for sale, and `Some(price)` denotes the kitty is for sale at some `price`. +The power of loose coupling may not be immediately obvious, but as you get deeper into developing in the Polkadot ecosystem, you will start to realize how powerful this approach can be. ## Your Turn -Now that you know how to create and use the `BalanceOf` type, add the type alias to your Pallet as shown in the template. +Import the `Inspect` and `Mutate` traits from `frame::traits::fungible`. + +Introduce the `NativeBalance` associated type to your `trait Config` using these traits. + +## Learn More -Then add a new field to the `Kitty` struct called `price`, which is an `Option>`. +To continue learning about Pallet Coupling, check out the following video from the Polkadot Blockchain Academy: -Finally, update the `mint` function to create a new `Kitty` with the new `price` field set as `None`. + diff --git a/steps/42/gitorial_metadata.json b/steps/42/gitorial_metadata.json index 9b842962..0f853111 100644 --- a/steps/42/gitorial_metadata.json +++ b/steps/42/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: introduce balance type and price" + "commitMessage": "solution: introduce native balances" } diff --git a/steps/42/src/impls.rs b/steps/42/src/impls.rs index 6ae2e34b..a638a8c0 100644 --- a/steps/42/src/impls.rs +++ b/steps/42/src/impls.rs @@ -20,7 +20,6 @@ impl Pallet { } pub fn mint(owner: T::AccountId, dna: [u8; 32]) -> DispatchResult { - /* 🚧 TODO 🚧: Add the `price` field set to `None` when initializing the `Kitty` struct. */ let kitty = Kitty { dna, owner: owner.clone() }; // Check if the kitty does not already exist in our storage map ensure!(!Kitties::::contains_key(dna), Error::::DuplicateKitty); diff --git a/steps/42/src/lib.rs b/steps/42/src/lib.rs index efd55a67..7305ab62 100644 --- a/steps/42/src/lib.rs +++ b/steps/42/src/lib.rs @@ -22,21 +22,12 @@ pub mod pallet { type NativeBalance: Inspect + Mutate; } - /* 🚧 TODO 🚧: - - Create a new type alias called `BalanceOf`. - - Extract the `Balance` type from the `NativeBalance` associated type: - - The `Balance` type comes from the `Inspect` trait. - - `Inspect` requires a generic parameter `AccountId` from `T as frame_system::Config`. - - Inspect comes from `NativeBalance`, which comes from `T as Config`. - */ - #[derive(Encode, Decode, TypeInfo, MaxEncodedLen)] #[scale_info(skip_type_params(T))] pub struct Kitty { // Using 32 bytes to represent a kitty DNA pub dna: [u8; 32], pub owner: T::AccountId, - /* 🚧 TODO 🚧: Add a new field `price`, which is an `Option>`. */ } #[pallet::storage] diff --git a/steps/43/README.md b/steps/43/README.md index 857d540c..dc9f337d 100644 --- a/steps/43/README.md +++ b/steps/43/README.md @@ -1,3 +1,139 @@ -# Solution +# Native Balance Type -Here you will find the solution for the previous step. +One of the most challenging parts of using the `polkadot-sdk` is using generic types. + +Hopefully, things like `T::AccountId` have been easy enough to use, but using the `Balance` type coming from `NativeBalance` can be a little tricky. + +## Generic Types + +The ability to use generic types in Rust is extremely powerful, but it can be hard to easily understand for those new to the `polkadot-sdk`. Not to mention that `polkadot-sdk` uses a lot of generic types. + +The key thing to remember is that all of these generic types eventually become a concrete type. So while we are not sure while we write our pallet if `T::AccountId` is `[u8; 20]`, `[u8; 32]`, or maybe even a `String`, we know that eventually it must be one of these primitive types. + +In this situation, the same can be said for the `Balance` type coming from `NativeBalance`. Depending on the configuration of your blockchain, and the required traits that `Balance` needs to satisfy, it is perfectly valid for your `Balance` type to be `u32`, `u64`, or `u128`. + +But it can only concretely be one of those, and the weird thing is that we don't know which one it is as we program our Kitties pallet! + +Let's look at how we would interact with this generic type, and solve many of the issues you might encounter when trying to use it. + +## Balance Type + +The `Balance` type is ultimately configured inside `pallet_balances`, and remember, we don't have direct access to that pallet because we used loose coupling. + +The way we can access the `Balance` type is through the `Inspect` trait of the `NativeBalance` associated type. Accessing it kind of funny, which is why we commonly introduce a `BalanceOf` alias type like so: + +```rust +// Allows easy access our Pallet's `Balance` type. Comes from `Fungible` interface. +pub type BalanceOf = + <::NativeBalance as Inspect<::AccountId>>::Balance; + +``` + +This is kind of a crazy line of code, so let's break it down: + +- At the very end, there is a `Balance` type. This is what we want to access and alias. + ```rust + Balance + ``` +- This `Balance` type is part of the `Inspect` trait. + ```rust + Inspect::Balance + ``` +- The `Inspect` trait is generic over `AccountId`, so we need to include that. + ```rust + Inspect::Balance + ``` +- The `AccountId` type comes from `T`, through `frame_system::Config`, where the type is defined. + ```rust + Inspect<::AccountId>::Balance + ``` +- The `Inspect` is accessible through the `NativeBalance` associated type. + ```rust + ::AccountId>>::Balance + ``` +- The `NativeBalance` type also comes from `T`, but though our pallet's own `Config`. + ```rust + <::NativeBalance as Inspect<::AccountId>>::Balance + ``` +- Finally, we assign this to a new alias `BalanceOf` which is generic over ``. + ```rust + pub type BalanceOf = <::NativeBalance as Inspect<::AccountId>>::Balance + ``` + +Phew! Did you get all that? If not, don't worry too much. You can review these Rust concepts after you complete the tutorial, but there is nothing here which is specific to the `polkadot-sdk`. + +Why do we need this `BalanceOf` alias? + +So that we can change this: + +```rust +fn set_price(id: [u8; 32], price: <::NativeBalance as Inspect<::AccountId>>::Balance) { + // -- snip -- +} +``` + +To this: + +```rust +fn set_price(id: [u8; 32], price: BalanceOf) { + // -- snip -- +} +``` + +The second is way better right? This type alias handles extracting the `Balance` type out of the `NativeBalance` associated type every time, and all we need to do is pass the generic parameter `T`. + +## Basic API + +Let's learn how we can use the `BalanceOf` type in our code. + +### Interacting with Primitive Numbers + +I will repeat again: Because the `BalanceOf` type is generic, we cannot know what underlying type it is. This means we CANNOT write the following: + +```rust +// This code doesn't work +fn add_one(input: BalanceOf) -> BalanceOf { + input + 1u128 +} +``` + +Even if we don't include `u128`, we cannot write the line above. This is because that line assumes that `input` must be some specific number type, and in that code, it is simply generic. + +However, `BalanceOf` [does have traits](https://docs.rs/frame-support/37.0.0/frame_support/traits/tokens/trait.Balance.html) that we can use to interact with it. The key one being [`AtLeast32BitUnsigned`](https://docs.rs/polkadot-sdk-frame/0.6.0/polkadot_sdk_frame/arithmetic/trait.AtLeast32BitUnsigned.html). + +This means our `BalanceOf` must be an unsigned integer, and must be at least `u32`. So it could be `u32`, `u64`, `u128`, or even bigger if you import other crates with those larger unsigned types. + +This also means we **would** be able to write the following: + +```rust +// This code does work +fn add_one(input: BalanceOf) -> BalanceOf { + input + 1u32.into() +} +``` + +We can convert any `u32` into the `BalanceOf` type because we know at a minimum `BalanceOf` is `AtLeast32BitUnsigned`. + +### Interacting with Itself + +Interacting between two `BalanceOf` types will act just like two normal numbers of the same type. + +You can add them, subtract them, multiply them, divide them, and even better, do safe math operations on all of them. + +```rust +let total_balance: BalanceOf = balance_1.checked_add(balance_2).ok_or(ArithmeticError::Overflow)?; +``` + +## Price Field + +We are going to use `BalanceOf` in the `Kitty` struct to keep track if it is for sale, and the price the owner wants. + +For this we can use an `Option>`, where `None` denotes that a kitty is not for sale, and `Some(price)` denotes the kitty is for sale at some `price`. + +## Your Turn + +Now that you know how to create and use the `BalanceOf` type, add the type alias to your Pallet as shown in the template. + +Then add a new field to the `Kitty` struct called `price`, which is an `Option>`. + +Finally, update the `mint` function to create a new `Kitty` with the new `price` field set as `None`. diff --git a/steps/43/gitorial_metadata.json b/steps/43/gitorial_metadata.json index b427de0a..9b842962 100644 --- a/steps/43/gitorial_metadata.json +++ b/steps/43/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: introduce balance type and price" + "commitMessage": "template: introduce balance type and price" } diff --git a/steps/43/src/impls.rs b/steps/43/src/impls.rs index 5ec04ae9..6ae2e34b 100644 --- a/steps/43/src/impls.rs +++ b/steps/43/src/impls.rs @@ -20,7 +20,8 @@ impl Pallet { } pub fn mint(owner: T::AccountId, dna: [u8; 32]) -> DispatchResult { - let kitty = Kitty { dna, owner: owner.clone(), price: None }; + /* 🚧 TODO 🚧: Add the `price` field set to `None` when initializing the `Kitty` struct. */ + let kitty = Kitty { dna, owner: owner.clone() }; // Check if the kitty does not already exist in our storage map ensure!(!Kitties::::contains_key(dna), Error::::DuplicateKitty); diff --git a/steps/43/src/lib.rs b/steps/43/src/lib.rs index f2625a63..efd55a67 100644 --- a/steps/43/src/lib.rs +++ b/steps/43/src/lib.rs @@ -22,9 +22,13 @@ pub mod pallet { type NativeBalance: Inspect + Mutate; } - // Allows easy access our Pallet's `Balance` type. Comes from `Fungible` interface. - pub type BalanceOf = - <::NativeBalance as Inspect<::AccountId>>::Balance; + /* 🚧 TODO 🚧: + - Create a new type alias called `BalanceOf`. + - Extract the `Balance` type from the `NativeBalance` associated type: + - The `Balance` type comes from the `Inspect` trait. + - `Inspect` requires a generic parameter `AccountId` from `T as frame_system::Config`. + - Inspect comes from `NativeBalance`, which comes from `T as Config`. + */ #[derive(Encode, Decode, TypeInfo, MaxEncodedLen)] #[scale_info(skip_type_params(T))] @@ -32,7 +36,7 @@ pub mod pallet { // Using 32 bytes to represent a kitty DNA pub dna: [u8; 32], pub owner: T::AccountId, - pub price: Option>, + /* 🚧 TODO 🚧: Add a new field `price`, which is an `Option>`. */ } #[pallet::storage] diff --git a/steps/44/README.md b/steps/44/README.md index fa2d028c..857d540c 100644 --- a/steps/44/README.md +++ b/steps/44/README.md @@ -1,23 +1,3 @@ -# Set Price Extrinsic +# Solution -Now that we our Pallet set up to handle balances, let's actually use them. - -In this step, we will create an extrinsic which allows the owner of a kitty to set a price for the kitty. - -## Set Price - -The set price extrinsic is pretty straight forward. - -As we noted in the last step, we allow the `price` field of a kitty to be `Option>`, where `None` denotes a kitty which is not for sale, and `Some(price)` denotes a kitty which is for sale at some `price`. - -With this in mind, our `set_price` extrinsic will also accept an `Option>` so that a user can put the kitty on or off the market. - -## Your Turn - -In this step, you will scaffold the extrinsic and internal functions for `set_price`. - -- Create a new event `PriceSet` with the fields noted in the template. -- Create a new extrinsic `set_price` with the params noted in the template. -- Create a new internal function `do_set_price` which simply deposits the `PriceSet` event. - -We will actually populate the logic for `do_set_price` in the next step. +Here you will find the solution for the previous step. diff --git a/steps/44/gitorial_metadata.json b/steps/44/gitorial_metadata.json index 92143046..b427de0a 100644 --- a/steps/44/gitorial_metadata.json +++ b/steps/44/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: create set price extrinsic" -} \ No newline at end of file + "commitMessage": "solution: introduce balance type and price" +} diff --git a/steps/44/src/impls.rs b/steps/44/src/impls.rs index 686cb0ab..5ec04ae9 100644 --- a/steps/44/src/impls.rs +++ b/steps/44/src/impls.rs @@ -57,15 +57,4 @@ impl Pallet { Self::deposit_event(Event::::Transferred { from, to, kitty_id }); Ok(()) } - - /* 🚧 TODO 🚧: Make an internal function called `do_set_price`: - - Inputs to the function are: - - `caller` which is `T::AccountId`. - - `kitty_id` which is `[u8; 32]`. - - `new_price` which is `Option`. - - Returns a `DispatchResult`. - - The internal logic, for now, should be: - - `Self::deposit_event` for `Event::::PriceSet` with the appropriate params. - - Return `Ok(())`. - */ } diff --git a/steps/44/src/lib.rs b/steps/44/src/lib.rs index 53bb1ecb..f2625a63 100644 --- a/steps/44/src/lib.rs +++ b/steps/44/src/lib.rs @@ -54,11 +54,6 @@ pub mod pallet { pub enum Event { Created { owner: T::AccountId }, Transferred { from: T::AccountId, to: T::AccountId, kitty_id: [u8; 32] }, - /* 🚧 TODO 🚧: Create a new `Event` called `PriceSet` with fields: - - `owner` which is `T::AccountId`. - - `kitty_id` which is `[u8; 32]`. - - `new_price` which is `Option>`. - */ } #[pallet::error] @@ -89,17 +84,5 @@ pub mod pallet { Self::do_transfer(who, to, kitty_id)?; Ok(()) } - - /* 🚧 TODO 🚧: Make an callable function called `set_price`: - - Inputs to the function are: - - `origin` which is `OriginFor`. - - `kitty_id` which is `[u8; 32]`. - - `new_price` which is `Option`. - - Returns a `DispatchResult` - - The internal logic, for now, should be: - - Extract the caller `who` with `ensure_signed`. - - Call `Self::do_set_price` with the appropriate parameters, propagating the result. - - Return `Ok(())`. - */ } } diff --git a/steps/45/README.md b/steps/45/README.md index 857d540c..fa2d028c 100644 --- a/steps/45/README.md +++ b/steps/45/README.md @@ -1,3 +1,23 @@ -# Solution +# Set Price Extrinsic -Here you will find the solution for the previous step. +Now that we our Pallet set up to handle balances, let's actually use them. + +In this step, we will create an extrinsic which allows the owner of a kitty to set a price for the kitty. + +## Set Price + +The set price extrinsic is pretty straight forward. + +As we noted in the last step, we allow the `price` field of a kitty to be `Option>`, where `None` denotes a kitty which is not for sale, and `Some(price)` denotes a kitty which is for sale at some `price`. + +With this in mind, our `set_price` extrinsic will also accept an `Option>` so that a user can put the kitty on or off the market. + +## Your Turn + +In this step, you will scaffold the extrinsic and internal functions for `set_price`. + +- Create a new event `PriceSet` with the fields noted in the template. +- Create a new extrinsic `set_price` with the params noted in the template. +- Create a new internal function `do_set_price` which simply deposits the `PriceSet` event. + +We will actually populate the logic for `do_set_price` in the next step. diff --git a/steps/45/gitorial_metadata.json b/steps/45/gitorial_metadata.json index 075d7582..92143046 100644 --- a/steps/45/gitorial_metadata.json +++ b/steps/45/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: create set price extrinsic" + "commitMessage": "template: create set price extrinsic" } \ No newline at end of file diff --git a/steps/45/src/impls.rs b/steps/45/src/impls.rs index f1e996c7..686cb0ab 100644 --- a/steps/45/src/impls.rs +++ b/steps/45/src/impls.rs @@ -58,12 +58,14 @@ impl Pallet { Ok(()) } - pub fn do_set_price( - caller: T::AccountId, - kitty_id: [u8; 32], - new_price: Option>, - ) -> DispatchResult { - Self::deposit_event(Event::::PriceSet { owner: caller, kitty_id, new_price }); - Ok(()) - } + /* 🚧 TODO 🚧: Make an internal function called `do_set_price`: + - Inputs to the function are: + - `caller` which is `T::AccountId`. + - `kitty_id` which is `[u8; 32]`. + - `new_price` which is `Option`. + - Returns a `DispatchResult`. + - The internal logic, for now, should be: + - `Self::deposit_event` for `Event::::PriceSet` with the appropriate params. + - Return `Ok(())`. + */ } diff --git a/steps/45/src/lib.rs b/steps/45/src/lib.rs index 1cbcf946..53bb1ecb 100644 --- a/steps/45/src/lib.rs +++ b/steps/45/src/lib.rs @@ -54,7 +54,11 @@ pub mod pallet { pub enum Event { Created { owner: T::AccountId }, Transferred { from: T::AccountId, to: T::AccountId, kitty_id: [u8; 32] }, - PriceSet { owner: T::AccountId, kitty_id: [u8; 32], new_price: Option> }, + /* 🚧 TODO 🚧: Create a new `Event` called `PriceSet` with fields: + - `owner` which is `T::AccountId`. + - `kitty_id` which is `[u8; 32]`. + - `new_price` which is `Option>`. + */ } #[pallet::error] @@ -86,14 +90,16 @@ pub mod pallet { Ok(()) } - pub fn set_price( - origin: OriginFor, - kitty_id: [u8; 32], - new_price: Option>, - ) -> DispatchResult { - let who = ensure_signed(origin)?; - Self::do_set_price(who, kitty_id, new_price)?; - Ok(()) - } + /* 🚧 TODO 🚧: Make an callable function called `set_price`: + - Inputs to the function are: + - `origin` which is `OriginFor`. + - `kitty_id` which is `[u8; 32]`. + - `new_price` which is `Option`. + - Returns a `DispatchResult` + - The internal logic, for now, should be: + - Extract the caller `who` with `ensure_signed`. + - Call `Self::do_set_price` with the appropriate parameters, propagating the result. + - Return `Ok(())`. + */ } } diff --git a/steps/46/README.md b/steps/46/README.md index 68d1d6d2..857d540c 100644 --- a/steps/46/README.md +++ b/steps/46/README.md @@ -1,11 +1,3 @@ -# Set Price Logic +# Solution -The set price logic is very straight forward. - -The only thing we really need to check is that the `kitty.owner` matches the `caller` of the function. - -Besides that, we simply need to update the `kitty.price` field, and write that back to the runtime storage. - -## Your Turn - -Follow the `TODO`s listed in the template, and complete the logic for the `do_set_price` function. +Here you will find the solution for the previous step. diff --git a/steps/46/gitorial_metadata.json b/steps/46/gitorial_metadata.json index 9ee539c3..075d7582 100644 --- a/steps/46/gitorial_metadata.json +++ b/steps/46/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: logic for set price" + "commitMessage": "solution: create set price extrinsic" } \ No newline at end of file diff --git a/steps/46/src/impls.rs b/steps/46/src/impls.rs index 4cbc8abc..f1e996c7 100644 --- a/steps/46/src/impls.rs +++ b/steps/46/src/impls.rs @@ -63,14 +63,6 @@ impl Pallet { kitty_id: [u8; 32], new_price: Option>, ) -> DispatchResult { - /* 🚧 TODO 🚧: Create the logic for setting the Kitty price: - - Create a mutable `kitty` by calling `get` on `Kitties` with `kitty_id`. - - Return an error if the kitty doesn't exist by returning `Error::::NoKitty`. - - `ensure!` that the `kitty.owner` is equal to the `caller` else return `Error::::NotOwner`. - - Set the `kitty.price` to `new_price`. - - Insert the modified `kitty` back into the `Kitties` map under `kitty_id`. - */ - Self::deposit_event(Event::::PriceSet { owner: caller, kitty_id, new_price }); Ok(()) } diff --git a/steps/47/README.md b/steps/47/README.md index 857d540c..68d1d6d2 100644 --- a/steps/47/README.md +++ b/steps/47/README.md @@ -1,3 +1,11 @@ -# Solution +# Set Price Logic -Here you will find the solution for the previous step. +The set price logic is very straight forward. + +The only thing we really need to check is that the `kitty.owner` matches the `caller` of the function. + +Besides that, we simply need to update the `kitty.price` field, and write that back to the runtime storage. + +## Your Turn + +Follow the `TODO`s listed in the template, and complete the logic for the `do_set_price` function. diff --git a/steps/47/gitorial_metadata.json b/steps/47/gitorial_metadata.json index b18a7246..9ee539c3 100644 --- a/steps/47/gitorial_metadata.json +++ b/steps/47/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: logic for set price" + "commitMessage": "template: logic for set price" } \ No newline at end of file diff --git a/steps/47/src/impls.rs b/steps/47/src/impls.rs index d6c9f188..4cbc8abc 100644 --- a/steps/47/src/impls.rs +++ b/steps/47/src/impls.rs @@ -63,10 +63,13 @@ impl Pallet { kitty_id: [u8; 32], new_price: Option>, ) -> DispatchResult { - let mut kitty = Kitties::::get(kitty_id).ok_or(Error::::NoKitty)?; - ensure!(kitty.owner == caller, Error::::NotOwner); - kitty.price = new_price; - Kitties::::insert(kitty_id, kitty); + /* 🚧 TODO 🚧: Create the logic for setting the Kitty price: + - Create a mutable `kitty` by calling `get` on `Kitties` with `kitty_id`. + - Return an error if the kitty doesn't exist by returning `Error::::NoKitty`. + - `ensure!` that the `kitty.owner` is equal to the `caller` else return `Error::::NotOwner`. + - Set the `kitty.price` to `new_price`. + - Insert the modified `kitty` back into the `Kitties` map under `kitty_id`. + */ Self::deposit_event(Event::::PriceSet { owner: caller, kitty_id, new_price }); Ok(()) diff --git a/steps/48/README.md b/steps/48/README.md index 60cbe37f..857d540c 100644 --- a/steps/48/README.md +++ b/steps/48/README.md @@ -1,39 +1,3 @@ -# Buy Kitty Extrinsic +# Solution -Now that kitties can have a price, we want to enable them to be purchaseable. - -For that, we will create the `buy_kitty` extrinsic. - -## Max Price - -You will notice in our scaffolding, one of the parameters of our `buy_kitty` extrinsic is `max_price: BalanceOf`. - -This allows the buyer to set the maximum price they are willing to spend to buy a specific kitty. - -But this is a little strange right? The kitty already has a price set on it. Why would we need the buyer to also send us a price? - -Well, without this `max_price` parameter, you open users of your pallet to a nasty attack! - -Remember that transactions on a blockchain are bundled into a block and executed one by one. - -Also remember that the order of transactions in the block is up for interpretation by the block producer! - -Imagine there is a kitty, and its price is set to 10 DOT. Then someone goes and submits `buy_kitty` without there being a `max_price` parameter. - -What can happen is that the kitty owner could see that transaction in the transaction pool, before the transaction is included in the block, then submit their own high priority transaction (usually by increasing the fees they pay), which raises the price of the kitty. - -Do you see the problem now? - -Basically without the `max_price` parameter, your pallet will become a honeypot for attackers to trick users into sending them their whole balance. - -The `max_price` parameter ensures the buyer and seller have reached an agreement on price, and that any changes to the agreement would not be executed. - -## Your Turn - -Hopefully you can see some of the ways that programming for a blockchain is different than what you might expect. Remember that blockchain systems need to be resilient to malicious individuals. Because it is a public and open system, we cannot make any assumptions about the behaviors of our users. We can only influence those behaviors through the rules of our state transition function. - -In this step, we again will just scaffold what we need for the `buy_kitty` extrinsic. - -- Create a new event `Sold` with the fields noted in the template. -- Create a new extrinsic `buy_kitty` with the params noted in the template. -- Create a new internal function `do_buy_kitty` which simply deposits the `Sold` event. +Here you will find the solution for the previous step. diff --git a/steps/48/gitorial_metadata.json b/steps/48/gitorial_metadata.json index b907179e..b18a7246 100644 --- a/steps/48/gitorial_metadata.json +++ b/steps/48/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: add buy kitty extrinsic" + "commitMessage": "solution: logic for set price" } \ No newline at end of file diff --git a/steps/48/src/impls.rs b/steps/48/src/impls.rs index 9fec611b..d6c9f188 100644 --- a/steps/48/src/impls.rs +++ b/steps/48/src/impls.rs @@ -71,15 +71,4 @@ impl Pallet { Self::deposit_event(Event::::PriceSet { owner: caller, kitty_id, new_price }); Ok(()) } - - /* 🚧 TODO 🚧: Create a new internal function `do_buy_kitty`: - - Inputs to the function are: - - `buyer` which is `T::AccountId`. - - `kitty_id` which is `[u8; 32]`. - - `price` which is `BalanceOf`. - - It returns `DispatchResult`. - - The internal logic, for now, should be: - - `Self::deposit_event` with `Event::::Sold` and the appropriate params. - - Return `Ok(())`. - */ } diff --git a/steps/48/src/lib.rs b/steps/48/src/lib.rs index aafed139..1cbcf946 100644 --- a/steps/48/src/lib.rs +++ b/steps/48/src/lib.rs @@ -55,11 +55,6 @@ pub mod pallet { Created { owner: T::AccountId }, Transferred { from: T::AccountId, to: T::AccountId, kitty_id: [u8; 32] }, PriceSet { owner: T::AccountId, kitty_id: [u8; 32], new_price: Option> }, - /* 🚧 TODO 🚧: Create a new `Event` called `Sold` with the following parameters: - - `buyer` which is `T::AccountId`. - - `kitty_id` which is `[u8; 32]`. - - `price` which is `BalanceOf`. - */ } #[pallet::error] @@ -100,17 +95,5 @@ pub mod pallet { Self::do_set_price(who, kitty_id, new_price)?; Ok(()) } - - /* 🚧 TODO 🚧: Create a new callable function `buy_kitty`: - - Inputs to the function are: - - `origin` which is `OriginFor`. - - `kitty_id` which is `[u8; 32]`. - - `max_price` which is `BalanceOf`. - - It returns `DispatchResult`. - - The internal logic should be: - - Extract `who` using `ensure_signed` on `origin`. - - Call `Self::do_buy_kitty` using appropriate params, and propagating the result. - - Return `Ok(())`. - */ } } diff --git a/steps/49/README.md b/steps/49/README.md index 857d540c..60cbe37f 100644 --- a/steps/49/README.md +++ b/steps/49/README.md @@ -1,3 +1,39 @@ -# Solution +# Buy Kitty Extrinsic -Here you will find the solution for the previous step. +Now that kitties can have a price, we want to enable them to be purchaseable. + +For that, we will create the `buy_kitty` extrinsic. + +## Max Price + +You will notice in our scaffolding, one of the parameters of our `buy_kitty` extrinsic is `max_price: BalanceOf`. + +This allows the buyer to set the maximum price they are willing to spend to buy a specific kitty. + +But this is a little strange right? The kitty already has a price set on it. Why would we need the buyer to also send us a price? + +Well, without this `max_price` parameter, you open users of your pallet to a nasty attack! + +Remember that transactions on a blockchain are bundled into a block and executed one by one. + +Also remember that the order of transactions in the block is up for interpretation by the block producer! + +Imagine there is a kitty, and its price is set to 10 DOT. Then someone goes and submits `buy_kitty` without there being a `max_price` parameter. + +What can happen is that the kitty owner could see that transaction in the transaction pool, before the transaction is included in the block, then submit their own high priority transaction (usually by increasing the fees they pay), which raises the price of the kitty. + +Do you see the problem now? + +Basically without the `max_price` parameter, your pallet will become a honeypot for attackers to trick users into sending them their whole balance. + +The `max_price` parameter ensures the buyer and seller have reached an agreement on price, and that any changes to the agreement would not be executed. + +## Your Turn + +Hopefully you can see some of the ways that programming for a blockchain is different than what you might expect. Remember that blockchain systems need to be resilient to malicious individuals. Because it is a public and open system, we cannot make any assumptions about the behaviors of our users. We can only influence those behaviors through the rules of our state transition function. + +In this step, we again will just scaffold what we need for the `buy_kitty` extrinsic. + +- Create a new event `Sold` with the fields noted in the template. +- Create a new extrinsic `buy_kitty` with the params noted in the template. +- Create a new internal function `do_buy_kitty` which simply deposits the `Sold` event. diff --git a/steps/49/gitorial_metadata.json b/steps/49/gitorial_metadata.json index 9db04de6..b907179e 100644 --- a/steps/49/gitorial_metadata.json +++ b/steps/49/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: add buy kitty extrinsic" + "commitMessage": "template: add buy kitty extrinsic" } \ No newline at end of file diff --git a/steps/49/src/impls.rs b/steps/49/src/impls.rs index 889e7a2e..9fec611b 100644 --- a/steps/49/src/impls.rs +++ b/steps/49/src/impls.rs @@ -72,12 +72,14 @@ impl Pallet { Ok(()) } - pub fn do_buy_kitty( - buyer: T::AccountId, - kitty_id: [u8; 32], - price: BalanceOf, - ) -> DispatchResult { - Self::deposit_event(Event::::Sold { buyer, kitty_id, price }); - Ok(()) - } + /* 🚧 TODO 🚧: Create a new internal function `do_buy_kitty`: + - Inputs to the function are: + - `buyer` which is `T::AccountId`. + - `kitty_id` which is `[u8; 32]`. + - `price` which is `BalanceOf`. + - It returns `DispatchResult`. + - The internal logic, for now, should be: + - `Self::deposit_event` with `Event::::Sold` and the appropriate params. + - Return `Ok(())`. + */ } diff --git a/steps/49/src/lib.rs b/steps/49/src/lib.rs index 93c74219..aafed139 100644 --- a/steps/49/src/lib.rs +++ b/steps/49/src/lib.rs @@ -55,7 +55,11 @@ pub mod pallet { Created { owner: T::AccountId }, Transferred { from: T::AccountId, to: T::AccountId, kitty_id: [u8; 32] }, PriceSet { owner: T::AccountId, kitty_id: [u8; 32], new_price: Option> }, - Sold { buyer: T::AccountId, kitty_id: [u8; 32], price: BalanceOf }, + /* 🚧 TODO 🚧: Create a new `Event` called `Sold` with the following parameters: + - `buyer` which is `T::AccountId`. + - `kitty_id` which is `[u8; 32]`. + - `price` which is `BalanceOf`. + */ } #[pallet::error] @@ -97,14 +101,16 @@ pub mod pallet { Ok(()) } - pub fn buy_kitty( - origin: OriginFor, - kitty_id: [u8; 32], - max_price: BalanceOf, - ) -> DispatchResult { - let who = ensure_signed(origin)?; - Self::do_buy_kitty(who, kitty_id, max_price)?; - Ok(()) - } + /* 🚧 TODO 🚧: Create a new callable function `buy_kitty`: + - Inputs to the function are: + - `origin` which is `OriginFor`. + - `kitty_id` which is `[u8; 32]`. + - `max_price` which is `BalanceOf`. + - It returns `DispatchResult`. + - The internal logic should be: + - Extract `who` using `ensure_signed` on `origin`. + - Call `Self::do_buy_kitty` using appropriate params, and propagating the result. + - Return `Ok(())`. + */ } } diff --git a/steps/5/README.md b/steps/5/README.md index f4854d4b..95ef7a44 100644 --- a/steps/5/README.md +++ b/steps/5/README.md @@ -1,79 +1,50 @@ -# Pallet Functions +# Pallet Struct -As noted earlier, functions are easily implemented directly on top of the `Pallet` struct. +The `Pallet` struct is the anchor on which we implement all logic and traits for our Pallet. -However, there are two types of functions exposed by Pallets: - -1. Internal Functions -2. Callable Functions - -Let's learn more about the differences. +```rust +#[pallet::pallet] +pub struct Pallet(core::marker::PhantomData); +``` -## Internal Functions +## Function Implementations -Internal Pallet functions are just normal Rust functions. These are defined with regular Rust syntax and without any of the Pallet macros. +For example, when you look more at the template, you will see code like: ```rust impl Pallet { - // None of the functions in this `impl` are callable by users. + // -- snip -- } ``` -They behave just like any Rust function from any Rust module. If they are marked `pub` they are exposed to other Rust modules, if not they are totally private. - -What is most important is that no matter how these functions are marked, none of these functions are callable from outside of the blockchain, which means they are not exposed to users. +This is just regular Rust and how you would implement functions on a struct. -For that, we have Callable Functions. +## Trait Implementations -## Callable Functions - -If you are familiar with smart contracts or any kind of blockchain application, you would know that the way users interact with the blockchain is through transactions. - -Those transactions are processed, and then dispatched to callable functions within the blockchain. - -### Pallet Call Macro - -Pallet development allows you to create callable functions by introducing the `#[pallet::call]` macro on top of a normal function implementation code block. +Imagine we had a trait `Hooks` we wanted to implement, we would also use the `Pallet` struct to to that: ```rust -#[pallet::call] -impl Pallet { - // All of the functions in this `impl` will be callable by users. +impl Hooks for Pallet { + fn on_finalize() { + // -- snip -- + } } ``` -Unlike regular Rust functions, these callable functions have rules on how they must be defined. - -### Origin - -The first parameter of every callable function must be `origin: OriginFor`. - -The origin is an abstract concept for defining the where the call is coming from. - -The most common origin is the signed origin, which is a regular transaction. We will learn about this more in the next section. - -### Dispatch Result - -Every callable function must return a `DispatchResult`, which is simply defined as: +And then we could access that those functions like: ```rust -pub type DispatchResult = Result<(), sp_runtime::DispatchError>; +pallet_kitties::Pallet::::on_finalize(); ``` -So these functions can return `Ok(())` or some `Err(DispatchError)`. - -You can easily define new `DispatchError` variants using the included `#[pallet::error]`, but we will get to that later. - -## Terminology - -In Polkadot, the term "call", "extrinsic", and "dispatchable" all get mixed together. +In fact, many traits are automatically implemented on top of `Pallet` and are accessible thanks to the `#[pallet::pallet]` attribute macro. -Here is a sentence which should help clarify their relationship, and why they are such similar terms: +### FRAME Traits -> Users submit an extrinsic to the blockchain, which is dispatched to a Pallet call. +You can see all the different traits implemented on `Pallet` by looking at the [autogenerated Rust docs](https://docs.rs/pallet-sudo/latest/pallet_sudo/pallet/struct.Pallet.html#trait-implementations). -In this case, "extrinsic" is a more broad term than a "transaction". +One simple example is the trait [`PalletInfoAccess`](https://docs.rs/frame-support/37.0.0/frame_support/traits/trait.PalletInfoAccess.html). -An extrinsic is any message from the outside coming to the blockchain. A transaction is specifically a **signed** message coming from the outside. +With this trait, you can do things like call `pallet_kitties::Pallet::::module_name()` which will return to you the name of the rust module, in this case `pallet_kitties`. Information like this is used mostly between other macros, which is why we hide it all from you behind the macros. -In this tutorial, we will only deal with transactions, but again, learning more about extrinsics can be something to follow up on after you have learned the basics. +In this tutorial, you will not interact with any of these automatically generated traits, but knowing that they exist can allow you to investigate further after learning the basics. diff --git a/steps/5/gitorial_metadata.json b/steps/5/gitorial_metadata.json index 9a0896e2..1cba1e02 100644 --- a/steps/5/gitorial_metadata.json +++ b/steps/5/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "action: learn about pallet functions" + "commitMessage": "action: learn about pallet struct" } \ No newline at end of file diff --git a/steps/5/src/impls.rs b/steps/5/src/impls.rs index 7454df9a..03abf99e 100644 --- a/steps/5/src/impls.rs +++ b/steps/5/src/impls.rs @@ -1,7 +1,6 @@ use super::*; use frame::prelude::*; -/* 🚧 TODO 🚧: Learn about internal functions. */ impl Pallet { pub fn mint(owner: T::AccountId) -> DispatchResult { Self::deposit_event(Event::::Created { owner }); diff --git a/steps/5/src/lib.rs b/steps/5/src/lib.rs index ef2382e2..95dc3a4e 100644 --- a/steps/5/src/lib.rs +++ b/steps/5/src/lib.rs @@ -9,6 +9,7 @@ pub use pallet::*; pub mod pallet { use super::*; + /* 🚧 TODO 🚧: Learn about the Pallet struct. */ #[pallet::pallet] pub struct Pallet(core::marker::PhantomData); @@ -26,7 +27,6 @@ pub mod pallet { #[pallet::error] pub enum Error {} - /* 🚧 TODO 🚧: Learn about callable functions and dispatch. */ #[pallet::call] impl Pallet { pub fn create_kitty(origin: OriginFor) -> DispatchResult { diff --git a/steps/50/README.md b/steps/50/README.md index b7c52700..857d540c 100644 --- a/steps/50/README.md +++ b/steps/50/README.md @@ -1,112 +1,3 @@ -# Buy Kitty Logic +# Solution -Now that we have scaffolded the `buy_kitty` extrinsic, its time for us to program it's logic. - -## Sanity Checks - -As always, before we execute any logic, we should check that everything is okay to actually proceed with the kitty purchase. - -The first check should obviously be if the kitty the user wants to purchase actually exists. - -Then we should check if the kitty is actually for sale, which is indicated by `Some(real_price)`, and extract that `real_price`. - -Finally, we should check that there is an agreement between the buyer and the seller on the price. - -The buyer will submit `max_price`, and we want to ensure that this `max_price` is greater than or equal to the `real_price`. - -## Transfer Logic - -To execute a purchase, we need to transfer two things: - -- The token balance from the buyer to the seller. -- The kitty from the seller to the buyer. - -### Transfer the Native Balance - -To transfer the `NativeBalance`, you can use the [`transfer`](https://docs.rs/frame-support/37.0.0/frame_support/traits/tokens/fungible/trait.Mutate.html#method.transfer) API which is included in the `fungible::Mutate` trait. - -```rust -fn transfer( - source: &AccountId, - dest: &AccountId, - amount: Self::Balance, - preservation: Preservation -) -> Result -``` - -> NOTE: To access this function, you will need import the trait to bring it in scope. Otherwise you will get an error that the function does not exist. So don't forget to include: -> -> ```rust -> use frame::traits::fungible::Mutate; -> ``` - -The first 3 parameters here are easy enough to understand: `source`, `dest`, and `amount`. - -However we also have a 4th parameter which is `preservation: Preservation`. - -```rust -/// The mode by which we describe whether an operation should keep an account alive. -pub enum Preservation { - /// We don't care if the account gets killed by this operation. - Expendable, - /// The account may not be killed, but we don't care if the balance gets dusted. - Protect, - /// The account may not be killed and our provider reference must remain (in the context of - /// tokens, this means that the account may not be dusted). - Preserve, -} -``` - -To understand this, you will need to dive deep into dust accounts, existential deposit, and account deletion. - -That is all beyond the scope of this tutorial, but the high level idea is that we require accounts in the `polkadot-sdk` to maintain a minimum balance. Whenever we transfer funds from the user, beyond checking they have enough to transfer, we also check whether that minimum amount is still left over in their account, and adjust the result of our transfer based on our `Preservation` requirements. - -In this context, we don't want someone to kill their account to buy a kitty, so we want to use `Preservation::Preserve` for our `transfer`. - -So the final syntax should look like: - -```rust -T::NativeBalance::transfer(&buyer, &kitty.owner, real_price, Preservation::Preserve)?; -``` - -### Transfer the Kitty - -To transfer the kitty, we can simply reuse our `Self::do_transfer` function that we wrote in the past. - -Hopefully you can start to see the payoff of how we have organized our code. - -As you work on more complex projects, breaking down behaviors into simple to understand and reusable pieces of internal logic will not only make your code more clean, but also easier to audit and update. - -It is unlikely you will have foresight on exactly how to break down your project when you first start writing it, but it is definitely something you should keep in mind as you find yourself writing potentially duplicate code. - -### Propagate Up Errors - -Both transfer functions need to succeed for the sale to complete successfully. - -If either one of them would fail, the whole purchase should fail. - -Thankfully, both of our transfer functions return a result, and to handle things correctly here, we just ned to propagate up those errors. For that, we simply include `?` at the end of the function. - -If at any point our extrinsic or the logic inside the extrinsic returns an error, the whole extrinsic will fail and all changes to storage will be undone. This is exactly the same behavior you would expect from a smart contract, and keeps our state transition function functioning smoothly. - -## Real Price - -As a final change in your pallet logic, we should update the `Event::::Sold` to emit the `real_price` instead of the buyers `max_price`. - -This is perhaps the first really good use case for emitting an Event. - -In all of our previous events, we basically just deposit the data that we already get from the extrinsic. - -However in this case, our `buy_kitty` extrinsic actually uses internal logic to manipulate what actually happens. It could be that the user submits a `max_price` higher than the `real_price`, and thus the extrinsic and a success message would not actually tell us what happened exactly. - -In this case, we can actually report by to the user and any UI they are using the executed sale price of the kitty. - -So this is really where Pallet Events shine, and how they should be used. This is something you will develop a sense for over time. - -## Your Turn - -You now have all the tools and information needed to build your `do_buy_kitty` logic. - -- Add the sanity checks needed to make sure `do_buy_kitty` should execute at all. -- Transfer both the `NativeBalance` and the `Kitty`, being sure to check for success. -- Finally, update the `Event::::Sold` to deposit the `real_price` that was transferred. +Here you will find the solution for the previous step. diff --git a/steps/50/gitorial_metadata.json b/steps/50/gitorial_metadata.json index d805c18b..9db04de6 100644 --- a/steps/50/gitorial_metadata.json +++ b/steps/50/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "template: add logic for buy kitty" + "commitMessage": "solution: add buy kitty extrinsic" } \ No newline at end of file diff --git a/steps/50/src/impls.rs b/steps/50/src/impls.rs index 2bb33859..889e7a2e 100644 --- a/steps/50/src/impls.rs +++ b/steps/50/src/impls.rs @@ -1,7 +1,6 @@ use super::*; use frame::prelude::*; use frame::primitives::BlakeTwo256; -/* 🚧 TODO 🚧: Import `frame::traits::tokens::Preservation`. */ use frame::traits::Hash; // Learn about internal functions. @@ -78,21 +77,6 @@ impl Pallet { kitty_id: [u8; 32], price: BalanceOf, ) -> DispatchResult { - /* 🚧 TODO 🚧: Sanity check that the purchase is allowed: - - Get `kitty` from `Kitties` using `kitty_id`, `ok_or` return `Error::::NoKitty`. - - Get the `real_price` from `kitty.price`, `ok_or` return `Error::::NotForSale`. - - `ensure!` that `price` is greater or equal to `real_price`, else `Error::::MaxPriceTooLow`. - */ - - /* 🚧 TODO 🚧: Execute the transfers: - - Use `T::NativeBalance` to `transfer` from the `buyer` to the `kitty.owner`. - - The amount transferred should be the `real_price`. - - Use `Preservation::Preserve` to ensure the buyer account stays alive. - - Use `Self::do_transfer` to transfer from the `kitty.owner` to the `buyer` with `kitty_id`. - - Remember to propagate up all results from these functions with `?`. - */ - - /* 🚧 TODO 🚧: Update the event to use the `real_price` in the `Event`. */ Self::deposit_event(Event::::Sold { buyer, kitty_id, price }); Ok(()) } diff --git a/steps/50/src/lib.rs b/steps/50/src/lib.rs index 214fb31f..93c74219 100644 --- a/steps/50/src/lib.rs +++ b/steps/50/src/lib.rs @@ -66,10 +66,6 @@ pub mod pallet { TransferToSelf, NoKitty, NotOwner, - /* 🚧 TODO 🚧: Add `Errors` needed for `do_buy_kitty`: - - `NotForSale`: for when the Kitty has a price set to `None`. - - `MaxPriceTooLow`: for when the price offered by the buyer is too low. - */ } #[pallet::call] diff --git a/steps/51/README.md b/steps/51/README.md index 857d540c..b7c52700 100644 --- a/steps/51/README.md +++ b/steps/51/README.md @@ -1,3 +1,112 @@ -# Solution +# Buy Kitty Logic -Here you will find the solution for the previous step. +Now that we have scaffolded the `buy_kitty` extrinsic, its time for us to program it's logic. + +## Sanity Checks + +As always, before we execute any logic, we should check that everything is okay to actually proceed with the kitty purchase. + +The first check should obviously be if the kitty the user wants to purchase actually exists. + +Then we should check if the kitty is actually for sale, which is indicated by `Some(real_price)`, and extract that `real_price`. + +Finally, we should check that there is an agreement between the buyer and the seller on the price. + +The buyer will submit `max_price`, and we want to ensure that this `max_price` is greater than or equal to the `real_price`. + +## Transfer Logic + +To execute a purchase, we need to transfer two things: + +- The token balance from the buyer to the seller. +- The kitty from the seller to the buyer. + +### Transfer the Native Balance + +To transfer the `NativeBalance`, you can use the [`transfer`](https://docs.rs/frame-support/37.0.0/frame_support/traits/tokens/fungible/trait.Mutate.html#method.transfer) API which is included in the `fungible::Mutate` trait. + +```rust +fn transfer( + source: &AccountId, + dest: &AccountId, + amount: Self::Balance, + preservation: Preservation +) -> Result +``` + +> NOTE: To access this function, you will need import the trait to bring it in scope. Otherwise you will get an error that the function does not exist. So don't forget to include: +> +> ```rust +> use frame::traits::fungible::Mutate; +> ``` + +The first 3 parameters here are easy enough to understand: `source`, `dest`, and `amount`. + +However we also have a 4th parameter which is `preservation: Preservation`. + +```rust +/// The mode by which we describe whether an operation should keep an account alive. +pub enum Preservation { + /// We don't care if the account gets killed by this operation. + Expendable, + /// The account may not be killed, but we don't care if the balance gets dusted. + Protect, + /// The account may not be killed and our provider reference must remain (in the context of + /// tokens, this means that the account may not be dusted). + Preserve, +} +``` + +To understand this, you will need to dive deep into dust accounts, existential deposit, and account deletion. + +That is all beyond the scope of this tutorial, but the high level idea is that we require accounts in the `polkadot-sdk` to maintain a minimum balance. Whenever we transfer funds from the user, beyond checking they have enough to transfer, we also check whether that minimum amount is still left over in their account, and adjust the result of our transfer based on our `Preservation` requirements. + +In this context, we don't want someone to kill their account to buy a kitty, so we want to use `Preservation::Preserve` for our `transfer`. + +So the final syntax should look like: + +```rust +T::NativeBalance::transfer(&buyer, &kitty.owner, real_price, Preservation::Preserve)?; +``` + +### Transfer the Kitty + +To transfer the kitty, we can simply reuse our `Self::do_transfer` function that we wrote in the past. + +Hopefully you can start to see the payoff of how we have organized our code. + +As you work on more complex projects, breaking down behaviors into simple to understand and reusable pieces of internal logic will not only make your code more clean, but also easier to audit and update. + +It is unlikely you will have foresight on exactly how to break down your project when you first start writing it, but it is definitely something you should keep in mind as you find yourself writing potentially duplicate code. + +### Propagate Up Errors + +Both transfer functions need to succeed for the sale to complete successfully. + +If either one of them would fail, the whole purchase should fail. + +Thankfully, both of our transfer functions return a result, and to handle things correctly here, we just ned to propagate up those errors. For that, we simply include `?` at the end of the function. + +If at any point our extrinsic or the logic inside the extrinsic returns an error, the whole extrinsic will fail and all changes to storage will be undone. This is exactly the same behavior you would expect from a smart contract, and keeps our state transition function functioning smoothly. + +## Real Price + +As a final change in your pallet logic, we should update the `Event::::Sold` to emit the `real_price` instead of the buyers `max_price`. + +This is perhaps the first really good use case for emitting an Event. + +In all of our previous events, we basically just deposit the data that we already get from the extrinsic. + +However in this case, our `buy_kitty` extrinsic actually uses internal logic to manipulate what actually happens. It could be that the user submits a `max_price` higher than the `real_price`, and thus the extrinsic and a success message would not actually tell us what happened exactly. + +In this case, we can actually report by to the user and any UI they are using the executed sale price of the kitty. + +So this is really where Pallet Events shine, and how they should be used. This is something you will develop a sense for over time. + +## Your Turn + +You now have all the tools and information needed to build your `do_buy_kitty` logic. + +- Add the sanity checks needed to make sure `do_buy_kitty` should execute at all. +- Transfer both the `NativeBalance` and the `Kitty`, being sure to check for success. +- Finally, update the `Event::::Sold` to deposit the `real_price` that was transferred. diff --git a/steps/51/gitorial_metadata.json b/steps/51/gitorial_metadata.json index 3ebadb0b..d805c18b 100644 --- a/steps/51/gitorial_metadata.json +++ b/steps/51/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "solution: add logic for buy kitty" + "commitMessage": "template: add logic for buy kitty" } \ No newline at end of file diff --git a/steps/51/src/impls.rs b/steps/51/src/impls.rs index a266e73c..2bb33859 100644 --- a/steps/51/src/impls.rs +++ b/steps/51/src/impls.rs @@ -1,7 +1,7 @@ use super::*; use frame::prelude::*; use frame::primitives::BlakeTwo256; -use frame::traits::tokens::Preservation; +/* 🚧 TODO 🚧: Import `frame::traits::tokens::Preservation`. */ use frame::traits::Hash; // Learn about internal functions. @@ -78,14 +78,22 @@ impl Pallet { kitty_id: [u8; 32], price: BalanceOf, ) -> DispatchResult { - let kitty = Kitties::::get(kitty_id).ok_or(Error::::NoKitty)?; - let real_price = kitty.price.ok_or(Error::::NotForSale)?; - ensure!(price >= real_price, Error::::MaxPriceTooLow); + /* 🚧 TODO 🚧: Sanity check that the purchase is allowed: + - Get `kitty` from `Kitties` using `kitty_id`, `ok_or` return `Error::::NoKitty`. + - Get the `real_price` from `kitty.price`, `ok_or` return `Error::::NotForSale`. + - `ensure!` that `price` is greater or equal to `real_price`, else `Error::::MaxPriceTooLow`. + */ - T::NativeBalance::transfer(&buyer, &kitty.owner, real_price, Preservation::Preserve)?; - Self::do_transfer(kitty.owner, buyer.clone(), kitty_id)?; + /* 🚧 TODO 🚧: Execute the transfers: + - Use `T::NativeBalance` to `transfer` from the `buyer` to the `kitty.owner`. + - The amount transferred should be the `real_price`. + - Use `Preservation::Preserve` to ensure the buyer account stays alive. + - Use `Self::do_transfer` to transfer from the `kitty.owner` to the `buyer` with `kitty_id`. + - Remember to propagate up all results from these functions with `?`. + */ - Self::deposit_event(Event::::Sold { buyer, kitty_id, price: real_price }); + /* 🚧 TODO 🚧: Update the event to use the `real_price` in the `Event`. */ + Self::deposit_event(Event::::Sold { buyer, kitty_id, price }); Ok(()) } } diff --git a/steps/51/src/lib.rs b/steps/51/src/lib.rs index 15ec1efd..214fb31f 100644 --- a/steps/51/src/lib.rs +++ b/steps/51/src/lib.rs @@ -66,8 +66,10 @@ pub mod pallet { TransferToSelf, NoKitty, NotOwner, - NotForSale, - MaxPriceTooLow, + /* 🚧 TODO 🚧: Add `Errors` needed for `do_buy_kitty`: + - `NotForSale`: for when the Kitty has a price set to `None`. + - `MaxPriceTooLow`: for when the price offered by the buyer is too low. + */ } #[pallet::call] diff --git a/steps/52/README.md b/steps/52/README.md index 30397d01..857d540c 100644 --- a/steps/52/README.md +++ b/steps/52/README.md @@ -1,55 +1,3 @@ -# Next Steps +# Solution -Congratulations! πŸŽ‰ - -You have completed this tutorial, and hopefully learned a lot along the way. - -However, your journey toward mastering the Polkadot SDK has just begun. - -Here are some ideas of what you can do next: - -- Share this tutorial! - - - Pick your favorite social networking platform, and share this tutorial with your peers! - -- Contribute back to this tutorial! - - - If you found errors or have suggestions on how to improve this tutorial, open an [issue](https://github.com/shawntabrizi/substrate-collectables-workshop/issues) or a [pull request](https://github.com/shawntabrizi/substrate-collectables-workshop/pulls). - -- Take a day to process this tutorial, then do it again! - - - Open all of the deep dive content. - - Watch all the linked videos. - - Check out all the additional resources. - -- If you need more Rust help, try the `rust-state-machine` tutorial: - - - [https://github.com/shawntabrizi/rust-state-machine](https://github.com/shawntabrizi/rust-state-machine) - -- Extend this project: - - - Create a function to "abandon" kitties, which removes them from our database. - - Create a function to breed kitties, and use the DNA of the parents to generate new DNA. - - Create a game using player stats based on the DNA of the kitty. - - etc... - -- If you want to take this tutorial to the next level: - - - TODO: Learn how to add this pallet to a custom blockchain. - - TODO: Learn how to create a UI using React for your NFT marketplace. - -- Check out the content from the Polkadot Blockchain Academy: - - - Slides: [https://polkadot-blockchain-academy.github.io/pba-content/](https://polkadot-blockchain-academy.github.io/pba-content/) - - Videos: [https://www.youtube.com/@polkadotblockchainacademy](https://www.youtube.com/@polkadotblockchainacademy) - -- Check out the Polkadot SDK Docs: - - - [https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/index.html](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/index.html) - -- Learn more about the Polkadot Network: - - - [https://polkadot.network/](https://polkadot.network/) - - -Good luck on your journey, and welcome to the Polkadot ecosystem! +Here you will find the solution for the previous step. diff --git a/steps/52/gitorial_metadata.json b/steps/52/gitorial_metadata.json index 6bf97460..3ebadb0b 100644 --- a/steps/52/gitorial_metadata.json +++ b/steps/52/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "section: next steps" -} + "commitMessage": "solution: add logic for buy kitty" +} \ No newline at end of file diff --git a/steps/53/.gitignore b/steps/53/.gitignore new file mode 100644 index 00000000..c537f0b6 --- /dev/null +++ b/steps/53/.gitignore @@ -0,0 +1,5 @@ +target/ +.vscode +chain_spec.json +book +steps diff --git a/steps/1/Cargo.lock b/steps/53/Cargo.lock similarity index 100% rename from steps/1/Cargo.lock rename to steps/53/Cargo.lock diff --git a/steps/1/Cargo.toml b/steps/53/Cargo.toml similarity index 100% rename from steps/1/Cargo.toml rename to steps/53/Cargo.toml diff --git a/steps/53/README.md b/steps/53/README.md new file mode 100644 index 00000000..30397d01 --- /dev/null +++ b/steps/53/README.md @@ -0,0 +1,55 @@ +# Next Steps + +Congratulations! πŸŽ‰ + +You have completed this tutorial, and hopefully learned a lot along the way. + +However, your journey toward mastering the Polkadot SDK has just begun. + +Here are some ideas of what you can do next: + +- Share this tutorial! + + - Pick your favorite social networking platform, and share this tutorial with your peers! + +- Contribute back to this tutorial! + + - If you found errors or have suggestions on how to improve this tutorial, open an [issue](https://github.com/shawntabrizi/substrate-collectables-workshop/issues) or a [pull request](https://github.com/shawntabrizi/substrate-collectables-workshop/pulls). + +- Take a day to process this tutorial, then do it again! + + - Open all of the deep dive content. + - Watch all the linked videos. + - Check out all the additional resources. + +- If you need more Rust help, try the `rust-state-machine` tutorial: + + - [https://github.com/shawntabrizi/rust-state-machine](https://github.com/shawntabrizi/rust-state-machine) + +- Extend this project: + + - Create a function to "abandon" kitties, which removes them from our database. + - Create a function to breed kitties, and use the DNA of the parents to generate new DNA. + - Create a game using player stats based on the DNA of the kitty. + - etc... + +- If you want to take this tutorial to the next level: + + - TODO: Learn how to add this pallet to a custom blockchain. + - TODO: Learn how to create a UI using React for your NFT marketplace. + +- Check out the content from the Polkadot Blockchain Academy: + + - Slides: [https://polkadot-blockchain-academy.github.io/pba-content/](https://polkadot-blockchain-academy.github.io/pba-content/) + - Videos: [https://www.youtube.com/@polkadotblockchainacademy](https://www.youtube.com/@polkadotblockchainacademy) + +- Check out the Polkadot SDK Docs: + + - [https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/index.html](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/index.html) + +- Learn more about the Polkadot Network: + + - [https://polkadot.network/](https://polkadot.network/) + + +Good luck on your journey, and welcome to the Polkadot ecosystem! diff --git a/steps/53/gitorial_metadata.json b/steps/53/gitorial_metadata.json new file mode 100644 index 00000000..6bf97460 --- /dev/null +++ b/steps/53/gitorial_metadata.json @@ -0,0 +1,4 @@ +{ + "_Note": "This file will not be included in your final gitorial.", + "commitMessage": "section: next steps" +} diff --git a/steps/1/rustfmt.toml b/steps/53/rustfmt.toml similarity index 100% rename from steps/1/rustfmt.toml rename to steps/53/rustfmt.toml diff --git a/steps/53/src/impls.rs b/steps/53/src/impls.rs new file mode 100644 index 00000000..a266e73c --- /dev/null +++ b/steps/53/src/impls.rs @@ -0,0 +1,91 @@ +use super::*; +use frame::prelude::*; +use frame::primitives::BlakeTwo256; +use frame::traits::tokens::Preservation; +use frame::traits::Hash; + +// Learn about internal functions. +impl Pallet { + // Generates and returns DNA and Sex + pub fn gen_dna() -> [u8; 32] { + // Create randomness payload. Multiple kitties can be generated in the same block, + // retaining uniqueness. + let unique_payload = ( + frame_system::Pallet::::parent_hash(), + frame_system::Pallet::::block_number(), + frame_system::Pallet::::extrinsic_index(), + CountForKitties::::get(), + ); + + BlakeTwo256::hash_of(&unique_payload).into() + } + + pub fn mint(owner: T::AccountId, dna: [u8; 32]) -> DispatchResult { + let kitty = Kitty { dna, owner: owner.clone(), price: None }; + // Check if the kitty does not already exist in our storage map + ensure!(!Kitties::::contains_key(dna), Error::::DuplicateKitty); + + let current_count: u32 = CountForKitties::::get(); + let new_count = current_count.checked_add(1).ok_or(Error::::TooManyKitties)?; + + KittiesOwned::::try_append(&owner, dna).map_err(|_| Error::::TooManyOwned)?; + Kitties::::insert(dna, kitty); + CountForKitties::::set(new_count); + + Self::deposit_event(Event::::Created { owner }); + Ok(()) + } + + pub fn do_transfer(from: T::AccountId, to: T::AccountId, kitty_id: [u8; 32]) -> DispatchResult { + ensure!(from != to, Error::::TransferToSelf); + let mut kitty = Kitties::::get(kitty_id).ok_or(Error::::NoKitty)?; + ensure!(kitty.owner == from, Error::::NotOwner); + kitty.owner = to.clone(); + + let mut to_owned = KittiesOwned::::get(&to); + to_owned.try_push(kitty_id).map_err(|_| Error::::TooManyOwned)?; + let mut from_owned = KittiesOwned::::get(&from); + if let Some(ind) = from_owned.iter().position(|&id| id == kitty_id) { + from_owned.swap_remove(ind); + } else { + return Err(Error::::NoKitty.into()) + } + + Kitties::::insert(kitty_id, kitty); + KittiesOwned::::insert(&to, to_owned); + KittiesOwned::::insert(&from, from_owned); + + Self::deposit_event(Event::::Transferred { from, to, kitty_id }); + Ok(()) + } + + pub fn do_set_price( + caller: T::AccountId, + kitty_id: [u8; 32], + new_price: Option>, + ) -> DispatchResult { + let mut kitty = Kitties::::get(kitty_id).ok_or(Error::::NoKitty)?; + ensure!(kitty.owner == caller, Error::::NotOwner); + kitty.price = new_price; + Kitties::::insert(kitty_id, kitty); + + Self::deposit_event(Event::::PriceSet { owner: caller, kitty_id, new_price }); + Ok(()) + } + + pub fn do_buy_kitty( + buyer: T::AccountId, + kitty_id: [u8; 32], + price: BalanceOf, + ) -> DispatchResult { + let kitty = Kitties::::get(kitty_id).ok_or(Error::::NoKitty)?; + let real_price = kitty.price.ok_or(Error::::NotForSale)?; + ensure!(price >= real_price, Error::::MaxPriceTooLow); + + T::NativeBalance::transfer(&buyer, &kitty.owner, real_price, Preservation::Preserve)?; + Self::do_transfer(kitty.owner, buyer.clone(), kitty_id)?; + + Self::deposit_event(Event::::Sold { buyer, kitty_id, price: real_price }); + Ok(()) + } +} diff --git a/steps/53/src/lib.rs b/steps/53/src/lib.rs new file mode 100644 index 00000000..15ec1efd --- /dev/null +++ b/steps/53/src/lib.rs @@ -0,0 +1,112 @@ +#![cfg_attr(not(feature = "std"), no_std)] + +mod impls; + +use frame::prelude::*; +use frame::traits::fungible::Inspect; +use frame::traits::fungible::Mutate; +pub use pallet::*; + +#[frame::pallet(dev_mode)] +pub mod pallet { + use super::*; + + #[pallet::pallet] + pub struct Pallet(core::marker::PhantomData); + + #[pallet::config] + pub trait Config: frame_system::Config { + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + + /// The Fungible handler for the kitties pallet. + type NativeBalance: Inspect + Mutate; + } + + // Allows easy access our Pallet's `Balance` type. Comes from `Fungible` interface. + pub type BalanceOf = + <::NativeBalance as Inspect<::AccountId>>::Balance; + + #[derive(Encode, Decode, TypeInfo, MaxEncodedLen)] + #[scale_info(skip_type_params(T))] + pub struct Kitty { + // Using 32 bytes to represent a kitty DNA + pub dna: [u8; 32], + pub owner: T::AccountId, + pub price: Option>, + } + + #[pallet::storage] + pub(super) type CountForKitties = StorageValue; + + #[pallet::storage] + pub(super) type Kitties = StorageMap>; + + /// Track the kitties owned by each account. + #[pallet::storage] + pub(super) type KittiesOwned = StorageMap< + Key = T::AccountId, + Value = BoundedVec<[u8; 32], ConstU32<100>>, + QueryKind = ValueQuery, + >; + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + Created { owner: T::AccountId }, + Transferred { from: T::AccountId, to: T::AccountId, kitty_id: [u8; 32] }, + PriceSet { owner: T::AccountId, kitty_id: [u8; 32], new_price: Option> }, + Sold { buyer: T::AccountId, kitty_id: [u8; 32], price: BalanceOf }, + } + + #[pallet::error] + pub enum Error { + TooManyKitties, + DuplicateKitty, + TooManyOwned, + TransferToSelf, + NoKitty, + NotOwner, + NotForSale, + MaxPriceTooLow, + } + + #[pallet::call] + impl Pallet { + pub fn create_kitty(origin: OriginFor) -> DispatchResult { + let who = ensure_signed(origin)?; + let dna = Self::gen_dna(); + Self::mint(who, dna)?; + Ok(()) + } + + pub fn transfer( + origin: OriginFor, + to: T::AccountId, + kitty_id: [u8; 32], + ) -> DispatchResult { + let who = ensure_signed(origin)?; + Self::do_transfer(who, to, kitty_id)?; + Ok(()) + } + + pub fn set_price( + origin: OriginFor, + kitty_id: [u8; 32], + new_price: Option>, + ) -> DispatchResult { + let who = ensure_signed(origin)?; + Self::do_set_price(who, kitty_id, new_price)?; + Ok(()) + } + + pub fn buy_kitty( + origin: OriginFor, + kitty_id: [u8; 32], + max_price: BalanceOf, + ) -> DispatchResult { + let who = ensure_signed(origin)?; + Self::do_buy_kitty(who, kitty_id, max_price)?; + Ok(()) + } + } +} diff --git a/steps/6/README.md b/steps/6/README.md index a092b86c..f4854d4b 100644 --- a/steps/6/README.md +++ b/steps/6/README.md @@ -1,56 +1,79 @@ -# Origin +# Pallet Functions -As we started to describe, the `origin` is the first parameter of every callable function. +As noted earlier, functions are easily implemented directly on top of the `Pallet` struct. -It describes where the call is calling from, and allows us to perform simple access control logic based on that information. +However, there are two types of functions exposed by Pallets: -## Origin vs Sender +1. Internal Functions +2. Callable Functions -If you are familiar with smart contract development, for example in Ethereum, you will be familiar with `msg.sender`. +Let's learn more about the differences. -Origin is a superset of this idea. No longer do we need to assume that every call to a callable function is coming from an external account. We could have pallets call one another, or other internal logic trigger a callable function. +## Internal Functions -It is hard to explain the power of Origin when you are still learning the basics of Pallet development, but this is again, something worth exploring deeper at a later point. - -## Ensure Signed - -In this tutorial, we will just use origin to check for signed messages. - -For this, we can use the `ensure_signed` function: +Internal Pallet functions are just normal Rust functions. These are defined with regular Rust syntax and without any of the Pallet macros. ```rust -let who: T::AccountId = ensure_signed(origin)?; +impl Pallet { + // None of the functions in this `impl` are callable by users. +} ``` -You can see this function takes the `OriginFor` type, and will return a `T::AccountId` if the `origin` was an account, otherwise it will return the error `BadOrigin`. +They behave just like any Rust function from any Rust module. If they are marked `pub` they are exposed to other Rust modules, if not they are totally private. -This turns origin into exactly the same as `msg.sender` from Ethereum contract development. +What is most important is that no matter how these functions are marked, none of these functions are callable from outside of the blockchain, which means they are not exposed to users. -With this, we are able to +For that, we have Callable Functions. -## Deep Dive +## Callable Functions -As a note, you should know that `ensure_signed` is not actually doing signature checking. +If you are familiar with smart contracts or any kind of blockchain application, you would know that the way users interact with the blockchain is through transactions. -Signature checking is very expensive, perhaps one of the most expensive things to perform when executing transactions. +Those transactions are processed, and then dispatched to callable functions within the blockchain. -So signature checking happens batched and parallelized at the beginning of executing a block. +### Pallet Call Macro -By the time your callable function gets the `origin`, it is just: +Pallet development allows you to create callable functions by introducing the `#[pallet::call]` macro on top of a normal function implementation code block. ```rust -let origin: OriginFor = RawOrigin::Signed(account_id).into(); +#[pallet::call] +impl Pallet { + // All of the functions in this `impl` will be callable by users. +} ``` -So it is simply an enum variant with the `T::AccountId` inside. So `ensure_signed` logic is as simple as: +Unlike regular Rust functions, these callable functions have rules on how they must be defined. + +### Origin + +The first parameter of every callable function must be `origin: OriginFor`. + +The origin is an abstract concept for defining the where the call is coming from. + +The most common origin is the signed origin, which is a regular transaction. We will learn about this more in the next section. + +### Dispatch Result + +Every callable function must return a `DispatchResult`, which is simply defined as: ```rust -pub fn ensure_signed(o: OriginFor) -> Result { - match o { - RawOrigin::Signed(t) => Ok(t), - _ => Err(BadOrigin), - } -} +pub type DispatchResult = Result<(), sp_runtime::DispatchError>; ``` -The real `ensure_signed` function has more generic stuff, but the idea is the same. +So these functions can return `Ok(())` or some `Err(DispatchError)`. + +You can easily define new `DispatchError` variants using the included `#[pallet::error]`, but we will get to that later. + +## Terminology + +In Polkadot, the term "call", "extrinsic", and "dispatchable" all get mixed together. + +Here is a sentence which should help clarify their relationship, and why they are such similar terms: + +> Users submit an extrinsic to the blockchain, which is dispatched to a Pallet call. + +In this case, "extrinsic" is a more broad term than a "transaction". + +An extrinsic is any message from the outside coming to the blockchain. A transaction is specifically a **signed** message coming from the outside. + +In this tutorial, we will only deal with transactions, but again, learning more about extrinsics can be something to follow up on after you have learned the basics. diff --git a/steps/6/gitorial_metadata.json b/steps/6/gitorial_metadata.json index 3abf8f74..9a0896e2 100644 --- a/steps/6/gitorial_metadata.json +++ b/steps/6/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "action: learn about origin" + "commitMessage": "action: learn about pallet functions" } \ No newline at end of file diff --git a/steps/6/src/impls.rs b/steps/6/src/impls.rs index ecb2e7df..7454df9a 100644 --- a/steps/6/src/impls.rs +++ b/steps/6/src/impls.rs @@ -1,8 +1,8 @@ use super::*; use frame::prelude::*; +/* 🚧 TODO 🚧: Learn about internal functions. */ impl Pallet { - /* 🚧 TODO 🚧: Learn about `AccountId`. */ pub fn mint(owner: T::AccountId) -> DispatchResult { Self::deposit_event(Event::::Created { owner }); Ok(()) diff --git a/steps/6/src/lib.rs b/steps/6/src/lib.rs index 973b65ba..ef2382e2 100644 --- a/steps/6/src/lib.rs +++ b/steps/6/src/lib.rs @@ -26,10 +26,10 @@ pub mod pallet { #[pallet::error] pub enum Error {} + /* 🚧 TODO 🚧: Learn about callable functions and dispatch. */ #[pallet::call] impl Pallet { pub fn create_kitty(origin: OriginFor) -> DispatchResult { - /* 🚧 TODO 🚧: Learn about origin. */ let who = ensure_signed(origin)?; Self::mint(who)?; Ok(()) diff --git a/steps/7/README.md b/steps/7/README.md index 6a70d6f7..a092b86c 100644 --- a/steps/7/README.md +++ b/steps/7/README.md @@ -1,86 +1,56 @@ -# Pallet Config +# Origin -Each pallet includes a trait `Config` which is used to configure the pallet in the context of your larger runtime. +As we started to describe, the `origin` is the first parameter of every callable function. -```rust -#[pallet::config] -pub trait Config: frame_system::Config { - // -- snip -- -} -``` +It describes where the call is calling from, and allows us to perform simple access control logic based on that information. -It sucks to keep repeating this about different parts of FRAME development, but the full power of the `Config` trait can only be understood once you have moved passed the basics. +## Origin vs Sender -For now, we just want to focus on the basics. +If you are familiar with smart contract development, for example in Ethereum, you will be familiar with `msg.sender`. -## T as Config +Origin is a superset of this idea. No longer do we need to assume that every call to a callable function is coming from an external account. We could have pallets call one another, or other internal logic trigger a callable function. -We use our Pallet's `Config` all over our code, but through a generic parameter `T`. +It is hard to explain the power of Origin when you are still learning the basics of Pallet development, but this is again, something worth exploring deeper at a later point. -This is what is meant with `` that you see everywhere. +## Ensure Signed -The simplest way to understand is that wherever you see `T`, you have access to our `trait Config` and the types and functions inside of it. +In this tutorial, we will just use origin to check for signed messages. -## Supertraits +For this, we can use the `ensure_signed` function: -To understand how we use the `Config` trait, we first need to learn about [Rust supertraits](https://doc.rust-lang.org/rust-by-example/trait/supertraits.html). +```rust +let who: T::AccountId = ensure_signed(origin)?; +``` -Supertraits are similar to the concept of "inheritance" from other programming languages. In Rust, it allows one trait as being a superset of another trait. +You can see this function takes the `OriginFor` type, and will return a `T::AccountId` if the `origin` was an account, otherwise it will return the error `BadOrigin`. -You will notice that our `Config` trait is a supertrait of the `frame_system::Config` trait. +This turns origin into exactly the same as `msg.sender` from Ethereum contract development. -What is `frame_system`? What is in `frame_system::Config`? +With this, we are able to -## FRAME System +## Deep Dive -In order for our blockchain to function, we need some base level primitives. +As a note, you should know that `ensure_signed` is not actually doing signature checking. -- Account Id -- Block Number -- Block Hash -- Nonce -- etc... +Signature checking is very expensive, perhaps one of the most expensive things to perform when executing transactions. -`frame_system` provides all of that, and all the basic level functions needed for your blockchain to operate. +So signature checking happens batched and parallelized at the beginning of executing a block. -These types, and more, are defined within the `frame_system::Config`: +By the time your callable function gets the `origin`, it is just: ```rust -pub trait Config: 'static + Eq + Clone { - type Hash: Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + SimpleBitOps + Ord + Default + Copy + CheckEqual + sp_std::hash::Hash + AsRef<[u8]> + AsMut<[u8]> + MaxEncodedLen; - type AccountId: Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + Ord + MaxEncodedLen; - type Block: Parameter + Member + traits::Block; - type Nonce: Parameter + Member + MaybeSerializeDeserialize + Debug + Default + MaybeDisplay + AtLeast32Bit + Copy + MaxEncodedLen; - // -- snip -- -} +let origin: OriginFor = RawOrigin::Signed(account_id).into(); ``` -Because our `trait Config` is a superset of `frame_system::Config`, we have access to these types too. - -This is why you see in our starting code `T::AccountId`. We are able to access the `AccountId` type, which is originally defined inside `frame_system::Config` through our `trait Config`, via the generic trait `T`. - -Phew. - -If this doesn't make sense, that's okay. You should be able to follow the patterns for successfully programming all this, and you can learn the deep Rust stuff later. - -## Our Config - -Our config only includes one item for now: `RuntimeEvent`. - -It has a pretty nasty trait bound: +So it is simply an enum variant with the `T::AccountId` inside. So `ensure_signed` logic is as simple as: ```rust -type RuntimeEvent: From> + IsType<::RuntimeEvent>; +pub fn ensure_signed(o: OriginFor) -> Result { + match o { + RawOrigin::Signed(t) => Ok(t), + _ => Err(BadOrigin), + } +} ``` -The main purpose of this trait bound is to allow events of this pallet to be converted to and from an "aggregated" event type, which contains all possible event variants from all possible Pallets in our blockchain. - -Remember, our runtime is composed of multiple pallets, some we create, some which come with the `polkadot-sdk`, some that we import from 3rd parties. - -Each of these pallets will want to include their own custom events, and our blockchain as a whole needs to be able to handle all of them. - -The `RuntimeEvent` type, with the help of our macros, aggregates all of these events coming from all of these pallets. These trait bounds help us use this type! - -If you want to learn more about this (super optional), check out this video: - - +The real `ensure_signed` function has more generic stuff, but the idea is the same. diff --git a/steps/7/gitorial_metadata.json b/steps/7/gitorial_metadata.json index ff157e1f..3abf8f74 100644 --- a/steps/7/gitorial_metadata.json +++ b/steps/7/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "action: learn about config and frame system" + "commitMessage": "action: learn about origin" } \ No newline at end of file diff --git a/steps/7/src/impls.rs b/steps/7/src/impls.rs index 03abf99e..ecb2e7df 100644 --- a/steps/7/src/impls.rs +++ b/steps/7/src/impls.rs @@ -2,6 +2,7 @@ use super::*; use frame::prelude::*; impl Pallet { + /* 🚧 TODO 🚧: Learn about `AccountId`. */ pub fn mint(owner: T::AccountId) -> DispatchResult { Self::deposit_event(Event::::Created { owner }); Ok(()) diff --git a/steps/7/src/lib.rs b/steps/7/src/lib.rs index 424711d4..973b65ba 100644 --- a/steps/7/src/lib.rs +++ b/steps/7/src/lib.rs @@ -12,7 +12,6 @@ pub mod pallet { #[pallet::pallet] pub struct Pallet(core::marker::PhantomData); - /* 🚧 TODO 🚧: Learn about Pallet `Config` and `frame_system`. */ #[pallet::config] pub trait Config: frame_system::Config { type RuntimeEvent: From> + IsType<::RuntimeEvent>; @@ -30,6 +29,7 @@ pub mod pallet { #[pallet::call] impl Pallet { pub fn create_kitty(origin: OriginFor) -> DispatchResult { + /* 🚧 TODO 🚧: Learn about origin. */ let who = ensure_signed(origin)?; Self::mint(who)?; Ok(()) diff --git a/steps/8/README.md b/steps/8/README.md index dfccc300..6a70d6f7 100644 --- a/steps/8/README.md +++ b/steps/8/README.md @@ -1,63 +1,86 @@ -# Pallet Events +# Pallet Config -The last thing we have included in our starting template is a simple event. +Each pallet includes a trait `Config` which is used to configure the pallet in the context of your larger runtime. -When a callable function completes successfully, there is often some metadata you would like to expose to the outside world about what exactly happened during the execution. +```rust +#[pallet::config] +pub trait Config: frame_system::Config { + // -- snip -- +} +``` -Events allow Pallets to express that something has happened, and allows off-chain systems like indexers or block explorers to track certain state transitions. +It sucks to keep repeating this about different parts of FRAME development, but the full power of the `Config` trait can only be understood once you have moved passed the basics. -## Event Macro +For now, we just want to focus on the basics. -The `#[pallet::event]` macro acts on an `enum Event`. +## T as Config -```rust -#[pallet::event] -#[pallet::generate_deposit(pub(super) fn deposit_event)] -pub enum Event { - Created { owner: T::AccountId }, -} -``` +We use our Pallet's `Config` all over our code, but through a generic parameter `T`. + +This is what is meant with `` that you see everywhere. + +The simplest way to understand is that wherever you see `T`, you have access to our `trait Config` and the types and functions inside of it. + +## Supertraits -In this enum, you can introduce new variants as objects with arbitrary fields. Obviously you don't want to stick a ton of data in there, but you should feel comfortable to put the data which is relevant for tools like indexers and block explorers. +To understand how we use the `Config` trait, we first need to learn about [Rust supertraits](https://doc.rust-lang.org/rust-by-example/trait/supertraits.html). -In this case, we set you up with a simple event stating a new kitty was created, and by whom. Of course there is no logic which is actually doing that yet, but that is what we will start to work on next. +Supertraits are similar to the concept of "inheritance" from other programming languages. In Rust, it allows one trait as being a superset of another trait. -Emitting an event is usually the last thing you will do in your extrinsic, noting when everything is done and with any final values you might have generated. +You will notice that our `Config` trait is a supertrait of the `frame_system::Config` trait. -We will probably want to update our `Created` event with details about the Kitty we created. We can do that in the future. +What is `frame_system`? What is in `frame_system::Config`? -## Macro Magic +## FRAME System -You might ask, "What is this `generate_deposit` stuff? +In order for our blockchain to function, we need some base level primitives. -When we deposit an event, we actually have to pass our event to `frame_system`, which manages events across all pallets. +- Account Id +- Block Number +- Block Hash +- Nonce +- etc... -The code for that function is: +`frame_system` provides all of that, and all the basic level functions needed for your blockchain to operate. + +These types, and more, are defined within the `frame_system::Config`: ```rust -impl Pallet { - pub(super) fn deposit_event(event: Event) { - let event = <::RuntimeEvent as From>>::from(event); - let event = <::RuntimeEvent as Into< - ::RuntimeEvent, - >>::into(event); - >::deposit_event(event) - } +pub trait Config: 'static + Eq + Clone { + type Hash: Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + SimpleBitOps + Ord + Default + Copy + CheckEqual + sp_std::hash::Hash + AsRef<[u8]> + AsMut<[u8]> + MaxEncodedLen; + type AccountId: Parameter + Member + MaybeSerializeDeserialize + Debug + MaybeDisplay + Ord + MaxEncodedLen; + type Block: Parameter + Member + traits::Block; + type Nonce: Parameter + Member + MaybeSerializeDeserialize + Debug + Default + MaybeDisplay + AtLeast32Bit + Copy + MaxEncodedLen; + // -- snip -- } ``` -Rather than asking the user to remember and write this every time, we are able to automatically generate it for the user. +Because our `trait Config` is a superset of `frame_system::Config`, we have access to these types too. + +This is why you see in our starting code `T::AccountId`. We are able to access the `AccountId` type, which is originally defined inside `frame_system::Config` through our `trait Config`, via the generic trait `T`. -Do you not like macro magic? +Phew. -Delete the `generate_deposit` line, and copy and paste this code block into your code! +If this doesn't make sense, that's okay. You should be able to follow the patterns for successfully programming all this, and you can learn the deep Rust stuff later. -It is literally the same. In this case, I think the macro magic is justified. +## Our Config -You are able to access this function like you could any other function implemented on `Pallet`: +Our config only includes one item for now: `RuntimeEvent`. + +It has a pretty nasty trait bound: ```rust -Self::deposit_event(Event::::Created { owner }); +type RuntimeEvent: From> + IsType<::RuntimeEvent>; ``` -As you see in our starting code. +The main purpose of this trait bound is to allow events of this pallet to be converted to and from an "aggregated" event type, which contains all possible event variants from all possible Pallets in our blockchain. + +Remember, our runtime is composed of multiple pallets, some we create, some which come with the `polkadot-sdk`, some that we import from 3rd parties. + +Each of these pallets will want to include their own custom events, and our blockchain as a whole needs to be able to handle all of them. + +The `RuntimeEvent` type, with the help of our macros, aggregates all of these events coming from all of these pallets. These trait bounds help us use this type! + +If you want to learn more about this (super optional), check out this video: + + diff --git a/steps/8/gitorial_metadata.json b/steps/8/gitorial_metadata.json index 9220787e..ff157e1f 100644 --- a/steps/8/gitorial_metadata.json +++ b/steps/8/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "action: learn about events" + "commitMessage": "action: learn about config and frame system" } \ No newline at end of file diff --git a/steps/8/src/lib.rs b/steps/8/src/lib.rs index 5bac8030..424711d4 100644 --- a/steps/8/src/lib.rs +++ b/steps/8/src/lib.rs @@ -12,12 +12,12 @@ pub mod pallet { #[pallet::pallet] pub struct Pallet(core::marker::PhantomData); + /* 🚧 TODO 🚧: Learn about Pallet `Config` and `frame_system`. */ #[pallet::config] pub trait Config: frame_system::Config { type RuntimeEvent: From> + IsType<::RuntimeEvent>; } - /* 🚧 TODO 🚧: Learn about Pallet Events. */ #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { diff --git a/steps/9/README.md b/steps/9/README.md index 0f3623b8..dfccc300 100644 --- a/steps/9/README.md +++ b/steps/9/README.md @@ -1,61 +1,63 @@ -# Storage Basics +# Pallet Events -Now that we have covered the basics of Pallets, and gone through all of the template code, we can start writing some code ourselves. +The last thing we have included in our starting template is a simple event. -In this section you will learn the basics of creating and using storage in your Pallet. +When a callable function completes successfully, there is often some metadata you would like to expose to the outside world about what exactly happened during the execution. -But before we can start coding, we need to learn some basics about blockchains. +Events allow Pallets to express that something has happened, and allows off-chain systems like indexers or block explorers to track certain state transitions. -## Hash Functions +## Event Macro -Hash functions are an important tool throughout blockchain development. +The `#[pallet::event]` macro acts on an `enum Event`. -A hash function takes an arbitrary sized input and returns a fixed-size string of bytes. +```rust +#[pallet::event] +#[pallet::generate_deposit(pub(super) fn deposit_event)] +pub enum Event { + Created { owner: T::AccountId }, +} +``` -This output, usually called a hash, is unique to each unique input. Even a small change to the input creates a dramatic change to the output. +In this enum, you can introduce new variants as objects with arbitrary fields. Obviously you don't want to stick a ton of data in there, but you should feel comfortable to put the data which is relevant for tools like indexers and block explorers. -Hash functions have several key properties: +In this case, we set you up with a simple event stating a new kitty was created, and by whom. Of course there is no logic which is actually doing that yet, but that is what we will start to work on next. -- Deterministic: The same input always produces the same output. -- Pre-image Resistant: It is difficult to derive the original input from its hash value. -- Collision Resistant: It’s hard to find two different inputs that produce the same hash output. +Emitting an event is usually the last thing you will do in your extrinsic, noting when everything is done and with any final values you might have generated. -These properties make hash functions key for ensuring data integrity and uniqueness in blockchain technology. +We will probably want to update our `Created` event with details about the Kitty we created. We can do that in the future. -## Hash Fingerprint +## Macro Magic -Due to the properties of a Hash, it is often referred to as a fingerprint. +You might ask, "What is this `generate_deposit` stuff? -For context, a 32-byte hash has 2^32 different possible outputs. This nearly as many atoms as there are in the whole universe! +When we deposit an event, we actually have to pass our event to `frame_system`, which manages events across all pallets. -This uniqueness property helps blockchain nodes come to consensus with one another. +The code for that function is: -Rather than needing to compare all the data in their blockchain database with one another, they can simply share the hash of that database, and know in a single small comparison if all data in that database is the same. +```rust +impl Pallet { + pub(super) fn deposit_event(event: Event) { + let event = <::RuntimeEvent as From>>::from(event); + let event = <::RuntimeEvent as Into< + ::RuntimeEvent, + >>::into(event); + >::deposit_event(event) + } +} +``` -Remember, if there were any small differences between their databases, even just one bit in a multi-terabyte database being different, the resulting hash would dramatically change, and they would know their databases are not the same. +Rather than asking the user to remember and write this every time, we are able to automatically generate it for the user. -## Merkle Trie +Do you not like macro magic? -A merkle trie is a data structure which is constructed using a hash function. +Delete the `generate_deposit` line, and copy and paste this code block into your code! -Rather than hashing the whole database into a single hash, we create a tree of hashes. +It is literally the same. In this case, I think the macro magic is justified. -For example, we take pairs of data, combine them, then hash them to generate a new output. Then we take pairs of hashes, combine them, then hash them to generate another new output. +You are able to access this function like you could any other function implemented on `Pallet`: -We can repeat this process until we are left with a single hash called the "root hash". This process literally creates a tree of hashes. +```rust +Self::deposit_event(Event::::Created { owner }); +``` -Just like before, we can use a single hash to represent the integrity of all data underneath it, but now we can efficiently represent specific pieces of data in the database using the path down the trie to that data. - -It is called a merkle "trie" because the trie data structure is used to reduce the amount of redundant data stored in the tree. - -### Complexity - -The reason we go into this much detail about merkle tries is that they increase the complexity in reading and writing to the blockchain database. - -Whereas reading and writing to a database could be considered `O(1)`, a merklized database has read and write complexity of `O(log N)`, where `N` is the total number of items stored in the database. - -This additional complexity means that designing storage for a blockchain is an extremely important and sensitive operation. - -The primary advantage of using a merkle trie is that proving specific data exists inside the database is much more efficient! Whereas you would normally need to share the whole database to prove that some data exists, with a merklized database, you only need to share `O(log N)` amount of data. - -In this next section, and throughout the tutorial, we will start to explore some of those decisions. +As you see in our starting code. diff --git a/steps/9/gitorial_metadata.json b/steps/9/gitorial_metadata.json index d75bd3e0..9220787e 100644 --- a/steps/9/gitorial_metadata.json +++ b/steps/9/gitorial_metadata.json @@ -1,4 +1,4 @@ { "_Note": "This file will not be included in your final gitorial.", - "commitMessage": "section: storage basics" + "commitMessage": "action: learn about events" } \ No newline at end of file diff --git a/steps/9/src/lib.rs b/steps/9/src/lib.rs index 7b6c6a21..5bac8030 100644 --- a/steps/9/src/lib.rs +++ b/steps/9/src/lib.rs @@ -17,6 +17,7 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; } + /* 🚧 TODO 🚧: Learn about Pallet Events. */ #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event {