diff --git a/.ai/categories/basics.md b/.ai/categories/basics.md index d30206a10..2fee44423 100644 --- a/.ai/categories/basics.md +++ b/.ai/categories/basics.md @@ -473,440 +473,6 @@ Launch your parachain locally and start producing blocks: ---- - -Page Title: Blocks - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-blocks.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/blocks/ -- Summary: Understand how blocks are produced, validated, and imported in Polkadot SDK-based blockchains, covering initialization, finalization, and authoring processes. - -# Blocks - -## Introduction - -In the Polkadot SDK, blocks are fundamental to the functioning of the blockchain, serving as containers for [transactions](/reference/parachains/blocks-transactions-fees/transactions/){target=\_blank} and changes to the chain's state. Blocks consist of headers and an array of transactions, ensuring the integrity and validity of operations on the network. This guide explores the essential components of a block, the process of block production, and how blocks are validated and imported across the network. By understanding these concepts, developers can better grasp how blockchains maintain security, consistency, and performance within the Polkadot ecosystem. - -## What is a Block? - -In the Polkadot SDK, a block is a fundamental unit that encapsulates both the header and an array of transactions. The block header includes critical metadata to ensure the integrity and sequence of the blockchain. Here's a breakdown of its components: - -- **Block height**: Indicates the number of blocks created in the chain so far. -- **Parent hash**: The hash of the previous block, providing a link to maintain the blockchain's immutability. -- **Transaction root**: Cryptographic digest summarizing all transactions in the block. -- **State root**: A cryptographic digest representing the post-execution state. -- **Digest**: Additional information that can be attached to a block, such as consensus-related messages. - -Each transaction is part of a series that is executed according to the runtime's rules. The transaction root is a cryptographic digest of this series, which prevents alterations and enables succinct verification by light clients. This verification process allows light clients to confirm whether a transaction exists in a block with only the block header, avoiding downloading the entire block. - -## Block Production - -When an authoring node is authorized to create a new block, it selects transactions from the transaction queue based on priority. This step, known as block production, relies heavily on the executive module to manage the initialization and finalization of blocks. The process is summarized as follows: - -### Initialize Block - -The block initialization process begins with a series of function calls that prepare the block for transaction execution: - -1. **Call `on_initialize`**: The executive module calls the [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} hook from the system pallet and other runtime pallets to prepare for the block's transactions. -2. **Coordinate runtime calls**: Coordinates function calls in the order defined by the transaction queue. -3. **Verify information**: Once [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} functions are executed, the executive module checks the parent hash in the block header and the trie root to verify information is consistent. - -### Finalize Block - -Once transactions are processed, the block must be finalized before being broadcast to the network. The finalization steps are as follows: - -1. **Call `on_finalize`**: The executive module calls the [`on_finalize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_finalize){target=\_blank} hooks in each pallet to ensure any remaining state updates or checks are completed before the block is sealed and published. -2. **Verify information**: The block's digest and storage root in the header are checked against the initialized block to ensure consistency. -3. **Call `on_idle`**: The [`on_idle`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_idle){target=\_blank} hook is triggered to process any remaining tasks using the leftover weight from the block. - -## Block Authoring and Import - -Once the block is finalized, it is gossiped to other nodes in the network. Nodes follow this procedure: - -1. **Receive transactions**: The authoring node collects transactions from the network. -2. **Validate**: Transactions are checked for validity. -3. **Queue**: Valid transactions are placed in the transaction pool for execution. -4. **Execute**: State changes are made as the transactions are executed. -5. **Publish**: The finalized block is broadcast to the network. - -### Block Import Queue - -After a block is published, other nodes on the network can import it into their chain state. The block import queue is part of the outer node in every Polkadot SDK-based node and ensures incoming blocks are valid before adding them to the node's state. - -In most cases, you don't need to know details about how transactions are gossiped or how other nodes on the network import blocks. The following traits are relevant, however, if you plan to write any custom consensus logic or want a deeper dive into the block import queue: - -- **[`ImportQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.ImportQueue.html){target=\_blank}**: The trait that defines the block import queue. -- **[`Link`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Link.html){target=\_blank}**: The trait that defines the link between the block import queue and the network. -- **[`BasicQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/struct.BasicQueue.html){target=\_blank}**: A basic implementation of the block import queue. -- **[`Verifier`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Verifier.html){target=\_blank}**: The trait that defines the block verifier. -- **[`BlockImport`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/block_import/trait.BlockImport.html){target=\_blank}**: The trait that defines the block import process. - -These traits govern how blocks are validated and imported across the network, ensuring consistency and security. - -## Additional Resources - -To learn more about the block structure in the Polkadot SDK runtime, see the [`Block` reference](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.Block.html){target=\_blank} entry in the Rust Docs. - - ---- - -Page Title: Chain Data - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-chain-data.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/chain-data/ -- Summary: Learn how to expose and utilize chain data for blockchain applications. Discover runtime metadata, RPC APIs, and tools for efficient development. - -# Chain Data - -## Introduction - -Understanding and leveraging on-chain data is a fundamental aspect of blockchain development. Whether you're building frontend applications or backend systems, accessing and decoding runtime metadata is vital to interacting with the blockchain. This guide introduces you to the tools and processes for generating and retrieving metadata, explains its role in application development, and outlines the additional APIs available for interacting with a Polkadot node. By mastering these components, you can ensure seamless communication between your applications and the blockchain. - -## Application Development - -You might not be directly involved in building frontend applications as a blockchain developer. However, most applications that run on a blockchain require some form of frontend or user-facing client to enable users or other programs to access and modify the data that the blockchain stores. For example, you might develop a browser-based, mobile, or desktop application that allows users to submit transactions, post articles, view their assets, or track previous activity. The backend for that application is configured in the runtime logic for your blockchain, but the frontend client makes the runtime features accessible to your users. - -For your custom chain to be useful to others, you'll need to provide a client application that allows users to view, interact with, or update information that the blockchain keeps track of. In this article, you'll learn how to expose information about your runtime so that client applications can use it, see examples of the information exposed, and explore tools and libraries that use it. - -## Understand Metadata - -Polkadot SDK-based blockchain networks are designed to expose their runtime information, allowing developers to learn granular details regarding pallets, RPC calls, and runtime APIs. The metadata also exposes their related documentation. The chain's metadata is [SCALE-encoded](/reference/parachains/data-encoding/){target=\_blank}, allowing for the development of browser-based, mobile, or desktop applications to support the chain's runtime upgrades seamlessly. It is also possible to develop applications compatible with multiple Polkadot SDK-based chains simultaneously. - -## Expose Runtime Information as Metadata - -To interact with a node or the state of the blockchain, you need to know how to connect to the chain and access the exposed runtime features. This interaction involves a Remote Procedure Call (RPC) through a node endpoint address, commonly through a secure web socket connection. - -An application developer typically needs to know the contents of the runtime logic, including the following details: - -- Version of the runtime the application is connecting to. -- Supported APIs. -- Implemented pallets. -- Defined functions and corresponding type signatures. -- Defined custom types. -- Exposed parameters users can set. - -As the Polkadot SDK is modular and provides a composable framework for building blockchains, there are limitless opportunities to customize the schema of properties. Each runtime can be configured with its properties, including function calls and types, which can be changed over time with runtime upgrades. - -The Polkadot SDK enables you to generate the runtime metadata schema to capture information unique to a runtime. The metadata for a runtime describes the pallets in use and types defined for a specific runtime version. The metadata includes information about each pallet's storage items, functions, events, errors, and constants. The metadata also provides type definitions for any custom types included in the runtime. - -Metadata provides a complete inventory of a chain's runtime. It is key to enabling client applications to interact with the node, parse responses, and correctly format message payloads sent back to that chain. - -## Generate Metadata - -To efficiently use the blockchain's networking resources and minimize the data transmitted over the network, the metadata schema is encoded using the [Parity SCALE Codec](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank}. This encoding is done automatically through the [`scale-info`](https://docs.rs/scale-info/latest/scale_info/){target=\_blank}crate. - -At a high level, generating the metadata involves the following steps: - -1. The pallets in the runtime logic expose callable functions, types, parameters, and documentation that need to be encoded in the metadata. -2. The `scale-info` crate collects type information for the pallets in the runtime, builds a registry of the pallets that exist in a particular runtime, and the relevant types for each pallet in the registry. The type information is detailed enough to enable encoding and decoding for every type. -3. The [`frame-metadata`](https://github.com/paritytech/frame-metadata){target=\_blank} crate describes the structure of the runtime based on the registry provided by the `scale-info` crate. -4. Nodes provide the RPC method `state_getMetadata` to return a complete description of all the types in the current runtime as a hex-encoded vector of SCALE-encoded bytes. - -## Retrieve Runtime Metadata - -The type information provided by the metadata enables applications to communicate with nodes using different runtime versions and across chains that expose different calls, events, types, and storage items. The metadata also allows libraries to generate a substantial portion of the code needed to communicate with a given node, enabling libraries like [`subxt`](https://github.com/paritytech/subxt){target=\_blank} to generate frontend interfaces that are specific to a target chain. - -### Use Polkadot.js - -Visit the [Polkadot.js Portal](https://polkadot.js.org/apps/#/rpc){target=\_blank} and select the **Developer** dropdown in the top banner. Select **RPC Calls** to make the call to request metadata. Follow these steps to make the RPC call: - -1. Select **state** as the endpoint to call. -2. Select **`getMetadata(at)`** as the method to call. -3. Click **Submit RPC call** to submit the call and return the metadata in JSON format. - -### Use Curl - -You can fetch the metadata for the network by calling the node's RPC endpoint. This request returns the metadata in bytes rather than human-readable JSON: - -```sh -curl -H "Content-Type: application/json" \ --d '{"id":1, "jsonrpc":"2.0", "method": "state_getMetadata"}' \ -https://rpc.polkadot.io - -``` - -### Use Subxt - -[`subxt`](https://github.com/paritytech/subxt){target=\_blank} may also be used to fetch the metadata of any data in a human-readable JSON format: - -```sh -subxt metadata --url wss://rpc.polkadot.io --format json > spec.json -``` - -Another option is to use the [`subxt` explorer web UI](https://paritytech.github.io/subxt-explorer/#/){target=\_blank}. - -## Client Applications and Metadata - -The metadata exposes the expected way to decode each type, meaning applications can send, retrieve, and process application information without manual encoding and decoding. Client applications must use the [SCALE codec library](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank} to encode and decode RPC payloads to use the metadata. Client applications use the metadata to interact with the node, parse responses, and format message payloads sent to the node. - -## Metadata Format - -Although the SCALE-encoded bytes can be decoded using the `frame-metadata` and [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} libraries, there are other tools, such as `subxt` and the Polkadot-JS API, that can convert the raw data to human-readable JSON format. - -The types and type definitions included in the metadata returned by the `state_getMetadata` RPC call depend on the runtime's metadata version. - -In general, the metadata includes the following information: - -- A constant identifying the file as containing metadata. -- The version of the metadata format used in the runtime. -- Type definitions for all types used in the runtime and generated by the `scale-info` crate. -- Pallet information for the pallets included in the runtime in the order that they are defined in the `construct_runtime` macro. - -!!!tip - Depending on the frontend library used (such as the [Polkadot API](https://papi.how/){target=\_blank}), they may format the metadata differently than the raw format shown. - -The following example illustrates a condensed and annotated section of metadata decoded and converted to JSON: - -```json -[ - 1635018093, - { - "V14": { - "types": { - "types": [{}] - }, - "pallets": [{}], - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [{}] - }, - "ty": 141 - } - } -] - -``` - -The constant `1635018093` is a magic number that identifies the file as a metadata file. The rest of the metadata is divided into the `types`, `pallets`, and `extrinsic` sections: - -- The `types` section contains an index of the types and information about each type's type signature. -- The `pallets` section contains information about each pallet in the runtime. -- The `extrinsic` section describes the type identifier and transaction format version that the runtime uses. - -Different extrinsic versions can have varying formats, especially when considering [signed transactions](/reference/parachains/blocks-transactions-fees/transactions/#signed-transactions){target=\_blank}. - -### Pallets - -The following is a condensed and annotated example of metadata for a single element in the `pallets` array (the [`sudo`](https://paritytech.github.io/polkadot-sdk/master/pallet_sudo/index.html){target=\_blank} pallet): - -```json -{ - "name": "Sudo", - "storage": { - "prefix": "Sudo", - "entries": [ - { - "name": "Key", - "modifier": "Optional", - "ty": { - "Plain": 0 - }, - "default": [0], - "docs": ["The `AccountId` of the sudo key."] - } - ] - }, - "calls": { - "ty": 117 - }, - "event": { - "ty": 42 - }, - "constants": [], - "error": { - "ty": 124 - }, - "index": 8 -} - -``` - -Every element metadata contains the name of the pallet it represents and information about its storage, calls, events, and errors. You can look up details about the definition of the calls, events, and errors by viewing the type index identifier. The type index identifier is the `u32` integer used to access the type information for that item. For example, the type index identifier for calls in the Sudo pallet is 117. If you view information for that type identifier in the `types` section of the metadata, it provides information about the available calls, including the documentation for each call. - -For example, the following is a condensed excerpt of the calls for the Sudo pallet: - -```json -{ - "id": 117, - "type": { - "path": ["pallet_sudo", "pallet", "Call"], - "params": [ - { - "name": "T", - "type": null - } - ], - "def": { - "variant": { - "variants": [ - { - "name": "sudo", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 0, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "sudo_unchecked_weight", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - }, - { - "name": "weight", - "type": 8, - "typeName": "Weight" - } - ], - "index": 1, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "set_key", - "fields": [ - { - "name": "new", - "type": 103, - "typeName": "AccountIdLookupOf" - } - ], - "index": 2, - "docs": [ - "Authenticates current sudo key, sets the given AccountId (`new`) as the new sudo" - ] - }, - { - "name": "sudo_as", - "fields": [ - { - "name": "who", - "type": 103, - "typeName": "AccountIdLookupOf" - }, - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 3, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Signed` origin from a given account" - ] - } - ] - } - } - } -} - -``` - -For each field, you can access type information and metadata for the following: - -- **Storage metadata**: Provides the information required to enable applications to get information for specific storage items. -- **Call metadata**: Includes information about the runtime calls defined by the `#[pallet]` macro including call names, arguments and documentation. -- **Event metadata**: Provides the metadata generated by the `#[pallet::event]` macro, including the name, arguments, and documentation for each pallet event. -- **Constants metadata**: Provides metadata generated by the `#[pallet::constant]` macro, including the name, type, and hex-encoded value of the constant. -- **Error metadata**: Provides metadata generated by the `#[pallet::error]` macro, including the name and documentation for each pallet error. - -!!!tip - Type identifiers change from time to time, so you should avoid relying on specific type identifiers in your applications. - -### Extrinsic - -The runtime generates extrinsic metadata and provides useful information about transaction format. When decoded, the metadata contains the transaction version and the list of signed extensions. - -For example: - -```json -{ - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [ - { - "identifier": "CheckNonZeroSender", - "ty": 132, - "additional_signed": 41 - }, - { - "identifier": "CheckSpecVersion", - "ty": 133, - "additional_signed": 4 - }, - { - "identifier": "CheckTxVersion", - "ty": 134, - "additional_signed": 4 - }, - { - "identifier": "CheckGenesis", - "ty": 135, - "additional_signed": 11 - }, - { - "identifier": "CheckMortality", - "ty": 136, - "additional_signed": 11 - }, - { - "identifier": "CheckNonce", - "ty": 138, - "additional_signed": 41 - }, - { - "identifier": "CheckWeight", - "ty": 139, - "additional_signed": 41 - }, - { - "identifier": "ChargeTransactionPayment", - "ty": 140, - "additional_signed": 41 - } - ] - }, - "ty": 141 -} - -``` - -The type system is [composite](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/frame_runtime_types/index.html){target=\_blank}, meaning each type identifier contains a reference to a specific type or to another type identifier that provides information about the associated primitive types. - -For example, you can encode the `BitVec` type, but to decode it properly, you must know the types used for the `Order` and `Store` types. To find type information for `Order` and `Store`, you can use the path in the decoded JSON to locate their type identifiers. - -## Included RPC APIs - -A standard node comes with the following APIs to interact with a node: - -- **[`AuthorApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/author/trait.AuthorApiServer.html){target=\_blank}**: Make calls into a full node, including authoring extrinsics and verifying session keys. -- **[`ChainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/chain/trait.ChainApiServer.html){target=\_blank}**: Retrieve block header and finality information. -- **[`OffchainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/offchain/trait.OffchainApiServer.html){target=\_blank}**: Make RPC calls for off-chain workers. -- **[`StateApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/state/trait.StateApiServer.html){target=\_blank}**: Query information about on-chain state such as runtime version, storage items, and proofs. -- **[`SystemApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/system/trait.SystemApiServer.html){target=\_blank}**: Retrieve information about network state, such as connected peers and node roles. - -## Additional Resources - -The following tools can help you locate and decode metadata: - -- [Subxt Explorer](https://paritytech.github.io/subxt-explorer/#/){target=\_blank} -- [Metadata Portal 🌗](https://github.com/paritytech/metadata-portal){target=\_blank} -- [De[code] Sub[strate]](https://github.com/paritytech/desub){target=\_blank} - - --- Page Title: Contract Deployment @@ -1018,280 +584,6 @@ Both REVM and PolkaVM deployments may show significant differences between gas e Both backends support contract deployment effectively, with REVM offering drop-in Ethereum compatibility and PolkaVM providing a more structured two-step approach. For the majority of use cases—deploying standard contracts like tokens or applications—both backends work seamlessly. Advanced patterns like factory contracts may require adjustment for PolkaVM, but these adaptations are straightforward with proper planning. ---- - -Page Title: Cryptography - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-cryptography.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/cryptography/ -- Summary: A concise guide to cryptography in blockchain, covering hash functions, encryption types, digital signatures, and elliptic curve applications. - -# Cryptography - -## Introduction - -Cryptography forms the backbone of blockchain technology, providing the mathematical verifiability crucial for consensus systems, data integrity, and user security. While a deep understanding of the underlying mathematical processes isn't necessary for most blockchain developers, grasping the fundamental applications of cryptography is essential. This page comprehensively overviews cryptographic implementations used across Polkadot SDK-based chains and the broader blockchain ecosystem. - -## Hash Functions - -Hash functions are fundamental to blockchain technology, creating a unique digital fingerprint for any piece of data, including simple text, images, or any other form of file. They map input data of any size to a fixed-size output (typically 32 bytes) using complex mathematical operations. Hashing is used to verify data integrity, create digital signatures, and provide a secure way to store passwords. This form of mapping is known as the ["pigeonhole principle,"](https://en.wikipedia.org/wiki/Pigeonhole_principle){target=\_blank} it is primarily implemented to efficiently and verifiably identify data from large sets. - -### Key Properties of Hash Functions - -- **Deterministic**: The same input always produces the same output. -- **Quick computation**: It's easy to calculate the hash value for any given input. -- **Pre-image resistance**: It's infeasible to generate the input data from its hash. -- **Small changes in input yield large changes in output**: Known as the ["avalanche effect"](https://en.wikipedia.org/wiki/Avalanche_effect){target=\_blank}. -- **Collision resistance**: The probabilities are extremely low to find two different inputs with the same hash. - -### Blake2 - -The Polkadot SDK utilizes Blake2, a state-of-the-art hashing method that offers: - -- Equal or greater security compared to [SHA-2](https://en.wikipedia.org/wiki/SHA-2){target=\_blank}. -- Significantly faster performance than other algorithms. - -These properties make Blake2 ideal for blockchain systems, reducing sync times for new nodes and lowering the resources required for validation. For detailed technical specifications about Blake2, see the [official Blake2 paper](https://www.blake2.net/blake2.pdf){target=\_blank}. - -## Types of Cryptography - -There are two different ways that cryptographic algorithms are implemented: symmetric cryptography and asymmetric cryptography. - -### Symmetric Cryptography - -Symmetric encryption is a branch of cryptography that isn't based on one-way functions, unlike asymmetric cryptography. It uses the same cryptographic key to encrypt plain text and decrypt the resulting ciphertext. - -Symmetric cryptography is a type of encryption that has been used throughout history, such as the Enigma Cipher and the Caesar Cipher. It is still widely used today and can be found in Web2 and Web3 applications alike. There is only one single key, and a recipient must also have access to it to access the contained information. - -#### Advantages {: #symmetric-advantages } - -- Fast and efficient for large amounts of data. -- Requires less computational power. - -#### Disadvantages {: #symmetric-disadvantages } - -- Key distribution can be challenging. -- Scalability issues in systems with many users. - -### Asymmetric Cryptography - -Asymmetric encryption is a type of cryptography that uses two different keys, known as a keypair: a public key, used to encrypt plain text, and a private counterpart, used to decrypt the ciphertext. - -The public key encrypts a fixed-length message that can only be decrypted with the recipient's private key and, sometimes, a set password. The public key can be used to cryptographically verify that the corresponding private key was used to create a piece of data without compromising the private key, such as with digital signatures. This has obvious implications for identity, ownership, and properties and is used in many different protocols across Web2 and Web3. - -#### Advantages {: #asymmetric-advantages } - -- Solves the key distribution problem. -- Enables digital signatures and secure key exchange. - -#### Disadvantages {: #asymmetric-disadvantages } - -- Slower than symmetric encryption. -- Requires more computational resources. - -### Trade-offs and Compromises - -Symmetric cryptography is faster and requires fewer bits in the key to achieve the same level of security that asymmetric cryptography provides. However, it requires a shared secret before communication can occur, which poses issues to its integrity and a potential compromise point. On the other hand, asymmetric cryptography doesn't require the secret to be shared ahead of time, allowing for far better end-user security. - -Hybrid symmetric and asymmetric cryptography is often used to overcome the engineering issues of asymmetric cryptography, as it is slower and requires more bits in the key to achieve the same level of security. It encrypts a key and then uses the comparatively lightweight symmetric cipher to do the "heavy lifting" with the message. - -## Digital Signatures - -Digital signatures are a way of verifying the authenticity of a document or message using asymmetric keypairs. They are used to ensure that a sender or signer's document or message hasn't been tampered with in transit, and for recipients to verify that the data is accurate and from the expected sender. - -Signing digital signatures only requires a low-level understanding of mathematics and cryptography. For a conceptual example -- when signing a check, it is expected that it cannot be cashed multiple times. This isn't a feature of the signature system but rather the check serialization system. The bank will check that the serial number on the check hasn't already been used. Digital signatures essentially combine these two concepts, allowing the signature to provide the serialization via a unique cryptographic fingerprint that cannot be reproduced. - -Unlike pen-and-paper signatures, knowledge of a digital signature cannot be used to create other signatures. Digital signatures are often used in bureaucratic processes, as they are more secure than simply scanning in a signature and pasting it onto a document. - -Polkadot SDK provides multiple different cryptographic schemes and is generic so that it can support anything that implements the [`Pair` trait](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Pair.html){target=\_blank}. - -### Example of Creating a Digital Signature - -The process of creating and verifying a digital signature involves several steps: - -1. The sender creates a hash of the message. -2. The hash is encrypted using the sender's private key, creating the signature. -3. The message and signature are sent to the recipient. -4. The recipient decrypts the signature using the sender's public key. -5. The recipient hashes the received message and compares it to the decrypted hash. - -If the hashes match, the signature is valid, confirming the message's integrity and the sender's identity. - -## Elliptic Curve - -Blockchain technology requires the ability to have multiple keys creating a signature for block proposal and validation. To this end, Elliptic Curve Digital Signature Algorithm (ECDSA) and Schnorr signatures are two of the most commonly used methods. While ECDSA is a far simpler implementation, Schnorr signatures are more efficient when it comes to multi-signatures. - -Schnorr signatures bring some noticeable features over the ECDSA/EdDSA schemes: - -- It is better for hierarchical deterministic key derivations. -- It allows for native multi-signature through [signature aggregation](https://bitcoincore.org/en/2017/03/23/schnorr-signature-aggregation/){target=\_blank}. -- It is generally more resistant to misuse. - -One sacrifice that is made when using Schnorr signatures over ECDSA is that both require 64 bytes, but only ECDSA signatures communicate their public key. - -### Various Implementations - -- **[ECDSA](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm){target=\_blank}**: Polkadot SDK provides an ECDSA signature scheme using the [secp256k1](https://en.bitcoin.it/wiki/Secp256k1){target=\_blank} curve. This is the same cryptographic algorithm used to secure [Bitcoin](https://en.wikipedia.org/wiki/Bitcoin){target=\_blank} and [Ethereum](https://en.wikipedia.org/wiki/Ethereum){target=\_blank}. - -- **[Ed25519](https://en.wikipedia.org/wiki/EdDSA#Ed25519){target=\_blank}**: An EdDSA signature scheme using [Curve25519](https://en.wikipedia.org/wiki/Curve25519){target=\_blank}. It is carefully engineered at several levels of design and implementation to achieve very high speeds without compromising security. - -- **[SR25519](https://research.web3.foundation/Polkadot/security/keys/accounts-more){target=\_blank}**: Based on the same underlying curve as Ed25519. However, it uses Schnorr signatures instead of the EdDSA scheme. - - ---- - -Page Title: Data Encoding - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-data-encoding.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/data-encoding/ -- Summary: SCALE codec enables fast, efficient data encoding, ideal for resource-constrained environments like Wasm, supporting custom types and compact encoding. - -# Data Encoding - -## Introduction - -The Polkadot SDK uses a lightweight and efficient encoding/decoding mechanism to optimize data transmission across the network. This mechanism, known as the _SCALE_ codec, is used for serializing and deserializing data. - -The SCALE codec enables communication between the runtime and the outer node. This mechanism is designed for high-performance, copy-free data encoding and decoding in resource-constrained environments like the Polkadot SDK [Wasm runtime](/develop/parachains/deployment/build-deterministic-runtime/#introduction){target=\_blank}. - -It is not self-describing, meaning the decoding context must fully know the encoded data types. - -Parity's libraries utilize the [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} crate (a Rust implementation of the SCALE codec) to handle encoding and decoding for interactions between RPCs and the runtime. - -The `codec` mechanism is ideal for Polkadot SDK-based chains because: - -- It is lightweight compared to generic serialization frameworks like [`serde`](https://serde.rs/){target=\_blank}, which add unnecessary bulk to binaries. -- It doesn’t rely on Rust’s `libstd`, making it compatible with `no_std` environments like Wasm runtime. -- It integrates seamlessly with Rust, allowing easy derivation of encoding and decoding logic for new types using `#[derive(Encode, Decode)]`. - -Defining a custom encoding scheme in the Polkadot SDK-based chains, rather than using an existing Rust codec library, is crucial for enabling cross-platform and multi-language support. - -## SCALE Codec - -The codec is implemented using the following traits: - -- [`Encode`](#encode) -- [`Decode`](#decode) -- [`CompactAs`](#compactas) -- [`HasCompact`](#hascompact) -- [`EncodeLike`](#encodelike) - -### Encode - -The [`Encode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Encode.html){target=\_blank} trait handles data encoding into SCALE format and includes the following key functions: - -- **`size_hint(&self) -> usize`**: Estimates the number of bytes required for encoding to prevent multiple memory allocations. This should be inexpensive and avoid complex operations. Optional if the size isn’t known. -- **`encode_to(&self, dest: &mut T)`**: Encodes the data, appending it to a destination buffer. -- **`encode(&self) -> Vec`**: Encodes the data and returns it as a byte vector. -- **`using_encoded R>(&self, f: F) -> R`**: Encodes the data and passes it to a closure, returning the result. -- **`encoded_size(&self) -> usize`**: Calculates the encoded size. Should be used when the encoded data isn’t required. - -!!!tip - For best performance, value types should override `using_encoded`, and allocating types should override `encode_to`. It's recommended to implement `size_hint` for all types where possible. - -### Decode - -The [`Decode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Decode.html){target=\_blank} trait handles decoding SCALE-encoded data back into the appropriate types: - -- **`fn decode(value: &mut I) -> Result`**: Decodes data from the SCALE format, returning an error if decoding fails. - -### CompactAs - -The [`CompactAs`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.CompactAs.html){target=\_blank} trait wraps custom types for compact encoding: - -- **`encode_as(&self) -> &Self::As`**: Encodes the type as a compact type. -- **`decode_from(_: Self::As) -> Result`**: decodes from a compact encoded type. - -### HasCompact - -The [`HasCompact`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.HasCompact.html){target=\_blank} trait indicates a type supports compact encoding. - -### EncodeLike - -The [`EncodeLike`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.EncodeLike.html){target=\_blank} trait is used to ensure multiple types that encode similarly are accepted by the same function. When using `derive`, it is automatically implemented. - -### Data Types - -The table below outlines how the Rust implementation of the Parity SCALE codec encodes different data types. - -| Type | Description | Example SCALE Decoded Value | SCALE Encoded Value | -|-------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------| -| Boolean | Boolean values are encoded using the least significant bit of a single byte. | `false` / `true` | `0x00` / `0x01` | -| Compact/general integers | A "compact" or general integer encoding is sufficient for encoding large integers (up to 2^536) and is more efficient at encoding most values than the fixed-width version. | `unsigned integer 0` / `unsigned integer 1` / `unsigned integer 42` / `unsigned integer 69` / `unsigned integer 65535` / `BigInt(100000000000000)` | `0x00` / `0x04` / `0xa8` / `0x1501` / `0xfeff0300` / `0x0b00407a10f35a` | -| Enumerations (tagged-unions) | A fixed number of variants, each mutually exclusive and potentially implying a further value or series of values. Encoded as the first byte identifying the index of the variant that the value is. Any further bytes are used to encode any data that the variant implies. Thus, no more than 256 variants are supported. | `Int(42)` and `Bool(true)` where `enum IntOrBool { Int(u8), Bool(bool) }` | `0x002a` and `0x0101` | -| Fixed-width integers | Basic integers are encoded using a fixed-width little-endian (LE) format. | `signed 8-bit integer 69` / `unsigned 16-bit integer 42` / `unsigned 32-bit integer 16777215` | `0x45` / `0x2a00` / `0xffffff00` | -| Options | One or zero values of a particular type. | `Some` / `None` | `0x01` followed by the encoded value / `0x00` | -| Results | Results are commonly used enumerations which indicate whether certain operations were successful or unsuccessful. | `Ok(42)` / `Err(false)` | `0x002a` / `0x0100` | -| Strings | Strings are Vectors of bytes (Vec) containing a valid UTF8 sequence. | | | -| Structs | For structures, the values are named, but that is irrelevant for the encoding (names are ignored - only order matters). | `SortedVecAsc::from([3, 5, 2, 8])` | `[3, 2, 5, 8] ` | -| Tuples | A fixed-size series of values, each with a possibly different but predetermined and fixed type. This is simply the concatenation of each encoded value. | Tuple of compact unsigned integer and boolean: `(3, false)` | `0x0c00` | -| Vectors (lists, series, sets) | A collection of same-typed values is encoded, prefixed with a compact encoding of the number of items, followed by each item's encoding concatenated in turn. | Vector of unsigned `16`-bit integers: `[4, 8, 15, 16, 23, 42]` | `0x18040008000f00100017002a00` | - -## Encode and Decode Rust Trait Implementations - -Here's how the `Encode` and `Decode` traits are implemented: - - -```rust -use parity_scale_codec::{Encode, Decode}; - -[derive(Debug, PartialEq, Encode, Decode)] -enum EnumType { - #[codec(index = 15)] - A, - B(u32, u64), - C { - a: u32, - b: u64, - }, -} - -let a = EnumType::A; -let b = EnumType::B(1, 2); -let c = EnumType::C { a: 1, b: 2 }; - -a.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x0f"); -}); - -b.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); - -c.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); - -let mut da: &[u8] = b"\x0f"; -assert_eq!(EnumType::decode(&mut da).ok(), Some(a)); - -let mut db: &[u8] = b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut db).ok(), Some(b)); - -let mut dc: &[u8] = b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut dc).ok(), Some(c)); - -let mut dz: &[u8] = &[0]; -assert_eq!(EnumType::decode(&mut dz).ok(), None); -``` - -## SCALE Codec Libraries - -Several SCALE codec implementations are available in various languages. Here's a list of them: - -- **AssemblyScript**: [`LimeChain/as-scale-codec`](https://github.com/LimeChain/as-scale-codec){target=\_blank} -- **C**: [`MatthewDarnell/cScale`](https://github.com/MatthewDarnell/cScale){target=\_blank} -- **C++**: [`qdrvm/scale-codec-cpp`](https://github.com/qdrvm/scale-codec-cpp){target=\_blank} -- **JavaScript**: [`polkadot-js/api`](https://github.com/polkadot-js/api){target=\_blank} -- **Dart**: [`leonardocustodio/polkadart`](https://github.com/leonardocustodio/polkadart){target=\_blank} -- **Haskell**: [`airalab/hs-web3`](https://github.com/airalab/hs-web3/tree/master/packages/scale){target=\_blank} -- **Golang**: [`itering/scale.go`](https://github.com/itering/scale.go){target=\_blank} -- **Java**: [`splix/polkaj`](https://github.com/splix/polkaj){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **Ruby**: [` wuminzhe/scale_rb`](https://github.com/wuminzhe/scale_rb){target=\_blank} -- **TypeScript**: [`parity-scale-codec-ts`](https://github.com/tjjfvi/subshape){target=\_blank}, [`scale-ts`](https://github.com/unstoppablejs/unstoppablejs/tree/main/packages/scale-ts#scale-ts){target=\_blank}, [`soramitsu/scale-codec-js-library`](https://github.com/soramitsu/scale-codec-js-library){target=\_blank}, [`subsquid/scale-codec`](https://github.com/subsquid/squid-sdk/tree/master/substrate/scale-codec){target=\_blank} - - --- Page Title: Deploy an ERC-20 to Polkadot Hub @@ -2374,31 +1666,159 @@ From here, follow the quick starts to get connected, iterate locally with your p --- -Page Title: Install Polkadot SDK +Page Title: Get Started with XCM -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-install-polkadot-sdk.md -- Canonical (HTML): https://docs.polkadot.com/parachains/install-polkadot-sdk/ -- Summary: Install all required Polkadot SDK dependencies, set up the SDK itself, and verify that it runs correctly on your machine. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md +- Canonical (HTML): https://docs.polkadot.com/parachains/interoperability/get-started/ +- Summary: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. -# Install Polkadot SDK +# Get Started with XCM -This guide provides step-by-step instructions for installing the Polkadot SDK on macOS, Linux, and Windows. The installation process consists of two main parts: +## Introduction -- **Installing dependencies**: Setting up Rust, required system packages, and development tools. -- **Building the Polkadot SDK**: Cloning and compiling the Polkadot SDK repository. +Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems. -Follow the appropriate section for your operating system to ensure all necessary tools are installed and configured properly. +With XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation. -## Install Dependencies: macOS +## Messaging Format -You can install Rust and set up a Substrate development environment on Apple macOS computers with Intel or Apple M1 processors. +XCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics. -### Before You Begin {: #before-you-begin-mac-os } +XCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing. -Before you install Rust and set up your development environment on macOS, verify that your computer meets the following basic requirements: +## The Four Principles of XCM -- Operating system version is 10.7 Lion or later. -- Processor speed of at least 2 GHz. Note that 3 GHz is recommended. +XCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems: + +- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes. +- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended. +- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin. +- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems. + +These principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments. + +## The XCM Tech Stack + +![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp) + +The XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels. + +## Core Functionalities of XCM + +XCM enhances cross-consensus communication by introducing several powerful features: + +- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management. +- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification. +- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location. + +The standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications. + +## XCM Example + +The following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA). + +```rust +let message = Xcm(vec![ + WithdrawAsset((Here, amount).into()), + BuyExecution { + fees: (Here, amount).into(), + weight_limit: WeightLimit::Unlimited + }, + DepositAsset { + assets: All.into(), + beneficiary: MultiLocation { + parents: 0, + interior: Junction::AccountId32 { + network: None, + id: BOB.clone().into() + }.into(), + }.into() + } +]); +``` + +The message consists of three instructions described as follows: + +- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register. + + ```rust + WithdrawAsset((Here, amount).into()), + ``` + + - **`Here`**: The native parachain token. + - **`amount`**: The number of tokens that are transferred. + + The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register. + +- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\_blank} of the XCM instructions. + + ```rust + BuyExecution { + fees: (Here, amount).into(), + weight_limit: WeightLimit::Unlimited + }, + ``` + + - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight. + - **`weight_limit`**: Defines the maximum fees that can be used to buy weight. + +- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\_blank}**: Moves the remaining tokens from the holding register to Bob’s account. + + ```rust + DepositAsset { + assets: All.into(), + beneficiary: MultiLocation { + parents: 0, + interior: Junction::AccountId32 { + network: None, + id: BOB.clone().into() + }.into(), + }.into() + } + ``` + + - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited. + +This step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. + +## Overview + +XCM revolutionizes cross-chain communication by enabling use cases such as: + +- Token transfers between blockchains. +- Asset locking for cross-chain smart contract interactions. +- Remote execution of functions on other blockchains. + +These functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. + + +--- + +Page Title: Install Polkadot SDK + +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-install-polkadot-sdk.md +- Canonical (HTML): https://docs.polkadot.com/parachains/install-polkadot-sdk/ +- Summary: Install all required Polkadot SDK dependencies, set up the SDK itself, and verify that it runs correctly on your machine. + +# Install Polkadot SDK + +This guide provides step-by-step instructions for installing the Polkadot SDK on macOS, Linux, and Windows. The installation process consists of two main parts: + +- **Installing dependencies**: Setting up Rust, required system packages, and development tools. +- **Building the Polkadot SDK**: Cloning and compiling the Polkadot SDK repository. + +Follow the appropriate section for your operating system to ensure all necessary tools are installed and configured properly. + +## Install Dependencies: macOS + +You can install Rust and set up a Substrate development environment on Apple macOS computers with Intel or Apple M1 processors. + +### Before You Begin {: #before-you-begin-mac-os } + +Before you install Rust and set up your development environment on macOS, verify that your computer meets the following basic requirements: + +- Operating system version is 10.7 Lion or later. +- Processor speed of at least 2 GHz. Note that 3 GHz is recommended. - Memory of at least 8 GB RAM. Note that 16 GB is recommended. - Storage of at least 10 GB of available space. - Broadband Internet connection. @@ -2796,1548 +2216,136 @@ To stop the node, press `Control-C` in the terminal. --- -Page Title: Interoperability +Page Title: Overview of FRAME -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-interoperability.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/interoperability/ -- Summary: Explore the importance of interoperability in the Polkadot ecosystem, covering XCM, bridges, and cross-chain communication. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime.md +- Canonical (HTML): https://docs.polkadot.com/parachains/customize-runtime/ +- Summary: Learn how Polkadot SDK’s FRAME framework simplifies blockchain development with modular pallets and support libraries for efficient runtime design. -# Interoperability +# Customize Your Runtime ## Introduction -Interoperability lies at the heart of the Polkadot ecosystem, enabling communication and collaboration across a diverse range of blockchains. By bridging the gaps between parachains, relay chains, and even external networks, Polkadot unlocks the potential for truly decentralized applications, efficient resource sharing, and scalable solutions. +A blockchain runtime is more than just a fixed set of rules—it's a dynamic foundation that you can shape to match your specific needs. With Polkadot SDK's [FRAME (Framework for Runtime Aggregation of Modularized Entities)](/reference/glossary/#frame-framework-for-runtime-aggregation-of-modularized-entities){target=\_blank}, customizing your runtime is straightforward and modular. Instead of building everything from scratch, you combine pre-built pallets with your own custom logic to create a runtime suited to your blockchain's purpose. -Polkadot’s design ensures that blockchains can transcend their individual limitations by working together as part of a unified system. This cooperative architecture is what sets Polkadot apart in the blockchain landscape. +This overview explains how runtime customization works, introduces the building blocks you'll use, and guides you through the key patterns for extending your runtime. -## Why Interoperability Matters +## Understanding Your Runtime -The blockchain ecosystem is inherently fragmented. Different blockchains excel in specialized domains such as finance, gaming, or supply chain management, but these chains function in isolation without interoperability. This lack of connectivity stifles the broader utility of blockchain technology. +The runtime is the core logic of your blockchain—it processes transactions, manages state, and enforces the rules that govern your network. When a transaction arrives at your blockchain, the [`frame_executive`](https://paritytech.github.io/polkadot-sdk/master/frame_executive/index.html){target=\_blank} pallet receives it and routes it to the appropriate pallet for execution. -Interoperability solves this problem by enabling blockchains to: +Think of your runtime as a collection of specialized modules, each handling a different aspect of your blockchain. Need token balances? Use the Balances pallet. Want governance? Add the Governance pallets. Need something custom? Create your own pallet. By mixing and matching these modules, you build a runtime that's efficient, secure, and tailored to your use case. -- **Collaborate across networks**: Chains can interact to share assets, functionality, and data, creating synergies that amplify their individual strengths. -- **Achieve greater scalability**: Specialized chains can offload tasks to others, optimizing performance and resource utilization. -- **Expand use-case potential**: Cross-chain applications can leverage features from multiple blockchains, unlocking novel user experiences and solutions. +## Runtime Architecture -In the Polkadot ecosystem, interoperability transforms a collection of isolated chains into a cohesive, efficient network, pushing the boundaries of what blockchains can achieve together. +The following diagram shows how FRAME components work together to form your runtime: -## Key Mechanisms for Interoperability +![](/images/parachains/customize-runtime/index/frame-overview-01.webp) -At the core of Polkadot's cross-chain collaboration are foundational technologies designed to break down barriers between networks. These mechanisms empower blockchains to communicate, share resources, and operate as a cohesive ecosystem. +The main components are: -### Cross-Consensus Messaging (XCM): The Backbone of Communication +- **`frame_executive`**: Routes all incoming transactions to the correct pallet for execution. +- **Pallets**: Domain-specific modules that implement your blockchain's features and business logic. +- **`frame_system`**: Provides core runtime primitives and storage. +- **`frame_support`**: Utilities and macros that simplify pallet development. -Polkadot's Cross-Consensus Messaging (XCM) is the standard framework for interaction between parachains, relay chains, and, eventually, external blockchains. XCM provides a trustless, secure messaging format for exchanging assets, sharing data, and executing cross-chain operations. +## Building Blocks: Pallets -Through XCM, decentralized applications can: +[Pallets](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/pallet/index.html){target=\_blank} are the fundamental units of runtime customization. Each pallet encapsulates specific functionality and can be independently developed, tested, and integrated. -- Transfer tokens and other assets across chains. -- Coordinate complex workflows that span multiple blockchains. -- Enable seamless user experiences where underlying blockchain differences are invisible. -- XCM exemplifies Polkadot’s commitment to creating a robust and interoperable ecosystem. +A pallet can implement virtually any blockchain feature you need: -For further information about XCM, check the [Introduction to XCM](/parachains/interoperability/get-started/){target=\_blank} article. +- Expose new transactions that users can submit. +- Store data on-chain. +- Enforce business rules and validation logic. +- Emit events to notify users of state changes. +- Handle errors gracefully. -### Bridges: Connecting External Networks +### Pre-Built Pallets vs. Custom Pallets -While XCM enables interoperability within the Polkadot ecosystem, bridges extend this functionality to external blockchains such as Ethereum and Bitcoin. By connecting these networks, bridges allow Polkadot-based chains to access external liquidity, additional functionalities, and broader user bases. +FRAME provides a comprehensive library of [pre-built pallets](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame){target=\_blank} for common blockchain features, including consensus, staking, balances, governance, and more. These pallets are battle-tested, optimized, and ready to use. -With bridges, developers and users gain the ability to: +However, you're not limited to pre-built functionality. When pre-built pallets don't meet your needs, you can create custom pallets with entirely custom logic. The real power of FRAME is the flexibility to use pre-built modules for standard features while building your own for unique requirements. -- Integrate external assets into Polkadot-based applications. -- Combine the strengths of Polkadot’s scalability with the liquidity of other networks. -- Facilitate accurate multi-chain applications that transcend ecosystem boundaries. +### Pallet Structure -For more information about bridges in the Polkadot ecosystem, see the [Bridge Hub](/reference/polkadot-hub/bridging/){target=\_blank} guide. +FRAME uses Rust macros extensively, allowing you to focus on your pallet's logic while the framework handles boilerplate and integration code. -## The Polkadot Advantage +A typical pallet looks like this: -Polkadot was purpose-built for interoperability. Unlike networks that add interoperability as an afterthought, Polkadot integrates it as a fundamental design principle. This approach offers several distinct advantages: +```rust +pub use pallet::*; -- **Developer empowerment**: Polkadot’s interoperability tools allow developers to build applications that leverage multiple chains’ capabilities without added complexity. -- **Enhanced ecosystem collaboration**: Chains in Polkadot can focus on their unique strengths while contributing to the ecosystem’s overall growth. -- **Future-proofing blockchain**: By enabling seamless communication, Polkadot ensures its ecosystem can adapt to evolving demands and technologies. +#[frame_support::pallet] +pub mod pallet { + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; -## Looking Ahead + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(_); -Polkadot’s vision of interoperability extends beyond technical functionality, representing a shift towards a more collaborative blockchain landscape. By enabling chains to work together, Polkadot fosters innovation, efficiency, and accessibility, paving the way for a decentralized future where blockchains are not isolated competitors but interconnected collaborators. + #[pallet::config] // snip + #[pallet::event] // snip + #[pallet::error] // snip + #[pallet::storage] // snip + #[pallet::call] // snip +} +``` +Every pallet can implement these core macros: ---- +- **`#[frame_support::pallet]`**: Marks your module as a FRAME pallet. +- **`#[pallet::pallet]`**: Designates the struct that holds pallet metadata. +- **`#[pallet::config]`**: Defines configuration and associated types. +- **`#[pallet::event]`**: Defines events emitted by your pallet. +- **`#[pallet::error]`**: Defines error types your pallet can return. +- **`#[pallet::storage]`**: Defines on-chain storage items. +- **`#[pallet::call]`**: Defines dispatchable functions (transactions). -Page Title: Introduction to XCM +For a comprehensive reference, see the [`pallet_macros` documentation](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/index.html){target=\_blank}. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md -- Canonical (HTML): https://docs.polkadot.com/parachains/interoperability/get-started/ -- Summary: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. +## How Runtime Customization Works -# Introduction to XCM +Customizing your runtime typically follows these patterns: -## Introduction +**Adding Pre-Built Pallets**: Select pallets from the FRAME library and integrate them into your runtime configuration. This is the fastest way to add functionality. -Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems. +**Creating Custom Pallets**: Write custom pallets for features that don't exist in the pre-built library. Custom pallets follow the same structure as pre-built ones and integrate seamlessly. -With XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation. +**Combining Multiple Pallets**: Layer multiple pallets together to create complex behaviors. Pallets can call each other and share storage when needed. -## Messaging Format +**Configuring Pallet Parameters**: Most pallets are configurable—you can adjust their behavior through configuration traits without modifying their code. -XCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics. +The following diagram illustrates how pallets combine to form a complete runtime: -XCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing. +![](/images/parachains/customize-runtime/index/frame-overview-02.webp) -## The Four Principles of XCM +## Starting Templates -XCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems: +The easiest way to begin customizing your runtime is with a starter template. These templates provide a pre-configured foundation so you can focus on customization rather than setup. -- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes. -- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended. -- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin. -- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems. +- **[Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank}**: The recommended choice for most developers, it includes pre-configured pallets for common features (balances, block production, governance), a complete runtime setup, and built-in parachain consensus support. This template offers the best balance of features and learning opportunities. -These principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments. +- **[Polkadot SDK Minimal Template](https://github.com/paritytech/polkadot-sdk-minimal-template){target=\_blank}**: Provides a bare-bones runtime with only essential components. Choose this if you want maximum flexibility and prefer building from a clean slate. -## The XCM Tech Stack +- **[Polkadot SDK Solochain Template](https://github.com/paritytech/polkadot-sdk/tree/master/templates/solochain){target=\_blank}**: Designed for building standalone blockchains with moderate features, simple consensus, and several core pallets. Use this if you want a sovereign blockchain independent of a relay chain. -![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp) +- **[OpenZeppelin Runtime Templates](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\_blank}**: Provides security-focused configurations following industry best practices. The [generic-template](https://github.com/OpenZeppelin/polkadot-runtime-templates/tree/main/generic-template){target=\_blank} includes curated pallet selections and production-ready defaults—ideal if security is your top priority. -The XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels. +## Key Customization Scenarios -## Core Functionalities of XCM +This section covers the most common customization patterns you'll encounter: -XCM enhances cross-consensus communication by introducing several powerful features: +- **[Add Existing Pallets to Your Runtime](/parachains/customize-runtime/add-existing-pallets/)**: Integrate pre-built pallets from the FRAME library with minimal configuration. -- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management. -- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification. -- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location. +- **[Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/)**: Run multiple instances of the same pallet with different configurations—useful for multi-token systems or parallel features. -The standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications. +- **[Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/)**: Enable smart contract execution on your parachain using Contracts pallets. -## XCM Example +- **[Create Custom Pallets](/parachains/customize-runtime/pallet-development/create-a-pallet/)**: Build entirely custom pallets for features unique to your blockchain. -The following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA). - -```rust -let message = Xcm(vec![ - WithdrawAsset((Here, amount).into()), - BuyExecution { - fees: (Here, amount).into(), - weight_limit: WeightLimit::Unlimited - }, - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: Junction::AccountId32 { - network: None, - id: BOB.clone().into() - }.into(), - }.into() - } -]); -``` - -The message consists of three instructions described as follows: - -- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register. - - ```rust - WithdrawAsset((Here, amount).into()), - ``` - - - **`Here`**: The native parachain token. - - **`amount`**: The number of tokens that are transferred. - - The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register. - -- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\_blank} of the XCM instructions. - - ```rust - BuyExecution { - fees: (Here, amount).into(), - weight_limit: WeightLimit::Unlimited - }, - ``` - - - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight. - - **`weight_limit`**: Defines the maximum fees that can be used to buy weight. - -- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\_blank}**: Moves the remaining tokens from the holding register to Bob’s account. - - ```rust - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: Junction::AccountId32 { - network: None, - id: BOB.clone().into() - }.into(), - }.into() - } - ``` - - - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited. - -This step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - -## Overview - -XCM revolutionizes cross-chain communication by enabling use cases such as: - -- Token transfers between blockchains. -- Asset locking for cross-chain smart contract interactions. -- Remote execution of functions on other blockchains. - -These functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - - ---- - -Page Title: Networks - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-networks.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/networks/ -- Summary: Explore Polkadot's testing and production networks, including Westend, Kusama, and Paseo, for efficient development, deployment, and testing. - -# Networks - -## Introduction - -The Polkadot ecosystem is built on a robust set of networks designed to enable secure and scalable development. Whether you are testing new features or deploying to live production, Polkadot offers several layers of networks tailored for each stage of the development process. From local environments to experimental networks like Kusama and community-run TestNets such as Paseo, developers can thoroughly test, iterate, and validate their applications. This guide will introduce you to Polkadot's various networks and explain how they fit into the development workflow. - -## Network Overview - -Polkadot's development process is structured to ensure new features and upgrades are rigorously tested before being deployed on live production networks. The progression follows a well-defined path, starting from local environments and advancing through TestNets, ultimately reaching the Polkadot MainNet. The diagram below outlines the typical progression of the Polkadot development cycle: - -``` mermaid -flowchart LR - id1[Local] --> id2[Westend] --> id4[Kusama] --> id5[Polkadot] - id1[Local] --> id3[Paseo] --> id5[Polkadot] -``` - -This flow ensures developers can thoroughly test and iterate without risking real tokens or affecting production networks. Testing tools like [Chopsticks](#chopsticks) and various TestNets make it easier to experiment safely before releasing to production. - -A typical journey through the Polkadot core protocol development process might look like this: - -1. **Local development node**: Development starts in a local environment, where developers can create, test, and iterate on upgrades or new features using a local development node. This stage allows rapid experimentation in an isolated setup without any external dependencies. - -2. **Westend**: After testing locally, upgrades are deployed to [Westend](#westend), Polkadot's primary TestNet. Westend simulates real-world conditions without using real tokens, making it the ideal place for rigorous feature testing before moving on to production networks. - -3. **Kusama**: Once features have passed extensive testing on Westend, they move to Kusama, Polkadot's experimental and fast-moving "canary" network. Kusama operates as a high-fidelity testing ground with actual economic incentives, giving developers insights into how their features will perform in a real-world environment. - -4. **Polkadot**: After passing tests on Westend and Kusama, features are considered ready for deployment to Polkadot, the live production network. - - In addition, parachain developers can leverage local TestNets like [Zombienet](#zombienet) and deploy upgrades on parachain TestNets. - -5. **Paseo**: For parachain and dApp developers, Paseo serves as a community-run TestNet that mirrors Polkadot's runtime. Like Westend for core protocol development, Paseo provides a testing ground for parachain development without affecting live networks. - -!!!note - The Rococo TestNet deprecation date was October 14, 2024. Teams should use Westend for Polkadot protocol and feature testing and Paseo for chain development-related testing. - -## Polkadot Development Networks - -Development and testing are crucial to building robust dApps and parachains and performing network upgrades within the Polkadot ecosystem. To achieve this, developers can leverage various networks and tools that provide a risk-free environment for experimentation and validation before deploying features to live networks. These networks help avoid the costs and risks associated with real tokens, enabling testing for functionalities like governance, cross-chain messaging, and runtime upgrades. - -## Kusama Network - -Kusama is the experimental version of Polkadot, designed for developers who want to move quickly and test their applications in a real-world environment with economic incentives. Kusama serves as a production-grade testing ground where developers can deploy features and upgrades with the pressure of game theory and economics in mind. It mirrors Polkadot but operates as a more flexible space for innovation. - -The native token for Kusama is KSM. For more information about KSM, visit the [Native Assets](https://wiki.polkadot.com/kusama/kusama-getting-started/){target=\_blank} page. - -## Test Networks - -The following test networks provide controlled environments for testing upgrades and new features. TestNet tokens are available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}. - -### Westend - -Westend is Polkadot's primary permanent TestNet. Unlike temporary test networks, Westend is not reset to the genesis block, making it an ongoing environment for testing Polkadot core features. Managed by Parity Technologies, Westend ensures that developers can test features in a real-world simulation without using actual tokens. - -The native token for Westend is WND. More details about WND can be found on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_2){target=\_blank} page. - -### Paseo - -[Paseo](https://github.com/paseo-network){target=\_blank} is a community-managed TestNet designed for parachain and dApp developers. It mirrors Polkadot's runtime and is maintained by Polkadot community members. Paseo provides a dedicated space for parachain developers to test their applications in a Polkadot-like environment without the risks associated with live networks. - -The native token for Paseo is PAS. Additional information on PAS is available on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_1){target=\_blank} page. - -## Local Test Networks - -Local test networks are an essential part of the development cycle for blockchain developers using the Polkadot SDK. They allow for fast, iterative testing in controlled, private environments without connecting to public TestNets. Developers can quickly spin up local instances to experiment, debug, and validate their code before deploying to larger TestNets like Westend or Paseo. Two key tools for local network testing are Zombienet and Chopsticks. - -### Zombienet - -[Zombienet](https://github.com/paritytech/zombienet){target=\_blank} is a flexible testing framework for Polkadot SDK-based blockchains. It enables developers to create and manage ephemeral, short-lived networks. This feature makes Zombienet particularly useful for quick iterations, as it allows you to run multiple local networks concurrently, mimicking different runtime conditions. Whether you're developing a parachain or testing your custom blockchain logic, Zombienet gives you the tools to automate local testing. - -Key features of Zombienet include: - -- Creating dynamic, local networks with different configurations. -- Running parachains and relay chains in a simulated environment. -- Efficient testing of network components like cross-chain messaging and governance. - -Zombienet is ideal for developers looking to test quickly and thoroughly before moving to more resource-intensive public TestNets. - -### Chopsticks - -[Chopsticks](https://github.com/AcalaNetwork/chopsticks){target=\_blank} is a tool designed to create forks of Polkadot SDK-based blockchains, allowing developers to interact with network forks as part of their testing process. This capability makes Chopsticks a powerful option for testing upgrades, runtime changes, or cross-chain applications in a forked network environment. - -Key features of Chopsticks include: - -- Forking live Polkadot SDK-based blockchains for isolated testing. -- Simulating cross-chain messages in a private, controlled setup. -- Debugging network behavior by interacting with the fork in real-time. - -Chopsticks provides a controlled environment for developers to safely explore the effects of runtime changes. It ensures that network behavior is tested and verified before upgrades are deployed to live networks. - - ---- - -Page Title: Node and Runtime - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-node-and-runtime.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/node-and-runtime/ -- Summary: Learn how Polkadot SDK-based nodes function, how the client and runtime are separated, and how they communicate using SCALE-encoded data. - -# Node and Runtime - -## Introduction - -Every blockchain platform relies on a decentralized network of computers, called nodes, that communicate with each other about transactions and blocks. In this context, a node refers to the software running on the connected devices rather than the physical or virtual machines in the network. - -Polkadot SDK-based nodes consist of two main components, each with distinct responsibilities: the client (also called node) and the runtime. - -If the system were a monolithic protocol, any modification would require updating the entire system. Instead, Polkadot achieves true upgradeability by defining an immutable meta-protocol (the client) and a protocol (the runtime) that can be upgraded independently. - -This separation gives the [Polkadot Relay Chain](/polkadot-protocol/architecture/polkadot-chain){target=\_blank} and all connected [parachains](/polkadot-protocol/architecture/parachains){target=\_blank} an evolutionary advantage over other blockchain platforms. - -## Architectural Principles - -The Polkadot SDK-based blockchain architecture is fundamentally built on two distinct yet interconnected components: - -- Client (Meta-protocol): - - Handles the foundational infrastructure of the blockchain. - - Manages runtime execution, networking, consensus, and other off-chain components. - - Provides an immutable base layer that ensures network stability. - - Upgradable only through hard forks. - -- Runtime (Protocol): - - Defines the blockchain's state transition logic. - - Determines the specific rules and behaviors of the blockchain. - - Compiled to WebAssembly (Wasm) for platform-independent execution. - - Capable of being upgraded without network-wide forking. - -### Advantages of this Architecture - -- **Forkless upgrades**: Runtime can be updated without disrupting the entire network. -- **Modularity**: Clear separation allows independent development of client and runtime. -- **Flexibility**: Enables rapid iteration and evolution of blockchain logic. -- **Performance**: WebAssembly compilation provides efficient, cross-platform execution. - -## Node (Client) - -The node, also known as the client, is the core component responsible for executing the Wasm runtime and orchestrating various essential blockchain components. It ensures the correct execution of the state transition function and manages multiple critical subsystems, including: - -- **Wasm execution**: Runs the blockchain runtime, which defines the state transition rules. -- **Database management**: Stores blockchain data. -- **Networking**: Facilitates peer-to-peer communication, block propagation, and transaction gossiping. -- **Transaction pool (Mempool)**: Manages pending transactions before they are included in a block. -- **Consensus mechanism**: Ensures agreement on the blockchain state across nodes. -- **RPC services**: Provides external interfaces for applications and users to interact with the node. - -## Runtime - -The runtime is more than just a set of rules. It's the fundamental logic engine that defines a blockchain's entire behavior. In Polkadot SDK-based blockchains, the runtime represents a complete, self-contained description of the blockchain's state transition function. - -### Characteristics - -The runtime is distinguished by three key characteristics: - -- **Business logic**: Defines the complete application-specific blockchain behavior. -- **WebAssembly compilation**: Ensures platform-independent, secure execution. -- **On-chain storage**: Stored within the blockchain's state, allowing dynamic updates. - -### Key Functions - -The runtime performs several critical functions, such as: - -- Define state transition rules. -- Implement blockchain-specific logic. -- Manage account interactions. -- Control transaction processing. -- Define governance mechanisms. -- Handle custom pallets and modules. - -## Communication Between Node and Runtime - -The client and runtime communicate exclusively using [SCALE-encoded](/polkadot-protocol/parachain-basics/data-encoding){target=\_blank} communication. This ensures efficient and compact data exchange between the two components. - -### Runtime APIs - -The Runtime API consists of well-defined functions and constants a client assumes are implemented in the Runtime Wasm blob. These APIs enable the client to interact with the runtime to execute blockchain operations and retrieve information. The client invokes these APIs to: - -- Build, execute, and finalize blocks. -- Access metadata. -- Access consensus related information. -- Handle transaction execution. - -### Host Functions - -During execution, the runtime can access certain external client functionalities via host functions. The specific functions the client exposes allow the runtime to perform operations outside the WebAssembly domain. Host functions enable the runtime to: - -- Perform cryptographic operations. -- Access the current blockchain state. -- Handle storage modifications. -- Allocate memory. - - ---- - -Page Title: On-Chain Governance Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-governance.md -- Canonical (HTML): https://docs.polkadot.com/reference/governance/ -- Summary: Discover Polkadot’s cutting-edge OpenGov system, enabling transparent, decentralized decision-making through direct democracy and flexible governance tracks. - -# On-Chain Governance - -## Introduction - -Polkadot’s governance system exemplifies decentralized decision-making, empowering its community of stakeholders to shape the network’s future through active participation. The latest evolution, OpenGov, builds on Polkadot’s foundation by providing a more inclusive and efficient governance model. - -This guide will explain the principles and structure of OpenGov and walk you through its key components, such as Origins, Tracks, and Delegation. You will learn about improvements over earlier governance systems, including streamlined voting processes and enhanced stakeholder participation. - -With OpenGov, Polkadot achieves a flexible, scalable, and democratic governance framework that allows multiple proposals to proceed simultaneously, ensuring the network evolves in alignment with its community's needs. - -## Governance Evolution - -Polkadot’s governance journey began with [Governance V1](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#governance-summary){target=\_blank}, a system that proved effective in managing treasury funds and protocol upgrades. However, it faced limitations, such as: - -- Slow voting cycles, causing delays in decision-making. -- Inflexibility in handling multiple referendums, restricting scalability. - -To address these challenges, Polkadot introduced OpenGov, a governance model designed for greater inclusivity, efficiency, and scalability. OpenGov replaces the centralized structures of Governance V1, such as the Council and Technical Committee, with a fully decentralized and dynamic framework. - -For a full comparison of the historic and current governance models, visit the [Gov1 vs. Polkadot OpenGov](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#gov1-vs-polkadot-opengov){target=\_blank} section of the Polkadot Wiki. - -## OpenGov Key Features - -OpenGov transforms Polkadot’s governance into a decentralized, stakeholder-driven model, eliminating centralized decision-making bodies like the Council. Key enhancements include: - -- **Decentralization**: Shifts all decision-making power to the public, ensuring a more democratic process. -- **Enhanced delegation**: Allows users to delegate their votes to trusted experts across specific governance tracks. -- **Simultaneous referendums**: Multiple proposals can progress at once, enabling faster decision-making. -- **Polkadot Technical Fellowship**: A broad, community-driven group replacing the centralized Technical Committee. - -This new system ensures Polkadot governance remains agile and inclusive, even as the ecosystem grows. - -## Origins and Tracks - -In OpenGov, origins and tracks are central to managing proposals and votes. - -- **Origin**: Determines the authority level of a proposal (e.g., Treasury, Root) which decides the track of all referendums from that origin. -- **Track**: Define the procedural flow of a proposal, such as voting duration, approval thresholds, and enactment timelines. - -Developers must be aware that referendums from different origins and tracks will take varying amounts of time to reach approval and enactment. The [Polkadot Technical Fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} has the option to shorten this timeline by whitelisting a proposal and allowing it to be enacted through the [Whitelist Caller](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#whitelisted-caller){target=\_blank} origin. - -Visit [Origins and Tracks Info](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#origins-and-tracks){target=\_blank} for details on current origins and tracks, associated terminology, and parameters. - -## Referendums - -In OpenGov, anyone can submit a referendum, fostering an open and participatory system. The timeline for a referendum depends on the privilege level of the origin with more significant changes offering more time for community voting and participation before enactment. - -The timeline for an individual referendum includes four distinct periods: - -- **Lead-in**: A minimum amount of time to allow for community participation, available room in the origin, and payment of the decision deposit. Voting is open during this period. -- **Decision**: Voting continues. -- **Confirmation**: Referendum must meet [approval and support](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#approval-and-support){target=\_blank} criteria during entire period to avoid rejection. -- **Enactment**: Changes approved by the referendum are executed. - -### Vote on Referendums - -Voters can vote with their tokens on each referendum. Polkadot uses a voluntary token locking mechanism, called conviction voting, as a way for voters to increase their voting power. A token holder signals they have a stronger preference for approving a proposal based upon their willingness to lock up tokens. Longer voluntary token locks are seen as a signal of continual approval and translate to increased voting weight. - -See [Voting on a Referendum](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank} for a deeper look at conviction voting and related token locks. - -### Delegate Voting Power - -The OpenGov system also supports multi-role delegations, allowing token holders to assign their voting power on different tracks to entities with expertise in those areas. - -For example, if a token holder lacks the technical knowledge to evaluate proposals on the [Root track](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#root){target=\_blank}, they can delegate their voting power for that track to an expert they trust to vote in the best interest of the network. This ensures informed decision-making across tracks while maintaining flexibility for token holders. - -Visit [Multirole Delegation](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#multirole-delegation){target=\_blank} for more details on delegating voting power. - -### Cancel a Referendum - -Polkadot OpenGov has two origins for rejecting ongoing referendums: - -- [**Referendum Canceller**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-canceller){target=\_blank}: Cancels an active referendum when non-malicious errors occur and refunds the deposits to the originators. -- [**Referendum Killer**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-killer){target=\_blank}: Used for urgent, malicious cases this origin instantly terminates an active referendum and slashes deposits. - -See [Cancelling, Killing, and Blacklisting](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#cancelling-killing--blacklisting){target=\_blank} for additional information on rejecting referendums. - -## Additional Resources - -- **[Democracy pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/democracy/src){target=\_blank}**: Handles administration of general stakeholder voting. -- **[Gov2: Polkadot’s Next Generation of Decentralised Governance](https://medium.com/polkadot-network/gov2-polkadots-next-generation-of-decentralised-governance-4d9ef657d11b){target=\_blank}**: Medium article by Gavin Wood. -- **[Polkadot Direction](https://matrix.to/#/#Polkadot-Direction:parity.io){target=\_blank}**: Matrix Element client. -- **[Polkassembly](https://polkadot.polkassembly.io/){target=\_blank}**: OpenGov dashboard and UI. -- **[Polkadot.js Apps Governance](https://polkadot.js.org/apps/#/referenda){target=\_blank}**: Overview of active referendums. - - ---- - -Page Title: Overview of FRAME - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime.md -- Canonical (HTML): https://docs.polkadot.com/parachains/customize-runtime/ -- Summary: Learn how Polkadot SDK’s FRAME framework simplifies blockchain development with modular pallets and support libraries for efficient runtime design. - -# Customize Your Runtime - -## Introduction - -A blockchain runtime is more than just a fixed set of rules—it's a dynamic foundation that you can shape to match your specific needs. With Polkadot SDK's [FRAME (Framework for Runtime Aggregation of Modularized Entities)](/reference/glossary/#frame-framework-for-runtime-aggregation-of-modularized-entities){target=\_blank}, customizing your runtime is straightforward and modular. Instead of building everything from scratch, you combine pre-built pallets with your own custom logic to create a runtime suited to your blockchain's purpose. - -This overview explains how runtime customization works, introduces the building blocks you'll use, and guides you through the key patterns for extending your runtime. - -## Understanding Your Runtime - -The runtime is the core logic of your blockchain—it processes transactions, manages state, and enforces the rules that govern your network. When a transaction arrives at your blockchain, the [`frame_executive`](https://paritytech.github.io/polkadot-sdk/master/frame_executive/index.html){target=\_blank} pallet receives it and routes it to the appropriate pallet for execution. - -Think of your runtime as a collection of specialized modules, each handling a different aspect of your blockchain. Need token balances? Use the Balances pallet. Want governance? Add the Governance pallets. Need something custom? Create your own pallet. By mixing and matching these modules, you build a runtime that's efficient, secure, and tailored to your use case. - -## Runtime Architecture - -The following diagram shows how FRAME components work together to form your runtime: - -![](/images/parachains/customize-runtime/index/frame-overview-01.webp) - -The main components are: - -- **`frame_executive`**: Routes all incoming transactions to the correct pallet for execution. -- **Pallets**: Domain-specific modules that implement your blockchain's features and business logic. -- **`frame_system`**: Provides core runtime primitives and storage. -- **`frame_support`**: Utilities and macros that simplify pallet development. - -## Building Blocks: Pallets - -[Pallets](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/pallet/index.html){target=\_blank} are the fundamental units of runtime customization. Each pallet encapsulates specific functionality and can be independently developed, tested, and integrated. - -A pallet can implement virtually any blockchain feature you need: - -- Expose new transactions that users can submit. -- Store data on-chain. -- Enforce business rules and validation logic. -- Emit events to notify users of state changes. -- Handle errors gracefully. - -### Pre-Built Pallets vs. Custom Pallets - -FRAME provides a comprehensive library of [pre-built pallets](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame){target=\_blank} for common blockchain features, including consensus, staking, balances, governance, and more. These pallets are battle-tested, optimized, and ready to use. - -However, you're not limited to pre-built functionality. When pre-built pallets don't meet your needs, you can create custom pallets with entirely custom logic. The real power of FRAME is the flexibility to use pre-built modules for standard features while building your own for unique requirements. - -### Pallet Structure - -FRAME uses Rust macros extensively, allowing you to focus on your pallet's logic while the framework handles boilerplate and integration code. - -A typical pallet looks like this: - -```rust -pub use pallet::*; - -#[frame_support::pallet] -pub mod pallet { - use frame_support::pallet_prelude::*; - use frame_system::pallet_prelude::*; - - #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] - pub struct Pallet(_); - - #[pallet::config] // snip - #[pallet::event] // snip - #[pallet::error] // snip - #[pallet::storage] // snip - #[pallet::call] // snip -} -``` - -Every pallet can implement these core macros: - -- **`#[frame_support::pallet]`**: Marks your module as a FRAME pallet. -- **`#[pallet::pallet]`**: Designates the struct that holds pallet metadata. -- **`#[pallet::config]`**: Defines configuration and associated types. -- **`#[pallet::event]`**: Defines events emitted by your pallet. -- **`#[pallet::error]`**: Defines error types your pallet can return. -- **`#[pallet::storage]`**: Defines on-chain storage items. -- **`#[pallet::call]`**: Defines dispatchable functions (transactions). - -For a comprehensive reference, see the [`pallet_macros` documentation](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/index.html){target=\_blank}. - -## How Runtime Customization Works - -Customizing your runtime typically follows these patterns: - -**Adding Pre-Built Pallets**: Select pallets from the FRAME library and integrate them into your runtime configuration. This is the fastest way to add functionality. - -**Creating Custom Pallets**: Write custom pallets for features that don't exist in the pre-built library. Custom pallets follow the same structure as pre-built ones and integrate seamlessly. - -**Combining Multiple Pallets**: Layer multiple pallets together to create complex behaviors. Pallets can call each other and share storage when needed. - -**Configuring Pallet Parameters**: Most pallets are configurable—you can adjust their behavior through configuration traits without modifying their code. - -The following diagram illustrates how pallets combine to form a complete runtime: - -![](/images/parachains/customize-runtime/index/frame-overview-02.webp) - -## Starting Templates - -The easiest way to begin customizing your runtime is with a starter template. These templates provide a pre-configured foundation so you can focus on customization rather than setup. - -- **[Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank}**: The recommended choice for most developers, it includes pre-configured pallets for common features (balances, block production, governance), a complete runtime setup, and built-in parachain consensus support. This template offers the best balance of features and learning opportunities. - -- **[Polkadot SDK Minimal Template](https://github.com/paritytech/polkadot-sdk-minimal-template){target=\_blank}**: Provides a bare-bones runtime with only essential components. Choose this if you want maximum flexibility and prefer building from a clean slate. - -- **[Polkadot SDK Solochain Template](https://github.com/paritytech/polkadot-sdk/tree/master/templates/solochain){target=\_blank}**: Designed for building standalone blockchains with moderate features, simple consensus, and several core pallets. Use this if you want a sovereign blockchain independent of a relay chain. - -- **[OpenZeppelin Runtime Templates](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\_blank}**: Provides security-focused configurations following industry best practices. The [generic-template](https://github.com/OpenZeppelin/polkadot-runtime-templates/tree/main/generic-template){target=\_blank} includes curated pallet selections and production-ready defaults—ideal if security is your top priority. - -## Key Customization Scenarios - -This section covers the most common customization patterns you'll encounter: - -- **[Add Existing Pallets to Your Runtime](/parachains/customize-runtime/add-existing-pallets/)**: Integrate pre-built pallets from the FRAME library with minimal configuration. - -- **[Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/)**: Run multiple instances of the same pallet with different configurations—useful for multi-token systems or parallel features. - -- **[Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/)**: Enable smart contract execution on your parachain using Contracts pallets. - -- **[Create Custom Pallets](/parachains/customize-runtime/pallet-development/create-a-pallet/)**: Build entirely custom pallets for features unique to your blockchain. - -- **[Test Your Runtime](/parachains/customize-runtime/pallet-development/pallet-testing/)**: Unit test pallets and mock complete runtimes to ensure everything works correctly. - - ---- - -Page Title: Overview of the Polkadot Relay Chain - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-relay-chain.md -- Canonical (HTML): https://docs.polkadot.com/reference/polkadot-hub/consensus-and-security/relay-chain/ -- Summary: Explore Polkadot's core architecture, including its multi-chain vision, shared security, and the DOT token's governance and staking roles. - -# Overview - -## Introduction - -Polkadot is a next-generation blockchain protocol designed to support a multi-chain future by enabling secure communication and interoperability between different blockchains. Built as a Layer-0 protocol, Polkadot introduces innovations like application-specific Layer-1 chains ([parachains](/polkadot-protocol/architecture/parachains/){targe=\_blank}), shared security through [Nominated Proof of Stake (NPoS)](/reference/glossary/#nominated-proof-of-stake-npos){target=\_blank}, and cross-chain interactions via its native [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank}. - -This guide covers key aspects of Polkadot’s architecture, including its high-level protocol structure, blockspace commoditization, and the role of its native token, DOT, in governance, staking, and resource allocation. - -## Polkadot 1.0 - -Polkadot 1.0 represents the state of Polkadot as of 2023, coinciding with the release of [Polkadot runtime v1.0.0](https://github.com/paritytech/polkadot/releases/tag/v1.0.0){target=\_blank}. This section will focus on Polkadot 1.0, along with philosophical insights into network resilience and blockspace. - -As a Layer-0 blockchain, Polkadot contributes to the multi-chain vision through several key innovations and initiatives, including: - -- **Application-specific Layer-1 blockchains (parachains)**: Polkadot's sharded network allows for parallel transaction processing, with shards that can have unique state transition functions, enabling custom-built L1 chains optimized for specific applications. - -- **Shared security and scalability**: L1 chains connected to Polkadot benefit from its [Nominated Proof of Stake (NPoS)](/reference/polkadot-hub/consensus-and-security/pos-consensus/#nominated-proof-of-stake){target=\_blank} system, providing security out-of-the-box without the need to bootstrap their own. - -- **Secure interoperability**: Polkadot's native interoperability enables seamless data and value exchange between parachains. This interoperability can also be used outside of the ecosystem for bridging with external networks. - -- **Resilient infrastructure**: Decentralized and scalable, Polkadot ensures ongoing support for development and community initiatives via its on-chain [treasury](https://wiki.polkadot.com/learn/learn-polkadot-opengov-treasury/){target=\_blank} and governance. - -- **Rapid L1 development**: The [Polkadot SDK](/reference/parachains/){target=\_blank} allows fast, flexible creation and deployment of Layer-1 chains. - -- **Cultivating the next generation of Web3 developers**: Polkadot supports the growth of Web3 core developers through initiatives such as. - - - [Polkadot Blockchain Academy](https://polkadot.com/blockchain-academy){target=\_blank} - - [EdX courses](https://www.edx.org/school/web3x){target=\_blank} - - Rust and Substrate courses (coming soon) - -### High-Level Architecture - -Polkadot features a chain that serves as the central component of the system. This chain is depicted as a ring encircled by several parachains that are connected to it. - -According to Polkadot's design, any blockchain that can compile to WebAssembly (Wasm) and adheres to the Parachains Protocol becomes a parachain on the Polkadot network. - -Here’s a high-level overview of the Polkadot protocol architecture: - -![](/images/reference/polkadot-hub/consensus-and-security/relay-chain/relay-chain-01.webp){ style="background:white" } - -Parachains propose blocks to Polkadot validators, who check for availability and validity before finalizing them. With the relay chain providing security, collators—full nodes of parachains—can focus on their tasks without needing strong incentives. - -The [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank} allows parachains to exchange messages freely, leveraging the chain's security for trust-free communication. - -In order to interact with chains that want to use their own finalization process (e.g., Bitcoin), Polkadot has [bridges](/reference/parachains/interoperability/#bridges-connecting-external-networks){target=\_blank} that offer two-way compatibility, meaning that transactions can be made between different parachains. - -### Polkadot's Additional Functionalities - -Historically, obtaining core slots on Polkadot chain relied upon crowdloans and auctions. Chain cores were leased through auctions for three-month periods, up to a maximum of two years. Crowdloans enabled users to securely lend funds to teams for lease deposits in exchange for pre-sale tokens, which is the only way to access slots on Polkadot 1.0. Auctions are now deprecated in favor of [coretime](/polkadot-protocol/architecture/system-chains/coretime/){target=\_blank}. - -Additionally, the chain handles [staking](https://wiki.polkadot.com/learn/learn-staking/){target=\_blank}, [accounts](/reference/parachains/accounts/){target=\_blank}, balances, and [governance](/reference/governance/){target=\_blank}. - -#### Agile Coretime - -The new and more efficient way of obtaining core on Polkadot is to go through the process of purchasing coretime. - -[Agile coretime](/reference/polkadot-hub/consensus-and-security/agile-coretime/){target=\_blank} improves the efficient use of Polkadot's network resources and offers economic flexibility for developers, extending Polkadot's capabilities far beyond the original vision outlined in the [whitepaper](https://polkadot.com/papers/Polkadot-whitepaper.pdf){target=\_blank}. - -It enables parachains to purchase monthly "bulk" allocations of coretime (the time allocated for utilizing a core, measured in Polkadot relay chain blocks), ensuring heavy-duty parachains that can author a block every six seconds with [Asynchronous Backing](https://wiki.polkadot.com/learn/learn-async-backing/#asynchronous-backing){target=\_blank} can reliably renew their coretime each month. Although six-second block times are now the default, parachains have the option of producing blocks less frequently. - -Renewal orders are prioritized over new orders, offering stability against price fluctuations and helping parachains budget more effectively for project costs. - -### Polkadot's Resilience - -Decentralization is a vital component of blockchain networks, but it comes with trade-offs: - -- An overly decentralized network may face challenges in reaching consensus and require significant energy to operate. -- Also, a network that achieves consensus quickly risks centralization, making it easier to manipulate or attack. - -A network should be decentralized enough to prevent manipulative or malicious influence. In this sense, decentralization is a tool for achieving resilience. - -Polkadot 1.0 currently achieves resilience through several strategies: - -- **Nominated Proof of Stake (NPoS)**: Ensures that the stake per validator is maximized and evenly distributed among validators. - -- **Decentralized nodes**: Designed to encourage operators to join the network. This program aims to expand and diversify the validators in the ecosystem who aim to become independent of the program during their term. Feel free to explore more about the program on the official [Decentralized Nodes](https://nodes.web3.foundation/){target=\_blank} page. - -- **On-chain treasury and governance**: Known as [OpenGov](/reference/governance/){target=\_blank}, this system allows every decision to be made through public referenda, enabling any token holder to cast a vote. - -### Polkadot's Blockspace - -Polkadot 1.0’s design allows for the commoditization of blockspace. - -Blockspace is a blockchain's capacity to finalize and commit operations, encompassing its security, computing, and storage capabilities. Its characteristics can vary across different blockchains, affecting security, flexibility, and availability. - -- **Security**: Measures the robustness of blockspace in Proof of Stake (PoS) networks linked to the stake locked on validator nodes, the variance in stake among validators, and the total number of validators. It also considers social centralization (how many validators are owned by single operators) and physical centralization (how many validators run on the same service provider). - -- **Flexibility**: Reflects the functionalities and types of data that can be stored, with high-quality data essential to avoid bottlenecks in critical processes. - -- **Availability**: Indicates how easily users can access blockspace. It should be easily accessible, allowing diverse business models to thrive, ideally regulated by a marketplace based on demand and supplemented by options for "second-hand" blockspace. - -Polkadot is built on core blockspace principles, but there's room for improvement. Tasks like balance transfers, staking, and governance are managed on the relay chain. - -Delegating these responsibilities to [system chains](/polkadot-protocol/architecture/system-chains/){target=\_blank} could enhance flexibility and allow the relay chain to concentrate on providing shared security and interoperability. - -For more information about blockspace, watch [Robert Habermeier’s interview](https://www.youtube.com/watch?v=e1vISppPwe4){target=\_blank} or read his [technical blog post](https://www.rob.tech/blog/polkadot-blockspace-over-blockchains/){target=\_blank}. - -## DOT Token - -DOT is the native token of the Polkadot network, much like BTC for Bitcoin and Ether for the Ethereum blockchain. DOT has 10 decimals, uses the Planck base unit, and has a balance type of `u128`. The same is true for Kusama's KSM token with the exception of having 12 decimals. - -### Redenomination of DOT - -Polkadot conducted a community poll, which ended on 27 July 2020 at block 888,888, to decide whether to redenominate the DOT token. The stakeholders chose to redenominate the token, changing the value of 1 DOT from 1e12 plancks to 1e10 plancks. - -Importantly, this did not affect the network's total number of base units (plancks); it only affects how a single DOT is represented. The redenomination became effective 72 hours after transfers were enabled, occurring at block 1,248,328 on 21 August 2020 around 16:50 UTC. - -### The Planck Unit - -The smallest unit of account balance on Polkadot SDK-based blockchains (such as Polkadot and Kusama) is called _Planck_, named after the Planck length, the smallest measurable distance in the physical universe. - -Similar to how BTC's smallest unit is the Satoshi and ETH's is the Wei, Polkadot's native token DOT equals 1e10 Planck, while Kusama's native token KSM equals 1e12 Planck. - -### Uses for DOT - -DOT serves three primary functions within the Polkadot network: - -- **Governance**: It is used to participate in the governance of the network. -- **Staking**: DOT is staked to support the network's operation and security. -- **Buying coretime**: Used to purchase coretime in-bulk or on-demand and access the chain to benefit from Polkadot's security and interoperability. - -Additionally, DOT can serve as a transferable token. For example, DOT, held in the treasury, can be allocated to teams developing projects that benefit the Polkadot ecosystem. - -## JAM and the Road Ahead - -The Join-Accumulate Machine (JAM) represents a transformative redesign of Polkadot's core architecture, envisioned as the successor to the current relay chain. Unlike traditional blockchain architectures, JAM introduces a unique computational model that processes work through two primary functions: - -- **Join**: Handles data integration. -- **Accumulate**: Folds computations into the chain's state. - -JAM removes many of the opinions and constraints of the current relay chain while maintaining its core security properties. Expected improvements include: - -- **Permissionless code execution**: JAM is designed to be more generic and flexible, allowing for permissionless code execution through services that can be deployed without governance approval. -- **More effective block time utilization**: JAM's efficient pipeline processing model places the prior state root in block headers instead of the posterior state root, enabling more effective utilization of block time for computations. - -This architectural evolution promises to enhance Polkadot's scalability and flexibility while maintaining robust security guarantees. JAM is planned to be rolled out to Polkadot as a single, complete upgrade rather than a stream of smaller updates. This approach seeks to minimize the developer overhead required to address any breaking changes. - - ---- - -Page Title: Parachains Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/ -- Summary: Learn about parachains, specialized blockchains on Polkadot that gain shared security and interoperability. Discover how they work and the tools to build them. - -# Parachains Overview - -## Introduction - -A parachain is a specialized blockchain that connects to the Polkadot relay chain, benefiting from shared security, interoperability, and scalability. Parachains are built using the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}, a powerful toolkit written in Rust that provides everything needed to create custom blockchain logic while integrating seamlessly with the Polkadot network. - -Unlike standalone blockchains that must bootstrap their own validator sets and security, parachains leverage Polkadot's pooled security model. This allows parachain developers to focus on their application-specific functionality rather than consensus and security infrastructure. Parachains can communicate with each other through Cross-Consensus Messaging (XCM), enabling seamless interoperability across the Polkadot ecosystem. - -Key capabilities that parachains provide include: - -- **Shared security**: Inherit security from Polkadot's validator set without maintaining your own. -- **Interoperability**: Communicate trustlessly with other parachains via XCM. -- **Scalability**: Process transactions in parallel with other parachains. -- **Customization**: Build application-specific logic tailored to your use case. -- **Upgradeability**: Upgrade runtime logic without hard forks. - -## Polkadot SDK: Parachain Architecture - -Building a parachain involves understanding and utilizing several key components of the Polkadot SDK: - -![](/images/reference/parachains/index/overview-01.webp) - -- **[Substrate](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/substrate/index.html){target=\_blank}**: The foundation providing core blockchain primitives and libraries. -- **[FRAME](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank}**: A modular framework for building your parachain's runtime logic. -- **[Cumulus](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/cumulus/index.html){target=\_blank}**: Essential libraries and pallets that enable parachain functionality. -- **[XCM (Cross Consensus Messaging)](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/xcm/index.html){target=\_blank}**: The messaging format for communicating with other parachains and the relay chain. -- **[Polkadot](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/polkadot/index.html){target=\_blank}**: The relay chain that provides security and coordination. - -### Substrate: The Foundation - -Substrate provides the core infrastructure that every parachain is built upon. It handles the low-level blockchain functionality, allowing you to focus on your application's unique features. Substrate includes implementations for networking, database management, consensus participation, and the execution environment for your runtime. - -Every Polkadot SDK node consists of two main components: - -- **Client (Host)**: Handles infrastructure services. - - - Native binary that runs on validator and collator nodes. - - Executes the Wasm-compiled runtime. - - Manages networking, database, mempool, and block production. - - Interfaces with the relay chain for validation. - -- **Runtime (State Transition Function)**: Contains your business logic. - - - Defines how your Polkadot SDK node processes transactions. - - Compiled to [Wasm](https://webassembly.org/){target=\_blank} for deterministic execution. - - Stored on-chain and upgradeable via governance. - -```mermaid -%%{init: {'flowchart': {'padding': 5, 'nodeSpacing': 50, 'rankSpacing': 10}}}%% -graph TB - classDef title font-size:20px,font-weight:bold,stroke-width:0px - classDef clientStyle font-size:16px,font-weight:bold - classDef clientSubNodeStyle margin-top:10px - classDef runtimeCallExecutorStyle padding-top:10px - - subgraph sg1[Parachain
Node] - direction TB - - I[RuntimeCall Executor] - B[Wasm Runtime - STF] - - subgraph sg2[Client] - direction TB - C[Network and Blockchain
Infrastructure Services
+ Relay Chain Interface] - end - - I --> B - end - - class sg1 title - class sg2 clientStyle - class C clientSubNodeStyle - class I runtimeCallExecutorStyle - -``` - -### FRAME: Building Blocks for Your Runtime - -FRAME provides modular components called [pallets](/reference/glossary#pallet){target=\_blank} that you can compose to build your parachain's runtime. Each pallet provides specific functionality that you can customize and configure for your needs. This modular approach allows you to quickly assemble complex functionality without writing everything from scratch. - -```mermaid -graph LR - subgraph SP["Parachain Runtime"] - direction LR - Timestamp ~~~ Aura ~~~ ParachainSystem - Balances ~~~ TransactionPayment ~~~ Sudo - subgraph Timestamp["Timestamp"] - SS1[Custom Config] - end - subgraph Aura["Aura"] - SS2[Custom Config] - end - subgraph ParachainSystem["Parachain System"] - SS3[Custom Config] - end - subgraph Balances["Balances"] - SS4[Custom Config] - end - subgraph TransactionPayment["Transaction Payment"] - SS5[Custom Config] - end - subgraph Sudo["Sudo"] - SS6[Custom Config] - end - style Timestamp stroke:#FF69B4 - style Aura stroke:#FF69B4 - style ParachainSystem stroke:#FF69B4 - style Balances stroke:#FF69B4 - style TransactionPayment stroke:#FF69B4 - style Sudo stroke:#FF69B4 - style SS1 stroke-dasharray: 5 - style SS2 stroke-dasharray: 5 - style SS3 stroke-dasharray: 5 - style SS4 stroke-dasharray: 5 - style SS5 stroke-dasharray: 5 - style SS6 stroke-dasharray: 5 - - end - subgraph AP["Available FRAME Pallets"] - direction LR - A1[Aura]~~~A2[Parachain
System]~~~A3[Transaction
Payment]~~~A4[Sudo] - B1[Identity]~~~B2[Balances]~~~B3[Assets]~~~B4[EVM] - C1[Timestamp]~~~C2[Staking]~~~C3[Contracts]~~~C4[and more...] - end - AP --> SP -``` - -### Cumulus: Parachain-Specific Functionality - -Cumulus is what transforms a Polkadot SDK-based runtime into a parachain-capable runtime. It provides the essential components for communicating with the relay chain, participating in Polkadot's consensus, and handling parachain-specific operations like block validation and collation. - -Key Cumulus components include: - -- **Parachain system pallet**: Core parachain functionality and relay chain communication. -- **Collator consensus**: Block production logic for parachain collators. -- **Relay chain interface**: APIs for interacting with the Polkadot relay chain. -- **Validation data**: Handling proof-of-validity data required by relay chain validators. - -## Where to Go Next - -Building a parachain requires understanding the relationship between your chain and the Polkadot relay chain. The Polkadot SDK provides all the tools needed to design custom runtime logic, enable cross-chain communication, and deploy your parachain to production. - -The following sections provide detailed guidance on each aspect of parachain development, from initial design through deployment and ongoing maintenance. - -
- -- Guide __Launch a Simple Parachain__ - - --- - - Walk through the complete parachain launch flow: from setup and deployment to obtaining coretime. - - [:octicons-arrow-right-24: Deploy](/parachains/launch-a-parachain/set-up-the-parachain-template/) - - -- Guide __Customize Your Runtime__ - - --- - - Design your parachain's runtime logic and choose appropriate pallets for your use case. - - [:octicons-arrow-right-24: Get Started](/parachains/customize-runtime/) - -- Guide __Interoperability__ - - --- - - Implement XCM for trustless cross-chain communication with other parachains. - - [:octicons-arrow-right-24: Learn More](/parachains/interoperability/get-started/) - -- Guide __Runtime Upgrades__ - - --- - - Upgrade your parachain's runtime without hard forks using forkless upgrade mechanisms. - - [:octicons-arrow-right-24: Maintain](/parachains/runtime-maintenance/runtime-upgrades/) - -
- - ---- - -Page Title: Polkadot SDK Accounts - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-accounts.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/accounts/ -- Summary: Learn about account structures, balances, and address formats in the Polkadot SDK, including how to manage lifecycle, references, and balances. - -# Accounts - -## Introduction - -Accounts are essential for managing identity, transactions, and governance on the network in the Polkadot SDK. Understanding these components is critical for seamless development and operation on the network, whether you're building or interacting with Polkadot-based chains. - -This page will guide you through the essential aspects of accounts, including their data structure, balance types, reference counters, and address formats. You’ll learn how accounts are managed within the runtime, how balances are categorized, and how addresses are encoded and validated. - -## Account Data Structure - -Accounts are foundational to any blockchain, and the Polkadot SDK provides a flexible management system. This section explains how the Polkadot SDK defines accounts and manages their lifecycle through data structures within the runtime. - -### Account - -The [`Account` data type](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/type.Account.html){target=\_blank} is a storage map within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank} that links an account ID to its corresponding data. This structure is fundamental for mapping account-related information within the chain. - -The code snippet below shows how accounts are defined: - -```rs - /// The full account information for a particular account ID. - #[pallet::storage] - #[pallet::getter(fn account)] - pub type Account = StorageMap< - _, - Blake2_128Concat, - T::AccountId, - AccountInfo, - ValueQuery, - >; -``` - -The preceding code block defines a storage map named `Account`. The `StorageMap` is a type of on-chain storage that maps keys to values. In the `Account` map, the key is an account ID, and the value is the account's information. Here, `T` represents the generic parameter for the runtime configuration, which is defined by the pallet's configuration trait (`Config`). - -The `StorageMap` consists of the following parameters: - -- **`_`**: Used in macro expansion and acts as a placeholder for the storage prefix type. Tells the macro to insert the default prefix during expansion. -- **`Blake2_128Concat`**: The hashing function applied to keys in the storage map. -- **`T: :AccountId`**: Represents the key type, which corresponds to the account’s unique ID. -- **`AccountInfo`**: The value type stored in the map. For each account ID, the map stores an `AccountInfo` struct containing: - - - **`T::Nonce`**: A nonce for the account, which is incremented with each transaction to ensure transaction uniqueness. - - **`T: :AccountData`**: Custom account data defined by the runtime configuration, which could include balances, locked funds, or other relevant information. - -- **`ValueQuery`**: Defines how queries to the storage map behave when no value is found; returns a default value instead of `None`. - -For a detailed explanation of storage maps, see the [`StorageMap`](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/struct.StorageMap.html){target=\_blank} entry in the Rust docs. - -### Account Info - -The `AccountInfo` structure is another key element within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank}, providing more granular details about each account's state. This structure tracks vital data, such as the number of transactions and the account’s relationships with other modules. - -```rs -/// Information of an account. -#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)] -pub struct AccountInfo { - /// The number of transactions this account has sent. - pub nonce: Nonce, - /// The number of other modules that currently depend on this account's existence. The account - /// cannot be reaped until this is zero. - pub consumers: RefCount, - /// The number of other modules that allow this account to exist. The account may not be reaped - /// until this and `sufficients` are both zero. - pub providers: RefCount, - /// The number of modules that allow this account to exist for their own purposes only. The - /// account may not be reaped until this and `providers` are both zero. - pub sufficients: RefCount, - /// The additional data that belongs to this account. Used to store the balance(s) in a lot of - /// chains. - pub data: AccountData, -} -``` - -The `AccountInfo` structure includes the following components: - -- **`nonce`**: Tracks the number of transactions initiated by the account, which ensures transaction uniqueness and prevents replay attacks. -- **`consumers`**: Counts how many other modules or pallets rely on this account’s existence. The account cannot be removed from the chain (reaped) until this count reaches zero. -- **`providers`**: Tracks how many modules permit this account’s existence. An account can only be reaped once both `providers` and `sufficients` are zero. -- **`sufficients`**: Represents the number of modules that allow the account to exist for internal purposes, independent of any other modules. -- **`AccountData`**: A flexible data structure that can be customized in the runtime configuration, usually containing balances or other user-specific data. - -This structure helps manage an account's state and prevents its premature removal while it is still referenced by other on-chain data or modules. The [`AccountInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.AccountInfo.html){target=\_blank} structure can vary as long as it satisfies the trait bounds defined by the `AccountData` associated type in the [`frame-system::pallet::Config`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/trait.Config.html){target=\_blank} trait. - -### Account Reference Counters - -Polkadot SDK uses reference counters to track an account’s dependencies across different runtime modules. These counters ensure that accounts remain active while data is associated with them. - -The reference counters include: - -- **`consumers`**: Prevents account removal while other pallets still rely on the account. -- **`providers`**: Ensures an account is active before other pallets store data related to it. -- **`sufficients`**: Indicates the account’s independence, ensuring it can exist even without a native token balance, such as when holding sufficient alternative assets. - -#### Providers Reference Counters - -The `providers` counter ensures that an account is ready to be depended upon by other runtime modules. For example, it is incremented when an account has a balance above the existential deposit, which marks the account as active. - -The system requires this reference counter to be greater than zero for the `consumers` counter to be incremented, ensuring the account is stable before any dependencies are added. - -#### Consumers Reference Counters - -The `consumers` counter ensures that the account cannot be reaped until all references to it across the runtime have been removed. This check prevents the accidental deletion of accounts that still have active on-chain data. - -It is the user’s responsibility to clear out any data from other runtime modules if they wish to remove their account and reclaim their existential deposit. - -#### Sufficients Reference Counter - -The `sufficients` counter tracks accounts that can exist independently without relying on a native account balance. This is useful for accounts holding other types of assets, like tokens, without needing a minimum balance in the native token. - -For instance, the [Assets pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_assets/index.html){target=\_blank}, may increment this counter for an account holding sufficient tokens. - -#### Account Deactivation - -In Polkadot SDK-based chains, an account is deactivated when its reference counters (such as `providers`, `consumers`, and `sufficient`) reach zero. These counters ensure the account remains active as long as other runtime modules or pallets reference it. - -When all dependencies are cleared and the counters drop to zero, the account becomes deactivated and may be removed from the chain (reaped). This is particularly important in Polkadot SDK-based blockchains, where accounts with balances below the existential deposit threshold are pruned from storage to conserve state resources. - -Each pallet that references an account has cleanup functions that decrement these counters when the pallet no longer depends on the account. Once these counters reach zero, the account is marked for deactivation. - -#### Updating Counters - -The Polkadot SDK provides runtime developers with various methods to manage account lifecycle events, such as deactivation or incrementing reference counters. These methods ensure that accounts cannot be reaped while still in use. - -The following helper functions manage these counters: - -- **`inc_consumers()`**: Increments the `consumer` reference counter for an account, signaling that another pallet depends on it. -- **`dec_consumers()`**: Decrements the `consumer` reference counter, signaling that a pallet no longer relies on the account. -- **`inc_providers()`**: Increments the `provider` reference counter, ensuring the account remains active. -- **`dec_providers()`**: Decrements the `provider` reference counter, allowing for account deactivation when no longer in use. -- **`inc_sufficients()`**: Increments the `sufficient` reference counter for accounts that hold sufficient assets. -- **`dec_sufficients()`**: Decrements the `sufficient` reference counter. - -To ensure proper account cleanup and lifecycle management, a corresponding decrement should be made for each increment action. - -The `System` pallet offers three query functions to assist developers in tracking account states: - -- **[`can_inc_consumer()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_inc_consumer){target=\_blank}**: Checks if the account can safely increment the consumer reference. -- **[`can_dec_provider()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_dec_provider){target=\_blank}**: Ensures that no consumers exist before allowing the decrement of the provider counter. -- **[`is_provider_required()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.is_provider_required){target=\_blank}**: Verifies whether the account still has any active consumer references. - -This modular and flexible system of reference counters tightly controls the lifecycle of accounts in Polkadot SDK-based blockchains, preventing the accidental removal or retention of unneeded accounts. You can refer to the [System pallet Rust docs](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html){target=\_blank} for more details. - - -## Account Balance Types - -In the Polkadot ecosystem, account balances are categorized into different types based on how the funds are utilized and their availability. These balance types determine the actions that can be performed, such as transferring tokens, paying transaction fees, or participating in governance activities. Understanding these balance types helps developers manage user accounts and implement balance-dependent logic. - -!!! note "A more efficient distribution of account balance types is in development" - Soon, pallets in the Polkadot SDK will implement the [`Fungible` trait](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} (see the [tracking issue](https://github.com/paritytech/polkadot-sdk/issues/226){target=\_blank} for more details). For example, the [`transaction-storage`](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_storage/index.html){target=\_blank} pallet changed the implementation of the [`Currency`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/currency/index.html){target=\_blank} trait (see the [Refactor transaction storage pallet to use fungible traits](https://github.com/paritytech/polkadot-sdk/pull/1800){target=\_blank} PR for further details): - - ```rust - type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; - ``` - - To the [`Fungible`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} trait: - - ```rust - type BalanceOf = <::Currency as FnInspect<::AccountId>>::Balance; - ``` - - This update will enable more efficient use of account balances, allowing the free balance to be utilized for on-chain activities such as setting proxies and managing identities. - -### Balance Types - -The five main balance types are: - -- **Free balance**: Represents the total tokens available to the account for any on-chain activity, including staking, governance, and voting. However, it may not be fully spendable or transferrable if portions of it are locked or reserved. -- **Locked balance**: Portions of the free balance that cannot be spent or transferred because they are tied up in specific activities like [staking](https://wiki.polkadot.com/learn/learn-staking/#nominating-validators){target=\_blank}, [vesting](https://wiki.polkadot.com/learn/learn-guides-transfers/#vested-transfers-with-the-polkadot-js-ui){target=\_blank}, or participating in [governance](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank}. While the tokens remain part of the free balance, they are non-transferable for the duration of the lock. -- **Reserved balance**: Funds locked by specific system actions, such as setting up an [identity](https://wiki.polkadot.com/learn/learn-identity/){target=\_blank}, creating [proxies](https://wiki.polkadot.com/learn/learn-proxies/){target=\_blank}, or submitting [deposits for governance proposals](https://wiki.polkadot.com/learn/learn-guides-polkadot-opengov/#claiming-opengov-deposits){target=\_blank}. These tokens are not part of the free balance and cannot be spent unless they are unreserved. -- **Spendable balance**: The portion of the free balance that is available for immediate spending or transfers. It is calculated by subtracting the maximum of locked or reserved amounts from the free balance, ensuring that existential deposit limits are met. -- **Untouchable balance**: Funds that cannot be directly spent or transferred but may still be utilized for on-chain activities, such as governance participation or staking. These tokens are typically tied to certain actions or locked for a specific period. - -The spendable balance is calculated as follows: - -```text -spendable = free - max(locked - reserved, ED) -``` - -Here, `free`, `locked`, and `reserved` are defined above. The `ED` represents the [existential deposit](https://wiki.polkadot.com/learn/learn-accounts/#existential-deposit-and-reaping){target=\_blank}, the minimum balance required to keep an account active and prevent it from being reaped. You may find you can't see all balance types when looking at your account via a wallet. Wallet providers often display only spendable, locked, and reserved balances. - -### Locks - -Locks are applied to an account's free balance, preventing that portion from being spent or transferred. Locks are automatically placed when an account participates in specific on-chain activities, such as staking or governance. Although multiple locks may be applied simultaneously, they do not stack. Instead, the largest lock determines the total amount of locked tokens. - -Locks follow these basic rules: - -- If different locks apply to varying amounts, the largest lock amount takes precedence. -- If multiple locks apply to the same amount, the lock with the longest duration governs when the balance can be unlocked. - -#### Locks Example - -Consider an example where an account has 80 DOT locked for both staking and governance purposes like so: - -- 80 DOT is staked with a 28-day lock period. -- 24 DOT is locked for governance with a 1x conviction and a 7-day lock period. -- 4 DOT is locked for governance with a 6x conviction and a 224-day lock period. - -In this case, the total locked amount is 80 DOT because only the largest lock (80 DOT from staking) governs the locked balance. These 80 DOT will be released at different times based on the lock durations. In this example, the 24 DOT locked for governance will be released first since the shortest lock period is seven days. The 80 DOT stake with a 28-day lock period is released next. Now, all that remains locked is the 4 DOT for governance. After 224 days, all 80 DOT (minus the existential deposit) will be free and transferable. - -![Illustration of Lock Example](/images/reference/parachains/accounts/accounts-01.webp) - -#### Edge Cases for Locks - -In scenarios where multiple convictions and lock periods are active, the lock duration and amount are determined by the longest period and largest amount. For example, if you delegate with different convictions and attempt to undelegate during an active lock period, the lock may be extended for the full amount of tokens. For a detailed discussion on edge case lock behavior, see this [Stack Exchange post](https://substrate.stackexchange.com/questions/5067/delegating-and-undelegating-during-the-lock-period-extends-it-for-the-initial-am){target=\_blank}. - -### Balance Types on Polkadot.js - -Polkadot.js provides a user-friendly interface for managing and visualizing various account balances on Polkadot and Kusama networks. When interacting with Polkadot.js, you will encounter multiple balance types that are critical for understanding how your funds are distributed and restricted. This section explains how different balances are displayed in the Polkadot.js UI and what each type represents. - -![](/images/reference/parachains/accounts/accounts-02.webp) - -The most common balance types displayed on Polkadot.js are: - -- **Total balance**: The total number of tokens available in the account. This includes all tokens, whether they are transferable, locked, reserved, or vested. However, the total balance does not always reflect what can be spent immediately. In this example, the total balance is 0.6274 KSM. - -- **Transferable balance**: Shows how many tokens are immediately available for transfer. It is calculated by subtracting the locked and reserved balances from the total balance. For example, if an account has a total balance of 0.6274 KSM and a transferable balance of 0.0106 KSM, only the latter amount can be sent or spent freely. - -- **Vested balance**: Tokens that allocated to the account but released according to a specific schedule. Vested tokens remain locked and cannot be transferred until fully vested. For example, an account with a vested balance of 0.2500 KSM means that this amount is owned but not yet transferable. - -- **Locked balance**: Tokens that are temporarily restricted from being transferred or spent. These locks typically result from participating in staking, governance, or vested transfers. In Polkadot.js, locked balances do not stack—only the largest lock is applied. For instance, if an account has 0.5500 KSM locked for governance and staking, the locked balance would display 0.5500 KSM, not the sum of all locked amounts. - -- **Reserved balance**: Refers to tokens locked for specific on-chain actions, such as setting an identity, creating a proxy, or making governance deposits. Reserved tokens are not part of the free balance, but can be freed by performing certain actions. For example, removing an identity would unreserve those funds. - -- **Bonded balance**: The tokens locked for staking purposes. Bonded tokens are not transferable until they are unbonded after the unbonding period. - -- **Redeemable balance**: The number of tokens that have completed the unbonding period and are ready to be unlocked and transferred again. For example, if an account has a redeemable balance of 0.1000 KSM, those tokens are now available for spending. - -- **Democracy balance**: Reflects the number of tokens locked for governance activities, such as voting on referenda. These tokens are locked for the duration of the governance action and are only released after the lock period ends. - -By understanding these balance types and their implications, developers and users can better manage their funds and engage with on-chain activities more effectively. - -## Address Formats - -The SS58 address format is a core component of the Polkadot SDK that enables accounts to be uniquely identified across Polkadot-based networks. This format is a modified version of Bitcoin's Base58Check encoding, specifically designed to accommodate the multi-chain nature of the Polkadot ecosystem. SS58 encoding allows each chain to define its own set of addresses while maintaining compatibility and checksum validation for security. - -### Basic Format - -SS58 addresses consist of three main components: - -```text -base58encode(concat(,
, )) -``` - -- **Address type**: A byte or set of bytes that define the network (or chain) for which the address is intended. This ensures that addresses are unique across different Polkadot SDK-based chains. -- **Address**: The public key of the account encoded as bytes. -- **Checksum**: A hash-based checksum which ensures that addresses are valid and unaltered. The checksum is derived from the concatenated address type and address components, ensuring integrity. - -The encoding process transforms the concatenated components into a Base58 string, providing a compact and human-readable format that avoids easily confused characters (e.g., zero '0', capital 'O', lowercase 'l'). This encoding function ([`encode`](https://docs.rs/bs58/latest/bs58/fn.encode.html){target=\_blank}) is implemented exactly as defined in Bitcoin and IPFS specifications, using the same alphabet as both implementations. - -For more details about the SS58 address format implementation, see the [`Ss58Codec`](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Ss58Codec.html){target=\_blank} trait in the Rust Docs. - -### Address Type - -The address type defines how an address is interpreted and to which network it belongs. Polkadot SDK uses different prefixes to distinguish between various chains and address formats: - -- **Address types `0-63`**: Simple addresses, commonly used for network identifiers. -- **Address types `64-127`**: Full addresses that support a wider range of network identifiers. -- **Address types `128-255`**: Reserved for future address format extensions. - -For example, Polkadot’s main network uses an address type of 0, while Kusama uses 2. This ensures that addresses can be used without confusion between networks. - -The address type is always encoded as part of the SS58 address, making it easy to quickly identify the network. Refer to the [SS58 registry](https://github.com/paritytech/ss58-registry){target=\_blank} for the canonical listing of all address type identifiers and how they map to Polkadot SDK-based networks. - -### Address Length - -SS58 addresses can have different lengths depending on the specific format. Address lengths range from as short as 3 to 35 bytes, depending on the complexity of the address and network requirements. This flexibility allows SS58 addresses to adapt to different chains while providing a secure encoding mechanism. - -| Total | Type | Raw account | Checksum | -|-------|------|-------------|----------| -| 3 | 1 | 1 | 1 | -| 4 | 1 | 2 | 1 | -| 5 | 1 | 2 | 2 | -| 6 | 1 | 4 | 1 | -| 7 | 1 | 4 | 2 | -| 8 | 1 | 4 | 3 | -| 9 | 1 | 4 | 4 | -| 10 | 1 | 8 | 1 | -| 11 | 1 | 8 | 2 | -| 12 | 1 | 8 | 3 | -| 13 | 1 | 8 | 4 | -| 14 | 1 | 8 | 5 | -| 15 | 1 | 8 | 6 | -| 16 | 1 | 8 | 7 | -| 17 | 1 | 8 | 8 | -| 35 | 1 | 32 | 2 | - -SS58 addresses also support different payload sizes, allowing a flexible range of account identifiers. - -### Checksum Types - -A checksum is applied to validate SS58 addresses. Polkadot SDK uses a Blake2b-512 hash function to calculate the checksum, which is appended to the address before encoding. The checksum length can vary depending on the address format (e.g., 1-byte, 2-byte, or longer), providing varying levels of validation strength. - -The checksum ensures that an address is not modified or corrupted, adding an extra layer of security for account management. - -### Validating Addresses - -SS58 addresses can be validated using the subkey command-line interface or the Polkadot.js API. These tools help ensure an address is correctly formatted and valid for the intended network. The following sections will provide an overview of how validation works with these tools. - -#### Using Subkey - -[Subkey](https://paritytech.github.io/polkadot-sdk/master/subkey/index.html){target=\_blank} is a CLI tool provided by Polkadot SDK for generating and managing keys. It can inspect and validate SS58 addresses. - -The `inspect` command gets a public key and an SS58 address from the provided secret URI. The basic syntax for the `subkey inspect` command is: - -```bash -subkey inspect [flags] [options] uri -``` - -For the `uri` command-line argument, you can specify the secret seed phrase, a hex-encoded private key, or an SS58 address. If the input is a valid address, the `subkey` program displays the corresponding hex-encoded public key, account identifier, and SS58 addresses. - -For example, to inspect the public keys derived from a secret seed phrase, you can run a command similar to the following: - -```bash -subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" -``` - -The command displays output similar to the following: - -
- subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" - Secret phrase `caution juice atom organ advance problem want pledge someone senior holiday very` is account: - Secret seed: 0xc8fa03532fb22ee1f7f6908b9c02b4e72483f0dbd66e4cd456b8f34c6230b849 - Public key (hex): 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - Public key (SS58): 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR - Account ID: 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - SS58 Address: 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR -
- -The `subkey` program assumes an address is based on a public/private key pair. If you inspect an address, the command returns the 32-byte account identifier. - -However, not all addresses in Polkadot SDK-based networks are based on keys. - -Depending on the command-line options you specify and the input you provided, the command output might also display the network for which the address has been encoded. For example: - -```bash -subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" -``` - -The command displays output similar to the following: - -
- subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" - Public Key URI `12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU` is account: - Network ID/Version: polkadot - Public key (hex): 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Account ID: 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Public key (SS58): 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU - SS58 Address: 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU -
- -#### Using Polkadot.js API - -To verify an address in JavaScript or TypeScript projects, you can use the functions built into the [Polkadot.js API](https://polkadot.js.org/docs/){target=\_blank}. For example: - -```js -// Import Polkadot.js API dependencies -const { decodeAddress, encodeAddress } = require('@polkadot/keyring'); -const { hexToU8a, isHex } = require('@polkadot/util'); - -// Specify an address to test. -const address = 'INSERT_ADDRESS_TO_TEST'; - -// Check address -const isValidSubstrateAddress = () => { - try { - encodeAddress(isHex(address) ? hexToU8a(address) : decodeAddress(address)); - - return true; - } catch (error) { - return false; - } -}; - -// Query result -const isValid = isValidSubstrateAddress(); -console.log(isValid); - -``` - -If the function returns `true`, the specified address is a valid address. - -#### Other SS58 Implementations - -Support for encoding and decoding Polkadot SDK SS58 addresses has been implemented in several other languages and libraries. - -- **Crystal**: [`wyhaines/base58.cr`](https://github.com/wyhaines/base58.cr){target=\_blank} -- **Go**: [`itering/subscan-plugin`](https://github.com/itering/subscan-plugin){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **TypeScript**: [`subsquid/squid-sdk`](https://github.com/subsquid/squid-sdk){target=\_blank} - - ---- - -Page Title: Randomness - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-randomness.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/randomness/ -- Summary: Explore the importance of randomness in PoS blockchains, focusing on Polkadot’s VRF-based approach to ensure fairness and security in validator selection. - -# Randomness - -## Introduction - -Randomness is crucial in Proof of Stake (PoS) blockchains to ensure a fair and unpredictable distribution of validator duties. However, computers are inherently deterministic, meaning the same input always produces the same output. What we typically refer to as "random" numbers on a computer are actually pseudo-random. These numbers rely on an initial "seed," which can come from external sources like [atmospheric noise](https://www.random.org/randomness/){target=\_blank}, [heart rates](https://mdpi.altmetric.com/details/47574324){target=\_blank}, or even [lava lamps](https://en.wikipedia.org/wiki/Lavarand){target=\_blank}. While this may seem random, given the same "seed," the same sequence of numbers will always be generated. - -In a global blockchain network, relying on real-world entropy for randomness isn’t feasible because these inputs vary by time and location. If nodes use different inputs, blockchains can fork. Hence, real-world randomness isn't suitable for use as a seed in blockchain systems. - -Currently, two primary methods for generating randomness in blockchains are used: [`RANDAO`](#randao) and [`VRF`](#vrf) (Verifiable Random Function). Polkadot adopts the `VRF` approach for its randomness. - -## VRF - -A Verifiable Random Function (VRF) is a cryptographic function that generates a random number and proof that ensures the submitter produced the number. This proof allows anyone to verify the validity of the random number. - -Polkadot's VRF is similar to the one used in [**Ouroboros Praos**](https://eprint.iacr.org/2017/573.pdf){target=\_blank}, which secures randomness for block production in systems like [BABE](/reference/polkadot-hub/consensus-and-security/pos-consensus/#block-production-babe){target=\_blank} (Polkadot’s block production mechanism). - -The key difference is that Polkadot's VRF doesn’t rely on a central clock—avoiding the issue of whose clock to trust. Instead, it uses its own past results and slot numbers to simulate time and determine future outcomes. - -### How VRF Works - -Slots on Polkadot are discrete units of time, each lasting six seconds, and can potentially hold a block. Multiple slots form an epoch, with 2400 slots making up one four-hour epoch. - -In each slot, validators execute a "die roll" using a VRF. The VRF uses three inputs: - -1. A "secret key," unique to each validator, is used for the die roll. -2. An epoch randomness value, derived from the hash of VRF outputs from blocks two epochs ago (N-2), so past randomness influences the current epoch (N). -3. The current slot number. - -This process helps maintain fair randomness across the network. - -Here is a graphical representation: - -![](/images/reference/parachains/randomness/randomness-01.webp) - -The VRF produces two outputs: a result (the random number) and a proof (verifying that the number was generated correctly). - -The result is checked by the validator against a protocol threshold. If it's below the threshold, the validator becomes a candidate for block production in that slot. - -The validator then attempts to create a block, submitting it along with the `PROOF` and `RESULT`. - -So, VRF can be expressed like: - -`(RESULT, PROOF) = VRF(SECRET, EPOCH_RANDOMNESS_VALUE, CURRENT_SLOT_NUMBER)` - -Put simply, performing a "VRF roll" generates a random number along with proof that the number was genuinely produced and not arbitrarily chosen. - -After executing the VRF, the `RESULT` is compared to a protocol-defined `THRESHOLD`. If the `RESULT` is below the `THRESHOLD`, the validator becomes a valid candidate to propose a block for that slot. Otherwise, the validator skips the slot. - -As a result, there may be multiple validators eligible to propose a block for a slot. In this case, the block accepted by other nodes will prevail, provided it is on the chain with the latest finalized block as determined by the GRANDPA finality gadget. It's also possible for no block producers to be available for a slot, in which case the AURA consensus takes over. AURA is a fallback mechanism that randomly selects a validator to produce a block, running in parallel with BABE and only stepping in when no block producers exist for a slot. Otherwise, it remains inactive. - -Because validators roll independently, no block candidates may appear in some slots if all roll numbers are above the threshold. - -To verify resolution of this issue and that Polkadot block times remain near constant-time, see the [PoS Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} page of this documentation. - -## RANDAO - -An alternative on-chain randomness method is Ethereum's RANDAO, where validators perform thousands of hashes on a seed and publish the final hash during a round. The collective input from all validators forms the random number, and as long as one honest validator participates, the randomness is secure. - -To enhance security, RANDAO can optionally be combined with a Verifiable Delay Function (VDF), ensuring that randomness can't be predicted or manipulated during computation. - -For more information about RANDAO, see the [Randomness - RANDAO](https://eth2book.info/capella/part2/building_blocks/randomness/){target=\_blank} section of the Upgrading Ethereum documentation. - -## VDFs - -Verifiable Delay Functions (VDFs) are time-bound computations that, even on parallel computers, take a set amount of time to complete. - -They produce a unique result that can be quickly verified publicly. When combined with RANDAO, feeding RANDAO's output into a VDF introduces a delay that nullifies an attacker's chance to influence the randomness. - -However, VDF likely requires specialized ASIC devices to run separately from standard nodes. - -!!!warning - While only one is needed to secure the system, and they will be open-source and inexpensive, running VDF devices involves significant costs without direct incentives, adding friction for blockchain users. - -## Additional Resources - -For more information about the reasoning for choices made along with proofs, see Polkadot's research on blockchain randomness and sortition in the [Block production](https://research.web3.foundation/Polkadot/protocols/block-production){target=\_blank} entry of the Polkadot Wiki. - -For a discussion with Web3 Foundation researchers about when and under what conditions Polkadot's randomness can be utilized, see the [Discussion on Randomness used in Polkadot](https://github.com/use-ink/ink/issues/57){target=\_blank} issue on GitHub. - - ---- - -Page Title: Register a Local Asset - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-token-operations-register-local-asset.md -- Canonical (HTML): https://docs.polkadot.com/chain-interactions/token-operations/register-local-asset/ -- Summary: Comprehensive guide to registering a local asset on the Asset Hub system parachain, including step-by-step instructions. - -# Register a Local Asset on Asset Hub - -## Introduction - -As detailed in the [Asset Hub Overview](/polkadot-protocol/architecture/system-chains/asset-hub){target=\_blank} page, Asset Hub accommodates two types of assets: local and foreign. Local assets are those that were created in Asset Hub and are identifiable by an integer ID. On the other hand, foreign assets originate from a sibling parachain and are identified by a Multilocation. - -This guide will take you through the steps of registering a local asset on the Asset Hub parachain. - -## Prerequisites - -Before you begin, ensure you have access to the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and a funded wallet with DOT or KSM. - -- For Polkadot Asset Hub, you would need a deposit of 10 DOT and around 0.201 DOT for the metadata. -- For Kusama Asset Hub, the deposit is 0.1 KSM and around 0.000669 KSM for the metadata. - -You need to ensure that your Asset Hub account balance is a bit more than the sum of those two deposits, which should seamlessly account for the required deposits and transaction fees. - -## Steps to Register a Local Asset - -To register a local asset on the Asset Hub parachain, follow these steps: - -1. Open the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and connect to the Asset Hub parachain using the network selector in the top left corner. - - - You may prefer to test local asset registration on TestNet before registering the asset on a MainNet hub. If you still need to set up a local testing environment, review the [Environment setup](#test-setup-environment) section for instructions. Once the local environment is set up, connect to the Local Node (Chopsticks) available on `ws://127.0.0.1:8000`. - - For the live network, connect to the **Asset Hub** parachain. Either Polkadot or Kusama Asset Hub can be selected from the dropdown list, choosing the desired RPC provider. - -2. Click on the **Network** tab on the top navigation bar and select **Assets** from the dropdown list. - - ![Access to Asset Hub through Polkadot.JS](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-01.webp) - -3. Now, you need to examine all the registered asset IDs. This step is crucial to ensure that the asset ID you are about to register is unique. Asset IDs are displayed in the **assets** column. - - ![Asset IDs on Asset Hub](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-02.webp) - -4. Once you have confirmed that the asset ID is unique, click on the **Create** button on the top right corner of the page. - - ![Create a new asset](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-03.webp) - -5. Fill in the required fields in the **Create Asset** form: - - 1. **creator account**: The account to be used for creating this asset and setting up the initial metadata. - 2. **asset name**: The descriptive name of the asset you are registering. - 3. **asset symbol**: The symbol that will be used to represent the asset. - 4. **asset decimals**: The number of decimal places for this token, with a maximum of 20 allowed through the user interface. - 5. **minimum balance**: The minimum balance for the asset. This is specified in the units and decimals as requested. - 6. **asset ID**: The selected id for the asset. This should not match an already-existing asset id. - 7. Click on the **Next** button. - - ![Create Asset Form](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-04.webp) - -6. Choose the accounts for the roles listed below: - - 1. **admin account**: The account designated for continuous administration of the token. - 2. **issuer account**: The account that will be used for issuing this token. - 3. **freezer account**: The account that will be used for performing token freezing operations. - 4. Click on the **Create** button. - - ![Admin, Issuer, Freezer accounts](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-05.webp) - -7. Click on the **Sign and Submit** button to complete the asset registration process. - - ![Sign and Submit](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-06.webp) - -## Verify Asset Registration - -After completing these steps, the asset will be successfully registered. You can now view your asset listed on the [**Assets**](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fasset-hub-polkadot-rpc.dwellir.com#/assets){target=\_blank} section of the Polkadot.js Apps interface. - -![Asset listed on Polkadot.js Apps](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-07.webp) - -!!! tip - Take into consideration that the **Assets** section’s link may differ depending on the network you are using. For the local environment, enter `ws://127.0.0.1:8000` into the **Custom Endpoint** field. - -In this way, you have successfully registered a local asset on the Asset Hub parachain. - -For an in-depth explanation about Asset Hub and its features, see the [Asset Hub](/chain-interactions/token-operations/convert-assets/){target=\_blank} entry in the Polkadot Wiki. - -## Test Setup Environment - -You can set up a local parachain environment to test the asset registration process before deploying it on the live network. This guide uses Chopsticks to simulate that process. For further information on chopsticks usage, refer to the [Chopsticks](/develop/toolkit/parachains/fork-chains/chopsticks/get-started){target=\_blank} documentation. - -To set up a test environment, execute the following command: - -```bash -npx @acala-network/chopsticks \ ---config=https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/polkadot-asset-hub.yml -``` - -The above command will spawn a lazy fork of Polkadot Asset Hub with the latest block data from the network. If you need to test Kusama Asset Hub, replace `polkadot-asset-hub.yml` with `kusama-asset-hub.yml` in the command. - -An Asset Hub instance is now running locally, and you can proceed with the asset registration process. Note that the local registration process does not differ from the live network process. Once you have a successful TestNet transaction, you can use the same steps to register the asset on MainNet. +- **[Test Your Runtime](/parachains/customize-runtime/pallet-development/pallet-testing/)**: Unit test pallets and mock complete runtimes to ensure everything works correctly. --- @@ -4596,507 +2604,115 @@ This page contains a list of all relevant tutorials and guides to help you get s | Title | Difficulty | Tools | Description | |---------------------------------------------------------------------------------------------------|:-----------:|--------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------| | [Deploy an ERC-20 to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/) | 🟢 Beginner | EVM Wallet, Polkadot Remix IDE | Deploy an ERC-20 token on Polkadot Hub using PolkaVM. This guide covers contract creation, compilation, deployment, and interaction via Polkadot Remix IDE. | -| [Deploy an NFT to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) | 🟢 Beginner | EVM Wallet, Polkadot Remix IDE | Deploy an NFT on Polkadot Hub using PolkaVM and OpenZeppelin. Learn how to compile, deploy, and interact with your contract using Polkadot Remix IDE. | - -## Port Ethereum DApps - -| Title | Difficulty | Tools | Description | -|-------------------------------------------------------------------------------------|:---------------:|---------|----------------------------------------------------------------------------------------------------------------------------------| -| [Deploying Uniswap V2 on Polkadot](/smart-contracts/cookbook/eth-dapps/uniswap-v2/) | 🟡 Intermediate | Hardhat | Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. | - - ---- - -Page Title: Smart Contracts Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-overview.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/overview/ -- Summary: Learn about smart contract development capabilities in the Polkadot ecosystem, either by leveraging Polkadot Hub or other alternatives. - -# Smart Contracts on Polkadot - -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction - -Polkadot offers developers multiple approaches to building and deploying smart contracts within its ecosystem. As a multi-chain network designed for interoperability, Polkadot provides various environments optimized for different developer preferences and application requirements. From native smart contract support on Polkadot Hub to specialized parachain environments, developers can choose the platform that best suits their technical needs while benefiting from Polkadot's shared security model and cross-chain messaging capabilities. - -Whether you're looking for Ethereum compatibility through EVM-based parachains like [Moonbeam](https://docs.moonbeam.network/){target=\_blank}, [Astar](https://docs.astar.network/){target=\_blank}, and [Acala](https://evmdocs.acala.network/){target=\_blank} or prefer PolkaVM-based development with [ink!](https://use.ink/docs/v6/){target=\_blank}, the Polkadot ecosystem accommodates a range of diverse developers. - -These guides explore the diverse smart contract options available in the Polkadot ecosystem, helping developers understand the unique advantages of each approach and make informed decisions about where to deploy their decentralized applications. - -## Native Smart Contracts - -### Introduction - -Polkadot Hub enables smart contract deployment and execution through PolkaVM, a cutting-edge virtual machine designed specifically for the Polkadot ecosystem. This native integration allows developers to deploy smart contracts directly on Polkadot's system chain while maintaining compatibility with Ethereum development tools and workflows. - -### Smart Contract Development - -The smart contract platform on Polkadot Hub combines _Polkadot's robust security and scalability_ with the extensive Ethereum development ecosystem. Developers can utilize familiar Ethereum libraries for contract interactions and leverage industry-standard development environments for writing and testing smart contracts. - -Polkadot Hub provides _full Ethereum JSON-RPC API compatibility_, ensuring seamless integration with existing development tools and services. This compatibility enables developers to maintain their preferred workflows while building on Polkadot's native infrastructure. - -### Technical Architecture - -PolkaVM, the underlying virtual machine, utilizes a RISC-V-based register architecture _optimized for the Polkadot ecosystem_. This design choice offers several advantages: - -- Enhanced performance for smart contract execution. -- Improved gas efficiency for complex operations. -- Native compatibility with Polkadot's runtime environment. -- Optimized storage and state management. - -### Development Tools and Resources - -Polkadot Hub supports a comprehensive suite of development tools familiar to Ethereum developers. The platform integrates with popular development frameworks, testing environments, and deployment tools. Key features include: - -- Contract development in Solidity or Rust. -- Support for standard Ethereum development libraries. -- Integration with widely used development environments. -- Access to blockchain explorers and indexing solutions. -- Compatibility with contract monitoring and management tools. - -### Cross-Chain Capabilities - -Smart contracts deployed on Polkadot Hub can leverage Polkadot's [cross-consensus messaging (XCM) protocol](/parachains/interoperability/get-started/){target=\_blank} protocol to seamlessly _transfer tokens and call functions on other blockchain networks_ within the Polkadot ecosystem, all without complex bridging infrastructure or third-party solutions. For further references, check the [Interoperability](/develop/interoperability/){target=\_blank} section. - -### Use Cases - -Polkadot Hub's smart contract platform is suitable for a wide range of applications: - -- DeFi protocols leveraging _cross-chain capabilities_. -- NFT platforms utilizing Polkadot's native token standards. -- Governance systems integrated with Polkadot's democracy mechanisms. -- Cross-chain bridges and asset management solutions. - -## Other Smart Contract Environments - -Beyond Polkadot Hub's native PolkaVM support, the ecosystem offers two main alternatives for smart contract development: - -- **EVM-compatible parachains**: Provide access to Ethereum's extensive developer ecosystem, smart contract portability, and established tooling like Hardhat, Remix, Foundry, and OpenZeppelin. The main options include Moonbeam (the first full Ethereum-compatible parachain serving as an interoperability hub), Astar (featuring dual VM support for both EVM and WebAssembly contracts), and Acala (DeFi-focused with enhanced Acala EVM+ offering advanced DeFi primitives). - -- **Rust (ink!)**: ink! is a Rust-based framework that can compile to PolkaVM. It uses [`#[ink(...)]`](https://use.ink/docs/v6/macros-attributes/){target=\_blank} attribute macros to create Polkadot SDK-compatible PolkaVM bytecode, offering strong memory safety from Rust, an advanced type system, high-performance PolkaVM execution, and platform independence with sandboxed security. - - -Each environment provides unique advantages based on developer preferences and application requirements. - -## Where to Go Next - -Developers can use their existing Ethereum development tools and connect to Polkadot Hub's RPC endpoints. The platform's Ethereum compatibility layer ensures a smooth transition for teams already building on Ethereum-compatible chains. - -Subsequent sections of this guide provide detailed information about specific development tools, advanced features, and best practices for building on Polkadot Hub. - -
- -- Guide __Libraries__ - - --- - - Explore essential libraries to optimize smart contract development and interaction. - - [:octicons-arrow-right-24: Reference](/smart-contracts/libraries/ethers-js/) - -- Guide __Dev Environments__ - - --- - - Set up your development environment for seamless contract deployment and testing. - - [:octicons-arrow-right-24: Reference](/smart-contracts/dev-environments/local-dev-node/) - -
- - ---- - -Page Title: Technical Reference Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference.md -- Canonical (HTML): https://docs.polkadot.com/reference/ -- Summary: Learn about Polkadot's technical architecture, governance framework, parachain ecosystem, and the tools you need to build and interact with the network. - -## Introduction - -The Technical Reference section provides comprehensive documentation of Polkadot's architecture, core concepts, and development tooling. Whether you're exploring how Polkadot's relay chain coordinates parachains, understanding governance mechanisms, or building applications on the network, this reference covers the technical foundations you need. - -Polkadot is a multi-chain network that enables diverse, interconnected blockchains to share security and communicate seamlessly. Understanding how these components interact from the [relay chain](/polkadot-protocol/glossary#relay-chain){target=\_blank} that validates [parachains](/polkadot-protocol/glossary#parachain){target=\_blank} to the [governance](/reference/glossary#governance){target=\_blank} mechanisms that evolve the protocol is essential for developers, validators, and network participants. - -This guide organizes technical documentation across five core areas: Polkadot Hub, Parachains, On-Chain Governance, Glossary, and Tools, each providing detailed information on different aspects of the Polkadot ecosystem. - -## Polkadot Hub - -[Polkadot Hub](/reference/polkadot-hub/){target=\_blank} is the entry point to Polkadot for all users and application developers. It provides access to essential Web3 services, including smart contracts, staking, governance, identity management, and cross-ecosystem interoperability—without requiring you to deploy or manage a parachain. - -The Hub encompasses a set of core functionality that enables developers and users to build and interact with applications on Polkadot. Key capabilities include: - -- **Smart contracts**: Deploy Ethereum-compatible smart contracts and build decentralized applications. -- **Assets and tokens**: Create, manage, and transfer fungible tokens and NFTs across the ecosystem. -- **Staking**: Participate in network security and earn rewards by staking DOT. -- **Governance**: Vote on proposals and participate in Polkadot's decentralized decision-making through OpenGov. -- **Identity services**: Register and manage on-chain identities, enabling access to governance roles and network opportunities. -- **Cross-chain interoperability**: Leverage XCM messaging to interact securely with other chains in the Polkadot ecosystem. -- **Collectives and DAOs**: Participate in governance collectives and decentralized autonomous organizations. - -## Parachains - -[Parachains](/reference/parachains/){target=\_blank} are specialized blockchains that connect to the Polkadot relay chain, inheriting its security while maintaining their own application-specific logic. The parachains documentation covers: - -- **Accounts**: Deep dive into account types, storage, and management on parachains. -- **Blocks, transactions and fees**: Understand block production, transaction inclusion, and fee mechanisms. -- **Consensus**: Learn how parachain blocks are validated and finalized through the relay chain's consensus. -- **Chain data**: Explore data structures, storage layouts, and state management. -- **Cryptography**: Study cryptographic primitives used in Polkadot SDK-based chains. -- **Data encoding**: Understand how data is encoded and decoded for blockchain compatibility. -- **Networks**: Learn about networking protocols and peer-to-peer communication. -- **Interoperability**: Discover [Cross-Consensus Messaging (XCM)](/parachains/interoperability/get-started/){target=\_blank}, the standard for cross-chain communication. -- **Randomness**: Understand how randomness is generated and used in Polkadot chains. -- **Node and runtime**: Learn about parachain nodes, runtime environments, and the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}. - -## On-Chain Governance - -[On-Chain governance](/reference/governance/){target=\_blank} is the decentralized decision-making mechanism for the Polkadot network. It manages the evolution and modification of the network's runtime logic, enabling community oversight and approval for proposed changes. The governance documentation details: - -- **OpenGov framework**: Understand Polkadot's next-generation governance system with enhanced delegation, flexible tracks, and simultaneous referendums. -- **Origins and tracks**: Learn how governance proposals are categorized, prioritized, and executed based on their privilege level and complexity. -- **Voting and delegation**: Explore conviction voting, vote delegation, and how token holders participate in governance. -- **Governance evolution**: See how Polkadot's governance has evolved from Governance V1 to the current OpenGov system. - -## Glossary - -The [Glossary](/reference/glossary/){target=\_blank} provides quick-reference definitions for Polkadot-specific terminology. Essential terms include: - -- Blockchain concepts (blocks, transactions, state) -- Consensus mechanisms (validators, collators, finality) -- Polkadot-specific terms (relay chain, parachain, XCM, FRAME) -- Network components (nodes, runtimes, storage) -- Governance terminology (origins, tracks, referendums) - -## Tools - -The [Tools](/reference/tools/){target=\_blank} section documents essential development and interaction tools for the Polkadot ecosystem: - -- **Light clients**: Lightweight solutions for interacting with the network without running full nodes. -- **JavaScript/TypeScript tools**: Libraries like [Polkadot.js API](/reference/tools/polkadot-js-api/){target=\_blank} and [PAPI](/reference/tools/papi/){target=\_blank} for building applications. -- **Rust tools**: [Polkadart](/reference/tools/polkadart/){target=\_blank} and other Rust-based libraries for SDK development. -- **Python tools**: [py-substrate-interface](/reference/tools/py-substrate-interface/){target=\_blank} for Python developers. -- **Testing and development**: Tools like [Moonwall](/reference/tools/moonwall/){target=\_blank}, [Chopsticks](/reference/tools/chopsticks/){target=\_blank}, and [Omninode](/reference/tools/omninode/){target=\_blank} for smart contract and parachain testing. -- **Indexing and monitoring**: [Sidecar](/reference/tools/sidecar/){target=\_blank} for data indexing and [Dedot](/reference/tools/dedot/){target=\_blank} for substrate interaction. -- **Cross-chain tools**: [ParaSpell](/reference/tools/paraspell/){target=\_blank} for XCM integration and asset transfers. - -## Where to Go Next - -For detailed exploration of specific areas, proceed to any of the main sections: - -
- -- Learn **Polkadot Hub** - - --- - - Understand the relay chain's role in coordinating parachains, providing shared security, and enabling governance. - - [:octicons-arrow-right-24: Reference](/reference/polkadot-hub/) - -- Learn **Parachains** - - --- - - Deep dive into parachain architecture, consensus, data structures, and building application-specific blockchains. - - [:octicons-arrow-right-24: Reference](/reference/parachains/) - -- Learn **On-Chain Governance** - - --- - - Explore Polkadot's decentralized governance framework and how to participate in network decision-making. - - [:octicons-arrow-right-24: Reference](/reference/governance/) - -- Guide **Glossary** - - --- - - Quick reference for Polkadot-specific terminology and concepts used throughout the documentation. - - [:octicons-arrow-right-24: Reference](/reference/glossary/) - -- Guide **Tools** - - --- - - Discover development tools, libraries, and frameworks for building and interacting with Polkadot. - - [:octicons-arrow-right-24: Reference](/reference/tools/) - -
- - ---- - -Page Title: Transactions - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-transactions.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/transactions/ -- Summary: Learn how to construct, submit, and validate transactions in the Polkadot SDK, covering signed, unsigned, and inherent types of transactions. - -# Transactions - -## Introduction - -Transactions are essential components of blockchain networks, enabling state changes and the execution of key operations. In the Polkadot SDK, transactions, often called extrinsics, come in multiple forms, including signed, unsigned, and inherent transactions. - -This guide walks you through the different transaction types and how they're formatted, validated, and processed within the Polkadot ecosystem. You'll also learn how to customize transaction formats and construct transactions for FRAME-based runtimes, ensuring a complete understanding of how transactions are built and executed in Polkadot SDK-based chains. - -## What Is a Transaction? - -In the Polkadot SDK, transactions represent operations that modify the chain's state, bundled into blocks for execution. The term extrinsic is often used to refer to any data that originates outside the runtime and is included in the chain. While other blockchain systems typically refer to these operations as "transactions," the Polkadot SDK adopts the broader term "extrinsic" to capture the wide variety of data types that can be added to a block. - -There are three primary types of transactions (extrinsics) in the Polkadot SDK: - -- **Signed transactions**: Signed by the submitting account, often carrying transaction fees. -- **Unsigned transactions**: Submitted without a signature, often requiring custom validation logic. -- **Inherent transactions**: Typically inserted directly into blocks by block authoring nodes, without gossiping between peers. - -Each type serves a distinct purpose, and understanding when and how to use each is key to efficiently working with the Polkadot SDK. - -### Signed Transactions - -Signed transactions require an account's signature and typically involve submitting a request to execute a runtime call. The signature serves as a form of cryptographic proof that the sender has authorized the action, using their private key. These transactions often involve a transaction fee to cover the cost of execution and incentivize block producers. - -Signed transactions are the most common type of transaction and are integral to user-driven actions, such as token transfers. For instance, when you transfer tokens from one account to another, the sending account must sign the transaction to authorize the operation. - -For example, the [`pallet_balances::Call::transfer_allow_death`](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/pallet/struct.Pallet.html#method.transfer_allow_death){target=\_blank} extrinsic in the Balances pallet allows you to transfer tokens. Since your account initiates this transaction, your account key is used to sign it. You'll also be responsible for paying the associated transaction fee, with the option to include an additional tip to incentivize faster inclusion in the block. - -### Unsigned Transactions - -Unsigned transactions do not require a signature or account-specific data from the sender. Unlike signed transactions, they do not come with any form of economic deterrent, such as fees, which makes them susceptible to spam or replay attacks. Custom validation logic must be implemented to mitigate these risks and ensure these transactions are secure. - -Unsigned transactions typically involve scenarios where including a fee or signature is unnecessary or counterproductive. However, due to the absence of fees, they require careful validation to protect the network. For example, [`pallet_im_online::Call::heartbeat`](https://paritytech.github.io/polkadot-sdk/master/pallet_im_online/pallet/struct.Pallet.html#method.heartbeat){target=\_blank} extrinsic allows validators to send a heartbeat signal, indicating they are active. Since only validators can make this call, the logic embedded in the transaction ensures that the sender is a validator, making the need for a signature or fee redundant. - -Unsigned transactions are more resource-intensive than signed ones because custom validation is required, but they play a crucial role in certain operational scenarios, especially when regular user accounts aren't involved. - -### Inherent Transactions - -Inherent transactions are a specialized type of unsigned transaction that is used primarily for block authoring. Unlike signed or other unsigned transactions, inherent transactions are added directly by block producers and are not broadcasted to the network or stored in the transaction queue. They don't require signatures or the usual validation steps and are generally used to insert system-critical data directly into blocks. - -A key example of an inherent transaction is inserting a timestamp into each block. The [`pallet_timestamp::Call::now`](https://paritytech.github.io/polkadot-sdk/master/pallet_timestamp/pallet/struct.Pallet.html#method.now-1){target=\_blank} extrinsic allows block authors to include the current time in the block they are producing. Since the block producer adds this information, there is no need for transaction validation, like signature verification. The validation in this case is done indirectly by the validators, who check whether the timestamp is within an acceptable range before finalizing the block. - -Another example is the [`paras_inherent::Call::enter`](https://paritytech.github.io/polkadot-sdk/master/polkadot_runtime_parachains/paras_inherent/pallet/struct.Pallet.html#method.enter){target=\_blank} extrinsic, which enables parachain collator nodes to send validation data to the relay chain. This inherent transaction ensures that the necessary parachain data is included in each block without the overhead of gossiped transactions. - -Inherent transactions serve a critical role in block authoring by allowing important operational data to be added directly to the chain without needing the validation processes required for standard transactions. - -## Transaction Formats - -Understanding the structure of signed and unsigned transactions is crucial for developers building on Polkadot SDK-based chains. Whether you're optimizing transaction processing, customizing formats, or interacting with the transaction pool, knowing the format of extrinsics, Polkadot's term for transactions, is essential. - -### Types of Transaction Formats - -In Polkadot SDK-based chains, extrinsics can fall into three main categories: - -- **Unchecked extrinsics**: Typically used for signed transactions that require validation. They contain a signature and additional data, such as a nonce and information for fee calculation. Unchecked extrinsics are named as such because they require validation checks before being accepted into the transaction pool. -- **Checked extrinsics**: Typically used for inherent extrinsics (unsigned transactions); these don't require signature verification. Instead, they carry information such as where the extrinsic originates and any additional data required for the block authoring process. -- **Opaque extrinsics**: Used when the format of an extrinsic is not yet fully committed or finalized. They are still decodable, but their structure can be flexible depending on the context. - -### Signed Transaction Data Structure - -A signed transaction typically includes the following components: - -- **Signature**: Verifies the authenticity of the transaction sender. -- **Call**: The actual function or method call the transaction is requesting (for example, transferring funds). -- **Nonce**: Tracks the number of prior transactions sent from the account, helping to prevent replay attacks. -- **Tip**: An optional incentive to prioritize the transaction in block inclusion. -- **Additional data**: Includes details such as spec version, block hash, and genesis hash to ensure the transaction is valid within the correct runtime and chain context. - -Here's a simplified breakdown of how signed transactions are typically constructed in a Polkadot SDK runtime: - -``` code - + + -``` - -Each part of the signed transaction has a purpose, ensuring the transaction's authenticity and context within the blockchain. - -### Signed Extensions - -Polkadot SDK also provides the concept of [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}, which allow developers to extend extrinsics with additional data or validation logic before they are included in a block. The [`SignedExtension`](https://paritytech.github.io/try-runtime-cli/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} set helps enforce custom rules or protections, such as ensuring the transaction's validity or calculating priority. - -The transaction queue regularly calls signed extensions to verify a transaction's validity before placing it in the ready queue. This safeguard ensures transactions won't fail in a block. Signed extensions are commonly used to enforce validation logic and protect the transaction pool from spam and replay attacks. - -In FRAME, a signed extension can hold any of the following types by default: - -- **[`AccountId`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/runtime/types_common/type.AccountId.html){target=\_blank}**: To encode the sender's identity. -- **[`Call`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Call){target=\_blank}**: To encode the pallet call to be dispatched. This data is used to calculate transaction fees. -- **[`AdditionalSigned`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.AdditionalSigned){target=\_blank}**: To handle any additional data to go into the signed payload allowing you to attach any custom logic prior to dispatching a transaction. -- **[`Pre`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Pre){target=\_blank}**: To encode the information that can be passed from before a call is dispatched to after it gets dispatched. - -Signed extensions can enforce checks like: - -- **[`CheckSpecVersion`](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/extensions/check_spec_version.rs.html){target=\_blank}**: Ensures the transaction is compatible with the runtime's current version. -- **[`CheckWeight`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.CheckWeight.html){target=\_blank}**: Calculates the weight (or computational cost) of the transaction, ensuring the block doesn't exceed the maximum allowed weight. - -These extensions are critical in the transaction lifecycle, ensuring that only valid and prioritized transactions are processed. - -## Transaction Construction - -Building transactions in the Polkadot SDK involves constructing a payload that can be verified, signed, and submitted for inclusion in a block. Each runtime in the Polkadot SDK has its own rules for validating and executing transactions, but there are common patterns for constructing a signed transaction. - -### Construct a Signed Transaction - -A signed transaction in the Polkadot SDK includes various pieces of data to ensure security, prevent replay attacks, and prioritize processing. Here's an overview of how to construct one: - -1. **Construct the unsigned payload**: Gather the necessary information for the call, including: - - - **Pallet index**: Identifies the pallet where the runtime function resides. - - **Function index**: Specifies the particular function to call in the pallet. - - **Parameters**: Any additional arguments required by the function call. - -2. **Create a signing payload**: Once the unsigned payload is ready, additional data must be included: - - - **Transaction nonce**: Unique identifier to prevent replay attacks. - - **Era information**: Defines how long the transaction is valid before it's dropped from the pool. - - **Block hash**: Ensures the transaction doesn't execute on the wrong chain or fork. - -3. **Sign the payload**: Using the sender's private key, sign the payload to ensure that the transaction can only be executed by the account holder. -4. **Serialize the signed payload**: Once signed, the transaction must be serialized into a binary format, ensuring the data is compact and easy to transmit over the network. -5. **Submit the serialized transaction**: Finally, submit the serialized transaction to the network, where it will enter the transaction pool and wait for processing by an authoring node. - -The following is an example of how a signed transaction might look: - -``` rust -node_runtime::UncheckedExtrinsic::new_signed( - function.clone(), // some call - sp_runtime::AccountId32::from(sender.public()).into(), // some sending account - node_runtime::Signature::Sr25519(signature.clone()), // the account's signature - extra.clone(), // the signed extensions -) -``` - -### Transaction Encoding - -Before a transaction is sent to the network, it is serialized and encoded using a structured encoding process that ensures consistency and prevents tampering: - -- **`[1]`**: Compact encoded length in bytes of the entire transaction. -- **`[2]`**: A u8 containing 1 byte to indicate whether the transaction is signed or unsigned (1 bit) and the encoded transaction version ID (7 bits). -- **`[3]`**: If signed, this field contains an account ID, an SR25519 signature, and some extra data. -- **`[4]`**: Encoded call data, including pallet and function indices and any required arguments. - -This encoded format ensures consistency and efficiency in processing transactions across the network. By adhering to this format, applications can construct valid transactions and pass them to the network for execution. - -To learn more about how compact encoding works using SCALE, see the [SCALE Codec](https://github.com/paritytech/parity-scale-codec){target=\_blank} README on GitHub. - -### Customize Transaction Construction - -Although the basic steps for constructing transactions are consistent across Polkadot SDK-based chains, developers can customize transaction formats and validation rules. For example: +| [Deploy an NFT to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) | 🟢 Beginner | EVM Wallet, Polkadot Remix IDE | Deploy an NFT on Polkadot Hub using PolkaVM and OpenZeppelin. Learn how to compile, deploy, and interact with your contract using Polkadot Remix IDE. | -- **Custom pallets**: You can define new pallets with custom function calls, each with its own parameters and validation logic. -- **Signed extensions**: Developers can implement custom extensions that modify how transactions are prioritized, validated, or included in blocks. +## Port Ethereum DApps -By leveraging Polkadot SDK's modular design, developers can create highly specialized transaction logic tailored to their chain's needs. +| Title | Difficulty | Tools | Description | +|-------------------------------------------------------------------------------------|:---------------:|---------|----------------------------------------------------------------------------------------------------------------------------------| +| [Deploying Uniswap V2 on Polkadot](/smart-contracts/cookbook/eth-dapps/uniswap-v2/) | 🟡 Intermediate | Hardhat | Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. | -## Lifecycle of a Transaction -In the Polkadot SDK, transactions are often referred to as extrinsics because the data in transactions originates outside of the runtime. These transactions contain data that initiates changes to the chain state. The most common type of extrinsic is a signed transaction, which is cryptographically verified and typically incurs a fee. This section focuses on how signed transactions are processed, validated, and ultimately included in a block. +--- -### Define Transaction Properties +Page Title: Smart Contracts Overview -The Polkadot SDK runtime defines key transaction properties, such as: +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-overview.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/overview/ +- Summary: Learn about smart contract development capabilities in the Polkadot ecosystem, either by leveraging Polkadot Hub or other alternatives. -- **Transaction validity**: Ensures the transaction meets all runtime requirements. -- **Signed or unsigned**: Identifies whether a transaction needs to be signed by an account. -- **State changes**: Determines how the transaction modifies the state of the chain. +# Smart Contracts on Polkadot -Pallets, which compose the runtime's logic, define the specific transactions that your chain supports. When a user submits a transaction, such as a token transfer, it becomes a signed transaction, verified by the user's account signature. If the account has enough funds to cover fees, the transaction is executed, and the chain's state is updated accordingly. +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. +## Introduction -### Process on a Block Authoring Node +Polkadot offers developers multiple approaches to building and deploying smart contracts within its ecosystem. As a multi-chain network designed for interoperability, Polkadot provides various environments optimized for different developer preferences and application requirements. From native smart contract support on Polkadot Hub to specialized parachain environments, developers can choose the platform that best suits their technical needs while benefiting from Polkadot's shared security model and cross-chain messaging capabilities. -In Polkadot SDK-based networks, some nodes are authorized to author blocks. These nodes validate and process transactions. When a transaction is sent to a node that can produce blocks, it undergoes a lifecycle that involves several stages, including validation and execution. Non-authoring nodes gossip the transaction across the network until an authoring node receives it. The following diagram illustrates the lifecycle of a transaction that's submitted to a network and processed by an authoring node. +Whether you're looking for Ethereum compatibility through EVM-based parachains like [Moonbeam](https://docs.moonbeam.network/){target=\_blank}, [Astar](https://docs.astar.network/){target=\_blank}, and [Acala](https://evmdocs.acala.network/){target=\_blank} or prefer PolkaVM-based development with [ink!](https://use.ink/docs/v6/){target=\_blank}, the Polkadot ecosystem accommodates a range of diverse developers. -![Transaction lifecycle diagram](/images/reference/parachains/blocks-transactions-fees/transactions/transactions-01.webp){ style="background:white" } +These guides explore the diverse smart contract options available in the Polkadot ecosystem, helping developers understand the unique advantages of each approach and make informed decisions about where to deploy their decentralized applications. -### Validate and Queue +## Native Smart Contracts -Once a transaction reaches an authoring node, it undergoes an initial validation process to ensure it meets specific conditions defined in the runtime. This validation includes checks for: +### Introduction -- **Correct nonce**: Ensures the transaction is sequentially valid for the account. -- **Sufficient funds**: Confirms the account can cover any associated transaction fees. -- **Signature validity**: Verifies that the sender's signature matches the transaction data. +Polkadot Hub enables smart contract deployment and execution through PolkaVM, a cutting-edge virtual machine designed specifically for the Polkadot ecosystem. This native integration allows developers to deploy smart contracts directly on Polkadot's system chain while maintaining compatibility with Ethereum development tools and workflows. -After these checks, valid transactions are placed in the transaction pool, where they are queued for inclusion in a block. The transaction pool regularly re-validates queued transactions to ensure they remain valid before being processed. To reach consensus, two-thirds of the nodes must agree on the order of the transactions executed and the resulting state change. Transactions are validated and queued on the local node in a transaction pool to prepare for consensus. +### Smart Contract Development -#### Transaction Pool +The smart contract platform on Polkadot Hub combines _Polkadot's robust security and scalability_ with the extensive Ethereum development ecosystem. Developers can utilize familiar Ethereum libraries for contract interactions and leverage industry-standard development environments for writing and testing smart contracts. -The transaction pool is responsible for managing valid transactions. It ensures that only transactions that pass initial validity checks are queued. Transactions that fail validation, expire, or become invalid for other reasons are removed from the pool. +Polkadot Hub provides _full Ethereum JSON-RPC API compatibility_, ensuring seamless integration with existing development tools and services. This compatibility enables developers to maintain their preferred workflows while building on Polkadot's native infrastructure. -The transaction pool organizes transactions into two queues: +### Technical Architecture -- **Ready queue**: Transactions that are valid and ready to be included in a block. -- **Future queue**: Transactions that are not yet valid but could be in the future, such as transactions with a nonce too high for the current state. +PolkaVM, the underlying virtual machine, utilizes a RISC-V-based register architecture _optimized for the Polkadot ecosystem_. This design choice offers several advantages: -Details on how the transaction pool validates transactions, including fee and signature handling, can be found in the [`validate_transaction`](https://paritytech.github.io/polkadot-sdk/master/sp_transaction_pool/runtime_api/trait.TaggedTransactionQueue.html#method.validate_transaction){target=\_blank} method. +- Enhanced performance for smart contract execution. +- Improved gas efficiency for complex operations. +- Native compatibility with Polkadot's runtime environment. +- Optimized storage and state management. -#### Invalid Transactions +### Development Tools and Resources -If a transaction is invalid, for example, due to an invalid signature or insufficient funds, it is rejected and won't be added to the block. Invalid transactions might be rejected for reasons such as: +Polkadot Hub supports a comprehensive suite of development tools familiar to Ethereum developers. The platform integrates with popular development frameworks, testing environments, and deployment tools. Key features include: -- The transaction has already been included in a block. -- The transaction's signature does not match the sender. -- The transaction is too large to fit in the current block. +- Contract development in Solidity or Rust. +- Support for standard Ethereum development libraries. +- Integration with widely used development environments. +- Access to blockchain explorers and indexing solutions. +- Compatibility with contract monitoring and management tools. -### Transaction Ordering and Priority +### Cross-Chain Capabilities -When a node is selected as the next block author, it prioritizes transactions based on weight, length, and tip amount. The goal is to fill the block with high-priority transactions without exceeding its maximum size or computational limits. Transactions are ordered as follows: +Smart contracts deployed on Polkadot Hub can leverage Polkadot's [cross-consensus messaging (XCM) protocol](/parachains/interoperability/get-started/){target=\_blank} protocol to seamlessly _transfer tokens and call functions on other blockchain networks_ within the Polkadot ecosystem, all without complex bridging infrastructure or third-party solutions. For further references, check the [Interoperability](/develop/interoperability/){target=\_blank} section. -- **Inherents first**: Inherent transactions, such as block timestamp updates, are always placed first. -- **Nonce-based ordering**: Transactions from the same account are ordered by their nonce. -- **Fee-based ordering**: Among transactions with the same nonce or priority level, those with higher fees are prioritized. +### Use Cases -### Transaction Execution +Polkadot Hub's smart contract platform is suitable for a wide range of applications: -Once a block author selects transactions from the pool, the transactions are executed in priority order. As each transaction is processed, the state changes are written directly to the chain's storage. It's important to note that these changes are not cached, meaning a failed transaction won't revert earlier state changes, which could leave the block in an inconsistent state. +- DeFi protocols leveraging _cross-chain capabilities_. +- NFT platforms utilizing Polkadot's native token standards. +- Governance systems integrated with Polkadot's democracy mechanisms. +- Cross-chain bridges and asset management solutions. -Events are also written to storage. Runtime logic should not emit an event before performing the associated actions. If the associated transaction fails after the event was emitted, the event will not revert. +## Other Smart Contract Environments -## Transaction Mortality +Beyond Polkadot Hub's native PolkaVM support, the ecosystem offers two main alternatives for smart contract development: -Transactions in the network can be configured as either mortal (with expiration) or immortal (without expiration). Every transaction payload contains a block checkpoint (reference block number and hash) and an era/validity period that determines how many blocks after the checkpoint the transaction remains valid. +- **EVM-compatible parachains**: Provide access to Ethereum's extensive developer ecosystem, smart contract portability, and established tooling like Hardhat, Remix, Foundry, and OpenZeppelin. The main options include Moonbeam (the first full Ethereum-compatible parachain serving as an interoperability hub), Astar (featuring dual VM support for both EVM and WebAssembly contracts), and Acala (DeFi-focused with enhanced Acala EVM+ offering advanced DeFi primitives). -When a transaction is submitted, the network validates it against these parameters. If the transaction is not included in a block within the specified validity window, it is automatically removed from the transaction queue. +- **Rust (ink!)**: ink! is a Rust-based framework that can compile to PolkaVM. It uses [`#[ink(...)]`](https://use.ink/docs/v6/macros-attributes/){target=\_blank} attribute macros to create Polkadot SDK-compatible PolkaVM bytecode, offering strong memory safety from Rust, an advanced type system, high-performance PolkaVM execution, and platform independence with sandboxed security. -- **Mortal transactions**: Have a finite lifespan and will expire after a specified number of blocks. For example, a transaction with a block checkpoint of 1000 and a validity period of 64 blocks will be valid from blocks 1000 to 1064. -- **Immortal transactions**: Never expire and remain valid indefinitely. To create an immortal transaction, set the block checkpoint to 0 (genesis block), use the genesis hash as a reference, and set the validity period to 0. +Each environment provides unique advantages based on developer preferences and application requirements. -However, immortal transactions pose significant security risks through replay attacks. If an account is reaped (balance drops to zero, account removed) and later re-funded, malicious actors can replay old immortal transactions. +## Where to Go Next -The blockchain maintains only a limited number of prior block hashes for reference validation, called `BlockHashCount`. If your validity period exceeds `BlockHashCount`, the effective validity period becomes the minimum of your specified period and the block hash count. +Developers can use their existing Ethereum development tools and connect to Polkadot Hub's RPC endpoints. The platform's Ethereum compatibility layer ensures a smooth transition for teams already building on Ethereum-compatible chains. -## Unique Identifiers for Extrinsics +Subsequent sections of this guide provide detailed information about specific development tools, advanced features, and best practices for building on Polkadot Hub. -Transaction hashes are **not unique identifiers** in Polkadot SDK-based chains. +
-Key differences from traditional blockchains: +- Guide __Libraries__ -- Transaction hashes serve only as fingerprints of transaction information. -- Multiple valid transactions can share the same hash. -- Hash uniqueness assumptions lead to serious issues. + --- -For example, when an account is reaped (removed due to insufficient balance) and later recreated, it resets to nonce 0, allowing identical transactions to be valid at different points: + Explore essential libraries to optimize smart contract development and interaction. -| Block | Extrinsic Index | Hash | Origin | Nonce | Call | Result | -|-------|----------------|------|-----------|-------|---------------------|-------------------------------| -| 100 | 0 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Account A reaped | -| 150 | 5 | 0x02 | Account B | 4 | Transfer 7 DOT to A | Account A created (nonce = 0) | -| 200 | 2 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Successful transaction | + [:octicons-arrow-right-24: Reference](/smart-contracts/libraries/ethers-js/) -Notice that blocks 100 and 200 contain transactions with identical hashes (0x01) but are completely different, valid operations occurring at different times. +- Guide __Dev Environments__ -Additional complexity comes from Polkadot SDK's origin abstraction. Origins can represent collectives, governance bodies, or other non-account entities that don't maintain nonces like regular accounts and might dispatch identical calls multiple times with the same hash values. Each execution occurs in different chain states with different results. + --- -The correct way to uniquely identify an extrinsic on a Polkadot SDK-based chain is to use the block ID (height or hash) and the extrinsic index. Since the Polkadot SDK defines blocks as headers plus ordered arrays of extrinsics, the index position within a canonical block provides guaranteed uniqueness. + Set up your development environment for seamless contract deployment and testing. -## Additional Resources + [:octicons-arrow-right-24: Reference](/smart-contracts/dev-environments/local-dev-node/) -For a video overview of the lifecycle of transactions and the types of transactions that exist, see the [Transaction lifecycle](https://www.youtube.com/watch?v=3pfM0GOp02c){target=\_blank} seminar from Parity Tech. +
--- @@ -5204,436 +2820,3 @@ The system maintains precise conversion mechanisms between: - Different resource metrics within the multi-dimensional model. This ensures accurate fee calculation while maintaining compatibility with existing Ethereum tools and workflows. - - ---- - -Page Title: Transactions Weights and Fees - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-fees.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/fees/ -- Summary: Overview of transaction weights and fees in Polkadot SDK chains, detailing how fees are calculated using a defined formula and runtime specifics. - -# Transactions Weights and Fees - -## Introductions - -When transactions are executed, or data is stored on-chain, the activity changes the chain's state and consumes blockchain resources. Because the resources available to a blockchain are limited, managing how operations on-chain consume them is important. In addition to being limited in practical terms, such as storage capacity, blockchain resources represent a potential attack vector for malicious users. For example, a malicious user might attempt to overload the network with messages to stop the network from producing new blocks. To protect blockchain resources from being drained or overloaded, you need to manage how they are made available and how they are consumed. The resources to be aware of include: - -- Memory usage -- Storage input and output -- Computation -- Transaction and block size -- State database size - -The Polkadot SDK provides block authors with several ways to manage access to resources and to prevent individual components of the chain from consuming too much of any single resource. Two of the most important mechanisms available to block authors are weights and transaction fees. - -[Weights](/reference/glossary/#weight){target=\_blank} manage the time it takes to validate a block and characterize the time it takes to execute the calls in the block's body. By controlling the execution time a block can consume, weights set limits on storage input, output, and computation. - -Some of the weight allowed for a block is consumed as part of the block's initialization and finalization. The weight might also be used to execute mandatory inherent extrinsic calls. To help ensure blocks don’t consume too much execution time and prevent malicious users from overloading the system with unnecessary calls, weights are combined with transaction fees. - -[Transaction fees](/reference/parachains/blocks-transactions-fees/transactions/#transaction-fees){target=\_blank} provide an economic incentive to limit execution time, computation, and the number of calls required to perform operations. Transaction fees are also used to make the blockchain economically sustainable because they are typically applied to transactions initiated by users and deducted before a transaction request is executed. - -## How Fees are Calculated - -The final fee for a transaction is calculated using the following parameters: - -- **`base fee`**: This is the minimum amount a user pays for a transaction. It is declared a base weight in the runtime and converted to a fee using the [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} conversion. -- **`weight fee`**: A fee proportional to the execution time (input and output and computation) that a transaction consumes. -- **`length fee`**: A fee proportional to the encoded length of the transaction. -- **`tip`**: An optional tip to increase the transaction’s priority, giving it a higher chance to be included in the transaction queue. - -The base fee and proportional weight and length fees constitute the inclusion fee. The inclusion fee is the minimum fee that must be available for a transaction to be included in a block. - -```text -inclusion fee = base fee + weight fee + length fee -``` - -Transaction fees are withdrawn before the transaction is executed. After the transaction is executed, the weight can be adjusted to reflect the resources used. If a transaction uses fewer resources than expected, the transaction fee is corrected, and the adjusted transaction fee is deposited. - -## Using the Transaction Payment Pallet - -The [Transaction Payment pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/transaction-payment){target=\_blank} provides the basic logic for calculating the inclusion fee. You can also use the Transaction Payment pallet to: - -- Convert a weight value into a deductible fee based on a currency type using [`Config::WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank}. -- Update the fee for the next block by defining a multiplier based on the chain’s final state at the end of the previous block using [`Config::FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank}. -- Manage the withdrawal, refund, and deposit of transaction fees using [`Config::OnChargeTransaction`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.OnChargeTransaction){target=\_blank}. - -You can learn more about these configuration traits in the [Transaction Payment documentation](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_payment/index.html){target=\_blank}. - -### Understanding the Inclusion Fee - -The formula for calculating the inclusion fee is as follows: - -```text -inclusion_fee = base_fee + length_fee + [targeted_fee_adjustment * weight_fee] -``` - -And then, for calculating the final fee: - -```text -final_fee = inclusion_fee + tip -``` - -In the first formula, the `targeted_fee_adjustment` is a multiplier that can tune the final fee based on the network’s congestion. - -- The `base_fee` derived from the base weight covers inclusion overhead like signature verification. -- The `length_fee` is a per-byte fee that is multiplied by the length of the encoded extrinsic. -- The `weight_fee` fee is calculated using two parameters: - - The `ExtrinsicBaseWeight` that is declared in the runtime and applies to all extrinsics. - - The `#[pallet::weight]` annotation that accounts for an extrinsic's complexity. - -To convert the weight to `Currency`, the runtime must define a `WeightToFee` struct that implements a conversion function, [`Convert`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/struct.Pallet.html#method.weight_to_fee){target=\_blank}. - -Note that the extrinsic sender is charged the inclusion fee before the extrinsic is invoked. The fee is deducted from the sender's balance even if the transaction fails upon execution. - -### Accounts with an Insufficient Balance - -If an account does not have a sufficient balance to pay the inclusion fee and remain alive—that is, enough to pay the inclusion fee and maintain the minimum existential deposit—then you should ensure the transaction is canceled so that no fee is deducted and the transaction does not begin execution. - -The Polkadot SDK doesn't enforce this rollback behavior. However, this scenario would be rare because the transaction queue and block-making logic perform checks to prevent it before adding an extrinsic to a block. - -### Fee Multipliers - -The inclusion fee formula always results in the same fee for the same input. However, weight can be dynamic and—based on how [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} is defined—the final fee can include some degree of variability. -The Transaction Payment pallet provides the [`FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank} configurable parameter to account for this variability. - -The Polkadot network inspires the default update function and implements a targeted adjustment in which a target saturation level of block weight is defined. If the previous block is more saturated, the fees increase slightly. Similarly, if the last block has fewer transactions than the target, fees are decreased by a small amount. For more information about fee multiplier adjustments, see the [Web3 Research Page](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank}. - -## Transactions with Special Requirements - -Inclusion fees must be computable before execution and can only represent fixed logic. Some transactions warrant limiting resources with other strategies. For example: - -- Bonds are a type of fee that might be returned or slashed after some on-chain event. For example, you might want to require users to place a bond to participate in a vote. The bond might then be returned at the end of the referendum or slashed if the voter attempted malicious behavior. -- Deposits are fees that might be returned later. For example, you might require users to pay a deposit to execute an operation that uses storage. The user’s deposit could be returned if a subsequent operation frees up storage. -- Burn operations are used to pay for a transaction based on its internal logic. For example, a transaction might burn funds from the sender if the transaction creates new storage items to pay for the increased state size. -- Limits enable you to enforce constant or configurable limits on specific operations. For example, the default [Staking pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/staking){target=\_blank} only allows nominators to nominate 16 validators to limit the complexity of the validator election process. - -It is important to note that if you query the chain for a transaction fee, it only returns the inclusion fee. - -## Default Weight Annotations - -All dispatchable functions in the Polkadot SDK must specify a weight. The way of doing that is using the annotation-based system that lets you combine fixed values for database read/write weight and/or fixed values based on benchmarks. The most basic example would look like this: - -```rust -#[pallet::weight(100_000)] -fn my_dispatchable() { - // ... -} -``` - -Note that the [`ExtrinsicBaseWeight`](https://crates.parity.io/frame_support/weights/constants/struct.ExtrinsicBaseWeight.html){target=\_blank} is automatically added to the declared weight to account for the costs of simply including an empty extrinsic into a block. - -### Weights and Database Read/Write Operations - -To make weight annotations independent of the deployed database backend, they are defined as a constant and then used in the annotations when expressing database accesses performed by the dispatchable: - -```rust -#[pallet::weight(T::DbWeight::get().reads_writes(1, 2) + 20_000)] -fn my_dispatchable() { - // ... -} -``` - -This dispatchable allows one database to read and two to write, in addition to other things that add the additional 20,000. Database access is generally every time a value declared inside the [`#[pallet::storage]`](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/attr.storage.html){target=\_blank} block is accessed. However, unique accesses are counted because after a value is accessed, it is cached, and reaccessing it does not result in a database operation. That is: - -- Multiple reads of the exact value count as one read. -- Multiple writes of the exact value count as one write. -- Multiple reads of the same value, followed by a write to that value, count as one read and one write. -- A write followed by a read-only counts as one write. - -### Dispatch Classes - -Dispatches are broken into three classes: - -- Normal -- Operational -- Mandatory - -If a dispatch is not defined as `Operational` or `Mandatory` in the weight annotation, the dispatch is identified as `Normal` by default. You can specify that the dispatchable uses another class like this: - -```rust -#[pallet::dispatch((DispatchClass::Operational))] -fn my_dispatchable() { - // ... -} -``` - -This tuple notation also allows you to specify a final argument determining whether the user is charged based on the annotated weight. If you don't specify otherwise, `Pays::Yes` is assumed: - -```rust -#[pallet::dispatch(DispatchClass::Normal, Pays::No)] -fn my_dispatchable() { - // ... -} -``` - -#### Normal Dispatches - -Dispatches in this class represent normal user-triggered transactions. These types of dispatches only consume a portion of a block's total weight limit. For information about the maximum portion of a block that can be consumed for normal dispatches, see [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Normal dispatches are sent to the transaction pool. - -#### Operational Dispatches - -Unlike normal dispatches, which represent the usage of network capabilities, operational dispatches are those that provide network capabilities. Operational dispatches can consume the entire weight limit of a block. They are not bound by the [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Dispatches in this class are given maximum priority and are exempt from paying the [`length_fee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/){target=\_blank}. - -#### Mandatory Dispatches - -Mandatory dispatches are included in a block even if they cause the block to surpass its weight limit. You can only use the mandatory dispatch class for inherent transactions that the block author submits. This dispatch class is intended to represent functions in the block validation process. Because these dispatches are always included in a block regardless of the function weight, the validation process must prevent malicious nodes from abusing the function to craft valid but impossibly heavy blocks. You can typically accomplish this by ensuring that: - -- The operation performed is always light. -- The operation can only be included in a block once. - -To make it more difficult for malicious nodes to abuse mandatory dispatches, they cannot be included in blocks that return errors. This dispatch class serves the assumption that it is better to allow an overweight block to be created than not to allow any block to be created at all. - -### Dynamic Weights - -In addition to purely fixed weights and constants, the weight calculation can consider the input arguments of a dispatchable. The weight should be trivially computable from the input arguments with some basic arithmetic: - -```rust -use frame_support:: { - dispatch:: { - DispatchClass::Normal, - Pays::Yes, - }, - weights::Weight, -}; - -#[pallet::weight(FunctionOf( - |args: (&Vec,)| args.0.len().saturating_mul(10_000), - ) -] -fn handle_users(origin, calls: Vec) { - // Do something per user -} -``` - -## Post Dispatch Weight Correction - -Depending on the execution logic, a dispatchable function might consume less weight than was prescribed pre-dispatch. To correct weight, the function declares a different return type and returns its actual weight: - -```rust -#[pallet::weight(10_000 + 500_000_000)] -fn expensive_or_cheap(input: u64) -> DispatchResultWithPostInfo { - let was_heavy = do_calculation(input); - - if (was_heavy) { - // None means "no correction" from the weight annotation. - Ok(None.into()) - } else { - // Return the actual weight consumed. - Ok(Some(10_000).into()) - } -} -``` - -## Custom Fees - -You can also define custom fee systems through custom weight functions or inclusion fee functions. - -### Custom Weights - -Instead of using the default weight annotations, you can create a custom weight calculation type using the weights module. The custom weight calculation type must implement the following traits: - -- [`WeighData`](https://crates.parity.io/frame_support/weights/trait.WeighData.html){target=\_blank} to determine the weight of the dispatch. -- [`ClassifyDispatch`](https://crates.parity.io/frame_support/weights/trait.ClassifyDispatch.html){target=\_blank} to determine the class of the dispatch. -- [`PaysFee`](https://crates.parity.io/frame_support/weights/trait.PaysFee.html){target=\_blank} to determine whether the sender of the dispatch pays fees. - -The Polkadot SDK then bundles the output information of the three traits into the [`DispatchInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_support/dispatch/struct.DispatchInfo.html){target=\_blank} struct and provides it by implementing the [`GetDispatchInfo`](https://docs.rs/frame-support/latest/frame_support/dispatch/trait.GetDispatchInfo.html){target=\_blank} for all `Call` variants and opaque extrinsic types. This is used internally by the System and Executive modules. - -`ClassifyDispatch`, `WeighData`, and `PaysFee` are generic over T, which gets resolved into the tuple of all dispatch arguments except for the origin. The following example illustrates a struct that calculates the weight as `m * len(args)`, where `m` is a given multiplier and args is the concatenated tuple of all dispatch arguments. In this example, the dispatch class is `Operational` if the transaction has more than 100 bytes of length in arguments and will pay fees if the encoded length exceeds 10 bytes. - -```rust -struct LenWeight(u32); -impl WeighData for LenWeight { - fn weigh_data(&self, target: T) -> Weight { - let multiplier = self.0; - let encoded_len = target.encode().len() as u32; - multiplier * encoded_len - } -} - -impl ClassifyDispatch for LenWeight { - fn classify_dispatch(&self, target: T) -> DispatchClass { - let encoded_len = target.encode().len() as u32; - if encoded_len > 100 { - DispatchClass::Operational - } else { - DispatchClass::Normal - } - } -} - -impl PaysFee { - fn pays_fee(&self, target: T) -> Pays { - let encoded_len = target.encode().len() as u32; - if encoded_len > 10 { - Pays::Yes - } else { - Pays::No - } - } -} -``` - -A weight calculator function can also be coerced to the final type of the argument instead of defining it as a vague type that can be encoded. The code would roughly look like this: - -```rust -struct CustomWeight; -impl WeighData<(&u32, &u64)> for CustomWeight { - fn weigh_data(&self, target: (&u32, &u64)) -> Weight { - ... - } -} - -// given a dispatch: -#[pallet::call] -impl, I: 'static> Pallet { - #[pallet::weight(CustomWeight)] - fn foo(a: u32, b: u64) { ... } -} -``` - -In this example, the `CustomWeight` can only be used in conjunction with a dispatch with a particular signature `(u32, u64)`, as opposed to `LenWeight`, which can be used with anything because there aren't any assumptions about ``. - -#### Custom Inclusion Fee - -The following example illustrates how to customize your inclusion fee. You must configure the appropriate associated types in the respective module. - -```rust -// Assume this is the balance type -type Balance = u64; - -// Assume we want all the weights to have a `100 + 2 * w` conversion to fees -struct CustomWeightToFee; -impl WeightToFee for CustomWeightToFee { - fn convert(w: Weight) -> Balance { - let a = Balance::from(100); - let b = Balance::from(2); - let w = Balance::from(w); - a + b * w - } -} - -parameter_types! { - pub const ExtrinsicBaseWeight: Weight = 10_000_000; -} - -impl frame_system::Config for Runtime { - type ExtrinsicBaseWeight = ExtrinsicBaseWeight; -} - -parameter_types! { - pub const TransactionByteFee: Balance = 10; -} - -impl transaction_payment::Config { - type TransactionByteFee = TransactionByteFee; - type WeightToFee = CustomWeightToFee; - type FeeMultiplierUpdate = TargetedFeeAdjustment; -} - -struct TargetedFeeAdjustment(sp_std::marker::PhantomData); -impl> WeightToFee for TargetedFeeAdjustment { - fn convert(multiplier: Fixed128) -> Fixed128 { - // Don't change anything. Put any fee update info here. - multiplier - } -} -``` - -## Additional Resources - -You now know the weight system, how it affects transaction fee computation, and how to specify weights for your dispatchable calls. The next step is determining the correct weight for your dispatchable operations. You can use Substrate benchmarking functions and frame-benchmarking calls to test your functions with different parameters and empirically determine the proper weight in their worst-case scenarios. - -- [Benchmark](/parachains/customize-runtime/pallet-development/benchmark-pallet/) -- [`SignedExtension`](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} -- [Custom weights for the Example pallet](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/substrate/frame/examples/basic/src/weights.rs){target=\_blank} -- [Web3 Foundation Research](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank} - - ---- - -Page Title: XCM Tools - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-xcm-tools.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/xcm-tools/ -- Summary: Explore essential XCM tools across Polkadot, crafted to enhance cross-chain functionality and integration within the ecosystem. - -# XCM Tools - -## Introduction - -As described in the [Interoperability](/develop/interoperability){target=\_blank} section, XCM (Cross-Consensus Messaging) is a protocol used in the Polkadot and Kusama ecosystems to enable communication and interaction between chains. It facilitates cross-chain communication, allowing assets, data, and messages to flow seamlessly across the ecosystem. - -As XCM is central to enabling communication between blockchains, developers need robust tools to help interact with, build, and test XCM messages. Several XCM tools simplify working with the protocol by providing libraries, frameworks, and utilities that enhance the development process, ensuring that applications built within the Polkadot ecosystem can efficiently use cross-chain functionalities. - -## Popular XCM Tools - -### Moonsong Labs XCM Tools - -[Moonsong Labs XCM Tools](https://github.com/Moonsong-Labs/xcm-tools){target=\_blank} provides a collection of scripts for managing and testing XCM operations between Polkadot SDK-based runtimes. These tools allow performing tasks like asset registration, channel setup, and XCM initialization. Key features include: - -- **Asset registration**: Registers assets, setting units per second (up-front fees), and configuring error (revert) codes. -- **XCM initializer**: Initializes XCM, sets default XCM versions, and configures revert codes for XCM-related precompiles. -- **HRMP manipulator**: Manages HRMP channel actions, including opening, accepting, or closing channels. -- **XCM-Transactor-Info-Setter**: Configures transactor information, including extra weight and fee settings. -- **Decode XCM**: Decodes XCM messages on the relay chain or parachains to help interpret cross-chain communication. - -To get started, clone the repository and install the required dependencies: - -```bash -git clone https://github.com/Moonsong-Labs/xcm-tools && -cd xcm-tools && -yarn install -``` - -For a full overview of each script, visit the [scripts](https://github.com/Moonsong-Labs/xcm-tools/tree/main/scripts){target=\_blank} directory or refer to the [official documentation](https://github.com/Moonsong-Labs/xcm-tools/blob/main/README.md){target=\_blank} on GitHub. - -### ParaSpell - -[ParaSpell](/reference/tools/paraspell/){target=\_blank} is a collection of open-source XCM tools that streamline cross-chain asset transfers and interactions across the Polkadot and Kusama ecosystems. It provides developers with an intuitive interface to build, test, and deploy interoperable dApps, featuring message composition, decoding, and practical utilities for parachain interactions that simplify debugging and cross-chain communication optimization. - -### Astar XCM Tools - -The [Astar parachain](https://github.com/AstarNetwork/Astar/tree/master){target=\_blank} offers a crate with a set of utilities for interacting with the XCM protocol. The [xcm-tools](https://github.com/AstarNetwork/Astar/tree/master/bin/xcm-tools){target=\_blank} crate provides a straightforward method for users to locate a sovereign account or calculate an XC20 asset ID. Some commands included by the xcm-tools crate allow users to perform the following tasks: - -- **Sovereign accounts**: Obtain the sovereign account address for any parachain, either on the Relay Chain or for sibling parachains, using a simple command. -- **XC20 EVM addresses**: Generate XC20-compatible Ethereum addresses for assets by entering the asset ID, making it easy to integrate assets across Ethereum-compatible environments. -- **Remote accounts**: Retrieve remote account addresses needed for multi-location compatibility, using flexible options to specify account types and parachain IDs. - -To start using these tools, clone the [Astar repository](https://github.com/AstarNetwork/Astar){target=\_blank} and compile the xcm-tools package: - -```bash -git clone https://github.com/AstarNetwork/Astar && -cd Astar && -cargo build --release -p xcm-tools -``` - -After compiling, verify the setup with the following command: - -```bash -./target/release/xcm-tools --help -``` -For more details on using Astar xcm-tools, consult the [official documentation](https://docs.astar.network/docs/learn/interoperability/xcm/integration/tools/){target=\_blank}. - -### Chopsticks - -The Chopsticks library provides XCM functionality for testing XCM messages across networks, enabling you to fork multiple parachains along with a relay chain. For further details, see the [Chopsticks documentation](/tutorials/polkadot-sdk/testing/fork-live-chains/){target=\_blank} about XCM. - -### Moonbeam XCM SDK - -The [Moonbeam XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk){target=\_blank} enables developers to easily transfer assets between chains, either between parachains or between a parachain and the relay chain, within the Polkadot/Kusama ecosystem. With the SDK, you don't need to worry about determining the [Multilocation](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#7-universal-consensus-location-identifiers){target=\_blank} of the origin or destination assets or which extrinsics are used on which networks. - -The SDK consists of two main packages: - -- **[XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/sdk){target=\_blank}**: Core SDK for executing XCM transfers between chains in the Polkadot/Kusama ecosystem. -- **[MRL SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/mrl){target=\_blank}**: Extension of the XCM SDK for transferring liquidity into and across the Polkadot ecosystem from other ecosystems like Ethereum. - -Key features include: - -- **Simplified asset transfers**: Abstracts away complex multilocation determinations and extrinsic selection. -- **Cross-ecosystem support**: Enables transfers between Polkadot/Kusama chains and external ecosystems. -- **Developer-friendly API**: Provides intuitive interfaces for cross-chain functionality. -- **Comprehensive documentation**: Includes usage guides and API references for both packages. - -For detailed usage examples and API documentation, visit the [official Moonbeam XCM SDK documentation](https://moonbeam-foundation.github.io/xcm-sdk/latest/){target=\_blank}. diff --git a/.ai/categories/dapps.md b/.ai/categories/dapps.md index dc3b8ec73..59fc473ca 100644 --- a/.ai/categories/dapps.md +++ b/.ai/categories/dapps.md @@ -474,440 +474,6 @@ Launch your parachain locally and start producing blocks: ---- - -Page Title: Blocks - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-blocks.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/blocks/ -- Summary: Understand how blocks are produced, validated, and imported in Polkadot SDK-based blockchains, covering initialization, finalization, and authoring processes. - -# Blocks - -## Introduction - -In the Polkadot SDK, blocks are fundamental to the functioning of the blockchain, serving as containers for [transactions](/reference/parachains/blocks-transactions-fees/transactions/){target=\_blank} and changes to the chain's state. Blocks consist of headers and an array of transactions, ensuring the integrity and validity of operations on the network. This guide explores the essential components of a block, the process of block production, and how blocks are validated and imported across the network. By understanding these concepts, developers can better grasp how blockchains maintain security, consistency, and performance within the Polkadot ecosystem. - -## What is a Block? - -In the Polkadot SDK, a block is a fundamental unit that encapsulates both the header and an array of transactions. The block header includes critical metadata to ensure the integrity and sequence of the blockchain. Here's a breakdown of its components: - -- **Block height**: Indicates the number of blocks created in the chain so far. -- **Parent hash**: The hash of the previous block, providing a link to maintain the blockchain's immutability. -- **Transaction root**: Cryptographic digest summarizing all transactions in the block. -- **State root**: A cryptographic digest representing the post-execution state. -- **Digest**: Additional information that can be attached to a block, such as consensus-related messages. - -Each transaction is part of a series that is executed according to the runtime's rules. The transaction root is a cryptographic digest of this series, which prevents alterations and enables succinct verification by light clients. This verification process allows light clients to confirm whether a transaction exists in a block with only the block header, avoiding downloading the entire block. - -## Block Production - -When an authoring node is authorized to create a new block, it selects transactions from the transaction queue based on priority. This step, known as block production, relies heavily on the executive module to manage the initialization and finalization of blocks. The process is summarized as follows: - -### Initialize Block - -The block initialization process begins with a series of function calls that prepare the block for transaction execution: - -1. **Call `on_initialize`**: The executive module calls the [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} hook from the system pallet and other runtime pallets to prepare for the block's transactions. -2. **Coordinate runtime calls**: Coordinates function calls in the order defined by the transaction queue. -3. **Verify information**: Once [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} functions are executed, the executive module checks the parent hash in the block header and the trie root to verify information is consistent. - -### Finalize Block - -Once transactions are processed, the block must be finalized before being broadcast to the network. The finalization steps are as follows: - -1. **Call `on_finalize`**: The executive module calls the [`on_finalize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_finalize){target=\_blank} hooks in each pallet to ensure any remaining state updates or checks are completed before the block is sealed and published. -2. **Verify information**: The block's digest and storage root in the header are checked against the initialized block to ensure consistency. -3. **Call `on_idle`**: The [`on_idle`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_idle){target=\_blank} hook is triggered to process any remaining tasks using the leftover weight from the block. - -## Block Authoring and Import - -Once the block is finalized, it is gossiped to other nodes in the network. Nodes follow this procedure: - -1. **Receive transactions**: The authoring node collects transactions from the network. -2. **Validate**: Transactions are checked for validity. -3. **Queue**: Valid transactions are placed in the transaction pool for execution. -4. **Execute**: State changes are made as the transactions are executed. -5. **Publish**: The finalized block is broadcast to the network. - -### Block Import Queue - -After a block is published, other nodes on the network can import it into their chain state. The block import queue is part of the outer node in every Polkadot SDK-based node and ensures incoming blocks are valid before adding them to the node's state. - -In most cases, you don't need to know details about how transactions are gossiped or how other nodes on the network import blocks. The following traits are relevant, however, if you plan to write any custom consensus logic or want a deeper dive into the block import queue: - -- **[`ImportQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.ImportQueue.html){target=\_blank}**: The trait that defines the block import queue. -- **[`Link`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Link.html){target=\_blank}**: The trait that defines the link between the block import queue and the network. -- **[`BasicQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/struct.BasicQueue.html){target=\_blank}**: A basic implementation of the block import queue. -- **[`Verifier`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Verifier.html){target=\_blank}**: The trait that defines the block verifier. -- **[`BlockImport`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/block_import/trait.BlockImport.html){target=\_blank}**: The trait that defines the block import process. - -These traits govern how blocks are validated and imported across the network, ensuring consistency and security. - -## Additional Resources - -To learn more about the block structure in the Polkadot SDK runtime, see the [`Block` reference](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.Block.html){target=\_blank} entry in the Rust Docs. - - ---- - -Page Title: Chain Data - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-chain-data.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/chain-data/ -- Summary: Learn how to expose and utilize chain data for blockchain applications. Discover runtime metadata, RPC APIs, and tools for efficient development. - -# Chain Data - -## Introduction - -Understanding and leveraging on-chain data is a fundamental aspect of blockchain development. Whether you're building frontend applications or backend systems, accessing and decoding runtime metadata is vital to interacting with the blockchain. This guide introduces you to the tools and processes for generating and retrieving metadata, explains its role in application development, and outlines the additional APIs available for interacting with a Polkadot node. By mastering these components, you can ensure seamless communication between your applications and the blockchain. - -## Application Development - -You might not be directly involved in building frontend applications as a blockchain developer. However, most applications that run on a blockchain require some form of frontend or user-facing client to enable users or other programs to access and modify the data that the blockchain stores. For example, you might develop a browser-based, mobile, or desktop application that allows users to submit transactions, post articles, view their assets, or track previous activity. The backend for that application is configured in the runtime logic for your blockchain, but the frontend client makes the runtime features accessible to your users. - -For your custom chain to be useful to others, you'll need to provide a client application that allows users to view, interact with, or update information that the blockchain keeps track of. In this article, you'll learn how to expose information about your runtime so that client applications can use it, see examples of the information exposed, and explore tools and libraries that use it. - -## Understand Metadata - -Polkadot SDK-based blockchain networks are designed to expose their runtime information, allowing developers to learn granular details regarding pallets, RPC calls, and runtime APIs. The metadata also exposes their related documentation. The chain's metadata is [SCALE-encoded](/reference/parachains/data-encoding/){target=\_blank}, allowing for the development of browser-based, mobile, or desktop applications to support the chain's runtime upgrades seamlessly. It is also possible to develop applications compatible with multiple Polkadot SDK-based chains simultaneously. - -## Expose Runtime Information as Metadata - -To interact with a node or the state of the blockchain, you need to know how to connect to the chain and access the exposed runtime features. This interaction involves a Remote Procedure Call (RPC) through a node endpoint address, commonly through a secure web socket connection. - -An application developer typically needs to know the contents of the runtime logic, including the following details: - -- Version of the runtime the application is connecting to. -- Supported APIs. -- Implemented pallets. -- Defined functions and corresponding type signatures. -- Defined custom types. -- Exposed parameters users can set. - -As the Polkadot SDK is modular and provides a composable framework for building blockchains, there are limitless opportunities to customize the schema of properties. Each runtime can be configured with its properties, including function calls and types, which can be changed over time with runtime upgrades. - -The Polkadot SDK enables you to generate the runtime metadata schema to capture information unique to a runtime. The metadata for a runtime describes the pallets in use and types defined for a specific runtime version. The metadata includes information about each pallet's storage items, functions, events, errors, and constants. The metadata also provides type definitions for any custom types included in the runtime. - -Metadata provides a complete inventory of a chain's runtime. It is key to enabling client applications to interact with the node, parse responses, and correctly format message payloads sent back to that chain. - -## Generate Metadata - -To efficiently use the blockchain's networking resources and minimize the data transmitted over the network, the metadata schema is encoded using the [Parity SCALE Codec](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank}. This encoding is done automatically through the [`scale-info`](https://docs.rs/scale-info/latest/scale_info/){target=\_blank}crate. - -At a high level, generating the metadata involves the following steps: - -1. The pallets in the runtime logic expose callable functions, types, parameters, and documentation that need to be encoded in the metadata. -2. The `scale-info` crate collects type information for the pallets in the runtime, builds a registry of the pallets that exist in a particular runtime, and the relevant types for each pallet in the registry. The type information is detailed enough to enable encoding and decoding for every type. -3. The [`frame-metadata`](https://github.com/paritytech/frame-metadata){target=\_blank} crate describes the structure of the runtime based on the registry provided by the `scale-info` crate. -4. Nodes provide the RPC method `state_getMetadata` to return a complete description of all the types in the current runtime as a hex-encoded vector of SCALE-encoded bytes. - -## Retrieve Runtime Metadata - -The type information provided by the metadata enables applications to communicate with nodes using different runtime versions and across chains that expose different calls, events, types, and storage items. The metadata also allows libraries to generate a substantial portion of the code needed to communicate with a given node, enabling libraries like [`subxt`](https://github.com/paritytech/subxt){target=\_blank} to generate frontend interfaces that are specific to a target chain. - -### Use Polkadot.js - -Visit the [Polkadot.js Portal](https://polkadot.js.org/apps/#/rpc){target=\_blank} and select the **Developer** dropdown in the top banner. Select **RPC Calls** to make the call to request metadata. Follow these steps to make the RPC call: - -1. Select **state** as the endpoint to call. -2. Select **`getMetadata(at)`** as the method to call. -3. Click **Submit RPC call** to submit the call and return the metadata in JSON format. - -### Use Curl - -You can fetch the metadata for the network by calling the node's RPC endpoint. This request returns the metadata in bytes rather than human-readable JSON: - -```sh -curl -H "Content-Type: application/json" \ --d '{"id":1, "jsonrpc":"2.0", "method": "state_getMetadata"}' \ -https://rpc.polkadot.io - -``` - -### Use Subxt - -[`subxt`](https://github.com/paritytech/subxt){target=\_blank} may also be used to fetch the metadata of any data in a human-readable JSON format: - -```sh -subxt metadata --url wss://rpc.polkadot.io --format json > spec.json -``` - -Another option is to use the [`subxt` explorer web UI](https://paritytech.github.io/subxt-explorer/#/){target=\_blank}. - -## Client Applications and Metadata - -The metadata exposes the expected way to decode each type, meaning applications can send, retrieve, and process application information without manual encoding and decoding. Client applications must use the [SCALE codec library](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank} to encode and decode RPC payloads to use the metadata. Client applications use the metadata to interact with the node, parse responses, and format message payloads sent to the node. - -## Metadata Format - -Although the SCALE-encoded bytes can be decoded using the `frame-metadata` and [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} libraries, there are other tools, such as `subxt` and the Polkadot-JS API, that can convert the raw data to human-readable JSON format. - -The types and type definitions included in the metadata returned by the `state_getMetadata` RPC call depend on the runtime's metadata version. - -In general, the metadata includes the following information: - -- A constant identifying the file as containing metadata. -- The version of the metadata format used in the runtime. -- Type definitions for all types used in the runtime and generated by the `scale-info` crate. -- Pallet information for the pallets included in the runtime in the order that they are defined in the `construct_runtime` macro. - -!!!tip - Depending on the frontend library used (such as the [Polkadot API](https://papi.how/){target=\_blank}), they may format the metadata differently than the raw format shown. - -The following example illustrates a condensed and annotated section of metadata decoded and converted to JSON: - -```json -[ - 1635018093, - { - "V14": { - "types": { - "types": [{}] - }, - "pallets": [{}], - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [{}] - }, - "ty": 141 - } - } -] - -``` - -The constant `1635018093` is a magic number that identifies the file as a metadata file. The rest of the metadata is divided into the `types`, `pallets`, and `extrinsic` sections: - -- The `types` section contains an index of the types and information about each type's type signature. -- The `pallets` section contains information about each pallet in the runtime. -- The `extrinsic` section describes the type identifier and transaction format version that the runtime uses. - -Different extrinsic versions can have varying formats, especially when considering [signed transactions](/reference/parachains/blocks-transactions-fees/transactions/#signed-transactions){target=\_blank}. - -### Pallets - -The following is a condensed and annotated example of metadata for a single element in the `pallets` array (the [`sudo`](https://paritytech.github.io/polkadot-sdk/master/pallet_sudo/index.html){target=\_blank} pallet): - -```json -{ - "name": "Sudo", - "storage": { - "prefix": "Sudo", - "entries": [ - { - "name": "Key", - "modifier": "Optional", - "ty": { - "Plain": 0 - }, - "default": [0], - "docs": ["The `AccountId` of the sudo key."] - } - ] - }, - "calls": { - "ty": 117 - }, - "event": { - "ty": 42 - }, - "constants": [], - "error": { - "ty": 124 - }, - "index": 8 -} - -``` - -Every element metadata contains the name of the pallet it represents and information about its storage, calls, events, and errors. You can look up details about the definition of the calls, events, and errors by viewing the type index identifier. The type index identifier is the `u32` integer used to access the type information for that item. For example, the type index identifier for calls in the Sudo pallet is 117. If you view information for that type identifier in the `types` section of the metadata, it provides information about the available calls, including the documentation for each call. - -For example, the following is a condensed excerpt of the calls for the Sudo pallet: - -```json -{ - "id": 117, - "type": { - "path": ["pallet_sudo", "pallet", "Call"], - "params": [ - { - "name": "T", - "type": null - } - ], - "def": { - "variant": { - "variants": [ - { - "name": "sudo", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 0, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "sudo_unchecked_weight", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - }, - { - "name": "weight", - "type": 8, - "typeName": "Weight" - } - ], - "index": 1, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "set_key", - "fields": [ - { - "name": "new", - "type": 103, - "typeName": "AccountIdLookupOf" - } - ], - "index": 2, - "docs": [ - "Authenticates current sudo key, sets the given AccountId (`new`) as the new sudo" - ] - }, - { - "name": "sudo_as", - "fields": [ - { - "name": "who", - "type": 103, - "typeName": "AccountIdLookupOf" - }, - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 3, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Signed` origin from a given account" - ] - } - ] - } - } - } -} - -``` - -For each field, you can access type information and metadata for the following: - -- **Storage metadata**: Provides the information required to enable applications to get information for specific storage items. -- **Call metadata**: Includes information about the runtime calls defined by the `#[pallet]` macro including call names, arguments and documentation. -- **Event metadata**: Provides the metadata generated by the `#[pallet::event]` macro, including the name, arguments, and documentation for each pallet event. -- **Constants metadata**: Provides metadata generated by the `#[pallet::constant]` macro, including the name, type, and hex-encoded value of the constant. -- **Error metadata**: Provides metadata generated by the `#[pallet::error]` macro, including the name and documentation for each pallet error. - -!!!tip - Type identifiers change from time to time, so you should avoid relying on specific type identifiers in your applications. - -### Extrinsic - -The runtime generates extrinsic metadata and provides useful information about transaction format. When decoded, the metadata contains the transaction version and the list of signed extensions. - -For example: - -```json -{ - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [ - { - "identifier": "CheckNonZeroSender", - "ty": 132, - "additional_signed": 41 - }, - { - "identifier": "CheckSpecVersion", - "ty": 133, - "additional_signed": 4 - }, - { - "identifier": "CheckTxVersion", - "ty": 134, - "additional_signed": 4 - }, - { - "identifier": "CheckGenesis", - "ty": 135, - "additional_signed": 11 - }, - { - "identifier": "CheckMortality", - "ty": 136, - "additional_signed": 11 - }, - { - "identifier": "CheckNonce", - "ty": 138, - "additional_signed": 41 - }, - { - "identifier": "CheckWeight", - "ty": 139, - "additional_signed": 41 - }, - { - "identifier": "ChargeTransactionPayment", - "ty": 140, - "additional_signed": 41 - } - ] - }, - "ty": 141 -} - -``` - -The type system is [composite](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/frame_runtime_types/index.html){target=\_blank}, meaning each type identifier contains a reference to a specific type or to another type identifier that provides information about the associated primitive types. - -For example, you can encode the `BitVec` type, but to decode it properly, you must know the types used for the `Order` and `Store` types. To find type information for `Order` and `Store`, you can use the path in the decoded JSON to locate their type identifiers. - -## Included RPC APIs - -A standard node comes with the following APIs to interact with a node: - -- **[`AuthorApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/author/trait.AuthorApiServer.html){target=\_blank}**: Make calls into a full node, including authoring extrinsics and verifying session keys. -- **[`ChainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/chain/trait.ChainApiServer.html){target=\_blank}**: Retrieve block header and finality information. -- **[`OffchainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/offchain/trait.OffchainApiServer.html){target=\_blank}**: Make RPC calls for off-chain workers. -- **[`StateApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/state/trait.StateApiServer.html){target=\_blank}**: Query information about on-chain state such as runtime version, storage items, and proofs. -- **[`SystemApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/system/trait.SystemApiServer.html){target=\_blank}**: Retrieve information about network state, such as connected peers and node roles. - -## Additional Resources - -The following tools can help you locate and decode metadata: - -- [Subxt Explorer](https://paritytech.github.io/subxt-explorer/#/){target=\_blank} -- [Metadata Portal 🌗](https://github.com/paritytech/metadata-portal){target=\_blank} -- [De[code] Sub[strate]](https://github.com/paritytech/desub){target=\_blank} - - --- Page Title: Contract Deployment @@ -1021,7480 +587,3339 @@ Both backends support contract deployment effectively, with REVM offering drop-i --- -Page Title: Convert Assets on Asset Hub +Page Title: Deploy an ERC-20 to Polkadot Hub -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-token-operations-convert-assets.md -- Canonical (HTML): https://docs.polkadot.com/chain-interactions/token-operations/convert-assets/ -- Summary: A guide detailing the step-by-step process of converting assets on Asset Hub, helping users efficiently navigate asset management on the platform. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-erc20-erc20-hardhat.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-hardhat/ +- Summary: Deploy an ERC-20 token on Polkadot Hub using PolkaVM. This guide covers contract creation, compilation, deployment, and interaction via Hardhat. -# Convert Assets on Asset Hub +# Deploy an ERC-20 to Polkadot Hub ## Introduction -Asset Conversion is an Automated Market Maker (AMM) utilizing [Uniswap V2](https://github.com/Uniswap/v2-core){target=\_blank} logic and implemented as a pallet on Polkadot's Asset Hub. - -This guide will provide detailed information about the key functionalities offered by the [Asset Conversion](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/asset-conversion){target=\_blank} pallet on Asset Hub, including: +[ERC-20](https://eips.ethereum.org/EIPS/eip-20){target=\_blank} tokens are fungible tokens commonly used for creating cryptocurrencies, governance tokens, and staking mechanisms. Polkadot Hub enables easy token deployment with Ethereum-compatible smart contracts and tools via the EVM backend. -- Creating a liquidity pool. -- Adding liquidity to a pool. -- Swapping assets. -- Withdrawing liquidity from a pool. +This tutorial covers deploying an ERC-20 contract on the Polkadot Hub TestNet using [Hardhat](https://hardhat.org/){target=\_blank}, an Ethereum development environment. The ERC-20 contract can be retrieved from OpenZeppelin's [GitHub repository](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20){target=\_blank} or their [Contract Wizard](https://wizard.openzeppelin.com/){target=\_blank}. ## Prerequisites -Before converting assets on Asset Hub, you must ensure you have: - -- Access to the [Polkadot.js Apps](https://polkadot.js.org/apps){target=\_blank} interface and a connection with the intended blockchain. -- A funded wallet containing the assets you wish to convert and enough available funds to cover the transaction fees. -- An asset registered on Asset Hub that you want to convert. If you haven't created an asset on Asset Hub yet, refer to the [Register a Local Asset](/chain-interactions/token-operations/register-local-asset/){target=\_blank} or [Register a Foreign Asset](/chain-interactions/token-operations/register-foreign-asset/){target=\_blank} documentation to create an asset. +Before starting, make sure you have: -## Create a Liquidity Pool +- Basic understanding of Solidity programming and fungible tokens. +- Node.js v22.13.1 or later. +- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. -If an asset on Asset Hub does not have an existing liquidity pool, the first step is to create one. +## Set Up Your Project -The asset conversion pallet provides the `createPool` extrinsic to create a new liquidity pool, creating an empty liquidity pool and a new `LP token` asset. +This tutorial uses a [Hardhat ERC-20 template](https://github.com/polkadot-developers/revm-hardhat-examples/tree/master/erc20-hardhat){target=\_blank} that contains all the necessary files. To get started, take the following steps: -!!! tip - A testing token with the asset ID `1112` and the name `PPM` was created for this example. +1. Clone the GitHub repository locally: -As stated in the [Test Environment Setup](#test-environment-setup) section, this tutorial is based on the assumption that you have an instance of Polkadot Asset Hub running locally. Therefore, the demo liquidity pool will be created between DOT and PPM tokens. However, the same steps can be applied to any other asset on Asset Hub. + ```bash + git clone https://github.com/polkadot-developers/revm-hardhat-examples/ + cd revm-hardhat-examples/erc20-hardhat + ``` -From the Asset Hub perspective, the Multilocation that identifies the PPM token is the following: +2. Install the dependencies: -```javascript -{ - parents: 0, - interior: { - X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }] - } -} -``` + ```bash + npm i + ``` -The `PalletInstance` value of `50` represents the Assets pallet on Asset Hub. The `GeneralIndex` value of `1112` is the PPM asset's asset ID. +This will fetch all the necessary packages to help you deploy an ERC-20 with Hardhat to Polkadot. -To create the liquidity pool, you can follow these steps: +## Configure Hardhat -1. Navigate to the **Extrinsics** section on the Polkadot.js Apps interface: +Once you've [setup your project](#set-up-your-project), you can configure the `hardhat.config.ts` to your needs. This tutorial has the file prepared to deploy to the Polkadot TestNet. - 1. Select **Developer** from the top menu. - 2. Click on **Extrinsics** from the dropdown menu. +To store and use private keys or network URLs, you can use Hardhat's configuration variables. This can be set via tasks in the **vars** scope. For example, to store the private key to deploy to the Polkadot TestNet, run the following command: - ![Extrinsics Section](/images/chain-interactions/token-operations/convert-assets/convert-assets-01.webp) +```bash +npx hardhat vars set TESTNET_PRIVATE_KEY +``` -2. Select extrinsic to create the pool: +The command will initiate a wizard in which you'll have to enter the value to be stored: - 1. Select the **`AssetConversion`** pallet. - 2. Choose the **`createPool`** extrinsic from the list of available extrinsics. +
+ npx hardhat vars set TESTNET_PRIVATE_KEY + ✔ Enter value: · ••••••••• + The configuration variable has been stored in /Users/albertoviera/Library/Preferences/hardhat-nodejs/vars.json +
- ![Create Pool Extrinsic](/images/chain-interactions/token-operations/convert-assets/convert-assets-02.webp) +??? warning "Key Encryption" + This solution just prevents variables to be included in the code repository. You should find a solution that encrypts private keys and access them securely. -3. Fill in the required fields: +You can now use the account related to this private key by importing it into the Hardhat configuration file: - 1. **`asset1`**: The Multilocation of the first asset in the pool. In this case, it is the DOT token, which the following Multilocation represents. +```ts title="hardhat.config.ts" hl_lines="1 17" - ```javascript - { - parents: 0, - interior: 'Here' - } - ``` +const config: HardhatUserConfig = { + solidity: { + version: "0.8.28", + settings: { + optimizer: { + enabled: true, + runs: 200, + }, + }, + }, + networks: { + polkadotTestnet: { + url: vars.get("TESTNET_URL", "http://127.0.0.1:8545"), + accounts: vars.has("TESTNET_PRIVATE_KEY") ? [vars.get("TESTNET_PRIVATE_KEY")] : [], + }, + }, + mocha: { + timeout: 40000, + }, +}; - 2. **`asset2`**: The second asset's Multilocation within the pool. This refers to the PPM token, which the following Multilocation identifies. +export default config; +``` - ```javascript - { - parents: 0, - interior: { - X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }] - } - } - ``` +## Compile your Contract - 3. Click on **Submit Transaction** to create the liquidity pool. +Once you've configured Hardhat, you can compile the contract. - ![Create Pool Fields](/images/chain-interactions/token-operations/convert-assets/convert-assets-03.webp) +In this tutorial, a simple ERC-20 is provided. Therefore, to compile the contract you can run the following command: -Signing and submitting the transaction triggers the creation of the liquidity pool. To verify the new pool's creation, check the **Explorer** section on the Polkadot.js Apps interface and ensure that the **`PoolCreated`** event was emitted. +```bash +npx hardhat compile +``` -![Pool Created Event](/images/chain-interactions/token-operations/convert-assets/convert-assets-04.webp) +If everything compiles successfully, you should see the following output: -As the preceding image shows, the **`lpToken`** ID created for this pool is 19. This ID is essential to identify the liquidity pool and associated LP tokens. +
+ npx hardhat compile + Generating typings for: 23 artifacts in dir: typechain-types for target: ethers-v6 + Successfully generated 62 typings! + Compiled 21 Solidity files successfully (evm target: paris). +
-## Add Liquidity to a Pool +## Test your Contract -The `addLiquidity` extrinsic allows users to provide liquidity to a pool of two assets. Users specify their preferred amounts for both assets and minimum acceptable quantities. The function determines the best asset contribution, which may vary from the amounts desired but won't fall below the specified minimums. Providers receive liquidity tokens representing their pool portion in return for their contribution. +Hardhat has a native feature to test contracts. You can run tests against the local Hardhat development node, but it could have some technical differences to Polkadot. Therefore, in this tutorial, you'll be testing against the Polkadot TestNet -To add liquidity to a pool, follow these steps: +This example has a predefined test file located in [`test/Token.test.js`](https://github.com/polkadot-developers/revm-hardhat-examples/blob/master/erc20-hardhat/test/MyToken.test.ts){target=\_blank}, that runs the following tests: -1. Navigate to the **Extrinsics** section on the Polkadot.js Apps interface: +1. The token was deployed by verifying its **name** and **symbol**. +2. The token has the right owner configured. +3. The token has an initial supply of zero. +4. The owner can mint tokens. +5. The total supply is increased after a mint. +6. Perform multiple mints to different addresses and checks the balance of each address and the new total supply. - 1. Select **Developer** from the top menu. - 2. Click on **Extrinsics** from the dropdown menu. +To run the test, you can execute the following command: - ![Extrinsics Section](/images/chain-interactions/token-operations/convert-assets/convert-assets-01.webp) +```bash +npx hardhat test --network polkadotTestnet +``` -2. Select extrinsic to add liqudity: +If tests are successful, you should see the following logs: - 1. Select the **`assetConversion`** pallet. - 2. Choose the **`addLiquidity`** extrinsic from the list of available extrinsics. +
+ npx hardhat test --network polkadotTestnet + +   MyToken +     Deployment +       ✔ Should have correct name and symbol +       ✔ Should set the right owner +       ✔ Should have zero initial supply +     Minting +       ✔ Should allow owner to mint tokens +       ✔ Should increase total supply on mint +     Multiple mints +       ✔ Should correctly track balance after multiple mints + +   6 passing (369ms) +
- ![Add Liquidity Extrinsic](/images/chain-interactions/token-operations/convert-assets/convert-assets-05.webp) +## Deploy your Contract -3. Fill in the required fields: +With the Hardhat configuration file ready, the private key stored as a variable under **vars**, and the contract compiled, you can proceed to deploy the contract to a given network. In this tutorial, you are deploying it to the Polkadot TestNet. - 1. **`asset1`**: The Multilocation of the first asset in the pool. In this case, it is the DOT token, which the following Multilocation represents. +To deploy the contract, run the following command: - ```javascript - { - parents: 0, - interior: 'Here' - } - ``` - - 2. **`asset2`**: The second asset's Multilocation within the pool. This refers to the PPM token, which the following Multilocation identifies. - - ```javascript - { - parents: 0, - interior: { - X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }] - } - } - ``` - - 3. **`amount1Desired`**: The amount of the first asset that will be contributed to the pool. - 4. **`amount2Desired`**: The quantity of the second asset intended for pool contribution. - 5. **`amount1Min`**: The minimum amount of the first asset that will be contributed. - 6. **`amount2Min`**: The lowest acceptable quantity of the second asset for contribution. - 7. **`mintTo`**: The account to which the liquidity tokens will be minted. - 8. Click on **Submit Transaction** to add liquidity to the pool. - - ![Add Liquidity Fields](/images/chain-interactions/token-operations/convert-assets/convert-assets-06.webp) - - !!! warning - Ensure that the appropriate amount of tokens provided has been minted previously and is available in your account before adding liquidity to the pool. - - In this case, the liquidity provided to the pool is between DOT tokens and PPM tokens with the asset ID 1112 on Polkadot Asset Hub. The intention is to provide liquidity for 1 DOT token (`u128` value of 1000000000000 as it has 10 decimals) and 1 PPM token (`u128` value of 1000000000000 as it also has 10 decimals). - -Signing and submitting the transaction adds liquidity to the pool. To verify the liquidity addition, check the **Explorer** section on the Polkadot.js Apps interface and ensure that the **`LiquidityAdded`** event was emitted. - -![Liquidity Added Event](/images/chain-interactions/token-operations/convert-assets/convert-assets-07.webp) - -## Swap Assets +```bash +npx hardhat ignition deploy ./ignition/modules/MyToken.ts --network polkadotTestnet +``` -### Swap from an Exact Amount of Tokens +You'll need to confirm the target network (by chain ID): -The asset conversion pallet enables users to exchange a specific quantity of one asset for another in a designated liquidity pool by swapping them for an exact amount of tokens. It guarantees the user will receive at least a predetermined minimum amount of the second asset. This function increases trading predictability and allows users to conduct asset exchanges with confidence that they are assured a minimum return. +
+ npx hardhat ignition deploy ./ignition/modules/MyToken.ts --network polkadotTestnet + ✔ Confirm deploy to network polkadotTestnet (420420420)? … yes +   + Hardhat Ignition 🚀 +   + Deploying [ TokenModule ] +   + Batch #1 + Executed TokenModule#MyToken +   + Batch #2 + Executed TokenModule#MyToken.mint +   + [ TokenModule ] successfully deployed 🚀 +   + Deployed Addresses +   + TokenModule#MyToken - 0xc01Ee7f10EA4aF4673cFff62710E1D7792aBa8f3 +
-To swap assets for an exact amount of tokens, follow these steps: +And that is it! You've successfully deployed an ERC-20 token contract to the Polkadot TestNet using Hardhat. -1. Navigate to the **Extrinsics** section on the Polkadot.js Apps interface: +## Where to Go Next - 1. Select **Developer** from the top menu. - 2. Click on **Extrinsics** from the dropdown menu. +
- ![Extrinsics Section](/images/chain-interactions/token-operations/convert-assets/convert-assets-01.webp) +- Guide __Deploy an NFT with Remix__ -2. Select extrinsic to swap assets: + --- - 1. Select the **`AssetConversion`** pallet. - 2. Choose the **`swapExactTokensForTokens`** extrinsic from the list of available extrinsics. + Walk through deploying an ERC-721 Non-Fungible Token (NFT) using OpenZeppelin's battle-tested NFT implementation and Remix. - ![Swap From Exact Tokens Extrinsic](/images/chain-interactions/token-operations/convert-assets/convert-assets-08.webp) + [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) -3. Fill in the required fields: +
- 1. **`path: Vec`**: An array of Multilocations representing the path of the swap. The first and last elements of the array are the input and output assets, respectively. In this case, the path consists of two elements: - - **`0: StagingXcmV3MultiLocation`**: The Multilocation of the first asset in the pool. In this case, it is the DOT token, which the following Multilocation represents. +--- - ```javascript - { - parents: 0, - interior: 'Here' - } - ``` +Page Title: Deploy an ERC-20 to Polkadot Hub - - **`1: StagingXcmV3MultiLocation`**: The second asset's Multilocation within the pool. This refers to the PPM token, which the following Multilocation identifies. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-erc20-erc20-remix.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix/ +- Summary: Deploy an ERC-20 token contract on Polkadot Hub. This guide covers contract creation, compilation, deployment, and interaction via the Remix IDE. - ```javascript - { - parents: 0, - interior: { - X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }] - } - } - ``` +# Deploy an ERC-20 to Polkadot Hub - 2. **`amountOut`**: The exact amount of the second asset that the user wants to receive. - 3. **`amountInMax`**: The maximum amount of the first asset that the user is willing to swap. - 4. **`sendTo`**: The account to which the swapped assets will be sent. - 5. **`keepAlive`**: A boolean value that determines whether the pool should be kept alive after the swap. - 6. Click on **Submit Transaction** to swap assets for an exact amount of tokens. +## Introduction - ![Swap For Exact Tokens Fields](/images/chain-interactions/token-operations/convert-assets/convert-assets-09.webp) +[ERC-20](https://eips.ethereum.org/EIPS/eip-20){target=\_blank} tokens are fungible tokens commonly used for creating cryptocurrencies, governance tokens, and staking mechanisms. Polkadot Hub enables easy token deployment with Ethereum-compatible smart contracts and tools via the EVM backend. - !!! warning - Ensure that the appropriate amount of tokens provided has been minted previously and is available in your account before adding liquidity to the pool. +This tutorial covers deploying an ERC-20 contract on the Polkadot Hub TestNet using [Remix IDE](https://remix.ethereum.org/){target=\_blank}, a web-based development tool. The ERC-20 contract can be retrieved from OpenZeppelin's [GitHub repository](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20){target=\_blank} or their [Contract Wizard](https://wizard.openzeppelin.com/){target=\_blank}. - In this case, the intention is to swap 0.01 DOT token (u128 value of 100000000000 as it has 10 decimals) for 0.04 PPM token (u128 value of 400000000000 as it also has 10 decimals). +## Prerequisites -Signing and submitting the transaction will execute the swap. To verify execution, check the **Explorer** section on the Polkadot.js Apps interface and make sure that the **`SwapExecuted`** event was emitted. +Before starting, make sure you have: -![Swap From Exact Tokens Event](/images/chain-interactions/token-operations/convert-assets/convert-assets-10.webp) +- Basic understanding of Solidity programming and fungible tokens. +- An EVM-compatible wallet [connected to Polkadot Hub](/smart-contracts/integrations/wallets){target=\_blank}. This example utilizes [MetaMask](https://metamask.io/){target=\_blank}. +- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. -### Swap to an Exact Amount of Tokens +## Create Your Contract -Conversely, the Asset Conversion pallet comes with a function that allows users to trade a variable amount of one asset to acquire a precise quantity of another. It ensures that users stay within a set maximum of the initial asset to obtain the desired amount of the second asset. This provides a method to control transaction costs while achieving the intended result. +To create the ERC-20 contract, you can follow the steps below: -To swap assets for an exact amount of tokens, follow these steps: +1. Navigate to the [Polkadot Remix IDE](https://remix.polkadot.io){target=\_blank}. +2. Click in the **Create new file** button under the **contracts** folder, and name your contract as `MyToken.sol`. -1. Navigate to the **Extrinsics** section on the Polkadot.js Apps interface: + ![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-1.webp) - 1. Select **Developer** from the top menu. - 2. Click on **Extrinsics** from the dropdown menu. +3. Now, paste the following ERC-20 contract code into the editor: - ![Extrinsics Section](/images/chain-interactions/token-operations/convert-assets/convert-assets-01.webp) + ```solidity title="MyToken.sol" + // SPDX-License-Identifier: MIT + // Compatible with OpenZeppelin Contracts ^5.4.0 + pragma solidity ^0.8.27; -2. Select extrinsic to swap tokens: + import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; + import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol"; + import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; - 1. Select the **`AssetConversion`** pallet. - 2. Choose the **`swapTokensForExactTokens`** extrinsic from the list of available extrinsics. + contract MyToken is ERC20, Ownable, ERC20Permit { + constructor(address initialOwner) + ERC20("MyToken", "MTK") + Ownable(initialOwner) + ERC20Permit("MyToken") + {} - ![Swap Tokens For Exact Tokens Extrinsic](/images/chain-interactions/token-operations/convert-assets/convert-assets-11.webp) + function mint(address to, uint256 amount) public onlyOwner { + _mint(to, amount); + } + } + ``` -3. Fill in the required fields: + The key components of the code above are: - 1. **`path: Vec`**: An array of Multilocations representing the path of the swap. The first and last elements of the array are the input and output assets, respectively. In this case, the path consists of two elements: - - **`0: StagingXcmV3MultiLocation`**: The Multilocation of the first asset in the pool. In this case, it is the PPM token, which the following Multilocation represents. + - Contract imports: - ```javascript - { - parents: 0, - interior: { - X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }] - } - } - ``` + - **[`ERC20.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20/ERC20.sol){target=\_blank}**: The base contract for fungible tokens, implementing core functionality like transfers, approvals, and balance tracking. + - **[`ERC20Permit.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20/extensions/ERC20Permit.sol){target=\_blank}**: [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612){target=\_blank} extension for ERC-20 that adds the [permit function](https://docs.openzeppelin.com/contracts/5.x/api/token/erc20#ERC20Permit-permit-address-address-uint256-uint256-uint8-bytes32-bytes32-){target=\_blank}, allowing approvals via off-chain signatures (no on-chain tx from the holder). Manages nonces and EIP-712 domain separator and updates allowances when a valid signature is presented. + - **[`Ownable.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/access/Ownable.sol){target=\_blank}**: Provides basic authorization control, ensuring only the contract owner can mint new tokens. + + - Constructor parameters: - - **`1: StagingXcmV3MultiLocation`**: The second asset's Multilocation within the pool. This refers to the DOT token, which the following Multilocation identifies. + - **`initialOwner`**: Sets the address that will have administrative rights over the contract. + - **`"MyToken"`**: The full name of your token. + - **`"MTK"`**: The symbol representing your token in wallets and exchanges. - ```javascript - { - parents: 0, - interior: 'Here' - } - ``` + - Key functions: - 2. **`amountOut`**: The exact amount of the second asset that the user wants to receive. - 3. **`amountInMax`**: The maximum amount of the first asset that the user is willing to swap. - 4. **`sendTo`**: The account to which the swapped assets will be sent. - 5. **`keepAlive`**: A boolean value that determines whether the pool should be kept alive after the swap. - 6. Click on **Submit Transaction** to swap assets for an exact amount of tokens. + - **`mint(address to, uint256 amount)`**: Allows the contract owner to create new tokens for any address. The amount should include 18 decimals (e.g., 1 token = 1000000000000000000). + - Inherited [Standard ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/){target=\_blank} functions: + - **`transfer(address recipient, uint256 amount)`**: Sends a specified amount of tokens to another address. + - **`approve(address spender, uint256 amount)`**: Grants permission for another address to spend a specific number of tokens on behalf of the token owner. + - **`transferFrom(address sender, address recipient, uint256 amount)`**: Transfers tokens from one address to another, if previously approved. + - **`balanceOf(address account)`**: Returns the token balance of a specific address. + - **`allowance(address owner, address spender)`**: Checks how many tokens an address is allowed to spend on behalf of another address. - ![Swap Tokens For Exact Tokens Fields](/images/chain-interactions/token-operations/convert-assets/convert-assets-12.webp) + !!! tip + Use the [OpenZeppelin Contracts Wizard](https://wizard.openzeppelin.com/){target=\_blank} to generate customized smart contracts quickly. Simply configure your contract, copy the generated code, and paste it into the Remix IDE for deployment. Below is an example of an ERC-20 token contract created with it: - !!! warning - Before swapping assets, ensure that the tokens provided have been minted previously and are available in your account. + ![Screenshot of the OpenZeppelin Contracts Wizard showing an ERC-20 contract configuration.](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-2.webp) + - In this case, the intention is to swap 0.01 DOT token (`u128` value of 100000000000 as it has ten decimals) for 0.04 PPM token (`u128` value of 400000000000 as it also has ten decimals). +## Compile -Signing and submitting the transaction will execute the swap. To verify execution, check the **Explorer** section on the Polkadot.js Apps interface and make sure that the **`SwapExecuted`** event was emitted. +The compilation transforms your Solidity source code into bytecode that can be deployed on the blockchain. During this process, the compiler checks your contract for syntax errors, ensures type safety, and generates the machine-readable instructions needed for blockchain execution. -![Swap Tokens For Exact Tokens Event](/images/chain-interactions/token-operations/convert-assets/convert-assets-13.webp) +To compile your contract, ensure you have it opened in the Remix IDE Editor, and follow the instructions below: -## Withdraw Liquidity from a Pool +1. Select the **Solidity Compiler** plugin from the left panel. +2. Click the **Compile MyToken.sol** button. +3. If the compilation succeeded, you'll see a green checkmark indicating success in the **Solidity Compiler** icon. -The Asset Conversion pallet provides the `removeLiquidity` extrinsic to remove liquidity from a pool. This function allows users to withdraw the liquidity they offered from a pool, returning the original assets. When calling this function, users specify the number of liquidity tokens (representing their share in the pool) they wish to burn. They also set minimum acceptable amounts for the assets they expect to receive back. This mechanism ensures that users can control the minimum value they receive, protecting against unfavorable price movements during the withdrawal process. +![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-3.gif) -To withdraw liquidity from a pool, follow these steps: +## Deploy -1. Navigate to the **Extrinsics** section on the Polkadot.js Apps interface: +Deployment is the process of publishing your compiled smart contract to the blockchain, making it permanently available for interaction. During deployment, you'll create a new instance of your contract on the blockchain, which involves: - 1. Select **Developer** from the top menu. - 2. Click on **Extrinsics** from the dropdown menu. +1. Select the **Deploy & Run Transactions** plugin from the left panel. +2. Configure the deployment settings: + 1. From the **ENVIRONMENT** dropdown, select **Injected Provider - MetaMask** (check the [Deploying Contracts](/smart-contracts/dev-environments/remix/deploy-a-contract/){target=\_blank} section of the Remix IDE guide for more details). + 2. (Optional) From the **ACCOUNT** dropdown, select the acccount you want to use for the deploy. - ![Extrinsics Section](/images/chain-interactions/token-operations/convert-assets/convert-assets-01.webp) +3. Configure the contract parameters: + 1. Enter the address that will own the deployed token contract. + 2. Click the **Deploy** button to initiate the deployment. -2. Select extrinsic to withdraw liqudity from a pool: +4. **MetaMask will pop up**: Review the transaction details. Click **Confirm** to deploy your contract. +5. If the deployment process succeeded, you will see the transaction details in the terminal, including the contract address and deployment transaction hash. - 1. Select the **`AssetConversion`** pallet. - 2. Choose the **`removeLiquidity`** extrinsic from the list of available extrinsics. +![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-4.gif) - ![Remove Liquidity Extrinsic](/images/chain-interactions/token-operations/convert-assets/convert-assets-14.webp) +## Interact with Your Contract -3. Fill in the required fields: +Once deployed, you can interact with your contract through Remix. Find your contract under **Deployed/Unpinned Contracts**, and click it to expand the available methods. In this example, you'll mint some tokens to a given address: - 1. **`asset1`**: The Multilocation of the first asset in the pool. In this case, it is the DOT token, which the following Multilocation represents. +1. Expand the **mint** function: + 1. Enter the recipient address and the amount (remember to add 18 zeros for 1 whole token). + 2. Click **transact**. - ```javascript - { - parents: 0, - interior: 'Here' - } - ``` +2. Click **Approve** to confirm the transaction in the MetaMask popup. - 2. **`asset2`**: The second asset's Multilocation within the pool. This refers to the PPM token, which the following Multilocation identifies. +3. If the transaction succeeds, you will see a green check mark in the terminal. - ```javascript - { - parents: 0, - interior: { - X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }] - } - } - ``` +4. You can also call the **balanceOf** function by passing the address of the **mint** call to confirm the new balance. - 3. **`lpTokenBurn`**: The number of liquidity tokens to burn. - 4. **`amount1MinReceived`**: The minimum amount of the first asset that the user expects to receive. - 5. **`amount2MinReceived`**: The minimum quantity of the second asset the user expects to receive. - 6. **`withdrawTo`**: The account to which the withdrawn assets will be sent. - 7. Click on **Submit Transaction** to withdraw liquidity from the pool. +![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-5.gif) - ![Remove Liquidity Fields](/images/chain-interactions/token-operations/convert-assets/convert-assets-15.webp) - !!! warning - Ensure that the tokens provided have been minted previously and are available in your account before withdrawing liquidity from the pool. +Other standard functions you can use: - In this case, the intention is to withdraw 0.05 liquidity tokens from the pool, expecting to receive 0.004 DOT token (`u128` value of 40000000000 as it has 10 decimals) and 0.04 PPM token (`u128` value of 400000000000 as it also has 10 decimals). +- **`transfer(address to, uint256 amount)`**: Send tokens to another address. +- **`approve(address spender, uint256 amount)`**: Allow another address to spend your tokens. -Signing and submitting the transaction will initiate the withdrawal of liquidity from the pool. To verify the withdrawal, check the **Explorer** section on the Polkadot.js Apps interface and ensure that the **`LiquidityRemoved`** event was emitted. +Feel free to explore and interact with the contract's other functions using the same approach: select the method, provide any required parameters, and confirm the transaction in MetaMask when needed. -![Remove Liquidity Event](/images/chain-interactions/token-operations/convert-assets/convert-assets-16.webp) +## Where to Go Next -## Test Environment Setup +
-To test the Asset Conversion pallet, you can set up a local test environment to simulate different scenarios. This guide uses Chopsticks to spin up an instance of Polkadot Asset Hub. For further details on using Chopsticks, please refer to the [Chopsticks documentation](/develop/toolkit/parachains/fork-chains/chopsticks/get-started){target=\_blank}. +- Guide __Deploy an NFT with Remix__ -To set up a local test environment, execute the following command: + --- -```bash -npx @acala-network/chopsticks \ ---config=https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/polkadot-asset-hub.yml -``` + Walk through deploying an ERC-721 Non-Fungible Token (NFT) using OpenZeppelin's battle-tested NFT implementation and Remix. -This command initiates a lazy fork of Polkadot Asset Hub, including the most recent block information from the network. For Kusama Asset Hub testing, simply switch out `polkadot-asset-hub.yml` with `kusama-asset-hub.yml` in the command. + [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) -You now have a local Asset Hub instance up and running, ready for you to test various asset conversion procedures. The process here mirrors what you'd do on MainNet. After completing a transaction on TestNet, you can apply the same steps to convert assets on MainNet. +
--- -Page Title: Cryptography +Page Title: Deploy an NFT to Polkadot Hub with Foundry -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-cryptography.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/cryptography/ -- Summary: A concise guide to cryptography in blockchain, covering hash functions, encryption types, digital signatures, and elliptic curve applications. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-.foundry.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/.foundry/ +- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub using Foundry, a Rust toolkit with high-performance compilation. -# Cryptography +# Deploy an NFT with Foundry ## Introduction -Cryptography forms the backbone of blockchain technology, providing the mathematical verifiability crucial for consensus systems, data integrity, and user security. While a deep understanding of the underlying mathematical processes isn't necessary for most blockchain developers, grasping the fundamental applications of cryptography is essential. This page comprehensively overviews cryptographic implementations used across Polkadot SDK-based chains and the broader blockchain ecosystem. - -## Hash Functions - -Hash functions are fundamental to blockchain technology, creating a unique digital fingerprint for any piece of data, including simple text, images, or any other form of file. They map input data of any size to a fixed-size output (typically 32 bytes) using complex mathematical operations. Hashing is used to verify data integrity, create digital signatures, and provide a secure way to store passwords. This form of mapping is known as the ["pigeonhole principle,"](https://en.wikipedia.org/wiki/Pigeonhole_principle){target=\_blank} it is primarily implemented to efficiently and verifiably identify data from large sets. - -### Key Properties of Hash Functions - -- **Deterministic**: The same input always produces the same output. -- **Quick computation**: It's easy to calculate the hash value for any given input. -- **Pre-image resistance**: It's infeasible to generate the input data from its hash. -- **Small changes in input yield large changes in output**: Known as the ["avalanche effect"](https://en.wikipedia.org/wiki/Avalanche_effect){target=\_blank}. -- **Collision resistance**: The probabilities are extremely low to find two different inputs with the same hash. +Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. -### Blake2 +This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. It showcases a secure approach using [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and the [Foundry](https://getfoundry.sh/){target=\_blank} toolchain. Foundry, a fast, Rust-written toolkit, ensures high-performance compilation and is fully compatible with the Hub’s EVM environment via standard Solidity compilation. -The Polkadot SDK utilizes Blake2, a state-of-the-art hashing method that offers: +## Prerequisites -- Equal or greater security compared to [SHA-2](https://en.wikipedia.org/wiki/SHA-2){target=\_blank}. -- Significantly faster performance than other algorithms. +- Basic understanding of Solidity programming and NFT standards. +- Test tokens for gas fees (available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}). See the [step-by-step instructions](/smart-contracts/faucet/#get-test-tokens){target=\_blank}. +- A wallet with a private key for signing transactions. -These properties make Blake2 ideal for blockchain systems, reducing sync times for new nodes and lowering the resources required for validation. For detailed technical specifications about Blake2, see the [official Blake2 paper](https://www.blake2.net/blake2.pdf){target=\_blank}. +## Set Up Your Project -## Types of Cryptography +To get started, take the following steps: -There are two different ways that cryptographic algorithms are implemented: symmetric cryptography and asymmetric cryptography. +1. Install Foundry: -### Symmetric Cryptography + ```bash + curl -L https://foundry.paradigm.xyz | bash + foundryup + ``` -Symmetric encryption is a branch of cryptography that isn't based on one-way functions, unlike asymmetric cryptography. It uses the same cryptographic key to encrypt plain text and decrypt the resulting ciphertext. +2. Initialize your project: -Symmetric cryptography is a type of encryption that has been used throughout history, such as the Enigma Cipher and the Caesar Cipher. It is still widely used today and can be found in Web2 and Web3 applications alike. There is only one single key, and a recipient must also have access to it to access the contained information. + ```bash + forge init foundry-nft-deployment + cd foundry-nft-deployment + ``` -#### Advantages {: #symmetric-advantages } +3. Install OpenZeppelin contracts: -- Fast and efficient for large amounts of data. -- Requires less computational power. + ```bash + forge install OpenZeppelin/openzeppelin-contracts + ``` -#### Disadvantages {: #symmetric-disadvantages } +## Configure Foundry -- Key distribution can be challenging. -- Scalability issues in systems with many users. +Edit `foundry.toml`: -### Asymmetric Cryptography +```toml title="foundry.toml" +[profile.default] +src = "src" +out = "out" +libs = ["lib"] +remappings = ['@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/'] -Asymmetric encryption is a type of cryptography that uses two different keys, known as a keypair: a public key, used to encrypt plain text, and a private counterpart, used to decrypt the ciphertext. +[rpc_endpoints] +polkadot_hub_testnet = "https://testnet-passet-hub-eth-rpc.polkadot.io" +``` -The public key encrypts a fixed-length message that can only be decrypted with the recipient's private key and, sometimes, a set password. The public key can be used to cryptographically verify that the corresponding private key was used to create a piece of data without compromising the private key, such as with digital signatures. This has obvious implications for identity, ownership, and properties and is used in many different protocols across Web2 and Web3. +## Create Your Contract -#### Advantages {: #asymmetric-advantages } +Create `src/MyNFT.sol`: -- Solves the key distribution problem. -- Enables digital signatures and secure key exchange. +```solidity title="src/MyNFT.sol" +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; -#### Disadvantages {: #asymmetric-disadvantages } +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/access/Ownable.sol"; -- Slower than symmetric encryption. -- Requires more computational resources. +contract MyNFT is ERC721, Ownable { + uint256 private _nextTokenId; -### Trade-offs and Compromises + constructor(address initialOwner) + ERC721("MyToken", "MTK") + Ownable(initialOwner) + {} -Symmetric cryptography is faster and requires fewer bits in the key to achieve the same level of security that asymmetric cryptography provides. However, it requires a shared secret before communication can occur, which poses issues to its integrity and a potential compromise point. On the other hand, asymmetric cryptography doesn't require the secret to be shared ahead of time, allowing for far better end-user security. + function safeMint(address to) public onlyOwner { + uint256 tokenId = _nextTokenId++; + _safeMint(to, tokenId); + } +} +``` -Hybrid symmetric and asymmetric cryptography is often used to overcome the engineering issues of asymmetric cryptography, as it is slower and requires more bits in the key to achieve the same level of security. It encrypts a key and then uses the comparatively lightweight symmetric cipher to do the "heavy lifting" with the message. +## Compile -## Digital Signatures +```bash +forge build +``` -Digital signatures are a way of verifying the authenticity of a document or message using asymmetric keypairs. They are used to ensure that a sender or signer's document or message hasn't been tampered with in transit, and for recipients to verify that the data is accurate and from the expected sender. +Verify the compilation by inspecting the bytecode: -Signing digital signatures only requires a low-level understanding of mathematics and cryptography. For a conceptual example -- when signing a check, it is expected that it cannot be cashed multiple times. This isn't a feature of the signature system but rather the check serialization system. The bank will check that the serial number on the check hasn't already been used. Digital signatures essentially combine these two concepts, allowing the signature to provide the serialization via a unique cryptographic fingerprint that cannot be reproduced. +```bash +forge inspect MyNFT bytecode +``` -Unlike pen-and-paper signatures, knowledge of a digital signature cannot be used to create other signatures. Digital signatures are often used in bureaucratic processes, as they are more secure than simply scanning in a signature and pasting it onto a document. +## Deploy -Polkadot SDK provides multiple different cryptographic schemes and is generic so that it can support anything that implements the [`Pair` trait](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Pair.html){target=\_blank}. +Deploy to Polkadot Hub TestNet: -### Example of Creating a Digital Signature +```bash +forge create MyNFT \ + --rpc-url polkadot_hub_testnet \ + --private-key YOUR_PRIVATE_KEY \ + --constructor-args YOUR_OWNER_ADDRESS \ + --broadcast +``` -The process of creating and verifying a digital signature involves several steps: +Replace `YOUR_PRIVATE_KEY` with your private key and `YOUR_OWNER_ADDRESS` with the address that will own the NFT contract. -1. The sender creates a hash of the message. -2. The hash is encrypted using the sender's private key, creating the signature. -3. The message and signature are sent to the recipient. -4. The recipient decrypts the signature using the sender's public key. -5. The recipient hashes the received message and compares it to the decrypted hash. +## Where to Go Next -If the hashes match, the signature is valid, confirming the message's integrity and the sender's identity. +
-## Elliptic Curve +- Guide __Verify Your Contract__ -Blockchain technology requires the ability to have multiple keys creating a signature for block proposal and validation. To this end, Elliptic Curve Digital Signature Algorithm (ECDSA) and Schnorr signatures are two of the most commonly used methods. While ECDSA is a far simpler implementation, Schnorr signatures are more efficient when it comes to multi-signatures. + --- -Schnorr signatures bring some noticeable features over the ECDSA/EdDSA schemes: + Now that you've deployed an NFT contract, learn how to verify it with Foundry. -- It is better for hierarchical deterministic key derivations. -- It allows for native multi-signature through [signature aggregation](https://bitcoincore.org/en/2017/03/23/schnorr-signature-aggregation/){target=\_blank}. -- It is generally more resistant to misuse. + [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/foundry/verify-a-contract/) -One sacrifice that is made when using Schnorr signatures over ECDSA is that both require 64 bytes, but only ECDSA signatures communicate their public key. +- Guide __Deploy an ERC-20__ -### Various Implementations + --- -- **[ECDSA](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm){target=\_blank}**: Polkadot SDK provides an ECDSA signature scheme using the [secp256k1](https://en.bitcoin.it/wiki/Secp256k1){target=\_blank} curve. This is the same cryptographic algorithm used to secure [Bitcoin](https://en.wikipedia.org/wiki/Bitcoin){target=\_blank} and [Ethereum](https://en.wikipedia.org/wiki/Ethereum){target=\_blank}. + Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Foundry. -- **[Ed25519](https://en.wikipedia.org/wiki/EdDSA#Ed25519){target=\_blank}**: An EdDSA signature scheme using [Curve25519](https://en.wikipedia.org/wiki/Curve25519){target=\_blank}. It is carefully engineered at several levels of design and implementation to achieve very high speeds without compromising security. + [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/foundry/) -- **[SR25519](https://research.web3.foundation/Polkadot/security/keys/accounts-more){target=\_blank}**: Based on the same underlying curve as Ed25519. However, it uses Schnorr signatures instead of the EdDSA scheme. +
--- -Page Title: Data Encoding +Page Title: Deploy an NFT to Polkadot Hub with Hardhat -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-data-encoding.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/data-encoding/ -- Summary: SCALE codec enables fast, efficient data encoding, ideal for resource-constrained environments like Wasm, supporting custom types and compact encoding. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-hardhat.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/hardhat/ +- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub with Hardhat, a comprehenive development environment with built-in deployment capabilities. -# Data Encoding +# Deploy an NFT with Hardhat ## Introduction -The Polkadot SDK uses a lightweight and efficient encoding/decoding mechanism to optimize data transmission across the network. This mechanism, known as the _SCALE_ codec, is used for serializing and deserializing data. - -The SCALE codec enables communication between the runtime and the outer node. This mechanism is designed for high-performance, copy-free data encoding and decoding in resource-constrained environments like the Polkadot SDK [Wasm runtime](/develop/parachains/deployment/build-deterministic-runtime/#introduction){target=\_blank}. - -It is not self-describing, meaning the decoding context must fully know the encoded data types. +Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. -Parity's libraries utilize the [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} crate (a Rust implementation of the SCALE codec) to handle encoding and decoding for interactions between RPCs and the runtime. +This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. You'll use [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and [Hardhat](https://hardhat.org/docs/getting-started){target=\_blank}, a comprehensive development environment with built-in testing, debugging, and deployment capabilities. Hardhat uses standard Solidity compilation to generate EVM bytecode, making it fully compatible with Polkadot Hub's EVM environment. -The `codec` mechanism is ideal for Polkadot SDK-based chains because: +## Prerequisites -- It is lightweight compared to generic serialization frameworks like [`serde`](https://serde.rs/){target=\_blank}, which add unnecessary bulk to binaries. -- It doesn’t rely on Rust’s `libstd`, making it compatible with `no_std` environments like Wasm runtime. -- It integrates seamlessly with Rust, allowing easy derivation of encoding and decoding logic for new types using `#[derive(Encode, Decode)]`. +- Basic understanding of Solidity programming and NFT standards. +- Node.js v22.13.1 or later. +- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. +- A wallet with a private key for signing transactions. -Defining a custom encoding scheme in the Polkadot SDK-based chains, rather than using an existing Rust codec library, is crucial for enabling cross-platform and multi-language support. +## Set Up Your Project -## SCALE Codec +Take the following steps to get started: -The codec is implemented using the following traits: +1. Initialize your Hardhat project: -- [`Encode`](#encode) -- [`Decode`](#decode) -- [`CompactAs`](#compactas) -- [`HasCompact`](#hascompact) -- [`EncodeLike`](#encodelike) - -### Encode + ```bash + mkdir hardhat-nft-deployment + cd hardhat-nft-deployment + npx hardhat --init + ``` -The [`Encode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Encode.html){target=\_blank} trait handles data encoding into SCALE format and includes the following key functions: +2. Install OpenZeppelin contracts: -- **`size_hint(&self) -> usize`**: Estimates the number of bytes required for encoding to prevent multiple memory allocations. This should be inexpensive and avoid complex operations. Optional if the size isn’t known. -- **`encode_to(&self, dest: &mut T)`**: Encodes the data, appending it to a destination buffer. -- **`encode(&self) -> Vec`**: Encodes the data and returns it as a byte vector. -- **`using_encoded R>(&self, f: F) -> R`**: Encodes the data and passes it to a closure, returning the result. -- **`encoded_size(&self) -> usize`**: Calculates the encoded size. Should be used when the encoded data isn’t required. + ```bash + npm install @openzeppelin/contracts + ``` -!!!tip - For best performance, value types should override `using_encoded`, and allocating types should override `encode_to`. It's recommended to implement `size_hint` for all types where possible. +## Configure Hardhat -### Decode +Edit `hardhat.config.ts`: -The [`Decode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Decode.html){target=\_blank} trait handles decoding SCALE-encoded data back into the appropriate types: +```typescript title="hardhat.config.ts" +import type { HardhatUserConfig } from 'hardhat/config'; -- **`fn decode(value: &mut I) -> Result`**: Decodes data from the SCALE format, returning an error if decoding fails. +import hardhatToolboxViemPlugin from '@nomicfoundation/hardhat-toolbox-viem'; +import { configVariable } from 'hardhat/config'; -### CompactAs +const config: HardhatUserConfig = { + plugins: [hardhatToolboxViemPlugin], + solidity: { + profiles: { + default: { + version: '0.8.28', + }, + production: { + version: '0.8.28', + settings: { + optimizer: { + enabled: true, + runs: 200, + }, + }, + }, + }, + }, + networks: { + hardhatMainnet: { + type: 'edr-simulated', + chainType: 'l1', + }, + hardhatOp: { + type: 'edr-simulated', + chainType: 'op', + }, + sepolia: { + type: 'http', + chainType: 'l1', + url: configVariable('SEPOLIA_RPC_URL'), + accounts: [configVariable('SEPOLIA_PRIVATE_KEY')], + }, + polkadotHubTestnet: { + type: 'http', + url: 'https://testnet-passet-hub-eth-rpc.polkadot.io', + chainId: 420420422, + accounts: [configVariable('PRIVATE_KEY')], + }, + }, +}; -The [`CompactAs`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.CompactAs.html){target=\_blank} trait wraps custom types for compact encoding: +export default config; +``` -- **`encode_as(&self) -> &Self::As`**: Encodes the type as a compact type. -- **`decode_from(_: Self::As) -> Result`**: decodes from a compact encoded type. +!!! tip + Learn how to use Hardhat's [Config Variables](https://hardhat.org/docs/learn-more/configuration-variables){target=\_blank} to handle your private keys in a secure way. -### HasCompact +## Create Your Contract -The [`HasCompact`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.HasCompact.html){target=\_blank} trait indicates a type supports compact encoding. +Create `contracts/MyNFT.sol`: -### EncodeLike +```solidity title="contracts/MyNFT.sol" +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; -The [`EncodeLike`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.EncodeLike.html){target=\_blank} trait is used to ensure multiple types that encode similarly are accepted by the same function. When using `derive`, it is automatically implemented. +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/access/Ownable.sol"; -### Data Types +contract MyNFT is ERC721, Ownable { + uint256 private _nextTokenId; -The table below outlines how the Rust implementation of the Parity SCALE codec encodes different data types. + constructor(address initialOwner) + ERC721("MyToken", "MTK") + Ownable(initialOwner) + {} -| Type | Description | Example SCALE Decoded Value | SCALE Encoded Value | -|-------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------| -| Boolean | Boolean values are encoded using the least significant bit of a single byte. | `false` / `true` | `0x00` / `0x01` | -| Compact/general integers | A "compact" or general integer encoding is sufficient for encoding large integers (up to 2^536) and is more efficient at encoding most values than the fixed-width version. | `unsigned integer 0` / `unsigned integer 1` / `unsigned integer 42` / `unsigned integer 69` / `unsigned integer 65535` / `BigInt(100000000000000)` | `0x00` / `0x04` / `0xa8` / `0x1501` / `0xfeff0300` / `0x0b00407a10f35a` | -| Enumerations (tagged-unions) | A fixed number of variants, each mutually exclusive and potentially implying a further value or series of values. Encoded as the first byte identifying the index of the variant that the value is. Any further bytes are used to encode any data that the variant implies. Thus, no more than 256 variants are supported. | `Int(42)` and `Bool(true)` where `enum IntOrBool { Int(u8), Bool(bool) }` | `0x002a` and `0x0101` | -| Fixed-width integers | Basic integers are encoded using a fixed-width little-endian (LE) format. | `signed 8-bit integer 69` / `unsigned 16-bit integer 42` / `unsigned 32-bit integer 16777215` | `0x45` / `0x2a00` / `0xffffff00` | -| Options | One or zero values of a particular type. | `Some` / `None` | `0x01` followed by the encoded value / `0x00` | -| Results | Results are commonly used enumerations which indicate whether certain operations were successful or unsuccessful. | `Ok(42)` / `Err(false)` | `0x002a` / `0x0100` | -| Strings | Strings are Vectors of bytes (Vec) containing a valid UTF8 sequence. | | | -| Structs | For structures, the values are named, but that is irrelevant for the encoding (names are ignored - only order matters). | `SortedVecAsc::from([3, 5, 2, 8])` | `[3, 2, 5, 8] ` | -| Tuples | A fixed-size series of values, each with a possibly different but predetermined and fixed type. This is simply the concatenation of each encoded value. | Tuple of compact unsigned integer and boolean: `(3, false)` | `0x0c00` | -| Vectors (lists, series, sets) | A collection of same-typed values is encoded, prefixed with a compact encoding of the number of items, followed by each item's encoding concatenated in turn. | Vector of unsigned `16`-bit integers: `[4, 8, 15, 16, 23, 42]` | `0x18040008000f00100017002a00` | + function safeMint(address to) public onlyOwner { + uint256 tokenId = _nextTokenId++; + _safeMint(to, tokenId); + } +} +``` -## Encode and Decode Rust Trait Implementations +## Compile -Here's how the `Encode` and `Decode` traits are implemented: +```bash +npx hardhat compile +``` +## Set Up Deployment -```rust -use parity_scale_codec::{Encode, Decode}; - -[derive(Debug, PartialEq, Encode, Decode)] -enum EnumType { - #[codec(index = 15)] - A, - B(u32, u64), - C { - a: u32, - b: u64, - }, -} +Create a deployment module in `ignition/modules/MyNFT.ts`: -let a = EnumType::A; -let b = EnumType::B(1, 2); -let c = EnumType::C { a: 1, b: 2 }; +```typescript title="ignition/modules/MyNFT.ts" +import { buildModule } from '@nomicfoundation/hardhat-ignition/modules'; -a.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x0f"); +export default buildModule('MyNFTModule', (m) => { + const initialOwner = m.getParameter('initialOwner', 'INSERT_OWNER_ADDRESS'); + const myNFT = m.contract('MyNFT', [initialOwner]); + return { myNFT }; }); +``` -b.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); +Replace `INSERT_OWNER_ADDRESS` with your desired owner address. -c.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); +## Deploy -let mut da: &[u8] = b"\x0f"; -assert_eq!(EnumType::decode(&mut da).ok(), Some(a)); +Deploy to Polkadot Hub TestNet: -let mut db: &[u8] = b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut db).ok(), Some(b)); +```bash +npx hardhat ignition deploy ignition/modules/MyNFT.ts --network polkadotHubTestnet +``` -let mut dc: &[u8] = b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut dc).ok(), Some(c)); +## Where to Go Next -let mut dz: &[u8] = &[0]; -assert_eq!(EnumType::decode(&mut dz).ok(), None); -``` +
-## SCALE Codec Libraries +- Guide __Verify Your Contract__ -Several SCALE codec implementations are available in various languages. Here's a list of them: + --- -- **AssemblyScript**: [`LimeChain/as-scale-codec`](https://github.com/LimeChain/as-scale-codec){target=\_blank} -- **C**: [`MatthewDarnell/cScale`](https://github.com/MatthewDarnell/cScale){target=\_blank} -- **C++**: [`qdrvm/scale-codec-cpp`](https://github.com/qdrvm/scale-codec-cpp){target=\_blank} -- **JavaScript**: [`polkadot-js/api`](https://github.com/polkadot-js/api){target=\_blank} -- **Dart**: [`leonardocustodio/polkadart`](https://github.com/leonardocustodio/polkadart){target=\_blank} -- **Haskell**: [`airalab/hs-web3`](https://github.com/airalab/hs-web3/tree/master/packages/scale){target=\_blank} -- **Golang**: [`itering/scale.go`](https://github.com/itering/scale.go){target=\_blank} -- **Java**: [`splix/polkaj`](https://github.com/splix/polkaj){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **Ruby**: [` wuminzhe/scale_rb`](https://github.com/wuminzhe/scale_rb){target=\_blank} -- **TypeScript**: [`parity-scale-codec-ts`](https://github.com/tjjfvi/subshape){target=\_blank}, [`scale-ts`](https://github.com/unstoppablejs/unstoppablejs/tree/main/packages/scale-ts#scale-ts){target=\_blank}, [`soramitsu/scale-codec-js-library`](https://github.com/soramitsu/scale-codec-js-library){target=\_blank}, [`subsquid/scale-codec`](https://github.com/subsquid/squid-sdk/tree/master/substrate/scale-codec){target=\_blank} + Now that you've deployed an NFT contract, learn how to verify it with Hardhat. + [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/hardhat/verify-a-contract/) ---- -Page Title: Dedot +- Guide __Deploy an ERC-20__ -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-dedot.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/dedot/ -- Summary: Dedot is a next-gen JavaScript client for Polkadot and Polkadot SDK-based blockchains, offering lightweight, tree-shakable APIs with strong TypeScript support. + --- -# Dedot + Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Hardhat. -## Introduction + [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/hardhat/) -[Dedot](https://github.com/dedotdev/dedot){target=\_blank} is a next-generation JavaScript client for Polkadot and Polkadot SDK-based blockchains. Designed to elevate the dApp development experience, Dedot is built and optimized to be lightweight and tree-shakable, offering precise types and APIs suggestions for individual Polkadot SDK-based blockchains and [ink! smart contracts](https://use.ink/){target=\_blank}. +
-### Key Features -- **Lightweight and tree-shakable**: No more bn.js or WebAssembly blobs, optimized for dapps bundle size. -- **Fully typed API**: Comprehensive TypeScript support for seamless on-chain interaction and ink! smart contract integration. -- **Multi-version JSON-RPC support**: Compatible with both [legacy](https://github.com/w3f/PSPs/blob/master/PSPs/drafts/psp-6.md){target=\_blank} and [new](https://paritytech.github.io/json-rpc-interface-spec/introduction.html){target=\_blank} JSON-RPC APIs for broad ecosystem interoperability. -- **Light client support**: Designed to work with light clients such as [Smoldot](https://github.com/smol-dot/smoldot){target=\_blank}. -- **Native TypeScript for scale codec**: Implements scale codec parsing directly in TypeScript without relying on custom wrappers. -- **Wallet integration**: Works out-of-the-box with [@polkadot/extension-based](https://github.com/polkadot-js/extension?tab=readme-ov-file#api-interface){target=\_blank} wallets. -- **Familiar API design**: Similar API style to Polkadot.js for easy and fast migration. +--- -## Installation +Page Title: Deploy an NFT to Polkadot Hub with Remix -To add Dedot to your project, use the following command: +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-remix.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/ +- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub using Remix, a browser-based IDE for quick prototyping and learning. -=== "npm" +# Deploy an NFT with Remix - ```bash - npm i dedot - ``` +## Introduction -=== "pnpm" +Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. - ```bash - pnpm add dedot - ``` +This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. You'll use [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and [Remix](https://remix.ethereum.org/){target=\_blank}, a visual, browser-based environment perfect for rapid prototyping and learning. It requires no local installation and provides an intuitive interface for contract development. -=== "yarn" +## Prerequisites - ```bash - yarn add dedot - ``` +- Basic understanding of Solidity programming and NFT standards. +- Test tokens for gas fees (available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}). See the [step-by-step instructions](/smart-contracts/faucet/#get-test-tokens){target=\_blank} +- A wallet with a private key for signing transactions. -To enable auto-completion/IntelliSense for individual chains, install the [`@dedot/chaintypes`](https://www.npmjs.com/package/@dedot/chaintypes){target=\_blank} package as a development dependency: +## Access Remix -=== "npm" +Navigate to [Remix](https://remix.ethereum.org/){target=\_blank} in your web browser. - ```bash - npm i -D @dedot/chaintypes - ``` +The interface will load with a default workspace containing sample contracts. In this interface, you can access a file explorer, edit your code, interact with various plugins for development, and use a terminal. -=== "pnpm" +## Create Your Contract - ```bash - pnpm add -D @dedot/chaintypes - ``` +1. Create a new file `contracts/MyNFT.sol`. +2. Paste the following code: -=== "yarn" + ```solidity title="contracts/MyNFT.sol" + // SPDX-License-Identifier: MIT + pragma solidity ^0.8.20; - ```bash - yarn add -D @dedot/chaintypes - ``` + import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; + import "@openzeppelin/contracts/access/Ownable.sol"; -## Get Started + contract MyNFT is ERC721, Ownable { + uint256 private _nextTokenId; -### Initialize a Client Instance + constructor(address initialOwner) + ERC721("MyToken", "MTK") + Ownable(initialOwner) + {} -To connect to and interact with different networks, Dedot provides two client options depending on your needs: + function safeMint(address to) public onlyOwner { + uint256 tokenId = _nextTokenId++; + _safeMint(to, tokenId); + } + } + ``` -- **[`DedotClient`](https://docs.dedot.dev/clients-and-providers/clients#dedotclient){target=\_blank}**: Interacts with chains via the [new JSON-RPC APIs](https://paritytech.github.io/json-rpc-interface-spec/introduction.html){target=\_blank}. -- **[`LegacyClient`](https://docs.dedot.dev/clients-and-providers/clients#legacyclient){target=\_blank}**: Interacts with chains via the [legacy JSON-RPC APIs](https://github.com/w3f/PSPs/blob/master/PSPs/drafts/psp-6.md){target=\_blank}. +![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-01.webp) -Use the following snippets to connect to Polkadot using `DedotClient`: +## Compile -=== "WebSocket" +1. Navigate to the **Solidity Compiler** tab (third icon in the left sidebar). +2. Click **Compile MyNFT.sol** or press `Ctrl+S`. - ```typescript - import { DedotClient, WsProvider } from 'dedot'; - import type { PolkadotApi } from '@dedot/chaintypes'; +![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-02.webp) - // Initialize providers & clients - const provider = new WsProvider('wss://rpc.polkadot.io'); - const client = await DedotClient.new(provider); +Compilation errors and warnings appear in the terminal panel at the bottom of the screen. - ``` +## Deploy -=== "Light Client (Smoldot)" +1. Navigate to the **Deploy & Run Transactions** tab. +2. Click the **Environment** dropdown, select **Browser Extension**, and click on **Injected Provider - MetaMask**. - ```typescript - import { DedotClient, SmoldotProvider } from 'dedot'; - import type { PolkadotApi } from '@dedot/chaintypes'; - import * as smoldot from 'smoldot'; + ![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-03.webp) - // import `polkadot` chain spec to connect to Polkadot - import { polkadot } from '@substrate/connect-known-chains'; +3. In the deploy section, enter the initial owner address in the constructor parameter field. +4. Click **Deploy**. - // Start smoldot instance & initialize a chain - const client = smoldot.start(); - const chain = await client.addChain({ chainSpec: polkadot }); + ![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-04.webp) - // Initialize providers & clients - const provider = new SmoldotProvider(chain); - const client = await DedotClient.new(provider); +5. Approve the transaction in your MetaMask wallet. - ``` +Your deployed contract will appear in the **Deployed Contracts** section, ready for interaction. -If the node doesn't support new JSON-RPC APIs yet, you can connect to the network using the `LegacyClient`, which is built on top of the legacy JSON-RPC APIs. +## Where to Go Next -```typescript -import { LegacyClient, WsProvider } from 'dedot'; -import type { PolkadotApi } from '@dedot/chaintypes'; +
-const provider = new WsProvider('wss://rpc.polkadot.io'); -const client = await LegacyClient.new(provider); +- Guide __Verify Your Contract__ -``` + --- -### Enable Type and API Suggestions + Now that you've deployed an NFT contract, learn how to verify it with Remix. -It is recommended to specify the `ChainApi` interface (e.g., `PolkadotApi` in the example in the previous section) of the chain you want to interact with. This enables type and API suggestions/autocompletion for that particular chain (via IntelliSense). If you don't specify a `ChainApi` interface, a default `SubstrateApi` interface will be used. + [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/remix/verify-a-contract/) -```typescript -import { DedotClient, WsProvider } from 'dedot'; -import type { PolkadotApi, KusamaApi } from '@dedot/chaintypes'; +- Guide __Deploy an ERC-20__ -const polkadotClient = await DedotClient.new( - new WsProvider('wss://rpc.polkadot.io') -); -const kusamaClient = await DedotClient.new( - new WsProvider('wss://kusama-rpc.polkadot.io') -); -const genericClient = await DedotClient.new( - new WsProvider('ws://localhost:9944') -); + --- -``` + Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Remix. -If you don't find the `ChainApi` for the network you're working with in [the list](https://github.com/dedotdev/chaintypes?tab=readme-ov-file#supported-networks){target=\_blank}, you can generate the `ChainApi` (types and APIs) using the built-in [`dedot` cli](https://docs.dedot.dev/cli){target=\_blank}. + [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/) -```bash -# Generate ChainApi interface for Polkadot network via rpc endpoint: wss://rpc.polkadot.io -npx dedot chaintypes -w wss://rpc.polkadot.io -``` +
-Or open a pull request to add your favorite network to the [`@dedot/chaintypes`](https://github.com/dedotdev/chaintypes){target=\_blank} repo. -### Read On-Chain Data +--- -Dedot provides several ways to read data from the chain: +Page Title: Deploying Uniswap V2 on Polkadot -- **Access runtime constants**: Use the syntax `client.consts..` to inspect runtime constants (parameter types). +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-eth-dapps-uniswap-v2.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/eth-dapps/uniswap-v2/ +- Summary: Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. - ```typescript - const ss58Prefix = client.consts.system.ss58Prefix; - console.log('Polkadot ss58Prefix:', ss58Prefix); +# Deploy Uniswap V2 - ``` +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. +## Introduction -- **Storage queries**: Use the syntax `client.query..` to query on-chain storage. +Decentralized exchanges (DEXs) are a cornerstone of the DeFi ecosystem, allowing for permissionless token swaps without intermediaries. [Uniswap V2](https://docs.uniswap.org/contracts/v2/overview){target=\_blank}, with its Automated Market Maker (AMM) model, revolutionized DEXs by enabling liquidity provision for any ERC-20 token pair. - ```typescript - const balance = await client.query.system.account('INSERT_ADDRESS'); - console.log('Balance:', balance.data.free); +This tutorial will guide you through how Uniswap V2 works so you can take advantage of it in your projects deployed to Polkadot Hub. By understanding these contracts, you'll gain hands-on experience with one of the most influential DeFi protocols and understand how it functions across blockchain ecosystems. - ``` +## Prerequisites -- **Subscribe to storage changes**: +Before starting, make sure you have: - ```typescript - const unsub = await client.query.system.number((blockNumber) => { - console.log(`Current block number: ${blockNumber}`); - }); +- Node.js (v16.0.0 or later) and npm installed. +- Basic understanding of Solidity and JavaScript. +- Familiarity with [`hardhat-polkadot`](/smart-contracts/dev-environments/hardhat/get-started/){target=\_blank} development environment. +- Some PAS test tokens to cover transaction fees (obtained from the [Polkadot faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}). +- Basic understanding of how AMMs and liquidity pools work. - ``` +## Set Up the Project -- **Call Runtime APIs**: Use the syntax `client.call..` to execute Runtime APIs. +Let's start by cloning the Uniswap V2 project: - ```typescript - const metadata = await client.call.metadata.metadataAtVersion(15); - console.log('Metadata V15', metadata); +1. Clone the Uniswap V2 repository: ``` + git clone https://github.com/polkadot-developers/polkavm-hardhat-examples.git -b v0.0.6 + cd polkavm-hardhat-examples/uniswap-v2-polkadot/ + ``` -- **Watch on-chain events**: Use the syntax `client.events..` to access pallet events. - - ```typescript - const unsub = await client.events.system.NewAccount.watch((events) => { - console.log('New Account Created', events); - }); +2. Install the required dependencies: + ```bash + npm install ``` -### Sign and Send Transactions - -Sign the transaction using `IKeyringPair` from Keyring ([`@polkadot/keyring`](https://polkadot.js.org/docs/keyring/start/sign-verify/){target=\_blank}) and send the transaction. - -```typescript -import { cryptoWaitReady } from '@polkadot/util-crypto'; -import { Keyring } from '@polkadot/keyring'; -// Setup keyring -await cryptoWaitReady(); -const keyring = new Keyring({ type: 'sr25519' }); -const alice = keyring.addFromUri('//Alice'); -// Send transaction -const unsub = await client.tx.balances - .transferKeepAlive('INSERT_DEST_ADDRESS', 2_000_000_000_000n) - .signAndSend(alice, async ({ status }) => { - console.log('Transaction status', status.type); - if (status.type === 'BestChainBlockIncluded') { - console.log(`Transaction is included in best block`); - } - if (status.type === 'Finalized') { - console.log( - `Transaction completed at block hash ${status.value.blockHash}` - ); - await unsub(); - } - }); +3. Update the `hardhat.config.js` file so the paths for the Substrate node and the ETH-RPC adapter match with the paths on your machine. For more info, check the [Testing your Contract](/smart-contracts/dev-environments/hardhat/compile-and-test/){target=\_blank} section in the Hardhat guide. -``` + ```js title="hardhat.config.js" + hardhat: { + polkavm: true, + nodeConfig: { + nodeBinaryPath: '../bin/substrate-node', + rpcPort: 8000, + dev: true, + }, + adapterConfig: { + adapterBinaryPath: '../bin/eth-rpc', + dev: true, + }, + }, + ``` -You can also use `Signer` from wallet extensions: - -```typescript -const injected = await window.injectedWeb3['polkadot-js'].enable('My dApp'); -const account = (await injected.accounts.get())[0]; -const signer = injected.signer; -const unsub = await client.tx.balances - .transferKeepAlive('INSERT_DEST_ADDRESS', 2_000_000_000_000n) - .signAndSend(account.address, { signer }, async ({ status }) => { - console.log('Transaction status', status.type); - if (status.type === 'BestChainBlockIncluded') { - console.log(`Transaction is included in best block`); - } - if (status.type === 'Finalized') { - console.log( - `Transaction completed at block hash ${status.value.blockHash}` - ); - await unsub(); - } - }); +4. Create a `.env` file in your project root to store your private keys (you can use as an example the `env.example` file): -``` + ```text title=".env" + LOCAL_PRIV_KEY="INSERT_LOCAL_PRIVATE_KEY" + AH_PRIV_KEY="INSERT_AH_PRIVATE_KEY" + ``` -## Where to Go Next - -For more detailed information about Dedot, check the [official documentation](https://dedot.dev/){target=\_blank}. - - ---- - -Page Title: Deploy an ERC-20 to Polkadot Hub - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-erc20-erc20-hardhat.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-hardhat/ -- Summary: Deploy an ERC-20 token on Polkadot Hub using PolkaVM. This guide covers contract creation, compilation, deployment, and interaction via Hardhat. - -# Deploy an ERC-20 to Polkadot Hub - -## Introduction - -[ERC-20](https://eips.ethereum.org/EIPS/eip-20){target=\_blank} tokens are fungible tokens commonly used for creating cryptocurrencies, governance tokens, and staking mechanisms. Polkadot Hub enables easy token deployment with Ethereum-compatible smart contracts and tools via the EVM backend. - -This tutorial covers deploying an ERC-20 contract on the Polkadot Hub TestNet using [Hardhat](https://hardhat.org/){target=\_blank}, an Ethereum development environment. The ERC-20 contract can be retrieved from OpenZeppelin's [GitHub repository](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20){target=\_blank} or their [Contract Wizard](https://wizard.openzeppelin.com/){target=\_blank}. - -## Prerequisites - -Before starting, make sure you have: - -- Basic understanding of Solidity programming and fungible tokens. -- Node.js v22.13.1 or later. -- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. - -## Set Up Your Project - -This tutorial uses a [Hardhat ERC-20 template](https://github.com/polkadot-developers/revm-hardhat-examples/tree/master/erc20-hardhat){target=\_blank} that contains all the necessary files. To get started, take the following steps: - -1. Clone the GitHub repository locally: - - ```bash - git clone https://github.com/polkadot-developers/revm-hardhat-examples/ - cd revm-hardhat-examples/erc20-hardhat - ``` - -2. Install the dependencies: - - ```bash - npm i - ``` - -This will fetch all the necessary packages to help you deploy an ERC-20 with Hardhat to Polkadot. - -## Configure Hardhat - -Once you've [setup your project](#set-up-your-project), you can configure the `hardhat.config.ts` to your needs. This tutorial has the file prepared to deploy to the Polkadot TestNet. - -To store and use private keys or network URLs, you can use Hardhat's configuration variables. This can be set via tasks in the **vars** scope. For example, to store the private key to deploy to the Polkadot TestNet, run the following command: - -```bash -npx hardhat vars set TESTNET_PRIVATE_KEY -``` - -The command will initiate a wizard in which you'll have to enter the value to be stored: - -
- npx hardhat vars set TESTNET_PRIVATE_KEY - ✔ Enter value: · ••••••••• - The configuration variable has been stored in /Users/albertoviera/Library/Preferences/hardhat-nodejs/vars.json -
- -??? warning "Key Encryption" - This solution just prevents variables to be included in the code repository. You should find a solution that encrypts private keys and access them securely. - -You can now use the account related to this private key by importing it into the Hardhat configuration file: - -```ts title="hardhat.config.ts" hl_lines="1 17" - -const config: HardhatUserConfig = { - solidity: { - version: "0.8.28", - settings: { - optimizer: { - enabled: true, - runs: 200, - }, - }, - }, - networks: { - polkadotTestnet: { - url: vars.get("TESTNET_URL", "http://127.0.0.1:8545"), - accounts: vars.has("TESTNET_PRIVATE_KEY") ? [vars.get("TESTNET_PRIVATE_KEY")] : [], - }, - }, - mocha: { - timeout: 40000, - }, -}; - -export default config; -``` - -## Compile your Contract - -Once you've configured Hardhat, you can compile the contract. - -In this tutorial, a simple ERC-20 is provided. Therefore, to compile the contract you can run the following command: - -```bash -npx hardhat compile -``` - -If everything compiles successfully, you should see the following output: - -
- npx hardhat compile - Generating typings for: 23 artifacts in dir: typechain-types for target: ethers-v6 - Successfully generated 62 typings! - Compiled 21 Solidity files successfully (evm target: paris). -
- -## Test your Contract - -Hardhat has a native feature to test contracts. You can run tests against the local Hardhat development node, but it could have some technical differences to Polkadot. Therefore, in this tutorial, you'll be testing against the Polkadot TestNet - -This example has a predefined test file located in [`test/Token.test.js`](https://github.com/polkadot-developers/revm-hardhat-examples/blob/master/erc20-hardhat/test/MyToken.test.ts){target=\_blank}, that runs the following tests: - -1. The token was deployed by verifying its **name** and **symbol**. -2. The token has the right owner configured. -3. The token has an initial supply of zero. -4. The owner can mint tokens. -5. The total supply is increased after a mint. -6. Perform multiple mints to different addresses and checks the balance of each address and the new total supply. - -To run the test, you can execute the following command: - -```bash -npx hardhat test --network polkadotTestnet -``` - -If tests are successful, you should see the following logs: - -
- npx hardhat test --network polkadotTestnet - -   MyToken -     Deployment -       ✔ Should have correct name and symbol -       ✔ Should set the right owner -       ✔ Should have zero initial supply -     Minting -       ✔ Should allow owner to mint tokens -       ✔ Should increase total supply on mint -     Multiple mints -       ✔ Should correctly track balance after multiple mints - -   6 passing (369ms) -
- -## Deploy your Contract - -With the Hardhat configuration file ready, the private key stored as a variable under **vars**, and the contract compiled, you can proceed to deploy the contract to a given network. In this tutorial, you are deploying it to the Polkadot TestNet. - -To deploy the contract, run the following command: - -```bash -npx hardhat ignition deploy ./ignition/modules/MyToken.ts --network polkadotTestnet -``` - -You'll need to confirm the target network (by chain ID): - -
- npx hardhat ignition deploy ./ignition/modules/MyToken.ts --network polkadotTestnet - ✔ Confirm deploy to network polkadotTestnet (420420420)? … yes -   - Hardhat Ignition 🚀 -   - Deploying [ TokenModule ] -   - Batch #1 - Executed TokenModule#MyToken -   - Batch #2 - Executed TokenModule#MyToken.mint -   - [ TokenModule ] successfully deployed 🚀 -   - Deployed Addresses -   - TokenModule#MyToken - 0xc01Ee7f10EA4aF4673cFff62710E1D7792aBa8f3 -
- -And that is it! You've successfully deployed an ERC-20 token contract to the Polkadot TestNet using Hardhat. - -## Where to Go Next - -
- -- Guide __Deploy an NFT with Remix__ - - --- - - Walk through deploying an ERC-721 Non-Fungible Token (NFT) using OpenZeppelin's battle-tested NFT implementation and Remix. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) - -
- - ---- - -Page Title: Deploy an ERC-20 to Polkadot Hub - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-erc20-erc20-remix.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix/ -- Summary: Deploy an ERC-20 token contract on Polkadot Hub. This guide covers contract creation, compilation, deployment, and interaction via the Remix IDE. - -# Deploy an ERC-20 to Polkadot Hub - -## Introduction - -[ERC-20](https://eips.ethereum.org/EIPS/eip-20){target=\_blank} tokens are fungible tokens commonly used for creating cryptocurrencies, governance tokens, and staking mechanisms. Polkadot Hub enables easy token deployment with Ethereum-compatible smart contracts and tools via the EVM backend. - -This tutorial covers deploying an ERC-20 contract on the Polkadot Hub TestNet using [Remix IDE](https://remix.ethereum.org/){target=\_blank}, a web-based development tool. The ERC-20 contract can be retrieved from OpenZeppelin's [GitHub repository](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20){target=\_blank} or their [Contract Wizard](https://wizard.openzeppelin.com/){target=\_blank}. - -## Prerequisites - -Before starting, make sure you have: - -- Basic understanding of Solidity programming and fungible tokens. -- An EVM-compatible wallet [connected to Polkadot Hub](/smart-contracts/integrations/wallets){target=\_blank}. This example utilizes [MetaMask](https://metamask.io/){target=\_blank}. -- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. - -## Create Your Contract - -To create the ERC-20 contract, you can follow the steps below: - -1. Navigate to the [Polkadot Remix IDE](https://remix.polkadot.io){target=\_blank}. -2. Click in the **Create new file** button under the **contracts** folder, and name your contract as `MyToken.sol`. - - ![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-1.webp) - -3. Now, paste the following ERC-20 contract code into the editor: - - ```solidity title="MyToken.sol" - // SPDX-License-Identifier: MIT - // Compatible with OpenZeppelin Contracts ^5.4.0 - pragma solidity ^0.8.27; - - import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol"; - import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; - - contract MyToken is ERC20, Ownable, ERC20Permit { - constructor(address initialOwner) - ERC20("MyToken", "MTK") - Ownable(initialOwner) - ERC20Permit("MyToken") - {} - - function mint(address to, uint256 amount) public onlyOwner { - _mint(to, amount); - } - } - ``` - - The key components of the code above are: - - - Contract imports: - - - **[`ERC20.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20/ERC20.sol){target=\_blank}**: The base contract for fungible tokens, implementing core functionality like transfers, approvals, and balance tracking. - - **[`ERC20Permit.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20/extensions/ERC20Permit.sol){target=\_blank}**: [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612){target=\_blank} extension for ERC-20 that adds the [permit function](https://docs.openzeppelin.com/contracts/5.x/api/token/erc20#ERC20Permit-permit-address-address-uint256-uint256-uint8-bytes32-bytes32-){target=\_blank}, allowing approvals via off-chain signatures (no on-chain tx from the holder). Manages nonces and EIP-712 domain separator and updates allowances when a valid signature is presented. - - **[`Ownable.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/access/Ownable.sol){target=\_blank}**: Provides basic authorization control, ensuring only the contract owner can mint new tokens. - - - Constructor parameters: - - - **`initialOwner`**: Sets the address that will have administrative rights over the contract. - - **`"MyToken"`**: The full name of your token. - - **`"MTK"`**: The symbol representing your token in wallets and exchanges. - - - Key functions: - - - **`mint(address to, uint256 amount)`**: Allows the contract owner to create new tokens for any address. The amount should include 18 decimals (e.g., 1 token = 1000000000000000000). - - Inherited [Standard ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/){target=\_blank} functions: - - **`transfer(address recipient, uint256 amount)`**: Sends a specified amount of tokens to another address. - - **`approve(address spender, uint256 amount)`**: Grants permission for another address to spend a specific number of tokens on behalf of the token owner. - - **`transferFrom(address sender, address recipient, uint256 amount)`**: Transfers tokens from one address to another, if previously approved. - - **`balanceOf(address account)`**: Returns the token balance of a specific address. - - **`allowance(address owner, address spender)`**: Checks how many tokens an address is allowed to spend on behalf of another address. - - !!! tip - Use the [OpenZeppelin Contracts Wizard](https://wizard.openzeppelin.com/){target=\_blank} to generate customized smart contracts quickly. Simply configure your contract, copy the generated code, and paste it into the Remix IDE for deployment. Below is an example of an ERC-20 token contract created with it: - - ![Screenshot of the OpenZeppelin Contracts Wizard showing an ERC-20 contract configuration.](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-2.webp) - - -## Compile - -The compilation transforms your Solidity source code into bytecode that can be deployed on the blockchain. During this process, the compiler checks your contract for syntax errors, ensures type safety, and generates the machine-readable instructions needed for blockchain execution. - -To compile your contract, ensure you have it opened in the Remix IDE Editor, and follow the instructions below: - -1. Select the **Solidity Compiler** plugin from the left panel. -2. Click the **Compile MyToken.sol** button. -3. If the compilation succeeded, you'll see a green checkmark indicating success in the **Solidity Compiler** icon. - -![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-3.gif) - -## Deploy - -Deployment is the process of publishing your compiled smart contract to the blockchain, making it permanently available for interaction. During deployment, you'll create a new instance of your contract on the blockchain, which involves: - -1. Select the **Deploy & Run Transactions** plugin from the left panel. -2. Configure the deployment settings: - 1. From the **ENVIRONMENT** dropdown, select **Injected Provider - MetaMask** (check the [Deploying Contracts](/smart-contracts/dev-environments/remix/deploy-a-contract/){target=\_blank} section of the Remix IDE guide for more details). - 2. (Optional) From the **ACCOUNT** dropdown, select the acccount you want to use for the deploy. - -3. Configure the contract parameters: - 1. Enter the address that will own the deployed token contract. - 2. Click the **Deploy** button to initiate the deployment. - -4. **MetaMask will pop up**: Review the transaction details. Click **Confirm** to deploy your contract. -5. If the deployment process succeeded, you will see the transaction details in the terminal, including the contract address and deployment transaction hash. - -![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-4.gif) - -## Interact with Your Contract - -Once deployed, you can interact with your contract through Remix. Find your contract under **Deployed/Unpinned Contracts**, and click it to expand the available methods. In this example, you'll mint some tokens to a given address: - -1. Expand the **mint** function: - 1. Enter the recipient address and the amount (remember to add 18 zeros for 1 whole token). - 2. Click **transact**. - -2. Click **Approve** to confirm the transaction in the MetaMask popup. - -3. If the transaction succeeds, you will see a green check mark in the terminal. - -4. You can also call the **balanceOf** function by passing the address of the **mint** call to confirm the new balance. - -![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-5.gif) - - -Other standard functions you can use: - -- **`transfer(address to, uint256 amount)`**: Send tokens to another address. -- **`approve(address spender, uint256 amount)`**: Allow another address to spend your tokens. - -Feel free to explore and interact with the contract's other functions using the same approach: select the method, provide any required parameters, and confirm the transaction in MetaMask when needed. - -## Where to Go Next - -
- -- Guide __Deploy an NFT with Remix__ - - --- - - Walk through deploying an ERC-721 Non-Fungible Token (NFT) using OpenZeppelin's battle-tested NFT implementation and Remix. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) - -
- - ---- - -Page Title: Deploy an NFT to Polkadot Hub with Foundry - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-.foundry.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/.foundry/ -- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub using Foundry, a Rust toolkit with high-performance compilation. - -# Deploy an NFT with Foundry - -## Introduction - -Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. - -This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. It showcases a secure approach using [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and the [Foundry](https://getfoundry.sh/){target=\_blank} toolchain. Foundry, a fast, Rust-written toolkit, ensures high-performance compilation and is fully compatible with the Hub’s EVM environment via standard Solidity compilation. - -## Prerequisites - -- Basic understanding of Solidity programming and NFT standards. -- Test tokens for gas fees (available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}). See the [step-by-step instructions](/smart-contracts/faucet/#get-test-tokens){target=\_blank}. -- A wallet with a private key for signing transactions. - -## Set Up Your Project - -To get started, take the following steps: - -1. Install Foundry: - - ```bash - curl -L https://foundry.paradigm.xyz | bash - foundryup - ``` - -2. Initialize your project: - - ```bash - forge init foundry-nft-deployment - cd foundry-nft-deployment - ``` - -3. Install OpenZeppelin contracts: - - ```bash - forge install OpenZeppelin/openzeppelin-contracts - ``` - -## Configure Foundry - -Edit `foundry.toml`: - -```toml title="foundry.toml" -[profile.default] -src = "src" -out = "out" -libs = ["lib"] -remappings = ['@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/'] - -[rpc_endpoints] -polkadot_hub_testnet = "https://testnet-passet-hub-eth-rpc.polkadot.io" -``` - -## Create Your Contract - -Create `src/MyNFT.sol`: - -```solidity title="src/MyNFT.sol" -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.20; - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "@openzeppelin/contracts/access/Ownable.sol"; - -contract MyNFT is ERC721, Ownable { - uint256 private _nextTokenId; - - constructor(address initialOwner) - ERC721("MyToken", "MTK") - Ownable(initialOwner) - {} - - function safeMint(address to) public onlyOwner { - uint256 tokenId = _nextTokenId++; - _safeMint(to, tokenId); - } -} -``` - -## Compile - -```bash -forge build -``` - -Verify the compilation by inspecting the bytecode: - -```bash -forge inspect MyNFT bytecode -``` - -## Deploy - -Deploy to Polkadot Hub TestNet: - -```bash -forge create MyNFT \ - --rpc-url polkadot_hub_testnet \ - --private-key YOUR_PRIVATE_KEY \ - --constructor-args YOUR_OWNER_ADDRESS \ - --broadcast -``` - -Replace `YOUR_PRIVATE_KEY` with your private key and `YOUR_OWNER_ADDRESS` with the address that will own the NFT contract. - -## Where to Go Next - -
- -- Guide __Verify Your Contract__ - - --- - - Now that you've deployed an NFT contract, learn how to verify it with Foundry. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/foundry/verify-a-contract/) - -- Guide __Deploy an ERC-20__ - - --- - - Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Foundry. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/foundry/) - -
- - ---- - -Page Title: Deploy an NFT to Polkadot Hub with Hardhat - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-hardhat.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/hardhat/ -- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub with Hardhat, a comprehenive development environment with built-in deployment capabilities. - -# Deploy an NFT with Hardhat - -## Introduction - -Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. - -This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. You'll use [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and [Hardhat](https://hardhat.org/docs/getting-started){target=\_blank}, a comprehensive development environment with built-in testing, debugging, and deployment capabilities. Hardhat uses standard Solidity compilation to generate EVM bytecode, making it fully compatible with Polkadot Hub's EVM environment. - -## Prerequisites - -- Basic understanding of Solidity programming and NFT standards. -- Node.js v22.13.1 or later. -- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. -- A wallet with a private key for signing transactions. - -## Set Up Your Project - -Take the following steps to get started: - -1. Initialize your Hardhat project: - - ```bash - mkdir hardhat-nft-deployment - cd hardhat-nft-deployment - npx hardhat --init - ``` - -2. Install OpenZeppelin contracts: - - ```bash - npm install @openzeppelin/contracts - ``` - -## Configure Hardhat - -Edit `hardhat.config.ts`: - -```typescript title="hardhat.config.ts" -import type { HardhatUserConfig } from 'hardhat/config'; - -import hardhatToolboxViemPlugin from '@nomicfoundation/hardhat-toolbox-viem'; -import { configVariable } from 'hardhat/config'; - -const config: HardhatUserConfig = { - plugins: [hardhatToolboxViemPlugin], - solidity: { - profiles: { - default: { - version: '0.8.28', - }, - production: { - version: '0.8.28', - settings: { - optimizer: { - enabled: true, - runs: 200, - }, - }, - }, - }, - }, - networks: { - hardhatMainnet: { - type: 'edr-simulated', - chainType: 'l1', - }, - hardhatOp: { - type: 'edr-simulated', - chainType: 'op', - }, - sepolia: { - type: 'http', - chainType: 'l1', - url: configVariable('SEPOLIA_RPC_URL'), - accounts: [configVariable('SEPOLIA_PRIVATE_KEY')], - }, - polkadotHubTestnet: { - type: 'http', - url: 'https://testnet-passet-hub-eth-rpc.polkadot.io', - chainId: 420420422, - accounts: [configVariable('PRIVATE_KEY')], - }, - }, -}; - -export default config; -``` - -!!! tip - Learn how to use Hardhat's [Config Variables](https://hardhat.org/docs/learn-more/configuration-variables){target=\_blank} to handle your private keys in a secure way. - -## Create Your Contract - -Create `contracts/MyNFT.sol`: - -```solidity title="contracts/MyNFT.sol" -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.20; - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "@openzeppelin/contracts/access/Ownable.sol"; - -contract MyNFT is ERC721, Ownable { - uint256 private _nextTokenId; - - constructor(address initialOwner) - ERC721("MyToken", "MTK") - Ownable(initialOwner) - {} - - function safeMint(address to) public onlyOwner { - uint256 tokenId = _nextTokenId++; - _safeMint(to, tokenId); - } -} -``` - -## Compile - -```bash -npx hardhat compile -``` - -## Set Up Deployment - -Create a deployment module in `ignition/modules/MyNFT.ts`: - -```typescript title="ignition/modules/MyNFT.ts" -import { buildModule } from '@nomicfoundation/hardhat-ignition/modules'; - -export default buildModule('MyNFTModule', (m) => { - const initialOwner = m.getParameter('initialOwner', 'INSERT_OWNER_ADDRESS'); - const myNFT = m.contract('MyNFT', [initialOwner]); - return { myNFT }; -}); -``` - -Replace `INSERT_OWNER_ADDRESS` with your desired owner address. - -## Deploy - -Deploy to Polkadot Hub TestNet: - -```bash -npx hardhat ignition deploy ignition/modules/MyNFT.ts --network polkadotHubTestnet -``` - -## Where to Go Next - -
- -- Guide __Verify Your Contract__ - - --- - - Now that you've deployed an NFT contract, learn how to verify it with Hardhat. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/hardhat/verify-a-contract/) - - -- Guide __Deploy an ERC-20__ - - --- - - Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Hardhat. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/hardhat/) - -
- - ---- - -Page Title: Deploy an NFT to Polkadot Hub with Remix - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-remix.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/ -- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub using Remix, a browser-based IDE for quick prototyping and learning. - -# Deploy an NFT with Remix - -## Introduction - -Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. - -This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. You'll use [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and [Remix](https://remix.ethereum.org/){target=\_blank}, a visual, browser-based environment perfect for rapid prototyping and learning. It requires no local installation and provides an intuitive interface for contract development. - -## Prerequisites - -- Basic understanding of Solidity programming and NFT standards. -- Test tokens for gas fees (available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}). See the [step-by-step instructions](/smart-contracts/faucet/#get-test-tokens){target=\_blank} -- A wallet with a private key for signing transactions. - -## Access Remix - -Navigate to [Remix](https://remix.ethereum.org/){target=\_blank} in your web browser. - -The interface will load with a default workspace containing sample contracts. In this interface, you can access a file explorer, edit your code, interact with various plugins for development, and use a terminal. - -## Create Your Contract - -1. Create a new file `contracts/MyNFT.sol`. -2. Paste the following code: - - ```solidity title="contracts/MyNFT.sol" - // SPDX-License-Identifier: MIT - pragma solidity ^0.8.20; - - import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; - import "@openzeppelin/contracts/access/Ownable.sol"; - - contract MyNFT is ERC721, Ownable { - uint256 private _nextTokenId; - - constructor(address initialOwner) - ERC721("MyToken", "MTK") - Ownable(initialOwner) - {} - - function safeMint(address to) public onlyOwner { - uint256 tokenId = _nextTokenId++; - _safeMint(to, tokenId); - } - } - ``` - -![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-01.webp) - -## Compile - -1. Navigate to the **Solidity Compiler** tab (third icon in the left sidebar). -2. Click **Compile MyNFT.sol** or press `Ctrl+S`. - -![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-02.webp) - -Compilation errors and warnings appear in the terminal panel at the bottom of the screen. - -## Deploy - -1. Navigate to the **Deploy & Run Transactions** tab. -2. Click the **Environment** dropdown, select **Browser Extension**, and click on **Injected Provider - MetaMask**. - - ![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-03.webp) - -3. In the deploy section, enter the initial owner address in the constructor parameter field. -4. Click **Deploy**. - - ![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-04.webp) - -5. Approve the transaction in your MetaMask wallet. - -Your deployed contract will appear in the **Deployed Contracts** section, ready for interaction. - -## Where to Go Next - -
- -- Guide __Verify Your Contract__ - - --- - - Now that you've deployed an NFT contract, learn how to verify it with Remix. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/remix/verify-a-contract/) - -- Guide __Deploy an ERC-20__ - - --- - - Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Remix. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/) - -
- - ---- - -Page Title: Deploying Uniswap V2 on Polkadot - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-eth-dapps-uniswap-v2.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/eth-dapps/uniswap-v2/ -- Summary: Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. - -# Deploy Uniswap V2 - -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction - -Decentralized exchanges (DEXs) are a cornerstone of the DeFi ecosystem, allowing for permissionless token swaps without intermediaries. [Uniswap V2](https://docs.uniswap.org/contracts/v2/overview){target=\_blank}, with its Automated Market Maker (AMM) model, revolutionized DEXs by enabling liquidity provision for any ERC-20 token pair. - -This tutorial will guide you through how Uniswap V2 works so you can take advantage of it in your projects deployed to Polkadot Hub. By understanding these contracts, you'll gain hands-on experience with one of the most influential DeFi protocols and understand how it functions across blockchain ecosystems. - -## Prerequisites - -Before starting, make sure you have: - -- Node.js (v16.0.0 or later) and npm installed. -- Basic understanding of Solidity and JavaScript. -- Familiarity with [`hardhat-polkadot`](/smart-contracts/dev-environments/hardhat/get-started/){target=\_blank} development environment. -- Some PAS test tokens to cover transaction fees (obtained from the [Polkadot faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}). -- Basic understanding of how AMMs and liquidity pools work. - -## Set Up the Project - -Let's start by cloning the Uniswap V2 project: - -1. Clone the Uniswap V2 repository: - - ``` - git clone https://github.com/polkadot-developers/polkavm-hardhat-examples.git -b v0.0.6 - cd polkavm-hardhat-examples/uniswap-v2-polkadot/ - ``` - -2. Install the required dependencies: - - ```bash - npm install - ``` - -3. Update the `hardhat.config.js` file so the paths for the Substrate node and the ETH-RPC adapter match with the paths on your machine. For more info, check the [Testing your Contract](/smart-contracts/dev-environments/hardhat/compile-and-test/){target=\_blank} section in the Hardhat guide. - - ```js title="hardhat.config.js" - hardhat: { - polkavm: true, - nodeConfig: { - nodeBinaryPath: '../bin/substrate-node', - rpcPort: 8000, - dev: true, - }, - adapterConfig: { - adapterBinaryPath: '../bin/eth-rpc', - dev: true, - }, - }, - ``` - -4. Create a `.env` file in your project root to store your private keys (you can use as an example the `env.example` file): - - ```text title=".env" - LOCAL_PRIV_KEY="INSERT_LOCAL_PRIVATE_KEY" - AH_PRIV_KEY="INSERT_AH_PRIVATE_KEY" - ``` - - Ensure to replace `"INSERT_LOCAL_PRIVATE_KEY"` with a private key available in the local environment (you can get them from this [file](https://github.com/paritytech/hardhat-polkadot/blob/main/packages/hardhat-polkadot-node/src/constants.ts#L22){target=\_blank}). And `"INSERT_AH_PRIVATE_KEY"` with the account's private key you want to use to deploy the contracts. You can get this by exporting the private key from your wallet (e.g., MetaMask). - - !!!warning - Keep your private key safe, and never share it with anyone. If it is compromised, your funds can be stolen. - -5. Compile the contracts: - - ```bash - npx hardhat compile - ``` - -If the compilation is successful, you should see the following output: - -
- npx hardhat compile - Compiling 12 Solidity files - Successfully compiled 12 Solidity files -
- -After running the above command, you should see the compiled contracts in the `artifacts-pvm` directory. This directory contains the ABI and bytecode of your contracts. - -## Understanding Uniswap V2 Architecture - -Before interacting with the contracts, it's essential to understand the core architecture that powers Uniswap V2. This model forms the basis of nearly every modern DEX implementation and operates under automated market making, token pair liquidity pools, and deterministic pricing principles. - -At the heart of Uniswap V2 lies a simple but powerful system composed of two major smart contracts: - -- **Factory contract**: The factory acts as a registry and creator of new trading pairs. When two ERC-20 tokens are to be traded, the Factory contract is responsible for generating a new Pair contract that will manage that specific token pair’s liquidity pool. It keeps track of all deployed pairs and ensures uniqueness—no duplicate pools can exist for the same token combination. -- **Pair contract**: Each pair contract is a decentralized liquidity pool that holds reserves of two ERC-20 tokens. These contracts implement the core logic of the AMM, maintaining a constant product invariant (x \* y = k) to facilitate swaps and price determination. Users can contribute tokens to these pools in return for LP (liquidity provider) tokens, which represent their proportional share of the reserves. - -This minimal architecture enables Uniswap to be highly modular, trustless, and extensible. By distributing responsibilities across these components, developers, and users can engage with the protocol in a composable and predictable manner, making it an ideal foundation for DEX functionality across ecosystems, including Polkadot Hub. - -The project scaffolding is as follows: - -```bash -uniswap-V2-polkadot -├── bin/ -├── contracts/ -│ ├── interfaces/ -│ │ ├── IERC20.sol -│ │ ├── IUniswapV2Callee.sol -│ │ ├── IUniswapV2ERC20.sol -│ │ ├── IUniswapV2Factory.sol -│ │ └── IUniswapV2Pair.sol -│ ├── libraries/ -│ │ ├── Math.sol -│ │ ├── SafeMath.sol -│ │ └── UQ112x112.sol -│ ├── test/ -│ │ └── ERC20.sol -│ ├── UniswapV2ERC20.sol -│ ├── UniswapV2Factory.sol -│ └── UniswapV2Pair.sol -├── ignition/ -├── scripts/ -│ └── deploy.js -├── node_modules/ -├── test/ -│ ├── shared/ -│ │ ├── fixtures.js -│ │ └── utilities.js -│ ├── UniswapV2ERC20.js -│ ├── UniswapV2Factory.js -│ └── UniswapV2Pair.js -├── .env.example -├── .gitignore -├── hardhat.config.js -├── package.json -└── README.md -``` - -## Test the Contracts - -You can run the provided test suite to ensure the contracts are working as expected. The tests cover various scenarios, including creating pairs, adding liquidity, and executing swaps. - -To test it locally, you can run the following commands: - -1. Spawn a local node for testing: - - ```bash - npx hardhat node - ``` - - This command will spawn a local Substrate node along with the ETH-RPC adapter. The node will be available at `ws://127.0.0.1:8000` and the ETH-RPC adapter at `http://localhost:8545`. - -2. In a new terminal, run the tests: - - ```bash - npx hardhat test --network localNode - ``` - -The result should look like this: - -
- npx hardhat test --network localNode - Compiling 12 Solidity files - Successfully compiled 12 Solidity files - - UniswapV2ERC20 - ✔ name, symbol, decimals, totalSupply, balanceOf, DOMAIN_SEPARATOR, PERMIT_TYPEHASH (44ms) - ✔ approve (5128ms) - ✔ transfer (5133ms) - ✔ transfer:fail - ✔ transferFrom (6270ms) - ✔ transferFrom:max (6306ms) - - UniswapV2Factory - ✔ feeTo, feeToSetter, allPairsLength - ✔ createPair (176ms) - ✔ createPair:reverse (1224ms) - ✔ setFeeTo (1138ms) - ✔ setFeeToSetter (1125ms) - - UniswapV2Pair - ✔ mint (11425ms) - ✔ getInputPrice:0 (12590ms) - ✔ getInputPrice:1 (17600ms) - ✔ getInputPrice:2 (17618ms) - ✔ getInputPrice:3 (17704ms) - ✔ getInputPrice:4 (17649ms) - ✔ getInputPrice:5 (17594ms) - ✔ getInputPrice:6 (13643ms) - ✔ optimistic:0 (17647ms) - ✔ optimistic:1 (17946ms) - ✔ optimistic:2 (17657ms) - ✔ optimistic:3 (21625ms) - ✔ swap:token0 (12665ms) - ✔ swap:token1 (17631ms) - ✔ burn (17690ms) - ✔ feeTo:off (23900ms) - ✔ feeTo:on (24991ms) - - 28 passing (12m) -
- -## Deploy the Contracts - -After successfully testing the contracts, you can deploy them to the local node or Polkadot Hub. The deployment script is located in the `scripts` directory and is named `deploy.js`. This script deploys the `Factory` and `Pair` contracts to the network. - -To deploy the contracts, run the following command: - -```bash -npx hardhat run scripts/deploy.js --network localNode -``` - -This command deploys the contracts to your local blockchain for development and testing. If you want to deploy to Polkadot Hub, you can use the following command: - -```bash -npx hardhat run scripts/deploy.js --network passetHub -``` - -The command above deploys to the actual Polkadot TestNet. It requires PAS test tokens, persists on the network, and operates under real network conditions. - -The deployment script will output the addresses of the deployed contracts. Save these addresses, as you will need them to interact with the contracts. For example, the output should look like this: - -
- npx hardhat run scripts/deploy.js --network localNode - Successfully compiled 12 Solidity files - Deploying contracts using 0xf24FF3a9CF04c71Dbc94D0b566f7A27B94566cac - Deploying UniswapV2ERC20... - ETH deployed to : 0x7acc1aC65892CF3547b1b0590066FB93199b430D - Deploying UniswapV2Factory... - Factory deployed to : 0x85b108660f47caDfAB9e0503104C08C1c96e0DA9 - Deploying UniswapV2Pair with JsonRpcProvider workaround... - Pair deployed to : 0xF0e46847c8bFD122C4b5EEE1D4494FF7C5FC5104 -
- -## Conclusion - -This tutorial guided you through deploying Uniswap V2 contracts to Polkadot Hub. This implementation brings the powerful AMM architecture to the Polkadot ecosystem, laying the foundation for the decentralized trading of ERC-20 token pairs. - -By following this guide, you've gained practical experience with: - -- Setting up a Hardhat project for deploying to Polkadot Hub. -- Understanding the Uniswap V2 architecture. -- Testing Uniswap V2 contracts in a local environment. -- Deploying contracts to both local and testnet environments. - -To build on this foundation, you could extend this project by implementing functionality to create liquidity pools, execute token swaps, and build a user interface for interacting with your deployment. - -This knowledge can be leveraged to build more complex DeFi applications or to integrate Uniswap V2 functionality into your existing projects on Polkadot. - - ---- - -Page Title: Dual Virtual Machine Stack - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-dual-vm-stack.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/dual-vm-stack/ -- Summary: Compare Polkadot’s dual smart contract VMs—REVM for EVM compatibility and PolkaVM for RISC-V performance, flexibility, and efficiency. - -# Dual Virtual Machine Stack - -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction - -Polkadot's smart contract platform supports two distinct virtual machine (VM) architectures, providing developers with flexibility in selecting the optimal execution backend for their specific needs. This approach strikes a balance between immediate Ethereum compatibility and long-term innovation, enabling developers to deploy either unmodified (Ethereum Virtual Machine) EVM contracts using Rust Ethereum Virtual Machine (REVM) or optimize for higher performance using PolkaVM (PVM). - -Both VM options share common infrastructure, including RPC interfaces, tooling support, and precompiles. The following sections compare architectures and guide you in selecting the best VM for your project's needs. - -## Migrate from EVM - -The [REVM backend](https://github.com/bluealloy/revm){target=\_blank} integrates a complete Rust implementation of the EVM, enabling Solidity contracts to run unchanged on Polkadot's smart contract platform. - -REVM allows developers to use their existing Ethereum tooling and infrastructure to build on Polkadot. Choose REVM to: - -- Migrate existing Ethereum contracts without modifications. -- Retain exact EVM behavior for audit tools. -- Use developer tools that rely upon inspecting EVM bytecode. -- Prioritize rapid deployment over optimization. -- Work with established Ethereum infrastructure and tooling to build on Polkadot. - -REVM enables Ethereum developers to seamlessly migrate to Polkadot, achieving performance and fee improvements without modifying their existing contracts or developer tooling stack. - -## Upgrade to PolkaVM - -[**PolkaVM**](https://github.com/paritytech/polkavm){target=\_blank} is a custom virtual machine optimized for performance with [RISC-V-based](https://en.wikipedia.org/wiki/RISC-V){target=\_blank} architecture, supporting Solidity and additional high-performance languages. It serves as the core execution environment, integrated directly within the runtime. Choose the PolkaVM for: - -- An efficient interpreter for immediate code execution. -- A planned [Just In Time (JIT)](https://en.wikipedia.org/wiki/Just-in-time_compilation){target=\_blank} compiler for optimized performance. -- Dual-mode execution capability, allowing selection of the most appropriate backend for specific workloads. -- Optimized performance for short-running contract calls through the interpreter. - -The interpreter remains particularly beneficial for contracts with minimal code execution, as it enables immediate code execution through lazy interpretation. - -## Architecture - -The following key components of PolkaVM work together to enable Ethereum compatibility on Polkadot-based chains. - -### Revive Pallet - -[**`pallet_revive`**](https://paritytech.github.io/polkadot-sdk/master/pallet_revive/index.html){target=\_blank} is a runtime module that executes smart contracts by adding extrinsics, runtime APIs, and logic to convert Ethereum-style transactions into formats compatible with Polkadot SDK-based blockchains. It processes Ethereum-style transactions through the following workflow: - -```mermaid -sequenceDiagram - participant User as User/dApp - participant Proxy as Ethereum JSON RPC Proxy - participant Chain as Blockchain Node - participant Pallet as pallet_revive - - User->>Proxy: Submit Ethereum Transaction - Proxy->>Chain: Repackage as Polkadot Compatible Transaction - Chain->>Pallet: Process Transaction - Pallet->>Pallet: Decode Ethereum Transaction - Pallet->>Pallet: Execute Contract via PolkaVM - Pallet->>Chain: Return Results - Chain->>Proxy: Forward Results - Proxy->>User: Return Ethereum-compatible Response -``` - -This proxy-based approach eliminates the need for node binary modifications, maintaining compatibility across different client implementations. Preserving the original Ethereum transaction payload simplifies the adaptation of existing tools, which can continue processing familiar transaction formats. - -### PolkaVM Design Fundamentals - -PolkaVM differs from the EVM in two key ways that make it faster, more hardware-efficient, and easier to extend: - -- **Register-based design**: Instead of a stack machine, PolkaVM uses a RISC-V–style register model. This design: - - - Uses a fixed set of registers to pass arguments, not an infinite stack. - - Maps cleanly to real hardware like x86-64. - - Simplifies compilation and boosts runtime efficiency. - - Enables tighter control over register allocation and performance tuning. - -- **64-bit word size**: PolkaVM runs on a native 64-bit word size, aligning directly with modern CPUs. This design: - - - Executes arithmetic operations with direct hardware support. - - Maintains compatibility with Solidity’s 256-bit types via YUL translation. - - Accelerates computation-heavy workloads through native word alignment. - - Integrates easily with low-level, performance-focused components. - -## Where To Go Next - -
- -- Learn __Contract Deployment__ - - --- - - Learn how REVM and PVM compare for compiling and deploying smart contracts. - - [:octicons-arrow-right-24: Reference](/smart-contracts/for-eth-devs/contract-deployment/) - -
- - ---- - -Page Title: Get Started with Parachain Development - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-get-started.md -- Canonical (HTML): https://docs.polkadot.com/parachains/get-started/ -- Summary: Practical examples and tutorials for building and deploying Polkadot parachains, covering everything from launch to customization and cross-chain messaging. - -# Get Started - -The following sections provide practical recipes for building parachains on Polkadot—each focused on specific development scenarios with step-by-step, hands-on examples. - -## Quick Start Guides - -Quick start guides help developers set up and interact with the Polkadot parachain ecosystem using various tools and frameworks. - -| Tutorial | Tools | Description | -| :--------------------------------------------------------------------------------------------: | :----------------------------: | :---------------------------------------------------------------------: | -| [Set Up the Parachain Template](/parachains/launch-a-parachain/set-up-the-parachain-template/) | Polkadot SDK | Learn how to set up and run the Polkadot SDK Parachain Template locally | -| [Launch a Local Parachain](/parachains/testing/run-a-parachain-network/) | Zombienet, Chopsticks | Set up a local development environment for testing | -| [Connect to Polkadot](/chain-interactions/query-on-chain-data/query-sdks/) | Polkadot.js, Substrate Connect | Connect your application to Polkadot networks | -| [Fork an Existing Parachain](/parachains/testing/fork-a-parachain/) | Chopsticks | Create a local fork of a live parachain for testing | - -## Launch a Simple Parachain - -Learn the fundamentals of launching and deploying a parachain to the Polkadot network. - -| Tutorial | Description | -| :--------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------: | -| [Set Up the Parachain Template](/parachains/launch-a-parachain/set-up-the-parachain-template/) | Polkadot SDK | -| [Deploy to Polkadot](/parachains/launch-a-parachain/deploy-to-polkadot/) | Step-by-step tutorial to deploying your parachain to Polkadot | -| [Obtain Coretime](/parachains/launch-a-parachain/obtain-coretime/) | Learn how to acquire blockspace using Polkadot's coretime model (RegionX) | - -## Customize Your Runtime - -Build custom functionality for your parachain by composing and creating pallets. - -| Tutorial | Description | -| :-------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------: | -| [Add Existing Pallets to the Runtime](/parachains/customize-runtime/add-existing-pallets/) | Integrate pre-built pallets from the FRAME ecosystem | -| [Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/) | Configure and use multiple instances of the same pallet | -| [Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/) | Enable smart contract capabilities using Contracts or EVM pallets | - -### Pallet Development - -Deep dive into creating and managing custom pallets for your parachain. - -| Tutorial | Description | -| :--------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------: | -| [Create a Custom Pallet](/parachains/customize-runtime/pallet-development/create-a-pallet/) | Build a pallet from scratch with custom logic | -| [Mock Your Runtime](/parachains/customize-runtime/pallet-development/mock-runtime/) | Set up a mock runtime environment for testing | -| [Pallet Unit Testing](/parachains/customize-runtime/pallet-development/pallet-testing/) | Write comprehensive tests for your pallet logic | -| [Add Your Custom Pallet to the Runtime](/parachains/customize-runtime/pallet-development/add-pallet-to-runtime/) | Integrate your custom pallet into your parachain runtime | -| [Benchmark the Custom Pallet](/parachains/customize-runtime/pallet-development/benchmark-pallet/) | Measure and optimize pallet performance with benchmarking | - -## Testing - -Test your parachain in various environments before production deployment. - -| Tutorial | Description | -| :---------------------------------------------------------------------: | :-----------------------------------------------------: | -| [Fork a Parachain](/parachains/testing/fork-a-parachain/) | Use Chopsticks to create a local fork for testing | -| [Run a Parachain Network](/parachains/testing/run-a-parachain-network/) | Launch a complete parachain test network with Zombienet | - -## Runtime Upgrades and Maintenance - -Manage your parachain's lifecycle with forkless upgrades and maintenance operations. - -| Tutorial | Description | -| :-----------------------------------------------------------------------: | :--------------------------------------------------: | -| [Runtime Upgrades](/parachains/runtime-maintenance/runtime-upgrades/) | Perform forkless runtime upgrades via governance | -| [Storage Migrations](/parachains/runtime-maintenance/storage-migrations/) | Safely migrate storage when updating runtime logic | -| [Unlock Parachains](/parachains/runtime-maintenance/unlock-parachains/) | Understand parachain lifecycle and unlock mechanisms | - -## Interoperability - -Configure your parachain for cross-chain communication using XCM (Cross-Consensus Messaging). - -| Tutorial | Description | -| :--------------------------------------------------------------------------------------------------------: | :----------------------------------------------------: | -| [Open HRMP Channels Between Parachains](/parachains/interoperability/channels-between-parachains/) | Establish communication channels with other parachains | -| [Open HRMP Channels with System Parachains](/parachains/interoperability/channels-with-system-parachains/) | Connect with Asset Hub and other system parachains | - -## Integrations - -Integrate your parachain with essential ecosystem tools and services. - -| Tutorial | Description | -| :--------------------------------------------: | :----------------------------------------------------: | -| [Wallets](/parachains/integrations/wallets/) | Integrate wallet support for user interactions | -| [Indexers](/parachains/integrations/indexers/) | Set up indexing solutions for querying blockchain data | -| [Oracles](/parachains/integrations/oracles/) | Connect your parachain to off-chain data sources | - -## Additional Resources - -- [Polkadot SDK Documentation](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/index.html) -- [Polkadot Wiki - Parachains](https://wiki.polkadot.network/docs/learn-parachains/) - - ---- - -Page Title: Get Started with Smart Contracts - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-get-started.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/get-started/ -- Summary: Practical examples for building and deploying smart contracts on Polkadot Hub, from connecting and tooling to deployment, integrations, and precompiles. - -# Get Started - -This resource provides quick-starts for building smart contracts on Polkadot Hub. Use the tables below to jump directly to the tools and workflows you need. - -## Quick Starts - -Kick off development fast with curated links for connecting, funding, exploring, and deploying your first contract. - -| Quick Start | Tools | Description | -|:---------------------------------------------------------------------------------------------------:|:---------------------:|:---------------------------------------------------------------:| -| [Connect to Polkadot](/smart-contracts/connect/){target=\_blank} | Polkadot.js, MetaMask | Add the network, configure RPC, verify activity in the explorer | -| [Get Test Tokens](/smart-contracts/faucets/){target=\_blank} | - | Request test funds to deploy and interact with contracts | -| [Explore Transactions](/smart-contracts/explorers/){target=\_blank} | Subscan | Inspect transactions, logs, token transfers, and contract state | -| [Deploy with Remix](/smart-contracts/dev-environments/remix/deploy-a-contract/){target=\_blank} | Remix | One‑click browser deployment to Polkadot Hub | -| [Deploy with Foundry](/smart-contracts/dev-environments/foundry/deploy-a-contract/){target=\_blank} | Foundry | Scripted deployments and testing from the CLI | -| [Deploy with Hardhat](/smart-contracts/dev-environments/hardhat/deploy-a-contract/){target=\_blank} | Hardhat | Project scaffolding, testing, and deployments | - -## Build and Test Locally - -Set up local environments and CI-friendly workflows to iterate quickly and validate changes before deploying. - -| Build and Test Locally | Tools | Description | -|:------------------------------------------------------------------------------------------------------------:|:-----------------:|:----------------------------------------------------:| -| [Run a Local Dev Node](/smart-contracts/dev-environments/local-dev-node/){target=\_blank} | Polkadot SDK node | Spin up a local node for iterative development | -| [Remix: Get Started](/smart-contracts/dev-environments/remix/get-started/){target=\_blank} | Remix | Connect Remix to Polkadot Hub and configure accounts | -| [Remix: Verify a Contract](/smart-contracts/dev-environments/remix/verify-a-contract/){target=\_blank} | Remix | Publish verified source on explorers | -| [Foundry: Install and Config](/smart-contracts/dev-environments/foundry/install-and-config/){target=\_blank} | Foundry | Install toolchain and configure networks | -| [Foundry: Compile and Test](/smart-contracts/dev-environments/foundry/compile-and-test/){target=\_blank} | Foundry | Write and run Solidity tests locally | -| [Foundry: Verify a Contract](/smart-contracts/dev-environments/foundry/verify-a-contract/){target=\_blank} | Foundry | Verify deployed bytecode and metadata | -| [Hardhat: Install and Config](/smart-contracts/dev-environments/hardhat/install-and-config/){target=\_blank} | Hardhat | Initialize a project and configure networks | -| [Hardhat: Compile and Test](/smart-contracts/dev-environments/hardhat/compile-and-test/){target=\_blank} | Hardhat | Unit test contracts and run scripts | -| [Hardhat: Verify a Contract](/smart-contracts/dev-environments/hardhat/verify-a-contract/){target=\_blank} | Hardhat | Verify deployments on explorers | - -## Ethereum Developer Resources - -Bridge your Ethereum knowledge with Polkadot Hub specifics: account mapping, fees, JSON‑RPC, and deployment. - -| Ethereum Developer Guides | Description | -|:---------------------------------------------------------------------------------------------------------:|:---------------------------------------------------------------:| -| [Accounts](/smart-contracts/for-eth-devs/accounts/){target=\_blank} | How 20‑byte Ethereum addresses map to 32‑byte Polkadot accounts | -| [Blocks, Transactions, and Fees](/smart-contracts/for-eth-devs/blocks-transactions-fees/){target=\_blank} | Transaction types, fees, and multi‑dimensional metering | -| [Gas Model](/smart-contracts/for-eth-devs/gas-model/){target=\_blank} | Gas vs. weight, proof size, and storage deposits | -| [Contract Deployment](/smart-contracts/for-eth-devs/contract-deployment/){target=\_blank} | Deployment patterns and best practices on Polkadot Hub | -| [JSON‑RPC APIs](/smart-contracts/for-eth-devs/json-rpc-apis/){target=\_blank} | Supported Ethereum JSON‑RPC methods and examples | -| [Migration](/smart-contracts/for-eth-devs/migration/){target=\_blank} | Port existing apps and tooling to Polkadot Hub | -| [Dual VM Stack](/smart-contracts/for-eth-devs/dual-vm-stack/){target=\_blank} | Overview of EVM and native execution on the Hub | - -## Cookbook: Hands‑on Tutorials - -Follow step‑by‑step guides that walk through common tasks and complete dApp examples. - -| Tutorial | Tools | Description | -|:--------------------------------------------------------------------------------------------------------:|:-------------------:|:-----------------------------------------:| -| [Deploy a Basic Contract](/smart-contracts/cookbook/smart-contracts/deploy-basic/remix/){target=\_blank} | Remix | Minimal deployment walkthrough | -| [Deploy an ERC‑20](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/){target=\_blank} | Remix, OpenZeppelin | Create, deploy, and mint a fungible token | -| [Deploy an NFT (ERC‑721)](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/){target=\_blank} | Remix, OpenZeppelin | Build and deploy an NFT collection | -| [Uniswap V2](/smart-contracts/cookbook/eth-dapps/uniswap-v2/){target=\_blank} | Hardhat | Full dApp project: compile, test, deploy | -| [Zero‑to‑Hero dApp](/smart-contracts/cookbook/dapps/zero-to-hero/){target=\_blank} | Multiple | End‑to‑end dApp patterns and practices | - -## Libraries - -Choose the client libraries that fit your stack for connecting wallets and calling contracts. - -| Library | Description | -|:------------------------------------------------------------------:|:-------------------------------------------------------:| -| [Ethers.js](/smart-contracts/libraries/ethers-js/){target=\_blank} | Connect, sign, and interact with contracts using Ethers | -| [viem](/smart-contracts/libraries/viem/){target=\_blank} | Type‑safe EVM interactions and utilities | -| [Wagmi](/smart-contracts/libraries/wagmi/){target=\_blank} | React hooks for wallet connections and contract calls | -| [Web3.js](/smart-contracts/libraries/web3-js/){target=\_blank} | Web3 provider and contract APIs | -| [Web3.py](/smart-contracts/libraries/web3-py/){target=\_blank} | Python toolkit for on‑chain interactions and scripts | - -## Integrations - -Integrate essential services like wallets, indexers, and oracles to round out your dApp. - -| Integration | Description | -|:-------------------------------------------------------------------:|:-----------------------------------------:| -| [Wallets](/smart-contracts/integrations/wallets/){target=\_blank} | Supported wallets and configuration notes | -| [Indexers](/smart-contracts/integrations/indexers/){target=\_blank} | Index and query blockchain data | -| [Oracles](/smart-contracts/integrations/oracles/){target=\_blank} | Bring external data on‑chain | - -## Precompiles - -Discover precompiled system contracts available on the Hub and how to use them. - -| Topic | Description | -|:------------------------------------------------------------------------:|:---------------------------------------------------:| -| [Overview of Precompiles](/smart-contracts/precompiles/){target=\_blank} | What precompiles are available on the Hub | -| [ETH Native](/smart-contracts/precompiles/eth-native/){target=\_blank} | EVM precompiles and interfaces | -| [Staking](/smart-contracts/precompiles/staking/){target=\_blank} | Interact with staking functionality via precompiles | -| [XCM](/smart-contracts/precompiles/xcm/){target=\_blank} | Cross‑chain messaging helpers for contracts | - -From here, follow the quick starts to get connected, iterate locally with your preferred tools, and use the guides, libraries, integrations, and precompiles as you grow into production‑ready dApps. If you get stuck, [open an issue](https://github.com/polkadot-developers/polkadot-docs/issues/new?template=docs-issue.yml){target=\_blank} or reach out in the community channels. - - ---- - -Page Title: Glossary - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-glossary.md -- Canonical (HTML): https://docs.polkadot.com/reference/glossary/ -- Summary: Glossary of terms used within the Polkadot ecosystem, Polkadot SDK, its subsequent libraries, and other relevant Web3 terminology. - -# Glossary - -Key definitions, concepts, and terminology specific to the Polkadot ecosystem are included here. - -Additional glossaries from around the ecosystem you might find helpful: - -- [Polkadot Wiki Glossary](https://wiki.polkadot.com/general/glossary){target=\_blank} -- [Polkadot SDK Glossary](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/glossary/index.html){target=\_blank} - -## Authority - -The role in a blockchain that can participate in consensus mechanisms. - -- **[GRANDPA](#grandpa)**: The authorities vote on chains they consider final. -- **[Blind Assignment of Blockchain Extension](#blind-assignment-of-blockchain-extension-babe) (BABE)**: The authorities are also [block authors](#block-author). - -Authority sets can be used as a basis for consensus mechanisms such as the [Nominated Proof of Stake (NPoS)](#nominated-proof-of-stake-npos) protocol. - -## Authority Round (Aura) - -A deterministic [consensus](#consensus) protocol where block production is limited to a rotating list of [authorities](#authority) that take turns creating blocks. In authority round (Aura) consensus, most online authorities are assumed to be honest. It is often used in combination with [GRANDPA](#grandpa) as a [hybrid consensus](#hybrid-consensus) protocol. - -Learn more by reading the official [Aura consensus algorithm](https://openethereum.github.io/Aura){target=\_blank} wiki article. - -## Blind Assignment of Blockchain Extension (BABE) - -A [block authoring](#block-author) protocol similar to [Aura](#authority-round-aura), except [authorities](#authority) win [slots](#slot) based on a Verifiable Random Function (VRF) instead of the round-robin selection method. The winning authority can select a chain and submit a new block. - -Learn more by reading the official Web3 Foundation [BABE research document](https://research.web3.foundation/Polkadot/protocols/block-production/Babe){target=\_blank}. - -## Block Author - -The node responsible for the creation of a block, also called _block producers_. In a Proof of Work (PoW) blockchain, these nodes are called _miners_. - -## Byzantine Fault Tolerance (BFT) - -The ability of a distributed computer network to remain operational if a certain proportion of its nodes or [authorities](#authority) are defective or behaving maliciously. A distributed network is typically considered Byzantine fault tolerant if it can remain functional, with up to one-third of nodes assumed to be defective, offline, actively malicious, and part of a coordinated attack. - -### Byzantine Failure - -The loss of a network service due to node failures that exceed the proportion of nodes required to reach consensus. - -### Practical Byzantine Fault Tolerance (pBFT) - -An early approach to Byzantine fault tolerance (BFT), practical Byzantine fault tolerance (pBFT) systems tolerate Byzantine behavior from up to one-third of participants. - -The communication overhead for such systems is `O(n²)`, where `n` is the number of nodes (participants) in the system. - -### Preimage - -A preimage is the data that is input into a hash function to calculate a hash. Since a hash function is a [one-way function](https://en.wikipedia.org/wiki/One-way_function){target=\_blank}, the output, the hash, cannot be used to reveal the input, the preimage. - -## Call - -In the context of pallets containing functions to be dispatched to the runtime, `Call` is an enumeration data type that describes the functions that can be dispatched with one variant per pallet. A `Call` represents a [dispatch](#dispatchable) data structure object. - -## Chain Specification - -A chain specification file defines the properties required to run a node in an active or new Polkadot SDK-built network. It often contains the initial genesis runtime code, network properties (such as the network's name), the initial state for some pallets, and the boot node list. The chain specification file makes it easy to use a single Polkadot SDK codebase as the foundation for multiple independently configured chains. - -## Collator - -An [author](#block-author) of a [parachain](#parachain) network. -They aren't [authorities](#authority) in themselves, as they require a [relay chain](#relay-chain) to coordinate [consensus](#consensus). - -More details are found on the [Polkadot Collator Wiki](https://wiki.polkadot.com/learn/learn-collator/){target=\_blank}. - -## Collective - -Most often used to refer to an instance of the Collective pallet on Polkadot SDK-based networks such as [Kusama](#kusama) or [Polkadot](#polkadot) if the Collective pallet is part of the FRAME-based runtime for the network. - -## Consensus - -Consensus is the process blockchain nodes use to agree on a chain's canonical fork. It is composed of [authorship](#block-author), finality, and [fork-choice rule](#fork-choice-rulestrategy). In the Polkadot ecosystem, these three components are usually separate and the term consensus often refers specifically to authorship. - -See also [hybrid consensus](#hybrid-consensus). - -## Consensus Algorithm - -Ensures a set of [actors](#authority)—who don't necessarily trust each other—can reach an agreement about the state as the result of some computation. Most consensus algorithms assume that up to one-third of the actors or nodes can be [Byzantine fault tolerant](#byzantine-fault-tolerance-bft). - -Consensus algorithms are generally concerned with ensuring two properties: - -- **Safety**: Indicating that all honest nodes eventually agreed on the state of the chain. -- **Liveness**: Indicating the ability of the chain to keep progressing. - -## Consensus Engine - -The node subsystem responsible for consensus tasks. - -For detailed information about the consensus strategies of the [Polkadot](#polkadot) network, see the [Polkadot Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} blog series. - -See also [hybrid consensus](#hybrid-consensus). - -## Coretime - -The time allocated for utilizing a core, measured in relay chain blocks. There are two types of coretime: *on-demand* and *bulk*. - -On-demand coretime refers to coretime acquired through bidding in near real-time for the validation of a single parachain block on one of the cores reserved specifically for on-demand orders. They are available as an on-demand coretime pool. Set of cores that are available on-demand. Cores reserved through bulk coretime could also be made available in the on-demand coretime pool, in parts or in entirety. - -Bulk coretime is a fixed duration of continuous coretime represented by an NFT that can be split, shared, or resold. It is managed by the [Broker pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_broker/index.html){target=\_blank}. - -## Development Phrase - -A [mnemonic phrase](https://en.wikipedia.org/wiki/Mnemonic#For_numerical_sequences_and_mathematical_operations){target=\_blank} that is intentionally made public. - -Well-known development accounts, such as Alice, Bob, Charlie, Dave, Eve, and Ferdie, are generated from the same secret phrase: - -``` -bottom drive obey lake curtain smoke basket hold race lonely fit walk -``` - -Many tools in the Polkadot SDK ecosystem, such as [`subkey`](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/bin/utils/subkey){target=\_blank}, allow you to implicitly specify an account using a derivation path such as `//Alice`. - -## Digest - -An extensible field of the [block header](#header) that encodes information needed by several actors in a blockchain network, including: - -- [Light clients](#light-client) for chain synchronization. -- Consensus engines for block verification. -- The runtime itself, in the case of pre-runtime digests. - -## Dispatchable - -Function objects that act as the entry points in FRAME [pallets](#pallet). Internal or external entities can call them to interact with the blockchain’s state. They are a core aspect of the runtime logic, handling [transactions](#transaction) and other state-changing operations. - -## Events - -A means of recording that some particular [state](#state) transition happened. - -In the context of [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities), events are composable data types that each [pallet](#pallet) can individually define. Events in FRAME are implemented as a set of transient storage items inspected immediately after a block has been executed and reset during block initialization. - -## Executor - -A means of executing a function call in a given [runtime](#runtime) with a set of dependencies. -There are two orchestration engines in Polkadot SDK, _WebAssembly_ and _native_. - -- The _native executor_ uses a natively compiled runtime embedded in the node to execute calls. This is a performance optimization available to up-to-date nodes. - -- The _WebAssembly executor_ uses a [Wasm](#webassembly-wasm) binary and a Wasm interpreter to execute calls. The binary is guaranteed to be up-to-date regardless of the version of the blockchain node because it is persisted in the [state](#state) of the Polkadot SDK-based chain. - -## Existential Deposit - -The minimum balance an account is allowed to have in the [Balances pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/index.html){target=\_blank}. Accounts cannot be created with a balance less than the existential deposit amount. - -If an account balance drops below this amount, the Balances pallet uses [a FRAME System API](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.dec_ref){target=\_blank} to drop its references to that account. - -If the Balances pallet reference to an account is dropped, the account can be [reaped](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.allow_death){target=\_blank}. - -## Extrinsic - -A general term for data that originates outside the runtime, is included in a block, and leads to some action. This includes user-initiated transactions and inherent transactions placed into the block by the block builder. - -It is a SCALE-encoded array typically consisting of a version number, signature, and varying data types indicating the resulting runtime function to be called. Extrinsics can take two forms: [inherents](#inherent-transactions) and [transactions](#transaction). - -For more technical details, see the [Polkadot spec](https://spec.polkadot.network/id-extrinsics){target=\_blank}. - -## Fork Choice Rule/Strategy - -A fork choice rule or strategy helps determine which chain is valid when reconciling several network forks. A common fork choice rule is the [longest chain](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/struct.LongestChain.html){target=\_blank}, in which the chain with the most blocks is selected. - -## FRAME (Framework for Runtime Aggregation of Modularized Entities) - -Enables developers to create blockchain [runtime](#runtime) environments from a modular set of components called [pallets](#pallet). It utilizes a set of procedural macros to construct runtimes. - -[Visit the Polkadot SDK docs for more details on FRAME.](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank} - -## Full Node - -A node that prunes historical states, keeping only recently finalized block states to reduce storage needs. Full nodes provide current chain state access and allow direct submission and validation of [extrinsics](#extrinsic), maintaining network decentralization. - -## Genesis Configuration - -A mechanism for specifying the initial state of a blockchain. By convention, this initial state or first block is commonly referred to as the genesis state or genesis block. The genesis configuration for Polkadot SDK-based chains is accomplished by way of a [chain specification](#chain-specification) file. - -## GRANDPA - -A deterministic finality mechanism for blockchains that is implemented in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. - -The [formal specification](https://github.com/w3f/consensus/blob/master/pdf/grandpa-old.pdf){target=\_blank} is maintained by the [Web3 Foundation](https://web3.foundation/){target=\_blank}. - -## Header - -A structure that aggregates the information used to summarize a block. Primarily, it consists of cryptographic information used by [light clients](#light-client) to get minimally secure but very efficient chain synchronization. - -## Hybrid Consensus - -A blockchain consensus protocol that consists of independent or loosely coupled mechanisms for [block production](#block-author) and finality. - -Hybrid consensus allows the chain to grow as fast as probabilistic consensus protocols, such as [Aura](#authority-round-aura), while maintaining the same level of security as deterministic finality consensus protocols, such as [GRANDPA](#grandpa). - -## Inherent Transactions - -A special type of unsigned transaction, referred to as _inherents_, that enables a block authoring node to insert information that doesn't require validation directly into a block. - -Only the block-authoring node that calls the inherent transaction function can insert data into its block. In general, validators assume the data inserted using an inherent transaction is valid and reasonable even if it can't be deterministically verified. - -## JSON-RPC - -A stateless, lightweight remote procedure call protocol encoded in JavaScript Object Notation (JSON). JSON-RPC provides a standard way to call functions on a remote system by using JSON. - -For Polkadot SDK, this protocol is implemented through the [Parity JSON-RPC](https://github.com/paritytech/jsonrpc){target=\_blank} crate. - -## Keystore - -A subsystem for managing keys for the purpose of producing new blocks. - -## Kusama - -[Kusama](https://kusama.network/){target=\_blank} is a Polkadot SDK-based blockchain that implements a design similar to the [Polkadot](#polkadot) network. - -Kusama is a [canary](https://en.wiktionary.org/wiki/canary_in_a_coal_mine){target=\_blank} network and is referred to as [Polkadot's "wild cousin."](https://wiki.polkadot.com/learn/learn-comparisons-kusama/){target=\_blank}. - -As a canary network, Kusama is expected to be more stable than a test network like [Westend](#westend) but less stable than a production network like [Polkadot](#polkadot). Kusama is controlled by its network participants and is intended to be stable enough to encourage meaningful experimentation. - -## libp2p - -A peer-to-peer networking stack that allows the use of many transport mechanisms, including WebSockets (usable in a web browser). - -Polkadot SDK uses the [Rust implementation](https://github.com/libp2p/rust-libp2p){target=\_blank} of the `libp2p` networking stack. - -## Light Client - -A type of blockchain node that doesn't store the [chain state](#state) or produce blocks. - -A light client can verify cryptographic primitives and provides a [remote procedure call (RPC)](https://en.wikipedia.org/wiki/Remote_procedure_call){target=\_blank} server, enabling blockchain users to interact with the network. - -## Metadata - -Data that provides information about one or more aspects of a system. -The metadata that exposes information about a Polkadot SDK blockchain enables you to interact with that system. - -## Nominated Proof of Stake (NPoS) - -A method for determining [validators](#validator) or _[authorities](#authority)_ based on a willingness to commit their stake to the proper functioning of one or more block-producing nodes. - -## Oracle - -An entity that connects a blockchain to a non-blockchain data source. Oracles enable the blockchain to access and act upon information from existing data sources and incorporate data from non-blockchain systems and services. - -## Origin - -A [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitive that identifies the source of a [dispatched](#dispatchable) function call into the [runtime](#runtime). The FRAME System pallet defines three built-in [origins](#origin). As a [pallet](#pallet) developer, you can also define custom origins, such as those defined by the [Collective pallet](https://paritytech.github.io/substrate/master/pallet_collective/enum.RawOrigin.html){target=\_blank}. - -## Pallet - -A module that can be used to extend the capabilities of a [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities)-based [runtime](#runtime). -Pallets bundle domain-specific logic with runtime primitives like [events](#events) and [storage items](#storage-item). - -## Parachain - -A parachain is a blockchain that derives shared infrastructure and security from a _[relay chain](#relay-chain)_. -You can learn more about parachains on the [Polkadot Wiki](https://wiki.polkadot.com/learn/learn-parachains/){target=\_blank}. - -## Paseo - -Paseo TestNet provisions testing on Polkadot's "production" runtime, which means less chance of feature or code mismatch when developing parachain apps. Specifically, after the [Polkadot Technical fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} proposes a runtime upgrade for Polkadot, this TestNet is updated, giving a period where the TestNet will be ahead of Polkadot to allow for testing. - -## Polkadot - -The [Polkadot network](https://polkadot.com/){target=\_blank} is a blockchain that serves as the central hub of a heterogeneous blockchain network. It serves the role of the [relay chain](#relay-chain) and provides shared infrastructure and security to support [parachains](#parachain). - -## Polkadot Cloud - -Polkadot Cloud is a platform for deploying resilient, customizable and scalable Web3 applications through Polkadot's functionality. It encompasses the wider Polkadot network infrastructure and security layer where parachains operate. The platform enables users to launch Ethereum-compatible chains, build specialized blockchains, and flexibly manage computing resources through on-demand or bulk coretime purchases. Initially launched with basic parachain functionality, Polkadot Cloud has evolved to offer enhanced flexibility with features like coretime, elastic scaling, and async backing for improved performance. - -## Polkadot Hub - -Polkadot Hub is a Layer 1 platform that serves as the primary entry point to the Polkadot ecosystem, providing essential functionality without requiring parachain deployment. It offers core services including smart contracts, identity management, staking, governance, and interoperability with other ecosystems, making it simple and fast for both builders and users to get started in Web3. - -## PolkaVM - -PolkaVM is a custom virtual machine optimized for performance, leveraging a RISC-V-based architecture to support Solidity and any language that compiles to RISC-V. It is specifically designed for the Polkadot ecosystem, enabling smart contract deployment and execution. - -## Relay Chain - -Relay chains are blockchains that provide shared infrastructure and security to the [parachains](#parachain) in the network. In addition to providing [consensus](#consensus) capabilities, relay chains allow parachains to communicate and exchange digital assets without needing to trust one another. - -## Rococo - -A [parachain](#parachain) test network for the Polkadot network. The [Rococo](#rococo) network is a Polkadot SDK-based blockchain with an October 14, 2024 deprecation date. Development teams are encouraged to use the Paseo TestNet instead. - -## Runtime - -The runtime represents the [state transition function](#state-transition-function-stf) for a blockchain. In Polkadot SDK, the runtime is stored as a [Wasm](#webassembly-wasm) binary in the chain state. The Runtime is stored under a unique state key and can be modified during the execution of the state transition function. - -## Slot - -A fixed, equal interval of time used by consensus engines such as [Aura](#authority-round-aura) and [BABE](#blind-assignment-of-blockchain-extension-babe). In each slot, a subset of [authorities](#authority) is permitted, or obliged, to [author](#block-author) a block. - -## Sovereign Account - -The unique account identifier for each chain in the relay chain ecosystem. It is often used in cross-consensus (XCM) interactions to sign XCM messages sent to the relay chain or other chains in the ecosystem. - -The sovereign account for each chain is a root-level account that can only be accessed using the Sudo pallet or through governance. The account identifier is calculated by concatenating the Blake2 hash of a specific text string and the registered parachain identifier. - -## SS58 Address Format - -A public key address based on the Bitcoin [`Base-58-check`](https://en.bitcoin.it/wiki/Base58Check_encoding){target=\_blank} encoding. Each Polkadot SDK SS58 address uses a `base-58` encoded value to identify a specific account on a specific Polkadot SDK-based chain - -The [canonical `ss58-registry`](https://github.com/paritytech/ss58-registry){target=\_blank} provides additional details about the address format used by different Polkadot SDK-based chains, including the network prefix and website used for different networks - -## State Transition Function (STF) - -The logic of a blockchain that determines how the state changes when a block is processed. In Polkadot SDK, the state transition function is effectively equivalent to the [runtime](#runtime). - -## Storage Item - -[FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitives that provide type-safe data persistence capabilities to the [runtime](#runtime). -Learn more in the [storage items](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/index.html){target=\_blank} reference document in the Polkadot SDK. - -## Substrate - -A flexible framework for building modular, efficient, and upgradeable blockchains. Substrate is written in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language and is maintained by [Parity Technologies](https://www.parity.io/){target=\_blank}. - -## Transaction - -An [extrinsic](#extrinsic) that includes a signature that can be used to verify the account authorizing it inherently or via [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}. - -## Transaction Era - -A definable period expressed as a range of block numbers during which a transaction can be included in a block. -Transaction eras are used to protect against transaction replay attacks if an account is reaped and its replay-protecting nonce is reset to zero. - -## Trie (Patricia Merkle Tree) - -A data structure used to represent sets of key-value pairs and enables the items in the data set to be stored and retrieved using a cryptographic hash. Because incremental changes to the data set result in a new hash, retrieving data is efficient even if the data set is very large. With this data structure, you can also prove whether the data set includes any particular key-value pair without access to the entire data set. - -In Polkadot SDK-based blockchains, state is stored in a trie data structure that supports the efficient creation of incremental digests. This trie is exposed to the [runtime](#runtime) as [a simple key/value map](#storage-item) where both keys and values can be arbitrary byte arrays. - -## Validator - -A validator is a node that participates in the consensus mechanism of the network. Its roles include block production, transaction validation, network integrity, and security maintenance. - -## WebAssembly (Wasm) - -An execution architecture that allows for the efficient, platform-neutral expression of -deterministic, machine-executable logic. - -[Wasm](https://webassembly.org/){target=\_blank} can be compiled from many languages, including -the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. Polkadot SDK-based chains use a Wasm binary to provide portable [runtimes](#runtime) that can be included as part of the chain's state. - -## Weight - -A convention used in Polkadot SDK-based blockchains to measure and manage the time it takes to validate a block. -Polkadot SDK defines one unit of weight as one picosecond of execution time on reference hardware. - -The maximum block weight should be equivalent to one-third of the target block time with an allocation of one-third each for: - -- Block construction -- Network propagation -- Import and verification - -By defining weights, you can trade-off the number of transactions per second and the hardware required to maintain the target block time appropriate for your use case. Weights are defined in the runtime, meaning you can tune them using runtime updates to keep up with hardware and software improvements. - -## Westend - -Westend is a Parity-maintained, Polkadot SDK-based blockchain that serves as a test network for the [Polkadot](#polkadot) network. - - ---- - -Page Title: Indexers - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-indexers.md -- Canonical (HTML): https://docs.polkadot.com/parachains/integrations/indexers/ -- Summary: Discover blockchain indexers. Enhance data access, enable fast and complex queries, and optimize blockchain data for seamless app performance. - -# Indexers - -## The Challenge of Blockchain Data Access - -Blockchain data is inherently sequential and distributed, with information stored chronologically across numerous blocks. While retrieving data from a single block through JSON-RPC API calls is straightforward, more complex queries that span multiple blocks present significant challenges: - -- Data is scattered and unorganized across the blockchain. -- Retrieving large datasets can take days or weeks to sync. -- Complex operations (like aggregations, averages, or cross-chain queries) require additional processing. -- Direct blockchain queries can impact dApp performance and responsiveness. - -## What is a Blockchain Indexer? - -A blockchain indexer is a specialized infrastructure tool that processes, organizes, and stores blockchain data in an optimized format for efficient querying. Think of it as a search engine for blockchain data that: - -- Continuously monitors the blockchain for new blocks and transactions. -- Processes and categorizes this data according to predefined schemas. -- Stores the processed data in an easily queryable database. -- Provides efficient APIs (typically [GraphQL](https://graphql.org/){target=\_blank}) for data retrieval. - -## Indexer Implementations - -
- -- __Subsquid__ - - --- - - Subsquid is a data network that allows rapid and cost-efficient retrieval of blockchain data from 100+ chains using Subsquid's decentralized data lake and open-source SDK. In simple terms, Subsquid can be considered an ETL (extract, transform, and load) tool with a GraphQL server included. It enables comprehensive filtering, pagination, and even full-text search capabilities. Subsquid has native and full support for EVM and Substrate data, even within the same project. - - [:octicons-arrow-right-24: Reference](https://www.sqd.ai/){target=\_blank} - -- __Subquery__ - - --- - - SubQuery is a fast, flexible, and reliable open-source data decentralised infrastructure network that provides both RPC and indexed data to consumers worldwide. - It provides custom APIs for your web3 project across multiple supported chains. - - [:octicons-arrow-right-24: Reference](https://subquery.network/){target=\_blank} - -
- - ---- - -Page Title: Install Polkadot SDK - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-install-polkadot-sdk.md -- Canonical (HTML): https://docs.polkadot.com/parachains/install-polkadot-sdk/ -- Summary: Install all required Polkadot SDK dependencies, set up the SDK itself, and verify that it runs correctly on your machine. - -# Install Polkadot SDK - -This guide provides step-by-step instructions for installing the Polkadot SDK on macOS, Linux, and Windows. The installation process consists of two main parts: - -- **Installing dependencies**: Setting up Rust, required system packages, and development tools. -- **Building the Polkadot SDK**: Cloning and compiling the Polkadot SDK repository. - -Follow the appropriate section for your operating system to ensure all necessary tools are installed and configured properly. - -## Install Dependencies: macOS - -You can install Rust and set up a Substrate development environment on Apple macOS computers with Intel or Apple M1 processors. - -### Before You Begin {: #before-you-begin-mac-os } - -Before you install Rust and set up your development environment on macOS, verify that your computer meets the following basic requirements: - -- Operating system version is 10.7 Lion or later. -- Processor speed of at least 2 GHz. Note that 3 GHz is recommended. -- Memory of at least 8 GB RAM. Note that 16 GB is recommended. -- Storage of at least 10 GB of available space. -- Broadband Internet connection. - -### Install Homebrew - -In most cases, you should use Homebrew to install and manage packages on macOS computers. If you don't already have Homebrew installed on your local computer, you should download and install it before continuing. - -To install Homebrew: - -1. Open the Terminal application. -2. Download and install Homebrew by running the following command: - - ```bash - /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" - ``` - -3. Verify Homebrew has been successfully installed by running the following command: - - ```bash - brew --version - ``` - - The command displays output similar to the following: - -
- brew --version - Homebrew 4.3.15 -
- -### Support for Apple Silicon - -Protobuf must be installed before the build process can begin. To install it, run the following command: - -```bash -brew install protobuf -``` - -### Install Required Packages and Rust {: #install-required-packages-and-rust-mac-os } - -Because the blockchain requires standard cryptography to support the generation of public/private key pairs and the validation of transaction signatures, you must also have a package that provides cryptography, such as `openssl`. - -To install `openssl` and the Rust toolchain on macOS: - -1. Open the Terminal application. -2. Ensure you have an updated version of Homebrew by running the following command: - - ```bash - brew update - ``` - -3. Install the `openssl` package by running the following command: - - ```bash - brew install openssl - ``` - -4. Download the `rustup` installation program and use it to install Rust by running the following command: - - ```bash - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh - ``` - -5. Follow the prompts displayed to proceed with a default installation. -6. Update your current shell to include Cargo by running the following command: - - ```bash - source ~/.cargo/env - ``` - -7. Configure the Rust toolchain to default to the latest stable version by running the following commands: - - ```bash - rustup default stable - rustup update - rustup target add wasm32-unknown-unknown - rustup component add rust-src - ``` - -8. Install `cmake` using the following command: - - ```bash - brew install cmake - ``` - -9. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). - -## Install Dependencies: Linux - -Rust supports most Linux distributions. Depending on the specific distribution and version of the operating system you use, you might need to add some software dependencies to your environment. In general, your development environment should include a linker or a C-compatible compiler, such as `clang`, and an appropriate integrated development environment (IDE). - -### Before You Begin {: #before-you-begin-linux } - -Check the documentation for your operating system for information about the installed packages and how to download and install any additional packages you might need. For example, if you use Ubuntu, you can use the Ubuntu Advanced Packaging Tool (`apt`) to install the `build-essential` package: - -```bash -sudo apt install build-essential -``` - -At a minimum, you need the following packages before you install Rust: - -```text -clang curl git make -``` - -Because the blockchain requires standard cryptography to support the generation of public/private key pairs and the validation of transaction signatures, you must also have a package that provides cryptography, such as `libssl-dev` or `openssl-devel`. - -### Install Required Packages and Rust {: #install-required-packages-and-rust-linux } - -To install the Rust toolchain on Linux: - -1. Open a terminal shell. -2. Check the packages installed on the local computer by running the appropriate package management command for your Linux distribution. -3. Add any package dependencies you are missing to your local development environment by running the appropriate package management command for your Linux distribution: - - === "Ubuntu" - - ```bash - sudo apt install --assume-yes git clang curl libssl-dev protobuf-compiler - ``` - - === "Debian" - - ```sh - sudo apt install --assume-yes git clang curl libssl-dev llvm libudev-dev make protobuf-compiler - ``` - - === "Arch" - - ```sh - pacman -Syu --needed --noconfirm curl git clang make protobuf - ``` - - === "Fedora" - - ```sh - sudo dnf update - sudo dnf install clang curl git openssl-devel make protobuf-compiler - ``` - - === "OpenSUSE" - - ```sh - sudo zypper install clang curl git openssl-devel llvm-devel libudev-devel make protobuf - ``` - - Remember that different distributions might use different package managers and bundle packages in different ways. For example, depending on your installation selections, Ubuntu Desktop and Ubuntu Server might have different packages and different requirements. However, the packages listed in the command-line examples are applicable to many common Linux distributions, including Debian, Linux Mint, MX Linux, and Elementary OS. - -4. Download the `rustup` installation program and use it to install Rust by running the following command: - - ```bash - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh - ``` - -5. Follow the prompts displayed to proceed with a default installation. -6. Update your current shell to include Cargo by running the following command: - - ```bash - source $HOME/.cargo/env - ``` - -7. Verify your installation by running the following command: - - ```bash - rustc --version - ``` - -8. Configure the Rust toolchain to default to the latest stable version by running the following commands: - - ```bash - rustup default stable - rustup update - rustup target add wasm32-unknown-unknown - rustup component add rust-src - ``` - -9. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). - -## Install Dependencies: Windows (WSL) - -In general, UNIX-based operating systems—like macOS or Linux—provide a better development environment for building Substrate-based blockchains. - -However, suppose your local computer uses Microsoft Windows instead of a UNIX-based operating system. In that case, you can configure it with additional software to make it a suitable development environment for building Substrate-based blockchains. To prepare a development environment on a Microsoft Windows computer, you can use Windows Subsystem for Linux (WSL) to emulate a UNIX operating environment. - -### Before You Begin {: #before-you-begin-windows-wls } - -Before installing on Microsoft Windows, verify the following basic requirements: - -- You have a computer running a supported Microsoft Windows operating system: - - **For Windows desktop**: You must be running Microsoft Windows 10, version 2004 or later, or Microsoft Windows 11 to install WSL. - - **For Windows server**: You must be running Microsoft Windows Server 2019, or later, to install WSL on a server operating system. -- You have a good internet connection and access to a shell terminal on your local computer. - -### Set Up Windows Subsystem for Linux - -WSL enables you to emulate a Linux environment on a computer that uses the Windows operating system. The primary advantage of this approach for Substrate development is that you can use all of the code and command-line examples as described in the Substrate documentation. For example, you can run common commands—such as `ls` and `ps`—unmodified. By using WSL, you can avoid configuring a virtual machine image or a dual-boot operating system. - -To prepare a development environment using WSL: - -1. Check your Windows version and build number to see if WSL is enabled by default. - - If you have Microsoft Windows 10, version 2004 (Build 19041 and higher), or Microsoft Windows 11, WSL is available by default and you can continue to the next step. - - If you have an older version of Microsoft Windows installed, see the [WSL manual installation steps for older versions](https://learn.microsoft.com/en-us/windows/wsl/install-manual){target=\_blank}. If you are installing on an older version of Microsoft Windows, you can download and install WLS 2 if your computer has Windows 10, version 1903 or higher. - -2. Select **Windows PowerShell** or **Command Prompt** from the **Start** menu, right-click, then **Run as administrator**. - -3. In the PowerShell or Command Prompt terminal, run the following command: - - ```bash - wsl --install - ``` - - This command enables the required WSL 2 components that are part of the Windows operating system, downloads the latest Linux kernel, and installs the Ubuntu Linux distribution by default. - - If you want to review the other Linux distributions available, run the following command: - - ```bash - wsl --list --online - ``` - -4. After the distribution is downloaded, close the terminal. - -5. Click the **Start** menu, select **Shut down or sign out**, then click **Restart** to restart the computer. - - Restarting the computer is required to start the installation of the Linux distribution. It can take a few minutes for the installation to complete after you restart. - - For more information about setting up WSL as a development environment, see the [Set up a WSL development environment](https://learn.microsoft.com/en-us/windows/wsl/setup/environment){target=\_blank} docs. - -### Install Required Packages and Rust {: #install-required-packages-and-rust-windows-wls } - -To install the Rust toolchain on WSL: - -1. Click the **Start** menu, then select **Ubuntu**. -2. Type a UNIX user name to create a user account. -3. Type a password for your UNIX user, then retype the password to confirm it. -4. Download the latest updates for the Ubuntu distribution using the Ubuntu Advanced Packaging Tool (`apt`) by running the following command: - - ```bash - sudo apt update - ``` - -5. Add the required packages for the Ubuntu distribution by running the following command: - - ```bash - sudo apt install --assume-yes git clang curl libssl-dev llvm libudev-dev make protobuf-compiler - ``` - -6. Download the `rustup` installation program and use it to install Rust for the Ubuntu distribution by running the following command: - - ```bash - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh - ``` - -7. Follow the prompts displayed to proceed with a default installation. - -8. Update your current shell to include Cargo by running the following command: - - ```bash - source ~/.cargo/env - ``` - -9. Verify your installation by running the following command: - - ```bash - rustc --version - ``` - -10. Configure the Rust toolchain to use the latest stable version as the default toolchain by running the following commands: - - ```bash - rustup default stable - rustup update - rustup target add wasm32-unknown-unknown - rustup component add rust-src - ``` - -11. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). - -## Build the Polkadot SDK - -After installing all dependencies, you can now clone and compile the Polkadot SDK repository to verify your setup. - -### Clone the Polkadot SDK - -1. Clone the Polkadot SDK repository: - - ```bash - git clone https://github.com/paritytech/polkadot-sdk.git - ``` - -2. Navigate into the project directory: - - ```bash - cd polkadot-sdk - ``` - -### Compile the Polkadot SDK - -Compile the entire Polkadot SDK repository to ensure your environment is properly configured: - -```bash -cargo build --release --locked -``` - -!!!note - This initial compilation will take significant time, depending on your machine specifications. It compiles all components of the Polkadot SDK to verify your toolchain is correctly configured. - -### Verify the Build - -Once the build completes successfully, verify the installation by checking the compiled binaries: - -```bash -ls target/release -``` - -You should see several binaries, including: - -- `polkadot`: The Polkadot relay chain node. -- `polkadot-parachain`: The parachain collator node. -- `polkadot-omni-node`:The omni node for running parachains. -- `substrate-node`: The kitchensink node with many pre-configured pallets. - -Verify the Polkadot binary works by checking its version: - -```bash -./target/release/polkadot --version -``` - -This should display version information similar to: - -```bash -polkadot 1.16.0-1234abcd567 -``` - -If you see the version output without errors, your development environment is correctly configured and ready for Polkadot SDK development! - -## Optional: Run the Kitchensink Node - -The Polkadot SDK includes a feature-rich node called "kitchensink" located at `substrate/bin/node`. This node comes pre-configured with many pallets and features from the Polkadot SDK, making it an excellent reference for exploring capabilities and understanding how different components work together. - -!!!note - If you've already compiled the Polkadot SDK in the previous step, the `substrate-node` binary is already built and ready to use. You can skip directly to running the node. - -### Run the Kitchensink Node in Development Mode - -From the `polkadot-sdk` root directory, start the kitchensink node in development mode: - -```bash -./target/release/substrate-node --dev -``` - -The `--dev` flag enables development mode, which: - -- Runs a single-node development chain. -- Produces and finalizes blocks automatically. -- Uses pre-configured development accounts (Alice, Bob, etc.). -- Deletes all data when stopped, ensuring a clean state on restart. - - -You should see log output indicating the node is running and producing blocks, with increasing block numbers after `finalized`. - -### Interact with the Kitchensink Node - -The kitchensink node is accessible at `ws://localhost:9944`. Open [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} in your browser to explore its features and connect to the local node. - -1. Click the network icon in the top left corner. -2. Scroll to **Development** and select **Local Node**. -3. Click **Switch** to connect to your local node. - -![](/images/parachains/install-polkadot-sdk/install-polkadot-sdk-1.webp) - -Once connected, the interface updates its color scheme to indicate a successful connection to the local node. - -![](/images/parachains/install-polkadot-sdk/install-polkadot-sdk-2.webp) - -You can now explore the various pallets and features included in the kitchensink node, making it a valuable reference as you develop your own blockchain applications. - -To stop the node, press `Control-C` in the terminal. - -## Where to Go Next - -
- -- __Get Started with Parachain Development__ - - --- - - Practical examples and tutorials for building and deploying Polkadot parachains, covering everything from launch to customization and cross-chain messaging. - - [:octicons-arrow-right-24: Get Started](/parachains/get-started/) - -
- - ---- - -Page Title: Interoperability - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-interoperability.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/interoperability/ -- Summary: Explore the importance of interoperability in the Polkadot ecosystem, covering XCM, bridges, and cross-chain communication. - -# Interoperability - -## Introduction - -Interoperability lies at the heart of the Polkadot ecosystem, enabling communication and collaboration across a diverse range of blockchains. By bridging the gaps between parachains, relay chains, and even external networks, Polkadot unlocks the potential for truly decentralized applications, efficient resource sharing, and scalable solutions. - -Polkadot’s design ensures that blockchains can transcend their individual limitations by working together as part of a unified system. This cooperative architecture is what sets Polkadot apart in the blockchain landscape. - -## Why Interoperability Matters - -The blockchain ecosystem is inherently fragmented. Different blockchains excel in specialized domains such as finance, gaming, or supply chain management, but these chains function in isolation without interoperability. This lack of connectivity stifles the broader utility of blockchain technology. - -Interoperability solves this problem by enabling blockchains to: - -- **Collaborate across networks**: Chains can interact to share assets, functionality, and data, creating synergies that amplify their individual strengths. -- **Achieve greater scalability**: Specialized chains can offload tasks to others, optimizing performance and resource utilization. -- **Expand use-case potential**: Cross-chain applications can leverage features from multiple blockchains, unlocking novel user experiences and solutions. - -In the Polkadot ecosystem, interoperability transforms a collection of isolated chains into a cohesive, efficient network, pushing the boundaries of what blockchains can achieve together. - -## Key Mechanisms for Interoperability - -At the core of Polkadot's cross-chain collaboration are foundational technologies designed to break down barriers between networks. These mechanisms empower blockchains to communicate, share resources, and operate as a cohesive ecosystem. - -### Cross-Consensus Messaging (XCM): The Backbone of Communication - -Polkadot's Cross-Consensus Messaging (XCM) is the standard framework for interaction between parachains, relay chains, and, eventually, external blockchains. XCM provides a trustless, secure messaging format for exchanging assets, sharing data, and executing cross-chain operations. - -Through XCM, decentralized applications can: - -- Transfer tokens and other assets across chains. -- Coordinate complex workflows that span multiple blockchains. -- Enable seamless user experiences where underlying blockchain differences are invisible. -- XCM exemplifies Polkadot’s commitment to creating a robust and interoperable ecosystem. - -For further information about XCM, check the [Introduction to XCM](/parachains/interoperability/get-started/){target=\_blank} article. - -### Bridges: Connecting External Networks - -While XCM enables interoperability within the Polkadot ecosystem, bridges extend this functionality to external blockchains such as Ethereum and Bitcoin. By connecting these networks, bridges allow Polkadot-based chains to access external liquidity, additional functionalities, and broader user bases. - -With bridges, developers and users gain the ability to: - -- Integrate external assets into Polkadot-based applications. -- Combine the strengths of Polkadot’s scalability with the liquidity of other networks. -- Facilitate accurate multi-chain applications that transcend ecosystem boundaries. - -For more information about bridges in the Polkadot ecosystem, see the [Bridge Hub](/reference/polkadot-hub/bridging/){target=\_blank} guide. - -## The Polkadot Advantage - -Polkadot was purpose-built for interoperability. Unlike networks that add interoperability as an afterthought, Polkadot integrates it as a fundamental design principle. This approach offers several distinct advantages: - -- **Developer empowerment**: Polkadot’s interoperability tools allow developers to build applications that leverage multiple chains’ capabilities without added complexity. -- **Enhanced ecosystem collaboration**: Chains in Polkadot can focus on their unique strengths while contributing to the ecosystem’s overall growth. -- **Future-proofing blockchain**: By enabling seamless communication, Polkadot ensures its ecosystem can adapt to evolving demands and technologies. - -## Looking Ahead - -Polkadot’s vision of interoperability extends beyond technical functionality, representing a shift towards a more collaborative blockchain landscape. By enabling chains to work together, Polkadot fosters innovation, efficiency, and accessibility, paving the way for a decentralized future where blockchains are not isolated competitors but interconnected collaborators. - - ---- - -Page Title: Introduction to XCM - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md -- Canonical (HTML): https://docs.polkadot.com/parachains/interoperability/get-started/ -- Summary: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. - -# Introduction to XCM - -## Introduction - -Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems. - -With XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation. - -## Messaging Format - -XCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics. - -XCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing. - -## The Four Principles of XCM - -XCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems: - -- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes. -- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended. -- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin. -- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems. - -These principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments. - -## The XCM Tech Stack - -![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp) - -The XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels. - -## Core Functionalities of XCM - -XCM enhances cross-consensus communication by introducing several powerful features: - -- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management. -- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification. -- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location. - -The standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications. - -## XCM Example - -The following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA). - -```rust -let message = Xcm(vec![ - WithdrawAsset((Here, amount).into()), - BuyExecution { - fees: (Here, amount).into(), - weight_limit: WeightLimit::Unlimited - }, - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: Junction::AccountId32 { - network: None, - id: BOB.clone().into() - }.into(), - }.into() - } -]); -``` - -The message consists of three instructions described as follows: - -- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register. - - ```rust - WithdrawAsset((Here, amount).into()), - ``` - - - **`Here`**: The native parachain token. - - **`amount`**: The number of tokens that are transferred. - - The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register. - -- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\_blank} of the XCM instructions. - - ```rust - BuyExecution { - fees: (Here, amount).into(), - weight_limit: WeightLimit::Unlimited - }, - ``` - - - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight. - - **`weight_limit`**: Defines the maximum fees that can be used to buy weight. - -- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\_blank}**: Moves the remaining tokens from the holding register to Bob’s account. - - ```rust - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: Junction::AccountId32 { - network: None, - id: BOB.clone().into() - }.into(), - }.into() - } - ``` - - - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited. - -This step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - -## Overview - -XCM revolutionizes cross-chain communication by enabling use cases such as: - -- Token transfers between blockchains. -- Asset locking for cross-chain smart contract interactions. -- Remote execution of functions on other blockchains. - -These functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - - ---- - -Page Title: JSON-RPC APIs - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-json-rpc-apis.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/json-rpc-apis/ -- Summary: JSON-RPC APIs guide for Polkadot Hub, covering supported methods, parameters, and examples for interacting with the chain. - -# JSON-RPC APIs - -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction - -Polkadot Hub provides Ethereum compatibility through its JSON-RPC interface, allowing developers to interact with the chain using familiar Ethereum tooling and methods. This document outlines the supported [Ethereum JSON-RPC methods](https://ethereum.org/developers/docs/apis/json-rpc/#json-rpc-methods){target=\_blank} and provides examples of how to use them. - -This guide uses the Polkadot Hub TestNet endpoint: - -```text -https://testnet-passet-hub-eth-rpc.polkadot.io -``` - -## Available Methods - -### eth_accounts - -Returns a list of addresses owned by the client. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_accounts){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_accounts" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_accounts", - "params":[], - "id":1 -}' -``` - ---- - -### eth_blockNumber - -Returns the number of the most recent block. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_blocknumber){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_blockNumber" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_blockNumber", - "params":[], - "id":1 -}' -``` - ---- - -### eth_call - -Executes a new message call immediately without creating a transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_call){target=\_blank}. - -**Parameters**: - -- **`transaction` ++"object"++**: The transaction call object. - - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - -**Example**: - -```bash title="eth_call" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_call", - "params":[{ - "to": "INSERT_RECIPIENT_ADDRESS", - "data": "INSERT_ENCODED_CALL" - }, "INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_RECIPIENT_ADDRESS`, `INSERT_ENCODED_CALL`, and `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_chainId - -Returns the chain ID used for signing transactions. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_chainid){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_chainId" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_chainId", - "params":[], - "id":1 -}' -``` - ---- - -### eth_estimateGas - -Estimates gas required for a transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_estimategas){target=\_blank}. - -**Parameters**: - -- **`transaction` ++"object"++**: The transaction call object. - - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - -**Example**: - -```bash title="eth_estimateGas" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_estimateGas", - "params":[{ - "to": "INSERT_RECIPIENT_ADDRESS", - "data": "INSERT_ENCODED_FUNCTION_CALL" - }], - "id":1 -}' -``` - -Ensure to replace the `INSERT_RECIPIENT_ADDRESS` and `INSERT_ENCODED_CALL` with the proper values. - ---- - -### eth_gasPrice - -Returns the current gas price in Wei. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gasprice){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_gasPrice" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_gasPrice", - "params":[], - "id":1 -}' -``` - ---- - -### eth_getBalance - -Returns the balance of a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getbalance){target=\_blank}. - -**Parameters**: - -- **`address` ++"string"++**: Address to query balance. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - -**Example**: - -```bash title="eth_getBalance" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getBalance", - "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_getBlockByHash - -Returns information about a block by its hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblockbyhash){target=\_blank}. - -**Parameters**: - -- **`blockHash` ++"string"++**: The hash of the block to retrieve. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`fullTransactions` ++"boolean"++**: If `true`, returns full transaction details; if `false`, returns only transaction hashes. - -**Example**: - -```bash title="eth_getBlockByHash" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getBlockByHash", - "params":["INSERT_BLOCK_HASH", INSERT_BOOLEAN], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_HASH` and `INSERT_BOOLEAN` with the proper values. - ---- - -### eth_getBlockByNumber - -Returns information about a block by its number. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblockbynumber){target=\_blank}. - -**Parameters**: - -- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -- **`fullTransactions` ++"boolean"++**: If `true`, returns full transaction details; if `false`, returns only transaction hashes. - -**Example**: - -```bash title="eth_getBlockByNumber" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getBlockByNumber", - "params":["INSERT_BLOCK_VALUE", INSERT_BOOLEAN], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_VALUE` and `INSERT_BOOLEAN` with the proper values. - ---- - -### eth_getBlockTransactionCountByNumber - -Returns the number of transactions in a block from a block number. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber){target=\_blank}. - -**Parameters**: - -- **`blockValue` ++"string"++**: The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - -**Example**: - -```bash title="eth_getBlockTransactionCountByNumber" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getBlockTransactionCountByNumber", - "params":["INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_getBlockTransactionCountByHash - -Returns the number of transactions in a block from a block hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash){target=\_blank}. - -**Parameters**: - -- **`blockHash` ++"string"++**: The hash of the block to retrieve. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getBlockTransactionCountByHash" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getBlockTransactionCountByHash", - "params":["INSERT_BLOCK_HASH"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_HASH` with the proper values. - ---- - -### eth_getCode - -Returns the code at a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getcode){target=\_blank}. - -**Parameters**: - -- **`address` ++"string"++**: Contract or account address to query code. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). - -**Example**: - -```bash title="eth_getCode" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getCode", - "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_getLogs - -Returns an array of all logs matching a given filter object. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getlogs){target=\_blank}. - -**Parameters**: - -- **`filter` ++"object"++**: The filter object. - - **`fromBlock` ++"string"++**: (Optional) Block number or tag to start from. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - - **`toBlock` ++"string"++**: (Optional) Block number or tag to end at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - - **`address` ++"string" or "array of strings"++**: (Optional) Contract address or a list of addresses from which to get logs. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`topics` ++"array of strings"++**: (Optional) Array of topics for filtering logs. Each topic can be a single [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string or an array of such strings (meaning OR). - - **`blockhash` ++"string"++**: (Optional) Hash of a specific block. Cannot be used with `fromBlock` or `toBlock`. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getLogs" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getLogs", - "params":[{ - "fromBlock": "latest", - "toBlock": "latest" - }], - "id":1 -}' -``` - ---- - -### eth_getStorageAt - -Returns the value from a storage position at a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getstorageat){target=\_blank}. - -**Parameters**: - -- **`address` ++"string"++**: Contract or account address to query code. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`storageKey` ++"string"++**: Position in storage to retrieve data from. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). - -**Example**: - -```bash title="eth_getStorageAt" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getStorageAt", - "params":["INSERT_ADDRESS", "INSERT_STORAGE_KEY", "INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_ADDRESS`, `INSERT_STORAGE_KEY`, and `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_getTransactionCount - -Returns the number of transactions sent from an address (nonce). [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactioncount){target=\_blank}. - -**Parameters**: - -- **`address` ++"string"++**: Address to query balance. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). - -**Example**: - -```bash title="eth_getTransactionCount" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getTransactionCount", - "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_getTransactionByHash - -Returns information about a transaction by its hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyhash){target=\_blank}. - -**Parameters**: - -- **`transactionHash` ++"string"++**: The hash of the transaction. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getTransactionByHash" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getTransactionByHash", - "params":["INSERT_TRANSACTION_HASH"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper values. - ---- - -### eth_getTransactionByBlockNumberAndIndex - -Returns information about a transaction by block number and transaction index. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyblocknumberandindex){target=\_blank}. - -**Parameters**: - -- **`blockValue` ++"string"++**: The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -- **`transactionIndex` ++"string"++**: The index of the transaction in the block. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getTransactionByBlockNumberAndIndex" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getTransactionByBlockNumberAndIndex", - "params":["INSERT_BLOCK_VALUE", "INSERT_TRANSACTION_INDEX"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_VALUE` and `INSERT_TRANSACTION_INDEX` with the proper values. - ---- - -### eth_getTransactionByBlockHashAndIndex - -Returns information about a transaction by block hash and transaction index. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyblockhashandindex){target=\_blank}. - -**Parameters**: - -- **`blockHash` ++"string"++**: The hash of the block. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`transactionIndex` ++"string"++**: The index of the transaction in the block. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getTransactionByBlockHashAndIndex" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getTransactionByBlockHashAndIndex", - "params":["INSERT_BLOCK_HASH", "INSERT_TRANSACTION_INDEX"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_HASH` and `INSERT_TRANSACTION_INDEX` with the proper values. - ---- - -### eth_getTransactionReceipt - -Returns the receipt of a transaction by transaction hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionreceipt){target=\_blank}. - -**Parameters**: - -- **`transactionHash` ++"string"++**: The hash of the transaction. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getTransactionReceipt" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getTransactionReceipt", - "params":["INSERT_TRANSACTION_HASH"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper values. - ---- - -### eth_maxPriorityFeePerGas - -Returns an estimate of the current priority fee per gas, in Wei, to be included in a block. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_maxPriorityFeePerGas" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_maxPriorityFeePerGas", - "params":[], - "id":1 -}' -``` - ---- - -### eth_sendRawTransaction - -Submits a raw transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_sendrawtransaction){target=\_blank}. - -**Parameters**: - -- **`callData` ++"string"++**: Signed transaction data. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_sendRawTransaction" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_sendRawTransaction", - "params":["INSERT_CALL_DATA"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_CALL_DATA` with the proper values. - ---- - -### eth_sendTransaction - -Creates and sends a new transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_sendtransaction){target=\_blank}. - -**Parameters**: - -- **`transaction` ++"object"++**: The transaction object. - - **`from` ++"string"++**: Address sending the transaction. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`to` ++"string"++**: (Optional) Recipient address. No need to provide this value when deploying a contract. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`gas` ++"string"++**: (optional, default: `90000`) gas limit for execution. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`gasPrice` ++"string"++**: (Optional) Gas price per unit. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`value` ++"string"++**: (Optional) Amount of Ether to send. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`data` ++"string"++**: (Optional) Contract bytecode or encoded method call. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`nonce` ++"string"++**: (Optional) Transaction nonce. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_sendTransaction" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_sendTransaction", - "params":[{ - "from": "INSERT_SENDER_ADDRESS", - "to": "INSERT_RECIPIENT_ADDRESS", - "gas": "INSERT_GAS_LIMIT", - "gasPrice": "INSERT_GAS_PRICE", - "value": "INSERT_VALUE", - "input": "INSERT_INPUT_DATA", - "nonce": "INSERT_NONCE" - }], - "id":1 -}' -``` - -Ensure to replace the `INSERT_SENDER_ADDRESS`, `INSERT_RECIPIENT_ADDRESS`, `INSERT_GAS_LIMIT`, `INSERT_GAS_PRICE`, `INSERT_VALUE`, `INSERT_INPUT_DATA`, and `INSERT_NONCE` with the proper values. - ---- - -### eth_syncing - -Returns an object with syncing data or `false` if not syncing. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_syncing){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_syncing" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_syncing", - "params":[], - "id":1 -}' -``` - ---- - -### net_listening - -Returns `true` if the client is currently listening for network connections, otherwise `false`. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#net_listening){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="net_listening" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"net_listening", - "params":[], - "id":1 -}' -``` - ---- - -### net_peerCount - -Returns the number of peers currently connected to the client. - -**Parameters**: - -None. - -**Example**: - -```bash title="net_peerCount" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"net_peerCount", - "params":[], - "id":1 -}' -``` - ---- - -### net_version - -Returns the current network ID as a string. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#net_version){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="net_version" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"net_version", - "params":[], - "id":1 -}' -``` - ---- - -### system_health - -Returns information about the health of the system. - -**Parameters**: - -None. - -**Example**: - -```bash title="system_health" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"system_health", - "params":[], - "id":1 -}' -``` - ---- - -### web3_clientVersion - -Returns the current client version. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#web3_clientversion){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="web3_clientVersion" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"web3_clientVersion", - "params":[], - "id":1 -}' -``` - ---- - -### debug_traceBlockByNumber - -Traces a block's execution by its number and returns a detailed execution trace for each transaction. - -**Parameters**: - -- **`blockValue` ++"string"++**: The block number or tag to trace. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -- **`options` ++"object"++**: (Optional) An object containing tracer options. - - **`tracer` ++"string"++**: The name of the tracer to use (e.g., `"callTracer"`, `"opTracer"`). - - Other tracer-specific options may be supported. - -**Example**: - -```bash title="debug_traceBlockByNumber" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"debug_traceBlockByNumber", - "params":["INSERT_BLOCK_VALUE", {"tracer": "callTracer"}], - "id":1 -}' -``` - -Ensure to replace `INSERT_BLOCK_VALUE` with a proper block number if needed. - ---- - -### debug_traceTransaction - -Traces the execution of a single transaction by its hash and returns a detailed execution trace. - -**Parameters**: - -- **`transactionHash` ++"string"++**: The hash of the transaction to trace. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`options` ++"object"++**: (Optional) An object containing tracer options (e.g., `tracer: "callTracer"`). - -**Example**: - -```bash title="debug_traceTransaction" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"debug_traceTransaction", - "params":["INSERT_TRANSACTION_HASH", {"tracer": "callTracer"}], - "id":1 -}' -``` - -Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper value. - ---- - -### debug_traceCall - -Executes a new message call and returns a detailed execution trace without creating a transaction on the blockchain. - -**Parameters**: - -- **`transaction` ++"object"++**: The transaction call object, similar to `eth_call` parameters. - - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -- **`options` ++"object"++**: (Optional) An object containing tracer options (e.g., `tracer: "callTracer"`). - -**Example**: - -```bash title="debug_traceCall" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"debug_traceCall", - "params":[{ - "from": "INSERT_SENDER_ADDRESS", - "to": "INSERT_RECIPIENT_ADDRESS", - "data": "INSERT_ENCODED_CALL" - }, "INSERT_BLOCK_VALUE", {"tracer": "callTracer"}], - "id":1 -}' -``` - -Ensure to replace the `INSERT_SENDER_ADDRESS`, `INSERT_RECIPIENT_ADDRESS`, `INSERT_ENCODED_CALL`, and `INSERT_BLOCK_VALUE` with the proper value. - ---- - -## Response Format - -All responses follow the standard JSON-RPC 2.0 format: - -```json -{ - "jsonrpc": "2.0", - "id": 1, - "result": ... // The return value varies by method -} -``` - -## Error Handling - -If an error occurs, the response will include an error object: - -```json -{ - "jsonrpc": "2.0", - "id": 1, - "error": { - "code": -32000, - "message": "Error message here" - } -} -``` - - ---- - -Page Title: Networks - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-networks.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/networks/ -- Summary: Explore Polkadot's testing and production networks, including Westend, Kusama, and Paseo, for efficient development, deployment, and testing. - -# Networks - -## Introduction - -The Polkadot ecosystem is built on a robust set of networks designed to enable secure and scalable development. Whether you are testing new features or deploying to live production, Polkadot offers several layers of networks tailored for each stage of the development process. From local environments to experimental networks like Kusama and community-run TestNets such as Paseo, developers can thoroughly test, iterate, and validate their applications. This guide will introduce you to Polkadot's various networks and explain how they fit into the development workflow. - -## Network Overview - -Polkadot's development process is structured to ensure new features and upgrades are rigorously tested before being deployed on live production networks. The progression follows a well-defined path, starting from local environments and advancing through TestNets, ultimately reaching the Polkadot MainNet. The diagram below outlines the typical progression of the Polkadot development cycle: - -``` mermaid -flowchart LR - id1[Local] --> id2[Westend] --> id4[Kusama] --> id5[Polkadot] - id1[Local] --> id3[Paseo] --> id5[Polkadot] -``` - -This flow ensures developers can thoroughly test and iterate without risking real tokens or affecting production networks. Testing tools like [Chopsticks](#chopsticks) and various TestNets make it easier to experiment safely before releasing to production. - -A typical journey through the Polkadot core protocol development process might look like this: - -1. **Local development node**: Development starts in a local environment, where developers can create, test, and iterate on upgrades or new features using a local development node. This stage allows rapid experimentation in an isolated setup without any external dependencies. - -2. **Westend**: After testing locally, upgrades are deployed to [Westend](#westend), Polkadot's primary TestNet. Westend simulates real-world conditions without using real tokens, making it the ideal place for rigorous feature testing before moving on to production networks. - -3. **Kusama**: Once features have passed extensive testing on Westend, they move to Kusama, Polkadot's experimental and fast-moving "canary" network. Kusama operates as a high-fidelity testing ground with actual economic incentives, giving developers insights into how their features will perform in a real-world environment. - -4. **Polkadot**: After passing tests on Westend and Kusama, features are considered ready for deployment to Polkadot, the live production network. - - In addition, parachain developers can leverage local TestNets like [Zombienet](#zombienet) and deploy upgrades on parachain TestNets. - -5. **Paseo**: For parachain and dApp developers, Paseo serves as a community-run TestNet that mirrors Polkadot's runtime. Like Westend for core protocol development, Paseo provides a testing ground for parachain development without affecting live networks. - -!!!note - The Rococo TestNet deprecation date was October 14, 2024. Teams should use Westend for Polkadot protocol and feature testing and Paseo for chain development-related testing. - -## Polkadot Development Networks - -Development and testing are crucial to building robust dApps and parachains and performing network upgrades within the Polkadot ecosystem. To achieve this, developers can leverage various networks and tools that provide a risk-free environment for experimentation and validation before deploying features to live networks. These networks help avoid the costs and risks associated with real tokens, enabling testing for functionalities like governance, cross-chain messaging, and runtime upgrades. - -## Kusama Network - -Kusama is the experimental version of Polkadot, designed for developers who want to move quickly and test their applications in a real-world environment with economic incentives. Kusama serves as a production-grade testing ground where developers can deploy features and upgrades with the pressure of game theory and economics in mind. It mirrors Polkadot but operates as a more flexible space for innovation. - -The native token for Kusama is KSM. For more information about KSM, visit the [Native Assets](https://wiki.polkadot.com/kusama/kusama-getting-started/){target=\_blank} page. - -## Test Networks - -The following test networks provide controlled environments for testing upgrades and new features. TestNet tokens are available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}. - -### Westend - -Westend is Polkadot's primary permanent TestNet. Unlike temporary test networks, Westend is not reset to the genesis block, making it an ongoing environment for testing Polkadot core features. Managed by Parity Technologies, Westend ensures that developers can test features in a real-world simulation without using actual tokens. - -The native token for Westend is WND. More details about WND can be found on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_2){target=\_blank} page. - -### Paseo - -[Paseo](https://github.com/paseo-network){target=\_blank} is a community-managed TestNet designed for parachain and dApp developers. It mirrors Polkadot's runtime and is maintained by Polkadot community members. Paseo provides a dedicated space for parachain developers to test their applications in a Polkadot-like environment without the risks associated with live networks. - -The native token for Paseo is PAS. Additional information on PAS is available on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_1){target=\_blank} page. - -## Local Test Networks - -Local test networks are an essential part of the development cycle for blockchain developers using the Polkadot SDK. They allow for fast, iterative testing in controlled, private environments without connecting to public TestNets. Developers can quickly spin up local instances to experiment, debug, and validate their code before deploying to larger TestNets like Westend or Paseo. Two key tools for local network testing are Zombienet and Chopsticks. - -### Zombienet - -[Zombienet](https://github.com/paritytech/zombienet){target=\_blank} is a flexible testing framework for Polkadot SDK-based blockchains. It enables developers to create and manage ephemeral, short-lived networks. This feature makes Zombienet particularly useful for quick iterations, as it allows you to run multiple local networks concurrently, mimicking different runtime conditions. Whether you're developing a parachain or testing your custom blockchain logic, Zombienet gives you the tools to automate local testing. - -Key features of Zombienet include: - -- Creating dynamic, local networks with different configurations. -- Running parachains and relay chains in a simulated environment. -- Efficient testing of network components like cross-chain messaging and governance. - -Zombienet is ideal for developers looking to test quickly and thoroughly before moving to more resource-intensive public TestNets. - -### Chopsticks - -[Chopsticks](https://github.com/AcalaNetwork/chopsticks){target=\_blank} is a tool designed to create forks of Polkadot SDK-based blockchains, allowing developers to interact with network forks as part of their testing process. This capability makes Chopsticks a powerful option for testing upgrades, runtime changes, or cross-chain applications in a forked network environment. - -Key features of Chopsticks include: - -- Forking live Polkadot SDK-based blockchains for isolated testing. -- Simulating cross-chain messages in a private, controlled setup. -- Debugging network behavior by interacting with the fork in real-time. - -Chopsticks provides a controlled environment for developers to safely explore the effects of runtime changes. It ensures that network behavior is tested and verified before upgrades are deployed to live networks. - - ---- - -Page Title: Node and Runtime - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-node-and-runtime.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/node-and-runtime/ -- Summary: Learn how Polkadot SDK-based nodes function, how the client and runtime are separated, and how they communicate using SCALE-encoded data. - -# Node and Runtime - -## Introduction - -Every blockchain platform relies on a decentralized network of computers, called nodes, that communicate with each other about transactions and blocks. In this context, a node refers to the software running on the connected devices rather than the physical or virtual machines in the network. - -Polkadot SDK-based nodes consist of two main components, each with distinct responsibilities: the client (also called node) and the runtime. - -If the system were a monolithic protocol, any modification would require updating the entire system. Instead, Polkadot achieves true upgradeability by defining an immutable meta-protocol (the client) and a protocol (the runtime) that can be upgraded independently. - -This separation gives the [Polkadot Relay Chain](/polkadot-protocol/architecture/polkadot-chain){target=\_blank} and all connected [parachains](/polkadot-protocol/architecture/parachains){target=\_blank} an evolutionary advantage over other blockchain platforms. - -## Architectural Principles - -The Polkadot SDK-based blockchain architecture is fundamentally built on two distinct yet interconnected components: - -- Client (Meta-protocol): - - Handles the foundational infrastructure of the blockchain. - - Manages runtime execution, networking, consensus, and other off-chain components. - - Provides an immutable base layer that ensures network stability. - - Upgradable only through hard forks. - -- Runtime (Protocol): - - Defines the blockchain's state transition logic. - - Determines the specific rules and behaviors of the blockchain. - - Compiled to WebAssembly (Wasm) for platform-independent execution. - - Capable of being upgraded without network-wide forking. - -### Advantages of this Architecture - -- **Forkless upgrades**: Runtime can be updated without disrupting the entire network. -- **Modularity**: Clear separation allows independent development of client and runtime. -- **Flexibility**: Enables rapid iteration and evolution of blockchain logic. -- **Performance**: WebAssembly compilation provides efficient, cross-platform execution. - -## Node (Client) - -The node, also known as the client, is the core component responsible for executing the Wasm runtime and orchestrating various essential blockchain components. It ensures the correct execution of the state transition function and manages multiple critical subsystems, including: - -- **Wasm execution**: Runs the blockchain runtime, which defines the state transition rules. -- **Database management**: Stores blockchain data. -- **Networking**: Facilitates peer-to-peer communication, block propagation, and transaction gossiping. -- **Transaction pool (Mempool)**: Manages pending transactions before they are included in a block. -- **Consensus mechanism**: Ensures agreement on the blockchain state across nodes. -- **RPC services**: Provides external interfaces for applications and users to interact with the node. - -## Runtime - -The runtime is more than just a set of rules. It's the fundamental logic engine that defines a blockchain's entire behavior. In Polkadot SDK-based blockchains, the runtime represents a complete, self-contained description of the blockchain's state transition function. - -### Characteristics - -The runtime is distinguished by three key characteristics: - -- **Business logic**: Defines the complete application-specific blockchain behavior. -- **WebAssembly compilation**: Ensures platform-independent, secure execution. -- **On-chain storage**: Stored within the blockchain's state, allowing dynamic updates. - -### Key Functions - -The runtime performs several critical functions, such as: - -- Define state transition rules. -- Implement blockchain-specific logic. -- Manage account interactions. -- Control transaction processing. -- Define governance mechanisms. -- Handle custom pallets and modules. - -## Communication Between Node and Runtime - -The client and runtime communicate exclusively using [SCALE-encoded](/polkadot-protocol/parachain-basics/data-encoding){target=\_blank} communication. This ensures efficient and compact data exchange between the two components. - -### Runtime APIs - -The Runtime API consists of well-defined functions and constants a client assumes are implemented in the Runtime Wasm blob. These APIs enable the client to interact with the runtime to execute blockchain operations and retrieve information. The client invokes these APIs to: - -- Build, execute, and finalize blocks. -- Access metadata. -- Access consensus related information. -- Handle transaction execution. - -### Host Functions - -During execution, the runtime can access certain external client functionalities via host functions. The specific functions the client exposes allow the runtime to perform operations outside the WebAssembly domain. Host functions enable the runtime to: - -- Perform cryptographic operations. -- Access the current blockchain state. -- Handle storage modifications. -- Allocate memory. - - ---- - -Page Title: On-Chain Governance Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-governance.md -- Canonical (HTML): https://docs.polkadot.com/reference/governance/ -- Summary: Discover Polkadot’s cutting-edge OpenGov system, enabling transparent, decentralized decision-making through direct democracy and flexible governance tracks. - -# On-Chain Governance - -## Introduction - -Polkadot’s governance system exemplifies decentralized decision-making, empowering its community of stakeholders to shape the network’s future through active participation. The latest evolution, OpenGov, builds on Polkadot’s foundation by providing a more inclusive and efficient governance model. - -This guide will explain the principles and structure of OpenGov and walk you through its key components, such as Origins, Tracks, and Delegation. You will learn about improvements over earlier governance systems, including streamlined voting processes and enhanced stakeholder participation. - -With OpenGov, Polkadot achieves a flexible, scalable, and democratic governance framework that allows multiple proposals to proceed simultaneously, ensuring the network evolves in alignment with its community's needs. - -## Governance Evolution - -Polkadot’s governance journey began with [Governance V1](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#governance-summary){target=\_blank}, a system that proved effective in managing treasury funds and protocol upgrades. However, it faced limitations, such as: - -- Slow voting cycles, causing delays in decision-making. -- Inflexibility in handling multiple referendums, restricting scalability. - -To address these challenges, Polkadot introduced OpenGov, a governance model designed for greater inclusivity, efficiency, and scalability. OpenGov replaces the centralized structures of Governance V1, such as the Council and Technical Committee, with a fully decentralized and dynamic framework. - -For a full comparison of the historic and current governance models, visit the [Gov1 vs. Polkadot OpenGov](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#gov1-vs-polkadot-opengov){target=\_blank} section of the Polkadot Wiki. - -## OpenGov Key Features - -OpenGov transforms Polkadot’s governance into a decentralized, stakeholder-driven model, eliminating centralized decision-making bodies like the Council. Key enhancements include: - -- **Decentralization**: Shifts all decision-making power to the public, ensuring a more democratic process. -- **Enhanced delegation**: Allows users to delegate their votes to trusted experts across specific governance tracks. -- **Simultaneous referendums**: Multiple proposals can progress at once, enabling faster decision-making. -- **Polkadot Technical Fellowship**: A broad, community-driven group replacing the centralized Technical Committee. - -This new system ensures Polkadot governance remains agile and inclusive, even as the ecosystem grows. - -## Origins and Tracks - -In OpenGov, origins and tracks are central to managing proposals and votes. - -- **Origin**: Determines the authority level of a proposal (e.g., Treasury, Root) which decides the track of all referendums from that origin. -- **Track**: Define the procedural flow of a proposal, such as voting duration, approval thresholds, and enactment timelines. - -Developers must be aware that referendums from different origins and tracks will take varying amounts of time to reach approval and enactment. The [Polkadot Technical Fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} has the option to shorten this timeline by whitelisting a proposal and allowing it to be enacted through the [Whitelist Caller](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#whitelisted-caller){target=\_blank} origin. - -Visit [Origins and Tracks Info](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#origins-and-tracks){target=\_blank} for details on current origins and tracks, associated terminology, and parameters. - -## Referendums - -In OpenGov, anyone can submit a referendum, fostering an open and participatory system. The timeline for a referendum depends on the privilege level of the origin with more significant changes offering more time for community voting and participation before enactment. - -The timeline for an individual referendum includes four distinct periods: - -- **Lead-in**: A minimum amount of time to allow for community participation, available room in the origin, and payment of the decision deposit. Voting is open during this period. -- **Decision**: Voting continues. -- **Confirmation**: Referendum must meet [approval and support](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#approval-and-support){target=\_blank} criteria during entire period to avoid rejection. -- **Enactment**: Changes approved by the referendum are executed. - -### Vote on Referendums - -Voters can vote with their tokens on each referendum. Polkadot uses a voluntary token locking mechanism, called conviction voting, as a way for voters to increase their voting power. A token holder signals they have a stronger preference for approving a proposal based upon their willingness to lock up tokens. Longer voluntary token locks are seen as a signal of continual approval and translate to increased voting weight. - -See [Voting on a Referendum](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank} for a deeper look at conviction voting and related token locks. - -### Delegate Voting Power - -The OpenGov system also supports multi-role delegations, allowing token holders to assign their voting power on different tracks to entities with expertise in those areas. - -For example, if a token holder lacks the technical knowledge to evaluate proposals on the [Root track](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#root){target=\_blank}, they can delegate their voting power for that track to an expert they trust to vote in the best interest of the network. This ensures informed decision-making across tracks while maintaining flexibility for token holders. - -Visit [Multirole Delegation](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#multirole-delegation){target=\_blank} for more details on delegating voting power. - -### Cancel a Referendum - -Polkadot OpenGov has two origins for rejecting ongoing referendums: - -- [**Referendum Canceller**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-canceller){target=\_blank}: Cancels an active referendum when non-malicious errors occur and refunds the deposits to the originators. -- [**Referendum Killer**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-killer){target=\_blank}: Used for urgent, malicious cases this origin instantly terminates an active referendum and slashes deposits. - -See [Cancelling, Killing, and Blacklisting](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#cancelling-killing--blacklisting){target=\_blank} for additional information on rejecting referendums. - -## Additional Resources - -- **[Democracy pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/democracy/src){target=\_blank}**: Handles administration of general stakeholder voting. -- **[Gov2: Polkadot’s Next Generation of Decentralised Governance](https://medium.com/polkadot-network/gov2-polkadots-next-generation-of-decentralised-governance-4d9ef657d11b){target=\_blank}**: Medium article by Gavin Wood. -- **[Polkadot Direction](https://matrix.to/#/#Polkadot-Direction:parity.io){target=\_blank}**: Matrix Element client. -- **[Polkassembly](https://polkadot.polkassembly.io/){target=\_blank}**: OpenGov dashboard and UI. -- **[Polkadot.js Apps Governance](https://polkadot.js.org/apps/#/referenda){target=\_blank}**: Overview of active referendums. - - ---- - -Page Title: Oracles - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-oracles.md -- Canonical (HTML): https://docs.polkadot.com/parachains/integrations/oracles/ -- Summary: Learn about blockchain oracles, the essential bridges connecting blockchains with real-world data for decentralized applications in the Polkadot ecosystem. - -# Oracles - -## What is a Blockchain Oracle? - -Oracles enable blockchains to access external data sources. Since blockchains operate as isolated networks, they cannot natively interact with external systems - this limitation is known as the "blockchain oracle problem." Oracles solves this by extracting data from external sources (like APIs, IoT devices, or other blockchains), validating it, and submitting it on-chain. - -While simple oracle implementations may rely on a single trusted provider, more sophisticated solutions use decentralized networks where multiple providers stake assets and reach consensus on data validity. Typical applications include DeFi price feeds, weather data for insurance contracts, and cross-chain asset verification. - -## Oracle Implementations - -
- -- __Acurast__ - - --- - - Acurast is a decentralized, serverless cloud platform that uses a distributed network of mobile devices for oracle services, addressing centralized trust and data ownership issues. In the Polkadot ecosystem, it allows developers to define off-chain data and computation needs, which are processed by these devices acting as decentralized oracle nodes, delivering results to Substrate (Wasm) and EVM environments. - - [:octicons-arrow-right-24: Reference](https://acurast.com/){target=\_blank} - -
- - ---- - -Page Title: Overview of FRAME - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime.md -- Canonical (HTML): https://docs.polkadot.com/parachains/customize-runtime/ -- Summary: Learn how Polkadot SDK’s FRAME framework simplifies blockchain development with modular pallets and support libraries for efficient runtime design. - -# Customize Your Runtime - -## Introduction - -A blockchain runtime is more than just a fixed set of rules—it's a dynamic foundation that you can shape to match your specific needs. With Polkadot SDK's [FRAME (Framework for Runtime Aggregation of Modularized Entities)](/reference/glossary/#frame-framework-for-runtime-aggregation-of-modularized-entities){target=\_blank}, customizing your runtime is straightforward and modular. Instead of building everything from scratch, you combine pre-built pallets with your own custom logic to create a runtime suited to your blockchain's purpose. - -This overview explains how runtime customization works, introduces the building blocks you'll use, and guides you through the key patterns for extending your runtime. - -## Understanding Your Runtime - -The runtime is the core logic of your blockchain—it processes transactions, manages state, and enforces the rules that govern your network. When a transaction arrives at your blockchain, the [`frame_executive`](https://paritytech.github.io/polkadot-sdk/master/frame_executive/index.html){target=\_blank} pallet receives it and routes it to the appropriate pallet for execution. - -Think of your runtime as a collection of specialized modules, each handling a different aspect of your blockchain. Need token balances? Use the Balances pallet. Want governance? Add the Governance pallets. Need something custom? Create your own pallet. By mixing and matching these modules, you build a runtime that's efficient, secure, and tailored to your use case. - -## Runtime Architecture - -The following diagram shows how FRAME components work together to form your runtime: - -![](/images/parachains/customize-runtime/index/frame-overview-01.webp) - -The main components are: - -- **`frame_executive`**: Routes all incoming transactions to the correct pallet for execution. -- **Pallets**: Domain-specific modules that implement your blockchain's features and business logic. -- **`frame_system`**: Provides core runtime primitives and storage. -- **`frame_support`**: Utilities and macros that simplify pallet development. - -## Building Blocks: Pallets - -[Pallets](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/pallet/index.html){target=\_blank} are the fundamental units of runtime customization. Each pallet encapsulates specific functionality and can be independently developed, tested, and integrated. - -A pallet can implement virtually any blockchain feature you need: - -- Expose new transactions that users can submit. -- Store data on-chain. -- Enforce business rules and validation logic. -- Emit events to notify users of state changes. -- Handle errors gracefully. - -### Pre-Built Pallets vs. Custom Pallets - -FRAME provides a comprehensive library of [pre-built pallets](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame){target=\_blank} for common blockchain features, including consensus, staking, balances, governance, and more. These pallets are battle-tested, optimized, and ready to use. - -However, you're not limited to pre-built functionality. When pre-built pallets don't meet your needs, you can create custom pallets with entirely custom logic. The real power of FRAME is the flexibility to use pre-built modules for standard features while building your own for unique requirements. - -### Pallet Structure - -FRAME uses Rust macros extensively, allowing you to focus on your pallet's logic while the framework handles boilerplate and integration code. - -A typical pallet looks like this: - -```rust -pub use pallet::*; - -#[frame_support::pallet] -pub mod pallet { - use frame_support::pallet_prelude::*; - use frame_system::pallet_prelude::*; - - #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] - pub struct Pallet(_); - - #[pallet::config] // snip - #[pallet::event] // snip - #[pallet::error] // snip - #[pallet::storage] // snip - #[pallet::call] // snip -} -``` - -Every pallet can implement these core macros: - -- **`#[frame_support::pallet]`**: Marks your module as a FRAME pallet. -- **`#[pallet::pallet]`**: Designates the struct that holds pallet metadata. -- **`#[pallet::config]`**: Defines configuration and associated types. -- **`#[pallet::event]`**: Defines events emitted by your pallet. -- **`#[pallet::error]`**: Defines error types your pallet can return. -- **`#[pallet::storage]`**: Defines on-chain storage items. -- **`#[pallet::call]`**: Defines dispatchable functions (transactions). - -For a comprehensive reference, see the [`pallet_macros` documentation](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/index.html){target=\_blank}. - -## How Runtime Customization Works - -Customizing your runtime typically follows these patterns: - -**Adding Pre-Built Pallets**: Select pallets from the FRAME library and integrate them into your runtime configuration. This is the fastest way to add functionality. - -**Creating Custom Pallets**: Write custom pallets for features that don't exist in the pre-built library. Custom pallets follow the same structure as pre-built ones and integrate seamlessly. - -**Combining Multiple Pallets**: Layer multiple pallets together to create complex behaviors. Pallets can call each other and share storage when needed. - -**Configuring Pallet Parameters**: Most pallets are configurable—you can adjust their behavior through configuration traits without modifying their code. - -The following diagram illustrates how pallets combine to form a complete runtime: - -![](/images/parachains/customize-runtime/index/frame-overview-02.webp) - -## Starting Templates - -The easiest way to begin customizing your runtime is with a starter template. These templates provide a pre-configured foundation so you can focus on customization rather than setup. - -- **[Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank}**: The recommended choice for most developers, it includes pre-configured pallets for common features (balances, block production, governance), a complete runtime setup, and built-in parachain consensus support. This template offers the best balance of features and learning opportunities. - -- **[Polkadot SDK Minimal Template](https://github.com/paritytech/polkadot-sdk-minimal-template){target=\_blank}**: Provides a bare-bones runtime with only essential components. Choose this if you want maximum flexibility and prefer building from a clean slate. - -- **[Polkadot SDK Solochain Template](https://github.com/paritytech/polkadot-sdk/tree/master/templates/solochain){target=\_blank}**: Designed for building standalone blockchains with moderate features, simple consensus, and several core pallets. Use this if you want a sovereign blockchain independent of a relay chain. - -- **[OpenZeppelin Runtime Templates](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\_blank}**: Provides security-focused configurations following industry best practices. The [generic-template](https://github.com/OpenZeppelin/polkadot-runtime-templates/tree/main/generic-template){target=\_blank} includes curated pallet selections and production-ready defaults—ideal if security is your top priority. - -## Key Customization Scenarios - -This section covers the most common customization patterns you'll encounter: - -- **[Add Existing Pallets to Your Runtime](/parachains/customize-runtime/add-existing-pallets/)**: Integrate pre-built pallets from the FRAME library with minimal configuration. - -- **[Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/)**: Run multiple instances of the same pallet with different configurations—useful for multi-token systems or parallel features. - -- **[Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/)**: Enable smart contract execution on your parachain using Contracts pallets. - -- **[Create Custom Pallets](/parachains/customize-runtime/pallet-development/create-a-pallet/)**: Build entirely custom pallets for features unique to your blockchain. - -- **[Test Your Runtime](/parachains/customize-runtime/pallet-development/pallet-testing/)**: Unit test pallets and mock complete runtimes to ensure everything works correctly. - - ---- - -Page Title: Overview of the Polkadot Relay Chain - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-relay-chain.md -- Canonical (HTML): https://docs.polkadot.com/reference/polkadot-hub/consensus-and-security/relay-chain/ -- Summary: Explore Polkadot's core architecture, including its multi-chain vision, shared security, and the DOT token's governance and staking roles. - -# Overview - -## Introduction - -Polkadot is a next-generation blockchain protocol designed to support a multi-chain future by enabling secure communication and interoperability between different blockchains. Built as a Layer-0 protocol, Polkadot introduces innovations like application-specific Layer-1 chains ([parachains](/polkadot-protocol/architecture/parachains/){targe=\_blank}), shared security through [Nominated Proof of Stake (NPoS)](/reference/glossary/#nominated-proof-of-stake-npos){target=\_blank}, and cross-chain interactions via its native [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank}. - -This guide covers key aspects of Polkadot’s architecture, including its high-level protocol structure, blockspace commoditization, and the role of its native token, DOT, in governance, staking, and resource allocation. - -## Polkadot 1.0 - -Polkadot 1.0 represents the state of Polkadot as of 2023, coinciding with the release of [Polkadot runtime v1.0.0](https://github.com/paritytech/polkadot/releases/tag/v1.0.0){target=\_blank}. This section will focus on Polkadot 1.0, along with philosophical insights into network resilience and blockspace. - -As a Layer-0 blockchain, Polkadot contributes to the multi-chain vision through several key innovations and initiatives, including: - -- **Application-specific Layer-1 blockchains (parachains)**: Polkadot's sharded network allows for parallel transaction processing, with shards that can have unique state transition functions, enabling custom-built L1 chains optimized for specific applications. - -- **Shared security and scalability**: L1 chains connected to Polkadot benefit from its [Nominated Proof of Stake (NPoS)](/reference/polkadot-hub/consensus-and-security/pos-consensus/#nominated-proof-of-stake){target=\_blank} system, providing security out-of-the-box without the need to bootstrap their own. - -- **Secure interoperability**: Polkadot's native interoperability enables seamless data and value exchange between parachains. This interoperability can also be used outside of the ecosystem for bridging with external networks. - -- **Resilient infrastructure**: Decentralized and scalable, Polkadot ensures ongoing support for development and community initiatives via its on-chain [treasury](https://wiki.polkadot.com/learn/learn-polkadot-opengov-treasury/){target=\_blank} and governance. - -- **Rapid L1 development**: The [Polkadot SDK](/reference/parachains/){target=\_blank} allows fast, flexible creation and deployment of Layer-1 chains. - -- **Cultivating the next generation of Web3 developers**: Polkadot supports the growth of Web3 core developers through initiatives such as. - - - [Polkadot Blockchain Academy](https://polkadot.com/blockchain-academy){target=\_blank} - - [EdX courses](https://www.edx.org/school/web3x){target=\_blank} - - Rust and Substrate courses (coming soon) - -### High-Level Architecture - -Polkadot features a chain that serves as the central component of the system. This chain is depicted as a ring encircled by several parachains that are connected to it. - -According to Polkadot's design, any blockchain that can compile to WebAssembly (Wasm) and adheres to the Parachains Protocol becomes a parachain on the Polkadot network. - -Here’s a high-level overview of the Polkadot protocol architecture: - -![](/images/reference/polkadot-hub/consensus-and-security/relay-chain/relay-chain-01.webp){ style="background:white" } - -Parachains propose blocks to Polkadot validators, who check for availability and validity before finalizing them. With the relay chain providing security, collators—full nodes of parachains—can focus on their tasks without needing strong incentives. - -The [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank} allows parachains to exchange messages freely, leveraging the chain's security for trust-free communication. - -In order to interact with chains that want to use their own finalization process (e.g., Bitcoin), Polkadot has [bridges](/reference/parachains/interoperability/#bridges-connecting-external-networks){target=\_blank} that offer two-way compatibility, meaning that transactions can be made between different parachains. - -### Polkadot's Additional Functionalities - -Historically, obtaining core slots on Polkadot chain relied upon crowdloans and auctions. Chain cores were leased through auctions for three-month periods, up to a maximum of two years. Crowdloans enabled users to securely lend funds to teams for lease deposits in exchange for pre-sale tokens, which is the only way to access slots on Polkadot 1.0. Auctions are now deprecated in favor of [coretime](/polkadot-protocol/architecture/system-chains/coretime/){target=\_blank}. - -Additionally, the chain handles [staking](https://wiki.polkadot.com/learn/learn-staking/){target=\_blank}, [accounts](/reference/parachains/accounts/){target=\_blank}, balances, and [governance](/reference/governance/){target=\_blank}. - -#### Agile Coretime - -The new and more efficient way of obtaining core on Polkadot is to go through the process of purchasing coretime. - -[Agile coretime](/reference/polkadot-hub/consensus-and-security/agile-coretime/){target=\_blank} improves the efficient use of Polkadot's network resources and offers economic flexibility for developers, extending Polkadot's capabilities far beyond the original vision outlined in the [whitepaper](https://polkadot.com/papers/Polkadot-whitepaper.pdf){target=\_blank}. - -It enables parachains to purchase monthly "bulk" allocations of coretime (the time allocated for utilizing a core, measured in Polkadot relay chain blocks), ensuring heavy-duty parachains that can author a block every six seconds with [Asynchronous Backing](https://wiki.polkadot.com/learn/learn-async-backing/#asynchronous-backing){target=\_blank} can reliably renew their coretime each month. Although six-second block times are now the default, parachains have the option of producing blocks less frequently. - -Renewal orders are prioritized over new orders, offering stability against price fluctuations and helping parachains budget more effectively for project costs. - -### Polkadot's Resilience - -Decentralization is a vital component of blockchain networks, but it comes with trade-offs: - -- An overly decentralized network may face challenges in reaching consensus and require significant energy to operate. -- Also, a network that achieves consensus quickly risks centralization, making it easier to manipulate or attack. - -A network should be decentralized enough to prevent manipulative or malicious influence. In this sense, decentralization is a tool for achieving resilience. - -Polkadot 1.0 currently achieves resilience through several strategies: - -- **Nominated Proof of Stake (NPoS)**: Ensures that the stake per validator is maximized and evenly distributed among validators. - -- **Decentralized nodes**: Designed to encourage operators to join the network. This program aims to expand and diversify the validators in the ecosystem who aim to become independent of the program during their term. Feel free to explore more about the program on the official [Decentralized Nodes](https://nodes.web3.foundation/){target=\_blank} page. - -- **On-chain treasury and governance**: Known as [OpenGov](/reference/governance/){target=\_blank}, this system allows every decision to be made through public referenda, enabling any token holder to cast a vote. - -### Polkadot's Blockspace - -Polkadot 1.0’s design allows for the commoditization of blockspace. - -Blockspace is a blockchain's capacity to finalize and commit operations, encompassing its security, computing, and storage capabilities. Its characteristics can vary across different blockchains, affecting security, flexibility, and availability. - -- **Security**: Measures the robustness of blockspace in Proof of Stake (PoS) networks linked to the stake locked on validator nodes, the variance in stake among validators, and the total number of validators. It also considers social centralization (how many validators are owned by single operators) and physical centralization (how many validators run on the same service provider). - -- **Flexibility**: Reflects the functionalities and types of data that can be stored, with high-quality data essential to avoid bottlenecks in critical processes. - -- **Availability**: Indicates how easily users can access blockspace. It should be easily accessible, allowing diverse business models to thrive, ideally regulated by a marketplace based on demand and supplemented by options for "second-hand" blockspace. - -Polkadot is built on core blockspace principles, but there's room for improvement. Tasks like balance transfers, staking, and governance are managed on the relay chain. - -Delegating these responsibilities to [system chains](/polkadot-protocol/architecture/system-chains/){target=\_blank} could enhance flexibility and allow the relay chain to concentrate on providing shared security and interoperability. - -For more information about blockspace, watch [Robert Habermeier’s interview](https://www.youtube.com/watch?v=e1vISppPwe4){target=\_blank} or read his [technical blog post](https://www.rob.tech/blog/polkadot-blockspace-over-blockchains/){target=\_blank}. - -## DOT Token - -DOT is the native token of the Polkadot network, much like BTC for Bitcoin and Ether for the Ethereum blockchain. DOT has 10 decimals, uses the Planck base unit, and has a balance type of `u128`. The same is true for Kusama's KSM token with the exception of having 12 decimals. - -### Redenomination of DOT - -Polkadot conducted a community poll, which ended on 27 July 2020 at block 888,888, to decide whether to redenominate the DOT token. The stakeholders chose to redenominate the token, changing the value of 1 DOT from 1e12 plancks to 1e10 plancks. - -Importantly, this did not affect the network's total number of base units (plancks); it only affects how a single DOT is represented. The redenomination became effective 72 hours after transfers were enabled, occurring at block 1,248,328 on 21 August 2020 around 16:50 UTC. - -### The Planck Unit - -The smallest unit of account balance on Polkadot SDK-based blockchains (such as Polkadot and Kusama) is called _Planck_, named after the Planck length, the smallest measurable distance in the physical universe. - -Similar to how BTC's smallest unit is the Satoshi and ETH's is the Wei, Polkadot's native token DOT equals 1e10 Planck, while Kusama's native token KSM equals 1e12 Planck. - -### Uses for DOT - -DOT serves three primary functions within the Polkadot network: - -- **Governance**: It is used to participate in the governance of the network. -- **Staking**: DOT is staked to support the network's operation and security. -- **Buying coretime**: Used to purchase coretime in-bulk or on-demand and access the chain to benefit from Polkadot's security and interoperability. - -Additionally, DOT can serve as a transferable token. For example, DOT, held in the treasury, can be allocated to teams developing projects that benefit the Polkadot ecosystem. - -## JAM and the Road Ahead - -The Join-Accumulate Machine (JAM) represents a transformative redesign of Polkadot's core architecture, envisioned as the successor to the current relay chain. Unlike traditional blockchain architectures, JAM introduces a unique computational model that processes work through two primary functions: - -- **Join**: Handles data integration. -- **Accumulate**: Folds computations into the chain's state. - -JAM removes many of the opinions and constraints of the current relay chain while maintaining its core security properties. Expected improvements include: - -- **Permissionless code execution**: JAM is designed to be more generic and flexible, allowing for permissionless code execution through services that can be deployed without governance approval. -- **More effective block time utilization**: JAM's efficient pipeline processing model places the prior state root in block headers instead of the posterior state root, enabling more effective utilization of block time for computations. - -This architectural evolution promises to enhance Polkadot's scalability and flexibility while maintaining robust security guarantees. JAM is planned to be rolled out to Polkadot as a single, complete upgrade rather than a stream of smaller updates. This approach seeks to minimize the developer overhead required to address any breaking changes. - - ---- - -Page Title: Parachains Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/ -- Summary: Learn about parachains, specialized blockchains on Polkadot that gain shared security and interoperability. Discover how they work and the tools to build them. - -# Parachains Overview - -## Introduction - -A parachain is a specialized blockchain that connects to the Polkadot relay chain, benefiting from shared security, interoperability, and scalability. Parachains are built using the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}, a powerful toolkit written in Rust that provides everything needed to create custom blockchain logic while integrating seamlessly with the Polkadot network. - -Unlike standalone blockchains that must bootstrap their own validator sets and security, parachains leverage Polkadot's pooled security model. This allows parachain developers to focus on their application-specific functionality rather than consensus and security infrastructure. Parachains can communicate with each other through Cross-Consensus Messaging (XCM), enabling seamless interoperability across the Polkadot ecosystem. - -Key capabilities that parachains provide include: - -- **Shared security**: Inherit security from Polkadot's validator set without maintaining your own. -- **Interoperability**: Communicate trustlessly with other parachains via XCM. -- **Scalability**: Process transactions in parallel with other parachains. -- **Customization**: Build application-specific logic tailored to your use case. -- **Upgradeability**: Upgrade runtime logic without hard forks. - -## Polkadot SDK: Parachain Architecture - -Building a parachain involves understanding and utilizing several key components of the Polkadot SDK: - -![](/images/reference/parachains/index/overview-01.webp) - -- **[Substrate](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/substrate/index.html){target=\_blank}**: The foundation providing core blockchain primitives and libraries. -- **[FRAME](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank}**: A modular framework for building your parachain's runtime logic. -- **[Cumulus](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/cumulus/index.html){target=\_blank}**: Essential libraries and pallets that enable parachain functionality. -- **[XCM (Cross Consensus Messaging)](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/xcm/index.html){target=\_blank}**: The messaging format for communicating with other parachains and the relay chain. -- **[Polkadot](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/polkadot/index.html){target=\_blank}**: The relay chain that provides security and coordination. - -### Substrate: The Foundation - -Substrate provides the core infrastructure that every parachain is built upon. It handles the low-level blockchain functionality, allowing you to focus on your application's unique features. Substrate includes implementations for networking, database management, consensus participation, and the execution environment for your runtime. - -Every Polkadot SDK node consists of two main components: - -- **Client (Host)**: Handles infrastructure services. - - - Native binary that runs on validator and collator nodes. - - Executes the Wasm-compiled runtime. - - Manages networking, database, mempool, and block production. - - Interfaces with the relay chain for validation. - -- **Runtime (State Transition Function)**: Contains your business logic. - - - Defines how your Polkadot SDK node processes transactions. - - Compiled to [Wasm](https://webassembly.org/){target=\_blank} for deterministic execution. - - Stored on-chain and upgradeable via governance. - -```mermaid -%%{init: {'flowchart': {'padding': 5, 'nodeSpacing': 50, 'rankSpacing': 10}}}%% -graph TB - classDef title font-size:20px,font-weight:bold,stroke-width:0px - classDef clientStyle font-size:16px,font-weight:bold - classDef clientSubNodeStyle margin-top:10px - classDef runtimeCallExecutorStyle padding-top:10px - - subgraph sg1[Parachain
Node] - direction TB - - I[RuntimeCall Executor] - B[Wasm Runtime - STF] - - subgraph sg2[Client] - direction TB - C[Network and Blockchain
Infrastructure Services
+ Relay Chain Interface] - end - - I --> B - end - - class sg1 title - class sg2 clientStyle - class C clientSubNodeStyle - class I runtimeCallExecutorStyle - -``` - -### FRAME: Building Blocks for Your Runtime - -FRAME provides modular components called [pallets](/reference/glossary#pallet){target=\_blank} that you can compose to build your parachain's runtime. Each pallet provides specific functionality that you can customize and configure for your needs. This modular approach allows you to quickly assemble complex functionality without writing everything from scratch. - -```mermaid -graph LR - subgraph SP["Parachain Runtime"] - direction LR - Timestamp ~~~ Aura ~~~ ParachainSystem - Balances ~~~ TransactionPayment ~~~ Sudo - subgraph Timestamp["Timestamp"] - SS1[Custom Config] - end - subgraph Aura["Aura"] - SS2[Custom Config] - end - subgraph ParachainSystem["Parachain System"] - SS3[Custom Config] - end - subgraph Balances["Balances"] - SS4[Custom Config] - end - subgraph TransactionPayment["Transaction Payment"] - SS5[Custom Config] - end - subgraph Sudo["Sudo"] - SS6[Custom Config] - end - style Timestamp stroke:#FF69B4 - style Aura stroke:#FF69B4 - style ParachainSystem stroke:#FF69B4 - style Balances stroke:#FF69B4 - style TransactionPayment stroke:#FF69B4 - style Sudo stroke:#FF69B4 - style SS1 stroke-dasharray: 5 - style SS2 stroke-dasharray: 5 - style SS3 stroke-dasharray: 5 - style SS4 stroke-dasharray: 5 - style SS5 stroke-dasharray: 5 - style SS6 stroke-dasharray: 5 - - end - subgraph AP["Available FRAME Pallets"] - direction LR - A1[Aura]~~~A2[Parachain
System]~~~A3[Transaction
Payment]~~~A4[Sudo] - B1[Identity]~~~B2[Balances]~~~B3[Assets]~~~B4[EVM] - C1[Timestamp]~~~C2[Staking]~~~C3[Contracts]~~~C4[and more...] - end - AP --> SP -``` - -### Cumulus: Parachain-Specific Functionality - -Cumulus is what transforms a Polkadot SDK-based runtime into a parachain-capable runtime. It provides the essential components for communicating with the relay chain, participating in Polkadot's consensus, and handling parachain-specific operations like block validation and collation. - -Key Cumulus components include: - -- **Parachain system pallet**: Core parachain functionality and relay chain communication. -- **Collator consensus**: Block production logic for parachain collators. -- **Relay chain interface**: APIs for interacting with the Polkadot relay chain. -- **Validation data**: Handling proof-of-validity data required by relay chain validators. - -## Where to Go Next - -Building a parachain requires understanding the relationship between your chain and the Polkadot relay chain. The Polkadot SDK provides all the tools needed to design custom runtime logic, enable cross-chain communication, and deploy your parachain to production. - -The following sections provide detailed guidance on each aspect of parachain development, from initial design through deployment and ongoing maintenance. - -
- -- Guide __Launch a Simple Parachain__ - - --- - - Walk through the complete parachain launch flow: from setup and deployment to obtaining coretime. - - [:octicons-arrow-right-24: Deploy](/parachains/launch-a-parachain/set-up-the-parachain-template/) - - -- Guide __Customize Your Runtime__ - - --- - - Design your parachain's runtime logic and choose appropriate pallets for your use case. - - [:octicons-arrow-right-24: Get Started](/parachains/customize-runtime/) - -- Guide __Interoperability__ - - --- + Ensure to replace `"INSERT_LOCAL_PRIVATE_KEY"` with a private key available in the local environment (you can get them from this [file](https://github.com/paritytech/hardhat-polkadot/blob/main/packages/hardhat-polkadot-node/src/constants.ts#L22){target=\_blank}). And `"INSERT_AH_PRIVATE_KEY"` with the account's private key you want to use to deploy the contracts. You can get this by exporting the private key from your wallet (e.g., MetaMask). - Implement XCM for trustless cross-chain communication with other parachains. + !!!warning + Keep your private key safe, and never share it with anyone. If it is compromised, your funds can be stolen. - [:octicons-arrow-right-24: Learn More](/parachains/interoperability/get-started/) +5. Compile the contracts: -- Guide __Runtime Upgrades__ + ```bash + npx hardhat compile + ``` - --- +If the compilation is successful, you should see the following output: - Upgrade your parachain's runtime without hard forks using forkless upgrade mechanisms. +
+ npx hardhat compile + Compiling 12 Solidity files + Successfully compiled 12 Solidity files +
- [:octicons-arrow-right-24: Maintain](/parachains/runtime-maintenance/runtime-upgrades/) +After running the above command, you should see the compiled contracts in the `artifacts-pvm` directory. This directory contains the ABI and bytecode of your contracts. -
+## Understanding Uniswap V2 Architecture +Before interacting with the contracts, it's essential to understand the core architecture that powers Uniswap V2. This model forms the basis of nearly every modern DEX implementation and operates under automated market making, token pair liquidity pools, and deterministic pricing principles. ---- +At the heart of Uniswap V2 lies a simple but powerful system composed of two major smart contracts: -Page Title: Polkadart +- **Factory contract**: The factory acts as a registry and creator of new trading pairs. When two ERC-20 tokens are to be traded, the Factory contract is responsible for generating a new Pair contract that will manage that specific token pair’s liquidity pool. It keeps track of all deployed pairs and ensures uniqueness—no duplicate pools can exist for the same token combination. +- **Pair contract**: Each pair contract is a decentralized liquidity pool that holds reserves of two ERC-20 tokens. These contracts implement the core logic of the AMM, maintaining a constant product invariant (x \* y = k) to facilitate swaps and price determination. Users can contribute tokens to these pools in return for LP (liquidity provider) tokens, which represent their proportional share of the reserves. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-polkadart.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/polkadart/ -- Summary: Polkadart is a type-safe, native Dart, SDK for Polkadot and any compatible Polkadot-SDK blockchain network. +This minimal architecture enables Uniswap to be highly modular, trustless, and extensible. By distributing responsibilities across these components, developers, and users can engage with the protocol in a composable and predictable manner, making it an ideal foundation for DEX functionality across ecosystems, including Polkadot Hub. -# Polkadart +The project scaffolding is as follows: -Polkadart is the most comprehensive Dart/Flutter SDK for interacting with Polkadot, Substrate, and other compatible blockchain networks. Designed with a Dart-first approach and type-safe APIs, it provides everything developers need to build powerful decentralized applications. +```bash +uniswap-V2-polkadot +├── bin/ +├── contracts/ +│ ├── interfaces/ +│ │ ├── IERC20.sol +│ │ ├── IUniswapV2Callee.sol +│ │ ├── IUniswapV2ERC20.sol +│ │ ├── IUniswapV2Factory.sol +│ │ └── IUniswapV2Pair.sol +│ ├── libraries/ +│ │ ├── Math.sol +│ │ ├── SafeMath.sol +│ │ └── UQ112x112.sol +│ ├── test/ +│ │ └── ERC20.sol +│ ├── UniswapV2ERC20.sol +│ ├── UniswapV2Factory.sol +│ └── UniswapV2Pair.sol +├── ignition/ +├── scripts/ +│ └── deploy.js +├── node_modules/ +├── test/ +│ ├── shared/ +│ │ ├── fixtures.js +│ │ └── utilities.js +│ ├── UniswapV2ERC20.js +│ ├── UniswapV2Factory.js +│ └── UniswapV2Pair.js +├── .env.example +├── .gitignore +├── hardhat.config.js +├── package.json +└── README.md +``` -This page will outline some of the core components of Polkadart. For more details, refer to the [official documentation](https://polkadart.dev){target=\_blank}. +## Test the Contracts -## Installation +You can run the provided test suite to ensure the contracts are working as expected. The tests cover various scenarios, including creating pairs, adding liquidity, and executing swaps. -Add Polkadart to your `pubspec.yaml`: +To test it locally, you can run the following commands: -=== "All packages" +1. Spawn a local node for testing: ```bash - dart pub add polkadart polkadart_cli polkadart_keyring polkadart_scale_codec secp256k1_ecdsa sr25519 ss58 substrate_bip39 substrate_metadata + npx hardhat node ``` -=== "Core only" + This command will spawn a local Substrate node along with the ETH-RPC adapter. The node will be available at `ws://127.0.0.1:8000` and the ETH-RPC adapter at `http://localhost:8545`. + +2. In a new terminal, run the tests: ```bash - dart pub add polkadart polkadart_cli polkadart_keyring + npx hardhat test --network localNode ``` -For type-safe API generation, add the following to your `pubspec.yaml`: - -{% raw %} -```yaml title="pubspec.yaml" -polkadart: - output_dir: lib/generated - chains: - polkadot: wss://rpc.polkadot.io - kusama: wss://kusama-rpc.polkadot.io - custom: wss://your-node.example.com -``` -{% endraw %} +The result should look like this: -## Get Started +
+ npx hardhat test --network localNode + Compiling 12 Solidity files + Successfully compiled 12 Solidity files + + UniswapV2ERC20 + ✔ name, symbol, decimals, totalSupply, balanceOf, DOMAIN_SEPARATOR, PERMIT_TYPEHASH (44ms) + ✔ approve (5128ms) + ✔ transfer (5133ms) + ✔ transfer:fail + ✔ transferFrom (6270ms) + ✔ transferFrom:max (6306ms) + + UniswapV2Factory + ✔ feeTo, feeToSetter, allPairsLength + ✔ createPair (176ms) + ✔ createPair:reverse (1224ms) + ✔ setFeeTo (1138ms) + ✔ setFeeToSetter (1125ms) + + UniswapV2Pair + ✔ mint (11425ms) + ✔ getInputPrice:0 (12590ms) + ✔ getInputPrice:1 (17600ms) + ✔ getInputPrice:2 (17618ms) + ✔ getInputPrice:3 (17704ms) + ✔ getInputPrice:4 (17649ms) + ✔ getInputPrice:5 (17594ms) + ✔ getInputPrice:6 (13643ms) + ✔ optimistic:0 (17647ms) + ✔ optimistic:1 (17946ms) + ✔ optimistic:2 (17657ms) + ✔ optimistic:3 (21625ms) + ✔ swap:token0 (12665ms) + ✔ swap:token1 (17631ms) + ✔ burn (17690ms) + ✔ feeTo:off (23900ms) + ✔ feeTo:on (24991ms) + + 28 passing (12m) +
-### Type Generation +## Deploy the Contracts -Polkadart provides a CLI tool to generate type definitions from any Polkadot-SDK compatible blockchain network. This allows you to build type-safe Dart applications without dealing with the low-level details of the blockchain. +After successfully testing the contracts, you can deploy them to the local node or Polkadot Hub. The deployment script is located in the `scripts` directory and is named `deploy.js`. This script deploys the `Factory` and `Pair` contracts to the network. -### Run Generator +To deploy the contracts, run the following command: ```bash -dart run polkadart_cli:generate -v -``` - -### Use Generated Types - -```dart -import 'package:your_app/generated/polkadot/polkadot.dart'; -import 'package:polkadart/polkadart.dart'; -import 'package:ss58/ss58.dart'; - -final provider = Provider.fromUri(Uri.parse('wss://rpc.polkadot.io')); -final polkadot = Polkadot(provider); - -// Account from SS58 address -final account = Address.decode('19t9Q2ay58hMDaeg6eeBhqmHsRnc2jDMV3cYYw9zbc59HLj'); - -// Retrieve Account Balance -final accountInfo = await polkadot.query.system.account(account.pubkey); -print('Balance: ${accountInfo.data.free}') +npx hardhat run scripts/deploy.js --network localNode ``` -### Creating an API Instance - -An API instance is required to interact with the blockchain. Polkadart provides a `Provider` class that allows you to connect to any network. - -```dart -import 'package:demo/generated/polkadot/polkadot.dart'; -import 'package:polkadart/provider.dart'; +This command deploys the contracts to your local blockchain for development and testing. If you want to deploy to Polkadot Hub, you can use the following command: -Future main(List arguments) async { - final provider = Provider.fromUri(Uri.parse('wss://rpc.polkadot.io')); - final polkadot = Polkadot(provider); -} +```bash +npx hardhat run scripts/deploy.js --network passetHub ``` -### Reading Chain Data - -Besides querying the data using the `query` from the generated API, you can also use the State API for querying storage data, metadata, runtime information, and other chain information. - -```dart -final stateApi = StateApi(provider); - -// Get current runtime version -final runtimeVersion = await stateApi.getRuntimeVersion(); -print(runtimeVersion.toJson()); +The command above deploys to the actual Polkadot TestNet. It requires PAS test tokens, persists on the network, and operates under real network conditions. -// Get metadata -final metadata = await stateApi.getMetadata(); -print('Metadata version: ${metadata.version}'); -``` +The deployment script will output the addresses of the deployed contracts. Save these addresses, as you will need them to interact with the contracts. For example, the output should look like this: -### Subscribe to New Blocks +
+ npx hardhat run scripts/deploy.js --network localNode + Successfully compiled 12 Solidity files + Deploying contracts using 0xf24FF3a9CF04c71Dbc94D0b566f7A27B94566cac + Deploying UniswapV2ERC20... + ETH deployed to : 0x7acc1aC65892CF3547b1b0590066FB93199b430D + Deploying UniswapV2Factory... + Factory deployed to : 0x85b108660f47caDfAB9e0503104C08C1c96e0DA9 + Deploying UniswapV2Pair with JsonRpcProvider workaround... + Pair deployed to : 0xF0e46847c8bFD122C4b5EEE1D4494FF7C5FC5104 +
-You can subscribe to new blocks on the blockchain using the `subscribe` method. +## Conclusion -```dart -final subscription = await provider.subscribe('chain_subscribeNewHeads', []); +This tutorial guided you through deploying Uniswap V2 contracts to Polkadot Hub. This implementation brings the powerful AMM architecture to the Polkadot ecosystem, laying the foundation for the decentralized trading of ERC-20 token pairs. -subscription.stream.forEach((response) { - print('New head: ${response.result}'); -}); -``` +By following this guide, you've gained practical experience with: -### Send a Transaction - -Perhaps the most common operation done in any blockchain is transferring funds. Here you can see how that can be done using Polkadart: - -```dart -final wallet = await KeyPair.sr25519.fromUri("//Alice"); -print('Alice\' wallet: ${wallet.address}'); - -// Get information necessary to build a proper extrinsic -final runtimeVersion = await polkadot.rpc.state.getRuntimeVersion(); -final currentBlockNumber = (await polkadot.query.system.number()) - 1; -final currentBlockHash = await polkadot.query.system.blockHash(currentBlockNumber); -final genesisHash = await polkadot.query.system.blockHash(0); -final nonce = await polkadot.rpc.system.accountNextIndex(wallet.address); - -// Make the encoded call -final multiAddress = $MultiAddress().id(wallet.publicKey.bytes); -final transferCall = polkadot.tx.balances.transferKeepAlive(dest: multiAddress, value: BigInt.one).encode(); - -// Make the payload -final payload = SigningPayload( - method: transferCall, - specVersion: runtimeVersion.specVersion, - transactionVersion: runtimeVersion.transactionVersion, - genesisHash: encodeHex(genesisHash), - blockHash: encodeHex(currentBlockHash), - blockNumber: currentBlockNumber, - eraPeriod: 64, - nonce: nonce, - tip: 0, -).encode(polkadot.registry); - -// Sign the payload and build the final extrinsic -final signature = wallet.sign(payload); -final extrinsic = ExtrinsicPayload( - signer: wallet.bytes(), - method: transferCall, - signature: signature, - eraPeriod: 64, - blockNumber: currentBlockNumber, - nonce: nonce, - tip: 0, -).encode(polkadot.registry, SignatureType.sr25519); - -// Send the extrinsic to the blockchain -final author = AuthorApi(provider); -await author.submitAndWatchExtrinsic(extrinsic, (data) { - print(data); -}); -``` +- Setting up a Hardhat project for deploying to Polkadot Hub. +- Understanding the Uniswap V2 architecture. +- Testing Uniswap V2 contracts in a local environment. +- Deploying contracts to both local and testnet environments. -## Where to Go Next +To build on this foundation, you could extend this project by implementing functionality to create liquidity pools, execute token swaps, and build a user interface for interacting with your deployment. -To dive deeper into Polkadart, refer to the [official Polkadart documentation](https://polkadart.dev/){target=\_blank}, where you can find comprehensive guides for common use cases and advanced usage. +This knowledge can be leveraged to build more complex DeFi applications or to integrate Uniswap V2 functionality into your existing projects on Polkadot. --- -Page Title: Polkadot SDK Accounts +Page Title: Dual Virtual Machine Stack -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-accounts.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/accounts/ -- Summary: Learn about account structures, balances, and address formats in the Polkadot SDK, including how to manage lifecycle, references, and balances. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-dual-vm-stack.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/dual-vm-stack/ +- Summary: Compare Polkadot’s dual smart contract VMs—REVM for EVM compatibility and PolkaVM for RISC-V performance, flexibility, and efficiency. -# Accounts +# Dual Virtual Machine Stack +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. ## Introduction -Accounts are essential for managing identity, transactions, and governance on the network in the Polkadot SDK. Understanding these components is critical for seamless development and operation on the network, whether you're building or interacting with Polkadot-based chains. - -This page will guide you through the essential aspects of accounts, including their data structure, balance types, reference counters, and address formats. You’ll learn how accounts are managed within the runtime, how balances are categorized, and how addresses are encoded and validated. - -## Account Data Structure - -Accounts are foundational to any blockchain, and the Polkadot SDK provides a flexible management system. This section explains how the Polkadot SDK defines accounts and manages their lifecycle through data structures within the runtime. - -### Account - -The [`Account` data type](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/type.Account.html){target=\_blank} is a storage map within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank} that links an account ID to its corresponding data. This structure is fundamental for mapping account-related information within the chain. - -The code snippet below shows how accounts are defined: - -```rs - /// The full account information for a particular account ID. - #[pallet::storage] - #[pallet::getter(fn account)] - pub type Account = StorageMap< - _, - Blake2_128Concat, - T::AccountId, - AccountInfo, - ValueQuery, - >; -``` - -The preceding code block defines a storage map named `Account`. The `StorageMap` is a type of on-chain storage that maps keys to values. In the `Account` map, the key is an account ID, and the value is the account's information. Here, `T` represents the generic parameter for the runtime configuration, which is defined by the pallet's configuration trait (`Config`). - -The `StorageMap` consists of the following parameters: - -- **`_`**: Used in macro expansion and acts as a placeholder for the storage prefix type. Tells the macro to insert the default prefix during expansion. -- **`Blake2_128Concat`**: The hashing function applied to keys in the storage map. -- **`T: :AccountId`**: Represents the key type, which corresponds to the account’s unique ID. -- **`AccountInfo`**: The value type stored in the map. For each account ID, the map stores an `AccountInfo` struct containing: - - - **`T::Nonce`**: A nonce for the account, which is incremented with each transaction to ensure transaction uniqueness. - - **`T: :AccountData`**: Custom account data defined by the runtime configuration, which could include balances, locked funds, or other relevant information. - -- **`ValueQuery`**: Defines how queries to the storage map behave when no value is found; returns a default value instead of `None`. - -For a detailed explanation of storage maps, see the [`StorageMap`](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/struct.StorageMap.html){target=\_blank} entry in the Rust docs. - -### Account Info - -The `AccountInfo` structure is another key element within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank}, providing more granular details about each account's state. This structure tracks vital data, such as the number of transactions and the account’s relationships with other modules. - -```rs -/// Information of an account. -#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)] -pub struct AccountInfo { - /// The number of transactions this account has sent. - pub nonce: Nonce, - /// The number of other modules that currently depend on this account's existence. The account - /// cannot be reaped until this is zero. - pub consumers: RefCount, - /// The number of other modules that allow this account to exist. The account may not be reaped - /// until this and `sufficients` are both zero. - pub providers: RefCount, - /// The number of modules that allow this account to exist for their own purposes only. The - /// account may not be reaped until this and `providers` are both zero. - pub sufficients: RefCount, - /// The additional data that belongs to this account. Used to store the balance(s) in a lot of - /// chains. - pub data: AccountData, -} -``` - -The `AccountInfo` structure includes the following components: - -- **`nonce`**: Tracks the number of transactions initiated by the account, which ensures transaction uniqueness and prevents replay attacks. -- **`consumers`**: Counts how many other modules or pallets rely on this account’s existence. The account cannot be removed from the chain (reaped) until this count reaches zero. -- **`providers`**: Tracks how many modules permit this account’s existence. An account can only be reaped once both `providers` and `sufficients` are zero. -- **`sufficients`**: Represents the number of modules that allow the account to exist for internal purposes, independent of any other modules. -- **`AccountData`**: A flexible data structure that can be customized in the runtime configuration, usually containing balances or other user-specific data. - -This structure helps manage an account's state and prevents its premature removal while it is still referenced by other on-chain data or modules. The [`AccountInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.AccountInfo.html){target=\_blank} structure can vary as long as it satisfies the trait bounds defined by the `AccountData` associated type in the [`frame-system::pallet::Config`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/trait.Config.html){target=\_blank} trait. - -### Account Reference Counters - -Polkadot SDK uses reference counters to track an account’s dependencies across different runtime modules. These counters ensure that accounts remain active while data is associated with them. - -The reference counters include: - -- **`consumers`**: Prevents account removal while other pallets still rely on the account. -- **`providers`**: Ensures an account is active before other pallets store data related to it. -- **`sufficients`**: Indicates the account’s independence, ensuring it can exist even without a native token balance, such as when holding sufficient alternative assets. - -#### Providers Reference Counters - -The `providers` counter ensures that an account is ready to be depended upon by other runtime modules. For example, it is incremented when an account has a balance above the existential deposit, which marks the account as active. - -The system requires this reference counter to be greater than zero for the `consumers` counter to be incremented, ensuring the account is stable before any dependencies are added. - -#### Consumers Reference Counters - -The `consumers` counter ensures that the account cannot be reaped until all references to it across the runtime have been removed. This check prevents the accidental deletion of accounts that still have active on-chain data. - -It is the user’s responsibility to clear out any data from other runtime modules if they wish to remove their account and reclaim their existential deposit. - -#### Sufficients Reference Counter - -The `sufficients` counter tracks accounts that can exist independently without relying on a native account balance. This is useful for accounts holding other types of assets, like tokens, without needing a minimum balance in the native token. - -For instance, the [Assets pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_assets/index.html){target=\_blank}, may increment this counter for an account holding sufficient tokens. - -#### Account Deactivation - -In Polkadot SDK-based chains, an account is deactivated when its reference counters (such as `providers`, `consumers`, and `sufficient`) reach zero. These counters ensure the account remains active as long as other runtime modules or pallets reference it. +Polkadot's smart contract platform supports two distinct virtual machine (VM) architectures, providing developers with flexibility in selecting the optimal execution backend for their specific needs. This approach strikes a balance between immediate Ethereum compatibility and long-term innovation, enabling developers to deploy either unmodified (Ethereum Virtual Machine) EVM contracts using Rust Ethereum Virtual Machine (REVM) or optimize for higher performance using PolkaVM (PVM). -When all dependencies are cleared and the counters drop to zero, the account becomes deactivated and may be removed from the chain (reaped). This is particularly important in Polkadot SDK-based blockchains, where accounts with balances below the existential deposit threshold are pruned from storage to conserve state resources. +Both VM options share common infrastructure, including RPC interfaces, tooling support, and precompiles. The following sections compare architectures and guide you in selecting the best VM for your project's needs. -Each pallet that references an account has cleanup functions that decrement these counters when the pallet no longer depends on the account. Once these counters reach zero, the account is marked for deactivation. +## Migrate from EVM -#### Updating Counters +The [REVM backend](https://github.com/bluealloy/revm){target=\_blank} integrates a complete Rust implementation of the EVM, enabling Solidity contracts to run unchanged on Polkadot's smart contract platform. -The Polkadot SDK provides runtime developers with various methods to manage account lifecycle events, such as deactivation or incrementing reference counters. These methods ensure that accounts cannot be reaped while still in use. +REVM allows developers to use their existing Ethereum tooling and infrastructure to build on Polkadot. Choose REVM to: -The following helper functions manage these counters: +- Migrate existing Ethereum contracts without modifications. +- Retain exact EVM behavior for audit tools. +- Use developer tools that rely upon inspecting EVM bytecode. +- Prioritize rapid deployment over optimization. +- Work with established Ethereum infrastructure and tooling to build on Polkadot. -- **`inc_consumers()`**: Increments the `consumer` reference counter for an account, signaling that another pallet depends on it. -- **`dec_consumers()`**: Decrements the `consumer` reference counter, signaling that a pallet no longer relies on the account. -- **`inc_providers()`**: Increments the `provider` reference counter, ensuring the account remains active. -- **`dec_providers()`**: Decrements the `provider` reference counter, allowing for account deactivation when no longer in use. -- **`inc_sufficients()`**: Increments the `sufficient` reference counter for accounts that hold sufficient assets. -- **`dec_sufficients()`**: Decrements the `sufficient` reference counter. +REVM enables Ethereum developers to seamlessly migrate to Polkadot, achieving performance and fee improvements without modifying their existing contracts or developer tooling stack. -To ensure proper account cleanup and lifecycle management, a corresponding decrement should be made for each increment action. +## Upgrade to PolkaVM -The `System` pallet offers three query functions to assist developers in tracking account states: +[**PolkaVM**](https://github.com/paritytech/polkavm){target=\_blank} is a custom virtual machine optimized for performance with [RISC-V-based](https://en.wikipedia.org/wiki/RISC-V){target=\_blank} architecture, supporting Solidity and additional high-performance languages. It serves as the core execution environment, integrated directly within the runtime. Choose the PolkaVM for: -- **[`can_inc_consumer()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_inc_consumer){target=\_blank}**: Checks if the account can safely increment the consumer reference. -- **[`can_dec_provider()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_dec_provider){target=\_blank}**: Ensures that no consumers exist before allowing the decrement of the provider counter. -- **[`is_provider_required()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.is_provider_required){target=\_blank}**: Verifies whether the account still has any active consumer references. +- An efficient interpreter for immediate code execution. +- A planned [Just In Time (JIT)](https://en.wikipedia.org/wiki/Just-in-time_compilation){target=\_blank} compiler for optimized performance. +- Dual-mode execution capability, allowing selection of the most appropriate backend for specific workloads. +- Optimized performance for short-running contract calls through the interpreter. -This modular and flexible system of reference counters tightly controls the lifecycle of accounts in Polkadot SDK-based blockchains, preventing the accidental removal or retention of unneeded accounts. You can refer to the [System pallet Rust docs](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html){target=\_blank} for more details. - +The interpreter remains particularly beneficial for contracts with minimal code execution, as it enables immediate code execution through lazy interpretation. -## Account Balance Types +## Architecture -In the Polkadot ecosystem, account balances are categorized into different types based on how the funds are utilized and their availability. These balance types determine the actions that can be performed, such as transferring tokens, paying transaction fees, or participating in governance activities. Understanding these balance types helps developers manage user accounts and implement balance-dependent logic. +The following key components of PolkaVM work together to enable Ethereum compatibility on Polkadot-based chains. -!!! note "A more efficient distribution of account balance types is in development" - Soon, pallets in the Polkadot SDK will implement the [`Fungible` trait](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} (see the [tracking issue](https://github.com/paritytech/polkadot-sdk/issues/226){target=\_blank} for more details). For example, the [`transaction-storage`](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_storage/index.html){target=\_blank} pallet changed the implementation of the [`Currency`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/currency/index.html){target=\_blank} trait (see the [Refactor transaction storage pallet to use fungible traits](https://github.com/paritytech/polkadot-sdk/pull/1800){target=\_blank} PR for further details): +### Revive Pallet - ```rust - type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; - ``` - - To the [`Fungible`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} trait: +[**`pallet_revive`**](https://paritytech.github.io/polkadot-sdk/master/pallet_revive/index.html){target=\_blank} is a runtime module that executes smart contracts by adding extrinsics, runtime APIs, and logic to convert Ethereum-style transactions into formats compatible with Polkadot SDK-based blockchains. It processes Ethereum-style transactions through the following workflow: - ```rust - type BalanceOf = <::Currency as FnInspect<::AccountId>>::Balance; - ``` +```mermaid +sequenceDiagram + participant User as User/dApp + participant Proxy as Ethereum JSON RPC Proxy + participant Chain as Blockchain Node + participant Pallet as pallet_revive - This update will enable more efficient use of account balances, allowing the free balance to be utilized for on-chain activities such as setting proxies and managing identities. - -### Balance Types + User->>Proxy: Submit Ethereum Transaction + Proxy->>Chain: Repackage as Polkadot Compatible Transaction + Chain->>Pallet: Process Transaction + Pallet->>Pallet: Decode Ethereum Transaction + Pallet->>Pallet: Execute Contract via PolkaVM + Pallet->>Chain: Return Results + Chain->>Proxy: Forward Results + Proxy->>User: Return Ethereum-compatible Response +``` -The five main balance types are: +This proxy-based approach eliminates the need for node binary modifications, maintaining compatibility across different client implementations. Preserving the original Ethereum transaction payload simplifies the adaptation of existing tools, which can continue processing familiar transaction formats. -- **Free balance**: Represents the total tokens available to the account for any on-chain activity, including staking, governance, and voting. However, it may not be fully spendable or transferrable if portions of it are locked or reserved. -- **Locked balance**: Portions of the free balance that cannot be spent or transferred because they are tied up in specific activities like [staking](https://wiki.polkadot.com/learn/learn-staking/#nominating-validators){target=\_blank}, [vesting](https://wiki.polkadot.com/learn/learn-guides-transfers/#vested-transfers-with-the-polkadot-js-ui){target=\_blank}, or participating in [governance](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank}. While the tokens remain part of the free balance, they are non-transferable for the duration of the lock. -- **Reserved balance**: Funds locked by specific system actions, such as setting up an [identity](https://wiki.polkadot.com/learn/learn-identity/){target=\_blank}, creating [proxies](https://wiki.polkadot.com/learn/learn-proxies/){target=\_blank}, or submitting [deposits for governance proposals](https://wiki.polkadot.com/learn/learn-guides-polkadot-opengov/#claiming-opengov-deposits){target=\_blank}. These tokens are not part of the free balance and cannot be spent unless they are unreserved. -- **Spendable balance**: The portion of the free balance that is available for immediate spending or transfers. It is calculated by subtracting the maximum of locked or reserved amounts from the free balance, ensuring that existential deposit limits are met. -- **Untouchable balance**: Funds that cannot be directly spent or transferred but may still be utilized for on-chain activities, such as governance participation or staking. These tokens are typically tied to certain actions or locked for a specific period. +### PolkaVM Design Fundamentals -The spendable balance is calculated as follows: +PolkaVM differs from the EVM in two key ways that make it faster, more hardware-efficient, and easier to extend: -```text -spendable = free - max(locked - reserved, ED) -``` +- **Register-based design**: Instead of a stack machine, PolkaVM uses a RISC-V–style register model. This design: -Here, `free`, `locked`, and `reserved` are defined above. The `ED` represents the [existential deposit](https://wiki.polkadot.com/learn/learn-accounts/#existential-deposit-and-reaping){target=\_blank}, the minimum balance required to keep an account active and prevent it from being reaped. You may find you can't see all balance types when looking at your account via a wallet. Wallet providers often display only spendable, locked, and reserved balances. + - Uses a fixed set of registers to pass arguments, not an infinite stack. + - Maps cleanly to real hardware like x86-64. + - Simplifies compilation and boosts runtime efficiency. + - Enables tighter control over register allocation and performance tuning. -### Locks +- **64-bit word size**: PolkaVM runs on a native 64-bit word size, aligning directly with modern CPUs. This design: -Locks are applied to an account's free balance, preventing that portion from being spent or transferred. Locks are automatically placed when an account participates in specific on-chain activities, such as staking or governance. Although multiple locks may be applied simultaneously, they do not stack. Instead, the largest lock determines the total amount of locked tokens. + - Executes arithmetic operations with direct hardware support. + - Maintains compatibility with Solidity’s 256-bit types via YUL translation. + - Accelerates computation-heavy workloads through native word alignment. + - Integrates easily with low-level, performance-focused components. -Locks follow these basic rules: +## Where To Go Next -- If different locks apply to varying amounts, the largest lock amount takes precedence. -- If multiple locks apply to the same amount, the lock with the longest duration governs when the balance can be unlocked. +
-#### Locks Example +- Learn __Contract Deployment__ -Consider an example where an account has 80 DOT locked for both staking and governance purposes like so: + --- -- 80 DOT is staked with a 28-day lock period. -- 24 DOT is locked for governance with a 1x conviction and a 7-day lock period. -- 4 DOT is locked for governance with a 6x conviction and a 224-day lock period. + Learn how REVM and PVM compare for compiling and deploying smart contracts. -In this case, the total locked amount is 80 DOT because only the largest lock (80 DOT from staking) governs the locked balance. These 80 DOT will be released at different times based on the lock durations. In this example, the 24 DOT locked for governance will be released first since the shortest lock period is seven days. The 80 DOT stake with a 28-day lock period is released next. Now, all that remains locked is the 4 DOT for governance. After 224 days, all 80 DOT (minus the existential deposit) will be free and transferable. + [:octicons-arrow-right-24: Reference](/smart-contracts/for-eth-devs/contract-deployment/) -![Illustration of Lock Example](/images/reference/parachains/accounts/accounts-01.webp) +
-#### Edge Cases for Locks -In scenarios where multiple convictions and lock periods are active, the lock duration and amount are determined by the longest period and largest amount. For example, if you delegate with different convictions and attempt to undelegate during an active lock period, the lock may be extended for the full amount of tokens. For a detailed discussion on edge case lock behavior, see this [Stack Exchange post](https://substrate.stackexchange.com/questions/5067/delegating-and-undelegating-during-the-lock-period-extends-it-for-the-initial-am){target=\_blank}. +--- -### Balance Types on Polkadot.js +Page Title: Get Started with Parachain Development -Polkadot.js provides a user-friendly interface for managing and visualizing various account balances on Polkadot and Kusama networks. When interacting with Polkadot.js, you will encounter multiple balance types that are critical for understanding how your funds are distributed and restricted. This section explains how different balances are displayed in the Polkadot.js UI and what each type represents. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-get-started.md +- Canonical (HTML): https://docs.polkadot.com/parachains/get-started/ +- Summary: Practical examples and tutorials for building and deploying Polkadot parachains, covering everything from launch to customization and cross-chain messaging. -![](/images/reference/parachains/accounts/accounts-02.webp) +# Get Started -The most common balance types displayed on Polkadot.js are: +The following sections provide practical recipes for building parachains on Polkadot—each focused on specific development scenarios with step-by-step, hands-on examples. -- **Total balance**: The total number of tokens available in the account. This includes all tokens, whether they are transferable, locked, reserved, or vested. However, the total balance does not always reflect what can be spent immediately. In this example, the total balance is 0.6274 KSM. +## Quick Start Guides -- **Transferable balance**: Shows how many tokens are immediately available for transfer. It is calculated by subtracting the locked and reserved balances from the total balance. For example, if an account has a total balance of 0.6274 KSM and a transferable balance of 0.0106 KSM, only the latter amount can be sent or spent freely. +Quick start guides help developers set up and interact with the Polkadot parachain ecosystem using various tools and frameworks. -- **Vested balance**: Tokens that allocated to the account but released according to a specific schedule. Vested tokens remain locked and cannot be transferred until fully vested. For example, an account with a vested balance of 0.2500 KSM means that this amount is owned but not yet transferable. +| Tutorial | Tools | Description | +| :--------------------------------------------------------------------------------------------: | :----------------------------: | :---------------------------------------------------------------------: | +| [Set Up the Parachain Template](/parachains/launch-a-parachain/set-up-the-parachain-template/) | Polkadot SDK | Learn how to set up and run the Polkadot SDK Parachain Template locally | +| [Launch a Local Parachain](/parachains/testing/run-a-parachain-network/) | Zombienet, Chopsticks | Set up a local development environment for testing | +| [Connect to Polkadot](/chain-interactions/query-on-chain-data/query-sdks/) | Polkadot.js, Substrate Connect | Connect your application to Polkadot networks | +| [Fork an Existing Parachain](/parachains/testing/fork-a-parachain/) | Chopsticks | Create a local fork of a live parachain for testing | -- **Locked balance**: Tokens that are temporarily restricted from being transferred or spent. These locks typically result from participating in staking, governance, or vested transfers. In Polkadot.js, locked balances do not stack—only the largest lock is applied. For instance, if an account has 0.5500 KSM locked for governance and staking, the locked balance would display 0.5500 KSM, not the sum of all locked amounts. +## Launch a Simple Parachain -- **Reserved balance**: Refers to tokens locked for specific on-chain actions, such as setting an identity, creating a proxy, or making governance deposits. Reserved tokens are not part of the free balance, but can be freed by performing certain actions. For example, removing an identity would unreserve those funds. +Learn the fundamentals of launching and deploying a parachain to the Polkadot network. -- **Bonded balance**: The tokens locked for staking purposes. Bonded tokens are not transferable until they are unbonded after the unbonding period. +| Tutorial | Description | +| :--------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------: | +| [Set Up the Parachain Template](/parachains/launch-a-parachain/set-up-the-parachain-template/) | Polkadot SDK | +| [Deploy to Polkadot](/parachains/launch-a-parachain/deploy-to-polkadot/) | Step-by-step tutorial to deploying your parachain to Polkadot | +| [Obtain Coretime](/parachains/launch-a-parachain/obtain-coretime/) | Learn how to acquire blockspace using Polkadot's coretime model (RegionX) | -- **Redeemable balance**: The number of tokens that have completed the unbonding period and are ready to be unlocked and transferred again. For example, if an account has a redeemable balance of 0.1000 KSM, those tokens are now available for spending. +## Customize Your Runtime -- **Democracy balance**: Reflects the number of tokens locked for governance activities, such as voting on referenda. These tokens are locked for the duration of the governance action and are only released after the lock period ends. +Build custom functionality for your parachain by composing and creating pallets. -By understanding these balance types and their implications, developers and users can better manage their funds and engage with on-chain activities more effectively. +| Tutorial | Description | +| :-------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------: | +| [Add Existing Pallets to the Runtime](/parachains/customize-runtime/add-existing-pallets/) | Integrate pre-built pallets from the FRAME ecosystem | +| [Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/) | Configure and use multiple instances of the same pallet | +| [Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/) | Enable smart contract capabilities using Contracts or EVM pallets | -## Address Formats +### Pallet Development -The SS58 address format is a core component of the Polkadot SDK that enables accounts to be uniquely identified across Polkadot-based networks. This format is a modified version of Bitcoin's Base58Check encoding, specifically designed to accommodate the multi-chain nature of the Polkadot ecosystem. SS58 encoding allows each chain to define its own set of addresses while maintaining compatibility and checksum validation for security. +Deep dive into creating and managing custom pallets for your parachain. -### Basic Format +| Tutorial | Description | +| :--------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------: | +| [Create a Custom Pallet](/parachains/customize-runtime/pallet-development/create-a-pallet/) | Build a pallet from scratch with custom logic | +| [Mock Your Runtime](/parachains/customize-runtime/pallet-development/mock-runtime/) | Set up a mock runtime environment for testing | +| [Pallet Unit Testing](/parachains/customize-runtime/pallet-development/pallet-testing/) | Write comprehensive tests for your pallet logic | +| [Add Your Custom Pallet to the Runtime](/parachains/customize-runtime/pallet-development/add-pallet-to-runtime/) | Integrate your custom pallet into your parachain runtime | +| [Benchmark the Custom Pallet](/parachains/customize-runtime/pallet-development/benchmark-pallet/) | Measure and optimize pallet performance with benchmarking | -SS58 addresses consist of three main components: +## Testing -```text -base58encode(concat(,
, )) -``` +Test your parachain in various environments before production deployment. -- **Address type**: A byte or set of bytes that define the network (or chain) for which the address is intended. This ensures that addresses are unique across different Polkadot SDK-based chains. -- **Address**: The public key of the account encoded as bytes. -- **Checksum**: A hash-based checksum which ensures that addresses are valid and unaltered. The checksum is derived from the concatenated address type and address components, ensuring integrity. +| Tutorial | Description | +| :---------------------------------------------------------------------: | :-----------------------------------------------------: | +| [Fork a Parachain](/parachains/testing/fork-a-parachain/) | Use Chopsticks to create a local fork for testing | +| [Run a Parachain Network](/parachains/testing/run-a-parachain-network/) | Launch a complete parachain test network with Zombienet | -The encoding process transforms the concatenated components into a Base58 string, providing a compact and human-readable format that avoids easily confused characters (e.g., zero '0', capital 'O', lowercase 'l'). This encoding function ([`encode`](https://docs.rs/bs58/latest/bs58/fn.encode.html){target=\_blank}) is implemented exactly as defined in Bitcoin and IPFS specifications, using the same alphabet as both implementations. +## Runtime Upgrades and Maintenance -For more details about the SS58 address format implementation, see the [`Ss58Codec`](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Ss58Codec.html){target=\_blank} trait in the Rust Docs. +Manage your parachain's lifecycle with forkless upgrades and maintenance operations. -### Address Type +| Tutorial | Description | +| :-----------------------------------------------------------------------: | :--------------------------------------------------: | +| [Runtime Upgrades](/parachains/runtime-maintenance/runtime-upgrades/) | Perform forkless runtime upgrades via governance | +| [Storage Migrations](/parachains/runtime-maintenance/storage-migrations/) | Safely migrate storage when updating runtime logic | +| [Unlock Parachains](/parachains/runtime-maintenance/unlock-parachains/) | Understand parachain lifecycle and unlock mechanisms | -The address type defines how an address is interpreted and to which network it belongs. Polkadot SDK uses different prefixes to distinguish between various chains and address formats: +## Interoperability -- **Address types `0-63`**: Simple addresses, commonly used for network identifiers. -- **Address types `64-127`**: Full addresses that support a wider range of network identifiers. -- **Address types `128-255`**: Reserved for future address format extensions. +Configure your parachain for cross-chain communication using XCM (Cross-Consensus Messaging). -For example, Polkadot’s main network uses an address type of 0, while Kusama uses 2. This ensures that addresses can be used without confusion between networks. +| Tutorial | Description | +| :--------------------------------------------------------------------------------------------------------: | :----------------------------------------------------: | +| [Open HRMP Channels Between Parachains](/parachains/interoperability/channels-between-parachains/) | Establish communication channels with other parachains | +| [Open HRMP Channels with System Parachains](/parachains/interoperability/channels-with-system-parachains/) | Connect with Asset Hub and other system parachains | -The address type is always encoded as part of the SS58 address, making it easy to quickly identify the network. Refer to the [SS58 registry](https://github.com/paritytech/ss58-registry){target=\_blank} for the canonical listing of all address type identifiers and how they map to Polkadot SDK-based networks. +## Integrations -### Address Length +Integrate your parachain with essential ecosystem tools and services. -SS58 addresses can have different lengths depending on the specific format. Address lengths range from as short as 3 to 35 bytes, depending on the complexity of the address and network requirements. This flexibility allows SS58 addresses to adapt to different chains while providing a secure encoding mechanism. +| Tutorial | Description | +| :--------------------------------------------: | :----------------------------------------------------: | +| [Wallets](/parachains/integrations/wallets/) | Integrate wallet support for user interactions | +| [Indexers](/parachains/integrations/indexers/) | Set up indexing solutions for querying blockchain data | +| [Oracles](/parachains/integrations/oracles/) | Connect your parachain to off-chain data sources | -| Total | Type | Raw account | Checksum | -|-------|------|-------------|----------| -| 3 | 1 | 1 | 1 | -| 4 | 1 | 2 | 1 | -| 5 | 1 | 2 | 2 | -| 6 | 1 | 4 | 1 | -| 7 | 1 | 4 | 2 | -| 8 | 1 | 4 | 3 | -| 9 | 1 | 4 | 4 | -| 10 | 1 | 8 | 1 | -| 11 | 1 | 8 | 2 | -| 12 | 1 | 8 | 3 | -| 13 | 1 | 8 | 4 | -| 14 | 1 | 8 | 5 | -| 15 | 1 | 8 | 6 | -| 16 | 1 | 8 | 7 | -| 17 | 1 | 8 | 8 | -| 35 | 1 | 32 | 2 | +## Additional Resources -SS58 addresses also support different payload sizes, allowing a flexible range of account identifiers. +- [Polkadot SDK Documentation](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/index.html) +- [Polkadot Wiki - Parachains](https://wiki.polkadot.network/docs/learn-parachains/) -### Checksum Types -A checksum is applied to validate SS58 addresses. Polkadot SDK uses a Blake2b-512 hash function to calculate the checksum, which is appended to the address before encoding. The checksum length can vary depending on the address format (e.g., 1-byte, 2-byte, or longer), providing varying levels of validation strength. +--- -The checksum ensures that an address is not modified or corrupted, adding an extra layer of security for account management. +Page Title: Get Started with Smart Contracts -### Validating Addresses +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-get-started.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/get-started/ +- Summary: Practical examples for building and deploying smart contracts on Polkadot Hub, from connecting and tooling to deployment, integrations, and precompiles. -SS58 addresses can be validated using the subkey command-line interface or the Polkadot.js API. These tools help ensure an address is correctly formatted and valid for the intended network. The following sections will provide an overview of how validation works with these tools. +# Get Started -#### Using Subkey +This resource provides quick-starts for building smart contracts on Polkadot Hub. Use the tables below to jump directly to the tools and workflows you need. -[Subkey](https://paritytech.github.io/polkadot-sdk/master/subkey/index.html){target=\_blank} is a CLI tool provided by Polkadot SDK for generating and managing keys. It can inspect and validate SS58 addresses. +## Quick Starts -The `inspect` command gets a public key and an SS58 address from the provided secret URI. The basic syntax for the `subkey inspect` command is: +Kick off development fast with curated links for connecting, funding, exploring, and deploying your first contract. -```bash -subkey inspect [flags] [options] uri -``` +| Quick Start | Tools | Description | +|:---------------------------------------------------------------------------------------------------:|:---------------------:|:---------------------------------------------------------------:| +| [Connect to Polkadot](/smart-contracts/connect/){target=\_blank} | Polkadot.js, MetaMask | Add the network, configure RPC, verify activity in the explorer | +| [Get Test Tokens](/smart-contracts/faucets/){target=\_blank} | - | Request test funds to deploy and interact with contracts | +| [Explore Transactions](/smart-contracts/explorers/){target=\_blank} | Subscan | Inspect transactions, logs, token transfers, and contract state | +| [Deploy with Remix](/smart-contracts/dev-environments/remix/deploy-a-contract/){target=\_blank} | Remix | One‑click browser deployment to Polkadot Hub | +| [Deploy with Foundry](/smart-contracts/dev-environments/foundry/deploy-a-contract/){target=\_blank} | Foundry | Scripted deployments and testing from the CLI | +| [Deploy with Hardhat](/smart-contracts/dev-environments/hardhat/deploy-a-contract/){target=\_blank} | Hardhat | Project scaffolding, testing, and deployments | -For the `uri` command-line argument, you can specify the secret seed phrase, a hex-encoded private key, or an SS58 address. If the input is a valid address, the `subkey` program displays the corresponding hex-encoded public key, account identifier, and SS58 addresses. +## Build and Test Locally -For example, to inspect the public keys derived from a secret seed phrase, you can run a command similar to the following: +Set up local environments and CI-friendly workflows to iterate quickly and validate changes before deploying. -```bash -subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" -``` +| Build and Test Locally | Tools | Description | +|:------------------------------------------------------------------------------------------------------------:|:-----------------:|:----------------------------------------------------:| +| [Run a Local Dev Node](/smart-contracts/dev-environments/local-dev-node/){target=\_blank} | Polkadot SDK node | Spin up a local node for iterative development | +| [Remix: Get Started](/smart-contracts/dev-environments/remix/get-started/){target=\_blank} | Remix | Connect Remix to Polkadot Hub and configure accounts | +| [Remix: Verify a Contract](/smart-contracts/dev-environments/remix/verify-a-contract/){target=\_blank} | Remix | Publish verified source on explorers | +| [Foundry: Install and Config](/smart-contracts/dev-environments/foundry/install-and-config/){target=\_blank} | Foundry | Install toolchain and configure networks | +| [Foundry: Compile and Test](/smart-contracts/dev-environments/foundry/compile-and-test/){target=\_blank} | Foundry | Write and run Solidity tests locally | +| [Foundry: Verify a Contract](/smart-contracts/dev-environments/foundry/verify-a-contract/){target=\_blank} | Foundry | Verify deployed bytecode and metadata | +| [Hardhat: Install and Config](/smart-contracts/dev-environments/hardhat/install-and-config/){target=\_blank} | Hardhat | Initialize a project and configure networks | +| [Hardhat: Compile and Test](/smart-contracts/dev-environments/hardhat/compile-and-test/){target=\_blank} | Hardhat | Unit test contracts and run scripts | +| [Hardhat: Verify a Contract](/smart-contracts/dev-environments/hardhat/verify-a-contract/){target=\_blank} | Hardhat | Verify deployments on explorers | -The command displays output similar to the following: +## Ethereum Developer Resources -
- subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" - Secret phrase `caution juice atom organ advance problem want pledge someone senior holiday very` is account: - Secret seed: 0xc8fa03532fb22ee1f7f6908b9c02b4e72483f0dbd66e4cd456b8f34c6230b849 - Public key (hex): 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - Public key (SS58): 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR - Account ID: 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - SS58 Address: 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR -
+Bridge your Ethereum knowledge with Polkadot Hub specifics: account mapping, fees, JSON‑RPC, and deployment. -The `subkey` program assumes an address is based on a public/private key pair. If you inspect an address, the command returns the 32-byte account identifier. +| Ethereum Developer Guides | Description | +|:---------------------------------------------------------------------------------------------------------:|:---------------------------------------------------------------:| +| [Accounts](/smart-contracts/for-eth-devs/accounts/){target=\_blank} | How 20‑byte Ethereum addresses map to 32‑byte Polkadot accounts | +| [Blocks, Transactions, and Fees](/smart-contracts/for-eth-devs/blocks-transactions-fees/){target=\_blank} | Transaction types, fees, and multi‑dimensional metering | +| [Gas Model](/smart-contracts/for-eth-devs/gas-model/){target=\_blank} | Gas vs. weight, proof size, and storage deposits | +| [Contract Deployment](/smart-contracts/for-eth-devs/contract-deployment/){target=\_blank} | Deployment patterns and best practices on Polkadot Hub | +| [JSON‑RPC APIs](/smart-contracts/for-eth-devs/json-rpc-apis/){target=\_blank} | Supported Ethereum JSON‑RPC methods and examples | +| [Migration](/smart-contracts/for-eth-devs/migration/){target=\_blank} | Port existing apps and tooling to Polkadot Hub | +| [Dual VM Stack](/smart-contracts/for-eth-devs/dual-vm-stack/){target=\_blank} | Overview of EVM and native execution on the Hub | -However, not all addresses in Polkadot SDK-based networks are based on keys. +## Cookbook: Hands‑on Tutorials -Depending on the command-line options you specify and the input you provided, the command output might also display the network for which the address has been encoded. For example: +Follow step‑by‑step guides that walk through common tasks and complete dApp examples. -```bash -subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" -``` +| Tutorial | Tools | Description | +|:--------------------------------------------------------------------------------------------------------:|:-------------------:|:-----------------------------------------:| +| [Deploy a Basic Contract](/smart-contracts/cookbook/smart-contracts/deploy-basic/remix/){target=\_blank} | Remix | Minimal deployment walkthrough | +| [Deploy an ERC‑20](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/){target=\_blank} | Remix, OpenZeppelin | Create, deploy, and mint a fungible token | +| [Deploy an NFT (ERC‑721)](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/){target=\_blank} | Remix, OpenZeppelin | Build and deploy an NFT collection | +| [Uniswap V2](/smart-contracts/cookbook/eth-dapps/uniswap-v2/){target=\_blank} | Hardhat | Full dApp project: compile, test, deploy | +| [Zero‑to‑Hero dApp](/smart-contracts/cookbook/dapps/zero-to-hero/){target=\_blank} | Multiple | End‑to‑end dApp patterns and practices | -The command displays output similar to the following: +## Libraries -
- subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" - Public Key URI `12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU` is account: - Network ID/Version: polkadot - Public key (hex): 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Account ID: 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Public key (SS58): 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU - SS58 Address: 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU -
+Choose the client libraries that fit your stack for connecting wallets and calling contracts. -#### Using Polkadot.js API +| Library | Description | +|:------------------------------------------------------------------:|:-------------------------------------------------------:| +| [Ethers.js](/smart-contracts/libraries/ethers-js/){target=\_blank} | Connect, sign, and interact with contracts using Ethers | +| [viem](/smart-contracts/libraries/viem/){target=\_blank} | Type‑safe EVM interactions and utilities | +| [Wagmi](/smart-contracts/libraries/wagmi/){target=\_blank} | React hooks for wallet connections and contract calls | +| [Web3.js](/smart-contracts/libraries/web3-js/){target=\_blank} | Web3 provider and contract APIs | +| [Web3.py](/smart-contracts/libraries/web3-py/){target=\_blank} | Python toolkit for on‑chain interactions and scripts | -To verify an address in JavaScript or TypeScript projects, you can use the functions built into the [Polkadot.js API](https://polkadot.js.org/docs/){target=\_blank}. For example: +## Integrations -```js -// Import Polkadot.js API dependencies -const { decodeAddress, encodeAddress } = require('@polkadot/keyring'); -const { hexToU8a, isHex } = require('@polkadot/util'); +Integrate essential services like wallets, indexers, and oracles to round out your dApp. -// Specify an address to test. -const address = 'INSERT_ADDRESS_TO_TEST'; +| Integration | Description | +|:-------------------------------------------------------------------:|:-----------------------------------------:| +| [Wallets](/smart-contracts/integrations/wallets/){target=\_blank} | Supported wallets and configuration notes | +| [Indexers](/smart-contracts/integrations/indexers/){target=\_blank} | Index and query blockchain data | +| [Oracles](/smart-contracts/integrations/oracles/){target=\_blank} | Bring external data on‑chain | -// Check address -const isValidSubstrateAddress = () => { - try { - encodeAddress(isHex(address) ? hexToU8a(address) : decodeAddress(address)); +## Precompiles - return true; - } catch (error) { - return false; - } -}; +Discover precompiled system contracts available on the Hub and how to use them. -// Query result -const isValid = isValidSubstrateAddress(); -console.log(isValid); +| Topic | Description | +|:------------------------------------------------------------------------:|:---------------------------------------------------:| +| [Overview of Precompiles](/smart-contracts/precompiles/){target=\_blank} | What precompiles are available on the Hub | +| [ETH Native](/smart-contracts/precompiles/eth-native/){target=\_blank} | EVM precompiles and interfaces | +| [Staking](/smart-contracts/precompiles/staking/){target=\_blank} | Interact with staking functionality via precompiles | +| [XCM](/smart-contracts/precompiles/xcm/){target=\_blank} | Cross‑chain messaging helpers for contracts | -``` +From here, follow the quick starts to get connected, iterate locally with your preferred tools, and use the guides, libraries, integrations, and precompiles as you grow into production‑ready dApps. If you get stuck, [open an issue](https://github.com/polkadot-developers/polkadot-docs/issues/new?template=docs-issue.yml){target=\_blank} or reach out in the community channels. -If the function returns `true`, the specified address is a valid address. -#### Other SS58 Implementations +--- -Support for encoding and decoding Polkadot SDK SS58 addresses has been implemented in several other languages and libraries. +Page Title: Get Started with XCM -- **Crystal**: [`wyhaines/base58.cr`](https://github.com/wyhaines/base58.cr){target=\_blank} -- **Go**: [`itering/subscan-plugin`](https://github.com/itering/subscan-plugin){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **TypeScript**: [`subsquid/squid-sdk`](https://github.com/subsquid/squid-sdk){target=\_blank} +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md +- Canonical (HTML): https://docs.polkadot.com/parachains/interoperability/get-started/ +- Summary: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. +# Get Started with XCM ---- +## Introduction -Page Title: Polkadot-API +Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-papi.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/papi/ -- Summary: Polkadot-API (PAPI) is a modular, composable library set designed for efficient interaction with Polkadot chains, prioritizing a "light-client first" approach. +With XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation. -# Polkadot-API +## Messaging Format -## Introduction +XCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics. -[Polkadot-API](https://github.com/polkadot-api/polkadot-api){target=\_blank} (PAPI) is a set of libraries built to be modular, composable, and grounded in a “light-client first” approach. Its primary aim is to equip dApp developers with an extensive toolkit for building fully decentralized applications. +XCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing. -PAPI is optimized for light-client functionality, using the new JSON-RPC spec to support decentralized interactions fully. It provides strong TypeScript support with types and documentation generated directly from on-chain metadata, and it offers seamless access to storage reads, constants, transactions, events, and runtime calls. Developers can connect to multiple chains simultaneously and prepare for runtime updates through multi-descriptor generation and compatibility checks. PAPI is lightweight and performant, leveraging native BigInt, dynamic imports, and modular subpaths to avoid bundling unnecessary assets. It supports promise-based and observable-based APIs, integrates easily with Polkadot.js extensions, and offers signing options through browser extensions or private keys. +## The Four Principles of XCM -## Get Started +XCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems: -### API Instantiation +- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes. +- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended. +- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin. +- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems. -To instantiate the API, you can install the package by using the following command: +These principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments. -=== "npm" +## The XCM Tech Stack - ```bash - npm i polkadot-api@1.17.2 - ``` +![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp) -=== "pnpm" +The XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels. - ```bash - pnpm add polkadot-api@1.17.2 - ``` +## Core Functionalities of XCM -=== "yarn" +XCM enhances cross-consensus communication by introducing several powerful features: - ```bash - yarn add polkadot-api@1.17.2 - ``` +- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management. +- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification. +- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location. -Then, obtain the latest metadata from the target chain and generate the necessary types: +The standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications. -```bash -# Add the target chain -npx papi add dot -n polkadot -``` +## XCM Example -The `papi add` command initializes the library by generating the corresponding types needed for the chain used. It assigns the chain a custom name and specifies downloading metadata from the Polkadot chain. You can replace `dot` with the name you prefer or with another chain if you want to add a different one. Once the latest metadata is downloaded, generate the required types: +The following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA). -```bash -# Generate the necessary types -npx papi +```rust +let message = Xcm(vec![ + WithdrawAsset((Here, amount).into()), + BuyExecution { + fees: (Here, amount).into(), + weight_limit: WeightLimit::Unlimited + }, + DepositAsset { + assets: All.into(), + beneficiary: MultiLocation { + parents: 0, + interior: Junction::AccountId32 { + network: None, + id: BOB.clone().into() + }.into(), + }.into() + } +]); ``` -You can now set up a [`PolkadotClient`](https://github.com/polkadot-api/polkadot-api/blob/main/packages/client/src/types.ts#L153){target=\_blank} with your chosen provider to begin interacting with the API. Choose from Smoldot via WebWorker, Node.js, or direct usage, or connect through the WSS provider. The examples below show how to configure each option for your setup. +The message consists of three instructions described as follows: -=== "Smoldot (WebWorker)" +- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register. - ```typescript - // `dot` is the identifier assigned during `npx papi add` - import { dot } from '@polkadot-api/descriptors'; - import { createClient } from 'polkadot-api'; - import { getSmProvider } from 'polkadot-api/sm-provider'; - import { chainSpec } from 'polkadot-api/chains/polkadot'; - import { startFromWorker } from 'polkadot-api/smoldot/from-worker'; - import SmWorker from 'polkadot-api/smoldot/worker?worker'; + ```rust + WithdrawAsset((Here, amount).into()), + ``` - const worker = new SmWorker(); - const smoldot = startFromWorker(worker); - const chain = await smoldot.addChain({ chainSpec }); + - **`Here`**: The native parachain token. + - **`amount`**: The number of tokens that are transferred. - // Establish connection to the Polkadot relay chain - const client = createClient(getSmProvider(chain)); + The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register. - // To interact with the chain, obtain the `TypedApi`, which provides - // the necessary types for every API call on this chain - const dotApi = client.getTypedApi(dot); +- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\_blank} of the XCM instructions. + ```rust + BuyExecution { + fees: (Here, amount).into(), + weight_limit: WeightLimit::Unlimited + }, ``` -=== "Smoldot (Node.js)" - - ```typescript - // `dot` is the alias assigned during `npx papi add` - import { dot } from '@polkadot-api/descriptors'; - import { createClient } from 'polkadot-api'; - import { getSmProvider } from 'polkadot-api/sm-provider'; - import { chainSpec } from 'polkadot-api/chains/polkadot'; - import { startFromWorker } from 'polkadot-api/smoldot/from-node-worker'; - import { fileURLToPath } from 'url'; - import { Worker } from 'worker_threads'; - - // Get the path for the worker file in ESM - const workerPath = fileURLToPath( - import.meta.resolve('polkadot-api/smoldot/node-worker'), - ); + - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight. + - **`weight_limit`**: Defines the maximum fees that can be used to buy weight. - const worker = new Worker(workerPath); - const smoldot = startFromWorker(worker); - const chain = await smoldot.addChain({ chainSpec }); +- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\_blank}**: Moves the remaining tokens from the holding register to Bob’s account. - // Set up a client to connect to the Polkadot relay chain - const client = createClient(getSmProvider(chain)); + ```rust + DepositAsset { + assets: All.into(), + beneficiary: MultiLocation { + parents: 0, + interior: Junction::AccountId32 { + network: None, + id: BOB.clone().into() + }.into(), + }.into() + } + ``` - // To interact with the chain's API, use `TypedApi` for access to - // all the necessary types and calls associated with this chain - const dotApi = client.getTypedApi(dot); + - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited. + +This step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - ``` +## Overview -=== "Smoldot" +XCM revolutionizes cross-chain communication by enabling use cases such as: - ```typescript - // `dot` is the alias assigned when running `npx papi add` - import { dot } from '@polkadot-api/descriptors'; - import { createClient } from 'polkadot-api'; - import { getSmProvider } from 'polkadot-api/sm-provider'; - import { chainSpec } from 'polkadot-api/chains/polkadot'; - import { start } from 'polkadot-api/smoldot'; +- Token transfers between blockchains. +- Asset locking for cross-chain smart contract interactions. +- Remote execution of functions on other blockchains. - // Initialize Smoldot client - const smoldot = start(); - const chain = await smoldot.addChain({ chainSpec }); +These functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - // Set up a client to connect to the Polkadot relay chain - const client = createClient(getSmProvider(chain)); - // Access the `TypedApi` to interact with all available chain calls and types - const dotApi = client.getTypedApi(dot); +--- - ``` +Page Title: Indexers -=== "WSS" +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-indexers.md +- Canonical (HTML): https://docs.polkadot.com/parachains/integrations/indexers/ +- Summary: Discover blockchain indexers. Enhance data access, enable fast and complex queries, and optimize blockchain data for seamless app performance. - ```typescript - // `dot` is the identifier assigned when executing `npx papi add` - import { dot } from '@polkadot-api/descriptors'; - import { createClient } from 'polkadot-api'; - // Use this import for Node.js environments - import { getWsProvider } from 'polkadot-api/ws-provider/web'; - import { withPolkadotSdkCompat } from 'polkadot-api/polkadot-sdk-compat'; +# Indexers - // Establish a connection to the Polkadot relay chain - const client = createClient( - // The Polkadot SDK nodes may have compatibility issues; using this enhancer is recommended. - // Refer to the Requirements page for additional details - withPolkadotSdkCompat(getWsProvider('wss://dot-rpc.stakeworld.io')), - ); +## The Challenge of Blockchain Data Access - // To interact with the chain, obtain the `TypedApi`, which provides - // the types for all available calls in that chain - const dotApi = client.getTypedApi(dot); +Blockchain data is inherently sequential and distributed, with information stored chronologically across numerous blocks. While retrieving data from a single block through JSON-RPC API calls is straightforward, more complex queries that span multiple blocks present significant challenges: - ``` +- Data is scattered and unorganized across the blockchain. +- Retrieving large datasets can take days or weeks to sync. +- Complex operations (like aggregations, averages, or cross-chain queries) require additional processing. +- Direct blockchain queries can impact dApp performance and responsiveness. -Now that you have set up the client, you can interact with the chain by reading and sending transactions. +## What is a Blockchain Indexer? -### Reading Chain Data +A blockchain indexer is a specialized infrastructure tool that processes, organizes, and stores blockchain data in an optimized format for efficient querying. Think of it as a search engine for blockchain data that: -The `TypedApi` provides a streamlined way to read blockchain data through three main interfaces, each designed for specific data access patterns: +- Continuously monitors the blockchain for new blocks and transactions. +- Processes and categorizes this data according to predefined schemas. +- Stores the processed data in an easily queryable database. +- Provides efficient APIs (typically [GraphQL](https://graphql.org/){target=\_blank}) for data retrieval. -- **Constants**: Access fixed values or configurations on the blockchain using the `constants` interface. +## Indexer Implementations - ```typescript - const version = await typedApi.constants.System.Version(); - ``` +
-- **Storage queries**: Retrieve stored values by querying the blockchain’s storage via the `query` interface. +- __Subsquid__ - ```typescript - const asset = await api.query.ForeignAssets.Asset.getValue( - token.location, - { at: 'best' }, - ); - ``` + --- -- **Runtime APIs**: Interact directly with runtime APIs using the `apis` interface. + Subsquid is a data network that allows rapid and cost-efficient retrieval of blockchain data from 100+ chains using Subsquid's decentralized data lake and open-source SDK. In simple terms, Subsquid can be considered an ETL (extract, transform, and load) tool with a GraphQL server included. It enables comprehensive filtering, pagination, and even full-text search capabilities. Subsquid has native and full support for EVM and Substrate data, even within the same project. - ```typescript - const metadata = await typedApi.apis.Metadata.metadata(); - ``` + [:octicons-arrow-right-24: Reference](https://www.sqd.ai/){target=\_blank} -To learn more about the different actions you can perform with the `TypedApi`, refer to the [TypedApi reference](https://papi.how/typed){target=\_blank}. +- __Subquery__ -### Sending Transactions + --- -In PAPI, the `TypedApi` provides the `tx` and `txFromCallData` methods to send transactions. + SubQuery is a fast, flexible, and reliable open-source data decentralised infrastructure network that provides both RPC and indexed data to consumers worldwide. + It provides custom APIs for your web3 project across multiple supported chains. -- The `tx` method allows you to directly send a transaction with the specified parameters by using the `typedApi.tx.Pallet.Call` pattern: + [:octicons-arrow-right-24: Reference](https://subquery.network/){target=\_blank} - ```typescript - const tx: Transaction = typedApi.tx.Pallet.Call({arg1, arg2, arg3}); - ``` +
- For instance, to execute the `balances.transferKeepAlive` call, you can use the following snippet: - ```typescript - import { MultiAddress } from '@polkadot-api/descriptors'; +--- - const tx: Transaction = typedApi.tx.Balances.transfer_keep_alive({ - dest: MultiAddress.Id('INSERT_DESTINATION_ADDRESS'), - value: BigInt(INSERT_VALUE), - }); +Page Title: Install Polkadot SDK - ``` +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-install-polkadot-sdk.md +- Canonical (HTML): https://docs.polkadot.com/parachains/install-polkadot-sdk/ +- Summary: Install all required Polkadot SDK dependencies, set up the SDK itself, and verify that it runs correctly on your machine. - Ensure you replace `INSERT_DESTINATION_ADDRESS` and `INSERT_VALUE` with the actual destination address and value, respectively. +# Install Polkadot SDK -- The `txFromCallData` method allows you to send a transaction using the call data. This option accepts binary call data and constructs the transaction from it. It validates the input upon creation and will throw an error if invalid data is provided. The pattern is as follows: +This guide provides step-by-step instructions for installing the Polkadot SDK on macOS, Linux, and Windows. The installation process consists of two main parts: - ```typescript - const callData = Binary.fromHex('0x...'); - const tx: Transaction = typedApi.txFromCallData(callData); - ``` +- **Installing dependencies**: Setting up Rust, required system packages, and development tools. +- **Building the Polkadot SDK**: Cloning and compiling the Polkadot SDK repository. - For instance, to execute a transaction using the call data, you can use the following snippet: +Follow the appropriate section for your operating system to ensure all necessary tools are installed and configured properly. - ```typescript - const callData = Binary.fromHex('0x00002470617065726d6f6f6e'); - const tx: Transaction = typedApi.txFromCallData(callData); - ``` +## Install Dependencies: macOS -For more information about sending transactions, refer to the [Transactions](https://papi.how/typed/tx#transactions){target=\_blank} page. +You can install Rust and set up a Substrate development environment on Apple macOS computers with Intel or Apple M1 processors. -## Where to Go Next +### Before You Begin {: #before-you-begin-mac-os } -For an in-depth guide on how to use PAPI, refer to the official [PAPI](https://papi.how/){target=\_blank} documentation. +Before you install Rust and set up your development environment on macOS, verify that your computer meets the following basic requirements: +- Operating system version is 10.7 Lion or later. +- Processor speed of at least 2 GHz. Note that 3 GHz is recommended. +- Memory of at least 8 GB RAM. Note that 16 GB is recommended. +- Storage of at least 10 GB of available space. +- Broadband Internet connection. ---- +### Install Homebrew -Page Title: Polkadot.js API +In most cases, you should use Homebrew to install and manage packages on macOS computers. If you don't already have Homebrew installed on your local computer, you should download and install it before continuing. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-polkadot-js-api.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/polkadot-js-api/ -- Summary: Interact with Polkadot SDK-based chains easily using the Polkadot.js API. Query chain data, submit transactions, and more via JavaScript or Typescript. +To install Homebrew: -# Polkadot.js API +1. Open the Terminal application. +2. Download and install Homebrew by running the following command: -!!! warning "Maintenance Mode Only" - The Polkadot.js API is now in maintenance mode and is no longer actively developed. New projects should use [Dedot](/develop/toolkit/api-libraries/dedot){target=\_blank} (TypeScript-first API) or [Polkadot API](/develop/toolkit/api-libraries/papi){target=\_blank} (modern, type-safe API) as actively maintained alternatives. + ```bash + /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" + ``` -## Introduction +3. Verify Homebrew has been successfully installed by running the following command: -The [Polkadot.js API](https://github.com/polkadot-js/api){target=\_blank} uses JavaScript/TypeScript to interact with Polkadot SDK-based chains. It allows you to query nodes, read chain state, and submit transactions through a dynamic, auto-generated API interface. + ```bash + brew --version + ``` -### Dynamic API Generation + The command displays output similar to the following: -Unlike traditional static APIs, the Polkadot.js API generates its interfaces automatically when connecting to a node. Here's what happens when you connect: +
+ brew --version + Homebrew 4.3.15 +
-1. The API connects to your node. -2. It retrieves the chain's metadata. -3. Based on this metadata, it creates specific endpoints in this format: `api...
`. +### Support for Apple Silicon -### Available API Categories +Protobuf must be installed before the build process can begin. To install it, run the following command: -You can access three main categories of chain interactions: +```bash +brew install protobuf +``` -- **[Runtime constants](https://polkadot.js.org/docs/api/start/api.consts){target=\_blank}** (`api.consts`): +### Install Required Packages and Rust {: #install-required-packages-and-rust-mac-os } - - Access runtime constants directly. - - Returns values immediately without function calls. - - **Example**: `api.consts.balances.existentialDeposit` +Because the blockchain requires standard cryptography to support the generation of public/private key pairs and the validation of transaction signatures, you must also have a package that provides cryptography, such as `openssl`. -- **[State queries](https://polkadot.js.org/docs/api/start/api.query/){target=\_blank}** (`api.query`): +To install `openssl` and the Rust toolchain on macOS: - - Read chain state. - - **Example**: `api.query.system.account(accountId)` +1. Open the Terminal application. +2. Ensure you have an updated version of Homebrew by running the following command: -- **[Transactions](https://polkadot.js.org/docs/api/start/api.tx/){target=\_blank}** (`api.tx`): - - Submit extrinsics (transactions). - - **Example**: `api.tx.balances.transfer(accountId, value)` + ```bash + brew update + ``` -The available methods and interfaces will automatically reflect what's possible on your connected chain. +3. Install the `openssl` package by running the following command: -## Installation + ```bash + brew install openssl + ``` -To add the Polkadot.js API to your project, use the following command to install the version `16.4.7` which supports any Polkadot SDK-based chain: +4. Download the `rustup` installation program and use it to install Rust by running the following command: -=== "npm" ```bash - npm i @polkadot/api@16.4.7 + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` -=== "pnpm" +5. Follow the prompts displayed to proceed with a default installation. +6. Update your current shell to include Cargo by running the following command: + ```bash - pnpm add @polkadot/api@16.4.7 + source ~/.cargo/env ``` -=== "yarn" +7. Configure the Rust toolchain to default to the latest stable version by running the following commands: + ```bash - yarn add @polkadot/api@16.4.7 + rustup default stable + rustup update + rustup target add wasm32-unknown-unknown + rustup component add rust-src ``` -For more detailed information about installation, see the [Installation](https://polkadot.js.org/docs/api/start/install/){target=\_blank} section in the official Polkadot.js API documentation. +8. Install `cmake` using the following command: -## Get Started + ```bash + brew install cmake + ``` -### Creating an API Instance +9. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). -To interact with a Polkadot SDK-based chain, you must establish a connection through an API instance. The API provides methods for querying chain state, sending transactions, and subscribing to updates. +## Install Dependencies: Linux -To create an API connection: +Rust supports most Linux distributions. Depending on the specific distribution and version of the operating system you use, you might need to add some software dependencies to your environment. In general, your development environment should include a linker or a C-compatible compiler, such as `clang`, and an appropriate integrated development environment (IDE). -```js -import { ApiPromise, WsProvider } from '@polkadot/api'; +### Before You Begin {: #before-you-begin-linux } -// Create a WebSocket provider -const wsProvider = new WsProvider('wss://rpc.polkadot.io'); +Check the documentation for your operating system for information about the installed packages and how to download and install any additional packages you might need. For example, if you use Ubuntu, you can use the Ubuntu Advanced Packaging Tool (`apt`) to install the `build-essential` package: -// Initialize the API -const api = await ApiPromise.create({ provider: wsProvider }); +```bash +sudo apt install build-essential +``` -// Verify the connection by getting the chain's genesis hash -console.log('Genesis Hash:', api.genesisHash.toHex()); +At a minimum, you need the following packages before you install Rust: +```text +clang curl git make ``` -!!!warning - All `await` operations must be wrapped in an async function or block since the API uses promises for asynchronous operations. +Because the blockchain requires standard cryptography to support the generation of public/private key pairs and the validation of transaction signatures, you must also have a package that provides cryptography, such as `libssl-dev` or `openssl-devel`. + +### Install Required Packages and Rust {: #install-required-packages-and-rust-linux } -### Reading Chain Data +To install the Rust toolchain on Linux: -The API provides several ways to read data from the chain. You can access: +1. Open a terminal shell. +2. Check the packages installed on the local computer by running the appropriate package management command for your Linux distribution. +3. Add any package dependencies you are missing to your local development environment by running the appropriate package management command for your Linux distribution: -- **Constants**: Values that are fixed in the runtime and don't change without a runtime upgrade. + === "Ubuntu" - ```js - // Get the minimum balance required for a new account - const minBalance = api.consts.balances.existentialDeposit.toNumber(); + ```bash + sudo apt install --assume-yes git clang curl libssl-dev protobuf-compiler + ``` - ``` + === "Debian" -- **State**: Current chain state that updates with each block. + ```sh + sudo apt install --assume-yes git clang curl libssl-dev llvm libudev-dev make protobuf-compiler + ``` - ```js - // Example address - const address = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFabHE'; + === "Arch" - // Get current timestamp - const timestamp = await api.query.timestamp.now(); + ```sh + pacman -Syu --needed --noconfirm curl git clang make protobuf + ``` - // Get account information - const { nonce, data: balance } = await api.query.system.account(address); + === "Fedora" - console.log(` - Timestamp: ${timestamp} - Free Balance: ${balance.free} - Nonce: ${nonce} - `); + ```sh + sudo dnf update + sudo dnf install clang curl git openssl-devel make protobuf-compiler + ``` - ``` + === "OpenSUSE" -### Sending Transactions + ```sh + sudo zypper install clang curl git openssl-devel llvm-devel libudev-devel make protobuf + ``` -Transactions (also called extrinsics) modify the chain state. Before sending a transaction, you need: + Remember that different distributions might use different package managers and bundle packages in different ways. For example, depending on your installation selections, Ubuntu Desktop and Ubuntu Server might have different packages and different requirements. However, the packages listed in the command-line examples are applicable to many common Linux distributions, including Debian, Linux Mint, MX Linux, and Elementary OS. -- A funded account with sufficient balance to pay transaction fees. -- The account's keypair for signing. +4. Download the `rustup` installation program and use it to install Rust by running the following command: -To make a transfer: + ```bash + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh + ``` -```js -// Assuming you have an `alice` keypair from the Keyring -const recipient = 'INSERT_RECIPIENT_ADDRESS'; -const amount = 'INSERT_VALUE'; // Amount in the smallest unit (e.g., Planck for DOT) +5. Follow the prompts displayed to proceed with a default installation. +6. Update your current shell to include Cargo by running the following command: -// Sign and send a transfer -const txHash = await api.tx.balances - .transfer(recipient, amount) - .signAndSend(alice); + ```bash + source $HOME/.cargo/env + ``` -console.log('Transaction Hash:', txHash); +7. Verify your installation by running the following command: -``` + ```bash + rustc --version + ``` -The `alice` keypair in the example comes from a `Keyring` object. For more details about managing keypairs, see the [Keyring documentation](https://polkadot.js.org/docs/keyring){target=\_blank}. +8. Configure the Rust toolchain to default to the latest stable version by running the following commands: -## Where to Go Next + ```bash + rustup default stable + rustup update + rustup target add wasm32-unknown-unknown + rustup component add rust-src + ``` -For more detailed information about the Polkadot.js API, check the [official documentation](https://polkadot.js.org/docs/){target=\_blank}. +9. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). +## Install Dependencies: Windows (WSL) ---- +In general, UNIX-based operating systems—like macOS or Linux—provide a better development environment for building Substrate-based blockchains. -Page Title: Python Substrate Interface +However, suppose your local computer uses Microsoft Windows instead of a UNIX-based operating system. In that case, you can configure it with additional software to make it a suitable development environment for building Substrate-based blockchains. To prepare a development environment on a Microsoft Windows computer, you can use Windows Subsystem for Linux (WSL) to emulate a UNIX operating environment. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-py-substrate-interface.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/py-substrate-interface/ -- Summary: Learn how to connect to Polkadot SDK-based nodes, query data, submit transactions, and manage blockchain interactions using the Python Substrate Interface. +### Before You Begin {: #before-you-begin-windows-wls } -# Python Substrate Interface +Before installing on Microsoft Windows, verify the following basic requirements: -## Introduction +- You have a computer running a supported Microsoft Windows operating system: + - **For Windows desktop**: You must be running Microsoft Windows 10, version 2004 or later, or Microsoft Windows 11 to install WSL. + - **For Windows server**: You must be running Microsoft Windows Server 2019, or later, to install WSL on a server operating system. +- You have a good internet connection and access to a shell terminal on your local computer. -The [Python Substrate Interface](https://github.com/polkascan/py-substrate-interface){target=\_blank} is a powerful library that enables interaction with Polkadot SDK-based chains. It provides essential functionality for: +### Set Up Windows Subsystem for Linux -- Querying on-chain storage. -- Composing and submitting extrinsics. -- SCALE encoding/decoding. -- Interacting with Substrate runtime metadata. -- Managing blockchain interactions through convenient utility methods. +WSL enables you to emulate a Linux environment on a computer that uses the Windows operating system. The primary advantage of this approach for Substrate development is that you can use all of the code and command-line examples as described in the Substrate documentation. For example, you can run common commands—such as `ls` and `ps`—unmodified. By using WSL, you can avoid configuring a virtual machine image or a dual-boot operating system. -## Installation +To prepare a development environment using WSL: -Install the library using `pip`: +1. Check your Windows version and build number to see if WSL is enabled by default. -```py -pip install substrate-interface -``` + If you have Microsoft Windows 10, version 2004 (Build 19041 and higher), or Microsoft Windows 11, WSL is available by default and you can continue to the next step. -For more installation details, see the [Installation](https://jamdottech.github.io/py-polkadot-sdk/getting-started/installation/){target=\_blank} section in the official Python Substrate Interface documentation. + If you have an older version of Microsoft Windows installed, see the [WSL manual installation steps for older versions](https://learn.microsoft.com/en-us/windows/wsl/install-manual){target=\_blank}. If you are installing on an older version of Microsoft Windows, you can download and install WLS 2 if your computer has Windows 10, version 1903 or higher. -## Get Started +2. Select **Windows PowerShell** or **Command Prompt** from the **Start** menu, right-click, then **Run as administrator**. -This guide will walk you through the basic operations with the Python Substrate Interface: connecting to a node, reading chain state, and submitting transactions. +3. In the PowerShell or Command Prompt terminal, run the following command: -### Establishing Connection + ```bash + wsl --install + ``` -The first step is to establish a connection to a Polkadot SDK-based node. You can connect to either a local or remote node: + This command enables the required WSL 2 components that are part of the Windows operating system, downloads the latest Linux kernel, and installs the Ubuntu Linux distribution by default. -```py -from substrateinterface import SubstrateInterface + If you want to review the other Linux distributions available, run the following command: -# Connect to a node using websocket -substrate = SubstrateInterface( - # For local node: "ws://127.0.0.1:9944" - # For Polkadot: "wss://rpc.polkadot.io" - # For Kusama: "wss://kusama-rpc.polkadot.io" - url="INSERT_WS_URL" -) + ```bash + wsl --list --online + ``` -# Verify connection -print(f"Connected to chain: {substrate.chain}") +4. After the distribution is downloaded, close the terminal. -``` +5. Click the **Start** menu, select **Shut down or sign out**, then click **Restart** to restart the computer. -### Reading Chain State + Restarting the computer is required to start the installation of the Linux distribution. It can take a few minutes for the installation to complete after you restart. -You can query various on-chain storage items. To retrieve data, you need to specify three key pieces of information: + For more information about setting up WSL as a development environment, see the [Set up a WSL development environment](https://learn.microsoft.com/en-us/windows/wsl/setup/environment){target=\_blank} docs. -- **Pallet name**: Module or pallet that contains the storage item you want to access. -- **Storage item**: Specific storage entry you want to query within the pallet. -- **Required parameters**: Any parameters needed to retrieve the desired data. +### Install Required Packages and Rust {: #install-required-packages-and-rust-windows-wls } -Here's an example of how to check an account's balance and other details: +To install the Rust toolchain on WSL: -```py -# ... +1. Click the **Start** menu, then select **Ubuntu**. +2. Type a UNIX user name to create a user account. +3. Type a password for your UNIX user, then retype the password to confirm it. +4. Download the latest updates for the Ubuntu distribution using the Ubuntu Advanced Packaging Tool (`apt`) by running the following command: -# Query account balance and info -account_info = substrate.query( - module="System", # The pallet name - storage_function="Account", # The storage item - params=["INSERT_ADDRESS"], # Account address in SS58 format -) + ```bash + sudo apt update + ``` -# Access account details from the result -free_balance = account_info.value["data"]["free"] -reserved = account_info.value["data"]["reserved"] -nonce = account_info.value["nonce"] +5. Add the required packages for the Ubuntu distribution by running the following command: -print( - f""" - Account Details: - - Free Balance: {free_balance} - - Reserved: {reserved} - - Nonce: {nonce} - """ -) + ```bash + sudo apt install --assume-yes git clang curl libssl-dev llvm libudev-dev make protobuf-compiler + ``` -``` +6. Download the `rustup` installation program and use it to install Rust for the Ubuntu distribution by running the following command: -### Submitting Transactions + ```bash + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh + ``` -To modify the chain state, you need to submit transactions (extrinsics). Before proceeding, ensure you have: +7. Follow the prompts displayed to proceed with a default installation. -- A funded account with sufficient balance to pay transaction fees. -- Access to the account's keypair. +8. Update your current shell to include Cargo by running the following command: -Here's how to create and submit a balance transfer: + ```bash + source ~/.cargo/env + ``` -```py -#... +9. Verify your installation by running the following command: -# Compose the transfer call -call = substrate.compose_call( - call_module="Balances", # The pallet name - call_function="transfer_keep_alive", # The extrinsic function - call_params={ - 'dest': 'INSERT_ADDRESS', # Recipient's address - 'value': 'INSERT_VALUE' # Amount in smallest unit (e.g., Planck for DOT) - } -) - -# Create a signed extrinsic -extrinsic = substrate.create_signed_extrinsic( - call=call, keypair=keypair # Your keypair for signing -) - -# Submit and wait for inclusion -receipt = substrate.submit_extrinsic( - extrinsic, wait_for_inclusion=True # Wait until the transaction is in a block -) - -if receipt.is_success: - print( - f""" - Transaction successful: - - Extrinsic Hash: {receipt.extrinsic_hash} - - Block Hash: {receipt.block_hash} - """ - ) -else: - print(f"Transaction failed: {receipt.error_message}") + ```bash + rustc --version + ``` -``` +10. Configure the Rust toolchain to use the latest stable version as the default toolchain by running the following commands: -The `keypair` object is essential for signing transactions. See the [Keypair](https://jamdottech.github.io/py-polkadot-sdk/reference/keypair/){target=\_blank} documentation for more details. + ```bash + rustup default stable + rustup update + rustup target add wasm32-unknown-unknown + rustup component add rust-src + ``` -## Where to Go Next +11. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). -Now that you understand the basics, you can: +## Build the Polkadot SDK -- Explore more complex queries and transactions. -- Learn about batch transactions and utility functions. -- Discover how to work with custom pallets and types. +After installing all dependencies, you can now clone and compile the Polkadot SDK repository to verify your setup. -For comprehensive reference materials and advanced features, see the [Python Substrate Interface](https://jamdottech.github.io/py-polkadot-sdk/){target=\_blank} documentation. +### Clone the Polkadot SDK +1. Clone the Polkadot SDK repository: ---- + ```bash + git clone https://github.com/paritytech/polkadot-sdk.git + ``` -Page Title: Randomness +2. Navigate into the project directory: -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-randomness.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/randomness/ -- Summary: Explore the importance of randomness in PoS blockchains, focusing on Polkadot’s VRF-based approach to ensure fairness and security in validator selection. + ```bash + cd polkadot-sdk + ``` -# Randomness +### Compile the Polkadot SDK -## Introduction +Compile the entire Polkadot SDK repository to ensure your environment is properly configured: -Randomness is crucial in Proof of Stake (PoS) blockchains to ensure a fair and unpredictable distribution of validator duties. However, computers are inherently deterministic, meaning the same input always produces the same output. What we typically refer to as "random" numbers on a computer are actually pseudo-random. These numbers rely on an initial "seed," which can come from external sources like [atmospheric noise](https://www.random.org/randomness/){target=\_blank}, [heart rates](https://mdpi.altmetric.com/details/47574324){target=\_blank}, or even [lava lamps](https://en.wikipedia.org/wiki/Lavarand){target=\_blank}. While this may seem random, given the same "seed," the same sequence of numbers will always be generated. +```bash +cargo build --release --locked +``` -In a global blockchain network, relying on real-world entropy for randomness isn’t feasible because these inputs vary by time and location. If nodes use different inputs, blockchains can fork. Hence, real-world randomness isn't suitable for use as a seed in blockchain systems. +!!!note + This initial compilation will take significant time, depending on your machine specifications. It compiles all components of the Polkadot SDK to verify your toolchain is correctly configured. -Currently, two primary methods for generating randomness in blockchains are used: [`RANDAO`](#randao) and [`VRF`](#vrf) (Verifiable Random Function). Polkadot adopts the `VRF` approach for its randomness. +### Verify the Build -## VRF +Once the build completes successfully, verify the installation by checking the compiled binaries: -A Verifiable Random Function (VRF) is a cryptographic function that generates a random number and proof that ensures the submitter produced the number. This proof allows anyone to verify the validity of the random number. +```bash +ls target/release +``` -Polkadot's VRF is similar to the one used in [**Ouroboros Praos**](https://eprint.iacr.org/2017/573.pdf){target=\_blank}, which secures randomness for block production in systems like [BABE](/reference/polkadot-hub/consensus-and-security/pos-consensus/#block-production-babe){target=\_blank} (Polkadot’s block production mechanism). +You should see several binaries, including: -The key difference is that Polkadot's VRF doesn’t rely on a central clock—avoiding the issue of whose clock to trust. Instead, it uses its own past results and slot numbers to simulate time and determine future outcomes. +- `polkadot`: The Polkadot relay chain node. +- `polkadot-parachain`: The parachain collator node. +- `polkadot-omni-node`:The omni node for running parachains. +- `substrate-node`: The kitchensink node with many pre-configured pallets. -### How VRF Works +Verify the Polkadot binary works by checking its version: -Slots on Polkadot are discrete units of time, each lasting six seconds, and can potentially hold a block. Multiple slots form an epoch, with 2400 slots making up one four-hour epoch. +```bash +./target/release/polkadot --version +``` -In each slot, validators execute a "die roll" using a VRF. The VRF uses three inputs: +This should display version information similar to: -1. A "secret key," unique to each validator, is used for the die roll. -2. An epoch randomness value, derived from the hash of VRF outputs from blocks two epochs ago (N-2), so past randomness influences the current epoch (N). -3. The current slot number. +```bash +polkadot 1.16.0-1234abcd567 +``` -This process helps maintain fair randomness across the network. +If you see the version output without errors, your development environment is correctly configured and ready for Polkadot SDK development! -Here is a graphical representation: +## Optional: Run the Kitchensink Node -![](/images/reference/parachains/randomness/randomness-01.webp) +The Polkadot SDK includes a feature-rich node called "kitchensink" located at `substrate/bin/node`. This node comes pre-configured with many pallets and features from the Polkadot SDK, making it an excellent reference for exploring capabilities and understanding how different components work together. -The VRF produces two outputs: a result (the random number) and a proof (verifying that the number was generated correctly). +!!!note + If you've already compiled the Polkadot SDK in the previous step, the `substrate-node` binary is already built and ready to use. You can skip directly to running the node. -The result is checked by the validator against a protocol threshold. If it's below the threshold, the validator becomes a candidate for block production in that slot. +### Run the Kitchensink Node in Development Mode -The validator then attempts to create a block, submitting it along with the `PROOF` and `RESULT`. +From the `polkadot-sdk` root directory, start the kitchensink node in development mode: -So, VRF can be expressed like: +```bash +./target/release/substrate-node --dev +``` -`(RESULT, PROOF) = VRF(SECRET, EPOCH_RANDOMNESS_VALUE, CURRENT_SLOT_NUMBER)` +The `--dev` flag enables development mode, which: -Put simply, performing a "VRF roll" generates a random number along with proof that the number was genuinely produced and not arbitrarily chosen. +- Runs a single-node development chain. +- Produces and finalizes blocks automatically. +- Uses pre-configured development accounts (Alice, Bob, etc.). +- Deletes all data when stopped, ensuring a clean state on restart. -After executing the VRF, the `RESULT` is compared to a protocol-defined `THRESHOLD`. If the `RESULT` is below the `THRESHOLD`, the validator becomes a valid candidate to propose a block for that slot. Otherwise, the validator skips the slot. -As a result, there may be multiple validators eligible to propose a block for a slot. In this case, the block accepted by other nodes will prevail, provided it is on the chain with the latest finalized block as determined by the GRANDPA finality gadget. It's also possible for no block producers to be available for a slot, in which case the AURA consensus takes over. AURA is a fallback mechanism that randomly selects a validator to produce a block, running in parallel with BABE and only stepping in when no block producers exist for a slot. Otherwise, it remains inactive. +You should see log output indicating the node is running and producing blocks, with increasing block numbers after `finalized`. -Because validators roll independently, no block candidates may appear in some slots if all roll numbers are above the threshold. +### Interact with the Kitchensink Node -To verify resolution of this issue and that Polkadot block times remain near constant-time, see the [PoS Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} page of this documentation. +The kitchensink node is accessible at `ws://localhost:9944`. Open [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} in your browser to explore its features and connect to the local node. -## RANDAO +1. Click the network icon in the top left corner. +2. Scroll to **Development** and select **Local Node**. +3. Click **Switch** to connect to your local node. -An alternative on-chain randomness method is Ethereum's RANDAO, where validators perform thousands of hashes on a seed and publish the final hash during a round. The collective input from all validators forms the random number, and as long as one honest validator participates, the randomness is secure. +![](/images/parachains/install-polkadot-sdk/install-polkadot-sdk-1.webp) -To enhance security, RANDAO can optionally be combined with a Verifiable Delay Function (VDF), ensuring that randomness can't be predicted or manipulated during computation. +Once connected, the interface updates its color scheme to indicate a successful connection to the local node. -For more information about RANDAO, see the [Randomness - RANDAO](https://eth2book.info/capella/part2/building_blocks/randomness/){target=\_blank} section of the Upgrading Ethereum documentation. +![](/images/parachains/install-polkadot-sdk/install-polkadot-sdk-2.webp) -## VDFs +You can now explore the various pallets and features included in the kitchensink node, making it a valuable reference as you develop your own blockchain applications. -Verifiable Delay Functions (VDFs) are time-bound computations that, even on parallel computers, take a set amount of time to complete. +To stop the node, press `Control-C` in the terminal. -They produce a unique result that can be quickly verified publicly. When combined with RANDAO, feeding RANDAO's output into a VDF introduces a delay that nullifies an attacker's chance to influence the randomness. +## Where to Go Next -However, VDF likely requires specialized ASIC devices to run separately from standard nodes. +
-!!!warning - While only one is needed to secure the system, and they will be open-source and inexpensive, running VDF devices involves significant costs without direct incentives, adding friction for blockchain users. +- __Get Started with Parachain Development__ -## Additional Resources + --- -For more information about the reasoning for choices made along with proofs, see Polkadot's research on blockchain randomness and sortition in the [Block production](https://research.web3.foundation/Polkadot/protocols/block-production){target=\_blank} entry of the Polkadot Wiki. + Practical examples and tutorials for building and deploying Polkadot parachains, covering everything from launch to customization and cross-chain messaging. -For a discussion with Web3 Foundation researchers about when and under what conditions Polkadot's randomness can be utilized, see the [Discussion on Randomness used in Polkadot](https://github.com/use-ink/ink/issues/57){target=\_blank} issue on GitHub. + [:octicons-arrow-right-24: Get Started](/parachains/get-started/) + +
--- -Page Title: Register a Foreign Asset on Asset Hub +Page Title: JSON-RPC APIs -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-token-operations-register-foreign-asset.md -- Canonical (HTML): https://docs.polkadot.com/chain-interactions/token-operations/register-foreign-asset/ -- Summary: An in-depth guide to registering a foreign asset on the Asset Hub parachain, providing clear, step-by-step instructions. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-json-rpc-apis.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/json-rpc-apis/ +- Summary: JSON-RPC APIs guide for Polkadot Hub, covering supported methods, parameters, and examples for interacting with the chain. -# Register a Foreign Asset on Asset Hub +# JSON-RPC APIs +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. ## Introduction -As outlined in the [Asset Hub Overview](/polkadot-protocol/architecture/system-chains/asset-hub){target=\_blank}, Asset Hub supports two categories of assets: local and foreign. Local assets are created on the Asset Hub system parachain and are identified by integer IDs. On the other hand, foreign assets, which originate outside of Asset Hub, are recognized by [Multilocations](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#7-universal-consensus-location-identifiers){target=\_blank}. - -When registering a foreign asset on Asset Hub, it's essential to notice that the process involves communication between two parachains. The Asset Hub parachain will be the destination of the foreign asset, while the source parachain will be the origin of the asset. The communication between the two parachains is facilitated by the [Cross-Chain Message Passing (XCMP)](/parachains/interoperability/get-started/){target=\_blank} protocol. +Polkadot Hub provides Ethereum compatibility through its JSON-RPC interface, allowing developers to interact with the chain using familiar Ethereum tooling and methods. This document outlines the supported [Ethereum JSON-RPC methods](https://ethereum.org/developers/docs/apis/json-rpc/#json-rpc-methods){target=\_blank} and provides examples of how to use them. -This guide will take you through the process of registering a foreign asset on the Asset Hub parachain. +This guide uses the Polkadot Hub TestNet endpoint: -## Prerequisites +```text +https://testnet-passet-hub-eth-rpc.polkadot.io +``` -The Asset Hub parachain is one of the system parachains on a relay chain, such as [Polkadot](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fpolkadot.api.onfinality.io%2Fpublic-ws#/explorer){target=\_blank} or [Kusama](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fkusama.api.onfinality.io%2Fpublic-ws#/explorer){target=\_blank}. To interact with these parachains, you can use the [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} interface for: +## Available Methods -- [Polkadot Asset Hub](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fasset-hub-polkadot-rpc.dwellir.com#/explorer){target=\_blank} -- [Kusama Asset Hub](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fsys.ibp.network%2Fstatemine#/explorer){target=\_blank} +### eth_accounts -For testing purposes, you can also interact with the Asset Hub instance on the following test networks: +Returns a list of addresses owned by the client. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_accounts){target=\_blank}. -- [Paseo Asset Hub](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fpas-rpc.stakeworld.io%2Fassethub#/explorer){target=\_blank} +**Parameters**: -Before you start, ensure that you have: +None. -- Access to the Polkadot.js Apps interface, and you are connected to the desired chain. -- A parachain that supports the XCMP protocol to interact with the Asset Hub parachain. -- A funded wallet to pay for the transaction fees and subsequent registration of the foreign asset. +**Example**: -This guide will use Polkadot, its local Asset Hub instance, and the [Astar](https://astar.network/){target=\_blank} parachain (`ID` 2006), as stated in the [Test Environment Setup](#test-environment-setup) section. However, the process is the same for other relay chains and their respective Asset Hub parachain, regardless of the network you are using and the parachain owner of the foreign asset. +```bash title="eth_accounts" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_accounts", + "params":[], + "id":1 +}' +``` -## Steps to Register a Foreign Asset +--- -### Asset Hub +### eth_blockNumber -1. Open the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and connect to the Asset Hub parachain using the network selector in the top left corner. +Returns the number of the most recent block. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_blocknumber){target=\_blank}. - - Testing foreign asset registration is recommended on TestNet before proceeding to MainNet. If you haven't set up a local testing environment yet, consult the [Environment setup](#test-environment-setup) guide. After setting up, connect to the Local Node (Chopsticks) at `ws://127.0.0.1:8000`. - - For live network operations, connect to the Asset Hub parachain. You can choose either Polkadot or Kusama Asset Hub from the dropdown menu, selecting your preferred RPC provider. +**Parameters**: -2. Navigate to the **Extrinsics** page: +None. - 1. Click on the **Developer** tab from the top navigation bar. - 2. Select **Extrinsics** from the dropdown. +**Example**: - ![Access to Developer Extrinsics section](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-01.webp) +```bash title="eth_blockNumber" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_blockNumber", + "params":[], + "id":1 +}' +``` -3. Select the Foreign Assets pallet: +--- - 3. Select the **`foreignAssets`** pallet from the dropdown list. - 4. Choose the **`create`** extrinsic. +### eth_call - ![Select the Foreign Asset pallet](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-02.webp) +Executes a new message call immediately without creating a transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_call){target=\_blank}. -3. Fill out the required fields and click on the copy icon to copy the **encoded call data** to your clipboard. The fields to be filled are: +**Parameters**: - - **id**: As this is a foreign asset, the ID will be represented by a Multilocation that reflects its origin. For this case, the Multilocation of the asset will be from the source parachain perspective. - - ```javascript - { parents: 1, interior: { X1: [{ Parachain: 2006 }] } } - ``` +- **`transaction` ++"object"++**: The transaction call object. + - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - - **admin**: Refers to the account that will be the admin of this asset. This account will be able to manage the asset, including updating its metadata. As the registered asset corresponds to a native asset of the source parachain, the admin account should be the sovereign account of the source parachain. - - The sovereign account can be obtained through [Substrate Utilities](https://www.shawntabrizi.com/substrate-js-utilities/){target=\_blank}. +**Example**: - Ensure that **Sibling** is selected and that the **Para ID** corresponds to the source parachain. In this case, since the guide follows the test setup stated in the [Test Environment Setup](#test-environment-setup) section, the **Para ID** is `2006`. +```bash title="eth_call" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_call", + "params":[{ + "to": "INSERT_RECIPIENT_ADDRESS", + "data": "INSERT_ENCODED_CALL" + }, "INSERT_BLOCK_VALUE"], + "id":1 +}' +``` - ![Get parachain sovereign account](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-03.webp) +Ensure to replace the `INSERT_RECIPIENT_ADDRESS`, `INSERT_ENCODED_CALL`, and `INSERT_BLOCK_VALUE` with the proper values. +--- - - **`minBalance`**: The minimum balance required to hold this asset. +### eth_chainId - ![Fill out the required fields](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-04.webp) +Returns the chain ID used for signing transactions. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_chainid){target=\_blank}. - !!! tip - If you need an example of the encoded call data, you can copy the following: - ``` - 0x3500010100591f007369626cd6070000000000000000000000000000000000000000000000000000a0860100000000000000000000000000 - ``` +**Parameters**: -### Source Parachain +None. -1. Navigate to the **Developer > Extrinsics** section. -2. Create the extrinsic to register the foreign asset through XCM: +**Example**: - 1. Paste the **encoded call data** copied in the previous step. - 2. Click the **Submit Transaction** button. +```bash title="eth_chainId" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_chainId", + "params":[], + "id":1 +}' +``` - ![Register foreign asset through XCM](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-05.webp) +--- - This XCM call involves withdrawing DOT from the sibling account of the parachain, using it to initiate an execution. The transaction will be carried out with XCM as the origin kind, and will be a hex-encoded call to create a foreign asset on Asset Hub for the specified parachain asset multilocation. Any surplus will be refunded, and the asset will be deposited into the sibling account. +### eth_estimateGas - !!! warning - Note that the sovereign account on the Asset Hub parachain must have a sufficient balance to cover the XCM `BuyExecution` instruction. If the account does not have enough balance, the transaction will fail. +Estimates gas required for a transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_estimategas){target=\_blank}. - If you want to have the whole XCM call ready to be copied, go to the **Developer > Extrinsics > Decode** section and paste the following hex-encoded call data: +**Parameters**: - ```text - 0x6300330003010100a10f030c000400010000070010a5d4e81300010000070010a5d4e80006030700b4f13501419ce03500010100591f007369626cd607000000000000000000000000000000000000000000000000000000000000000000000000000000000000 - ``` +- **`transaction` ++"object"++**: The transaction call object. + - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - Be sure to replace the encoded call data with the one you copied in the previous step. +**Example**: -After the transaction is successfully executed, the foreign asset will be registered on the Asset Hub parachain. +```bash title="eth_estimateGas" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_estimateGas", + "params":[{ + "to": "INSERT_RECIPIENT_ADDRESS", + "data": "INSERT_ENCODED_FUNCTION_CALL" + }], + "id":1 +}' +``` -## Asset Registration Verification +Ensure to replace the `INSERT_RECIPIENT_ADDRESS` and `INSERT_ENCODED_CALL` with the proper values. -To confirm that a foreign asset has been successfully accepted and registered on the Asset Hub parachain, you can navigate to the `Network > Explorer` section of the Polkadot.js Apps interface for Asset Hub. You should be able to see an event that includes the following details: +--- -![Asset registration event](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-06.webp) +### eth_gasPrice -In the image above, the **success** field indicates whether the asset registration was successful. +Returns the current gas price in Wei. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gasprice){target=\_blank}. -## Test Environment Setup +**Parameters**: -To test the foreign asset registration process before deploying it on a live network, you can set up a local parachain environment. This guide uses Chopsticks to simulate that process. For more information on using Chopsticks, please refer to the [Chopsticks documentation](/develop/toolkit/parachains/fork-chains/chopsticks/get-started){target=\_blank}. +None. -To set up a test environment, run the following command: +**Example**: -```bash -npx @acala-network/chopsticks xcm \ ---r polkadot \ ---p polkadot-asset-hub \ ---p astar +```bash title="eth_gasPrice" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_gasPrice", + "params":[], + "id":1 +}' ``` -The preceding command will create a lazy fork of Polkadot as the relay chain, its Asset Hub instance, and the Astar parachain. The `xcm` parameter enables communication through the XCMP protocol between the relay chain and the parachains, allowing the registration of foreign assets on Asset Hub. For further information on the chopsticks usage of the XCMP protocol, refer to the [XCM Testing](/tutorials/polkadot-sdk/testing/fork-live-chains/#xcm-testing){target=\_blank} section of the Chopsticks documentation. - -After executing the command, the terminal will display output indicating the Polkadot relay chain, the Polkadot Asset Hub, and the Astar parachain are running locally and connected through XCM. You can access them individually via the Polkadot.js Apps interface. - -- [Polkadot Relay Chain](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Flocalhost%3A8002#/explorer){target=\_blank} -- [Polkadot Asset Hub](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Flocalhost%3A8000#/explorer){target=\_blank} -- [Astar Parachain](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Flocalhost%3A8001#/explorer){target=\_blank} - - --- -Page Title: Register a Local Asset +### eth_getBalance + +Returns the balance of a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getbalance){target=\_blank}. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-token-operations-register-local-asset.md -- Canonical (HTML): https://docs.polkadot.com/chain-interactions/token-operations/register-local-asset/ -- Summary: Comprehensive guide to registering a local asset on the Asset Hub system parachain, including step-by-step instructions. +**Parameters**: -# Register a Local Asset on Asset Hub +- **`address` ++"string"++**: Address to query balance. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -## Introduction +**Example**: -As detailed in the [Asset Hub Overview](/polkadot-protocol/architecture/system-chains/asset-hub){target=\_blank} page, Asset Hub accommodates two types of assets: local and foreign. Local assets are those that were created in Asset Hub and are identifiable by an integer ID. On the other hand, foreign assets originate from a sibling parachain and are identified by a Multilocation. +```bash title="eth_getBalance" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getBalance", + "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], + "id":1 +}' +``` -This guide will take you through the steps of registering a local asset on the Asset Hub parachain. +Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. -## Prerequisites +--- -Before you begin, ensure you have access to the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and a funded wallet with DOT or KSM. +### eth_getBlockByHash -- For Polkadot Asset Hub, you would need a deposit of 10 DOT and around 0.201 DOT for the metadata. -- For Kusama Asset Hub, the deposit is 0.1 KSM and around 0.000669 KSM for the metadata. +Returns information about a block by its hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblockbyhash){target=\_blank}. -You need to ensure that your Asset Hub account balance is a bit more than the sum of those two deposits, which should seamlessly account for the required deposits and transaction fees. +**Parameters**: -## Steps to Register a Local Asset +- **`blockHash` ++"string"++**: The hash of the block to retrieve. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`fullTransactions` ++"boolean"++**: If `true`, returns full transaction details; if `false`, returns only transaction hashes. -To register a local asset on the Asset Hub parachain, follow these steps: +**Example**: -1. Open the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and connect to the Asset Hub parachain using the network selector in the top left corner. +```bash title="eth_getBlockByHash" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getBlockByHash", + "params":["INSERT_BLOCK_HASH", INSERT_BOOLEAN], + "id":1 +}' +``` - - You may prefer to test local asset registration on TestNet before registering the asset on a MainNet hub. If you still need to set up a local testing environment, review the [Environment setup](#test-setup-environment) section for instructions. Once the local environment is set up, connect to the Local Node (Chopsticks) available on `ws://127.0.0.1:8000`. - - For the live network, connect to the **Asset Hub** parachain. Either Polkadot or Kusama Asset Hub can be selected from the dropdown list, choosing the desired RPC provider. +Ensure to replace the `INSERT_BLOCK_HASH` and `INSERT_BOOLEAN` with the proper values. -2. Click on the **Network** tab on the top navigation bar and select **Assets** from the dropdown list. +--- - ![Access to Asset Hub through Polkadot.JS](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-01.webp) +### eth_getBlockByNumber -3. Now, you need to examine all the registered asset IDs. This step is crucial to ensure that the asset ID you are about to register is unique. Asset IDs are displayed in the **assets** column. +Returns information about a block by its number. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblockbynumber){target=\_blank}. - ![Asset IDs on Asset Hub](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-02.webp) +**Parameters**: -4. Once you have confirmed that the asset ID is unique, click on the **Create** button on the top right corner of the page. +- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. +- **`fullTransactions` ++"boolean"++**: If `true`, returns full transaction details; if `false`, returns only transaction hashes. - ![Create a new asset](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-03.webp) +**Example**: -5. Fill in the required fields in the **Create Asset** form: +```bash title="eth_getBlockByNumber" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getBlockByNumber", + "params":["INSERT_BLOCK_VALUE", INSERT_BOOLEAN], + "id":1 +}' +``` - 1. **creator account**: The account to be used for creating this asset and setting up the initial metadata. - 2. **asset name**: The descriptive name of the asset you are registering. - 3. **asset symbol**: The symbol that will be used to represent the asset. - 4. **asset decimals**: The number of decimal places for this token, with a maximum of 20 allowed through the user interface. - 5. **minimum balance**: The minimum balance for the asset. This is specified in the units and decimals as requested. - 6. **asset ID**: The selected id for the asset. This should not match an already-existing asset id. - 7. Click on the **Next** button. - - ![Create Asset Form](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-04.webp) +Ensure to replace the `INSERT_BLOCK_VALUE` and `INSERT_BOOLEAN` with the proper values. -6. Choose the accounts for the roles listed below: +--- - 1. **admin account**: The account designated for continuous administration of the token. - 2. **issuer account**: The account that will be used for issuing this token. - 3. **freezer account**: The account that will be used for performing token freezing operations. - 4. Click on the **Create** button. +### eth_getBlockTransactionCountByNumber - ![Admin, Issuer, Freezer accounts](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-05.webp) +Returns the number of transactions in a block from a block number. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber){target=\_blank}. -7. Click on the **Sign and Submit** button to complete the asset registration process. +**Parameters**: - ![Sign and Submit](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-06.webp) +- **`blockValue` ++"string"++**: The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -## Verify Asset Registration +**Example**: -After completing these steps, the asset will be successfully registered. You can now view your asset listed on the [**Assets**](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fasset-hub-polkadot-rpc.dwellir.com#/assets){target=\_blank} section of the Polkadot.js Apps interface. +```bash title="eth_getBlockTransactionCountByNumber" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getBlockTransactionCountByNumber", + "params":["INSERT_BLOCK_VALUE"], + "id":1 +}' +``` -![Asset listed on Polkadot.js Apps](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-07.webp) +Ensure to replace the `INSERT_BLOCK_VALUE` with the proper values. -!!! tip - Take into consideration that the **Assets** section’s link may differ depending on the network you are using. For the local environment, enter `ws://127.0.0.1:8000` into the **Custom Endpoint** field. +--- -In this way, you have successfully registered a local asset on the Asset Hub parachain. +### eth_getBlockTransactionCountByHash -For an in-depth explanation about Asset Hub and its features, see the [Asset Hub](/chain-interactions/token-operations/convert-assets/){target=\_blank} entry in the Polkadot Wiki. +Returns the number of transactions in a block from a block hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash){target=\_blank}. -## Test Setup Environment +**Parameters**: -You can set up a local parachain environment to test the asset registration process before deploying it on the live network. This guide uses Chopsticks to simulate that process. For further information on chopsticks usage, refer to the [Chopsticks](/develop/toolkit/parachains/fork-chains/chopsticks/get-started){target=\_blank} documentation. +- **`blockHash` ++"string"++**: The hash of the block to retrieve. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -To set up a test environment, execute the following command: +**Example**: -```bash -npx @acala-network/chopsticks \ ---config=https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/polkadot-asset-hub.yml +```bash title="eth_getBlockTransactionCountByHash" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getBlockTransactionCountByHash", + "params":["INSERT_BLOCK_HASH"], + "id":1 +}' ``` -The above command will spawn a lazy fork of Polkadot Asset Hub with the latest block data from the network. If you need to test Kusama Asset Hub, replace `polkadot-asset-hub.yml` with `kusama-asset-hub.yml` in the command. - -An Asset Hub instance is now running locally, and you can proceed with the asset registration process. Note that the local registration process does not differ from the live network process. Once you have a successful TestNet transaction, you can use the same steps to register the asset on MainNet. - +Ensure to replace the `INSERT_BLOCK_HASH` with the proper values. --- -Page Title: Set Up the Polkadot SDK Parachain Template - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-launch-a-parachain-set-up-the-parachain-template.md -- Canonical (HTML): https://docs.polkadot.com/parachains/launch-a-parachain/set-up-the-parachain-template/ -- Summary: Learn how to set up and run the Polkadot SDK Parachain Template locally, creating a ready-to-customize foundation for your parachain. - -# Set Up the Polkadot SDK Parachain Template - -## Introduction - -The [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank} includes several [templates](/parachains/customize-runtime/#starting-templates){target=\_blank} designed to help you quickly start building your own blockchain. Each template offers a different level of configuration, from minimal setups to feature-rich environments, allowing you to choose the foundation that best fits your project's needs. +### eth_getCode -Among these, the [Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank} provides a preconfigured runtime with commonly used pallets, making it an ideal starting point for most parachain development projects. +Returns the code at a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getcode){target=\_blank}. -This guide walks you through the full process of working with this template. You will: +**Parameters**: -- Set up the Polkadot SDK Parachain Template. -- Understand the project structure and key components. -- Verify your template is ready for development. -- Run the parachain template locally in development mode. +- **`address` ++"string"++**: Contract or account address to query code. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). -By the end of this guide, you'll have a working template ready to customize and deploy as a parachain. +**Example**: -## Prerequisites +```bash title="eth_getCode" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getCode", + "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], + "id":1 +}' +``` -Before getting started, ensure you have done the following: +Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. -- Completed the [Install Polkadot SDK](/parachains/install-polkadot-sdk/){target=\_blank} guide and successfully installed [Rust](https://www.rust-lang.org/){target=\_blank} and the required packages to set up your development environment. +--- -For this tutorial series, you need to use Rust `1.86`. Newer versions of the compiler may not work with this parachain template version. +### eth_getLogs -Run the following commands to set up the correct Rust version: +Returns an array of all logs matching a given filter object. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getlogs){target=\_blank}. -=== "macOS" +**Parameters**: - ```bash - rustup install 1.86 - rustup default 1.86 - rustup target add wasm32-unknown-unknown --toolchain 1.86-aarch64-apple-darwin - rustup component add rust-src --toolchain 1.86-aarch64-apple-darwin - ``` +- **`filter` ++"object"++**: The filter object. + - **`fromBlock` ++"string"++**: (Optional) Block number or tag to start from. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. + - **`toBlock` ++"string"++**: (Optional) Block number or tag to end at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. + - **`address` ++"string" or "array of strings"++**: (Optional) Contract address or a list of addresses from which to get logs. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`topics` ++"array of strings"++**: (Optional) Array of topics for filtering logs. Each topic can be a single [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string or an array of such strings (meaning OR). + - **`blockhash` ++"string"++**: (Optional) Hash of a specific block. Cannot be used with `fromBlock` or `toBlock`. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -=== "Ubuntu" +**Example**: - ```bash - rustup toolchain install 1.86.0 - rustup default 1.86.0 - rustup target add wasm32-unknown-unknown --toolchain 1.86.0 - rustup component add rust-src --toolchain 1.86.0 - ``` +```bash title="eth_getLogs" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getLogs", + "params":[{ + "fromBlock": "latest", + "toBlock": "latest" + }], + "id":1 +}' +``` -## Polkadot SDK Utility Tools +--- -This tutorial requires two essential tools: +### eth_getStorageAt -- [**Chain spec builder**](https://crates.io/crates/staging-chain-spec-builder/10.0.0){target=\_blank}: A Polkadot SDK utility for generating chain specifications. Refer to the [Generate Chain Specs](/develop/parachains/deployment/generate-chain-specs/){target=\_blank} documentation for detailed usage. - - Install it by executing the following command: - - ```bash - cargo install --locked staging-chain-spec-builder@10.0.0 - ``` +Returns the value from a storage position at a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getstorageat){target=\_blank}. - This command installs the `chain-spec-builder` binary. +**Parameters**: -- [**Polkadot Omni Node**](https://crates.io/crates/polkadot-omni-node/0.5.0){target=\_blank}: A white-labeled binary, released as a part of Polkadot SDK that can act as the collator of a parachain in production, with all the related auxiliary functionalities that a normal collator node has: RPC server, archiving state, etc. Moreover, it can also run the Wasm blob of the parachain locally for testing and development. +- **`address` ++"string"++**: Contract or account address to query code. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`storageKey` ++"string"++**: Position in storage to retrieve data from. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). - To install it, run the following command: +**Example**: - ```bash - cargo install --locked polkadot-omni-node@0.5.0 - ``` +```bash title="eth_getStorageAt" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getStorageAt", + "params":["INSERT_ADDRESS", "INSERT_STORAGE_KEY", "INSERT_BLOCK_VALUE"], + "id":1 +}' +``` - This command installs the `polkadot-omni-node` binary. +Ensure to replace the `INSERT_ADDRESS`, `INSERT_STORAGE_KEY`, and `INSERT_BLOCK_VALUE` with the proper values. -## Clone the Template +--- -The [Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank} provides a ready-to-use development environment for building with the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}. Follow these steps to set up the template: +### eth_getTransactionCount -1. Clone the template repository: +Returns the number of transactions sent from an address (nonce). [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactioncount){target=\_blank}. - ```bash - git clone https://github.com/paritytech/polkadot-sdk-parachain-template.git parachain-template - ``` +**Parameters**: -2. Navigate into the project directory: +- **`address` ++"string"++**: Address to query balance. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). - ```bash - cd parachain-template - ``` +**Example**: -## Explore the Project Structure +```bash title="eth_getTransactionCount" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getTransactionCount", + "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], + "id":1 +}' +``` -Before building the template, take a moment to familiarize yourself with its structure. Understanding this organization will help you navigate the codebase as you develop your parachain. +Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. -The template follows a standard Polkadot SDK project layout: +--- -```text -parachain-template/ -├── node/ # Node implementation and client -├── pallets/ # Custom pallets for your parachain -├── runtime/ # Runtime configuration and logic -├── Cargo.toml # Workspace configuration -└── README.md # Documentation -``` +### eth_getTransactionByHash -Key directories explained: +Returns information about a transaction by its hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyhash){target=\_blank}. -- **runtime/**: Contains your parachain's state transition function and pallet configuration. This is where you'll define what your blockchain can do. -- **node/**: Houses the client implementation that runs your blockchain, handles networking, and manages the database. -- **pallets/**: Where you'll create custom business logic modules (pallets) for your specific use case. -- **Cargo.toml**: The workspace configuration that ties all components together. +**Parameters**: -!!!note - The runtime is compiled to WebAssembly (Wasm), enabling forkless upgrades. The node binary remains constant while the runtime can be updated on-chain. +- **`transactionHash` ++"string"++**: The hash of the transaction. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -## Compile the Runtime +**Example**: -Now that you understand the template structure, let's compile the runtime to ensure everything is working correctly. +```bash title="eth_getTransactionByHash" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getTransactionByHash", + "params":["INSERT_TRANSACTION_HASH"], + "id":1 +}' +``` -1. Compile the runtime: +Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper values. - ```bash - cargo build --release --locked - ``` +--- - !!!tip - Initial compilation may take several minutes, depending on your machine specifications. Use the `--release` flag for improved runtime performance compared to the default `--debug` build. If you need to troubleshoot issues, the `--debug` build provides better diagnostics. - - For production deployments, consider using a dedicated `--profile production` flag - this can provide an additional 15-30% performance improvement over the standard `--release` profile. +### eth_getTransactionByBlockNumberAndIndex -2. Upon successful compilation, you should see output indicating the build was successful. The compiled runtime will be located at: - - `./target/release/wbuild/parachain-template-runtime/parachain_template_runtime.compact.compressed.wasm` +Returns information about a transaction by block number and transaction index. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyblocknumberandindex){target=\_blank}. -## Verify the Build +**Parameters**: -After compilation completes, verify that the runtime was created successfully by checking for the Wasm blob: +- **`blockValue` ++"string"++**: The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. +- **`transactionIndex` ++"string"++**: The index of the transaction in the block. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -```bash -ls -la ./target/release/wbuild/parachain-template-runtime/ +**Example**: + +```bash title="eth_getTransactionByBlockNumberAndIndex" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getTransactionByBlockNumberAndIndex", + "params":["INSERT_BLOCK_VALUE", "INSERT_TRANSACTION_INDEX"], + "id":1 +}' ``` -You should see the `parachain_template_runtime.compact.compressed.wasm` file in the output, confirming the build was successful. +Ensure to replace the `INSERT_BLOCK_VALUE` and `INSERT_TRANSACTION_INDEX` with the proper values. -## Run the Node Locally +--- -After successfully compiling your runtime, you can spin up a local chain and produce blocks. This process will start your local parachain using the Polkadot Omni Node and allow you to interact with it. You'll first need to generate a chain specification that defines your network's identity, initial connections, and genesis state, providing the foundational configuration for how your nodes connect and what initial state they agree upon. +### eth_getTransactionByBlockHashAndIndex -Follow these steps to launch your node in development mode: +Returns information about a transaction by block hash and transaction index. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyblockhashandindex){target=\_blank}. -1. Generate the chain specification file of your parachain: +**Parameters**: - ```bash - chain-spec-builder create -t development \ - --relay-chain paseo \ - --para-id 1000 \ - --runtime ./target/release/wbuild/parachain-template-runtime/parachain_template_runtime.compact.compressed.wasm \ - named-preset development - ``` +- **`blockHash` ++"string"++**: The hash of the block. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`transactionIndex` ++"string"++**: The index of the transaction in the block. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -2. Start the Omni Node with the generated chain spec. You'll start it in development mode (without a relay chain config), producing and finalizing blocks: +**Example**: - ```bash - polkadot-omni-node --chain ./chain_spec.json --dev - ``` +```bash title="eth_getTransactionByBlockHashAndIndex" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getTransactionByBlockHashAndIndex", + "params":["INSERT_BLOCK_HASH", "INSERT_TRANSACTION_INDEX"], + "id":1 +}' +``` - The `--dev` option does the following: +Ensure to replace the `INSERT_BLOCK_HASH` and `INSERT_TRANSACTION_INDEX` with the proper values. - - Deletes all active data (keys, blockchain database, networking information) when stopped. - - Ensures a clean working state each time you restart the node. +--- -3. Verify that your node is running by reviewing the terminal output. You should see log messages indicating block production and finalization. +### eth_getTransactionReceipt -4. Confirm that your blockchain is producing new blocks by checking if the number after `finalized` is increasing in the output. +Returns the receipt of a transaction by transaction hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionreceipt){target=\_blank}. -The details of the log output will be explored in a later tutorial. For now, knowing that your node is running and producing blocks is sufficient. +**Parameters**: -## Interact with the Node +- **`transactionHash` ++"string"++**: The hash of the transaction. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -When running the template node, it's accessible by default at `ws://localhost:9944`. To interact with your node using the [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} interface, follow these steps: +**Example**: -1. Open [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} in your web browser and click the network icon (which should be the Polkadot logo) in the top left corner: - - ![](/images/parachains/launch-a-parachain/set-up-the-parachain-template/parachain-template-01.webp) +```bash title="eth_getTransactionReceipt" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getTransactionReceipt", + "params":["INSERT_TRANSACTION_HASH"], + "id":1 +}' +``` -2. Connect to your local node: +Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper values. - 1. Scroll to the bottom and select **Development**. - 2. Choose **Custom**. - 3. Enter `ws://localhost:9944` in the **custom endpoint** input field. - 4. Click the **Switch** button. - - ![](/images/parachains/launch-a-parachain/set-up-the-parachain-template/parachain-template-02.webp) +--- -3. Once connected, you should see **parachain-template-runtime** in the top left corner, with the interface displaying information about your local blockchain. - - ![](/images/parachains/launch-a-parachain/set-up-the-parachain-template/parachain-template-03.webp) +### eth_maxPriorityFeePerGas -You are now connected to your local node and can interact with it through the Polkadot.js Apps interface. This tool enables you to explore blocks, execute transactions, and interact with your blockchain's features. For in-depth guidance on using the interface effectively, refer to the [Polkadot.js Guides](https://wiki.polkadot.com/general/polkadotjs/){target=\_blank} available on the Polkadot Wiki. +Returns an estimate of the current priority fee per gas, in Wei, to be included in a block. -## Stop the Node +**Parameters**: -When you're done exploring your local node, you can stop it to remove any state changes you've made. Since you started the node with the `--dev` option, stopping the node will purge all persistent block data, allowing you to start fresh the next time. +None. -To stop the local node: +**Example**: -1. Return to the terminal window where the node output is displayed. -2. Press `Control-C` to stop the running process. -3. Verify that your terminal returns to the prompt in the `parachain-template` directory. +```bash title="eth_maxPriorityFeePerGas" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_maxPriorityFeePerGas", + "params":[], + "id":1 +}' +``` -## Where to Go Next +--- -
+### eth_sendRawTransaction -- Tutorial __Deploy to Polkadot__ +Submits a raw transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_sendrawtransaction){target=\_blank}. - --- +**Parameters**: - Learn how to deploy your parachain template to a relay chain testnet. Configure your chain specification, register as a parachain, and start producing blocks. +- **`callData` ++"string"++**: Signed transaction data. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - [:octicons-arrow-right-24: Get Started](/parachains/launch-a-parachain/deploy-to-polkadot.md) +**Example**: -
+```bash title="eth_sendRawTransaction" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_sendRawTransaction", + "params":["INSERT_CALL_DATA"], + "id":1 +}' +``` +Ensure to replace the `INSERT_CALL_DATA` with the proper values. --- -Page Title: Sidecar REST API - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-sidecar.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/sidecar/ -- Summary: Learn about Substrate API Sidecar, a REST service that provides endpoints for interacting with Polkadot SDK-based chains and simplifies blockchain interactions. +### eth_sendTransaction -# Sidecar API +Creates and sends a new transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_sendtransaction){target=\_blank}. -## Introduction +**Parameters**: -The [Sidecar REST API](https://github.com/paritytech/substrate-api-sidecar){target=\_blank} is a service that provides a REST interface for interacting with Polkadot SDK-based blockchains. With this API, developers can easily access a broad range of endpoints for nodes, accounts, transactions, parachains, and more. +- **`transaction` ++"object"++**: The transaction object. + - **`from` ++"string"++**: Address sending the transaction. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`to` ++"string"++**: (Optional) Recipient address. No need to provide this value when deploying a contract. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`gas` ++"string"++**: (optional, default: `90000`) gas limit for execution. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`gasPrice` ++"string"++**: (Optional) Gas price per unit. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`value` ++"string"++**: (Optional) Amount of Ether to send. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`data` ++"string"++**: (Optional) Contract bytecode or encoded method call. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`nonce` ++"string"++**: (Optional) Transaction nonce. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -Sidecar functions as a caching layer between your application and a Polkadot SDK-based node, offering standardized REST endpoints that simplify interactions without requiring complex, direct RPC calls. This approach is especially valuable for developers who prefer REST APIs or build applications in languages with limited WebSocket support. +**Example**: -Some of the key features of the Sidecar API include: +```bash title="eth_sendTransaction" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_sendTransaction", + "params":[{ + "from": "INSERT_SENDER_ADDRESS", + "to": "INSERT_RECIPIENT_ADDRESS", + "gas": "INSERT_GAS_LIMIT", + "gasPrice": "INSERT_GAS_PRICE", + "value": "INSERT_VALUE", + "input": "INSERT_INPUT_DATA", + "nonce": "INSERT_NONCE" + }], + "id":1 +}' +``` -- **REST API interface**: Provides a familiar REST API interface for interacting with Polkadot SDK-based chains. -- **Standardized endpoints**: Offers consistent endpoint formats across different chain implementations. -- **Caching layer**: Acts as a caching layer to improve performance and reduce direct node requests. -- **Multiple chain support**: Works with any Polkadot SDK-based chain, including Polkadot, Kusama, and custom chains. +Ensure to replace the `INSERT_SENDER_ADDRESS`, `INSERT_RECIPIENT_ADDRESS`, `INSERT_GAS_LIMIT`, `INSERT_GAS_PRICE`, `INSERT_VALUE`, `INSERT_INPUT_DATA`, and `INSERT_NONCE` with the proper values. -## Prerequisites +--- -Sidecar API requires Node.js version 18.14 LTS or higher. Verify your Node.js version: +### eth_syncing -```bash -node --version -``` +Returns an object with syncing data or `false` if not syncing. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_syncing){target=\_blank}. -If you need to install or update Node.js, visit the [official Node.js website](https://nodejs.org/){target=\_blank} to download and install the latest LTS version. +**Parameters**: -## Installation +None. -To install Substrate API Sidecar, use one of the following commands: +**Example**: -=== "npm" +```bash title="eth_syncing" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_syncing", + "params":[], + "id":1 +}' +``` - ```bash - npm install -g @substrate/api-sidecar - ``` +--- -=== "pnpm" +### net_listening - ```bash - pnpm install -g @substrate/api-sidecar - ``` +Returns `true` if the client is currently listening for network connections, otherwise `false`. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#net_listening){target=\_blank}. -=== "yarn" +**Parameters**: - ```bash - yarn global add @substrate/api-sidecar - ``` +None. -You can confirm the installation by running: +**Example**: -```bash -substrate-api-sidecar --version +```bash title="net_listening" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"net_listening", + "params":[], + "id":1 +}' ``` -For more information about the Sidecar API installation, see the [installation and usage](https://github.com/paritytech/substrate-api-sidecar?tab=readme-ov-file#npm-package-installation-and-usage){target=\_blank} section of the Sidecar API README. +--- -## Usage +### net_peerCount -To use the Sidecar API, you have two options: +Returns the number of peers currently connected to the client. -- **Local node**: Run a node locally, which Sidecar will connect to by default, requiring no additional configuration. To start, run the following: +**Parameters**: - ```bash - substrate-api-sidecar - ``` +None. -- **Remote node**: Connect Sidecar to a remote node by specifying the RPC endpoint for that chain. For example, to gain access to the Polkadot Asset Hub associated endpoints. +**Example**: - ```bash - SAS_SUBSTRATE_URL=wss://polkadot-asset-hub-rpc.polkadot.io substrate-api-sidecar - ``` +```bash title="net_peerCount" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"net_peerCount", + "params":[], + "id":1 +}' +``` - For more configuration details, see the [Configuration](https://github.com/paritytech/substrate-api-sidecar?tab=readme-ov-file#configuration){target=\_blank} section of the Sidecar API documentation. +--- -Once the Sidecar API is running, you’ll see output similar to this: +### net_version -
- SAS_SUBSTRATE_URL=wss://polkadot-asset-hub-rpc.polkadot.io substrate-api-sidecar -
- SAS: - 📦 LOG: - ✅ LEVEL: "info" - ✅ JSON: false - ✅ FILTER_RPC: false - ✅ STRIP_ANSI: false - ✅ WRITE: false - ✅ WRITE_PATH: "/opt/homebrew/lib/node_modules/@substrate/api-sidecar/build/src/logs" - ✅ WRITE_MAX_FILE_SIZE: 5242880 - ✅ WRITE_MAX_FILES: 5 - 📦 SUBSTRATE: - ✅ URL: "wss://polkadot-asset-hub-rpc.polkadot.io" - ✅ TYPES_BUNDLE: undefined - ✅ TYPES_CHAIN: undefined - ✅ TYPES_SPEC: undefined - ✅ TYPES: undefined - ✅ CACHE_CAPACITY: undefined - 📦 EXPRESS: - ✅ BIND_HOST: "127.0.0.1" - ✅ PORT: 8080 - ✅ KEEP_ALIVE_TIMEOUT: 5000 - 📦 METRICS: - ✅ ENABLED: false - ✅ PROM_HOST: "127.0.0.1" - ✅ PROM_PORT: 9100 - ✅ LOKI_HOST: "127.0.0.1" - ✅ LOKI_PORT: 3100 - ✅ INCLUDE_QUERYPARAMS: false -
- 2024-11-06 08:06:01 info: Version: 19.3.0 - 2024-11-06 08:06:02 warn: API/INIT: RPC methods not decorated: chainHead_v1_body, chainHead_v1_call, chainHead_v1_continue, chainHead_v1_follow, chainHead_v1_header, chainHead_v1_stopOperation, chainHead_v1_storage, chainHead_v1_unfollow, chainHead_v1_unpin, chainSpec_v1_chainName, chainSpec_v1_genesisHash, chainSpec_v1_properties, transactionWatch_v1_submitAndWatch, transactionWatch_v1_unwatch, transaction_v1_broadcast, transaction_v1_stop - 2024-11-06 08:06:02 info: Connected to chain Polkadot Asset Hub on the statemint client at wss://polkadot-asset-hub-rpc.polkadot.io - 2024-11-06 08:06:02 info: Listening on http://127.0.0.1:8080/ - 2024-11-06 08:06:02 info: Check the root endpoint (http://127.0.0.1:8080/) to see the available endpoints for the current node -
-With Sidecar running, you can access the exposed endpoints via a browser, [`Postman`](https://www.postman.com/){target=\_blank}, [`curl`](https://curl.se/){target=\_blank}, or your preferred tool. +Returns the current network ID as a string. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#net_version){target=\_blank}. -### Endpoints +**Parameters**: -Sidecar API provides a set of REST endpoints that allow you to query different aspects of the chain, including blocks, accounts, and transactions. Each endpoint offers specific insights into the chain’s state and activities. +None. -For example, to retrieve the version of the node, use the `/node/version` endpoint: +**Example**: -```bash -curl -X 'GET' \ - 'http://127.0.0.1:8080/node/version' \ - -H 'accept: application/json' +```bash title="net_version" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"net_version", + "params":[], + "id":1 +}' ``` -Alternatively, you can access `http://127.0.0.1:8080/node/version` directly in a browser since it’s a `GET` request. +--- + +### system_health -In response, you’ll see output similar to this (assuming you’re connected to Polkadot Asset Hub): +Returns information about the health of the system. -
- curl -X 'GET' 'http://127.0.0.1:8080/node/version' -H 'accept: application/json' -
- { - "clientVersion": "1.16.1-835e0767fe8", - "clientImplName": "statemint", - "chain": "Polkadot Asset Hub" - } -
-For a complete list of available endpoints and their documentation, visit the [Sidecar API list endpoints](https://paritytech.github.io/substrate-api-sidecar/dist/){target=\_blank}. You can learn about the endpoints and how to use them in your applications. +**Parameters**: -## Where to Go Next +None. -To dive deeper, refer to the [official Sidecar documentation](https://github.com/paritytech/substrate-api-sidecar?tab=readme-ov-file#substrateapi-sidecar){target=\_blank}. This provides a comprehensive guide to the available configurations and advanced usage. +**Example**: +```bash title="system_health" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"system_health", + "params":[], + "id":1 +}' +``` --- -Page Title: Smart Contracts Cookbook Index - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/ -- Summary: Explore our full collection of tutorials and guides to learn step-by-step how to build, deploy, and work with smart contracts on Polkadot. +### web3_clientVersion -# Smart Contracts Cookbook +Returns the current client version. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#web3_clientversion){target=\_blank}. -Welcome to the Polkadot smart contracts cookbook index. +**Parameters**: -This page contains a list of all relevant tutorials and guides to help you get started coding smart contracts and dApps in Polkadot. +None. +**Example**: +```bash title="web3_clientVersion" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"web3_clientVersion", + "params":[], + "id":1 +}' +``` +--- -## Get Tokens from the Faucet +### debug_traceBlockByNumber -| Title | Difficulty | Tools | Description | -|------------------------------------|:-----------:|-------|-----------------------------------------------------------------------------------------------------------------------| -| [Faucet](/smart-contracts/faucet/) | 🟢 Beginner | N/A | Learn how to obtain test tokens from Polkadot faucets for development and testing purposes across different networks. | +Traces a block's execution by its number and returns a detailed execution trace for each transaction. -## EVM/PVM Smart Contracts +**Parameters**: -| Title | Difficulty | Tools | Description | -|---------------------------------------------------------------------------------------------------|:-----------:|--------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------| -| [Deploy an ERC-20 to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/) | 🟢 Beginner | EVM Wallet, Polkadot Remix IDE | Deploy an ERC-20 token on Polkadot Hub using PolkaVM. This guide covers contract creation, compilation, deployment, and interaction via Polkadot Remix IDE. | -| [Deploy an NFT to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) | 🟢 Beginner | EVM Wallet, Polkadot Remix IDE | Deploy an NFT on Polkadot Hub using PolkaVM and OpenZeppelin. Learn how to compile, deploy, and interact with your contract using Polkadot Remix IDE. | +- **`blockValue` ++"string"++**: The block number or tag to trace. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. +- **`options` ++"object"++**: (Optional) An object containing tracer options. + - **`tracer` ++"string"++**: The name of the tracer to use (e.g., `"callTracer"`, `"opTracer"`). + - Other tracer-specific options may be supported. -## Port Ethereum DApps +**Example**: -| Title | Difficulty | Tools | Description | -|-------------------------------------------------------------------------------------|:---------------:|---------|----------------------------------------------------------------------------------------------------------------------------------| -| [Deploying Uniswap V2 on Polkadot](/smart-contracts/cookbook/eth-dapps/uniswap-v2/) | 🟡 Intermediate | Hardhat | Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. | +```bash title="debug_traceBlockByNumber" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"debug_traceBlockByNumber", + "params":["INSERT_BLOCK_VALUE", {"tracer": "callTracer"}], + "id":1 +}' +``` +Ensure to replace `INSERT_BLOCK_VALUE` with a proper block number if needed. --- -Page Title: Smart Contracts Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-overview.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/overview/ -- Summary: Learn about smart contract development capabilities in the Polkadot ecosystem, either by leveraging Polkadot Hub or other alternatives. - -# Smart Contracts on Polkadot +### debug_traceTransaction -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction +Traces the execution of a single transaction by its hash and returns a detailed execution trace. -Polkadot offers developers multiple approaches to building and deploying smart contracts within its ecosystem. As a multi-chain network designed for interoperability, Polkadot provides various environments optimized for different developer preferences and application requirements. From native smart contract support on Polkadot Hub to specialized parachain environments, developers can choose the platform that best suits their technical needs while benefiting from Polkadot's shared security model and cross-chain messaging capabilities. +**Parameters**: -Whether you're looking for Ethereum compatibility through EVM-based parachains like [Moonbeam](https://docs.moonbeam.network/){target=\_blank}, [Astar](https://docs.astar.network/){target=\_blank}, and [Acala](https://evmdocs.acala.network/){target=\_blank} or prefer PolkaVM-based development with [ink!](https://use.ink/docs/v6/){target=\_blank}, the Polkadot ecosystem accommodates a range of diverse developers. +- **`transactionHash` ++"string"++**: The hash of the transaction to trace. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`options` ++"object"++**: (Optional) An object containing tracer options (e.g., `tracer: "callTracer"`). -These guides explore the diverse smart contract options available in the Polkadot ecosystem, helping developers understand the unique advantages of each approach and make informed decisions about where to deploy their decentralized applications. +**Example**: -## Native Smart Contracts +```bash title="debug_traceTransaction" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"debug_traceTransaction", + "params":["INSERT_TRANSACTION_HASH", {"tracer": "callTracer"}], + "id":1 +}' +``` -### Introduction +Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper value. -Polkadot Hub enables smart contract deployment and execution through PolkaVM, a cutting-edge virtual machine designed specifically for the Polkadot ecosystem. This native integration allows developers to deploy smart contracts directly on Polkadot's system chain while maintaining compatibility with Ethereum development tools and workflows. +--- -### Smart Contract Development +### debug_traceCall -The smart contract platform on Polkadot Hub combines _Polkadot's robust security and scalability_ with the extensive Ethereum development ecosystem. Developers can utilize familiar Ethereum libraries for contract interactions and leverage industry-standard development environments for writing and testing smart contracts. +Executes a new message call and returns a detailed execution trace without creating a transaction on the blockchain. -Polkadot Hub provides _full Ethereum JSON-RPC API compatibility_, ensuring seamless integration with existing development tools and services. This compatibility enables developers to maintain their preferred workflows while building on Polkadot's native infrastructure. +**Parameters**: -### Technical Architecture +- **`transaction` ++"object"++**: The transaction call object, similar to `eth_call` parameters. + - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. +- **`options` ++"object"++**: (Optional) An object containing tracer options (e.g., `tracer: "callTracer"`). -PolkaVM, the underlying virtual machine, utilizes a RISC-V-based register architecture _optimized for the Polkadot ecosystem_. This design choice offers several advantages: +**Example**: -- Enhanced performance for smart contract execution. -- Improved gas efficiency for complex operations. -- Native compatibility with Polkadot's runtime environment. -- Optimized storage and state management. +```bash title="debug_traceCall" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"debug_traceCall", + "params":[{ + "from": "INSERT_SENDER_ADDRESS", + "to": "INSERT_RECIPIENT_ADDRESS", + "data": "INSERT_ENCODED_CALL" + }, "INSERT_BLOCK_VALUE", {"tracer": "callTracer"}], + "id":1 +}' +``` -### Development Tools and Resources +Ensure to replace the `INSERT_SENDER_ADDRESS`, `INSERT_RECIPIENT_ADDRESS`, `INSERT_ENCODED_CALL`, and `INSERT_BLOCK_VALUE` with the proper value. -Polkadot Hub supports a comprehensive suite of development tools familiar to Ethereum developers. The platform integrates with popular development frameworks, testing environments, and deployment tools. Key features include: +--- -- Contract development in Solidity or Rust. -- Support for standard Ethereum development libraries. -- Integration with widely used development environments. -- Access to blockchain explorers and indexing solutions. -- Compatibility with contract monitoring and management tools. +## Response Format -### Cross-Chain Capabilities +All responses follow the standard JSON-RPC 2.0 format: -Smart contracts deployed on Polkadot Hub can leverage Polkadot's [cross-consensus messaging (XCM) protocol](/parachains/interoperability/get-started/){target=\_blank} protocol to seamlessly _transfer tokens and call functions on other blockchain networks_ within the Polkadot ecosystem, all without complex bridging infrastructure or third-party solutions. For further references, check the [Interoperability](/develop/interoperability/){target=\_blank} section. +```json +{ + "jsonrpc": "2.0", + "id": 1, + "result": ... // The return value varies by method +} +``` -### Use Cases +## Error Handling -Polkadot Hub's smart contract platform is suitable for a wide range of applications: +If an error occurs, the response will include an error object: -- DeFi protocols leveraging _cross-chain capabilities_. -- NFT platforms utilizing Polkadot's native token standards. -- Governance systems integrated with Polkadot's democracy mechanisms. -- Cross-chain bridges and asset management solutions. +```json +{ + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32000, + "message": "Error message here" + } +} +``` -## Other Smart Contract Environments -Beyond Polkadot Hub's native PolkaVM support, the ecosystem offers two main alternatives for smart contract development: +--- -- **EVM-compatible parachains**: Provide access to Ethereum's extensive developer ecosystem, smart contract portability, and established tooling like Hardhat, Remix, Foundry, and OpenZeppelin. The main options include Moonbeam (the first full Ethereum-compatible parachain serving as an interoperability hub), Astar (featuring dual VM support for both EVM and WebAssembly contracts), and Acala (DeFi-focused with enhanced Acala EVM+ offering advanced DeFi primitives). +Page Title: Oracles -- **Rust (ink!)**: ink! is a Rust-based framework that can compile to PolkaVM. It uses [`#[ink(...)]`](https://use.ink/docs/v6/macros-attributes/){target=\_blank} attribute macros to create Polkadot SDK-compatible PolkaVM bytecode, offering strong memory safety from Rust, an advanced type system, high-performance PolkaVM execution, and platform independence with sandboxed security. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-oracles.md +- Canonical (HTML): https://docs.polkadot.com/parachains/integrations/oracles/ +- Summary: Learn about blockchain oracles, the essential bridges connecting blockchains with real-world data for decentralized applications in the Polkadot ecosystem. +# Oracles -Each environment provides unique advantages based on developer preferences and application requirements. +## What is a Blockchain Oracle? -## Where to Go Next +Oracles enable blockchains to access external data sources. Since blockchains operate as isolated networks, they cannot natively interact with external systems - this limitation is known as the "blockchain oracle problem." Oracles solves this by extracting data from external sources (like APIs, IoT devices, or other blockchains), validating it, and submitting it on-chain. -Developers can use their existing Ethereum development tools and connect to Polkadot Hub's RPC endpoints. The platform's Ethereum compatibility layer ensures a smooth transition for teams already building on Ethereum-compatible chains. +While simple oracle implementations may rely on a single trusted provider, more sophisticated solutions use decentralized networks where multiple providers stake assets and reach consensus on data validity. Typical applications include DeFi price feeds, weather data for insurance contracts, and cross-chain asset verification. -Subsequent sections of this guide provide detailed information about specific development tools, advanced features, and best practices for building on Polkadot Hub. +## Oracle Implementations
-- Guide __Libraries__ - - --- - - Explore essential libraries to optimize smart contract development and interaction. - - [:octicons-arrow-right-24: Reference](/smart-contracts/libraries/ethers-js/) - -- Guide __Dev Environments__ +- __Acurast__ --- - Set up your development environment for seamless contract deployment and testing. + Acurast is a decentralized, serverless cloud platform that uses a distributed network of mobile devices for oracle services, addressing centralized trust and data ownership issues. In the Polkadot ecosystem, it allows developers to define off-chain data and computation needs, which are processed by these devices acting as decentralized oracle nodes, delivering results to Substrate (Wasm) and EVM environments. - [:octicons-arrow-right-24: Reference](/smart-contracts/dev-environments/local-dev-node/) + [:octicons-arrow-right-24: Reference](https://acurast.com/){target=\_blank}
--- -Page Title: Subxt Rust API +Page Title: Overview of FRAME -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-subxt.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/subxt/ -- Summary: Subxt is a Rust library for type-safe interaction with Polkadot SDK blockchains, enabling transactions, state queries, runtime API access, and more. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime.md +- Canonical (HTML): https://docs.polkadot.com/parachains/customize-runtime/ +- Summary: Learn how Polkadot SDK’s FRAME framework simplifies blockchain development with modular pallets and support libraries for efficient runtime design. -# Subxt Rust API +# Customize Your Runtime ## Introduction -Subxt is a Rust library designed to interact with Polkadot SDK-based blockchains. It provides a type-safe interface for submitting transactions, querying on-chain state, and performing other blockchain interactions. By leveraging Rust's strong type system, subxt ensures that your code is validated at compile time, reducing runtime errors and improving reliability. - -## Prerequisites - -Before using subxt, ensure you have the following requirements: - -- Rust and Cargo installed on your system. You can install them using [Rustup](https://rustup.rs/){target=\_blank}. -- A Rust project initialized. If you don't have one, create it with: - ```bash - cargo new my_project && cd my_project - ``` - -## Installation - -To use subxt in your project, you must install the necessary dependencies. Each plays a specific role in enabling interaction with the blockchain: - -1. **Install the subxt CLI**: [`subxt-cli`](https://crates.io/crates/subxt-cli){target=\_blank} is a command-line tool that provides utilities for working with Polkadot SDK metadata. In the context of subxt, it is essential to download chain metadata, which is required to generate type-safe Rust interfaces for interacting with the blockchain. Install it using the following: - - ```bash - cargo install subxt-cli@0.44.0 - ``` - -2. **Add core dependencies**: These dependencies are essential for interacting with the blockchain. - - - **[subxt](https://crates.io/crates/subxt){target=\_blank}**: The main library for communicating with Polkadot SDK nodes. It handles RPC requests, encoding/decoding, and type generation. - - ```bash - cargo add subxt@0.44.0 - ``` - - - **[subxt-signer](https://crates.io/crates/subxt-signer){target=\_blank}**: Provides cryptographic functionality for signing transactions. Without this, you can only read data but cannot submit transactions. +A blockchain runtime is more than just a fixed set of rules—it's a dynamic foundation that you can shape to match your specific needs. With Polkadot SDK's [FRAME (Framework for Runtime Aggregation of Modularized Entities)](/reference/glossary/#frame-framework-for-runtime-aggregation-of-modularized-entities){target=\_blank}, customizing your runtime is straightforward and modular. Instead of building everything from scratch, you combine pre-built pallets with your own custom logic to create a runtime suited to your blockchain's purpose. - ```bash - cargo add subxt-signer@0.44.0 - ``` +This overview explains how runtime customization works, introduces the building blocks you'll use, and guides you through the key patterns for extending your runtime. - - **[tokio](https://crates.io/crates/tokio){target=\_blank}**: An asynchronous runtime for Rust. Since blockchain operations are async, Tokio enables the efficient handling of network requests. The `rt` feature enables Tokio's runtime, including the current-thread single-threaded scheduler, which is necessary for async execution. The `macros` feature provides procedural macros like `#[tokio::main]` to simplify runtime setup. +## Understanding Your Runtime - ```bash - cargo add tokio@1.44.2 --features rt,macros - ``` +The runtime is the core logic of your blockchain—it processes transactions, manages state, and enforces the rules that govern your network. When a transaction arrives at your blockchain, the [`frame_executive`](https://paritytech.github.io/polkadot-sdk/master/frame_executive/index.html){target=\_blank} pallet receives it and routes it to the appropriate pallet for execution. - After adding the dependencies, your `Cargo.toml` should look like this: +Think of your runtime as a collection of specialized modules, each handling a different aspect of your blockchain. Need token balances? Use the Balances pallet. Want governance? Add the Governance pallets. Need something custom? Create your own pallet. By mixing and matching these modules, you build a runtime that's efficient, secure, and tailored to your use case. - ```toml - [package] - name = "my_project" - version = "0.1.0" - edition = "2021" +## Runtime Architecture - [dependencies] - subxt = "0.41.0" - subxt-signer = "0.41.0" - tokio = { version = "1.44.2", features = ["rt", "macros"] } +The following diagram shows how FRAME components work together to form your runtime: - ``` +![](/images/parachains/customize-runtime/index/frame-overview-01.webp) -## Get Started +The main components are: -This guide will walk you through the fundamental operations of subxt, from setting up your environment to executing transactions and querying blockchain state. +- **`frame_executive`**: Routes all incoming transactions to the correct pallet for execution. +- **Pallets**: Domain-specific modules that implement your blockchain's features and business logic. +- **`frame_system`**: Provides core runtime primitives and storage. +- **`frame_support`**: Utilities and macros that simplify pallet development. -### Download Chain Metadata +## Building Blocks: Pallets -Before interacting with a blockchain, you need to retrieve its metadata. This metadata defines storage structures, extrinsics, and other runtime details. Use the `subxt-cli` tool to download the metadata, replacing `INSERT_NODE_URL` with the URL of the node you want to interact with: +[Pallets](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/pallet/index.html){target=\_blank} are the fundamental units of runtime customization. Each pallet encapsulates specific functionality and can be independently developed, tested, and integrated. -```bash -subxt metadata --url INSERT_NODE_URL > polkadot_metadata.scale -``` +A pallet can implement virtually any blockchain feature you need: -### Generate Type-Safe Interfaces +- Expose new transactions that users can submit. +- Store data on-chain. +- Enforce business rules and validation logic. +- Emit events to notify users of state changes. +- Handle errors gracefully. -Use the `#[subxt::subxt]` macro to generate a type-safe Rust interface from the downloaded metadata: +### Pre-Built Pallets vs. Custom Pallets -```rust -// Generate an interface that we can use from the node's metadata. -#[subxt::subxt(runtime_metadata_path = "./polkadot_metadata.scale")] -pub mod polkadot {} -``` +FRAME provides a comprehensive library of [pre-built pallets](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame){target=\_blank} for common blockchain features, including consensus, staking, balances, governance, and more. These pallets are battle-tested, optimized, and ready to use. -Once subxt interfaces are generated, you can interact with your node in the following ways. You can use the links below to view the related subxt documentation: +However, you're not limited to pre-built functionality. When pre-built pallets don't meet your needs, you can create custom pallets with entirely custom logic. The real power of FRAME is the flexibility to use pre-built modules for standard features while building your own for unique requirements. -- **[Transactions](https://docs.rs/subxt/latest/subxt/book/usage/transactions/index.html){target=\_blank}**: Builds and submits transactions, monitors their inclusion in blocks, and retrieves associated events. -- **[Storage](https://docs.rs/subxt/latest/subxt/book/usage/storage/index.html){target=\_blank}**: Enables querying of node storage data. -- **[Events](https://docs.rs/subxt/latest/subxt/book/usage/events/index.html){target=\_blank}**: Retrieves events emitted from recent blocks. -- **[Constants](https://docs.rs/subxt/latest/subxt/book/usage/constants/index.html){target=\_blank}**: Accesses constant values stored in nodes that remain unchanged across a specific runtime version. -- **[Blocks](https://docs.rs/subxt/latest/subxt/book/usage/blocks/index.html){target=\_blank}**: Loads recent blocks or subscribes to new/finalized blocks, allowing examination of extrinsics, events, and storage at those blocks. -- **[Runtime APIs](https://docs.rs/subxt/latest/subxt/book/usage/runtime_apis/index.html){target=\_blank}**: Makes calls into pallet runtime APIs to fetch data. -- **[Custom values](https://docs.rs/subxt/latest/subxt/book/usage/custom_values/index.html){target=\_blank}**: Accesses "custom values" contained within metadata. -- **[Raw RPC calls](https://docs.rs/subxt/latest/subxt/book/usage/rpc/index.html){target=\_blank}**: Facilitates raw RPC requests to compatible nodes. +### Pallet Structure -### Initialize the Subxt Client +FRAME uses Rust macros extensively, allowing you to focus on your pallet's logic while the framework handles boilerplate and integration code. -To interact with a blockchain node using subxt, create an asynchronous main function and initialize the client. Replace `INSERT_NODE_URL` with the URL of your target node: +A typical pallet looks like this: ```rust -use std::str::FromStr; -use subxt::utils::AccountId32; -use subxt::{OnlineClient, PolkadotConfig}; -use subxt_signer::{bip39::Mnemonic,sr25519::Keypair}; - -// Generate an interface that we can use from the node's metadata. -#[subxt::subxt(runtime_metadata_path = "./polkadot_metadata.scale")] -pub mod polkadot {} - -#[tokio::main(flavor = "current_thread")] -async fn main() -> Result<(), Box> { - // Define the node URL. - const NODE_URL: &str = "INSERT_NODE_URL"; +pub use pallet::*; - // Initialize the Subxt client to interact with the blockchain. - let api = OnlineClient::::from_url(NODE_URL).await?; +#[frame_support::pallet] +pub mod pallet { + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; - // Your code here... + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(_); - Ok(()) + #[pallet::config] // snip + #[pallet::event] // snip + #[pallet::error] // snip + #[pallet::storage] // snip + #[pallet::call] // snip } ``` -### Read Chain Data - -subxt provides multiple ways to access on-chain data: - -- **Constants**: Constants are predefined values in the runtime that remain unchanged unless modified by a runtime upgrade. - - For example, to retrieve the existential deposit, use: - - ```rust - // A query to obtain some constant. - let constant_query = polkadot::constants().balances().existential_deposit(); - - // Obtain the value. - let value = api.constants().at(&constant_query)?; - - println!("Existential deposit: {:?}", value); - ``` - -- **State**: State refers to the current chain data, which updates with each block. +Every pallet can implement these core macros: - To fetch account information, replace `INSERT_ADDRESS` with the address you want to fetch data from and use: +- **`#[frame_support::pallet]`**: Marks your module as a FRAME pallet. +- **`#[pallet::pallet]`**: Designates the struct that holds pallet metadata. +- **`#[pallet::config]`**: Defines configuration and associated types. +- **`#[pallet::event]`**: Defines events emitted by your pallet. +- **`#[pallet::error]`**: Defines error types your pallet can return. +- **`#[pallet::storage]`**: Defines on-chain storage items. +- **`#[pallet::call]`**: Defines dispatchable functions (transactions). - ```rust - // Define the target account address. - const ADDRESS: &str = "INSERT_ADDRESS"; - let account = AccountId32::from_str(ADDRESS).unwrap(); - - // Build a storage query to access account information. - let storage_query = polkadot::storage().system().account(&account.into()); - - // Fetch the latest state for the account. - let result = api - .storage() - .at_latest() - .await? - .fetch(&storage_query) - .await? - .unwrap(); - - println!("Account info: {:?}", result); - ``` +For a comprehensive reference, see the [`pallet_macros` documentation](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/index.html){target=\_blank}. -### Submit Transactions +## How Runtime Customization Works -To submit a transaction, you must construct an extrinsic, sign it with your private key, and send it to the blockchain. Replace `INSERT_DEST_ADDRESS` with the recipient's address, `INSERT_AMOUNT` with the amount to transfer, and `INSERT_SECRET_PHRASE` with the sender's mnemonic phrase: +Customizing your runtime typically follows these patterns: -```rust - // Define the recipient address and transfer amount. - const DEST_ADDRESS: &str = "INSERT_DEST_ADDRESS"; - const AMOUNT: u128 = INSERT_AMOUNT; - - // Convert the recipient address into an `AccountId32`. - let dest = AccountId32::from_str(DEST_ADDRESS).unwrap(); - - // Build the balance transfer extrinsic. - let balance_transfer_tx = polkadot::tx() - .balances() - .transfer_allow_death(dest.into(), AMOUNT); - - // Load the sender's keypair from a mnemonic phrase. - const SECRET_PHRASE: &str = "INSERT_SECRET_PHRASE"; - let mnemonic = Mnemonic::parse(SECRET_PHRASE).unwrap(); - let sender_keypair = Keypair::from_phrase(&mnemonic, None).unwrap(); - - // Sign and submit the extrinsic, then wait for it to be finalized. - let events = api - .tx() - .sign_and_submit_then_watch_default(&balance_transfer_tx, &sender_keypair) - .await? - .wait_for_finalized_success() - .await?; - - // Check for a successful transfer event. - if let Some(event) = events.find_first::()? { - println!("Balance transfer successful: {:?}", event); - } -``` +**Adding Pre-Built Pallets**: Select pallets from the FRAME library and integrate them into your runtime configuration. This is the fastest way to add functionality. -## Where to Go Next +**Creating Custom Pallets**: Write custom pallets for features that don't exist in the pre-built library. Custom pallets follow the same structure as pre-built ones and integrate seamlessly. -Now that you've covered the basics dive into the official [subxt documentation](https://docs.rs/subxt/latest/subxt/book/index.html){target=\_blank} for comprehensive reference materials and advanced features. +**Combining Multiple Pallets**: Layer multiple pallets together to create complex behaviors. Pallets can call each other and share storage when needed. +**Configuring Pallet Parameters**: Most pallets are configurable—you can adjust their behavior through configuration traits without modifying their code. ---- +The following diagram illustrates how pallets combine to form a complete runtime: -Page Title: Technical Reference Overview +![](/images/parachains/customize-runtime/index/frame-overview-02.webp) -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference.md -- Canonical (HTML): https://docs.polkadot.com/reference/ -- Summary: Learn about Polkadot's technical architecture, governance framework, parachain ecosystem, and the tools you need to build and interact with the network. +## Starting Templates -## Introduction +The easiest way to begin customizing your runtime is with a starter template. These templates provide a pre-configured foundation so you can focus on customization rather than setup. -The Technical Reference section provides comprehensive documentation of Polkadot's architecture, core concepts, and development tooling. Whether you're exploring how Polkadot's relay chain coordinates parachains, understanding governance mechanisms, or building applications on the network, this reference covers the technical foundations you need. +- **[Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank}**: The recommended choice for most developers, it includes pre-configured pallets for common features (balances, block production, governance), a complete runtime setup, and built-in parachain consensus support. This template offers the best balance of features and learning opportunities. -Polkadot is a multi-chain network that enables diverse, interconnected blockchains to share security and communicate seamlessly. Understanding how these components interact from the [relay chain](/polkadot-protocol/glossary#relay-chain){target=\_blank} that validates [parachains](/polkadot-protocol/glossary#parachain){target=\_blank} to the [governance](/reference/glossary#governance){target=\_blank} mechanisms that evolve the protocol is essential for developers, validators, and network participants. +- **[Polkadot SDK Minimal Template](https://github.com/paritytech/polkadot-sdk-minimal-template){target=\_blank}**: Provides a bare-bones runtime with only essential components. Choose this if you want maximum flexibility and prefer building from a clean slate. -This guide organizes technical documentation across five core areas: Polkadot Hub, Parachains, On-Chain Governance, Glossary, and Tools, each providing detailed information on different aspects of the Polkadot ecosystem. +- **[Polkadot SDK Solochain Template](https://github.com/paritytech/polkadot-sdk/tree/master/templates/solochain){target=\_blank}**: Designed for building standalone blockchains with moderate features, simple consensus, and several core pallets. Use this if you want a sovereign blockchain independent of a relay chain. -## Polkadot Hub +- **[OpenZeppelin Runtime Templates](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\_blank}**: Provides security-focused configurations following industry best practices. The [generic-template](https://github.com/OpenZeppelin/polkadot-runtime-templates/tree/main/generic-template){target=\_blank} includes curated pallet selections and production-ready defaults—ideal if security is your top priority. -[Polkadot Hub](/reference/polkadot-hub/){target=\_blank} is the entry point to Polkadot for all users and application developers. It provides access to essential Web3 services, including smart contracts, staking, governance, identity management, and cross-ecosystem interoperability—without requiring you to deploy or manage a parachain. +## Key Customization Scenarios -The Hub encompasses a set of core functionality that enables developers and users to build and interact with applications on Polkadot. Key capabilities include: +This section covers the most common customization patterns you'll encounter: -- **Smart contracts**: Deploy Ethereum-compatible smart contracts and build decentralized applications. -- **Assets and tokens**: Create, manage, and transfer fungible tokens and NFTs across the ecosystem. -- **Staking**: Participate in network security and earn rewards by staking DOT. -- **Governance**: Vote on proposals and participate in Polkadot's decentralized decision-making through OpenGov. -- **Identity services**: Register and manage on-chain identities, enabling access to governance roles and network opportunities. -- **Cross-chain interoperability**: Leverage XCM messaging to interact securely with other chains in the Polkadot ecosystem. -- **Collectives and DAOs**: Participate in governance collectives and decentralized autonomous organizations. +- **[Add Existing Pallets to Your Runtime](/parachains/customize-runtime/add-existing-pallets/)**: Integrate pre-built pallets from the FRAME library with minimal configuration. -## Parachains +- **[Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/)**: Run multiple instances of the same pallet with different configurations—useful for multi-token systems or parallel features. -[Parachains](/reference/parachains/){target=\_blank} are specialized blockchains that connect to the Polkadot relay chain, inheriting its security while maintaining their own application-specific logic. The parachains documentation covers: +- **[Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/)**: Enable smart contract execution on your parachain using Contracts pallets. -- **Accounts**: Deep dive into account types, storage, and management on parachains. -- **Blocks, transactions and fees**: Understand block production, transaction inclusion, and fee mechanisms. -- **Consensus**: Learn how parachain blocks are validated and finalized through the relay chain's consensus. -- **Chain data**: Explore data structures, storage layouts, and state management. -- **Cryptography**: Study cryptographic primitives used in Polkadot SDK-based chains. -- **Data encoding**: Understand how data is encoded and decoded for blockchain compatibility. -- **Networks**: Learn about networking protocols and peer-to-peer communication. -- **Interoperability**: Discover [Cross-Consensus Messaging (XCM)](/parachains/interoperability/get-started/){target=\_blank}, the standard for cross-chain communication. -- **Randomness**: Understand how randomness is generated and used in Polkadot chains. -- **Node and runtime**: Learn about parachain nodes, runtime environments, and the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}. +- **[Create Custom Pallets](/parachains/customize-runtime/pallet-development/create-a-pallet/)**: Build entirely custom pallets for features unique to your blockchain. -## On-Chain Governance +- **[Test Your Runtime](/parachains/customize-runtime/pallet-development/pallet-testing/)**: Unit test pallets and mock complete runtimes to ensure everything works correctly. -[On-Chain governance](/reference/governance/){target=\_blank} is the decentralized decision-making mechanism for the Polkadot network. It manages the evolution and modification of the network's runtime logic, enabling community oversight and approval for proposed changes. The governance documentation details: -- **OpenGov framework**: Understand Polkadot's next-generation governance system with enhanced delegation, flexible tracks, and simultaneous referendums. -- **Origins and tracks**: Learn how governance proposals are categorized, prioritized, and executed based on their privilege level and complexity. -- **Voting and delegation**: Explore conviction voting, vote delegation, and how token holders participate in governance. -- **Governance evolution**: See how Polkadot's governance has evolved from Governance V1 to the current OpenGov system. +--- -## Glossary +Page Title: Set Up the Polkadot SDK Parachain Template -The [Glossary](/reference/glossary/){target=\_blank} provides quick-reference definitions for Polkadot-specific terminology. Essential terms include: +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-launch-a-parachain-set-up-the-parachain-template.md +- Canonical (HTML): https://docs.polkadot.com/parachains/launch-a-parachain/set-up-the-parachain-template/ +- Summary: Learn how to set up and run the Polkadot SDK Parachain Template locally, creating a ready-to-customize foundation for your parachain. -- Blockchain concepts (blocks, transactions, state) -- Consensus mechanisms (validators, collators, finality) -- Polkadot-specific terms (relay chain, parachain, XCM, FRAME) -- Network components (nodes, runtimes, storage) -- Governance terminology (origins, tracks, referendums) +# Set Up the Polkadot SDK Parachain Template -## Tools +## Introduction -The [Tools](/reference/tools/){target=\_blank} section documents essential development and interaction tools for the Polkadot ecosystem: +The [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank} includes several [templates](/parachains/customize-runtime/#starting-templates){target=\_blank} designed to help you quickly start building your own blockchain. Each template offers a different level of configuration, from minimal setups to feature-rich environments, allowing you to choose the foundation that best fits your project's needs. -- **Light clients**: Lightweight solutions for interacting with the network without running full nodes. -- **JavaScript/TypeScript tools**: Libraries like [Polkadot.js API](/reference/tools/polkadot-js-api/){target=\_blank} and [PAPI](/reference/tools/papi/){target=\_blank} for building applications. -- **Rust tools**: [Polkadart](/reference/tools/polkadart/){target=\_blank} and other Rust-based libraries for SDK development. -- **Python tools**: [py-substrate-interface](/reference/tools/py-substrate-interface/){target=\_blank} for Python developers. -- **Testing and development**: Tools like [Moonwall](/reference/tools/moonwall/){target=\_blank}, [Chopsticks](/reference/tools/chopsticks/){target=\_blank}, and [Omninode](/reference/tools/omninode/){target=\_blank} for smart contract and parachain testing. -- **Indexing and monitoring**: [Sidecar](/reference/tools/sidecar/){target=\_blank} for data indexing and [Dedot](/reference/tools/dedot/){target=\_blank} for substrate interaction. -- **Cross-chain tools**: [ParaSpell](/reference/tools/paraspell/){target=\_blank} for XCM integration and asset transfers. +Among these, the [Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank} provides a preconfigured runtime with commonly used pallets, making it an ideal starting point for most parachain development projects. -## Where to Go Next +This guide walks you through the full process of working with this template. You will: -For detailed exploration of specific areas, proceed to any of the main sections: +- Set up the Polkadot SDK Parachain Template. +- Understand the project structure and key components. +- Verify your template is ready for development. +- Run the parachain template locally in development mode. -
+By the end of this guide, you'll have a working template ready to customize and deploy as a parachain. -- Learn **Polkadot Hub** +## Prerequisites - --- +Before getting started, ensure you have done the following: - Understand the relay chain's role in coordinating parachains, providing shared security, and enabling governance. +- Completed the [Install Polkadot SDK](/parachains/install-polkadot-sdk/){target=\_blank} guide and successfully installed [Rust](https://www.rust-lang.org/){target=\_blank} and the required packages to set up your development environment. - [:octicons-arrow-right-24: Reference](/reference/polkadot-hub/) +For this tutorial series, you need to use Rust `1.86`. Newer versions of the compiler may not work with this parachain template version. -- Learn **Parachains** +Run the following commands to set up the correct Rust version: - --- +=== "macOS" - Deep dive into parachain architecture, consensus, data structures, and building application-specific blockchains. + ```bash + rustup install 1.86 + rustup default 1.86 + rustup target add wasm32-unknown-unknown --toolchain 1.86-aarch64-apple-darwin + rustup component add rust-src --toolchain 1.86-aarch64-apple-darwin + ``` - [:octicons-arrow-right-24: Reference](/reference/parachains/) +=== "Ubuntu" -- Learn **On-Chain Governance** + ```bash + rustup toolchain install 1.86.0 + rustup default 1.86.0 + rustup target add wasm32-unknown-unknown --toolchain 1.86.0 + rustup component add rust-src --toolchain 1.86.0 + ``` - --- +## Polkadot SDK Utility Tools - Explore Polkadot's decentralized governance framework and how to participate in network decision-making. +This tutorial requires two essential tools: - [:octicons-arrow-right-24: Reference](/reference/governance/) +- [**Chain spec builder**](https://crates.io/crates/staging-chain-spec-builder/10.0.0){target=\_blank}: A Polkadot SDK utility for generating chain specifications. Refer to the [Generate Chain Specs](/develop/parachains/deployment/generate-chain-specs/){target=\_blank} documentation for detailed usage. + + Install it by executing the following command: + + ```bash + cargo install --locked staging-chain-spec-builder@10.0.0 + ``` -- Guide **Glossary** + This command installs the `chain-spec-builder` binary. - --- +- [**Polkadot Omni Node**](https://crates.io/crates/polkadot-omni-node/0.5.0){target=\_blank}: A white-labeled binary, released as a part of Polkadot SDK that can act as the collator of a parachain in production, with all the related auxiliary functionalities that a normal collator node has: RPC server, archiving state, etc. Moreover, it can also run the Wasm blob of the parachain locally for testing and development. - Quick reference for Polkadot-specific terminology and concepts used throughout the documentation. + To install it, run the following command: - [:octicons-arrow-right-24: Reference](/reference/glossary/) + ```bash + cargo install --locked polkadot-omni-node@0.5.0 + ``` -- Guide **Tools** + This command installs the `polkadot-omni-node` binary. - --- +## Clone the Template - Discover development tools, libraries, and frameworks for building and interacting with Polkadot. +The [Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank} provides a ready-to-use development environment for building with the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}. Follow these steps to set up the template: - [:octicons-arrow-right-24: Reference](/reference/tools/) +1. Clone the template repository: -
+ ```bash + git clone https://github.com/paritytech/polkadot-sdk-parachain-template.git parachain-template + ``` +2. Navigate into the project directory: ---- + ```bash + cd parachain-template + ``` -Page Title: Transactions +## Explore the Project Structure -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-transactions.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/transactions/ -- Summary: Learn how to construct, submit, and validate transactions in the Polkadot SDK, covering signed, unsigned, and inherent types of transactions. +Before building the template, take a moment to familiarize yourself with its structure. Understanding this organization will help you navigate the codebase as you develop your parachain. -# Transactions +The template follows a standard Polkadot SDK project layout: -## Introduction +```text +parachain-template/ +├── node/ # Node implementation and client +├── pallets/ # Custom pallets for your parachain +├── runtime/ # Runtime configuration and logic +├── Cargo.toml # Workspace configuration +└── README.md # Documentation +``` -Transactions are essential components of blockchain networks, enabling state changes and the execution of key operations. In the Polkadot SDK, transactions, often called extrinsics, come in multiple forms, including signed, unsigned, and inherent transactions. +Key directories explained: -This guide walks you through the different transaction types and how they're formatted, validated, and processed within the Polkadot ecosystem. You'll also learn how to customize transaction formats and construct transactions for FRAME-based runtimes, ensuring a complete understanding of how transactions are built and executed in Polkadot SDK-based chains. +- **runtime/**: Contains your parachain's state transition function and pallet configuration. This is where you'll define what your blockchain can do. +- **node/**: Houses the client implementation that runs your blockchain, handles networking, and manages the database. +- **pallets/**: Where you'll create custom business logic modules (pallets) for your specific use case. +- **Cargo.toml**: The workspace configuration that ties all components together. -## What Is a Transaction? +!!!note + The runtime is compiled to WebAssembly (Wasm), enabling forkless upgrades. The node binary remains constant while the runtime can be updated on-chain. -In the Polkadot SDK, transactions represent operations that modify the chain's state, bundled into blocks for execution. The term extrinsic is often used to refer to any data that originates outside the runtime and is included in the chain. While other blockchain systems typically refer to these operations as "transactions," the Polkadot SDK adopts the broader term "extrinsic" to capture the wide variety of data types that can be added to a block. +## Compile the Runtime -There are three primary types of transactions (extrinsics) in the Polkadot SDK: +Now that you understand the template structure, let's compile the runtime to ensure everything is working correctly. -- **Signed transactions**: Signed by the submitting account, often carrying transaction fees. -- **Unsigned transactions**: Submitted without a signature, often requiring custom validation logic. -- **Inherent transactions**: Typically inserted directly into blocks by block authoring nodes, without gossiping between peers. +1. Compile the runtime: -Each type serves a distinct purpose, and understanding when and how to use each is key to efficiently working with the Polkadot SDK. + ```bash + cargo build --release --locked + ``` -### Signed Transactions + !!!tip + Initial compilation may take several minutes, depending on your machine specifications. Use the `--release` flag for improved runtime performance compared to the default `--debug` build. If you need to troubleshoot issues, the `--debug` build provides better diagnostics. + + For production deployments, consider using a dedicated `--profile production` flag - this can provide an additional 15-30% performance improvement over the standard `--release` profile. -Signed transactions require an account's signature and typically involve submitting a request to execute a runtime call. The signature serves as a form of cryptographic proof that the sender has authorized the action, using their private key. These transactions often involve a transaction fee to cover the cost of execution and incentivize block producers. +2. Upon successful compilation, you should see output indicating the build was successful. The compiled runtime will be located at: + + `./target/release/wbuild/parachain-template-runtime/parachain_template_runtime.compact.compressed.wasm` -Signed transactions are the most common type of transaction and are integral to user-driven actions, such as token transfers. For instance, when you transfer tokens from one account to another, the sending account must sign the transaction to authorize the operation. +## Verify the Build -For example, the [`pallet_balances::Call::transfer_allow_death`](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/pallet/struct.Pallet.html#method.transfer_allow_death){target=\_blank} extrinsic in the Balances pallet allows you to transfer tokens. Since your account initiates this transaction, your account key is used to sign it. You'll also be responsible for paying the associated transaction fee, with the option to include an additional tip to incentivize faster inclusion in the block. +After compilation completes, verify that the runtime was created successfully by checking for the Wasm blob: -### Unsigned Transactions +```bash +ls -la ./target/release/wbuild/parachain-template-runtime/ +``` -Unsigned transactions do not require a signature or account-specific data from the sender. Unlike signed transactions, they do not come with any form of economic deterrent, such as fees, which makes them susceptible to spam or replay attacks. Custom validation logic must be implemented to mitigate these risks and ensure these transactions are secure. +You should see the `parachain_template_runtime.compact.compressed.wasm` file in the output, confirming the build was successful. -Unsigned transactions typically involve scenarios where including a fee or signature is unnecessary or counterproductive. However, due to the absence of fees, they require careful validation to protect the network. For example, [`pallet_im_online::Call::heartbeat`](https://paritytech.github.io/polkadot-sdk/master/pallet_im_online/pallet/struct.Pallet.html#method.heartbeat){target=\_blank} extrinsic allows validators to send a heartbeat signal, indicating they are active. Since only validators can make this call, the logic embedded in the transaction ensures that the sender is a validator, making the need for a signature or fee redundant. +## Run the Node Locally -Unsigned transactions are more resource-intensive than signed ones because custom validation is required, but they play a crucial role in certain operational scenarios, especially when regular user accounts aren't involved. +After successfully compiling your runtime, you can spin up a local chain and produce blocks. This process will start your local parachain using the Polkadot Omni Node and allow you to interact with it. You'll first need to generate a chain specification that defines your network's identity, initial connections, and genesis state, providing the foundational configuration for how your nodes connect and what initial state they agree upon. -### Inherent Transactions +Follow these steps to launch your node in development mode: -Inherent transactions are a specialized type of unsigned transaction that is used primarily for block authoring. Unlike signed or other unsigned transactions, inherent transactions are added directly by block producers and are not broadcasted to the network or stored in the transaction queue. They don't require signatures or the usual validation steps and are generally used to insert system-critical data directly into blocks. +1. Generate the chain specification file of your parachain: -A key example of an inherent transaction is inserting a timestamp into each block. The [`pallet_timestamp::Call::now`](https://paritytech.github.io/polkadot-sdk/master/pallet_timestamp/pallet/struct.Pallet.html#method.now-1){target=\_blank} extrinsic allows block authors to include the current time in the block they are producing. Since the block producer adds this information, there is no need for transaction validation, like signature verification. The validation in this case is done indirectly by the validators, who check whether the timestamp is within an acceptable range before finalizing the block. + ```bash + chain-spec-builder create -t development \ + --relay-chain paseo \ + --para-id 1000 \ + --runtime ./target/release/wbuild/parachain-template-runtime/parachain_template_runtime.compact.compressed.wasm \ + named-preset development + ``` -Another example is the [`paras_inherent::Call::enter`](https://paritytech.github.io/polkadot-sdk/master/polkadot_runtime_parachains/paras_inherent/pallet/struct.Pallet.html#method.enter){target=\_blank} extrinsic, which enables parachain collator nodes to send validation data to the relay chain. This inherent transaction ensures that the necessary parachain data is included in each block without the overhead of gossiped transactions. +2. Start the Omni Node with the generated chain spec. You'll start it in development mode (without a relay chain config), producing and finalizing blocks: -Inherent transactions serve a critical role in block authoring by allowing important operational data to be added directly to the chain without needing the validation processes required for standard transactions. + ```bash + polkadot-omni-node --chain ./chain_spec.json --dev + ``` -## Transaction Formats + The `--dev` option does the following: -Understanding the structure of signed and unsigned transactions is crucial for developers building on Polkadot SDK-based chains. Whether you're optimizing transaction processing, customizing formats, or interacting with the transaction pool, knowing the format of extrinsics, Polkadot's term for transactions, is essential. + - Deletes all active data (keys, blockchain database, networking information) when stopped. + - Ensures a clean working state each time you restart the node. -### Types of Transaction Formats +3. Verify that your node is running by reviewing the terminal output. You should see log messages indicating block production and finalization. -In Polkadot SDK-based chains, extrinsics can fall into three main categories: +4. Confirm that your blockchain is producing new blocks by checking if the number after `finalized` is increasing in the output. -- **Unchecked extrinsics**: Typically used for signed transactions that require validation. They contain a signature and additional data, such as a nonce and information for fee calculation. Unchecked extrinsics are named as such because they require validation checks before being accepted into the transaction pool. -- **Checked extrinsics**: Typically used for inherent extrinsics (unsigned transactions); these don't require signature verification. Instead, they carry information such as where the extrinsic originates and any additional data required for the block authoring process. -- **Opaque extrinsics**: Used when the format of an extrinsic is not yet fully committed or finalized. They are still decodable, but their structure can be flexible depending on the context. +The details of the log output will be explored in a later tutorial. For now, knowing that your node is running and producing blocks is sufficient. -### Signed Transaction Data Structure +## Interact with the Node -A signed transaction typically includes the following components: +When running the template node, it's accessible by default at `ws://localhost:9944`. To interact with your node using the [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} interface, follow these steps: -- **Signature**: Verifies the authenticity of the transaction sender. -- **Call**: The actual function or method call the transaction is requesting (for example, transferring funds). -- **Nonce**: Tracks the number of prior transactions sent from the account, helping to prevent replay attacks. -- **Tip**: An optional incentive to prioritize the transaction in block inclusion. -- **Additional data**: Includes details such as spec version, block hash, and genesis hash to ensure the transaction is valid within the correct runtime and chain context. +1. Open [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} in your web browser and click the network icon (which should be the Polkadot logo) in the top left corner: + + ![](/images/parachains/launch-a-parachain/set-up-the-parachain-template/parachain-template-01.webp) -Here's a simplified breakdown of how signed transactions are typically constructed in a Polkadot SDK runtime: +2. Connect to your local node: -``` code - + + -``` + 1. Scroll to the bottom and select **Development**. + 2. Choose **Custom**. + 3. Enter `ws://localhost:9944` in the **custom endpoint** input field. + 4. Click the **Switch** button. + + ![](/images/parachains/launch-a-parachain/set-up-the-parachain-template/parachain-template-02.webp) -Each part of the signed transaction has a purpose, ensuring the transaction's authenticity and context within the blockchain. +3. Once connected, you should see **parachain-template-runtime** in the top left corner, with the interface displaying information about your local blockchain. + + ![](/images/parachains/launch-a-parachain/set-up-the-parachain-template/parachain-template-03.webp) -### Signed Extensions +You are now connected to your local node and can interact with it through the Polkadot.js Apps interface. This tool enables you to explore blocks, execute transactions, and interact with your blockchain's features. For in-depth guidance on using the interface effectively, refer to the [Polkadot.js Guides](https://wiki.polkadot.com/general/polkadotjs/){target=\_blank} available on the Polkadot Wiki. -Polkadot SDK also provides the concept of [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}, which allow developers to extend extrinsics with additional data or validation logic before they are included in a block. The [`SignedExtension`](https://paritytech.github.io/try-runtime-cli/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} set helps enforce custom rules or protections, such as ensuring the transaction's validity or calculating priority. +## Stop the Node -The transaction queue regularly calls signed extensions to verify a transaction's validity before placing it in the ready queue. This safeguard ensures transactions won't fail in a block. Signed extensions are commonly used to enforce validation logic and protect the transaction pool from spam and replay attacks. +When you're done exploring your local node, you can stop it to remove any state changes you've made. Since you started the node with the `--dev` option, stopping the node will purge all persistent block data, allowing you to start fresh the next time. -In FRAME, a signed extension can hold any of the following types by default: +To stop the local node: -- **[`AccountId`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/runtime/types_common/type.AccountId.html){target=\_blank}**: To encode the sender's identity. -- **[`Call`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Call){target=\_blank}**: To encode the pallet call to be dispatched. This data is used to calculate transaction fees. -- **[`AdditionalSigned`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.AdditionalSigned){target=\_blank}**: To handle any additional data to go into the signed payload allowing you to attach any custom logic prior to dispatching a transaction. -- **[`Pre`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Pre){target=\_blank}**: To encode the information that can be passed from before a call is dispatched to after it gets dispatched. +1. Return to the terminal window where the node output is displayed. +2. Press `Control-C` to stop the running process. +3. Verify that your terminal returns to the prompt in the `parachain-template` directory. -Signed extensions can enforce checks like: +## Where to Go Next -- **[`CheckSpecVersion`](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/extensions/check_spec_version.rs.html){target=\_blank}**: Ensures the transaction is compatible with the runtime's current version. -- **[`CheckWeight`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.CheckWeight.html){target=\_blank}**: Calculates the weight (or computational cost) of the transaction, ensuring the block doesn't exceed the maximum allowed weight. +
-These extensions are critical in the transaction lifecycle, ensuring that only valid and prioritized transactions are processed. +- Tutorial __Deploy to Polkadot__ -## Transaction Construction + --- -Building transactions in the Polkadot SDK involves constructing a payload that can be verified, signed, and submitted for inclusion in a block. Each runtime in the Polkadot SDK has its own rules for validating and executing transactions, but there are common patterns for constructing a signed transaction. + Learn how to deploy your parachain template to a relay chain testnet. Configure your chain specification, register as a parachain, and start producing blocks. -### Construct a Signed Transaction + [:octicons-arrow-right-24: Get Started](/parachains/launch-a-parachain/deploy-to-polkadot.md) -A signed transaction in the Polkadot SDK includes various pieces of data to ensure security, prevent replay attacks, and prioritize processing. Here's an overview of how to construct one: +
-1. **Construct the unsigned payload**: Gather the necessary information for the call, including: - - **Pallet index**: Identifies the pallet where the runtime function resides. - - **Function index**: Specifies the particular function to call in the pallet. - - **Parameters**: Any additional arguments required by the function call. +--- -2. **Create a signing payload**: Once the unsigned payload is ready, additional data must be included: +Page Title: Smart Contracts Cookbook Index - - **Transaction nonce**: Unique identifier to prevent replay attacks. - - **Era information**: Defines how long the transaction is valid before it's dropped from the pool. - - **Block hash**: Ensures the transaction doesn't execute on the wrong chain or fork. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/ +- Summary: Explore our full collection of tutorials and guides to learn step-by-step how to build, deploy, and work with smart contracts on Polkadot. -3. **Sign the payload**: Using the sender's private key, sign the payload to ensure that the transaction can only be executed by the account holder. -4. **Serialize the signed payload**: Once signed, the transaction must be serialized into a binary format, ensuring the data is compact and easy to transmit over the network. -5. **Submit the serialized transaction**: Finally, submit the serialized transaction to the network, where it will enter the transaction pool and wait for processing by an authoring node. +# Smart Contracts Cookbook -The following is an example of how a signed transaction might look: +Welcome to the Polkadot smart contracts cookbook index. -``` rust -node_runtime::UncheckedExtrinsic::new_signed( - function.clone(), // some call - sp_runtime::AccountId32::from(sender.public()).into(), // some sending account - node_runtime::Signature::Sr25519(signature.clone()), // the account's signature - extra.clone(), // the signed extensions -) -``` +This page contains a list of all relevant tutorials and guides to help you get started coding smart contracts and dApps in Polkadot. -### Transaction Encoding -Before a transaction is sent to the network, it is serialized and encoded using a structured encoding process that ensures consistency and prevents tampering: -- **`[1]`**: Compact encoded length in bytes of the entire transaction. -- **`[2]`**: A u8 containing 1 byte to indicate whether the transaction is signed or unsigned (1 bit) and the encoded transaction version ID (7 bits). -- **`[3]`**: If signed, this field contains an account ID, an SR25519 signature, and some extra data. -- **`[4]`**: Encoded call data, including pallet and function indices and any required arguments. -This encoded format ensures consistency and efficiency in processing transactions across the network. By adhering to this format, applications can construct valid transactions and pass them to the network for execution. +## Get Tokens from the Faucet -To learn more about how compact encoding works using SCALE, see the [SCALE Codec](https://github.com/paritytech/parity-scale-codec){target=\_blank} README on GitHub. +| Title | Difficulty | Tools | Description | +|------------------------------------|:-----------:|-------|-----------------------------------------------------------------------------------------------------------------------| +| [Faucet](/smart-contracts/faucet/) | 🟢 Beginner | N/A | Learn how to obtain test tokens from Polkadot faucets for development and testing purposes across different networks. | -### Customize Transaction Construction +## EVM/PVM Smart Contracts -Although the basic steps for constructing transactions are consistent across Polkadot SDK-based chains, developers can customize transaction formats and validation rules. For example: +| Title | Difficulty | Tools | Description | +|---------------------------------------------------------------------------------------------------|:-----------:|--------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [Deploy an ERC-20 to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/) | 🟢 Beginner | EVM Wallet, Polkadot Remix IDE | Deploy an ERC-20 token on Polkadot Hub using PolkaVM. This guide covers contract creation, compilation, deployment, and interaction via Polkadot Remix IDE. | +| [Deploy an NFT to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) | 🟢 Beginner | EVM Wallet, Polkadot Remix IDE | Deploy an NFT on Polkadot Hub using PolkaVM and OpenZeppelin. Learn how to compile, deploy, and interact with your contract using Polkadot Remix IDE. | -- **Custom pallets**: You can define new pallets with custom function calls, each with its own parameters and validation logic. -- **Signed extensions**: Developers can implement custom extensions that modify how transactions are prioritized, validated, or included in blocks. +## Port Ethereum DApps -By leveraging Polkadot SDK's modular design, developers can create highly specialized transaction logic tailored to their chain's needs. +| Title | Difficulty | Tools | Description | +|-------------------------------------------------------------------------------------|:---------------:|---------|----------------------------------------------------------------------------------------------------------------------------------| +| [Deploying Uniswap V2 on Polkadot](/smart-contracts/cookbook/eth-dapps/uniswap-v2/) | 🟡 Intermediate | Hardhat | Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. | -## Lifecycle of a Transaction -In the Polkadot SDK, transactions are often referred to as extrinsics because the data in transactions originates outside of the runtime. These transactions contain data that initiates changes to the chain state. The most common type of extrinsic is a signed transaction, which is cryptographically verified and typically incurs a fee. This section focuses on how signed transactions are processed, validated, and ultimately included in a block. +--- -### Define Transaction Properties +Page Title: Smart Contracts Overview -The Polkadot SDK runtime defines key transaction properties, such as: +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-overview.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/overview/ +- Summary: Learn about smart contract development capabilities in the Polkadot ecosystem, either by leveraging Polkadot Hub or other alternatives. -- **Transaction validity**: Ensures the transaction meets all runtime requirements. -- **Signed or unsigned**: Identifies whether a transaction needs to be signed by an account. -- **State changes**: Determines how the transaction modifies the state of the chain. +# Smart Contracts on Polkadot -Pallets, which compose the runtime's logic, define the specific transactions that your chain supports. When a user submits a transaction, such as a token transfer, it becomes a signed transaction, verified by the user's account signature. If the account has enough funds to cover fees, the transaction is executed, and the chain's state is updated accordingly. +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. +## Introduction -### Process on a Block Authoring Node +Polkadot offers developers multiple approaches to building and deploying smart contracts within its ecosystem. As a multi-chain network designed for interoperability, Polkadot provides various environments optimized for different developer preferences and application requirements. From native smart contract support on Polkadot Hub to specialized parachain environments, developers can choose the platform that best suits their technical needs while benefiting from Polkadot's shared security model and cross-chain messaging capabilities. -In Polkadot SDK-based networks, some nodes are authorized to author blocks. These nodes validate and process transactions. When a transaction is sent to a node that can produce blocks, it undergoes a lifecycle that involves several stages, including validation and execution. Non-authoring nodes gossip the transaction across the network until an authoring node receives it. The following diagram illustrates the lifecycle of a transaction that's submitted to a network and processed by an authoring node. +Whether you're looking for Ethereum compatibility through EVM-based parachains like [Moonbeam](https://docs.moonbeam.network/){target=\_blank}, [Astar](https://docs.astar.network/){target=\_blank}, and [Acala](https://evmdocs.acala.network/){target=\_blank} or prefer PolkaVM-based development with [ink!](https://use.ink/docs/v6/){target=\_blank}, the Polkadot ecosystem accommodates a range of diverse developers. -![Transaction lifecycle diagram](/images/reference/parachains/blocks-transactions-fees/transactions/transactions-01.webp){ style="background:white" } +These guides explore the diverse smart contract options available in the Polkadot ecosystem, helping developers understand the unique advantages of each approach and make informed decisions about where to deploy their decentralized applications. -### Validate and Queue +## Native Smart Contracts -Once a transaction reaches an authoring node, it undergoes an initial validation process to ensure it meets specific conditions defined in the runtime. This validation includes checks for: +### Introduction -- **Correct nonce**: Ensures the transaction is sequentially valid for the account. -- **Sufficient funds**: Confirms the account can cover any associated transaction fees. -- **Signature validity**: Verifies that the sender's signature matches the transaction data. +Polkadot Hub enables smart contract deployment and execution through PolkaVM, a cutting-edge virtual machine designed specifically for the Polkadot ecosystem. This native integration allows developers to deploy smart contracts directly on Polkadot's system chain while maintaining compatibility with Ethereum development tools and workflows. -After these checks, valid transactions are placed in the transaction pool, where they are queued for inclusion in a block. The transaction pool regularly re-validates queued transactions to ensure they remain valid before being processed. To reach consensus, two-thirds of the nodes must agree on the order of the transactions executed and the resulting state change. Transactions are validated and queued on the local node in a transaction pool to prepare for consensus. +### Smart Contract Development -#### Transaction Pool +The smart contract platform on Polkadot Hub combines _Polkadot's robust security and scalability_ with the extensive Ethereum development ecosystem. Developers can utilize familiar Ethereum libraries for contract interactions and leverage industry-standard development environments for writing and testing smart contracts. -The transaction pool is responsible for managing valid transactions. It ensures that only transactions that pass initial validity checks are queued. Transactions that fail validation, expire, or become invalid for other reasons are removed from the pool. +Polkadot Hub provides _full Ethereum JSON-RPC API compatibility_, ensuring seamless integration with existing development tools and services. This compatibility enables developers to maintain their preferred workflows while building on Polkadot's native infrastructure. -The transaction pool organizes transactions into two queues: +### Technical Architecture -- **Ready queue**: Transactions that are valid and ready to be included in a block. -- **Future queue**: Transactions that are not yet valid but could be in the future, such as transactions with a nonce too high for the current state. +PolkaVM, the underlying virtual machine, utilizes a RISC-V-based register architecture _optimized for the Polkadot ecosystem_. This design choice offers several advantages: -Details on how the transaction pool validates transactions, including fee and signature handling, can be found in the [`validate_transaction`](https://paritytech.github.io/polkadot-sdk/master/sp_transaction_pool/runtime_api/trait.TaggedTransactionQueue.html#method.validate_transaction){target=\_blank} method. +- Enhanced performance for smart contract execution. +- Improved gas efficiency for complex operations. +- Native compatibility with Polkadot's runtime environment. +- Optimized storage and state management. -#### Invalid Transactions +### Development Tools and Resources -If a transaction is invalid, for example, due to an invalid signature or insufficient funds, it is rejected and won't be added to the block. Invalid transactions might be rejected for reasons such as: +Polkadot Hub supports a comprehensive suite of development tools familiar to Ethereum developers. The platform integrates with popular development frameworks, testing environments, and deployment tools. Key features include: -- The transaction has already been included in a block. -- The transaction's signature does not match the sender. -- The transaction is too large to fit in the current block. +- Contract development in Solidity or Rust. +- Support for standard Ethereum development libraries. +- Integration with widely used development environments. +- Access to blockchain explorers and indexing solutions. +- Compatibility with contract monitoring and management tools. -### Transaction Ordering and Priority +### Cross-Chain Capabilities -When a node is selected as the next block author, it prioritizes transactions based on weight, length, and tip amount. The goal is to fill the block with high-priority transactions without exceeding its maximum size or computational limits. Transactions are ordered as follows: +Smart contracts deployed on Polkadot Hub can leverage Polkadot's [cross-consensus messaging (XCM) protocol](/parachains/interoperability/get-started/){target=\_blank} protocol to seamlessly _transfer tokens and call functions on other blockchain networks_ within the Polkadot ecosystem, all without complex bridging infrastructure or third-party solutions. For further references, check the [Interoperability](/develop/interoperability/){target=\_blank} section. -- **Inherents first**: Inherent transactions, such as block timestamp updates, are always placed first. -- **Nonce-based ordering**: Transactions from the same account are ordered by their nonce. -- **Fee-based ordering**: Among transactions with the same nonce or priority level, those with higher fees are prioritized. +### Use Cases -### Transaction Execution +Polkadot Hub's smart contract platform is suitable for a wide range of applications: -Once a block author selects transactions from the pool, the transactions are executed in priority order. As each transaction is processed, the state changes are written directly to the chain's storage. It's important to note that these changes are not cached, meaning a failed transaction won't revert earlier state changes, which could leave the block in an inconsistent state. +- DeFi protocols leveraging _cross-chain capabilities_. +- NFT platforms utilizing Polkadot's native token standards. +- Governance systems integrated with Polkadot's democracy mechanisms. +- Cross-chain bridges and asset management solutions. -Events are also written to storage. Runtime logic should not emit an event before performing the associated actions. If the associated transaction fails after the event was emitted, the event will not revert. +## Other Smart Contract Environments -## Transaction Mortality +Beyond Polkadot Hub's native PolkaVM support, the ecosystem offers two main alternatives for smart contract development: -Transactions in the network can be configured as either mortal (with expiration) or immortal (without expiration). Every transaction payload contains a block checkpoint (reference block number and hash) and an era/validity period that determines how many blocks after the checkpoint the transaction remains valid. +- **EVM-compatible parachains**: Provide access to Ethereum's extensive developer ecosystem, smart contract portability, and established tooling like Hardhat, Remix, Foundry, and OpenZeppelin. The main options include Moonbeam (the first full Ethereum-compatible parachain serving as an interoperability hub), Astar (featuring dual VM support for both EVM and WebAssembly contracts), and Acala (DeFi-focused with enhanced Acala EVM+ offering advanced DeFi primitives). -When a transaction is submitted, the network validates it against these parameters. If the transaction is not included in a block within the specified validity window, it is automatically removed from the transaction queue. +- **Rust (ink!)**: ink! is a Rust-based framework that can compile to PolkaVM. It uses [`#[ink(...)]`](https://use.ink/docs/v6/macros-attributes/){target=\_blank} attribute macros to create Polkadot SDK-compatible PolkaVM bytecode, offering strong memory safety from Rust, an advanced type system, high-performance PolkaVM execution, and platform independence with sandboxed security. -- **Mortal transactions**: Have a finite lifespan and will expire after a specified number of blocks. For example, a transaction with a block checkpoint of 1000 and a validity period of 64 blocks will be valid from blocks 1000 to 1064. -- **Immortal transactions**: Never expire and remain valid indefinitely. To create an immortal transaction, set the block checkpoint to 0 (genesis block), use the genesis hash as a reference, and set the validity period to 0. +Each environment provides unique advantages based on developer preferences and application requirements. -However, immortal transactions pose significant security risks through replay attacks. If an account is reaped (balance drops to zero, account removed) and later re-funded, malicious actors can replay old immortal transactions. +## Where to Go Next -The blockchain maintains only a limited number of prior block hashes for reference validation, called `BlockHashCount`. If your validity period exceeds `BlockHashCount`, the effective validity period becomes the minimum of your specified period and the block hash count. +Developers can use their existing Ethereum development tools and connect to Polkadot Hub's RPC endpoints. The platform's Ethereum compatibility layer ensures a smooth transition for teams already building on Ethereum-compatible chains. -## Unique Identifiers for Extrinsics +Subsequent sections of this guide provide detailed information about specific development tools, advanced features, and best practices for building on Polkadot Hub. -Transaction hashes are **not unique identifiers** in Polkadot SDK-based chains. +
-Key differences from traditional blockchains: +- Guide __Libraries__ -- Transaction hashes serve only as fingerprints of transaction information. -- Multiple valid transactions can share the same hash. -- Hash uniqueness assumptions lead to serious issues. + --- -For example, when an account is reaped (removed due to insufficient balance) and later recreated, it resets to nonce 0, allowing identical transactions to be valid at different points: + Explore essential libraries to optimize smart contract development and interaction. -| Block | Extrinsic Index | Hash | Origin | Nonce | Call | Result | -|-------|----------------|------|-----------|-------|---------------------|-------------------------------| -| 100 | 0 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Account A reaped | -| 150 | 5 | 0x02 | Account B | 4 | Transfer 7 DOT to A | Account A created (nonce = 0) | -| 200 | 2 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Successful transaction | + [:octicons-arrow-right-24: Reference](/smart-contracts/libraries/ethers-js/) -Notice that blocks 100 and 200 contain transactions with identical hashes (0x01) but are completely different, valid operations occurring at different times. +- Guide __Dev Environments__ -Additional complexity comes from Polkadot SDK's origin abstraction. Origins can represent collectives, governance bodies, or other non-account entities that don't maintain nonces like regular accounts and might dispatch identical calls multiple times with the same hash values. Each execution occurs in different chain states with different results. + --- -The correct way to uniquely identify an extrinsic on a Polkadot SDK-based chain is to use the block ID (height or hash) and the extrinsic index. Since the Polkadot SDK defines blocks as headers plus ordered arrays of extrinsics, the index position within a canonical block provides guaranteed uniqueness. + Set up your development environment for seamless contract deployment and testing. -## Additional Resources + [:octicons-arrow-right-24: Reference](/smart-contracts/dev-environments/local-dev-node/) -For a video overview of the lifecycle of transactions and the types of transactions that exist, see the [Transaction lifecycle](https://www.youtube.com/watch?v=3pfM0GOp02c){target=\_blank} seminar from Parity Tech. +
--- @@ -8604,351 +4029,6 @@ The system maintains precise conversion mechanisms between: This ensures accurate fee calculation while maintaining compatibility with existing Ethereum tools and workflows. ---- - -Page Title: Transactions Weights and Fees - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-fees.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/fees/ -- Summary: Overview of transaction weights and fees in Polkadot SDK chains, detailing how fees are calculated using a defined formula and runtime specifics. - -# Transactions Weights and Fees - -## Introductions - -When transactions are executed, or data is stored on-chain, the activity changes the chain's state and consumes blockchain resources. Because the resources available to a blockchain are limited, managing how operations on-chain consume them is important. In addition to being limited in practical terms, such as storage capacity, blockchain resources represent a potential attack vector for malicious users. For example, a malicious user might attempt to overload the network with messages to stop the network from producing new blocks. To protect blockchain resources from being drained or overloaded, you need to manage how they are made available and how they are consumed. The resources to be aware of include: - -- Memory usage -- Storage input and output -- Computation -- Transaction and block size -- State database size - -The Polkadot SDK provides block authors with several ways to manage access to resources and to prevent individual components of the chain from consuming too much of any single resource. Two of the most important mechanisms available to block authors are weights and transaction fees. - -[Weights](/reference/glossary/#weight){target=\_blank} manage the time it takes to validate a block and characterize the time it takes to execute the calls in the block's body. By controlling the execution time a block can consume, weights set limits on storage input, output, and computation. - -Some of the weight allowed for a block is consumed as part of the block's initialization and finalization. The weight might also be used to execute mandatory inherent extrinsic calls. To help ensure blocks don’t consume too much execution time and prevent malicious users from overloading the system with unnecessary calls, weights are combined with transaction fees. - -[Transaction fees](/reference/parachains/blocks-transactions-fees/transactions/#transaction-fees){target=\_blank} provide an economic incentive to limit execution time, computation, and the number of calls required to perform operations. Transaction fees are also used to make the blockchain economically sustainable because they are typically applied to transactions initiated by users and deducted before a transaction request is executed. - -## How Fees are Calculated - -The final fee for a transaction is calculated using the following parameters: - -- **`base fee`**: This is the minimum amount a user pays for a transaction. It is declared a base weight in the runtime and converted to a fee using the [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} conversion. -- **`weight fee`**: A fee proportional to the execution time (input and output and computation) that a transaction consumes. -- **`length fee`**: A fee proportional to the encoded length of the transaction. -- **`tip`**: An optional tip to increase the transaction’s priority, giving it a higher chance to be included in the transaction queue. - -The base fee and proportional weight and length fees constitute the inclusion fee. The inclusion fee is the minimum fee that must be available for a transaction to be included in a block. - -```text -inclusion fee = base fee + weight fee + length fee -``` - -Transaction fees are withdrawn before the transaction is executed. After the transaction is executed, the weight can be adjusted to reflect the resources used. If a transaction uses fewer resources than expected, the transaction fee is corrected, and the adjusted transaction fee is deposited. - -## Using the Transaction Payment Pallet - -The [Transaction Payment pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/transaction-payment){target=\_blank} provides the basic logic for calculating the inclusion fee. You can also use the Transaction Payment pallet to: - -- Convert a weight value into a deductible fee based on a currency type using [`Config::WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank}. -- Update the fee for the next block by defining a multiplier based on the chain’s final state at the end of the previous block using [`Config::FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank}. -- Manage the withdrawal, refund, and deposit of transaction fees using [`Config::OnChargeTransaction`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.OnChargeTransaction){target=\_blank}. - -You can learn more about these configuration traits in the [Transaction Payment documentation](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_payment/index.html){target=\_blank}. - -### Understanding the Inclusion Fee - -The formula for calculating the inclusion fee is as follows: - -```text -inclusion_fee = base_fee + length_fee + [targeted_fee_adjustment * weight_fee] -``` - -And then, for calculating the final fee: - -```text -final_fee = inclusion_fee + tip -``` - -In the first formula, the `targeted_fee_adjustment` is a multiplier that can tune the final fee based on the network’s congestion. - -- The `base_fee` derived from the base weight covers inclusion overhead like signature verification. -- The `length_fee` is a per-byte fee that is multiplied by the length of the encoded extrinsic. -- The `weight_fee` fee is calculated using two parameters: - - The `ExtrinsicBaseWeight` that is declared in the runtime and applies to all extrinsics. - - The `#[pallet::weight]` annotation that accounts for an extrinsic's complexity. - -To convert the weight to `Currency`, the runtime must define a `WeightToFee` struct that implements a conversion function, [`Convert`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/struct.Pallet.html#method.weight_to_fee){target=\_blank}. - -Note that the extrinsic sender is charged the inclusion fee before the extrinsic is invoked. The fee is deducted from the sender's balance even if the transaction fails upon execution. - -### Accounts with an Insufficient Balance - -If an account does not have a sufficient balance to pay the inclusion fee and remain alive—that is, enough to pay the inclusion fee and maintain the minimum existential deposit—then you should ensure the transaction is canceled so that no fee is deducted and the transaction does not begin execution. - -The Polkadot SDK doesn't enforce this rollback behavior. However, this scenario would be rare because the transaction queue and block-making logic perform checks to prevent it before adding an extrinsic to a block. - -### Fee Multipliers - -The inclusion fee formula always results in the same fee for the same input. However, weight can be dynamic and—based on how [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} is defined—the final fee can include some degree of variability. -The Transaction Payment pallet provides the [`FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank} configurable parameter to account for this variability. - -The Polkadot network inspires the default update function and implements a targeted adjustment in which a target saturation level of block weight is defined. If the previous block is more saturated, the fees increase slightly. Similarly, if the last block has fewer transactions than the target, fees are decreased by a small amount. For more information about fee multiplier adjustments, see the [Web3 Research Page](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank}. - -## Transactions with Special Requirements - -Inclusion fees must be computable before execution and can only represent fixed logic. Some transactions warrant limiting resources with other strategies. For example: - -- Bonds are a type of fee that might be returned or slashed after some on-chain event. For example, you might want to require users to place a bond to participate in a vote. The bond might then be returned at the end of the referendum or slashed if the voter attempted malicious behavior. -- Deposits are fees that might be returned later. For example, you might require users to pay a deposit to execute an operation that uses storage. The user’s deposit could be returned if a subsequent operation frees up storage. -- Burn operations are used to pay for a transaction based on its internal logic. For example, a transaction might burn funds from the sender if the transaction creates new storage items to pay for the increased state size. -- Limits enable you to enforce constant or configurable limits on specific operations. For example, the default [Staking pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/staking){target=\_blank} only allows nominators to nominate 16 validators to limit the complexity of the validator election process. - -It is important to note that if you query the chain for a transaction fee, it only returns the inclusion fee. - -## Default Weight Annotations - -All dispatchable functions in the Polkadot SDK must specify a weight. The way of doing that is using the annotation-based system that lets you combine fixed values for database read/write weight and/or fixed values based on benchmarks. The most basic example would look like this: - -```rust -#[pallet::weight(100_000)] -fn my_dispatchable() { - // ... -} -``` - -Note that the [`ExtrinsicBaseWeight`](https://crates.parity.io/frame_support/weights/constants/struct.ExtrinsicBaseWeight.html){target=\_blank} is automatically added to the declared weight to account for the costs of simply including an empty extrinsic into a block. - -### Weights and Database Read/Write Operations - -To make weight annotations independent of the deployed database backend, they are defined as a constant and then used in the annotations when expressing database accesses performed by the dispatchable: - -```rust -#[pallet::weight(T::DbWeight::get().reads_writes(1, 2) + 20_000)] -fn my_dispatchable() { - // ... -} -``` - -This dispatchable allows one database to read and two to write, in addition to other things that add the additional 20,000. Database access is generally every time a value declared inside the [`#[pallet::storage]`](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/attr.storage.html){target=\_blank} block is accessed. However, unique accesses are counted because after a value is accessed, it is cached, and reaccessing it does not result in a database operation. That is: - -- Multiple reads of the exact value count as one read. -- Multiple writes of the exact value count as one write. -- Multiple reads of the same value, followed by a write to that value, count as one read and one write. -- A write followed by a read-only counts as one write. - -### Dispatch Classes - -Dispatches are broken into three classes: - -- Normal -- Operational -- Mandatory - -If a dispatch is not defined as `Operational` or `Mandatory` in the weight annotation, the dispatch is identified as `Normal` by default. You can specify that the dispatchable uses another class like this: - -```rust -#[pallet::dispatch((DispatchClass::Operational))] -fn my_dispatchable() { - // ... -} -``` - -This tuple notation also allows you to specify a final argument determining whether the user is charged based on the annotated weight. If you don't specify otherwise, `Pays::Yes` is assumed: - -```rust -#[pallet::dispatch(DispatchClass::Normal, Pays::No)] -fn my_dispatchable() { - // ... -} -``` - -#### Normal Dispatches - -Dispatches in this class represent normal user-triggered transactions. These types of dispatches only consume a portion of a block's total weight limit. For information about the maximum portion of a block that can be consumed for normal dispatches, see [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Normal dispatches are sent to the transaction pool. - -#### Operational Dispatches - -Unlike normal dispatches, which represent the usage of network capabilities, operational dispatches are those that provide network capabilities. Operational dispatches can consume the entire weight limit of a block. They are not bound by the [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Dispatches in this class are given maximum priority and are exempt from paying the [`length_fee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/){target=\_blank}. - -#### Mandatory Dispatches - -Mandatory dispatches are included in a block even if they cause the block to surpass its weight limit. You can only use the mandatory dispatch class for inherent transactions that the block author submits. This dispatch class is intended to represent functions in the block validation process. Because these dispatches are always included in a block regardless of the function weight, the validation process must prevent malicious nodes from abusing the function to craft valid but impossibly heavy blocks. You can typically accomplish this by ensuring that: - -- The operation performed is always light. -- The operation can only be included in a block once. - -To make it more difficult for malicious nodes to abuse mandatory dispatches, they cannot be included in blocks that return errors. This dispatch class serves the assumption that it is better to allow an overweight block to be created than not to allow any block to be created at all. - -### Dynamic Weights - -In addition to purely fixed weights and constants, the weight calculation can consider the input arguments of a dispatchable. The weight should be trivially computable from the input arguments with some basic arithmetic: - -```rust -use frame_support:: { - dispatch:: { - DispatchClass::Normal, - Pays::Yes, - }, - weights::Weight, -}; - -#[pallet::weight(FunctionOf( - |args: (&Vec,)| args.0.len().saturating_mul(10_000), - ) -] -fn handle_users(origin, calls: Vec) { - // Do something per user -} -``` - -## Post Dispatch Weight Correction - -Depending on the execution logic, a dispatchable function might consume less weight than was prescribed pre-dispatch. To correct weight, the function declares a different return type and returns its actual weight: - -```rust -#[pallet::weight(10_000 + 500_000_000)] -fn expensive_or_cheap(input: u64) -> DispatchResultWithPostInfo { - let was_heavy = do_calculation(input); - - if (was_heavy) { - // None means "no correction" from the weight annotation. - Ok(None.into()) - } else { - // Return the actual weight consumed. - Ok(Some(10_000).into()) - } -} -``` - -## Custom Fees - -You can also define custom fee systems through custom weight functions or inclusion fee functions. - -### Custom Weights - -Instead of using the default weight annotations, you can create a custom weight calculation type using the weights module. The custom weight calculation type must implement the following traits: - -- [`WeighData`](https://crates.parity.io/frame_support/weights/trait.WeighData.html){target=\_blank} to determine the weight of the dispatch. -- [`ClassifyDispatch`](https://crates.parity.io/frame_support/weights/trait.ClassifyDispatch.html){target=\_blank} to determine the class of the dispatch. -- [`PaysFee`](https://crates.parity.io/frame_support/weights/trait.PaysFee.html){target=\_blank} to determine whether the sender of the dispatch pays fees. - -The Polkadot SDK then bundles the output information of the three traits into the [`DispatchInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_support/dispatch/struct.DispatchInfo.html){target=\_blank} struct and provides it by implementing the [`GetDispatchInfo`](https://docs.rs/frame-support/latest/frame_support/dispatch/trait.GetDispatchInfo.html){target=\_blank} for all `Call` variants and opaque extrinsic types. This is used internally by the System and Executive modules. - -`ClassifyDispatch`, `WeighData`, and `PaysFee` are generic over T, which gets resolved into the tuple of all dispatch arguments except for the origin. The following example illustrates a struct that calculates the weight as `m * len(args)`, where `m` is a given multiplier and args is the concatenated tuple of all dispatch arguments. In this example, the dispatch class is `Operational` if the transaction has more than 100 bytes of length in arguments and will pay fees if the encoded length exceeds 10 bytes. - -```rust -struct LenWeight(u32); -impl WeighData for LenWeight { - fn weigh_data(&self, target: T) -> Weight { - let multiplier = self.0; - let encoded_len = target.encode().len() as u32; - multiplier * encoded_len - } -} - -impl ClassifyDispatch for LenWeight { - fn classify_dispatch(&self, target: T) -> DispatchClass { - let encoded_len = target.encode().len() as u32; - if encoded_len > 100 { - DispatchClass::Operational - } else { - DispatchClass::Normal - } - } -} - -impl PaysFee { - fn pays_fee(&self, target: T) -> Pays { - let encoded_len = target.encode().len() as u32; - if encoded_len > 10 { - Pays::Yes - } else { - Pays::No - } - } -} -``` - -A weight calculator function can also be coerced to the final type of the argument instead of defining it as a vague type that can be encoded. The code would roughly look like this: - -```rust -struct CustomWeight; -impl WeighData<(&u32, &u64)> for CustomWeight { - fn weigh_data(&self, target: (&u32, &u64)) -> Weight { - ... - } -} - -// given a dispatch: -#[pallet::call] -impl, I: 'static> Pallet { - #[pallet::weight(CustomWeight)] - fn foo(a: u32, b: u64) { ... } -} -``` - -In this example, the `CustomWeight` can only be used in conjunction with a dispatch with a particular signature `(u32, u64)`, as opposed to `LenWeight`, which can be used with anything because there aren't any assumptions about ``. - -#### Custom Inclusion Fee - -The following example illustrates how to customize your inclusion fee. You must configure the appropriate associated types in the respective module. - -```rust -// Assume this is the balance type -type Balance = u64; - -// Assume we want all the weights to have a `100 + 2 * w` conversion to fees -struct CustomWeightToFee; -impl WeightToFee for CustomWeightToFee { - fn convert(w: Weight) -> Balance { - let a = Balance::from(100); - let b = Balance::from(2); - let w = Balance::from(w); - a + b * w - } -} - -parameter_types! { - pub const ExtrinsicBaseWeight: Weight = 10_000_000; -} - -impl frame_system::Config for Runtime { - type ExtrinsicBaseWeight = ExtrinsicBaseWeight; -} - -parameter_types! { - pub const TransactionByteFee: Balance = 10; -} - -impl transaction_payment::Config { - type TransactionByteFee = TransactionByteFee; - type WeightToFee = CustomWeightToFee; - type FeeMultiplierUpdate = TargetedFeeAdjustment; -} - -struct TargetedFeeAdjustment(sp_std::marker::PhantomData); -impl> WeightToFee for TargetedFeeAdjustment { - fn convert(multiplier: Fixed128) -> Fixed128 { - // Don't change anything. Put any fee update info here. - multiplier - } -} -``` - -## Additional Resources - -You now know the weight system, how it affects transaction fee computation, and how to specify weights for your dispatchable calls. The next step is determining the correct weight for your dispatchable operations. You can use Substrate benchmarking functions and frame-benchmarking calls to test your functions with different parameters and empirically determine the proper weight in their worst-case scenarios. - -- [Benchmark](/parachains/customize-runtime/pallet-development/benchmark-pallet/) -- [`SignedExtension`](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} -- [Custom weights for the Example pallet](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/substrate/frame/examples/basic/src/weights.rs){target=\_blank} -- [Web3 Foundation Research](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank} - - --- Page Title: Wallets @@ -9035,91 +4115,3 @@ Wallet types fall into two categories based on their connection to the internet: - - ---- - -Page Title: XCM Tools - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-xcm-tools.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/xcm-tools/ -- Summary: Explore essential XCM tools across Polkadot, crafted to enhance cross-chain functionality and integration within the ecosystem. - -# XCM Tools - -## Introduction - -As described in the [Interoperability](/develop/interoperability){target=\_blank} section, XCM (Cross-Consensus Messaging) is a protocol used in the Polkadot and Kusama ecosystems to enable communication and interaction between chains. It facilitates cross-chain communication, allowing assets, data, and messages to flow seamlessly across the ecosystem. - -As XCM is central to enabling communication between blockchains, developers need robust tools to help interact with, build, and test XCM messages. Several XCM tools simplify working with the protocol by providing libraries, frameworks, and utilities that enhance the development process, ensuring that applications built within the Polkadot ecosystem can efficiently use cross-chain functionalities. - -## Popular XCM Tools - -### Moonsong Labs XCM Tools - -[Moonsong Labs XCM Tools](https://github.com/Moonsong-Labs/xcm-tools){target=\_blank} provides a collection of scripts for managing and testing XCM operations between Polkadot SDK-based runtimes. These tools allow performing tasks like asset registration, channel setup, and XCM initialization. Key features include: - -- **Asset registration**: Registers assets, setting units per second (up-front fees), and configuring error (revert) codes. -- **XCM initializer**: Initializes XCM, sets default XCM versions, and configures revert codes for XCM-related precompiles. -- **HRMP manipulator**: Manages HRMP channel actions, including opening, accepting, or closing channels. -- **XCM-Transactor-Info-Setter**: Configures transactor information, including extra weight and fee settings. -- **Decode XCM**: Decodes XCM messages on the relay chain or parachains to help interpret cross-chain communication. - -To get started, clone the repository and install the required dependencies: - -```bash -git clone https://github.com/Moonsong-Labs/xcm-tools && -cd xcm-tools && -yarn install -``` - -For a full overview of each script, visit the [scripts](https://github.com/Moonsong-Labs/xcm-tools/tree/main/scripts){target=\_blank} directory or refer to the [official documentation](https://github.com/Moonsong-Labs/xcm-tools/blob/main/README.md){target=\_blank} on GitHub. - -### ParaSpell - -[ParaSpell](/reference/tools/paraspell/){target=\_blank} is a collection of open-source XCM tools that streamline cross-chain asset transfers and interactions across the Polkadot and Kusama ecosystems. It provides developers with an intuitive interface to build, test, and deploy interoperable dApps, featuring message composition, decoding, and practical utilities for parachain interactions that simplify debugging and cross-chain communication optimization. - -### Astar XCM Tools - -The [Astar parachain](https://github.com/AstarNetwork/Astar/tree/master){target=\_blank} offers a crate with a set of utilities for interacting with the XCM protocol. The [xcm-tools](https://github.com/AstarNetwork/Astar/tree/master/bin/xcm-tools){target=\_blank} crate provides a straightforward method for users to locate a sovereign account or calculate an XC20 asset ID. Some commands included by the xcm-tools crate allow users to perform the following tasks: - -- **Sovereign accounts**: Obtain the sovereign account address for any parachain, either on the Relay Chain or for sibling parachains, using a simple command. -- **XC20 EVM addresses**: Generate XC20-compatible Ethereum addresses for assets by entering the asset ID, making it easy to integrate assets across Ethereum-compatible environments. -- **Remote accounts**: Retrieve remote account addresses needed for multi-location compatibility, using flexible options to specify account types and parachain IDs. - -To start using these tools, clone the [Astar repository](https://github.com/AstarNetwork/Astar){target=\_blank} and compile the xcm-tools package: - -```bash -git clone https://github.com/AstarNetwork/Astar && -cd Astar && -cargo build --release -p xcm-tools -``` - -After compiling, verify the setup with the following command: - -```bash -./target/release/xcm-tools --help -``` -For more details on using Astar xcm-tools, consult the [official documentation](https://docs.astar.network/docs/learn/interoperability/xcm/integration/tools/){target=\_blank}. - -### Chopsticks - -The Chopsticks library provides XCM functionality for testing XCM messages across networks, enabling you to fork multiple parachains along with a relay chain. For further details, see the [Chopsticks documentation](/tutorials/polkadot-sdk/testing/fork-live-chains/){target=\_blank} about XCM. - -### Moonbeam XCM SDK - -The [Moonbeam XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk){target=\_blank} enables developers to easily transfer assets between chains, either between parachains or between a parachain and the relay chain, within the Polkadot/Kusama ecosystem. With the SDK, you don't need to worry about determining the [Multilocation](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#7-universal-consensus-location-identifiers){target=\_blank} of the origin or destination assets or which extrinsics are used on which networks. - -The SDK consists of two main packages: - -- **[XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/sdk){target=\_blank}**: Core SDK for executing XCM transfers between chains in the Polkadot/Kusama ecosystem. -- **[MRL SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/mrl){target=\_blank}**: Extension of the XCM SDK for transferring liquidity into and across the Polkadot ecosystem from other ecosystems like Ethereum. - -Key features include: - -- **Simplified asset transfers**: Abstracts away complex multilocation determinations and extrinsic selection. -- **Cross-ecosystem support**: Enables transfers between Polkadot/Kusama chains and external ecosystems. -- **Developer-friendly API**: Provides intuitive interfaces for cross-chain functionality. -- **Comprehensive documentation**: Includes usage guides and API references for both packages. - -For detailed usage examples and API documentation, visit the [official Moonbeam XCM SDK documentation](https://moonbeam-foundation.github.io/xcm-sdk/latest/){target=\_blank}. diff --git a/.ai/categories/infrastructure.md b/.ai/categories/infrastructure.md index 100597494..fdb9107eb 100644 --- a/.ai/categories/infrastructure.md +++ b/.ai/categories/infrastructure.md @@ -474,440 +474,6 @@ Launch your parachain locally and start producing blocks: ---- - -Page Title: Blocks - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-blocks.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/blocks/ -- Summary: Understand how blocks are produced, validated, and imported in Polkadot SDK-based blockchains, covering initialization, finalization, and authoring processes. - -# Blocks - -## Introduction - -In the Polkadot SDK, blocks are fundamental to the functioning of the blockchain, serving as containers for [transactions](/reference/parachains/blocks-transactions-fees/transactions/){target=\_blank} and changes to the chain's state. Blocks consist of headers and an array of transactions, ensuring the integrity and validity of operations on the network. This guide explores the essential components of a block, the process of block production, and how blocks are validated and imported across the network. By understanding these concepts, developers can better grasp how blockchains maintain security, consistency, and performance within the Polkadot ecosystem. - -## What is a Block? - -In the Polkadot SDK, a block is a fundamental unit that encapsulates both the header and an array of transactions. The block header includes critical metadata to ensure the integrity and sequence of the blockchain. Here's a breakdown of its components: - -- **Block height**: Indicates the number of blocks created in the chain so far. -- **Parent hash**: The hash of the previous block, providing a link to maintain the blockchain's immutability. -- **Transaction root**: Cryptographic digest summarizing all transactions in the block. -- **State root**: A cryptographic digest representing the post-execution state. -- **Digest**: Additional information that can be attached to a block, such as consensus-related messages. - -Each transaction is part of a series that is executed according to the runtime's rules. The transaction root is a cryptographic digest of this series, which prevents alterations and enables succinct verification by light clients. This verification process allows light clients to confirm whether a transaction exists in a block with only the block header, avoiding downloading the entire block. - -## Block Production - -When an authoring node is authorized to create a new block, it selects transactions from the transaction queue based on priority. This step, known as block production, relies heavily on the executive module to manage the initialization and finalization of blocks. The process is summarized as follows: - -### Initialize Block - -The block initialization process begins with a series of function calls that prepare the block for transaction execution: - -1. **Call `on_initialize`**: The executive module calls the [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} hook from the system pallet and other runtime pallets to prepare for the block's transactions. -2. **Coordinate runtime calls**: Coordinates function calls in the order defined by the transaction queue. -3. **Verify information**: Once [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} functions are executed, the executive module checks the parent hash in the block header and the trie root to verify information is consistent. - -### Finalize Block - -Once transactions are processed, the block must be finalized before being broadcast to the network. The finalization steps are as follows: - -1. **Call `on_finalize`**: The executive module calls the [`on_finalize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_finalize){target=\_blank} hooks in each pallet to ensure any remaining state updates or checks are completed before the block is sealed and published. -2. **Verify information**: The block's digest and storage root in the header are checked against the initialized block to ensure consistency. -3. **Call `on_idle`**: The [`on_idle`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_idle){target=\_blank} hook is triggered to process any remaining tasks using the leftover weight from the block. - -## Block Authoring and Import - -Once the block is finalized, it is gossiped to other nodes in the network. Nodes follow this procedure: - -1. **Receive transactions**: The authoring node collects transactions from the network. -2. **Validate**: Transactions are checked for validity. -3. **Queue**: Valid transactions are placed in the transaction pool for execution. -4. **Execute**: State changes are made as the transactions are executed. -5. **Publish**: The finalized block is broadcast to the network. - -### Block Import Queue - -After a block is published, other nodes on the network can import it into their chain state. The block import queue is part of the outer node in every Polkadot SDK-based node and ensures incoming blocks are valid before adding them to the node's state. - -In most cases, you don't need to know details about how transactions are gossiped or how other nodes on the network import blocks. The following traits are relevant, however, if you plan to write any custom consensus logic or want a deeper dive into the block import queue: - -- **[`ImportQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.ImportQueue.html){target=\_blank}**: The trait that defines the block import queue. -- **[`Link`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Link.html){target=\_blank}**: The trait that defines the link between the block import queue and the network. -- **[`BasicQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/struct.BasicQueue.html){target=\_blank}**: A basic implementation of the block import queue. -- **[`Verifier`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Verifier.html){target=\_blank}**: The trait that defines the block verifier. -- **[`BlockImport`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/block_import/trait.BlockImport.html){target=\_blank}**: The trait that defines the block import process. - -These traits govern how blocks are validated and imported across the network, ensuring consistency and security. - -## Additional Resources - -To learn more about the block structure in the Polkadot SDK runtime, see the [`Block` reference](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.Block.html){target=\_blank} entry in the Rust Docs. - - ---- - -Page Title: Chain Data - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-chain-data.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/chain-data/ -- Summary: Learn how to expose and utilize chain data for blockchain applications. Discover runtime metadata, RPC APIs, and tools for efficient development. - -# Chain Data - -## Introduction - -Understanding and leveraging on-chain data is a fundamental aspect of blockchain development. Whether you're building frontend applications or backend systems, accessing and decoding runtime metadata is vital to interacting with the blockchain. This guide introduces you to the tools and processes for generating and retrieving metadata, explains its role in application development, and outlines the additional APIs available for interacting with a Polkadot node. By mastering these components, you can ensure seamless communication between your applications and the blockchain. - -## Application Development - -You might not be directly involved in building frontend applications as a blockchain developer. However, most applications that run on a blockchain require some form of frontend or user-facing client to enable users or other programs to access and modify the data that the blockchain stores. For example, you might develop a browser-based, mobile, or desktop application that allows users to submit transactions, post articles, view their assets, or track previous activity. The backend for that application is configured in the runtime logic for your blockchain, but the frontend client makes the runtime features accessible to your users. - -For your custom chain to be useful to others, you'll need to provide a client application that allows users to view, interact with, or update information that the blockchain keeps track of. In this article, you'll learn how to expose information about your runtime so that client applications can use it, see examples of the information exposed, and explore tools and libraries that use it. - -## Understand Metadata - -Polkadot SDK-based blockchain networks are designed to expose their runtime information, allowing developers to learn granular details regarding pallets, RPC calls, and runtime APIs. The metadata also exposes their related documentation. The chain's metadata is [SCALE-encoded](/reference/parachains/data-encoding/){target=\_blank}, allowing for the development of browser-based, mobile, or desktop applications to support the chain's runtime upgrades seamlessly. It is also possible to develop applications compatible with multiple Polkadot SDK-based chains simultaneously. - -## Expose Runtime Information as Metadata - -To interact with a node or the state of the blockchain, you need to know how to connect to the chain and access the exposed runtime features. This interaction involves a Remote Procedure Call (RPC) through a node endpoint address, commonly through a secure web socket connection. - -An application developer typically needs to know the contents of the runtime logic, including the following details: - -- Version of the runtime the application is connecting to. -- Supported APIs. -- Implemented pallets. -- Defined functions and corresponding type signatures. -- Defined custom types. -- Exposed parameters users can set. - -As the Polkadot SDK is modular and provides a composable framework for building blockchains, there are limitless opportunities to customize the schema of properties. Each runtime can be configured with its properties, including function calls and types, which can be changed over time with runtime upgrades. - -The Polkadot SDK enables you to generate the runtime metadata schema to capture information unique to a runtime. The metadata for a runtime describes the pallets in use and types defined for a specific runtime version. The metadata includes information about each pallet's storage items, functions, events, errors, and constants. The metadata also provides type definitions for any custom types included in the runtime. - -Metadata provides a complete inventory of a chain's runtime. It is key to enabling client applications to interact with the node, parse responses, and correctly format message payloads sent back to that chain. - -## Generate Metadata - -To efficiently use the blockchain's networking resources and minimize the data transmitted over the network, the metadata schema is encoded using the [Parity SCALE Codec](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank}. This encoding is done automatically through the [`scale-info`](https://docs.rs/scale-info/latest/scale_info/){target=\_blank}crate. - -At a high level, generating the metadata involves the following steps: - -1. The pallets in the runtime logic expose callable functions, types, parameters, and documentation that need to be encoded in the metadata. -2. The `scale-info` crate collects type information for the pallets in the runtime, builds a registry of the pallets that exist in a particular runtime, and the relevant types for each pallet in the registry. The type information is detailed enough to enable encoding and decoding for every type. -3. The [`frame-metadata`](https://github.com/paritytech/frame-metadata){target=\_blank} crate describes the structure of the runtime based on the registry provided by the `scale-info` crate. -4. Nodes provide the RPC method `state_getMetadata` to return a complete description of all the types in the current runtime as a hex-encoded vector of SCALE-encoded bytes. - -## Retrieve Runtime Metadata - -The type information provided by the metadata enables applications to communicate with nodes using different runtime versions and across chains that expose different calls, events, types, and storage items. The metadata also allows libraries to generate a substantial portion of the code needed to communicate with a given node, enabling libraries like [`subxt`](https://github.com/paritytech/subxt){target=\_blank} to generate frontend interfaces that are specific to a target chain. - -### Use Polkadot.js - -Visit the [Polkadot.js Portal](https://polkadot.js.org/apps/#/rpc){target=\_blank} and select the **Developer** dropdown in the top banner. Select **RPC Calls** to make the call to request metadata. Follow these steps to make the RPC call: - -1. Select **state** as the endpoint to call. -2. Select **`getMetadata(at)`** as the method to call. -3. Click **Submit RPC call** to submit the call and return the metadata in JSON format. - -### Use Curl - -You can fetch the metadata for the network by calling the node's RPC endpoint. This request returns the metadata in bytes rather than human-readable JSON: - -```sh -curl -H "Content-Type: application/json" \ --d '{"id":1, "jsonrpc":"2.0", "method": "state_getMetadata"}' \ -https://rpc.polkadot.io - -``` - -### Use Subxt - -[`subxt`](https://github.com/paritytech/subxt){target=\_blank} may also be used to fetch the metadata of any data in a human-readable JSON format: - -```sh -subxt metadata --url wss://rpc.polkadot.io --format json > spec.json -``` - -Another option is to use the [`subxt` explorer web UI](https://paritytech.github.io/subxt-explorer/#/){target=\_blank}. - -## Client Applications and Metadata - -The metadata exposes the expected way to decode each type, meaning applications can send, retrieve, and process application information without manual encoding and decoding. Client applications must use the [SCALE codec library](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank} to encode and decode RPC payloads to use the metadata. Client applications use the metadata to interact with the node, parse responses, and format message payloads sent to the node. - -## Metadata Format - -Although the SCALE-encoded bytes can be decoded using the `frame-metadata` and [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} libraries, there are other tools, such as `subxt` and the Polkadot-JS API, that can convert the raw data to human-readable JSON format. - -The types and type definitions included in the metadata returned by the `state_getMetadata` RPC call depend on the runtime's metadata version. - -In general, the metadata includes the following information: - -- A constant identifying the file as containing metadata. -- The version of the metadata format used in the runtime. -- Type definitions for all types used in the runtime and generated by the `scale-info` crate. -- Pallet information for the pallets included in the runtime in the order that they are defined in the `construct_runtime` macro. - -!!!tip - Depending on the frontend library used (such as the [Polkadot API](https://papi.how/){target=\_blank}), they may format the metadata differently than the raw format shown. - -The following example illustrates a condensed and annotated section of metadata decoded and converted to JSON: - -```json -[ - 1635018093, - { - "V14": { - "types": { - "types": [{}] - }, - "pallets": [{}], - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [{}] - }, - "ty": 141 - } - } -] - -``` - -The constant `1635018093` is a magic number that identifies the file as a metadata file. The rest of the metadata is divided into the `types`, `pallets`, and `extrinsic` sections: - -- The `types` section contains an index of the types and information about each type's type signature. -- The `pallets` section contains information about each pallet in the runtime. -- The `extrinsic` section describes the type identifier and transaction format version that the runtime uses. - -Different extrinsic versions can have varying formats, especially when considering [signed transactions](/reference/parachains/blocks-transactions-fees/transactions/#signed-transactions){target=\_blank}. - -### Pallets - -The following is a condensed and annotated example of metadata for a single element in the `pallets` array (the [`sudo`](https://paritytech.github.io/polkadot-sdk/master/pallet_sudo/index.html){target=\_blank} pallet): - -```json -{ - "name": "Sudo", - "storage": { - "prefix": "Sudo", - "entries": [ - { - "name": "Key", - "modifier": "Optional", - "ty": { - "Plain": 0 - }, - "default": [0], - "docs": ["The `AccountId` of the sudo key."] - } - ] - }, - "calls": { - "ty": 117 - }, - "event": { - "ty": 42 - }, - "constants": [], - "error": { - "ty": 124 - }, - "index": 8 -} - -``` - -Every element metadata contains the name of the pallet it represents and information about its storage, calls, events, and errors. You can look up details about the definition of the calls, events, and errors by viewing the type index identifier. The type index identifier is the `u32` integer used to access the type information for that item. For example, the type index identifier for calls in the Sudo pallet is 117. If you view information for that type identifier in the `types` section of the metadata, it provides information about the available calls, including the documentation for each call. - -For example, the following is a condensed excerpt of the calls for the Sudo pallet: - -```json -{ - "id": 117, - "type": { - "path": ["pallet_sudo", "pallet", "Call"], - "params": [ - { - "name": "T", - "type": null - } - ], - "def": { - "variant": { - "variants": [ - { - "name": "sudo", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 0, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "sudo_unchecked_weight", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - }, - { - "name": "weight", - "type": 8, - "typeName": "Weight" - } - ], - "index": 1, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "set_key", - "fields": [ - { - "name": "new", - "type": 103, - "typeName": "AccountIdLookupOf" - } - ], - "index": 2, - "docs": [ - "Authenticates current sudo key, sets the given AccountId (`new`) as the new sudo" - ] - }, - { - "name": "sudo_as", - "fields": [ - { - "name": "who", - "type": 103, - "typeName": "AccountIdLookupOf" - }, - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 3, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Signed` origin from a given account" - ] - } - ] - } - } - } -} - -``` - -For each field, you can access type information and metadata for the following: - -- **Storage metadata**: Provides the information required to enable applications to get information for specific storage items. -- **Call metadata**: Includes information about the runtime calls defined by the `#[pallet]` macro including call names, arguments and documentation. -- **Event metadata**: Provides the metadata generated by the `#[pallet::event]` macro, including the name, arguments, and documentation for each pallet event. -- **Constants metadata**: Provides metadata generated by the `#[pallet::constant]` macro, including the name, type, and hex-encoded value of the constant. -- **Error metadata**: Provides metadata generated by the `#[pallet::error]` macro, including the name and documentation for each pallet error. - -!!!tip - Type identifiers change from time to time, so you should avoid relying on specific type identifiers in your applications. - -### Extrinsic - -The runtime generates extrinsic metadata and provides useful information about transaction format. When decoded, the metadata contains the transaction version and the list of signed extensions. - -For example: - -```json -{ - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [ - { - "identifier": "CheckNonZeroSender", - "ty": 132, - "additional_signed": 41 - }, - { - "identifier": "CheckSpecVersion", - "ty": 133, - "additional_signed": 4 - }, - { - "identifier": "CheckTxVersion", - "ty": 134, - "additional_signed": 4 - }, - { - "identifier": "CheckGenesis", - "ty": 135, - "additional_signed": 11 - }, - { - "identifier": "CheckMortality", - "ty": 136, - "additional_signed": 11 - }, - { - "identifier": "CheckNonce", - "ty": 138, - "additional_signed": 41 - }, - { - "identifier": "CheckWeight", - "ty": 139, - "additional_signed": 41 - }, - { - "identifier": "ChargeTransactionPayment", - "ty": 140, - "additional_signed": 41 - } - ] - }, - "ty": 141 -} - -``` - -The type system is [composite](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/frame_runtime_types/index.html){target=\_blank}, meaning each type identifier contains a reference to a specific type or to another type identifier that provides information about the associated primitive types. - -For example, you can encode the `BitVec` type, but to decode it properly, you must know the types used for the `Order` and `Store` types. To find type information for `Order` and `Store`, you can use the path in the decoded JSON to locate their type identifiers. - -## Included RPC APIs - -A standard node comes with the following APIs to interact with a node: - -- **[`AuthorApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/author/trait.AuthorApiServer.html){target=\_blank}**: Make calls into a full node, including authoring extrinsics and verifying session keys. -- **[`ChainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/chain/trait.ChainApiServer.html){target=\_blank}**: Retrieve block header and finality information. -- **[`OffchainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/offchain/trait.OffchainApiServer.html){target=\_blank}**: Make RPC calls for off-chain workers. -- **[`StateApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/state/trait.StateApiServer.html){target=\_blank}**: Query information about on-chain state such as runtime version, storage items, and proofs. -- **[`SystemApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/system/trait.SystemApiServer.html){target=\_blank}**: Retrieve information about network state, such as connected peers and node roles. - -## Additional Resources - -The following tools can help you locate and decode metadata: - -- [Subxt Explorer](https://paritytech.github.io/subxt-explorer/#/){target=\_blank} -- [Metadata Portal 🌗](https://github.com/paritytech/metadata-portal){target=\_blank} -- [De[code] Sub[strate]](https://github.com/paritytech/desub){target=\_blank} - - --- Page Title: Contract Deployment @@ -1019,280 +585,6 @@ Both REVM and PolkaVM deployments may show significant differences between gas e Both backends support contract deployment effectively, with REVM offering drop-in Ethereum compatibility and PolkaVM providing a more structured two-step approach. For the majority of use cases—deploying standard contracts like tokens or applications—both backends work seamlessly. Advanced patterns like factory contracts may require adjustment for PolkaVM, but these adaptations are straightforward with proper planning. ---- - -Page Title: Cryptography - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-cryptography.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/cryptography/ -- Summary: A concise guide to cryptography in blockchain, covering hash functions, encryption types, digital signatures, and elliptic curve applications. - -# Cryptography - -## Introduction - -Cryptography forms the backbone of blockchain technology, providing the mathematical verifiability crucial for consensus systems, data integrity, and user security. While a deep understanding of the underlying mathematical processes isn't necessary for most blockchain developers, grasping the fundamental applications of cryptography is essential. This page comprehensively overviews cryptographic implementations used across Polkadot SDK-based chains and the broader blockchain ecosystem. - -## Hash Functions - -Hash functions are fundamental to blockchain technology, creating a unique digital fingerprint for any piece of data, including simple text, images, or any other form of file. They map input data of any size to a fixed-size output (typically 32 bytes) using complex mathematical operations. Hashing is used to verify data integrity, create digital signatures, and provide a secure way to store passwords. This form of mapping is known as the ["pigeonhole principle,"](https://en.wikipedia.org/wiki/Pigeonhole_principle){target=\_blank} it is primarily implemented to efficiently and verifiably identify data from large sets. - -### Key Properties of Hash Functions - -- **Deterministic**: The same input always produces the same output. -- **Quick computation**: It's easy to calculate the hash value for any given input. -- **Pre-image resistance**: It's infeasible to generate the input data from its hash. -- **Small changes in input yield large changes in output**: Known as the ["avalanche effect"](https://en.wikipedia.org/wiki/Avalanche_effect){target=\_blank}. -- **Collision resistance**: The probabilities are extremely low to find two different inputs with the same hash. - -### Blake2 - -The Polkadot SDK utilizes Blake2, a state-of-the-art hashing method that offers: - -- Equal or greater security compared to [SHA-2](https://en.wikipedia.org/wiki/SHA-2){target=\_blank}. -- Significantly faster performance than other algorithms. - -These properties make Blake2 ideal for blockchain systems, reducing sync times for new nodes and lowering the resources required for validation. For detailed technical specifications about Blake2, see the [official Blake2 paper](https://www.blake2.net/blake2.pdf){target=\_blank}. - -## Types of Cryptography - -There are two different ways that cryptographic algorithms are implemented: symmetric cryptography and asymmetric cryptography. - -### Symmetric Cryptography - -Symmetric encryption is a branch of cryptography that isn't based on one-way functions, unlike asymmetric cryptography. It uses the same cryptographic key to encrypt plain text and decrypt the resulting ciphertext. - -Symmetric cryptography is a type of encryption that has been used throughout history, such as the Enigma Cipher and the Caesar Cipher. It is still widely used today and can be found in Web2 and Web3 applications alike. There is only one single key, and a recipient must also have access to it to access the contained information. - -#### Advantages {: #symmetric-advantages } - -- Fast and efficient for large amounts of data. -- Requires less computational power. - -#### Disadvantages {: #symmetric-disadvantages } - -- Key distribution can be challenging. -- Scalability issues in systems with many users. - -### Asymmetric Cryptography - -Asymmetric encryption is a type of cryptography that uses two different keys, known as a keypair: a public key, used to encrypt plain text, and a private counterpart, used to decrypt the ciphertext. - -The public key encrypts a fixed-length message that can only be decrypted with the recipient's private key and, sometimes, a set password. The public key can be used to cryptographically verify that the corresponding private key was used to create a piece of data without compromising the private key, such as with digital signatures. This has obvious implications for identity, ownership, and properties and is used in many different protocols across Web2 and Web3. - -#### Advantages {: #asymmetric-advantages } - -- Solves the key distribution problem. -- Enables digital signatures and secure key exchange. - -#### Disadvantages {: #asymmetric-disadvantages } - -- Slower than symmetric encryption. -- Requires more computational resources. - -### Trade-offs and Compromises - -Symmetric cryptography is faster and requires fewer bits in the key to achieve the same level of security that asymmetric cryptography provides. However, it requires a shared secret before communication can occur, which poses issues to its integrity and a potential compromise point. On the other hand, asymmetric cryptography doesn't require the secret to be shared ahead of time, allowing for far better end-user security. - -Hybrid symmetric and asymmetric cryptography is often used to overcome the engineering issues of asymmetric cryptography, as it is slower and requires more bits in the key to achieve the same level of security. It encrypts a key and then uses the comparatively lightweight symmetric cipher to do the "heavy lifting" with the message. - -## Digital Signatures - -Digital signatures are a way of verifying the authenticity of a document or message using asymmetric keypairs. They are used to ensure that a sender or signer's document or message hasn't been tampered with in transit, and for recipients to verify that the data is accurate and from the expected sender. - -Signing digital signatures only requires a low-level understanding of mathematics and cryptography. For a conceptual example -- when signing a check, it is expected that it cannot be cashed multiple times. This isn't a feature of the signature system but rather the check serialization system. The bank will check that the serial number on the check hasn't already been used. Digital signatures essentially combine these two concepts, allowing the signature to provide the serialization via a unique cryptographic fingerprint that cannot be reproduced. - -Unlike pen-and-paper signatures, knowledge of a digital signature cannot be used to create other signatures. Digital signatures are often used in bureaucratic processes, as they are more secure than simply scanning in a signature and pasting it onto a document. - -Polkadot SDK provides multiple different cryptographic schemes and is generic so that it can support anything that implements the [`Pair` trait](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Pair.html){target=\_blank}. - -### Example of Creating a Digital Signature - -The process of creating and verifying a digital signature involves several steps: - -1. The sender creates a hash of the message. -2. The hash is encrypted using the sender's private key, creating the signature. -3. The message and signature are sent to the recipient. -4. The recipient decrypts the signature using the sender's public key. -5. The recipient hashes the received message and compares it to the decrypted hash. - -If the hashes match, the signature is valid, confirming the message's integrity and the sender's identity. - -## Elliptic Curve - -Blockchain technology requires the ability to have multiple keys creating a signature for block proposal and validation. To this end, Elliptic Curve Digital Signature Algorithm (ECDSA) and Schnorr signatures are two of the most commonly used methods. While ECDSA is a far simpler implementation, Schnorr signatures are more efficient when it comes to multi-signatures. - -Schnorr signatures bring some noticeable features over the ECDSA/EdDSA schemes: - -- It is better for hierarchical deterministic key derivations. -- It allows for native multi-signature through [signature aggregation](https://bitcoincore.org/en/2017/03/23/schnorr-signature-aggregation/){target=\_blank}. -- It is generally more resistant to misuse. - -One sacrifice that is made when using Schnorr signatures over ECDSA is that both require 64 bytes, but only ECDSA signatures communicate their public key. - -### Various Implementations - -- **[ECDSA](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm){target=\_blank}**: Polkadot SDK provides an ECDSA signature scheme using the [secp256k1](https://en.bitcoin.it/wiki/Secp256k1){target=\_blank} curve. This is the same cryptographic algorithm used to secure [Bitcoin](https://en.wikipedia.org/wiki/Bitcoin){target=\_blank} and [Ethereum](https://en.wikipedia.org/wiki/Ethereum){target=\_blank}. - -- **[Ed25519](https://en.wikipedia.org/wiki/EdDSA#Ed25519){target=\_blank}**: An EdDSA signature scheme using [Curve25519](https://en.wikipedia.org/wiki/Curve25519){target=\_blank}. It is carefully engineered at several levels of design and implementation to achieve very high speeds without compromising security. - -- **[SR25519](https://research.web3.foundation/Polkadot/security/keys/accounts-more){target=\_blank}**: Based on the same underlying curve as Ed25519. However, it uses Schnorr signatures instead of the EdDSA scheme. - - ---- - -Page Title: Data Encoding - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-data-encoding.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/data-encoding/ -- Summary: SCALE codec enables fast, efficient data encoding, ideal for resource-constrained environments like Wasm, supporting custom types and compact encoding. - -# Data Encoding - -## Introduction - -The Polkadot SDK uses a lightweight and efficient encoding/decoding mechanism to optimize data transmission across the network. This mechanism, known as the _SCALE_ codec, is used for serializing and deserializing data. - -The SCALE codec enables communication between the runtime and the outer node. This mechanism is designed for high-performance, copy-free data encoding and decoding in resource-constrained environments like the Polkadot SDK [Wasm runtime](/develop/parachains/deployment/build-deterministic-runtime/#introduction){target=\_blank}. - -It is not self-describing, meaning the decoding context must fully know the encoded data types. - -Parity's libraries utilize the [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} crate (a Rust implementation of the SCALE codec) to handle encoding and decoding for interactions between RPCs and the runtime. - -The `codec` mechanism is ideal for Polkadot SDK-based chains because: - -- It is lightweight compared to generic serialization frameworks like [`serde`](https://serde.rs/){target=\_blank}, which add unnecessary bulk to binaries. -- It doesn’t rely on Rust’s `libstd`, making it compatible with `no_std` environments like Wasm runtime. -- It integrates seamlessly with Rust, allowing easy derivation of encoding and decoding logic for new types using `#[derive(Encode, Decode)]`. - -Defining a custom encoding scheme in the Polkadot SDK-based chains, rather than using an existing Rust codec library, is crucial for enabling cross-platform and multi-language support. - -## SCALE Codec - -The codec is implemented using the following traits: - -- [`Encode`](#encode) -- [`Decode`](#decode) -- [`CompactAs`](#compactas) -- [`HasCompact`](#hascompact) -- [`EncodeLike`](#encodelike) - -### Encode - -The [`Encode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Encode.html){target=\_blank} trait handles data encoding into SCALE format and includes the following key functions: - -- **`size_hint(&self) -> usize`**: Estimates the number of bytes required for encoding to prevent multiple memory allocations. This should be inexpensive and avoid complex operations. Optional if the size isn’t known. -- **`encode_to(&self, dest: &mut T)`**: Encodes the data, appending it to a destination buffer. -- **`encode(&self) -> Vec`**: Encodes the data and returns it as a byte vector. -- **`using_encoded R>(&self, f: F) -> R`**: Encodes the data and passes it to a closure, returning the result. -- **`encoded_size(&self) -> usize`**: Calculates the encoded size. Should be used when the encoded data isn’t required. - -!!!tip - For best performance, value types should override `using_encoded`, and allocating types should override `encode_to`. It's recommended to implement `size_hint` for all types where possible. - -### Decode - -The [`Decode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Decode.html){target=\_blank} trait handles decoding SCALE-encoded data back into the appropriate types: - -- **`fn decode(value: &mut I) -> Result`**: Decodes data from the SCALE format, returning an error if decoding fails. - -### CompactAs - -The [`CompactAs`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.CompactAs.html){target=\_blank} trait wraps custom types for compact encoding: - -- **`encode_as(&self) -> &Self::As`**: Encodes the type as a compact type. -- **`decode_from(_: Self::As) -> Result`**: decodes from a compact encoded type. - -### HasCompact - -The [`HasCompact`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.HasCompact.html){target=\_blank} trait indicates a type supports compact encoding. - -### EncodeLike - -The [`EncodeLike`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.EncodeLike.html){target=\_blank} trait is used to ensure multiple types that encode similarly are accepted by the same function. When using `derive`, it is automatically implemented. - -### Data Types - -The table below outlines how the Rust implementation of the Parity SCALE codec encodes different data types. - -| Type | Description | Example SCALE Decoded Value | SCALE Encoded Value | -|-------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------| -| Boolean | Boolean values are encoded using the least significant bit of a single byte. | `false` / `true` | `0x00` / `0x01` | -| Compact/general integers | A "compact" or general integer encoding is sufficient for encoding large integers (up to 2^536) and is more efficient at encoding most values than the fixed-width version. | `unsigned integer 0` / `unsigned integer 1` / `unsigned integer 42` / `unsigned integer 69` / `unsigned integer 65535` / `BigInt(100000000000000)` | `0x00` / `0x04` / `0xa8` / `0x1501` / `0xfeff0300` / `0x0b00407a10f35a` | -| Enumerations (tagged-unions) | A fixed number of variants, each mutually exclusive and potentially implying a further value or series of values. Encoded as the first byte identifying the index of the variant that the value is. Any further bytes are used to encode any data that the variant implies. Thus, no more than 256 variants are supported. | `Int(42)` and `Bool(true)` where `enum IntOrBool { Int(u8), Bool(bool) }` | `0x002a` and `0x0101` | -| Fixed-width integers | Basic integers are encoded using a fixed-width little-endian (LE) format. | `signed 8-bit integer 69` / `unsigned 16-bit integer 42` / `unsigned 32-bit integer 16777215` | `0x45` / `0x2a00` / `0xffffff00` | -| Options | One or zero values of a particular type. | `Some` / `None` | `0x01` followed by the encoded value / `0x00` | -| Results | Results are commonly used enumerations which indicate whether certain operations were successful or unsuccessful. | `Ok(42)` / `Err(false)` | `0x002a` / `0x0100` | -| Strings | Strings are Vectors of bytes (Vec) containing a valid UTF8 sequence. | | | -| Structs | For structures, the values are named, but that is irrelevant for the encoding (names are ignored - only order matters). | `SortedVecAsc::from([3, 5, 2, 8])` | `[3, 2, 5, 8] ` | -| Tuples | A fixed-size series of values, each with a possibly different but predetermined and fixed type. This is simply the concatenation of each encoded value. | Tuple of compact unsigned integer and boolean: `(3, false)` | `0x0c00` | -| Vectors (lists, series, sets) | A collection of same-typed values is encoded, prefixed with a compact encoding of the number of items, followed by each item's encoding concatenated in turn. | Vector of unsigned `16`-bit integers: `[4, 8, 15, 16, 23, 42]` | `0x18040008000f00100017002a00` | - -## Encode and Decode Rust Trait Implementations - -Here's how the `Encode` and `Decode` traits are implemented: - - -```rust -use parity_scale_codec::{Encode, Decode}; - -[derive(Debug, PartialEq, Encode, Decode)] -enum EnumType { - #[codec(index = 15)] - A, - B(u32, u64), - C { - a: u32, - b: u64, - }, -} - -let a = EnumType::A; -let b = EnumType::B(1, 2); -let c = EnumType::C { a: 1, b: 2 }; - -a.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x0f"); -}); - -b.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); - -c.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); - -let mut da: &[u8] = b"\x0f"; -assert_eq!(EnumType::decode(&mut da).ok(), Some(a)); - -let mut db: &[u8] = b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut db).ok(), Some(b)); - -let mut dc: &[u8] = b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut dc).ok(), Some(c)); - -let mut dz: &[u8] = &[0]; -assert_eq!(EnumType::decode(&mut dz).ok(), None); -``` - -## SCALE Codec Libraries - -Several SCALE codec implementations are available in various languages. Here's a list of them: - -- **AssemblyScript**: [`LimeChain/as-scale-codec`](https://github.com/LimeChain/as-scale-codec){target=\_blank} -- **C**: [`MatthewDarnell/cScale`](https://github.com/MatthewDarnell/cScale){target=\_blank} -- **C++**: [`qdrvm/scale-codec-cpp`](https://github.com/qdrvm/scale-codec-cpp){target=\_blank} -- **JavaScript**: [`polkadot-js/api`](https://github.com/polkadot-js/api){target=\_blank} -- **Dart**: [`leonardocustodio/polkadart`](https://github.com/leonardocustodio/polkadart){target=\_blank} -- **Haskell**: [`airalab/hs-web3`](https://github.com/airalab/hs-web3/tree/master/packages/scale){target=\_blank} -- **Golang**: [`itering/scale.go`](https://github.com/itering/scale.go){target=\_blank} -- **Java**: [`splix/polkaj`](https://github.com/splix/polkaj){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **Ruby**: [` wuminzhe/scale_rb`](https://github.com/wuminzhe/scale_rb){target=\_blank} -- **TypeScript**: [`parity-scale-codec-ts`](https://github.com/tjjfvi/subshape){target=\_blank}, [`scale-ts`](https://github.com/unstoppablejs/unstoppablejs/tree/main/packages/scale-ts#scale-ts){target=\_blank}, [`soramitsu/scale-codec-js-library`](https://github.com/soramitsu/scale-codec-js-library){target=\_blank}, [`subsquid/scale-codec`](https://github.com/subsquid/squid-sdk/tree/master/substrate/scale-codec){target=\_blank} - - --- Page Title: Deploy an ERC-20 to Polkadot Hub @@ -3100,370 +2392,130 @@ From here, follow the quick starts to get connected, iterate locally with your p --- -Page Title: Glossary +Page Title: Get Started with XCM -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-glossary.md -- Canonical (HTML): https://docs.polkadot.com/reference/glossary/ -- Summary: Glossary of terms used within the Polkadot ecosystem, Polkadot SDK, its subsequent libraries, and other relevant Web3 terminology. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md +- Canonical (HTML): https://docs.polkadot.com/parachains/interoperability/get-started/ +- Summary: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. -# Glossary +# Get Started with XCM -Key definitions, concepts, and terminology specific to the Polkadot ecosystem are included here. +## Introduction -Additional glossaries from around the ecosystem you might find helpful: - -- [Polkadot Wiki Glossary](https://wiki.polkadot.com/general/glossary){target=\_blank} -- [Polkadot SDK Glossary](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/glossary/index.html){target=\_blank} - -## Authority - -The role in a blockchain that can participate in consensus mechanisms. - -- **[GRANDPA](#grandpa)**: The authorities vote on chains they consider final. -- **[Blind Assignment of Blockchain Extension](#blind-assignment-of-blockchain-extension-babe) (BABE)**: The authorities are also [block authors](#block-author). - -Authority sets can be used as a basis for consensus mechanisms such as the [Nominated Proof of Stake (NPoS)](#nominated-proof-of-stake-npos) protocol. - -## Authority Round (Aura) - -A deterministic [consensus](#consensus) protocol where block production is limited to a rotating list of [authorities](#authority) that take turns creating blocks. In authority round (Aura) consensus, most online authorities are assumed to be honest. It is often used in combination with [GRANDPA](#grandpa) as a [hybrid consensus](#hybrid-consensus) protocol. - -Learn more by reading the official [Aura consensus algorithm](https://openethereum.github.io/Aura){target=\_blank} wiki article. - -## Blind Assignment of Blockchain Extension (BABE) - -A [block authoring](#block-author) protocol similar to [Aura](#authority-round-aura), except [authorities](#authority) win [slots](#slot) based on a Verifiable Random Function (VRF) instead of the round-robin selection method. The winning authority can select a chain and submit a new block. - -Learn more by reading the official Web3 Foundation [BABE research document](https://research.web3.foundation/Polkadot/protocols/block-production/Babe){target=\_blank}. - -## Block Author - -The node responsible for the creation of a block, also called _block producers_. In a Proof of Work (PoW) blockchain, these nodes are called _miners_. - -## Byzantine Fault Tolerance (BFT) - -The ability of a distributed computer network to remain operational if a certain proportion of its nodes or [authorities](#authority) are defective or behaving maliciously. A distributed network is typically considered Byzantine fault tolerant if it can remain functional, with up to one-third of nodes assumed to be defective, offline, actively malicious, and part of a coordinated attack. - -### Byzantine Failure - -The loss of a network service due to node failures that exceed the proportion of nodes required to reach consensus. - -### Practical Byzantine Fault Tolerance (pBFT) - -An early approach to Byzantine fault tolerance (BFT), practical Byzantine fault tolerance (pBFT) systems tolerate Byzantine behavior from up to one-third of participants. - -The communication overhead for such systems is `O(n²)`, where `n` is the number of nodes (participants) in the system. - -### Preimage - -A preimage is the data that is input into a hash function to calculate a hash. Since a hash function is a [one-way function](https://en.wikipedia.org/wiki/One-way_function){target=\_blank}, the output, the hash, cannot be used to reveal the input, the preimage. - -## Call - -In the context of pallets containing functions to be dispatched to the runtime, `Call` is an enumeration data type that describes the functions that can be dispatched with one variant per pallet. A `Call` represents a [dispatch](#dispatchable) data structure object. - -## Chain Specification - -A chain specification file defines the properties required to run a node in an active or new Polkadot SDK-built network. It often contains the initial genesis runtime code, network properties (such as the network's name), the initial state for some pallets, and the boot node list. The chain specification file makes it easy to use a single Polkadot SDK codebase as the foundation for multiple independently configured chains. - -## Collator - -An [author](#block-author) of a [parachain](#parachain) network. -They aren't [authorities](#authority) in themselves, as they require a [relay chain](#relay-chain) to coordinate [consensus](#consensus). - -More details are found on the [Polkadot Collator Wiki](https://wiki.polkadot.com/learn/learn-collator/){target=\_blank}. - -## Collective - -Most often used to refer to an instance of the Collective pallet on Polkadot SDK-based networks such as [Kusama](#kusama) or [Polkadot](#polkadot) if the Collective pallet is part of the FRAME-based runtime for the network. - -## Consensus +Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems. -Consensus is the process blockchain nodes use to agree on a chain's canonical fork. It is composed of [authorship](#block-author), finality, and [fork-choice rule](#fork-choice-rulestrategy). In the Polkadot ecosystem, these three components are usually separate and the term consensus often refers specifically to authorship. +With XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation. -See also [hybrid consensus](#hybrid-consensus). +## Messaging Format -## Consensus Algorithm +XCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics. -Ensures a set of [actors](#authority)—who don't necessarily trust each other—can reach an agreement about the state as the result of some computation. Most consensus algorithms assume that up to one-third of the actors or nodes can be [Byzantine fault tolerant](#byzantine-fault-tolerance-bft). +XCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing. -Consensus algorithms are generally concerned with ensuring two properties: +## The Four Principles of XCM -- **Safety**: Indicating that all honest nodes eventually agreed on the state of the chain. -- **Liveness**: Indicating the ability of the chain to keep progressing. +XCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems: -## Consensus Engine +- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes. +- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended. +- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin. +- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems. -The node subsystem responsible for consensus tasks. +These principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments. -For detailed information about the consensus strategies of the [Polkadot](#polkadot) network, see the [Polkadot Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} blog series. +## The XCM Tech Stack -See also [hybrid consensus](#hybrid-consensus). +![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp) -## Coretime +The XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels. -The time allocated for utilizing a core, measured in relay chain blocks. There are two types of coretime: *on-demand* and *bulk*. +## Core Functionalities of XCM -On-demand coretime refers to coretime acquired through bidding in near real-time for the validation of a single parachain block on one of the cores reserved specifically for on-demand orders. They are available as an on-demand coretime pool. Set of cores that are available on-demand. Cores reserved through bulk coretime could also be made available in the on-demand coretime pool, in parts or in entirety. +XCM enhances cross-consensus communication by introducing several powerful features: -Bulk coretime is a fixed duration of continuous coretime represented by an NFT that can be split, shared, or resold. It is managed by the [Broker pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_broker/index.html){target=\_blank}. +- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management. +- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification. +- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location. -## Development Phrase +The standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications. -A [mnemonic phrase](https://en.wikipedia.org/wiki/Mnemonic#For_numerical_sequences_and_mathematical_operations){target=\_blank} that is intentionally made public. +## XCM Example -Well-known development accounts, such as Alice, Bob, Charlie, Dave, Eve, and Ferdie, are generated from the same secret phrase: +The following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA). +```rust +let message = Xcm(vec![ + WithdrawAsset((Here, amount).into()), + BuyExecution { + fees: (Here, amount).into(), + weight_limit: WeightLimit::Unlimited + }, + DepositAsset { + assets: All.into(), + beneficiary: MultiLocation { + parents: 0, + interior: Junction::AccountId32 { + network: None, + id: BOB.clone().into() + }.into(), + }.into() + } +]); ``` -bottom drive obey lake curtain smoke basket hold race lonely fit walk -``` - -Many tools in the Polkadot SDK ecosystem, such as [`subkey`](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/bin/utils/subkey){target=\_blank}, allow you to implicitly specify an account using a derivation path such as `//Alice`. - -## Digest - -An extensible field of the [block header](#header) that encodes information needed by several actors in a blockchain network, including: - -- [Light clients](#light-client) for chain synchronization. -- Consensus engines for block verification. -- The runtime itself, in the case of pre-runtime digests. - -## Dispatchable - -Function objects that act as the entry points in FRAME [pallets](#pallet). Internal or external entities can call them to interact with the blockchain’s state. They are a core aspect of the runtime logic, handling [transactions](#transaction) and other state-changing operations. - -## Events - -A means of recording that some particular [state](#state) transition happened. - -In the context of [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities), events are composable data types that each [pallet](#pallet) can individually define. Events in FRAME are implemented as a set of transient storage items inspected immediately after a block has been executed and reset during block initialization. - -## Executor - -A means of executing a function call in a given [runtime](#runtime) with a set of dependencies. -There are two orchestration engines in Polkadot SDK, _WebAssembly_ and _native_. - -- The _native executor_ uses a natively compiled runtime embedded in the node to execute calls. This is a performance optimization available to up-to-date nodes. - -- The _WebAssembly executor_ uses a [Wasm](#webassembly-wasm) binary and a Wasm interpreter to execute calls. The binary is guaranteed to be up-to-date regardless of the version of the blockchain node because it is persisted in the [state](#state) of the Polkadot SDK-based chain. - -## Existential Deposit - -The minimum balance an account is allowed to have in the [Balances pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/index.html){target=\_blank}. Accounts cannot be created with a balance less than the existential deposit amount. - -If an account balance drops below this amount, the Balances pallet uses [a FRAME System API](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.dec_ref){target=\_blank} to drop its references to that account. - -If the Balances pallet reference to an account is dropped, the account can be [reaped](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.allow_death){target=\_blank}. - -## Extrinsic - -A general term for data that originates outside the runtime, is included in a block, and leads to some action. This includes user-initiated transactions and inherent transactions placed into the block by the block builder. - -It is a SCALE-encoded array typically consisting of a version number, signature, and varying data types indicating the resulting runtime function to be called. Extrinsics can take two forms: [inherents](#inherent-transactions) and [transactions](#transaction). - -For more technical details, see the [Polkadot spec](https://spec.polkadot.network/id-extrinsics){target=\_blank}. - -## Fork Choice Rule/Strategy - -A fork choice rule or strategy helps determine which chain is valid when reconciling several network forks. A common fork choice rule is the [longest chain](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/struct.LongestChain.html){target=\_blank}, in which the chain with the most blocks is selected. - -## FRAME (Framework for Runtime Aggregation of Modularized Entities) - -Enables developers to create blockchain [runtime](#runtime) environments from a modular set of components called [pallets](#pallet). It utilizes a set of procedural macros to construct runtimes. - -[Visit the Polkadot SDK docs for more details on FRAME.](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank} - -## Full Node - -A node that prunes historical states, keeping only recently finalized block states to reduce storage needs. Full nodes provide current chain state access and allow direct submission and validation of [extrinsics](#extrinsic), maintaining network decentralization. - -## Genesis Configuration - -A mechanism for specifying the initial state of a blockchain. By convention, this initial state or first block is commonly referred to as the genesis state or genesis block. The genesis configuration for Polkadot SDK-based chains is accomplished by way of a [chain specification](#chain-specification) file. - -## GRANDPA - -A deterministic finality mechanism for blockchains that is implemented in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. - -The [formal specification](https://github.com/w3f/consensus/blob/master/pdf/grandpa-old.pdf){target=\_blank} is maintained by the [Web3 Foundation](https://web3.foundation/){target=\_blank}. - -## Header - -A structure that aggregates the information used to summarize a block. Primarily, it consists of cryptographic information used by [light clients](#light-client) to get minimally secure but very efficient chain synchronization. - -## Hybrid Consensus - -A blockchain consensus protocol that consists of independent or loosely coupled mechanisms for [block production](#block-author) and finality. - -Hybrid consensus allows the chain to grow as fast as probabilistic consensus protocols, such as [Aura](#authority-round-aura), while maintaining the same level of security as deterministic finality consensus protocols, such as [GRANDPA](#grandpa). - -## Inherent Transactions - -A special type of unsigned transaction, referred to as _inherents_, that enables a block authoring node to insert information that doesn't require validation directly into a block. - -Only the block-authoring node that calls the inherent transaction function can insert data into its block. In general, validators assume the data inserted using an inherent transaction is valid and reasonable even if it can't be deterministically verified. - -## JSON-RPC - -A stateless, lightweight remote procedure call protocol encoded in JavaScript Object Notation (JSON). JSON-RPC provides a standard way to call functions on a remote system by using JSON. - -For Polkadot SDK, this protocol is implemented through the [Parity JSON-RPC](https://github.com/paritytech/jsonrpc){target=\_blank} crate. - -## Keystore - -A subsystem for managing keys for the purpose of producing new blocks. - -## Kusama - -[Kusama](https://kusama.network/){target=\_blank} is a Polkadot SDK-based blockchain that implements a design similar to the [Polkadot](#polkadot) network. - -Kusama is a [canary](https://en.wiktionary.org/wiki/canary_in_a_coal_mine){target=\_blank} network and is referred to as [Polkadot's "wild cousin."](https://wiki.polkadot.com/learn/learn-comparisons-kusama/){target=\_blank}. - -As a canary network, Kusama is expected to be more stable than a test network like [Westend](#westend) but less stable than a production network like [Polkadot](#polkadot). Kusama is controlled by its network participants and is intended to be stable enough to encourage meaningful experimentation. - -## libp2p - -A peer-to-peer networking stack that allows the use of many transport mechanisms, including WebSockets (usable in a web browser). - -Polkadot SDK uses the [Rust implementation](https://github.com/libp2p/rust-libp2p){target=\_blank} of the `libp2p` networking stack. -## Light Client - -A type of blockchain node that doesn't store the [chain state](#state) or produce blocks. - -A light client can verify cryptographic primitives and provides a [remote procedure call (RPC)](https://en.wikipedia.org/wiki/Remote_procedure_call){target=\_blank} server, enabling blockchain users to interact with the network. - -## Metadata - -Data that provides information about one or more aspects of a system. -The metadata that exposes information about a Polkadot SDK blockchain enables you to interact with that system. - -## Nominated Proof of Stake (NPoS) - -A method for determining [validators](#validator) or _[authorities](#authority)_ based on a willingness to commit their stake to the proper functioning of one or more block-producing nodes. - -## Oracle - -An entity that connects a blockchain to a non-blockchain data source. Oracles enable the blockchain to access and act upon information from existing data sources and incorporate data from non-blockchain systems and services. - -## Origin - -A [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitive that identifies the source of a [dispatched](#dispatchable) function call into the [runtime](#runtime). The FRAME System pallet defines three built-in [origins](#origin). As a [pallet](#pallet) developer, you can also define custom origins, such as those defined by the [Collective pallet](https://paritytech.github.io/substrate/master/pallet_collective/enum.RawOrigin.html){target=\_blank}. - -## Pallet - -A module that can be used to extend the capabilities of a [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities)-based [runtime](#runtime). -Pallets bundle domain-specific logic with runtime primitives like [events](#events) and [storage items](#storage-item). - -## Parachain - -A parachain is a blockchain that derives shared infrastructure and security from a _[relay chain](#relay-chain)_. -You can learn more about parachains on the [Polkadot Wiki](https://wiki.polkadot.com/learn/learn-parachains/){target=\_blank}. - -## Paseo - -Paseo TestNet provisions testing on Polkadot's "production" runtime, which means less chance of feature or code mismatch when developing parachain apps. Specifically, after the [Polkadot Technical fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} proposes a runtime upgrade for Polkadot, this TestNet is updated, giving a period where the TestNet will be ahead of Polkadot to allow for testing. - -## Polkadot - -The [Polkadot network](https://polkadot.com/){target=\_blank} is a blockchain that serves as the central hub of a heterogeneous blockchain network. It serves the role of the [relay chain](#relay-chain) and provides shared infrastructure and security to support [parachains](#parachain). - -## Polkadot Cloud - -Polkadot Cloud is a platform for deploying resilient, customizable and scalable Web3 applications through Polkadot's functionality. It encompasses the wider Polkadot network infrastructure and security layer where parachains operate. The platform enables users to launch Ethereum-compatible chains, build specialized blockchains, and flexibly manage computing resources through on-demand or bulk coretime purchases. Initially launched with basic parachain functionality, Polkadot Cloud has evolved to offer enhanced flexibility with features like coretime, elastic scaling, and async backing for improved performance. - -## Polkadot Hub - -Polkadot Hub is a Layer 1 platform that serves as the primary entry point to the Polkadot ecosystem, providing essential functionality without requiring parachain deployment. It offers core services including smart contracts, identity management, staking, governance, and interoperability with other ecosystems, making it simple and fast for both builders and users to get started in Web3. - -## PolkaVM - -PolkaVM is a custom virtual machine optimized for performance, leveraging a RISC-V-based architecture to support Solidity and any language that compiles to RISC-V. It is specifically designed for the Polkadot ecosystem, enabling smart contract deployment and execution. - -## Relay Chain - -Relay chains are blockchains that provide shared infrastructure and security to the [parachains](#parachain) in the network. In addition to providing [consensus](#consensus) capabilities, relay chains allow parachains to communicate and exchange digital assets without needing to trust one another. - -## Rococo - -A [parachain](#parachain) test network for the Polkadot network. The [Rococo](#rococo) network is a Polkadot SDK-based blockchain with an October 14, 2024 deprecation date. Development teams are encouraged to use the Paseo TestNet instead. - -## Runtime - -The runtime represents the [state transition function](#state-transition-function-stf) for a blockchain. In Polkadot SDK, the runtime is stored as a [Wasm](#webassembly-wasm) binary in the chain state. The Runtime is stored under a unique state key and can be modified during the execution of the state transition function. - -## Slot - -A fixed, equal interval of time used by consensus engines such as [Aura](#authority-round-aura) and [BABE](#blind-assignment-of-blockchain-extension-babe). In each slot, a subset of [authorities](#authority) is permitted, or obliged, to [author](#block-author) a block. - -## Sovereign Account - -The unique account identifier for each chain in the relay chain ecosystem. It is often used in cross-consensus (XCM) interactions to sign XCM messages sent to the relay chain or other chains in the ecosystem. - -The sovereign account for each chain is a root-level account that can only be accessed using the Sudo pallet or through governance. The account identifier is calculated by concatenating the Blake2 hash of a specific text string and the registered parachain identifier. - -## SS58 Address Format - -A public key address based on the Bitcoin [`Base-58-check`](https://en.bitcoin.it/wiki/Base58Check_encoding){target=\_blank} encoding. Each Polkadot SDK SS58 address uses a `base-58` encoded value to identify a specific account on a specific Polkadot SDK-based chain - -The [canonical `ss58-registry`](https://github.com/paritytech/ss58-registry){target=\_blank} provides additional details about the address format used by different Polkadot SDK-based chains, including the network prefix and website used for different networks - -## State Transition Function (STF) - -The logic of a blockchain that determines how the state changes when a block is processed. In Polkadot SDK, the state transition function is effectively equivalent to the [runtime](#runtime). - -## Storage Item - -[FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitives that provide type-safe data persistence capabilities to the [runtime](#runtime). -Learn more in the [storage items](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/index.html){target=\_blank} reference document in the Polkadot SDK. - -## Substrate - -A flexible framework for building modular, efficient, and upgradeable blockchains. Substrate is written in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language and is maintained by [Parity Technologies](https://www.parity.io/){target=\_blank}. - -## Transaction - -An [extrinsic](#extrinsic) that includes a signature that can be used to verify the account authorizing it inherently or via [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}. - -## Transaction Era - -A definable period expressed as a range of block numbers during which a transaction can be included in a block. -Transaction eras are used to protect against transaction replay attacks if an account is reaped and its replay-protecting nonce is reset to zero. - -## Trie (Patricia Merkle Tree) +The message consists of three instructions described as follows: -A data structure used to represent sets of key-value pairs and enables the items in the data set to be stored and retrieved using a cryptographic hash. Because incremental changes to the data set result in a new hash, retrieving data is efficient even if the data set is very large. With this data structure, you can also prove whether the data set includes any particular key-value pair without access to the entire data set. +- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register. -In Polkadot SDK-based blockchains, state is stored in a trie data structure that supports the efficient creation of incremental digests. This trie is exposed to the [runtime](#runtime) as [a simple key/value map](#storage-item) where both keys and values can be arbitrary byte arrays. + ```rust + WithdrawAsset((Here, amount).into()), + ``` -## Validator + - **`Here`**: The native parachain token. + - **`amount`**: The number of tokens that are transferred. -A validator is a node that participates in the consensus mechanism of the network. Its roles include block production, transaction validation, network integrity, and security maintenance. + The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register. -## WebAssembly (Wasm) +- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\_blank} of the XCM instructions. -An execution architecture that allows for the efficient, platform-neutral expression of -deterministic, machine-executable logic. + ```rust + BuyExecution { + fees: (Here, amount).into(), + weight_limit: WeightLimit::Unlimited + }, + ``` -[Wasm](https://webassembly.org/){target=\_blank} can be compiled from many languages, including -the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. Polkadot SDK-based chains use a Wasm binary to provide portable [runtimes](#runtime) that can be included as part of the chain's state. + - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight. + - **`weight_limit`**: Defines the maximum fees that can be used to buy weight. -## Weight +- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\_blank}**: Moves the remaining tokens from the holding register to Bob’s account. -A convention used in Polkadot SDK-based blockchains to measure and manage the time it takes to validate a block. -Polkadot SDK defines one unit of weight as one picosecond of execution time on reference hardware. + ```rust + DepositAsset { + assets: All.into(), + beneficiary: MultiLocation { + parents: 0, + interior: Junction::AccountId32 { + network: None, + id: BOB.clone().into() + }.into(), + }.into() + } + ``` -The maximum block weight should be equivalent to one-third of the target block time with an allocation of one-third each for: + - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited. + +This step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. -- Block construction -- Network propagation -- Import and verification +## Overview -By defining weights, you can trade-off the number of transactions per second and the hardware required to maintain the target block time appropriate for your use case. Weights are defined in the runtime, meaning you can tune them using runtime updates to keep up with hardware and software improvements. +XCM revolutionizes cross-chain communication by enabling use cases such as: -## Westend +- Token transfers between blockchains. +- Asset locking for cross-chain smart contract interactions. +- Remote execution of functions on other blockchains. -Westend is a Parity-maintained, Polkadot SDK-based blockchain that serves as a test network for the [Polkadot](#polkadot) network. +These functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. --- @@ -3890,258 +2942,60 @@ To stop the node, press `Control-C` in the terminal. --- -Page Title: Interoperability +Page Title: JSON-RPC APIs -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-interoperability.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/interoperability/ -- Summary: Explore the importance of interoperability in the Polkadot ecosystem, covering XCM, bridges, and cross-chain communication. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-json-rpc-apis.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/json-rpc-apis/ +- Summary: JSON-RPC APIs guide for Polkadot Hub, covering supported methods, parameters, and examples for interacting with the chain. -# Interoperability +# JSON-RPC APIs +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. ## Introduction -Interoperability lies at the heart of the Polkadot ecosystem, enabling communication and collaboration across a diverse range of blockchains. By bridging the gaps between parachains, relay chains, and even external networks, Polkadot unlocks the potential for truly decentralized applications, efficient resource sharing, and scalable solutions. - -Polkadot’s design ensures that blockchains can transcend their individual limitations by working together as part of a unified system. This cooperative architecture is what sets Polkadot apart in the blockchain landscape. - -## Why Interoperability Matters - -The blockchain ecosystem is inherently fragmented. Different blockchains excel in specialized domains such as finance, gaming, or supply chain management, but these chains function in isolation without interoperability. This lack of connectivity stifles the broader utility of blockchain technology. - -Interoperability solves this problem by enabling blockchains to: - -- **Collaborate across networks**: Chains can interact to share assets, functionality, and data, creating synergies that amplify their individual strengths. -- **Achieve greater scalability**: Specialized chains can offload tasks to others, optimizing performance and resource utilization. -- **Expand use-case potential**: Cross-chain applications can leverage features from multiple blockchains, unlocking novel user experiences and solutions. - -In the Polkadot ecosystem, interoperability transforms a collection of isolated chains into a cohesive, efficient network, pushing the boundaries of what blockchains can achieve together. +Polkadot Hub provides Ethereum compatibility through its JSON-RPC interface, allowing developers to interact with the chain using familiar Ethereum tooling and methods. This document outlines the supported [Ethereum JSON-RPC methods](https://ethereum.org/developers/docs/apis/json-rpc/#json-rpc-methods){target=\_blank} and provides examples of how to use them. -## Key Mechanisms for Interoperability +This guide uses the Polkadot Hub TestNet endpoint: -At the core of Polkadot's cross-chain collaboration are foundational technologies designed to break down barriers between networks. These mechanisms empower blockchains to communicate, share resources, and operate as a cohesive ecosystem. +```text +https://testnet-passet-hub-eth-rpc.polkadot.io +``` -### Cross-Consensus Messaging (XCM): The Backbone of Communication +## Available Methods -Polkadot's Cross-Consensus Messaging (XCM) is the standard framework for interaction between parachains, relay chains, and, eventually, external blockchains. XCM provides a trustless, secure messaging format for exchanging assets, sharing data, and executing cross-chain operations. +### eth_accounts -Through XCM, decentralized applications can: +Returns a list of addresses owned by the client. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_accounts){target=\_blank}. -- Transfer tokens and other assets across chains. -- Coordinate complex workflows that span multiple blockchains. -- Enable seamless user experiences where underlying blockchain differences are invisible. -- XCM exemplifies Polkadot’s commitment to creating a robust and interoperable ecosystem. +**Parameters**: -For further information about XCM, check the [Introduction to XCM](/parachains/interoperability/get-started/){target=\_blank} article. +None. -### Bridges: Connecting External Networks +**Example**: -While XCM enables interoperability within the Polkadot ecosystem, bridges extend this functionality to external blockchains such as Ethereum and Bitcoin. By connecting these networks, bridges allow Polkadot-based chains to access external liquidity, additional functionalities, and broader user bases. +```bash title="eth_accounts" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_accounts", + "params":[], + "id":1 +}' +``` -With bridges, developers and users gain the ability to: +--- -- Integrate external assets into Polkadot-based applications. -- Combine the strengths of Polkadot’s scalability with the liquidity of other networks. -- Facilitate accurate multi-chain applications that transcend ecosystem boundaries. +### eth_blockNumber -For more information about bridges in the Polkadot ecosystem, see the [Bridge Hub](/reference/polkadot-hub/bridging/){target=\_blank} guide. +Returns the number of the most recent block. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_blocknumber){target=\_blank}. -## The Polkadot Advantage +**Parameters**: -Polkadot was purpose-built for interoperability. Unlike networks that add interoperability as an afterthought, Polkadot integrates it as a fundamental design principle. This approach offers several distinct advantages: +None. -- **Developer empowerment**: Polkadot’s interoperability tools allow developers to build applications that leverage multiple chains’ capabilities without added complexity. -- **Enhanced ecosystem collaboration**: Chains in Polkadot can focus on their unique strengths while contributing to the ecosystem’s overall growth. -- **Future-proofing blockchain**: By enabling seamless communication, Polkadot ensures its ecosystem can adapt to evolving demands and technologies. - -## Looking Ahead - -Polkadot’s vision of interoperability extends beyond technical functionality, representing a shift towards a more collaborative blockchain landscape. By enabling chains to work together, Polkadot fosters innovation, efficiency, and accessibility, paving the way for a decentralized future where blockchains are not isolated competitors but interconnected collaborators. - - ---- - -Page Title: Introduction to XCM - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md -- Canonical (HTML): https://docs.polkadot.com/parachains/interoperability/get-started/ -- Summary: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. - -# Introduction to XCM - -## Introduction - -Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems. - -With XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation. - -## Messaging Format - -XCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics. - -XCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing. - -## The Four Principles of XCM - -XCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems: - -- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes. -- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended. -- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin. -- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems. - -These principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments. - -## The XCM Tech Stack - -![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp) - -The XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels. - -## Core Functionalities of XCM - -XCM enhances cross-consensus communication by introducing several powerful features: - -- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management. -- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification. -- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location. - -The standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications. - -## XCM Example - -The following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA). - -```rust -let message = Xcm(vec![ - WithdrawAsset((Here, amount).into()), - BuyExecution { - fees: (Here, amount).into(), - weight_limit: WeightLimit::Unlimited - }, - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: Junction::AccountId32 { - network: None, - id: BOB.clone().into() - }.into(), - }.into() - } -]); -``` - -The message consists of three instructions described as follows: - -- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register. - - ```rust - WithdrawAsset((Here, amount).into()), - ``` - - - **`Here`**: The native parachain token. - - **`amount`**: The number of tokens that are transferred. - - The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register. - -- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\_blank} of the XCM instructions. - - ```rust - BuyExecution { - fees: (Here, amount).into(), - weight_limit: WeightLimit::Unlimited - }, - ``` - - - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight. - - **`weight_limit`**: Defines the maximum fees that can be used to buy weight. - -- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\_blank}**: Moves the remaining tokens from the holding register to Bob’s account. - - ```rust - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: Junction::AccountId32 { - network: None, - id: BOB.clone().into() - }.into(), - }.into() - } - ``` - - - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited. - -This step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - -## Overview - -XCM revolutionizes cross-chain communication by enabling use cases such as: - -- Token transfers between blockchains. -- Asset locking for cross-chain smart contract interactions. -- Remote execution of functions on other blockchains. - -These functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - - ---- - -Page Title: JSON-RPC APIs - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-json-rpc-apis.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/json-rpc-apis/ -- Summary: JSON-RPC APIs guide for Polkadot Hub, covering supported methods, parameters, and examples for interacting with the chain. - -# JSON-RPC APIs - -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction - -Polkadot Hub provides Ethereum compatibility through its JSON-RPC interface, allowing developers to interact with the chain using familiar Ethereum tooling and methods. This document outlines the supported [Ethereum JSON-RPC methods](https://ethereum.org/developers/docs/apis/json-rpc/#json-rpc-methods){target=\_blank} and provides examples of how to use them. - -This guide uses the Polkadot Hub TestNet endpoint: - -```text -https://testnet-passet-hub-eth-rpc.polkadot.io -``` - -## Available Methods - -### eth_accounts - -Returns a list of addresses owned by the client. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_accounts){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_accounts" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_accounts", - "params":[], - "id":1 -}' -``` - ---- - -### eth_blockNumber - -Returns the number of the most recent block. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_blocknumber){target=\_blank}. - -**Parameters**: - -None. - -**Example**: +**Example**: ```bash title="eth_blockNumber" curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ @@ -4959,306 +3813,108 @@ If an error occurs, the response will include an error object: --- -Page Title: Networks +Page Title: Offenses and Slashes -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-networks.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/networks/ -- Summary: Explore Polkadot's testing and production networks, including Westend, Kusama, and Paseo, for efficient development, deployment, and testing. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-staking-mechanics-offenses-and-slashes.md +- Canonical (HTML): https://docs.polkadot.com/nodes-and-validators/run-a-validator/staking-mechanics/offenses-and-slashes/ +- Summary: Learn about how Polkadot discourages validator misconduct via an offenses and slashing system, including details on offenses and their consequences. -# Networks +# Offenses and Slashes ## Introduction -The Polkadot ecosystem is built on a robust set of networks designed to enable secure and scalable development. Whether you are testing new features or deploying to live production, Polkadot offers several layers of networks tailored for each stage of the development process. From local environments to experimental networks like Kusama and community-run TestNets such as Paseo, developers can thoroughly test, iterate, and validate their applications. This guide will introduce you to Polkadot's various networks and explain how they fit into the development workflow. +In Polkadot's Nominated Proof of Stake (NPoS) system, validator misconduct is deterred through a combination of slashing, disabling, and reputation penalties. Validators and nominators who stake tokens face consequences for validator misbehavior, which range from token slashes to restrictions on network participation. -## Network Overview +This page outlines the types of offenses recognized by Polkadot, including block equivocations and invalid votes, as well as the corresponding penalties. While some parachains may implement additional custom slashing mechanisms, this guide focuses on the offenses tied to staking within the Polkadot ecosystem. -Polkadot's development process is structured to ensure new features and upgrades are rigorously tested before being deployed on live production networks. The progression follows a well-defined path, starting from local environments and advancing through TestNets, ultimately reaching the Polkadot MainNet. The diagram below outlines the typical progression of the Polkadot development cycle: +## Offenses -``` mermaid -flowchart LR - id1[Local] --> id2[Westend] --> id4[Kusama] --> id5[Polkadot] - id1[Local] --> id3[Paseo] --> id5[Polkadot] -``` +Polkadot is a public permissionless network. As such, it has a mechanism to disincentivize offenses and incentivize good behavior. You can review the [parachain protocol](https://wiki.polkadot.com/learn/learn-parachains-protocol/#parachain-protocol){target=\_blank} to understand better the terminology used to describe offenses. Polkadot validator offenses fall into two categories: invalid votes and equivocations. -This flow ensures developers can thoroughly test and iterate without risking real tokens or affecting production networks. Testing tools like [Chopsticks](#chopsticks) and various TestNets make it easier to experiment safely before releasing to production. +### Invalid Votes -A typical journey through the Polkadot core protocol development process might look like this: +A validator will be penalized for inappropriate voting activity during the block inclusion and approval processes. The invalid voting related offenses are as follows: -1. **Local development node**: Development starts in a local environment, where developers can create, test, and iterate on upgrades or new features using a local development node. This stage allows rapid experimentation in an isolated setup without any external dependencies. +- **Backing an invalid block**: A para-validator backs an invalid block for inclusion in a fork of the relay chain. +- **`ForInvalid` vote**: When acting as a secondary checker, the validator votes in favor of an invalid block. +- **`AgainstValid` vote**: When acting as a secondary checker, the validator votes against a valid block. This type of vote wastes network resources required to resolve the disparate votes and resulting dispute. -2. **Westend**: After testing locally, upgrades are deployed to [Westend](#westend), Polkadot's primary TestNet. Westend simulates real-world conditions without using real tokens, making it the ideal place for rigorous feature testing before moving on to production networks. +### Equivocations -3. **Kusama**: Once features have passed extensive testing on Westend, they move to Kusama, Polkadot's experimental and fast-moving "canary" network. Kusama operates as a high-fidelity testing ground with actual economic incentives, giving developers insights into how their features will perform in a real-world environment. +Equivocation occurs when a validator produces statements that conflict with each other when producing blocks or voting. Unintentional equivocations usually occur when duplicate signing keys reside on the validator host. If keys are never duplicated, the probability of an honest equivocation slash decreases to near zero. The equivocation related offenses are as follows: -4. **Polkadot**: After passing tests on Westend and Kusama, features are considered ready for deployment to Polkadot, the live production network. +- **Equivocation**: The validator produces two or more of the same block or vote. + - **GRANDPA and BEEFY equivocation**: The validator signs two or more votes in the same round on different chains. + - **BABE equivocation**: The validator produces two or more blocks on the relay chain in the same time slot. +- **Double seconded equivocation**: The validator attempts to second, or back, more than one block in the same round. +- **Seconded and valid equivocation**: The validator seconds, or backs, a block and then attempts to hide their role as the responsible backer by later placing a standard validation vote. - In addition, parachain developers can leverage local TestNets like [Zombienet](#zombienet) and deploy upgrades on parachain TestNets. +## Penalties -5. **Paseo**: For parachain and dApp developers, Paseo serves as a community-run TestNet that mirrors Polkadot's runtime. Like Westend for core protocol development, Paseo provides a testing ground for parachain development without affecting live networks. +On Polkadot, offenses to the network incur different penalties depending on severity. There are three main penalties: slashing, disabling, and reputation changes. -!!!note - The Rococo TestNet deprecation date was October 14, 2024. Teams should use Westend for Polkadot protocol and feature testing and Paseo for chain development-related testing. +### Slashing -## Polkadot Development Networks +Validators engaging in bad actor behavior in the network may be subject to slashing if they commit a qualifying offense. When a validator is slashed, they and their nominators lose a percentage of their staked DOT or KSM, from as little as 0.01% up to 100% based on the severity of the offense. Nominators are evaluated for slashing against their active validations at any given time. Validator nodes are evaluated as discrete entities, meaning an operator can't attempt to mitigate the offense on another node they operate in order to avoid a slash. -Development and testing are crucial to building robust dApps and parachains and performing network upgrades within the Polkadot ecosystem. To achieve this, developers can leverage various networks and tools that provide a risk-free environment for experimentation and validation before deploying features to live networks. These networks help avoid the costs and risks associated with real tokens, enabling testing for functionalities like governance, cross-chain messaging, and runtime upgrades. +Any slashed DOT or KSM will be added to the [Treasury](https://wiki.polkadot.com/learn/learn-polkadot-opengov-treasury/){target=\_blank} rather than burned or distributed as rewards. Moving slashed funds to the Treasury allows tokens to be quickly moved away from malicious validators while maintaining the ability to revert faulty slashes when needed. -## Kusama Network +A nominator with a very large bond may nominate several validators in a single era. In this case, a slash is proportionate to the amount staked to the offending validator. Stake allocation and validator activation is controlled by the [Phragmén algorithm](https://wiki.polkadot.com/learn/learn-phragmen/#algorithm){target=\_blank}. -Kusama is the experimental version of Polkadot, designed for developers who want to move quickly and test their applications in a real-world environment with economic incentives. Kusama serves as a production-grade testing ground where developers can deploy features and upgrades with the pressure of game theory and economics in mind. It mirrors Polkadot but operates as a more flexible space for innovation. +A validator slash creates an `unapplied` state transition. You can view pending slashes on [Polkadot.js Apps](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Frpc.polkadot.io#/staking/slashes){target=\_blank}. The UI will display the slash per validator, the affected nominators, and the slash amounts. The unapplied state includes a 27-day grace period during which a governance proposal can be made to reverse the slash. Once this grace period expires, the slash is applied. -The native token for Kusama is KSM. For more information about KSM, visit the [Native Assets](https://wiki.polkadot.com/kusama/kusama-getting-started/){target=\_blank} page. +#### Equivocation Slash -## Test Networks +The Web3 Foundation's [Slashing mechanisms](https://research.web3.foundation/Polkadot/security/slashing/amounts){target=\_blank} page provides guidelines for evaluating the security threat level of different offenses and determining penalties proportionate to the threat level of the offense. Offenses requiring coordination between validators or extensive computational costs to the system will typically call for harsher penalties than those more likely to be unintentional than malicious. A description of potential offenses for each threat level and the corresponding penalties is as follows: -The following test networks provide controlled environments for testing upgrades and new features. TestNet tokens are available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}. +- **Level 1**: Honest misconduct such as isolated cases of unresponsiveness. + - **Penalty**: Validator can be kicked out or slashed up to 0.1% of stake in the validator slot. +- **Level 2**: Misconduct that can occur honestly but is a sign of bad practices. Examples include repeated cases of unresponsiveness and isolated cases of equivocation. + - **Penalty**: Slash of up to 1% of stake in the validator slot. +- **Level 3**: Misconduct that is likely intentional but of limited effect on the performance or security of the network. This level will typically include signs of coordination between validators. Examples include repeated cases of equivocation or isolated cases of unjustified voting on GRANDPA. + - **Penalty**: Reduction in networking reputation metrics, slash of up to 10% of stake in the validator slot. +- **Level 4**: Misconduct that poses severe security or monetary risk to the system or mass collusion. Examples include signs of extensive coordination, creating a serious security risk to the system, or forcing the system to use extensive resources to counter the misconduct. + - **Penalty**: Slash of up to 100% of stake in the validator slot. -### Westend +See the next section to understand how slash amounts for equivocations are calculated. If you want to know more details about slashing, please look at the research page on [Slashing mechanisms](https://research.web3.foundation/Polkadot/security/slashing/amounts){target=\_blank}. -Westend is Polkadot's primary permanent TestNet. Unlike temporary test networks, Westend is not reset to the genesis block, making it an ongoing environment for testing Polkadot core features. Managed by Parity Technologies, Westend ensures that developers can test features in a real-world simulation without using actual tokens. +#### Slash Calculation for Equivocation -The native token for Westend is WND. More details about WND can be found on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_2){target=\_blank} page. +The slashing penalty for GRANDPA, BABE, and BEEFY equivocations is calculated using the formula below, where `x` represents the number of offenders and `n` is the total number of validators in the active set: -### Paseo +```text +min((3 * x / n )^2, 1) +``` -[Paseo](https://github.com/paseo-network){target=\_blank} is a community-managed TestNet designed for parachain and dApp developers. It mirrors Polkadot's runtime and is maintained by Polkadot community members. Paseo provides a dedicated space for parachain developers to test their applications in a Polkadot-like environment without the risks associated with live networks. +The following scenarios demonstrate how this formula means slash percentages can increase exponentially based on the number of offenders involved compared to the size of the validator pool: -The native token for Paseo is PAS. Additional information on PAS is available on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_1){target=\_blank} page. +- **Minor offense**: Assume 1 validator out of a 100 validator active set equivocates in a slot. A single validator committing an isolated offense is most likely a mistake rather than malicious attack on the network. This offense results in a 0.09% slash to the stake in the validator slot. -## Local Test Networks + ``` mermaid + flowchart LR + N["Total Validators = 100"] + X["Offenders = 1"] + F["min((3 * 1 / 100)^2, 1) = 0.0009"] + G["0.09% slash of stake"] -Local test networks are an essential part of the development cycle for blockchain developers using the Polkadot SDK. They allow for fast, iterative testing in controlled, private environments without connecting to public TestNets. Developers can quickly spin up local instances to experiment, debug, and validate their code before deploying to larger TestNets like Westend or Paseo. Two key tools for local network testing are Zombienet and Chopsticks. + N --> F + X --> F + F --> G + ``` -### Zombienet +- **Moderate offense**: Assume 5 validators out a 100 validator active set equivocate in a slot. This is a slightly more serious event as there may be some element of coordination involved. This offense results in a 2.25% slash to the stake in the validator slot. -[Zombienet](https://github.com/paritytech/zombienet){target=\_blank} is a flexible testing framework for Polkadot SDK-based blockchains. It enables developers to create and manage ephemeral, short-lived networks. This feature makes Zombienet particularly useful for quick iterations, as it allows you to run multiple local networks concurrently, mimicking different runtime conditions. Whether you're developing a parachain or testing your custom blockchain logic, Zombienet gives you the tools to automate local testing. + ``` mermaid + flowchart LR + N["Total Validators = 100"] + X["Offenders = 5"] + F["min((3 * 5 / 100)^2, 1) = 0.0225"] + G["2.25% slash of stake"] -Key features of Zombienet include: - -- Creating dynamic, local networks with different configurations. -- Running parachains and relay chains in a simulated environment. -- Efficient testing of network components like cross-chain messaging and governance. - -Zombienet is ideal for developers looking to test quickly and thoroughly before moving to more resource-intensive public TestNets. - -### Chopsticks - -[Chopsticks](https://github.com/AcalaNetwork/chopsticks){target=\_blank} is a tool designed to create forks of Polkadot SDK-based blockchains, allowing developers to interact with network forks as part of their testing process. This capability makes Chopsticks a powerful option for testing upgrades, runtime changes, or cross-chain applications in a forked network environment. - -Key features of Chopsticks include: - -- Forking live Polkadot SDK-based blockchains for isolated testing. -- Simulating cross-chain messages in a private, controlled setup. -- Debugging network behavior by interacting with the fork in real-time. - -Chopsticks provides a controlled environment for developers to safely explore the effects of runtime changes. It ensures that network behavior is tested and verified before upgrades are deployed to live networks. - - ---- - -Page Title: Node and Runtime - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-node-and-runtime.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/node-and-runtime/ -- Summary: Learn how Polkadot SDK-based nodes function, how the client and runtime are separated, and how they communicate using SCALE-encoded data. - -# Node and Runtime - -## Introduction - -Every blockchain platform relies on a decentralized network of computers, called nodes, that communicate with each other about transactions and blocks. In this context, a node refers to the software running on the connected devices rather than the physical or virtual machines in the network. - -Polkadot SDK-based nodes consist of two main components, each with distinct responsibilities: the client (also called node) and the runtime. - -If the system were a monolithic protocol, any modification would require updating the entire system. Instead, Polkadot achieves true upgradeability by defining an immutable meta-protocol (the client) and a protocol (the runtime) that can be upgraded independently. - -This separation gives the [Polkadot Relay Chain](/polkadot-protocol/architecture/polkadot-chain){target=\_blank} and all connected [parachains](/polkadot-protocol/architecture/parachains){target=\_blank} an evolutionary advantage over other blockchain platforms. - -## Architectural Principles - -The Polkadot SDK-based blockchain architecture is fundamentally built on two distinct yet interconnected components: - -- Client (Meta-protocol): - - Handles the foundational infrastructure of the blockchain. - - Manages runtime execution, networking, consensus, and other off-chain components. - - Provides an immutable base layer that ensures network stability. - - Upgradable only through hard forks. - -- Runtime (Protocol): - - Defines the blockchain's state transition logic. - - Determines the specific rules and behaviors of the blockchain. - - Compiled to WebAssembly (Wasm) for platform-independent execution. - - Capable of being upgraded without network-wide forking. - -### Advantages of this Architecture - -- **Forkless upgrades**: Runtime can be updated without disrupting the entire network. -- **Modularity**: Clear separation allows independent development of client and runtime. -- **Flexibility**: Enables rapid iteration and evolution of blockchain logic. -- **Performance**: WebAssembly compilation provides efficient, cross-platform execution. - -## Node (Client) - -The node, also known as the client, is the core component responsible for executing the Wasm runtime and orchestrating various essential blockchain components. It ensures the correct execution of the state transition function and manages multiple critical subsystems, including: - -- **Wasm execution**: Runs the blockchain runtime, which defines the state transition rules. -- **Database management**: Stores blockchain data. -- **Networking**: Facilitates peer-to-peer communication, block propagation, and transaction gossiping. -- **Transaction pool (Mempool)**: Manages pending transactions before they are included in a block. -- **Consensus mechanism**: Ensures agreement on the blockchain state across nodes. -- **RPC services**: Provides external interfaces for applications and users to interact with the node. - -## Runtime - -The runtime is more than just a set of rules. It's the fundamental logic engine that defines a blockchain's entire behavior. In Polkadot SDK-based blockchains, the runtime represents a complete, self-contained description of the blockchain's state transition function. - -### Characteristics - -The runtime is distinguished by three key characteristics: - -- **Business logic**: Defines the complete application-specific blockchain behavior. -- **WebAssembly compilation**: Ensures platform-independent, secure execution. -- **On-chain storage**: Stored within the blockchain's state, allowing dynamic updates. - -### Key Functions - -The runtime performs several critical functions, such as: - -- Define state transition rules. -- Implement blockchain-specific logic. -- Manage account interactions. -- Control transaction processing. -- Define governance mechanisms. -- Handle custom pallets and modules. - -## Communication Between Node and Runtime - -The client and runtime communicate exclusively using [SCALE-encoded](/polkadot-protocol/parachain-basics/data-encoding){target=\_blank} communication. This ensures efficient and compact data exchange between the two components. - -### Runtime APIs - -The Runtime API consists of well-defined functions and constants a client assumes are implemented in the Runtime Wasm blob. These APIs enable the client to interact with the runtime to execute blockchain operations and retrieve information. The client invokes these APIs to: - -- Build, execute, and finalize blocks. -- Access metadata. -- Access consensus related information. -- Handle transaction execution. - -### Host Functions - -During execution, the runtime can access certain external client functionalities via host functions. The specific functions the client exposes allow the runtime to perform operations outside the WebAssembly domain. Host functions enable the runtime to: - -- Perform cryptographic operations. -- Access the current blockchain state. -- Handle storage modifications. -- Allocate memory. - - ---- - -Page Title: Offenses and Slashes - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-staking-mechanics-offenses-and-slashes.md -- Canonical (HTML): https://docs.polkadot.com/nodes-and-validators/run-a-validator/staking-mechanics/offenses-and-slashes/ -- Summary: Learn about how Polkadot discourages validator misconduct via an offenses and slashing system, including details on offenses and their consequences. - -# Offenses and Slashes - -## Introduction - -In Polkadot's Nominated Proof of Stake (NPoS) system, validator misconduct is deterred through a combination of slashing, disabling, and reputation penalties. Validators and nominators who stake tokens face consequences for validator misbehavior, which range from token slashes to restrictions on network participation. - -This page outlines the types of offenses recognized by Polkadot, including block equivocations and invalid votes, as well as the corresponding penalties. While some parachains may implement additional custom slashing mechanisms, this guide focuses on the offenses tied to staking within the Polkadot ecosystem. - -## Offenses - -Polkadot is a public permissionless network. As such, it has a mechanism to disincentivize offenses and incentivize good behavior. You can review the [parachain protocol](https://wiki.polkadot.com/learn/learn-parachains-protocol/#parachain-protocol){target=\_blank} to understand better the terminology used to describe offenses. Polkadot validator offenses fall into two categories: invalid votes and equivocations. - -### Invalid Votes - -A validator will be penalized for inappropriate voting activity during the block inclusion and approval processes. The invalid voting related offenses are as follows: - -- **Backing an invalid block**: A para-validator backs an invalid block for inclusion in a fork of the relay chain. -- **`ForInvalid` vote**: When acting as a secondary checker, the validator votes in favor of an invalid block. -- **`AgainstValid` vote**: When acting as a secondary checker, the validator votes against a valid block. This type of vote wastes network resources required to resolve the disparate votes and resulting dispute. - -### Equivocations - -Equivocation occurs when a validator produces statements that conflict with each other when producing blocks or voting. Unintentional equivocations usually occur when duplicate signing keys reside on the validator host. If keys are never duplicated, the probability of an honest equivocation slash decreases to near zero. The equivocation related offenses are as follows: - -- **Equivocation**: The validator produces two or more of the same block or vote. - - **GRANDPA and BEEFY equivocation**: The validator signs two or more votes in the same round on different chains. - - **BABE equivocation**: The validator produces two or more blocks on the relay chain in the same time slot. -- **Double seconded equivocation**: The validator attempts to second, or back, more than one block in the same round. -- **Seconded and valid equivocation**: The validator seconds, or backs, a block and then attempts to hide their role as the responsible backer by later placing a standard validation vote. - -## Penalties - -On Polkadot, offenses to the network incur different penalties depending on severity. There are three main penalties: slashing, disabling, and reputation changes. - -### Slashing - -Validators engaging in bad actor behavior in the network may be subject to slashing if they commit a qualifying offense. When a validator is slashed, they and their nominators lose a percentage of their staked DOT or KSM, from as little as 0.01% up to 100% based on the severity of the offense. Nominators are evaluated for slashing against their active validations at any given time. Validator nodes are evaluated as discrete entities, meaning an operator can't attempt to mitigate the offense on another node they operate in order to avoid a slash. - -Any slashed DOT or KSM will be added to the [Treasury](https://wiki.polkadot.com/learn/learn-polkadot-opengov-treasury/){target=\_blank} rather than burned or distributed as rewards. Moving slashed funds to the Treasury allows tokens to be quickly moved away from malicious validators while maintaining the ability to revert faulty slashes when needed. - -A nominator with a very large bond may nominate several validators in a single era. In this case, a slash is proportionate to the amount staked to the offending validator. Stake allocation and validator activation is controlled by the [Phragmén algorithm](https://wiki.polkadot.com/learn/learn-phragmen/#algorithm){target=\_blank}. - -A validator slash creates an `unapplied` state transition. You can view pending slashes on [Polkadot.js Apps](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Frpc.polkadot.io#/staking/slashes){target=\_blank}. The UI will display the slash per validator, the affected nominators, and the slash amounts. The unapplied state includes a 27-day grace period during which a governance proposal can be made to reverse the slash. Once this grace period expires, the slash is applied. - -#### Equivocation Slash - -The Web3 Foundation's [Slashing mechanisms](https://research.web3.foundation/Polkadot/security/slashing/amounts){target=\_blank} page provides guidelines for evaluating the security threat level of different offenses and determining penalties proportionate to the threat level of the offense. Offenses requiring coordination between validators or extensive computational costs to the system will typically call for harsher penalties than those more likely to be unintentional than malicious. A description of potential offenses for each threat level and the corresponding penalties is as follows: - -- **Level 1**: Honest misconduct such as isolated cases of unresponsiveness. - - **Penalty**: Validator can be kicked out or slashed up to 0.1% of stake in the validator slot. -- **Level 2**: Misconduct that can occur honestly but is a sign of bad practices. Examples include repeated cases of unresponsiveness and isolated cases of equivocation. - - **Penalty**: Slash of up to 1% of stake in the validator slot. -- **Level 3**: Misconduct that is likely intentional but of limited effect on the performance or security of the network. This level will typically include signs of coordination between validators. Examples include repeated cases of equivocation or isolated cases of unjustified voting on GRANDPA. - - **Penalty**: Reduction in networking reputation metrics, slash of up to 10% of stake in the validator slot. -- **Level 4**: Misconduct that poses severe security or monetary risk to the system or mass collusion. Examples include signs of extensive coordination, creating a serious security risk to the system, or forcing the system to use extensive resources to counter the misconduct. - - **Penalty**: Slash of up to 100% of stake in the validator slot. - -See the next section to understand how slash amounts for equivocations are calculated. If you want to know more details about slashing, please look at the research page on [Slashing mechanisms](https://research.web3.foundation/Polkadot/security/slashing/amounts){target=\_blank}. - -#### Slash Calculation for Equivocation - -The slashing penalty for GRANDPA, BABE, and BEEFY equivocations is calculated using the formula below, where `x` represents the number of offenders and `n` is the total number of validators in the active set: - -```text -min((3 * x / n )^2, 1) -``` - -The following scenarios demonstrate how this formula means slash percentages can increase exponentially based on the number of offenders involved compared to the size of the validator pool: - -- **Minor offense**: Assume 1 validator out of a 100 validator active set equivocates in a slot. A single validator committing an isolated offense is most likely a mistake rather than malicious attack on the network. This offense results in a 0.09% slash to the stake in the validator slot. - - ``` mermaid - flowchart LR - N["Total Validators = 100"] - X["Offenders = 1"] - F["min((3 * 1 / 100)^2, 1) = 0.0009"] - G["0.09% slash of stake"] - - N --> F - X --> F - F --> G - ``` - -- **Moderate offense**: Assume 5 validators out a 100 validator active set equivocate in a slot. This is a slightly more serious event as there may be some element of coordination involved. This offense results in a 2.25% slash to the stake in the validator slot. - - ``` mermaid - flowchart LR - N["Total Validators = 100"] - X["Offenders = 5"] - F["min((3 * 5 / 100)^2, 1) = 0.0225"] - G["2.25% slash of stake"] - - N --> F - X --> F - F --> G - ``` + N --> F + X --> F + F --> G + ``` - **Major offense**: Assume 20 validators out a 100 validator active set equivocate in a slot. This is a major security threat as it possible represents a coordinated attack on the network. This offense results in a 36% slash and all slashed validators will also be chilled. ``` mermaid @@ -5329,100 +3985,6 @@ Some minor offenses, such as spamming, are only punished by networking reputatio Refer to the Polkadot Wiki's [offenses page](https://wiki.polkadot.com/learn/learn-offenses/){target=\_blank} for a summary of penalties for specific offenses. ---- - -Page Title: On-Chain Governance Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-governance.md -- Canonical (HTML): https://docs.polkadot.com/reference/governance/ -- Summary: Discover Polkadot’s cutting-edge OpenGov system, enabling transparent, decentralized decision-making through direct democracy and flexible governance tracks. - -# On-Chain Governance - -## Introduction - -Polkadot’s governance system exemplifies decentralized decision-making, empowering its community of stakeholders to shape the network’s future through active participation. The latest evolution, OpenGov, builds on Polkadot’s foundation by providing a more inclusive and efficient governance model. - -This guide will explain the principles and structure of OpenGov and walk you through its key components, such as Origins, Tracks, and Delegation. You will learn about improvements over earlier governance systems, including streamlined voting processes and enhanced stakeholder participation. - -With OpenGov, Polkadot achieves a flexible, scalable, and democratic governance framework that allows multiple proposals to proceed simultaneously, ensuring the network evolves in alignment with its community's needs. - -## Governance Evolution - -Polkadot’s governance journey began with [Governance V1](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#governance-summary){target=\_blank}, a system that proved effective in managing treasury funds and protocol upgrades. However, it faced limitations, such as: - -- Slow voting cycles, causing delays in decision-making. -- Inflexibility in handling multiple referendums, restricting scalability. - -To address these challenges, Polkadot introduced OpenGov, a governance model designed for greater inclusivity, efficiency, and scalability. OpenGov replaces the centralized structures of Governance V1, such as the Council and Technical Committee, with a fully decentralized and dynamic framework. - -For a full comparison of the historic and current governance models, visit the [Gov1 vs. Polkadot OpenGov](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#gov1-vs-polkadot-opengov){target=\_blank} section of the Polkadot Wiki. - -## OpenGov Key Features - -OpenGov transforms Polkadot’s governance into a decentralized, stakeholder-driven model, eliminating centralized decision-making bodies like the Council. Key enhancements include: - -- **Decentralization**: Shifts all decision-making power to the public, ensuring a more democratic process. -- **Enhanced delegation**: Allows users to delegate their votes to trusted experts across specific governance tracks. -- **Simultaneous referendums**: Multiple proposals can progress at once, enabling faster decision-making. -- **Polkadot Technical Fellowship**: A broad, community-driven group replacing the centralized Technical Committee. - -This new system ensures Polkadot governance remains agile and inclusive, even as the ecosystem grows. - -## Origins and Tracks - -In OpenGov, origins and tracks are central to managing proposals and votes. - -- **Origin**: Determines the authority level of a proposal (e.g., Treasury, Root) which decides the track of all referendums from that origin. -- **Track**: Define the procedural flow of a proposal, such as voting duration, approval thresholds, and enactment timelines. - -Developers must be aware that referendums from different origins and tracks will take varying amounts of time to reach approval and enactment. The [Polkadot Technical Fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} has the option to shorten this timeline by whitelisting a proposal and allowing it to be enacted through the [Whitelist Caller](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#whitelisted-caller){target=\_blank} origin. - -Visit [Origins and Tracks Info](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#origins-and-tracks){target=\_blank} for details on current origins and tracks, associated terminology, and parameters. - -## Referendums - -In OpenGov, anyone can submit a referendum, fostering an open and participatory system. The timeline for a referendum depends on the privilege level of the origin with more significant changes offering more time for community voting and participation before enactment. - -The timeline for an individual referendum includes four distinct periods: - -- **Lead-in**: A minimum amount of time to allow for community participation, available room in the origin, and payment of the decision deposit. Voting is open during this period. -- **Decision**: Voting continues. -- **Confirmation**: Referendum must meet [approval and support](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#approval-and-support){target=\_blank} criteria during entire period to avoid rejection. -- **Enactment**: Changes approved by the referendum are executed. - -### Vote on Referendums - -Voters can vote with their tokens on each referendum. Polkadot uses a voluntary token locking mechanism, called conviction voting, as a way for voters to increase their voting power. A token holder signals they have a stronger preference for approving a proposal based upon their willingness to lock up tokens. Longer voluntary token locks are seen as a signal of continual approval and translate to increased voting weight. - -See [Voting on a Referendum](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank} for a deeper look at conviction voting and related token locks. - -### Delegate Voting Power - -The OpenGov system also supports multi-role delegations, allowing token holders to assign their voting power on different tracks to entities with expertise in those areas. - -For example, if a token holder lacks the technical knowledge to evaluate proposals on the [Root track](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#root){target=\_blank}, they can delegate their voting power for that track to an expert they trust to vote in the best interest of the network. This ensures informed decision-making across tracks while maintaining flexibility for token holders. - -Visit [Multirole Delegation](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#multirole-delegation){target=\_blank} for more details on delegating voting power. - -### Cancel a Referendum - -Polkadot OpenGov has two origins for rejecting ongoing referendums: - -- [**Referendum Canceller**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-canceller){target=\_blank}: Cancels an active referendum when non-malicious errors occur and refunds the deposits to the originators. -- [**Referendum Killer**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-killer){target=\_blank}: Used for urgent, malicious cases this origin instantly terminates an active referendum and slashes deposits. - -See [Cancelling, Killing, and Blacklisting](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#cancelling-killing--blacklisting){target=\_blank} for additional information on rejecting referendums. - -## Additional Resources - -- **[Democracy pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/democracy/src){target=\_blank}**: Handles administration of general stakeholder voting. -- **[Gov2: Polkadot’s Next Generation of Decentralised Governance](https://medium.com/polkadot-network/gov2-polkadots-next-generation-of-decentralised-governance-4d9ef657d11b){target=\_blank}**: Medium article by Gavin Wood. -- **[Polkadot Direction](https://matrix.to/#/#Polkadot-Direction:parity.io){target=\_blank}**: Matrix Element client. -- **[Polkassembly](https://polkadot.polkassembly.io/){target=\_blank}**: OpenGov dashboard and UI. -- **[Polkadot.js Apps Governance](https://polkadot.js.org/apps/#/referenda){target=\_blank}**: Overview of active referendums. - - --- Page Title: Overview of FRAME @@ -5559,973 +4121,51 @@ This section covers the most common customization patterns you'll encounter: --- -Page Title: Overview of the Polkadot Relay Chain +Page Title: Pause Validating -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-relay-chain.md -- Canonical (HTML): https://docs.polkadot.com/reference/polkadot-hub/consensus-and-security/relay-chain/ -- Summary: Explore Polkadot's core architecture, including its multi-chain vision, shared security, and the DOT token's governance and staking roles. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-operational-tasks-pause-validating.md +- Canonical (HTML): https://docs.polkadot.com/nodes-and-validators/run-a-validator/operational-tasks/pause-validating/ +- Summary: Learn how to temporarily pause staking activity in Polkadot using the chill extrinsic, with guidance for validators and nominators. -# Overview +# Pause Validating ## Introduction -Polkadot is a next-generation blockchain protocol designed to support a multi-chain future by enabling secure communication and interoperability between different blockchains. Built as a Layer-0 protocol, Polkadot introduces innovations like application-specific Layer-1 chains ([parachains](/polkadot-protocol/architecture/parachains/){targe=\_blank}), shared security through [Nominated Proof of Stake (NPoS)](/reference/glossary/#nominated-proof-of-stake-npos){target=\_blank}, and cross-chain interactions via its native [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank}. - -This guide covers key aspects of Polkadot’s architecture, including its high-level protocol structure, blockspace commoditization, and the role of its native token, DOT, in governance, staking, and resource allocation. - -## Polkadot 1.0 - -Polkadot 1.0 represents the state of Polkadot as of 2023, coinciding with the release of [Polkadot runtime v1.0.0](https://github.com/paritytech/polkadot/releases/tag/v1.0.0){target=\_blank}. This section will focus on Polkadot 1.0, along with philosophical insights into network resilience and blockspace. - -As a Layer-0 blockchain, Polkadot contributes to the multi-chain vision through several key innovations and initiatives, including: - -- **Application-specific Layer-1 blockchains (parachains)**: Polkadot's sharded network allows for parallel transaction processing, with shards that can have unique state transition functions, enabling custom-built L1 chains optimized for specific applications. - -- **Shared security and scalability**: L1 chains connected to Polkadot benefit from its [Nominated Proof of Stake (NPoS)](/reference/polkadot-hub/consensus-and-security/pos-consensus/#nominated-proof-of-stake){target=\_blank} system, providing security out-of-the-box without the need to bootstrap their own. - -- **Secure interoperability**: Polkadot's native interoperability enables seamless data and value exchange between parachains. This interoperability can also be used outside of the ecosystem for bridging with external networks. - -- **Resilient infrastructure**: Decentralized and scalable, Polkadot ensures ongoing support for development and community initiatives via its on-chain [treasury](https://wiki.polkadot.com/learn/learn-polkadot-opengov-treasury/){target=\_blank} and governance. - -- **Rapid L1 development**: The [Polkadot SDK](/reference/parachains/){target=\_blank} allows fast, flexible creation and deployment of Layer-1 chains. - -- **Cultivating the next generation of Web3 developers**: Polkadot supports the growth of Web3 core developers through initiatives such as. - - - [Polkadot Blockchain Academy](https://polkadot.com/blockchain-academy){target=\_blank} - - [EdX courses](https://www.edx.org/school/web3x){target=\_blank} - - Rust and Substrate courses (coming soon) - -### High-Level Architecture - -Polkadot features a chain that serves as the central component of the system. This chain is depicted as a ring encircled by several parachains that are connected to it. - -According to Polkadot's design, any blockchain that can compile to WebAssembly (Wasm) and adheres to the Parachains Protocol becomes a parachain on the Polkadot network. - -Here’s a high-level overview of the Polkadot protocol architecture: - -![](/images/reference/polkadot-hub/consensus-and-security/relay-chain/relay-chain-01.webp){ style="background:white" } - -Parachains propose blocks to Polkadot validators, who check for availability and validity before finalizing them. With the relay chain providing security, collators—full nodes of parachains—can focus on their tasks without needing strong incentives. - -The [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank} allows parachains to exchange messages freely, leveraging the chain's security for trust-free communication. - -In order to interact with chains that want to use their own finalization process (e.g., Bitcoin), Polkadot has [bridges](/reference/parachains/interoperability/#bridges-connecting-external-networks){target=\_blank} that offer two-way compatibility, meaning that transactions can be made between different parachains. - -### Polkadot's Additional Functionalities - -Historically, obtaining core slots on Polkadot chain relied upon crowdloans and auctions. Chain cores were leased through auctions for three-month periods, up to a maximum of two years. Crowdloans enabled users to securely lend funds to teams for lease deposits in exchange for pre-sale tokens, which is the only way to access slots on Polkadot 1.0. Auctions are now deprecated in favor of [coretime](/polkadot-protocol/architecture/system-chains/coretime/){target=\_blank}. - -Additionally, the chain handles [staking](https://wiki.polkadot.com/learn/learn-staking/){target=\_blank}, [accounts](/reference/parachains/accounts/){target=\_blank}, balances, and [governance](/reference/governance/){target=\_blank}. - -#### Agile Coretime - -The new and more efficient way of obtaining core on Polkadot is to go through the process of purchasing coretime. - -[Agile coretime](/reference/polkadot-hub/consensus-and-security/agile-coretime/){target=\_blank} improves the efficient use of Polkadot's network resources and offers economic flexibility for developers, extending Polkadot's capabilities far beyond the original vision outlined in the [whitepaper](https://polkadot.com/papers/Polkadot-whitepaper.pdf){target=\_blank}. - -It enables parachains to purchase monthly "bulk" allocations of coretime (the time allocated for utilizing a core, measured in Polkadot relay chain blocks), ensuring heavy-duty parachains that can author a block every six seconds with [Asynchronous Backing](https://wiki.polkadot.com/learn/learn-async-backing/#asynchronous-backing){target=\_blank} can reliably renew their coretime each month. Although six-second block times are now the default, parachains have the option of producing blocks less frequently. - -Renewal orders are prioritized over new orders, offering stability against price fluctuations and helping parachains budget more effectively for project costs. - -### Polkadot's Resilience - -Decentralization is a vital component of blockchain networks, but it comes with trade-offs: - -- An overly decentralized network may face challenges in reaching consensus and require significant energy to operate. -- Also, a network that achieves consensus quickly risks centralization, making it easier to manipulate or attack. - -A network should be decentralized enough to prevent manipulative or malicious influence. In this sense, decentralization is a tool for achieving resilience. - -Polkadot 1.0 currently achieves resilience through several strategies: - -- **Nominated Proof of Stake (NPoS)**: Ensures that the stake per validator is maximized and evenly distributed among validators. - -- **Decentralized nodes**: Designed to encourage operators to join the network. This program aims to expand and diversify the validators in the ecosystem who aim to become independent of the program during their term. Feel free to explore more about the program on the official [Decentralized Nodes](https://nodes.web3.foundation/){target=\_blank} page. - -- **On-chain treasury and governance**: Known as [OpenGov](/reference/governance/){target=\_blank}, this system allows every decision to be made through public referenda, enabling any token holder to cast a vote. - -### Polkadot's Blockspace - -Polkadot 1.0’s design allows for the commoditization of blockspace. - -Blockspace is a blockchain's capacity to finalize and commit operations, encompassing its security, computing, and storage capabilities. Its characteristics can vary across different blockchains, affecting security, flexibility, and availability. - -- **Security**: Measures the robustness of blockspace in Proof of Stake (PoS) networks linked to the stake locked on validator nodes, the variance in stake among validators, and the total number of validators. It also considers social centralization (how many validators are owned by single operators) and physical centralization (how many validators run on the same service provider). - -- **Flexibility**: Reflects the functionalities and types of data that can be stored, with high-quality data essential to avoid bottlenecks in critical processes. - -- **Availability**: Indicates how easily users can access blockspace. It should be easily accessible, allowing diverse business models to thrive, ideally regulated by a marketplace based on demand and supplemented by options for "second-hand" blockspace. - -Polkadot is built on core blockspace principles, but there's room for improvement. Tasks like balance transfers, staking, and governance are managed on the relay chain. - -Delegating these responsibilities to [system chains](/polkadot-protocol/architecture/system-chains/){target=\_blank} could enhance flexibility and allow the relay chain to concentrate on providing shared security and interoperability. - -For more information about blockspace, watch [Robert Habermeier’s interview](https://www.youtube.com/watch?v=e1vISppPwe4){target=\_blank} or read his [technical blog post](https://www.rob.tech/blog/polkadot-blockspace-over-blockchains/){target=\_blank}. - -## DOT Token - -DOT is the native token of the Polkadot network, much like BTC for Bitcoin and Ether for the Ethereum blockchain. DOT has 10 decimals, uses the Planck base unit, and has a balance type of `u128`. The same is true for Kusama's KSM token with the exception of having 12 decimals. - -### Redenomination of DOT - -Polkadot conducted a community poll, which ended on 27 July 2020 at block 888,888, to decide whether to redenominate the DOT token. The stakeholders chose to redenominate the token, changing the value of 1 DOT from 1e12 plancks to 1e10 plancks. - -Importantly, this did not affect the network's total number of base units (plancks); it only affects how a single DOT is represented. The redenomination became effective 72 hours after transfers were enabled, occurring at block 1,248,328 on 21 August 2020 around 16:50 UTC. - -### The Planck Unit - -The smallest unit of account balance on Polkadot SDK-based blockchains (such as Polkadot and Kusama) is called _Planck_, named after the Planck length, the smallest measurable distance in the physical universe. - -Similar to how BTC's smallest unit is the Satoshi and ETH's is the Wei, Polkadot's native token DOT equals 1e10 Planck, while Kusama's native token KSM equals 1e12 Planck. - -### Uses for DOT - -DOT serves three primary functions within the Polkadot network: - -- **Governance**: It is used to participate in the governance of the network. -- **Staking**: DOT is staked to support the network's operation and security. -- **Buying coretime**: Used to purchase coretime in-bulk or on-demand and access the chain to benefit from Polkadot's security and interoperability. - -Additionally, DOT can serve as a transferable token. For example, DOT, held in the treasury, can be allocated to teams developing projects that benefit the Polkadot ecosystem. - -## JAM and the Road Ahead - -The Join-Accumulate Machine (JAM) represents a transformative redesign of Polkadot's core architecture, envisioned as the successor to the current relay chain. Unlike traditional blockchain architectures, JAM introduces a unique computational model that processes work through two primary functions: - -- **Join**: Handles data integration. -- **Accumulate**: Folds computations into the chain's state. - -JAM removes many of the opinions and constraints of the current relay chain while maintaining its core security properties. Expected improvements include: - -- **Permissionless code execution**: JAM is designed to be more generic and flexible, allowing for permissionless code execution through services that can be deployed without governance approval. -- **More effective block time utilization**: JAM's efficient pipeline processing model places the prior state root in block headers instead of the posterior state root, enabling more effective utilization of block time for computations. - -This architectural evolution promises to enhance Polkadot's scalability and flexibility while maintaining robust security guarantees. JAM is planned to be rolled out to Polkadot as a single, complete upgrade rather than a stream of smaller updates. This approach seeks to minimize the developer overhead required to address any breaking changes. - - ---- - -Page Title: Parachains Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/ -- Summary: Learn about parachains, specialized blockchains on Polkadot that gain shared security and interoperability. Discover how they work and the tools to build them. - -# Parachains Overview - -## Introduction - -A parachain is a specialized blockchain that connects to the Polkadot relay chain, benefiting from shared security, interoperability, and scalability. Parachains are built using the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}, a powerful toolkit written in Rust that provides everything needed to create custom blockchain logic while integrating seamlessly with the Polkadot network. - -Unlike standalone blockchains that must bootstrap their own validator sets and security, parachains leverage Polkadot's pooled security model. This allows parachain developers to focus on their application-specific functionality rather than consensus and security infrastructure. Parachains can communicate with each other through Cross-Consensus Messaging (XCM), enabling seamless interoperability across the Polkadot ecosystem. - -Key capabilities that parachains provide include: - -- **Shared security**: Inherit security from Polkadot's validator set without maintaining your own. -- **Interoperability**: Communicate trustlessly with other parachains via XCM. -- **Scalability**: Process transactions in parallel with other parachains. -- **Customization**: Build application-specific logic tailored to your use case. -- **Upgradeability**: Upgrade runtime logic without hard forks. - -## Polkadot SDK: Parachain Architecture - -Building a parachain involves understanding and utilizing several key components of the Polkadot SDK: - -![](/images/reference/parachains/index/overview-01.webp) - -- **[Substrate](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/substrate/index.html){target=\_blank}**: The foundation providing core blockchain primitives and libraries. -- **[FRAME](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank}**: A modular framework for building your parachain's runtime logic. -- **[Cumulus](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/cumulus/index.html){target=\_blank}**: Essential libraries and pallets that enable parachain functionality. -- **[XCM (Cross Consensus Messaging)](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/xcm/index.html){target=\_blank}**: The messaging format for communicating with other parachains and the relay chain. -- **[Polkadot](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/polkadot/index.html){target=\_blank}**: The relay chain that provides security and coordination. - -### Substrate: The Foundation - -Substrate provides the core infrastructure that every parachain is built upon. It handles the low-level blockchain functionality, allowing you to focus on your application's unique features. Substrate includes implementations for networking, database management, consensus participation, and the execution environment for your runtime. - -Every Polkadot SDK node consists of two main components: - -- **Client (Host)**: Handles infrastructure services. - - - Native binary that runs on validator and collator nodes. - - Executes the Wasm-compiled runtime. - - Manages networking, database, mempool, and block production. - - Interfaces with the relay chain for validation. - -- **Runtime (State Transition Function)**: Contains your business logic. - - - Defines how your Polkadot SDK node processes transactions. - - Compiled to [Wasm](https://webassembly.org/){target=\_blank} for deterministic execution. - - Stored on-chain and upgradeable via governance. - -```mermaid -%%{init: {'flowchart': {'padding': 5, 'nodeSpacing': 50, 'rankSpacing': 10}}}%% -graph TB - classDef title font-size:20px,font-weight:bold,stroke-width:0px - classDef clientStyle font-size:16px,font-weight:bold - classDef clientSubNodeStyle margin-top:10px - classDef runtimeCallExecutorStyle padding-top:10px - - subgraph sg1[Parachain
Node] - direction TB - - I[RuntimeCall Executor] - B[Wasm Runtime - STF] - - subgraph sg2[Client] - direction TB - C[Network and Blockchain
Infrastructure Services
+ Relay Chain Interface] - end - - I --> B - end - - class sg1 title - class sg2 clientStyle - class C clientSubNodeStyle - class I runtimeCallExecutorStyle - -``` - -### FRAME: Building Blocks for Your Runtime - -FRAME provides modular components called [pallets](/reference/glossary#pallet){target=\_blank} that you can compose to build your parachain's runtime. Each pallet provides specific functionality that you can customize and configure for your needs. This modular approach allows you to quickly assemble complex functionality without writing everything from scratch. - -```mermaid -graph LR - subgraph SP["Parachain Runtime"] - direction LR - Timestamp ~~~ Aura ~~~ ParachainSystem - Balances ~~~ TransactionPayment ~~~ Sudo - subgraph Timestamp["Timestamp"] - SS1[Custom Config] - end - subgraph Aura["Aura"] - SS2[Custom Config] - end - subgraph ParachainSystem["Parachain System"] - SS3[Custom Config] - end - subgraph Balances["Balances"] - SS4[Custom Config] - end - subgraph TransactionPayment["Transaction Payment"] - SS5[Custom Config] - end - subgraph Sudo["Sudo"] - SS6[Custom Config] - end - style Timestamp stroke:#FF69B4 - style Aura stroke:#FF69B4 - style ParachainSystem stroke:#FF69B4 - style Balances stroke:#FF69B4 - style TransactionPayment stroke:#FF69B4 - style Sudo stroke:#FF69B4 - style SS1 stroke-dasharray: 5 - style SS2 stroke-dasharray: 5 - style SS3 stroke-dasharray: 5 - style SS4 stroke-dasharray: 5 - style SS5 stroke-dasharray: 5 - style SS6 stroke-dasharray: 5 - - end - subgraph AP["Available FRAME Pallets"] - direction LR - A1[Aura]~~~A2[Parachain
System]~~~A3[Transaction
Payment]~~~A4[Sudo] - B1[Identity]~~~B2[Balances]~~~B3[Assets]~~~B4[EVM] - C1[Timestamp]~~~C2[Staking]~~~C3[Contracts]~~~C4[and more...] - end - AP --> SP -``` - -### Cumulus: Parachain-Specific Functionality - -Cumulus is what transforms a Polkadot SDK-based runtime into a parachain-capable runtime. It provides the essential components for communicating with the relay chain, participating in Polkadot's consensus, and handling parachain-specific operations like block validation and collation. - -Key Cumulus components include: - -- **Parachain system pallet**: Core parachain functionality and relay chain communication. -- **Collator consensus**: Block production logic for parachain collators. -- **Relay chain interface**: APIs for interacting with the Polkadot relay chain. -- **Validation data**: Handling proof-of-validity data required by relay chain validators. - -## Where to Go Next - -Building a parachain requires understanding the relationship between your chain and the Polkadot relay chain. The Polkadot SDK provides all the tools needed to design custom runtime logic, enable cross-chain communication, and deploy your parachain to production. - -The following sections provide detailed guidance on each aspect of parachain development, from initial design through deployment and ongoing maintenance. - -
- -- Guide __Launch a Simple Parachain__ - - --- - - Walk through the complete parachain launch flow: from setup and deployment to obtaining coretime. - - [:octicons-arrow-right-24: Deploy](/parachains/launch-a-parachain/set-up-the-parachain-template/) - - -- Guide __Customize Your Runtime__ - - --- - - Design your parachain's runtime logic and choose appropriate pallets for your use case. - - [:octicons-arrow-right-24: Get Started](/parachains/customize-runtime/) - -- Guide __Interoperability__ - - --- - - Implement XCM for trustless cross-chain communication with other parachains. - - [:octicons-arrow-right-24: Learn More](/parachains/interoperability/get-started/) - -- Guide __Runtime Upgrades__ - - --- - - Upgrade your parachain's runtime without hard forks using forkless upgrade mechanisms. - - [:octicons-arrow-right-24: Maintain](/parachains/runtime-maintenance/runtime-upgrades/) - -
- - ---- - -Page Title: Pause Validating - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-operational-tasks-pause-validating.md -- Canonical (HTML): https://docs.polkadot.com/nodes-and-validators/run-a-validator/operational-tasks/pause-validating/ -- Summary: Learn how to temporarily pause staking activity in Polkadot using the chill extrinsic, with guidance for validators and nominators. - -# Pause Validating - -## Introduction - -If you need to temporarily stop participating in Polkadot staking activities without fully unbonding your funds, chilling your account allows you to do so efficiently. Chilling removes your node from active validation or nomination in the next era while keeping your funds bonded, making it ideal for planned downtimes or temporary pauses. - -This guide covers the steps for chilling as a validator or nominator, using the `chill` and `chillOther` extrinsics, and how these affect your staking status and nominations. - -## Chilling Your Node - -If you need to temporarily step back from staking without unbonding your funds, you can "chill" your account. Chilling pauses your active staking participation, setting your account to inactive in the next era while keeping your funds bonded. - -To chill your account, go to the **Network > Staking > Account Actions** page on [Polkadot.js Apps](https://polkadot.js.org/apps){target=\_blank}, and select **Stop**. Alternatively, you can call the [`chill`](https://paritytech.github.io/polkadot-sdk/master/pallet_staking/enum.Call.html#variant.chill){target=\_blank} extrinsic in the Staking pallet. - -## Staking Election Timing Considerations - -When a node actively participates in staking but then chills, it will continue contributing for the remainder of the current era. However, its eligibility for the next election depends on the chill status at the start of the new era: - -- **Chilled during previous era**: Will not participate in the current era election and will remain inactive until reactivated. -- **Chilled during current era**: Will not be selected for the next era's election. -- **Chilled after current era**: May be selected if it was active during the previous era and is now chilled. - -## Chilling as a Nominator - -When you choose to chill as a nominator, your active nominations are reset. Upon re-entering the nominating process, you must reselect validators to support manually. Depending on preferences, these can be the same validators as before or a new set. Remember that your previous nominations won’t be saved or automatically reactivated after chilling. - -While chilled, your nominator account remains bonded, preserving your staked funds without requiring a full unbonding process. When you’re ready to start nominating again, you can issue a new nomination call to activate your bond with a fresh set of validators. This process bypasses the need for re-bonding, allowing you to maintain your stake while adjusting your involvement in active staking. - -## Chilling as a Validator - -When you chill as a validator, your active validator status is paused. Although your nominators remain bonded to you, the validator bond will no longer appear as an active choice for new or revised nominations until reactivated. Any existing nominators who take no action will still have their stake linked to the validator, meaning they don’t need to reselect the validator upon reactivation. However, if nominators adjust their stakes while the validator is chilled, they will not be able to nominate the chilled validator until it resumes activity. - -Upon reactivating as a validator, you must also reconfigure your validator preferences, such as commission rate and other parameters. These can be set to match your previous configuration or updated as desired. This step is essential for rejoining the active validator set and regaining eligibility for nominations. - -## Chill Other - -Historical constraints in the runtime prevented unlimited nominators and validators from being supported. These constraints created a need for checks to keep the size of the staking system manageable. One of these checks is the `chillOther` extrinsic, allowing users to chill accounts that no longer met standards such as minimum staking requirements set through on-chain governance. - -This control mechanism included a `ChillThreshold`, which was structured to define how close to the maximum number of nominators or validators the staking system would be allowed to get before users could start chilling one another. With the passage of [Referendum #90](https://polkadot-old.polkassembly.io/referendum/90){target=\_blank}, the value for `maxNominatorCount` on Polkadot was set to `None`, effectively removing the limit on how many nominators and validators can participate. This means the `ChillThreshold` will never be met; thus, `chillOther` no longer has any effect. - - ---- - -Page Title: Polkadot SDK Accounts - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-accounts.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/accounts/ -- Summary: Learn about account structures, balances, and address formats in the Polkadot SDK, including how to manage lifecycle, references, and balances. - -# Accounts - -## Introduction - -Accounts are essential for managing identity, transactions, and governance on the network in the Polkadot SDK. Understanding these components is critical for seamless development and operation on the network, whether you're building or interacting with Polkadot-based chains. - -This page will guide you through the essential aspects of accounts, including their data structure, balance types, reference counters, and address formats. You’ll learn how accounts are managed within the runtime, how balances are categorized, and how addresses are encoded and validated. - -## Account Data Structure - -Accounts are foundational to any blockchain, and the Polkadot SDK provides a flexible management system. This section explains how the Polkadot SDK defines accounts and manages their lifecycle through data structures within the runtime. - -### Account - -The [`Account` data type](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/type.Account.html){target=\_blank} is a storage map within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank} that links an account ID to its corresponding data. This structure is fundamental for mapping account-related information within the chain. - -The code snippet below shows how accounts are defined: - -```rs - /// The full account information for a particular account ID. - #[pallet::storage] - #[pallet::getter(fn account)] - pub type Account = StorageMap< - _, - Blake2_128Concat, - T::AccountId, - AccountInfo, - ValueQuery, - >; -``` - -The preceding code block defines a storage map named `Account`. The `StorageMap` is a type of on-chain storage that maps keys to values. In the `Account` map, the key is an account ID, and the value is the account's information. Here, `T` represents the generic parameter for the runtime configuration, which is defined by the pallet's configuration trait (`Config`). - -The `StorageMap` consists of the following parameters: - -- **`_`**: Used in macro expansion and acts as a placeholder for the storage prefix type. Tells the macro to insert the default prefix during expansion. -- **`Blake2_128Concat`**: The hashing function applied to keys in the storage map. -- **`T: :AccountId`**: Represents the key type, which corresponds to the account’s unique ID. -- **`AccountInfo`**: The value type stored in the map. For each account ID, the map stores an `AccountInfo` struct containing: - - - **`T::Nonce`**: A nonce for the account, which is incremented with each transaction to ensure transaction uniqueness. - - **`T: :AccountData`**: Custom account data defined by the runtime configuration, which could include balances, locked funds, or other relevant information. - -- **`ValueQuery`**: Defines how queries to the storage map behave when no value is found; returns a default value instead of `None`. - -For a detailed explanation of storage maps, see the [`StorageMap`](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/struct.StorageMap.html){target=\_blank} entry in the Rust docs. - -### Account Info - -The `AccountInfo` structure is another key element within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank}, providing more granular details about each account's state. This structure tracks vital data, such as the number of transactions and the account’s relationships with other modules. - -```rs -/// Information of an account. -#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)] -pub struct AccountInfo { - /// The number of transactions this account has sent. - pub nonce: Nonce, - /// The number of other modules that currently depend on this account's existence. The account - /// cannot be reaped until this is zero. - pub consumers: RefCount, - /// The number of other modules that allow this account to exist. The account may not be reaped - /// until this and `sufficients` are both zero. - pub providers: RefCount, - /// The number of modules that allow this account to exist for their own purposes only. The - /// account may not be reaped until this and `providers` are both zero. - pub sufficients: RefCount, - /// The additional data that belongs to this account. Used to store the balance(s) in a lot of - /// chains. - pub data: AccountData, -} -``` - -The `AccountInfo` structure includes the following components: - -- **`nonce`**: Tracks the number of transactions initiated by the account, which ensures transaction uniqueness and prevents replay attacks. -- **`consumers`**: Counts how many other modules or pallets rely on this account’s existence. The account cannot be removed from the chain (reaped) until this count reaches zero. -- **`providers`**: Tracks how many modules permit this account’s existence. An account can only be reaped once both `providers` and `sufficients` are zero. -- **`sufficients`**: Represents the number of modules that allow the account to exist for internal purposes, independent of any other modules. -- **`AccountData`**: A flexible data structure that can be customized in the runtime configuration, usually containing balances or other user-specific data. - -This structure helps manage an account's state and prevents its premature removal while it is still referenced by other on-chain data or modules. The [`AccountInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.AccountInfo.html){target=\_blank} structure can vary as long as it satisfies the trait bounds defined by the `AccountData` associated type in the [`frame-system::pallet::Config`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/trait.Config.html){target=\_blank} trait. - -### Account Reference Counters - -Polkadot SDK uses reference counters to track an account’s dependencies across different runtime modules. These counters ensure that accounts remain active while data is associated with them. - -The reference counters include: - -- **`consumers`**: Prevents account removal while other pallets still rely on the account. -- **`providers`**: Ensures an account is active before other pallets store data related to it. -- **`sufficients`**: Indicates the account’s independence, ensuring it can exist even without a native token balance, such as when holding sufficient alternative assets. - -#### Providers Reference Counters - -The `providers` counter ensures that an account is ready to be depended upon by other runtime modules. For example, it is incremented when an account has a balance above the existential deposit, which marks the account as active. - -The system requires this reference counter to be greater than zero for the `consumers` counter to be incremented, ensuring the account is stable before any dependencies are added. - -#### Consumers Reference Counters - -The `consumers` counter ensures that the account cannot be reaped until all references to it across the runtime have been removed. This check prevents the accidental deletion of accounts that still have active on-chain data. - -It is the user’s responsibility to clear out any data from other runtime modules if they wish to remove their account and reclaim their existential deposit. - -#### Sufficients Reference Counter - -The `sufficients` counter tracks accounts that can exist independently without relying on a native account balance. This is useful for accounts holding other types of assets, like tokens, without needing a minimum balance in the native token. - -For instance, the [Assets pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_assets/index.html){target=\_blank}, may increment this counter for an account holding sufficient tokens. - -#### Account Deactivation - -In Polkadot SDK-based chains, an account is deactivated when its reference counters (such as `providers`, `consumers`, and `sufficient`) reach zero. These counters ensure the account remains active as long as other runtime modules or pallets reference it. - -When all dependencies are cleared and the counters drop to zero, the account becomes deactivated and may be removed from the chain (reaped). This is particularly important in Polkadot SDK-based blockchains, where accounts with balances below the existential deposit threshold are pruned from storage to conserve state resources. - -Each pallet that references an account has cleanup functions that decrement these counters when the pallet no longer depends on the account. Once these counters reach zero, the account is marked for deactivation. - -#### Updating Counters - -The Polkadot SDK provides runtime developers with various methods to manage account lifecycle events, such as deactivation or incrementing reference counters. These methods ensure that accounts cannot be reaped while still in use. - -The following helper functions manage these counters: - -- **`inc_consumers()`**: Increments the `consumer` reference counter for an account, signaling that another pallet depends on it. -- **`dec_consumers()`**: Decrements the `consumer` reference counter, signaling that a pallet no longer relies on the account. -- **`inc_providers()`**: Increments the `provider` reference counter, ensuring the account remains active. -- **`dec_providers()`**: Decrements the `provider` reference counter, allowing for account deactivation when no longer in use. -- **`inc_sufficients()`**: Increments the `sufficient` reference counter for accounts that hold sufficient assets. -- **`dec_sufficients()`**: Decrements the `sufficient` reference counter. - -To ensure proper account cleanup and lifecycle management, a corresponding decrement should be made for each increment action. - -The `System` pallet offers three query functions to assist developers in tracking account states: - -- **[`can_inc_consumer()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_inc_consumer){target=\_blank}**: Checks if the account can safely increment the consumer reference. -- **[`can_dec_provider()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_dec_provider){target=\_blank}**: Ensures that no consumers exist before allowing the decrement of the provider counter. -- **[`is_provider_required()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.is_provider_required){target=\_blank}**: Verifies whether the account still has any active consumer references. - -This modular and flexible system of reference counters tightly controls the lifecycle of accounts in Polkadot SDK-based blockchains, preventing the accidental removal or retention of unneeded accounts. You can refer to the [System pallet Rust docs](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html){target=\_blank} for more details. - - -## Account Balance Types - -In the Polkadot ecosystem, account balances are categorized into different types based on how the funds are utilized and their availability. These balance types determine the actions that can be performed, such as transferring tokens, paying transaction fees, or participating in governance activities. Understanding these balance types helps developers manage user accounts and implement balance-dependent logic. - -!!! note "A more efficient distribution of account balance types is in development" - Soon, pallets in the Polkadot SDK will implement the [`Fungible` trait](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} (see the [tracking issue](https://github.com/paritytech/polkadot-sdk/issues/226){target=\_blank} for more details). For example, the [`transaction-storage`](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_storage/index.html){target=\_blank} pallet changed the implementation of the [`Currency`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/currency/index.html){target=\_blank} trait (see the [Refactor transaction storage pallet to use fungible traits](https://github.com/paritytech/polkadot-sdk/pull/1800){target=\_blank} PR for further details): - - ```rust - type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; - ``` - - To the [`Fungible`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} trait: - - ```rust - type BalanceOf = <::Currency as FnInspect<::AccountId>>::Balance; - ``` - - This update will enable more efficient use of account balances, allowing the free balance to be utilized for on-chain activities such as setting proxies and managing identities. - -### Balance Types - -The five main balance types are: - -- **Free balance**: Represents the total tokens available to the account for any on-chain activity, including staking, governance, and voting. However, it may not be fully spendable or transferrable if portions of it are locked or reserved. -- **Locked balance**: Portions of the free balance that cannot be spent or transferred because they are tied up in specific activities like [staking](https://wiki.polkadot.com/learn/learn-staking/#nominating-validators){target=\_blank}, [vesting](https://wiki.polkadot.com/learn/learn-guides-transfers/#vested-transfers-with-the-polkadot-js-ui){target=\_blank}, or participating in [governance](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank}. While the tokens remain part of the free balance, they are non-transferable for the duration of the lock. -- **Reserved balance**: Funds locked by specific system actions, such as setting up an [identity](https://wiki.polkadot.com/learn/learn-identity/){target=\_blank}, creating [proxies](https://wiki.polkadot.com/learn/learn-proxies/){target=\_blank}, or submitting [deposits for governance proposals](https://wiki.polkadot.com/learn/learn-guides-polkadot-opengov/#claiming-opengov-deposits){target=\_blank}. These tokens are not part of the free balance and cannot be spent unless they are unreserved. -- **Spendable balance**: The portion of the free balance that is available for immediate spending or transfers. It is calculated by subtracting the maximum of locked or reserved amounts from the free balance, ensuring that existential deposit limits are met. -- **Untouchable balance**: Funds that cannot be directly spent or transferred but may still be utilized for on-chain activities, such as governance participation or staking. These tokens are typically tied to certain actions or locked for a specific period. - -The spendable balance is calculated as follows: - -```text -spendable = free - max(locked - reserved, ED) -``` - -Here, `free`, `locked`, and `reserved` are defined above. The `ED` represents the [existential deposit](https://wiki.polkadot.com/learn/learn-accounts/#existential-deposit-and-reaping){target=\_blank}, the minimum balance required to keep an account active and prevent it from being reaped. You may find you can't see all balance types when looking at your account via a wallet. Wallet providers often display only spendable, locked, and reserved balances. - -### Locks - -Locks are applied to an account's free balance, preventing that portion from being spent or transferred. Locks are automatically placed when an account participates in specific on-chain activities, such as staking or governance. Although multiple locks may be applied simultaneously, they do not stack. Instead, the largest lock determines the total amount of locked tokens. - -Locks follow these basic rules: - -- If different locks apply to varying amounts, the largest lock amount takes precedence. -- If multiple locks apply to the same amount, the lock with the longest duration governs when the balance can be unlocked. - -#### Locks Example - -Consider an example where an account has 80 DOT locked for both staking and governance purposes like so: - -- 80 DOT is staked with a 28-day lock period. -- 24 DOT is locked for governance with a 1x conviction and a 7-day lock period. -- 4 DOT is locked for governance with a 6x conviction and a 224-day lock period. - -In this case, the total locked amount is 80 DOT because only the largest lock (80 DOT from staking) governs the locked balance. These 80 DOT will be released at different times based on the lock durations. In this example, the 24 DOT locked for governance will be released first since the shortest lock period is seven days. The 80 DOT stake with a 28-day lock period is released next. Now, all that remains locked is the 4 DOT for governance. After 224 days, all 80 DOT (minus the existential deposit) will be free and transferable. - -![Illustration of Lock Example](/images/reference/parachains/accounts/accounts-01.webp) - -#### Edge Cases for Locks - -In scenarios where multiple convictions and lock periods are active, the lock duration and amount are determined by the longest period and largest amount. For example, if you delegate with different convictions and attempt to undelegate during an active lock period, the lock may be extended for the full amount of tokens. For a detailed discussion on edge case lock behavior, see this [Stack Exchange post](https://substrate.stackexchange.com/questions/5067/delegating-and-undelegating-during-the-lock-period-extends-it-for-the-initial-am){target=\_blank}. - -### Balance Types on Polkadot.js - -Polkadot.js provides a user-friendly interface for managing and visualizing various account balances on Polkadot and Kusama networks. When interacting with Polkadot.js, you will encounter multiple balance types that are critical for understanding how your funds are distributed and restricted. This section explains how different balances are displayed in the Polkadot.js UI and what each type represents. - -![](/images/reference/parachains/accounts/accounts-02.webp) - -The most common balance types displayed on Polkadot.js are: - -- **Total balance**: The total number of tokens available in the account. This includes all tokens, whether they are transferable, locked, reserved, or vested. However, the total balance does not always reflect what can be spent immediately. In this example, the total balance is 0.6274 KSM. - -- **Transferable balance**: Shows how many tokens are immediately available for transfer. It is calculated by subtracting the locked and reserved balances from the total balance. For example, if an account has a total balance of 0.6274 KSM and a transferable balance of 0.0106 KSM, only the latter amount can be sent or spent freely. - -- **Vested balance**: Tokens that allocated to the account but released according to a specific schedule. Vested tokens remain locked and cannot be transferred until fully vested. For example, an account with a vested balance of 0.2500 KSM means that this amount is owned but not yet transferable. - -- **Locked balance**: Tokens that are temporarily restricted from being transferred or spent. These locks typically result from participating in staking, governance, or vested transfers. In Polkadot.js, locked balances do not stack—only the largest lock is applied. For instance, if an account has 0.5500 KSM locked for governance and staking, the locked balance would display 0.5500 KSM, not the sum of all locked amounts. - -- **Reserved balance**: Refers to tokens locked for specific on-chain actions, such as setting an identity, creating a proxy, or making governance deposits. Reserved tokens are not part of the free balance, but can be freed by performing certain actions. For example, removing an identity would unreserve those funds. - -- **Bonded balance**: The tokens locked for staking purposes. Bonded tokens are not transferable until they are unbonded after the unbonding period. - -- **Redeemable balance**: The number of tokens that have completed the unbonding period and are ready to be unlocked and transferred again. For example, if an account has a redeemable balance of 0.1000 KSM, those tokens are now available for spending. - -- **Democracy balance**: Reflects the number of tokens locked for governance activities, such as voting on referenda. These tokens are locked for the duration of the governance action and are only released after the lock period ends. - -By understanding these balance types and their implications, developers and users can better manage their funds and engage with on-chain activities more effectively. - -## Address Formats - -The SS58 address format is a core component of the Polkadot SDK that enables accounts to be uniquely identified across Polkadot-based networks. This format is a modified version of Bitcoin's Base58Check encoding, specifically designed to accommodate the multi-chain nature of the Polkadot ecosystem. SS58 encoding allows each chain to define its own set of addresses while maintaining compatibility and checksum validation for security. - -### Basic Format - -SS58 addresses consist of three main components: - -```text -base58encode(concat(,
, )) -``` - -- **Address type**: A byte or set of bytes that define the network (or chain) for which the address is intended. This ensures that addresses are unique across different Polkadot SDK-based chains. -- **Address**: The public key of the account encoded as bytes. -- **Checksum**: A hash-based checksum which ensures that addresses are valid and unaltered. The checksum is derived from the concatenated address type and address components, ensuring integrity. - -The encoding process transforms the concatenated components into a Base58 string, providing a compact and human-readable format that avoids easily confused characters (e.g., zero '0', capital 'O', lowercase 'l'). This encoding function ([`encode`](https://docs.rs/bs58/latest/bs58/fn.encode.html){target=\_blank}) is implemented exactly as defined in Bitcoin and IPFS specifications, using the same alphabet as both implementations. - -For more details about the SS58 address format implementation, see the [`Ss58Codec`](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Ss58Codec.html){target=\_blank} trait in the Rust Docs. - -### Address Type - -The address type defines how an address is interpreted and to which network it belongs. Polkadot SDK uses different prefixes to distinguish between various chains and address formats: - -- **Address types `0-63`**: Simple addresses, commonly used for network identifiers. -- **Address types `64-127`**: Full addresses that support a wider range of network identifiers. -- **Address types `128-255`**: Reserved for future address format extensions. - -For example, Polkadot’s main network uses an address type of 0, while Kusama uses 2. This ensures that addresses can be used without confusion between networks. - -The address type is always encoded as part of the SS58 address, making it easy to quickly identify the network. Refer to the [SS58 registry](https://github.com/paritytech/ss58-registry){target=\_blank} for the canonical listing of all address type identifiers and how they map to Polkadot SDK-based networks. - -### Address Length - -SS58 addresses can have different lengths depending on the specific format. Address lengths range from as short as 3 to 35 bytes, depending on the complexity of the address and network requirements. This flexibility allows SS58 addresses to adapt to different chains while providing a secure encoding mechanism. - -| Total | Type | Raw account | Checksum | -|-------|------|-------------|----------| -| 3 | 1 | 1 | 1 | -| 4 | 1 | 2 | 1 | -| 5 | 1 | 2 | 2 | -| 6 | 1 | 4 | 1 | -| 7 | 1 | 4 | 2 | -| 8 | 1 | 4 | 3 | -| 9 | 1 | 4 | 4 | -| 10 | 1 | 8 | 1 | -| 11 | 1 | 8 | 2 | -| 12 | 1 | 8 | 3 | -| 13 | 1 | 8 | 4 | -| 14 | 1 | 8 | 5 | -| 15 | 1 | 8 | 6 | -| 16 | 1 | 8 | 7 | -| 17 | 1 | 8 | 8 | -| 35 | 1 | 32 | 2 | - -SS58 addresses also support different payload sizes, allowing a flexible range of account identifiers. - -### Checksum Types - -A checksum is applied to validate SS58 addresses. Polkadot SDK uses a Blake2b-512 hash function to calculate the checksum, which is appended to the address before encoding. The checksum length can vary depending on the address format (e.g., 1-byte, 2-byte, or longer), providing varying levels of validation strength. - -The checksum ensures that an address is not modified or corrupted, adding an extra layer of security for account management. - -### Validating Addresses - -SS58 addresses can be validated using the subkey command-line interface or the Polkadot.js API. These tools help ensure an address is correctly formatted and valid for the intended network. The following sections will provide an overview of how validation works with these tools. - -#### Using Subkey - -[Subkey](https://paritytech.github.io/polkadot-sdk/master/subkey/index.html){target=\_blank} is a CLI tool provided by Polkadot SDK for generating and managing keys. It can inspect and validate SS58 addresses. - -The `inspect` command gets a public key and an SS58 address from the provided secret URI. The basic syntax for the `subkey inspect` command is: - -```bash -subkey inspect [flags] [options] uri -``` - -For the `uri` command-line argument, you can specify the secret seed phrase, a hex-encoded private key, or an SS58 address. If the input is a valid address, the `subkey` program displays the corresponding hex-encoded public key, account identifier, and SS58 addresses. - -For example, to inspect the public keys derived from a secret seed phrase, you can run a command similar to the following: - -```bash -subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" -``` - -The command displays output similar to the following: - -
- subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" - Secret phrase `caution juice atom organ advance problem want pledge someone senior holiday very` is account: - Secret seed: 0xc8fa03532fb22ee1f7f6908b9c02b4e72483f0dbd66e4cd456b8f34c6230b849 - Public key (hex): 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - Public key (SS58): 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR - Account ID: 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - SS58 Address: 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR -
- -The `subkey` program assumes an address is based on a public/private key pair. If you inspect an address, the command returns the 32-byte account identifier. - -However, not all addresses in Polkadot SDK-based networks are based on keys. - -Depending on the command-line options you specify and the input you provided, the command output might also display the network for which the address has been encoded. For example: - -```bash -subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" -``` - -The command displays output similar to the following: - -
- subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" - Public Key URI `12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU` is account: - Network ID/Version: polkadot - Public key (hex): 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Account ID: 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Public key (SS58): 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU - SS58 Address: 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU -
- -#### Using Polkadot.js API - -To verify an address in JavaScript or TypeScript projects, you can use the functions built into the [Polkadot.js API](https://polkadot.js.org/docs/){target=\_blank}. For example: - -```js -// Import Polkadot.js API dependencies -const { decodeAddress, encodeAddress } = require('@polkadot/keyring'); -const { hexToU8a, isHex } = require('@polkadot/util'); - -// Specify an address to test. -const address = 'INSERT_ADDRESS_TO_TEST'; - -// Check address -const isValidSubstrateAddress = () => { - try { - encodeAddress(isHex(address) ? hexToU8a(address) : decodeAddress(address)); - - return true; - } catch (error) { - return false; - } -}; - -// Query result -const isValid = isValidSubstrateAddress(); -console.log(isValid); - -``` - -If the function returns `true`, the specified address is a valid address. - -#### Other SS58 Implementations - -Support for encoding and decoding Polkadot SDK SS58 addresses has been implemented in several other languages and libraries. - -- **Crystal**: [`wyhaines/base58.cr`](https://github.com/wyhaines/base58.cr){target=\_blank} -- **Go**: [`itering/subscan-plugin`](https://github.com/itering/subscan-plugin){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **TypeScript**: [`subsquid/squid-sdk`](https://github.com/subsquid/squid-sdk){target=\_blank} - - ---- - -Page Title: Randomness - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-randomness.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/randomness/ -- Summary: Explore the importance of randomness in PoS blockchains, focusing on Polkadot’s VRF-based approach to ensure fairness and security in validator selection. - -# Randomness - -## Introduction - -Randomness is crucial in Proof of Stake (PoS) blockchains to ensure a fair and unpredictable distribution of validator duties. However, computers are inherently deterministic, meaning the same input always produces the same output. What we typically refer to as "random" numbers on a computer are actually pseudo-random. These numbers rely on an initial "seed," which can come from external sources like [atmospheric noise](https://www.random.org/randomness/){target=\_blank}, [heart rates](https://mdpi.altmetric.com/details/47574324){target=\_blank}, or even [lava lamps](https://en.wikipedia.org/wiki/Lavarand){target=\_blank}. While this may seem random, given the same "seed," the same sequence of numbers will always be generated. - -In a global blockchain network, relying on real-world entropy for randomness isn’t feasible because these inputs vary by time and location. If nodes use different inputs, blockchains can fork. Hence, real-world randomness isn't suitable for use as a seed in blockchain systems. - -Currently, two primary methods for generating randomness in blockchains are used: [`RANDAO`](#randao) and [`VRF`](#vrf) (Verifiable Random Function). Polkadot adopts the `VRF` approach for its randomness. - -## VRF - -A Verifiable Random Function (VRF) is a cryptographic function that generates a random number and proof that ensures the submitter produced the number. This proof allows anyone to verify the validity of the random number. - -Polkadot's VRF is similar to the one used in [**Ouroboros Praos**](https://eprint.iacr.org/2017/573.pdf){target=\_blank}, which secures randomness for block production in systems like [BABE](/reference/polkadot-hub/consensus-and-security/pos-consensus/#block-production-babe){target=\_blank} (Polkadot’s block production mechanism). - -The key difference is that Polkadot's VRF doesn’t rely on a central clock—avoiding the issue of whose clock to trust. Instead, it uses its own past results and slot numbers to simulate time and determine future outcomes. - -### How VRF Works - -Slots on Polkadot are discrete units of time, each lasting six seconds, and can potentially hold a block. Multiple slots form an epoch, with 2400 slots making up one four-hour epoch. - -In each slot, validators execute a "die roll" using a VRF. The VRF uses three inputs: - -1. A "secret key," unique to each validator, is used for the die roll. -2. An epoch randomness value, derived from the hash of VRF outputs from blocks two epochs ago (N-2), so past randomness influences the current epoch (N). -3. The current slot number. - -This process helps maintain fair randomness across the network. - -Here is a graphical representation: - -![](/images/reference/parachains/randomness/randomness-01.webp) - -The VRF produces two outputs: a result (the random number) and a proof (verifying that the number was generated correctly). - -The result is checked by the validator against a protocol threshold. If it's below the threshold, the validator becomes a candidate for block production in that slot. - -The validator then attempts to create a block, submitting it along with the `PROOF` and `RESULT`. - -So, VRF can be expressed like: - -`(RESULT, PROOF) = VRF(SECRET, EPOCH_RANDOMNESS_VALUE, CURRENT_SLOT_NUMBER)` - -Put simply, performing a "VRF roll" generates a random number along with proof that the number was genuinely produced and not arbitrarily chosen. - -After executing the VRF, the `RESULT` is compared to a protocol-defined `THRESHOLD`. If the `RESULT` is below the `THRESHOLD`, the validator becomes a valid candidate to propose a block for that slot. Otherwise, the validator skips the slot. - -As a result, there may be multiple validators eligible to propose a block for a slot. In this case, the block accepted by other nodes will prevail, provided it is on the chain with the latest finalized block as determined by the GRANDPA finality gadget. It's also possible for no block producers to be available for a slot, in which case the AURA consensus takes over. AURA is a fallback mechanism that randomly selects a validator to produce a block, running in parallel with BABE and only stepping in when no block producers exist for a slot. Otherwise, it remains inactive. - -Because validators roll independently, no block candidates may appear in some slots if all roll numbers are above the threshold. - -To verify resolution of this issue and that Polkadot block times remain near constant-time, see the [PoS Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} page of this documentation. - -## RANDAO - -An alternative on-chain randomness method is Ethereum's RANDAO, where validators perform thousands of hashes on a seed and publish the final hash during a round. The collective input from all validators forms the random number, and as long as one honest validator participates, the randomness is secure. - -To enhance security, RANDAO can optionally be combined with a Verifiable Delay Function (VDF), ensuring that randomness can't be predicted or manipulated during computation. - -For more information about RANDAO, see the [Randomness - RANDAO](https://eth2book.info/capella/part2/building_blocks/randomness/){target=\_blank} section of the Upgrading Ethereum documentation. - -## VDFs - -Verifiable Delay Functions (VDFs) are time-bound computations that, even on parallel computers, take a set amount of time to complete. - -They produce a unique result that can be quickly verified publicly. When combined with RANDAO, feeding RANDAO's output into a VDF introduces a delay that nullifies an attacker's chance to influence the randomness. - -However, VDF likely requires specialized ASIC devices to run separately from standard nodes. - -!!!warning - While only one is needed to secure the system, and they will be open-source and inexpensive, running VDF devices involves significant costs without direct incentives, adding friction for blockchain users. - -## Additional Resources - -For more information about the reasoning for choices made along with proofs, see Polkadot's research on blockchain randomness and sortition in the [Block production](https://research.web3.foundation/Polkadot/protocols/block-production){target=\_blank} entry of the Polkadot Wiki. - -For a discussion with Web3 Foundation researchers about when and under what conditions Polkadot's randomness can be utilized, see the [Discussion on Randomness used in Polkadot](https://github.com/use-ink/ink/issues/57){target=\_blank} issue on GitHub. - - ---- - -Page Title: Register a Local Asset - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-token-operations-register-local-asset.md -- Canonical (HTML): https://docs.polkadot.com/chain-interactions/token-operations/register-local-asset/ -- Summary: Comprehensive guide to registering a local asset on the Asset Hub system parachain, including step-by-step instructions. - -# Register a Local Asset on Asset Hub - -## Introduction - -As detailed in the [Asset Hub Overview](/polkadot-protocol/architecture/system-chains/asset-hub){target=\_blank} page, Asset Hub accommodates two types of assets: local and foreign. Local assets are those that were created in Asset Hub and are identifiable by an integer ID. On the other hand, foreign assets originate from a sibling parachain and are identified by a Multilocation. - -This guide will take you through the steps of registering a local asset on the Asset Hub parachain. - -## Prerequisites - -Before you begin, ensure you have access to the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and a funded wallet with DOT or KSM. - -- For Polkadot Asset Hub, you would need a deposit of 10 DOT and around 0.201 DOT for the metadata. -- For Kusama Asset Hub, the deposit is 0.1 KSM and around 0.000669 KSM for the metadata. - -You need to ensure that your Asset Hub account balance is a bit more than the sum of those two deposits, which should seamlessly account for the required deposits and transaction fees. - -## Steps to Register a Local Asset - -To register a local asset on the Asset Hub parachain, follow these steps: - -1. Open the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and connect to the Asset Hub parachain using the network selector in the top left corner. - - - You may prefer to test local asset registration on TestNet before registering the asset on a MainNet hub. If you still need to set up a local testing environment, review the [Environment setup](#test-setup-environment) section for instructions. Once the local environment is set up, connect to the Local Node (Chopsticks) available on `ws://127.0.0.1:8000`. - - For the live network, connect to the **Asset Hub** parachain. Either Polkadot or Kusama Asset Hub can be selected from the dropdown list, choosing the desired RPC provider. - -2. Click on the **Network** tab on the top navigation bar and select **Assets** from the dropdown list. - - ![Access to Asset Hub through Polkadot.JS](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-01.webp) - -3. Now, you need to examine all the registered asset IDs. This step is crucial to ensure that the asset ID you are about to register is unique. Asset IDs are displayed in the **assets** column. - - ![Asset IDs on Asset Hub](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-02.webp) - -4. Once you have confirmed that the asset ID is unique, click on the **Create** button on the top right corner of the page. - - ![Create a new asset](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-03.webp) - -5. Fill in the required fields in the **Create Asset** form: - - 1. **creator account**: The account to be used for creating this asset and setting up the initial metadata. - 2. **asset name**: The descriptive name of the asset you are registering. - 3. **asset symbol**: The symbol that will be used to represent the asset. - 4. **asset decimals**: The number of decimal places for this token, with a maximum of 20 allowed through the user interface. - 5. **minimum balance**: The minimum balance for the asset. This is specified in the units and decimals as requested. - 6. **asset ID**: The selected id for the asset. This should not match an already-existing asset id. - 7. Click on the **Next** button. - - ![Create Asset Form](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-04.webp) - -6. Choose the accounts for the roles listed below: +If you need to temporarily stop participating in Polkadot staking activities without fully unbonding your funds, chilling your account allows you to do so efficiently. Chilling removes your node from active validation or nomination in the next era while keeping your funds bonded, making it ideal for planned downtimes or temporary pauses. - 1. **admin account**: The account designated for continuous administration of the token. - 2. **issuer account**: The account that will be used for issuing this token. - 3. **freezer account**: The account that will be used for performing token freezing operations. - 4. Click on the **Create** button. +This guide covers the steps for chilling as a validator or nominator, using the `chill` and `chillOther` extrinsics, and how these affect your staking status and nominations. - ![Admin, Issuer, Freezer accounts](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-05.webp) +## Chilling Your Node -7. Click on the **Sign and Submit** button to complete the asset registration process. +If you need to temporarily step back from staking without unbonding your funds, you can "chill" your account. Chilling pauses your active staking participation, setting your account to inactive in the next era while keeping your funds bonded. - ![Sign and Submit](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-06.webp) +To chill your account, go to the **Network > Staking > Account Actions** page on [Polkadot.js Apps](https://polkadot.js.org/apps){target=\_blank}, and select **Stop**. Alternatively, you can call the [`chill`](https://paritytech.github.io/polkadot-sdk/master/pallet_staking/enum.Call.html#variant.chill){target=\_blank} extrinsic in the Staking pallet. -## Verify Asset Registration +## Staking Election Timing Considerations -After completing these steps, the asset will be successfully registered. You can now view your asset listed on the [**Assets**](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fasset-hub-polkadot-rpc.dwellir.com#/assets){target=\_blank} section of the Polkadot.js Apps interface. +When a node actively participates in staking but then chills, it will continue contributing for the remainder of the current era. However, its eligibility for the next election depends on the chill status at the start of the new era: -![Asset listed on Polkadot.js Apps](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-07.webp) +- **Chilled during previous era**: Will not participate in the current era election and will remain inactive until reactivated. +- **Chilled during current era**: Will not be selected for the next era's election. +- **Chilled after current era**: May be selected if it was active during the previous era and is now chilled. -!!! tip - Take into consideration that the **Assets** section’s link may differ depending on the network you are using. For the local environment, enter `ws://127.0.0.1:8000` into the **Custom Endpoint** field. +## Chilling as a Nominator -In this way, you have successfully registered a local asset on the Asset Hub parachain. +When you choose to chill as a nominator, your active nominations are reset. Upon re-entering the nominating process, you must reselect validators to support manually. Depending on preferences, these can be the same validators as before or a new set. Remember that your previous nominations won’t be saved or automatically reactivated after chilling. -For an in-depth explanation about Asset Hub and its features, see the [Asset Hub](/chain-interactions/token-operations/convert-assets/){target=\_blank} entry in the Polkadot Wiki. +While chilled, your nominator account remains bonded, preserving your staked funds without requiring a full unbonding process. When you’re ready to start nominating again, you can issue a new nomination call to activate your bond with a fresh set of validators. This process bypasses the need for re-bonding, allowing you to maintain your stake while adjusting your involvement in active staking. -## Test Setup Environment +## Chilling as a Validator -You can set up a local parachain environment to test the asset registration process before deploying it on the live network. This guide uses Chopsticks to simulate that process. For further information on chopsticks usage, refer to the [Chopsticks](/develop/toolkit/parachains/fork-chains/chopsticks/get-started){target=\_blank} documentation. +When you chill as a validator, your active validator status is paused. Although your nominators remain bonded to you, the validator bond will no longer appear as an active choice for new or revised nominations until reactivated. Any existing nominators who take no action will still have their stake linked to the validator, meaning they don’t need to reselect the validator upon reactivation. However, if nominators adjust their stakes while the validator is chilled, they will not be able to nominate the chilled validator until it resumes activity. -To set up a test environment, execute the following command: +Upon reactivating as a validator, you must also reconfigure your validator preferences, such as commission rate and other parameters. These can be set to match your previous configuration or updated as desired. This step is essential for rejoining the active validator set and regaining eligibility for nominations. -```bash -npx @acala-network/chopsticks \ ---config=https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/polkadot-asset-hub.yml -``` +## Chill Other -The above command will spawn a lazy fork of Polkadot Asset Hub with the latest block data from the network. If you need to test Kusama Asset Hub, replace `polkadot-asset-hub.yml` with `kusama-asset-hub.yml` in the command. +Historical constraints in the runtime prevented unlimited nominators and validators from being supported. These constraints created a need for checks to keep the size of the staking system manageable. One of these checks is the `chillOther` extrinsic, allowing users to chill accounts that no longer met standards such as minimum staking requirements set through on-chain governance. -An Asset Hub instance is now running locally, and you can proceed with the asset registration process. Note that the local registration process does not differ from the live network process. Once you have a successful TestNet transaction, you can use the same steps to register the asset on MainNet. +This control mechanism included a `ChillThreshold`, which was structured to define how close to the maximum number of nominators or validators the staking system would be allowed to get before users could start chilling one another. With the passage of [Referendum #90](https://polkadot-old.polkassembly.io/referendum/90){target=\_blank}, the value for `maxNominatorCount` on Polkadot was set to `None`, effectively removing the limit on how many nominators and validators can participate. This means the `ChillThreshold` will never be met; thus, `chillOther` no longer has any effect. --- @@ -8126,495 +5766,103 @@ ProtectClock=true ProtectControlGroups=true ProtectHostname=true ProtectKernelModules=true -ProtectKernelTunables=true -ProtectSystem=strict -RemoveIPC=true -RestrictAddressFamilies=AF_INET AF_INET6 AF_NETLINK AF_UNIX -RestrictNamespaces=false -RestrictSUIDSGID=true -SystemCallArchitectures=native -SystemCallFilter=@system-service -SystemCallFilter=landlock_add_rule landlock_create_ruleset landlock_restrict_self seccomp mount umount2 -SystemCallFilter=~@clock @module @reboot @swap @privileged -SystemCallFilter=pivot_root -UMask=0027 - -[Install] -WantedBy=multi-user.target -``` - -!!! warning "Restart delay and equivocation risk" - It is recommended that a node's restart be delayed with `RestartSec` in the case of a crash. It's possible that when a node crashes, consensus votes in GRANDPA aren't persisted to disk. In this case, there is potential to equivocate when immediately restarting. Delaying the restart will allow the network to progress past potentially conflicting votes. - -### Run the Service - -Activate the systemd service to start on system boot by running: - -```bash -systemctl enable polkadot-validator.service -``` - -To start the service manually, use: - -```bash -systemctl start polkadot-validator.service -``` - -Check the service's status to confirm it is running: - -```bash -systemctl status polkadot-validator.service -``` - -To view the logs in real-time, use [journalctl](https://www.freedesktop.org/software/systemd/man/latest/journalctl.html){target=\_blank} like so: - -```bash -journalctl -f -u polkadot-validator -``` - -With these steps, you can effectively manage and monitor your validator as a systemd service. - -Once your validator is active, it's officially part of Polkadot's security infrastructure. For questions or further support, you can reach out to the [Polkadot Validator chat](https://matrix.to/#/!NZrbtteFeqYKCUGQtr:matrix.parity.io?via=matrix.parity.io&via=matrix.org&via=web3.foundation){target=\_blank} for tips and troubleshooting. - - ---- - -Page Title: Stop Validating - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-onboarding-and-offboarding-stop-validating.md -- Canonical (HTML): https://docs.polkadot.com/nodes-and-validators/run-a-validator/onboarding-and-offboarding/stop-validating/ -- Summary: Learn to safely stop validating on Polkadot, including chilling, unbonding tokens, and purging validator keys. - -# Stop Validating - -## Introduction - -If you're ready to stop validating on Polkadot, there are essential steps to ensure a smooth transition while protecting your funds and account integrity. Whether you're taking a break for maintenance or unbonding entirely, you'll need to chill your validator, purge session keys, and unbond your tokens. This guide explains how to use Polkadot's tools and extrinsics to safely withdraw from validation activities, safeguarding your account's future usability. - -## Pause Versus Stop - -If you wish to remain a validator or nominator (for example, stopping for planned downtime or server maintenance), submitting the `chill` extrinsic in the `staking` pallet should suffice. Additional steps are only needed to unbond funds or reap an account. - -The following are steps to ensure a smooth stop to validation: - -- Chill the validator. -- Purge validator session keys. -- Unbond your tokens. - -## Chill Validator - -When stepping back from validating, the first step is to chill your validator status. This action stops your validator from being considered for the next era without fully unbonding your tokens, which can be useful for temporary pauses like maintenance or planned downtime. - -Use the `staking.chill` extrinsic to initiate this. For more guidance on chilling your node, refer to the [Pause Validating](/nodes-and-validators/run-a-validator/operational-tasks/pause-validating/){target=\_blank} guide. You may also claim any pending staking rewards at this point. - -## Purge Validator Session Keys - -Purging validator session keys is a critical step in removing the association between your validator account and its session keys, which ensures that your account is fully disassociated from validator activities. The `session.purgeKeys` extrinsic removes the reference to your session keys from the stash or staking proxy account that originally set them. - -Here are a couple of important things to know about purging keys: - -- **Account used to purge keys**: Always use the same account to purge keys you originally used to set them, usually your stash or staking proxy account. Using a different account may leave an unremovable reference to the session keys on the original account, preventing its reaping. -- **Account reaping issue**: Failing to purge keys will prevent you from reaping (fully deleting) your stash account. If you attempt to transfer tokens without purging, you'll need to rebond, purge the session keys, unbond again, and wait through the unbonding period before any transfer. - -## Unbond Your Tokens - -After chilling your node and purging session keys, the final step is to unbond your staked tokens. This action removes them from staking and begins the unbonding period (usually 28 days for Polkadot and seven days for Kusama), after which the tokens will be transferable. - -To unbond tokens, go to **Network > Staking > Account Actions** on Polkadot.js Apps. Select your stash account, click on the dropdown menu, and choose **Unbond Funds**. Alternatively, you can use the `staking.unbond` extrinsic if you handle this via a staking proxy account. - -Once the unbonding period is complete, your tokens will be available for use in transactions or transfers outside of staking. - - ---- - -Page Title: Technical Reference Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference.md -- Canonical (HTML): https://docs.polkadot.com/reference/ -- Summary: Learn about Polkadot's technical architecture, governance framework, parachain ecosystem, and the tools you need to build and interact with the network. - -## Introduction - -The Technical Reference section provides comprehensive documentation of Polkadot's architecture, core concepts, and development tooling. Whether you're exploring how Polkadot's relay chain coordinates parachains, understanding governance mechanisms, or building applications on the network, this reference covers the technical foundations you need. - -Polkadot is a multi-chain network that enables diverse, interconnected blockchains to share security and communicate seamlessly. Understanding how these components interact from the [relay chain](/polkadot-protocol/glossary#relay-chain){target=\_blank} that validates [parachains](/polkadot-protocol/glossary#parachain){target=\_blank} to the [governance](/reference/glossary#governance){target=\_blank} mechanisms that evolve the protocol is essential for developers, validators, and network participants. - -This guide organizes technical documentation across five core areas: Polkadot Hub, Parachains, On-Chain Governance, Glossary, and Tools, each providing detailed information on different aspects of the Polkadot ecosystem. - -## Polkadot Hub - -[Polkadot Hub](/reference/polkadot-hub/){target=\_blank} is the entry point to Polkadot for all users and application developers. It provides access to essential Web3 services, including smart contracts, staking, governance, identity management, and cross-ecosystem interoperability—without requiring you to deploy or manage a parachain. - -The Hub encompasses a set of core functionality that enables developers and users to build and interact with applications on Polkadot. Key capabilities include: - -- **Smart contracts**: Deploy Ethereum-compatible smart contracts and build decentralized applications. -- **Assets and tokens**: Create, manage, and transfer fungible tokens and NFTs across the ecosystem. -- **Staking**: Participate in network security and earn rewards by staking DOT. -- **Governance**: Vote on proposals and participate in Polkadot's decentralized decision-making through OpenGov. -- **Identity services**: Register and manage on-chain identities, enabling access to governance roles and network opportunities. -- **Cross-chain interoperability**: Leverage XCM messaging to interact securely with other chains in the Polkadot ecosystem. -- **Collectives and DAOs**: Participate in governance collectives and decentralized autonomous organizations. - -## Parachains - -[Parachains](/reference/parachains/){target=\_blank} are specialized blockchains that connect to the Polkadot relay chain, inheriting its security while maintaining their own application-specific logic. The parachains documentation covers: - -- **Accounts**: Deep dive into account types, storage, and management on parachains. -- **Blocks, transactions and fees**: Understand block production, transaction inclusion, and fee mechanisms. -- **Consensus**: Learn how parachain blocks are validated and finalized through the relay chain's consensus. -- **Chain data**: Explore data structures, storage layouts, and state management. -- **Cryptography**: Study cryptographic primitives used in Polkadot SDK-based chains. -- **Data encoding**: Understand how data is encoded and decoded for blockchain compatibility. -- **Networks**: Learn about networking protocols and peer-to-peer communication. -- **Interoperability**: Discover [Cross-Consensus Messaging (XCM)](/parachains/interoperability/get-started/){target=\_blank}, the standard for cross-chain communication. -- **Randomness**: Understand how randomness is generated and used in Polkadot chains. -- **Node and runtime**: Learn about parachain nodes, runtime environments, and the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}. - -## On-Chain Governance - -[On-Chain governance](/reference/governance/){target=\_blank} is the decentralized decision-making mechanism for the Polkadot network. It manages the evolution and modification of the network's runtime logic, enabling community oversight and approval for proposed changes. The governance documentation details: - -- **OpenGov framework**: Understand Polkadot's next-generation governance system with enhanced delegation, flexible tracks, and simultaneous referendums. -- **Origins and tracks**: Learn how governance proposals are categorized, prioritized, and executed based on their privilege level and complexity. -- **Voting and delegation**: Explore conviction voting, vote delegation, and how token holders participate in governance. -- **Governance evolution**: See how Polkadot's governance has evolved from Governance V1 to the current OpenGov system. - -## Glossary - -The [Glossary](/reference/glossary/){target=\_blank} provides quick-reference definitions for Polkadot-specific terminology. Essential terms include: - -- Blockchain concepts (blocks, transactions, state) -- Consensus mechanisms (validators, collators, finality) -- Polkadot-specific terms (relay chain, parachain, XCM, FRAME) -- Network components (nodes, runtimes, storage) -- Governance terminology (origins, tracks, referendums) - -## Tools - -The [Tools](/reference/tools/){target=\_blank} section documents essential development and interaction tools for the Polkadot ecosystem: - -- **Light clients**: Lightweight solutions for interacting with the network without running full nodes. -- **JavaScript/TypeScript tools**: Libraries like [Polkadot.js API](/reference/tools/polkadot-js-api/){target=\_blank} and [PAPI](/reference/tools/papi/){target=\_blank} for building applications. -- **Rust tools**: [Polkadart](/reference/tools/polkadart/){target=\_blank} and other Rust-based libraries for SDK development. -- **Python tools**: [py-substrate-interface](/reference/tools/py-substrate-interface/){target=\_blank} for Python developers. -- **Testing and development**: Tools like [Moonwall](/reference/tools/moonwall/){target=\_blank}, [Chopsticks](/reference/tools/chopsticks/){target=\_blank}, and [Omninode](/reference/tools/omninode/){target=\_blank} for smart contract and parachain testing. -- **Indexing and monitoring**: [Sidecar](/reference/tools/sidecar/){target=\_blank} for data indexing and [Dedot](/reference/tools/dedot/){target=\_blank} for substrate interaction. -- **Cross-chain tools**: [ParaSpell](/reference/tools/paraspell/){target=\_blank} for XCM integration and asset transfers. - -## Where to Go Next - -For detailed exploration of specific areas, proceed to any of the main sections: - -
- -- Learn **Polkadot Hub** - - --- - - Understand the relay chain's role in coordinating parachains, providing shared security, and enabling governance. - - [:octicons-arrow-right-24: Reference](/reference/polkadot-hub/) - -- Learn **Parachains** - - --- - - Deep dive into parachain architecture, consensus, data structures, and building application-specific blockchains. - - [:octicons-arrow-right-24: Reference](/reference/parachains/) - -- Learn **On-Chain Governance** - - --- - - Explore Polkadot's decentralized governance framework and how to participate in network decision-making. - - [:octicons-arrow-right-24: Reference](/reference/governance/) - -- Guide **Glossary** - - --- - - Quick reference for Polkadot-specific terminology and concepts used throughout the documentation. - - [:octicons-arrow-right-24: Reference](/reference/glossary/) - -- Guide **Tools** - - --- - - Discover development tools, libraries, and frameworks for building and interacting with Polkadot. - - [:octicons-arrow-right-24: Reference](/reference/tools/) - -
- - ---- - -Page Title: Transactions - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-transactions.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/transactions/ -- Summary: Learn how to construct, submit, and validate transactions in the Polkadot SDK, covering signed, unsigned, and inherent types of transactions. - -# Transactions - -## Introduction - -Transactions are essential components of blockchain networks, enabling state changes and the execution of key operations. In the Polkadot SDK, transactions, often called extrinsics, come in multiple forms, including signed, unsigned, and inherent transactions. - -This guide walks you through the different transaction types and how they're formatted, validated, and processed within the Polkadot ecosystem. You'll also learn how to customize transaction formats and construct transactions for FRAME-based runtimes, ensuring a complete understanding of how transactions are built and executed in Polkadot SDK-based chains. - -## What Is a Transaction? - -In the Polkadot SDK, transactions represent operations that modify the chain's state, bundled into blocks for execution. The term extrinsic is often used to refer to any data that originates outside the runtime and is included in the chain. While other blockchain systems typically refer to these operations as "transactions," the Polkadot SDK adopts the broader term "extrinsic" to capture the wide variety of data types that can be added to a block. - -There are three primary types of transactions (extrinsics) in the Polkadot SDK: - -- **Signed transactions**: Signed by the submitting account, often carrying transaction fees. -- **Unsigned transactions**: Submitted without a signature, often requiring custom validation logic. -- **Inherent transactions**: Typically inserted directly into blocks by block authoring nodes, without gossiping between peers. - -Each type serves a distinct purpose, and understanding when and how to use each is key to efficiently working with the Polkadot SDK. - -### Signed Transactions - -Signed transactions require an account's signature and typically involve submitting a request to execute a runtime call. The signature serves as a form of cryptographic proof that the sender has authorized the action, using their private key. These transactions often involve a transaction fee to cover the cost of execution and incentivize block producers. - -Signed transactions are the most common type of transaction and are integral to user-driven actions, such as token transfers. For instance, when you transfer tokens from one account to another, the sending account must sign the transaction to authorize the operation. - -For example, the [`pallet_balances::Call::transfer_allow_death`](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/pallet/struct.Pallet.html#method.transfer_allow_death){target=\_blank} extrinsic in the Balances pallet allows you to transfer tokens. Since your account initiates this transaction, your account key is used to sign it. You'll also be responsible for paying the associated transaction fee, with the option to include an additional tip to incentivize faster inclusion in the block. - -### Unsigned Transactions - -Unsigned transactions do not require a signature or account-specific data from the sender. Unlike signed transactions, they do not come with any form of economic deterrent, such as fees, which makes them susceptible to spam or replay attacks. Custom validation logic must be implemented to mitigate these risks and ensure these transactions are secure. - -Unsigned transactions typically involve scenarios where including a fee or signature is unnecessary or counterproductive. However, due to the absence of fees, they require careful validation to protect the network. For example, [`pallet_im_online::Call::heartbeat`](https://paritytech.github.io/polkadot-sdk/master/pallet_im_online/pallet/struct.Pallet.html#method.heartbeat){target=\_blank} extrinsic allows validators to send a heartbeat signal, indicating they are active. Since only validators can make this call, the logic embedded in the transaction ensures that the sender is a validator, making the need for a signature or fee redundant. - -Unsigned transactions are more resource-intensive than signed ones because custom validation is required, but they play a crucial role in certain operational scenarios, especially when regular user accounts aren't involved. - -### Inherent Transactions - -Inherent transactions are a specialized type of unsigned transaction that is used primarily for block authoring. Unlike signed or other unsigned transactions, inherent transactions are added directly by block producers and are not broadcasted to the network or stored in the transaction queue. They don't require signatures or the usual validation steps and are generally used to insert system-critical data directly into blocks. - -A key example of an inherent transaction is inserting a timestamp into each block. The [`pallet_timestamp::Call::now`](https://paritytech.github.io/polkadot-sdk/master/pallet_timestamp/pallet/struct.Pallet.html#method.now-1){target=\_blank} extrinsic allows block authors to include the current time in the block they are producing. Since the block producer adds this information, there is no need for transaction validation, like signature verification. The validation in this case is done indirectly by the validators, who check whether the timestamp is within an acceptable range before finalizing the block. - -Another example is the [`paras_inherent::Call::enter`](https://paritytech.github.io/polkadot-sdk/master/polkadot_runtime_parachains/paras_inherent/pallet/struct.Pallet.html#method.enter){target=\_blank} extrinsic, which enables parachain collator nodes to send validation data to the relay chain. This inherent transaction ensures that the necessary parachain data is included in each block without the overhead of gossiped transactions. - -Inherent transactions serve a critical role in block authoring by allowing important operational data to be added directly to the chain without needing the validation processes required for standard transactions. - -## Transaction Formats - -Understanding the structure of signed and unsigned transactions is crucial for developers building on Polkadot SDK-based chains. Whether you're optimizing transaction processing, customizing formats, or interacting with the transaction pool, knowing the format of extrinsics, Polkadot's term for transactions, is essential. - -### Types of Transaction Formats - -In Polkadot SDK-based chains, extrinsics can fall into three main categories: - -- **Unchecked extrinsics**: Typically used for signed transactions that require validation. They contain a signature and additional data, such as a nonce and information for fee calculation. Unchecked extrinsics are named as such because they require validation checks before being accepted into the transaction pool. -- **Checked extrinsics**: Typically used for inherent extrinsics (unsigned transactions); these don't require signature verification. Instead, they carry information such as where the extrinsic originates and any additional data required for the block authoring process. -- **Opaque extrinsics**: Used when the format of an extrinsic is not yet fully committed or finalized. They are still decodable, but their structure can be flexible depending on the context. - -### Signed Transaction Data Structure - -A signed transaction typically includes the following components: - -- **Signature**: Verifies the authenticity of the transaction sender. -- **Call**: The actual function or method call the transaction is requesting (for example, transferring funds). -- **Nonce**: Tracks the number of prior transactions sent from the account, helping to prevent replay attacks. -- **Tip**: An optional incentive to prioritize the transaction in block inclusion. -- **Additional data**: Includes details such as spec version, block hash, and genesis hash to ensure the transaction is valid within the correct runtime and chain context. - -Here's a simplified breakdown of how signed transactions are typically constructed in a Polkadot SDK runtime: - -``` code - + + -``` - -Each part of the signed transaction has a purpose, ensuring the transaction's authenticity and context within the blockchain. - -### Signed Extensions - -Polkadot SDK also provides the concept of [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}, which allow developers to extend extrinsics with additional data or validation logic before they are included in a block. The [`SignedExtension`](https://paritytech.github.io/try-runtime-cli/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} set helps enforce custom rules or protections, such as ensuring the transaction's validity or calculating priority. - -The transaction queue regularly calls signed extensions to verify a transaction's validity before placing it in the ready queue. This safeguard ensures transactions won't fail in a block. Signed extensions are commonly used to enforce validation logic and protect the transaction pool from spam and replay attacks. - -In FRAME, a signed extension can hold any of the following types by default: - -- **[`AccountId`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/runtime/types_common/type.AccountId.html){target=\_blank}**: To encode the sender's identity. -- **[`Call`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Call){target=\_blank}**: To encode the pallet call to be dispatched. This data is used to calculate transaction fees. -- **[`AdditionalSigned`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.AdditionalSigned){target=\_blank}**: To handle any additional data to go into the signed payload allowing you to attach any custom logic prior to dispatching a transaction. -- **[`Pre`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Pre){target=\_blank}**: To encode the information that can be passed from before a call is dispatched to after it gets dispatched. - -Signed extensions can enforce checks like: - -- **[`CheckSpecVersion`](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/extensions/check_spec_version.rs.html){target=\_blank}**: Ensures the transaction is compatible with the runtime's current version. -- **[`CheckWeight`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.CheckWeight.html){target=\_blank}**: Calculates the weight (or computational cost) of the transaction, ensuring the block doesn't exceed the maximum allowed weight. - -These extensions are critical in the transaction lifecycle, ensuring that only valid and prioritized transactions are processed. - -## Transaction Construction - -Building transactions in the Polkadot SDK involves constructing a payload that can be verified, signed, and submitted for inclusion in a block. Each runtime in the Polkadot SDK has its own rules for validating and executing transactions, but there are common patterns for constructing a signed transaction. - -### Construct a Signed Transaction - -A signed transaction in the Polkadot SDK includes various pieces of data to ensure security, prevent replay attacks, and prioritize processing. Here's an overview of how to construct one: - -1. **Construct the unsigned payload**: Gather the necessary information for the call, including: - - - **Pallet index**: Identifies the pallet where the runtime function resides. - - **Function index**: Specifies the particular function to call in the pallet. - - **Parameters**: Any additional arguments required by the function call. - -2. **Create a signing payload**: Once the unsigned payload is ready, additional data must be included: - - - **Transaction nonce**: Unique identifier to prevent replay attacks. - - **Era information**: Defines how long the transaction is valid before it's dropped from the pool. - - **Block hash**: Ensures the transaction doesn't execute on the wrong chain or fork. - -3. **Sign the payload**: Using the sender's private key, sign the payload to ensure that the transaction can only be executed by the account holder. -4. **Serialize the signed payload**: Once signed, the transaction must be serialized into a binary format, ensuring the data is compact and easy to transmit over the network. -5. **Submit the serialized transaction**: Finally, submit the serialized transaction to the network, where it will enter the transaction pool and wait for processing by an authoring node. - -The following is an example of how a signed transaction might look: - -``` rust -node_runtime::UncheckedExtrinsic::new_signed( - function.clone(), // some call - sp_runtime::AccountId32::from(sender.public()).into(), // some sending account - node_runtime::Signature::Sr25519(signature.clone()), // the account's signature - extra.clone(), // the signed extensions -) -``` - -### Transaction Encoding - -Before a transaction is sent to the network, it is serialized and encoded using a structured encoding process that ensures consistency and prevents tampering: - -- **`[1]`**: Compact encoded length in bytes of the entire transaction. -- **`[2]`**: A u8 containing 1 byte to indicate whether the transaction is signed or unsigned (1 bit) and the encoded transaction version ID (7 bits). -- **`[3]`**: If signed, this field contains an account ID, an SR25519 signature, and some extra data. -- **`[4]`**: Encoded call data, including pallet and function indices and any required arguments. - -This encoded format ensures consistency and efficiency in processing transactions across the network. By adhering to this format, applications can construct valid transactions and pass them to the network for execution. - -To learn more about how compact encoding works using SCALE, see the [SCALE Codec](https://github.com/paritytech/parity-scale-codec){target=\_blank} README on GitHub. - -### Customize Transaction Construction - -Although the basic steps for constructing transactions are consistent across Polkadot SDK-based chains, developers can customize transaction formats and validation rules. For example: - -- **Custom pallets**: You can define new pallets with custom function calls, each with its own parameters and validation logic. -- **Signed extensions**: Developers can implement custom extensions that modify how transactions are prioritized, validated, or included in blocks. - -By leveraging Polkadot SDK's modular design, developers can create highly specialized transaction logic tailored to their chain's needs. - -## Lifecycle of a Transaction - -In the Polkadot SDK, transactions are often referred to as extrinsics because the data in transactions originates outside of the runtime. These transactions contain data that initiates changes to the chain state. The most common type of extrinsic is a signed transaction, which is cryptographically verified and typically incurs a fee. This section focuses on how signed transactions are processed, validated, and ultimately included in a block. - -### Define Transaction Properties - -The Polkadot SDK runtime defines key transaction properties, such as: - -- **Transaction validity**: Ensures the transaction meets all runtime requirements. -- **Signed or unsigned**: Identifies whether a transaction needs to be signed by an account. -- **State changes**: Determines how the transaction modifies the state of the chain. - -Pallets, which compose the runtime's logic, define the specific transactions that your chain supports. When a user submits a transaction, such as a token transfer, it becomes a signed transaction, verified by the user's account signature. If the account has enough funds to cover fees, the transaction is executed, and the chain's state is updated accordingly. - -### Process on a Block Authoring Node - -In Polkadot SDK-based networks, some nodes are authorized to author blocks. These nodes validate and process transactions. When a transaction is sent to a node that can produce blocks, it undergoes a lifecycle that involves several stages, including validation and execution. Non-authoring nodes gossip the transaction across the network until an authoring node receives it. The following diagram illustrates the lifecycle of a transaction that's submitted to a network and processed by an authoring node. - -![Transaction lifecycle diagram](/images/reference/parachains/blocks-transactions-fees/transactions/transactions-01.webp){ style="background:white" } - -### Validate and Queue +ProtectKernelTunables=true +ProtectSystem=strict +RemoveIPC=true +RestrictAddressFamilies=AF_INET AF_INET6 AF_NETLINK AF_UNIX +RestrictNamespaces=false +RestrictSUIDSGID=true +SystemCallArchitectures=native +SystemCallFilter=@system-service +SystemCallFilter=landlock_add_rule landlock_create_ruleset landlock_restrict_self seccomp mount umount2 +SystemCallFilter=~@clock @module @reboot @swap @privileged +SystemCallFilter=pivot_root +UMask=0027 -Once a transaction reaches an authoring node, it undergoes an initial validation process to ensure it meets specific conditions defined in the runtime. This validation includes checks for: +[Install] +WantedBy=multi-user.target +``` -- **Correct nonce**: Ensures the transaction is sequentially valid for the account. -- **Sufficient funds**: Confirms the account can cover any associated transaction fees. -- **Signature validity**: Verifies that the sender's signature matches the transaction data. +!!! warning "Restart delay and equivocation risk" + It is recommended that a node's restart be delayed with `RestartSec` in the case of a crash. It's possible that when a node crashes, consensus votes in GRANDPA aren't persisted to disk. In this case, there is potential to equivocate when immediately restarting. Delaying the restart will allow the network to progress past potentially conflicting votes. -After these checks, valid transactions are placed in the transaction pool, where they are queued for inclusion in a block. The transaction pool regularly re-validates queued transactions to ensure they remain valid before being processed. To reach consensus, two-thirds of the nodes must agree on the order of the transactions executed and the resulting state change. Transactions are validated and queued on the local node in a transaction pool to prepare for consensus. +### Run the Service -#### Transaction Pool +Activate the systemd service to start on system boot by running: -The transaction pool is responsible for managing valid transactions. It ensures that only transactions that pass initial validity checks are queued. Transactions that fail validation, expire, or become invalid for other reasons are removed from the pool. +```bash +systemctl enable polkadot-validator.service +``` -The transaction pool organizes transactions into two queues: +To start the service manually, use: -- **Ready queue**: Transactions that are valid and ready to be included in a block. -- **Future queue**: Transactions that are not yet valid but could be in the future, such as transactions with a nonce too high for the current state. +```bash +systemctl start polkadot-validator.service +``` -Details on how the transaction pool validates transactions, including fee and signature handling, can be found in the [`validate_transaction`](https://paritytech.github.io/polkadot-sdk/master/sp_transaction_pool/runtime_api/trait.TaggedTransactionQueue.html#method.validate_transaction){target=\_blank} method. +Check the service's status to confirm it is running: -#### Invalid Transactions +```bash +systemctl status polkadot-validator.service +``` -If a transaction is invalid, for example, due to an invalid signature or insufficient funds, it is rejected and won't be added to the block. Invalid transactions might be rejected for reasons such as: +To view the logs in real-time, use [journalctl](https://www.freedesktop.org/software/systemd/man/latest/journalctl.html){target=\_blank} like so: -- The transaction has already been included in a block. -- The transaction's signature does not match the sender. -- The transaction is too large to fit in the current block. +```bash +journalctl -f -u polkadot-validator +``` -### Transaction Ordering and Priority +With these steps, you can effectively manage and monitor your validator as a systemd service. -When a node is selected as the next block author, it prioritizes transactions based on weight, length, and tip amount. The goal is to fill the block with high-priority transactions without exceeding its maximum size or computational limits. Transactions are ordered as follows: +Once your validator is active, it's officially part of Polkadot's security infrastructure. For questions or further support, you can reach out to the [Polkadot Validator chat](https://matrix.to/#/!NZrbtteFeqYKCUGQtr:matrix.parity.io?via=matrix.parity.io&via=matrix.org&via=web3.foundation){target=\_blank} for tips and troubleshooting. -- **Inherents first**: Inherent transactions, such as block timestamp updates, are always placed first. -- **Nonce-based ordering**: Transactions from the same account are ordered by their nonce. -- **Fee-based ordering**: Among transactions with the same nonce or priority level, those with higher fees are prioritized. -### Transaction Execution +--- -Once a block author selects transactions from the pool, the transactions are executed in priority order. As each transaction is processed, the state changes are written directly to the chain's storage. It's important to note that these changes are not cached, meaning a failed transaction won't revert earlier state changes, which could leave the block in an inconsistent state. +Page Title: Stop Validating -Events are also written to storage. Runtime logic should not emit an event before performing the associated actions. If the associated transaction fails after the event was emitted, the event will not revert. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-onboarding-and-offboarding-stop-validating.md +- Canonical (HTML): https://docs.polkadot.com/nodes-and-validators/run-a-validator/onboarding-and-offboarding/stop-validating/ +- Summary: Learn to safely stop validating on Polkadot, including chilling, unbonding tokens, and purging validator keys. -## Transaction Mortality +# Stop Validating -Transactions in the network can be configured as either mortal (with expiration) or immortal (without expiration). Every transaction payload contains a block checkpoint (reference block number and hash) and an era/validity period that determines how many blocks after the checkpoint the transaction remains valid. +## Introduction -When a transaction is submitted, the network validates it against these parameters. If the transaction is not included in a block within the specified validity window, it is automatically removed from the transaction queue. +If you're ready to stop validating on Polkadot, there are essential steps to ensure a smooth transition while protecting your funds and account integrity. Whether you're taking a break for maintenance or unbonding entirely, you'll need to chill your validator, purge session keys, and unbond your tokens. This guide explains how to use Polkadot's tools and extrinsics to safely withdraw from validation activities, safeguarding your account's future usability. -- **Mortal transactions**: Have a finite lifespan and will expire after a specified number of blocks. For example, a transaction with a block checkpoint of 1000 and a validity period of 64 blocks will be valid from blocks 1000 to 1064. +## Pause Versus Stop -- **Immortal transactions**: Never expire and remain valid indefinitely. To create an immortal transaction, set the block checkpoint to 0 (genesis block), use the genesis hash as a reference, and set the validity period to 0. +If you wish to remain a validator or nominator (for example, stopping for planned downtime or server maintenance), submitting the `chill` extrinsic in the `staking` pallet should suffice. Additional steps are only needed to unbond funds or reap an account. -However, immortal transactions pose significant security risks through replay attacks. If an account is reaped (balance drops to zero, account removed) and later re-funded, malicious actors can replay old immortal transactions. +The following are steps to ensure a smooth stop to validation: -The blockchain maintains only a limited number of prior block hashes for reference validation, called `BlockHashCount`. If your validity period exceeds `BlockHashCount`, the effective validity period becomes the minimum of your specified period and the block hash count. +- Chill the validator. +- Purge validator session keys. +- Unbond your tokens. -## Unique Identifiers for Extrinsics +## Chill Validator -Transaction hashes are **not unique identifiers** in Polkadot SDK-based chains. +When stepping back from validating, the first step is to chill your validator status. This action stops your validator from being considered for the next era without fully unbonding your tokens, which can be useful for temporary pauses like maintenance or planned downtime. -Key differences from traditional blockchains: +Use the `staking.chill` extrinsic to initiate this. For more guidance on chilling your node, refer to the [Pause Validating](/nodes-and-validators/run-a-validator/operational-tasks/pause-validating/){target=\_blank} guide. You may also claim any pending staking rewards at this point. -- Transaction hashes serve only as fingerprints of transaction information. -- Multiple valid transactions can share the same hash. -- Hash uniqueness assumptions lead to serious issues. +## Purge Validator Session Keys -For example, when an account is reaped (removed due to insufficient balance) and later recreated, it resets to nonce 0, allowing identical transactions to be valid at different points: +Purging validator session keys is a critical step in removing the association between your validator account and its session keys, which ensures that your account is fully disassociated from validator activities. The `session.purgeKeys` extrinsic removes the reference to your session keys from the stash or staking proxy account that originally set them. -| Block | Extrinsic Index | Hash | Origin | Nonce | Call | Result | -|-------|----------------|------|-----------|-------|---------------------|-------------------------------| -| 100 | 0 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Account A reaped | -| 150 | 5 | 0x02 | Account B | 4 | Transfer 7 DOT to A | Account A created (nonce = 0) | -| 200 | 2 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Successful transaction | +Here are a couple of important things to know about purging keys: -Notice that blocks 100 and 200 contain transactions with identical hashes (0x01) but are completely different, valid operations occurring at different times. +- **Account used to purge keys**: Always use the same account to purge keys you originally used to set them, usually your stash or staking proxy account. Using a different account may leave an unremovable reference to the session keys on the original account, preventing its reaping. +- **Account reaping issue**: Failing to purge keys will prevent you from reaping (fully deleting) your stash account. If you attempt to transfer tokens without purging, you'll need to rebond, purge the session keys, unbond again, and wait through the unbonding period before any transfer. -Additional complexity comes from Polkadot SDK's origin abstraction. Origins can represent collectives, governance bodies, or other non-account entities that don't maintain nonces like regular accounts and might dispatch identical calls multiple times with the same hash values. Each execution occurs in different chain states with different results. +## Unbond Your Tokens -The correct way to uniquely identify an extrinsic on a Polkadot SDK-based chain is to use the block ID (height or hash) and the extrinsic index. Since the Polkadot SDK defines blocks as headers plus ordered arrays of extrinsics, the index position within a canonical block provides guaranteed uniqueness. +After chilling your node and purging session keys, the final step is to unbond your staked tokens. This action removes them from staking and begins the unbonding period (usually 28 days for Polkadot and seven days for Kusama), after which the tokens will be transferable. -## Additional Resources +To unbond tokens, go to **Network > Staking > Account Actions** on Polkadot.js Apps. Select your stash account, click on the dropdown menu, and choose **Unbond Funds**. Alternatively, you can use the `staking.unbond` extrinsic if you handle this via a staking proxy account. -For a video overview of the lifecycle of transactions and the types of transactions that exist, see the [Transaction lifecycle](https://www.youtube.com/watch?v=3pfM0GOp02c){target=\_blank} seminar from Parity Tech. +Once the unbonding period is complete, your tokens will be available for use in transactions or transfers outside of staking. --- @@ -8724,351 +5972,6 @@ The system maintains precise conversion mechanisms between: This ensures accurate fee calculation while maintaining compatibility with existing Ethereum tools and workflows. ---- - -Page Title: Transactions Weights and Fees - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-fees.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/fees/ -- Summary: Overview of transaction weights and fees in Polkadot SDK chains, detailing how fees are calculated using a defined formula and runtime specifics. - -# Transactions Weights and Fees - -## Introductions - -When transactions are executed, or data is stored on-chain, the activity changes the chain's state and consumes blockchain resources. Because the resources available to a blockchain are limited, managing how operations on-chain consume them is important. In addition to being limited in practical terms, such as storage capacity, blockchain resources represent a potential attack vector for malicious users. For example, a malicious user might attempt to overload the network with messages to stop the network from producing new blocks. To protect blockchain resources from being drained or overloaded, you need to manage how they are made available and how they are consumed. The resources to be aware of include: - -- Memory usage -- Storage input and output -- Computation -- Transaction and block size -- State database size - -The Polkadot SDK provides block authors with several ways to manage access to resources and to prevent individual components of the chain from consuming too much of any single resource. Two of the most important mechanisms available to block authors are weights and transaction fees. - -[Weights](/reference/glossary/#weight){target=\_blank} manage the time it takes to validate a block and characterize the time it takes to execute the calls in the block's body. By controlling the execution time a block can consume, weights set limits on storage input, output, and computation. - -Some of the weight allowed for a block is consumed as part of the block's initialization and finalization. The weight might also be used to execute mandatory inherent extrinsic calls. To help ensure blocks don’t consume too much execution time and prevent malicious users from overloading the system with unnecessary calls, weights are combined with transaction fees. - -[Transaction fees](/reference/parachains/blocks-transactions-fees/transactions/#transaction-fees){target=\_blank} provide an economic incentive to limit execution time, computation, and the number of calls required to perform operations. Transaction fees are also used to make the blockchain economically sustainable because they are typically applied to transactions initiated by users and deducted before a transaction request is executed. - -## How Fees are Calculated - -The final fee for a transaction is calculated using the following parameters: - -- **`base fee`**: This is the minimum amount a user pays for a transaction. It is declared a base weight in the runtime and converted to a fee using the [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} conversion. -- **`weight fee`**: A fee proportional to the execution time (input and output and computation) that a transaction consumes. -- **`length fee`**: A fee proportional to the encoded length of the transaction. -- **`tip`**: An optional tip to increase the transaction’s priority, giving it a higher chance to be included in the transaction queue. - -The base fee and proportional weight and length fees constitute the inclusion fee. The inclusion fee is the minimum fee that must be available for a transaction to be included in a block. - -```text -inclusion fee = base fee + weight fee + length fee -``` - -Transaction fees are withdrawn before the transaction is executed. After the transaction is executed, the weight can be adjusted to reflect the resources used. If a transaction uses fewer resources than expected, the transaction fee is corrected, and the adjusted transaction fee is deposited. - -## Using the Transaction Payment Pallet - -The [Transaction Payment pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/transaction-payment){target=\_blank} provides the basic logic for calculating the inclusion fee. You can also use the Transaction Payment pallet to: - -- Convert a weight value into a deductible fee based on a currency type using [`Config::WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank}. -- Update the fee for the next block by defining a multiplier based on the chain’s final state at the end of the previous block using [`Config::FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank}. -- Manage the withdrawal, refund, and deposit of transaction fees using [`Config::OnChargeTransaction`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.OnChargeTransaction){target=\_blank}. - -You can learn more about these configuration traits in the [Transaction Payment documentation](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_payment/index.html){target=\_blank}. - -### Understanding the Inclusion Fee - -The formula for calculating the inclusion fee is as follows: - -```text -inclusion_fee = base_fee + length_fee + [targeted_fee_adjustment * weight_fee] -``` - -And then, for calculating the final fee: - -```text -final_fee = inclusion_fee + tip -``` - -In the first formula, the `targeted_fee_adjustment` is a multiplier that can tune the final fee based on the network’s congestion. - -- The `base_fee` derived from the base weight covers inclusion overhead like signature verification. -- The `length_fee` is a per-byte fee that is multiplied by the length of the encoded extrinsic. -- The `weight_fee` fee is calculated using two parameters: - - The `ExtrinsicBaseWeight` that is declared in the runtime and applies to all extrinsics. - - The `#[pallet::weight]` annotation that accounts for an extrinsic's complexity. - -To convert the weight to `Currency`, the runtime must define a `WeightToFee` struct that implements a conversion function, [`Convert`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/struct.Pallet.html#method.weight_to_fee){target=\_blank}. - -Note that the extrinsic sender is charged the inclusion fee before the extrinsic is invoked. The fee is deducted from the sender's balance even if the transaction fails upon execution. - -### Accounts with an Insufficient Balance - -If an account does not have a sufficient balance to pay the inclusion fee and remain alive—that is, enough to pay the inclusion fee and maintain the minimum existential deposit—then you should ensure the transaction is canceled so that no fee is deducted and the transaction does not begin execution. - -The Polkadot SDK doesn't enforce this rollback behavior. However, this scenario would be rare because the transaction queue and block-making logic perform checks to prevent it before adding an extrinsic to a block. - -### Fee Multipliers - -The inclusion fee formula always results in the same fee for the same input. However, weight can be dynamic and—based on how [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} is defined—the final fee can include some degree of variability. -The Transaction Payment pallet provides the [`FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank} configurable parameter to account for this variability. - -The Polkadot network inspires the default update function and implements a targeted adjustment in which a target saturation level of block weight is defined. If the previous block is more saturated, the fees increase slightly. Similarly, if the last block has fewer transactions than the target, fees are decreased by a small amount. For more information about fee multiplier adjustments, see the [Web3 Research Page](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank}. - -## Transactions with Special Requirements - -Inclusion fees must be computable before execution and can only represent fixed logic. Some transactions warrant limiting resources with other strategies. For example: - -- Bonds are a type of fee that might be returned or slashed after some on-chain event. For example, you might want to require users to place a bond to participate in a vote. The bond might then be returned at the end of the referendum or slashed if the voter attempted malicious behavior. -- Deposits are fees that might be returned later. For example, you might require users to pay a deposit to execute an operation that uses storage. The user’s deposit could be returned if a subsequent operation frees up storage. -- Burn operations are used to pay for a transaction based on its internal logic. For example, a transaction might burn funds from the sender if the transaction creates new storage items to pay for the increased state size. -- Limits enable you to enforce constant or configurable limits on specific operations. For example, the default [Staking pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/staking){target=\_blank} only allows nominators to nominate 16 validators to limit the complexity of the validator election process. - -It is important to note that if you query the chain for a transaction fee, it only returns the inclusion fee. - -## Default Weight Annotations - -All dispatchable functions in the Polkadot SDK must specify a weight. The way of doing that is using the annotation-based system that lets you combine fixed values for database read/write weight and/or fixed values based on benchmarks. The most basic example would look like this: - -```rust -#[pallet::weight(100_000)] -fn my_dispatchable() { - // ... -} -``` - -Note that the [`ExtrinsicBaseWeight`](https://crates.parity.io/frame_support/weights/constants/struct.ExtrinsicBaseWeight.html){target=\_blank} is automatically added to the declared weight to account for the costs of simply including an empty extrinsic into a block. - -### Weights and Database Read/Write Operations - -To make weight annotations independent of the deployed database backend, they are defined as a constant and then used in the annotations when expressing database accesses performed by the dispatchable: - -```rust -#[pallet::weight(T::DbWeight::get().reads_writes(1, 2) + 20_000)] -fn my_dispatchable() { - // ... -} -``` - -This dispatchable allows one database to read and two to write, in addition to other things that add the additional 20,000. Database access is generally every time a value declared inside the [`#[pallet::storage]`](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/attr.storage.html){target=\_blank} block is accessed. However, unique accesses are counted because after a value is accessed, it is cached, and reaccessing it does not result in a database operation. That is: - -- Multiple reads of the exact value count as one read. -- Multiple writes of the exact value count as one write. -- Multiple reads of the same value, followed by a write to that value, count as one read and one write. -- A write followed by a read-only counts as one write. - -### Dispatch Classes - -Dispatches are broken into three classes: - -- Normal -- Operational -- Mandatory - -If a dispatch is not defined as `Operational` or `Mandatory` in the weight annotation, the dispatch is identified as `Normal` by default. You can specify that the dispatchable uses another class like this: - -```rust -#[pallet::dispatch((DispatchClass::Operational))] -fn my_dispatchable() { - // ... -} -``` - -This tuple notation also allows you to specify a final argument determining whether the user is charged based on the annotated weight. If you don't specify otherwise, `Pays::Yes` is assumed: - -```rust -#[pallet::dispatch(DispatchClass::Normal, Pays::No)] -fn my_dispatchable() { - // ... -} -``` - -#### Normal Dispatches - -Dispatches in this class represent normal user-triggered transactions. These types of dispatches only consume a portion of a block's total weight limit. For information about the maximum portion of a block that can be consumed for normal dispatches, see [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Normal dispatches are sent to the transaction pool. - -#### Operational Dispatches - -Unlike normal dispatches, which represent the usage of network capabilities, operational dispatches are those that provide network capabilities. Operational dispatches can consume the entire weight limit of a block. They are not bound by the [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Dispatches in this class are given maximum priority and are exempt from paying the [`length_fee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/){target=\_blank}. - -#### Mandatory Dispatches - -Mandatory dispatches are included in a block even if they cause the block to surpass its weight limit. You can only use the mandatory dispatch class for inherent transactions that the block author submits. This dispatch class is intended to represent functions in the block validation process. Because these dispatches are always included in a block regardless of the function weight, the validation process must prevent malicious nodes from abusing the function to craft valid but impossibly heavy blocks. You can typically accomplish this by ensuring that: - -- The operation performed is always light. -- The operation can only be included in a block once. - -To make it more difficult for malicious nodes to abuse mandatory dispatches, they cannot be included in blocks that return errors. This dispatch class serves the assumption that it is better to allow an overweight block to be created than not to allow any block to be created at all. - -### Dynamic Weights - -In addition to purely fixed weights and constants, the weight calculation can consider the input arguments of a dispatchable. The weight should be trivially computable from the input arguments with some basic arithmetic: - -```rust -use frame_support:: { - dispatch:: { - DispatchClass::Normal, - Pays::Yes, - }, - weights::Weight, -}; - -#[pallet::weight(FunctionOf( - |args: (&Vec,)| args.0.len().saturating_mul(10_000), - ) -] -fn handle_users(origin, calls: Vec) { - // Do something per user -} -``` - -## Post Dispatch Weight Correction - -Depending on the execution logic, a dispatchable function might consume less weight than was prescribed pre-dispatch. To correct weight, the function declares a different return type and returns its actual weight: - -```rust -#[pallet::weight(10_000 + 500_000_000)] -fn expensive_or_cheap(input: u64) -> DispatchResultWithPostInfo { - let was_heavy = do_calculation(input); - - if (was_heavy) { - // None means "no correction" from the weight annotation. - Ok(None.into()) - } else { - // Return the actual weight consumed. - Ok(Some(10_000).into()) - } -} -``` - -## Custom Fees - -You can also define custom fee systems through custom weight functions or inclusion fee functions. - -### Custom Weights - -Instead of using the default weight annotations, you can create a custom weight calculation type using the weights module. The custom weight calculation type must implement the following traits: - -- [`WeighData`](https://crates.parity.io/frame_support/weights/trait.WeighData.html){target=\_blank} to determine the weight of the dispatch. -- [`ClassifyDispatch`](https://crates.parity.io/frame_support/weights/trait.ClassifyDispatch.html){target=\_blank} to determine the class of the dispatch. -- [`PaysFee`](https://crates.parity.io/frame_support/weights/trait.PaysFee.html){target=\_blank} to determine whether the sender of the dispatch pays fees. - -The Polkadot SDK then bundles the output information of the three traits into the [`DispatchInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_support/dispatch/struct.DispatchInfo.html){target=\_blank} struct and provides it by implementing the [`GetDispatchInfo`](https://docs.rs/frame-support/latest/frame_support/dispatch/trait.GetDispatchInfo.html){target=\_blank} for all `Call` variants and opaque extrinsic types. This is used internally by the System and Executive modules. - -`ClassifyDispatch`, `WeighData`, and `PaysFee` are generic over T, which gets resolved into the tuple of all dispatch arguments except for the origin. The following example illustrates a struct that calculates the weight as `m * len(args)`, where `m` is a given multiplier and args is the concatenated tuple of all dispatch arguments. In this example, the dispatch class is `Operational` if the transaction has more than 100 bytes of length in arguments and will pay fees if the encoded length exceeds 10 bytes. - -```rust -struct LenWeight(u32); -impl WeighData for LenWeight { - fn weigh_data(&self, target: T) -> Weight { - let multiplier = self.0; - let encoded_len = target.encode().len() as u32; - multiplier * encoded_len - } -} - -impl ClassifyDispatch for LenWeight { - fn classify_dispatch(&self, target: T) -> DispatchClass { - let encoded_len = target.encode().len() as u32; - if encoded_len > 100 { - DispatchClass::Operational - } else { - DispatchClass::Normal - } - } -} - -impl PaysFee { - fn pays_fee(&self, target: T) -> Pays { - let encoded_len = target.encode().len() as u32; - if encoded_len > 10 { - Pays::Yes - } else { - Pays::No - } - } -} -``` - -A weight calculator function can also be coerced to the final type of the argument instead of defining it as a vague type that can be encoded. The code would roughly look like this: - -```rust -struct CustomWeight; -impl WeighData<(&u32, &u64)> for CustomWeight { - fn weigh_data(&self, target: (&u32, &u64)) -> Weight { - ... - } -} - -// given a dispatch: -#[pallet::call] -impl, I: 'static> Pallet { - #[pallet::weight(CustomWeight)] - fn foo(a: u32, b: u64) { ... } -} -``` - -In this example, the `CustomWeight` can only be used in conjunction with a dispatch with a particular signature `(u32, u64)`, as opposed to `LenWeight`, which can be used with anything because there aren't any assumptions about ``. - -#### Custom Inclusion Fee - -The following example illustrates how to customize your inclusion fee. You must configure the appropriate associated types in the respective module. - -```rust -// Assume this is the balance type -type Balance = u64; - -// Assume we want all the weights to have a `100 + 2 * w` conversion to fees -struct CustomWeightToFee; -impl WeightToFee for CustomWeightToFee { - fn convert(w: Weight) -> Balance { - let a = Balance::from(100); - let b = Balance::from(2); - let w = Balance::from(w); - a + b * w - } -} - -parameter_types! { - pub const ExtrinsicBaseWeight: Weight = 10_000_000; -} - -impl frame_system::Config for Runtime { - type ExtrinsicBaseWeight = ExtrinsicBaseWeight; -} - -parameter_types! { - pub const TransactionByteFee: Balance = 10; -} - -impl transaction_payment::Config { - type TransactionByteFee = TransactionByteFee; - type WeightToFee = CustomWeightToFee; - type FeeMultiplierUpdate = TargetedFeeAdjustment; -} - -struct TargetedFeeAdjustment(sp_std::marker::PhantomData); -impl> WeightToFee for TargetedFeeAdjustment { - fn convert(multiplier: Fixed128) -> Fixed128 { - // Don't change anything. Put any fee update info here. - multiplier - } -} -``` - -## Additional Resources - -You now know the weight system, how it affects transaction fee computation, and how to specify weights for your dispatchable calls. The next step is determining the correct weight for your dispatchable operations. You can use Substrate benchmarking functions and frame-benchmarking calls to test your functions with different parameters and empirically determine the proper weight in their worst-case scenarios. - -- [Benchmark](/parachains/customize-runtime/pallet-development/benchmark-pallet/) -- [`SignedExtension`](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} -- [Custom weights for the Example pallet](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/substrate/frame/examples/basic/src/weights.rs){target=\_blank} -- [Web3 Foundation Research](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank} - - --- Page Title: Upgrade a Validator Node @@ -9391,91 +6294,3 @@ For example, on November 19, 2024, the minimum stake backing a validator in Polk - [**Chain State Values**](https://wiki.polkadot.com/general/chain-state-values/){target=\_blank} - [**Subscan**](https://polkadot.subscan.io/validator_list?status=validator){target=\_blank} - [**Staking Dashboard**](https://staking.polkadot.cloud/#/overview){target=\_blank} - - ---- - -Page Title: XCM Tools - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-xcm-tools.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/xcm-tools/ -- Summary: Explore essential XCM tools across Polkadot, crafted to enhance cross-chain functionality and integration within the ecosystem. - -# XCM Tools - -## Introduction - -As described in the [Interoperability](/develop/interoperability){target=\_blank} section, XCM (Cross-Consensus Messaging) is a protocol used in the Polkadot and Kusama ecosystems to enable communication and interaction between chains. It facilitates cross-chain communication, allowing assets, data, and messages to flow seamlessly across the ecosystem. - -As XCM is central to enabling communication between blockchains, developers need robust tools to help interact with, build, and test XCM messages. Several XCM tools simplify working with the protocol by providing libraries, frameworks, and utilities that enhance the development process, ensuring that applications built within the Polkadot ecosystem can efficiently use cross-chain functionalities. - -## Popular XCM Tools - -### Moonsong Labs XCM Tools - -[Moonsong Labs XCM Tools](https://github.com/Moonsong-Labs/xcm-tools){target=\_blank} provides a collection of scripts for managing and testing XCM operations between Polkadot SDK-based runtimes. These tools allow performing tasks like asset registration, channel setup, and XCM initialization. Key features include: - -- **Asset registration**: Registers assets, setting units per second (up-front fees), and configuring error (revert) codes. -- **XCM initializer**: Initializes XCM, sets default XCM versions, and configures revert codes for XCM-related precompiles. -- **HRMP manipulator**: Manages HRMP channel actions, including opening, accepting, or closing channels. -- **XCM-Transactor-Info-Setter**: Configures transactor information, including extra weight and fee settings. -- **Decode XCM**: Decodes XCM messages on the relay chain or parachains to help interpret cross-chain communication. - -To get started, clone the repository and install the required dependencies: - -```bash -git clone https://github.com/Moonsong-Labs/xcm-tools && -cd xcm-tools && -yarn install -``` - -For a full overview of each script, visit the [scripts](https://github.com/Moonsong-Labs/xcm-tools/tree/main/scripts){target=\_blank} directory or refer to the [official documentation](https://github.com/Moonsong-Labs/xcm-tools/blob/main/README.md){target=\_blank} on GitHub. - -### ParaSpell - -[ParaSpell](/reference/tools/paraspell/){target=\_blank} is a collection of open-source XCM tools that streamline cross-chain asset transfers and interactions across the Polkadot and Kusama ecosystems. It provides developers with an intuitive interface to build, test, and deploy interoperable dApps, featuring message composition, decoding, and practical utilities for parachain interactions that simplify debugging and cross-chain communication optimization. - -### Astar XCM Tools - -The [Astar parachain](https://github.com/AstarNetwork/Astar/tree/master){target=\_blank} offers a crate with a set of utilities for interacting with the XCM protocol. The [xcm-tools](https://github.com/AstarNetwork/Astar/tree/master/bin/xcm-tools){target=\_blank} crate provides a straightforward method for users to locate a sovereign account or calculate an XC20 asset ID. Some commands included by the xcm-tools crate allow users to perform the following tasks: - -- **Sovereign accounts**: Obtain the sovereign account address for any parachain, either on the Relay Chain or for sibling parachains, using a simple command. -- **XC20 EVM addresses**: Generate XC20-compatible Ethereum addresses for assets by entering the asset ID, making it easy to integrate assets across Ethereum-compatible environments. -- **Remote accounts**: Retrieve remote account addresses needed for multi-location compatibility, using flexible options to specify account types and parachain IDs. - -To start using these tools, clone the [Astar repository](https://github.com/AstarNetwork/Astar){target=\_blank} and compile the xcm-tools package: - -```bash -git clone https://github.com/AstarNetwork/Astar && -cd Astar && -cargo build --release -p xcm-tools -``` - -After compiling, verify the setup with the following command: - -```bash -./target/release/xcm-tools --help -``` -For more details on using Astar xcm-tools, consult the [official documentation](https://docs.astar.network/docs/learn/interoperability/xcm/integration/tools/){target=\_blank}. - -### Chopsticks - -The Chopsticks library provides XCM functionality for testing XCM messages across networks, enabling you to fork multiple parachains along with a relay chain. For further details, see the [Chopsticks documentation](/tutorials/polkadot-sdk/testing/fork-live-chains/){target=\_blank} about XCM. - -### Moonbeam XCM SDK - -The [Moonbeam XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk){target=\_blank} enables developers to easily transfer assets between chains, either between parachains or between a parachain and the relay chain, within the Polkadot/Kusama ecosystem. With the SDK, you don't need to worry about determining the [Multilocation](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#7-universal-consensus-location-identifiers){target=\_blank} of the origin or destination assets or which extrinsics are used on which networks. - -The SDK consists of two main packages: - -- **[XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/sdk){target=\_blank}**: Core SDK for executing XCM transfers between chains in the Polkadot/Kusama ecosystem. -- **[MRL SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/mrl){target=\_blank}**: Extension of the XCM SDK for transferring liquidity into and across the Polkadot ecosystem from other ecosystems like Ethereum. - -Key features include: - -- **Simplified asset transfers**: Abstracts away complex multilocation determinations and extrinsic selection. -- **Cross-ecosystem support**: Enables transfers between Polkadot/Kusama chains and external ecosystems. -- **Developer-friendly API**: Provides intuitive interfaces for cross-chain functionality. -- **Comprehensive documentation**: Includes usage guides and API references for both packages. - -For detailed usage examples and API documentation, visit the [official Moonbeam XCM SDK documentation](https://moonbeam-foundation.github.io/xcm-sdk/latest/){target=\_blank}. diff --git a/.ai/categories/networks.md b/.ai/categories/networks.md index 095a99153..32021e250 100644 --- a/.ai/categories/networks.md +++ b/.ai/categories/networks.md @@ -474,440 +474,6 @@ Launch your parachain locally and start producing blocks: ---- - -Page Title: Blocks - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-blocks.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/blocks/ -- Summary: Understand how blocks are produced, validated, and imported in Polkadot SDK-based blockchains, covering initialization, finalization, and authoring processes. - -# Blocks - -## Introduction - -In the Polkadot SDK, blocks are fundamental to the functioning of the blockchain, serving as containers for [transactions](/reference/parachains/blocks-transactions-fees/transactions/){target=\_blank} and changes to the chain's state. Blocks consist of headers and an array of transactions, ensuring the integrity and validity of operations on the network. This guide explores the essential components of a block, the process of block production, and how blocks are validated and imported across the network. By understanding these concepts, developers can better grasp how blockchains maintain security, consistency, and performance within the Polkadot ecosystem. - -## What is a Block? - -In the Polkadot SDK, a block is a fundamental unit that encapsulates both the header and an array of transactions. The block header includes critical metadata to ensure the integrity and sequence of the blockchain. Here's a breakdown of its components: - -- **Block height**: Indicates the number of blocks created in the chain so far. -- **Parent hash**: The hash of the previous block, providing a link to maintain the blockchain's immutability. -- **Transaction root**: Cryptographic digest summarizing all transactions in the block. -- **State root**: A cryptographic digest representing the post-execution state. -- **Digest**: Additional information that can be attached to a block, such as consensus-related messages. - -Each transaction is part of a series that is executed according to the runtime's rules. The transaction root is a cryptographic digest of this series, which prevents alterations and enables succinct verification by light clients. This verification process allows light clients to confirm whether a transaction exists in a block with only the block header, avoiding downloading the entire block. - -## Block Production - -When an authoring node is authorized to create a new block, it selects transactions from the transaction queue based on priority. This step, known as block production, relies heavily on the executive module to manage the initialization and finalization of blocks. The process is summarized as follows: - -### Initialize Block - -The block initialization process begins with a series of function calls that prepare the block for transaction execution: - -1. **Call `on_initialize`**: The executive module calls the [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} hook from the system pallet and other runtime pallets to prepare for the block's transactions. -2. **Coordinate runtime calls**: Coordinates function calls in the order defined by the transaction queue. -3. **Verify information**: Once [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} functions are executed, the executive module checks the parent hash in the block header and the trie root to verify information is consistent. - -### Finalize Block - -Once transactions are processed, the block must be finalized before being broadcast to the network. The finalization steps are as follows: - -1. **Call `on_finalize`**: The executive module calls the [`on_finalize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_finalize){target=\_blank} hooks in each pallet to ensure any remaining state updates or checks are completed before the block is sealed and published. -2. **Verify information**: The block's digest and storage root in the header are checked against the initialized block to ensure consistency. -3. **Call `on_idle`**: The [`on_idle`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_idle){target=\_blank} hook is triggered to process any remaining tasks using the leftover weight from the block. - -## Block Authoring and Import - -Once the block is finalized, it is gossiped to other nodes in the network. Nodes follow this procedure: - -1. **Receive transactions**: The authoring node collects transactions from the network. -2. **Validate**: Transactions are checked for validity. -3. **Queue**: Valid transactions are placed in the transaction pool for execution. -4. **Execute**: State changes are made as the transactions are executed. -5. **Publish**: The finalized block is broadcast to the network. - -### Block Import Queue - -After a block is published, other nodes on the network can import it into their chain state. The block import queue is part of the outer node in every Polkadot SDK-based node and ensures incoming blocks are valid before adding them to the node's state. - -In most cases, you don't need to know details about how transactions are gossiped or how other nodes on the network import blocks. The following traits are relevant, however, if you plan to write any custom consensus logic or want a deeper dive into the block import queue: - -- **[`ImportQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.ImportQueue.html){target=\_blank}**: The trait that defines the block import queue. -- **[`Link`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Link.html){target=\_blank}**: The trait that defines the link between the block import queue and the network. -- **[`BasicQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/struct.BasicQueue.html){target=\_blank}**: A basic implementation of the block import queue. -- **[`Verifier`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Verifier.html){target=\_blank}**: The trait that defines the block verifier. -- **[`BlockImport`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/block_import/trait.BlockImport.html){target=\_blank}**: The trait that defines the block import process. - -These traits govern how blocks are validated and imported across the network, ensuring consistency and security. - -## Additional Resources - -To learn more about the block structure in the Polkadot SDK runtime, see the [`Block` reference](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.Block.html){target=\_blank} entry in the Rust Docs. - - ---- - -Page Title: Chain Data - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-chain-data.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/chain-data/ -- Summary: Learn how to expose and utilize chain data for blockchain applications. Discover runtime metadata, RPC APIs, and tools for efficient development. - -# Chain Data - -## Introduction - -Understanding and leveraging on-chain data is a fundamental aspect of blockchain development. Whether you're building frontend applications or backend systems, accessing and decoding runtime metadata is vital to interacting with the blockchain. This guide introduces you to the tools and processes for generating and retrieving metadata, explains its role in application development, and outlines the additional APIs available for interacting with a Polkadot node. By mastering these components, you can ensure seamless communication between your applications and the blockchain. - -## Application Development - -You might not be directly involved in building frontend applications as a blockchain developer. However, most applications that run on a blockchain require some form of frontend or user-facing client to enable users or other programs to access and modify the data that the blockchain stores. For example, you might develop a browser-based, mobile, or desktop application that allows users to submit transactions, post articles, view their assets, or track previous activity. The backend for that application is configured in the runtime logic for your blockchain, but the frontend client makes the runtime features accessible to your users. - -For your custom chain to be useful to others, you'll need to provide a client application that allows users to view, interact with, or update information that the blockchain keeps track of. In this article, you'll learn how to expose information about your runtime so that client applications can use it, see examples of the information exposed, and explore tools and libraries that use it. - -## Understand Metadata - -Polkadot SDK-based blockchain networks are designed to expose their runtime information, allowing developers to learn granular details regarding pallets, RPC calls, and runtime APIs. The metadata also exposes their related documentation. The chain's metadata is [SCALE-encoded](/reference/parachains/data-encoding/){target=\_blank}, allowing for the development of browser-based, mobile, or desktop applications to support the chain's runtime upgrades seamlessly. It is also possible to develop applications compatible with multiple Polkadot SDK-based chains simultaneously. - -## Expose Runtime Information as Metadata - -To interact with a node or the state of the blockchain, you need to know how to connect to the chain and access the exposed runtime features. This interaction involves a Remote Procedure Call (RPC) through a node endpoint address, commonly through a secure web socket connection. - -An application developer typically needs to know the contents of the runtime logic, including the following details: - -- Version of the runtime the application is connecting to. -- Supported APIs. -- Implemented pallets. -- Defined functions and corresponding type signatures. -- Defined custom types. -- Exposed parameters users can set. - -As the Polkadot SDK is modular and provides a composable framework for building blockchains, there are limitless opportunities to customize the schema of properties. Each runtime can be configured with its properties, including function calls and types, which can be changed over time with runtime upgrades. - -The Polkadot SDK enables you to generate the runtime metadata schema to capture information unique to a runtime. The metadata for a runtime describes the pallets in use and types defined for a specific runtime version. The metadata includes information about each pallet's storage items, functions, events, errors, and constants. The metadata also provides type definitions for any custom types included in the runtime. - -Metadata provides a complete inventory of a chain's runtime. It is key to enabling client applications to interact with the node, parse responses, and correctly format message payloads sent back to that chain. - -## Generate Metadata - -To efficiently use the blockchain's networking resources and minimize the data transmitted over the network, the metadata schema is encoded using the [Parity SCALE Codec](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank}. This encoding is done automatically through the [`scale-info`](https://docs.rs/scale-info/latest/scale_info/){target=\_blank}crate. - -At a high level, generating the metadata involves the following steps: - -1. The pallets in the runtime logic expose callable functions, types, parameters, and documentation that need to be encoded in the metadata. -2. The `scale-info` crate collects type information for the pallets in the runtime, builds a registry of the pallets that exist in a particular runtime, and the relevant types for each pallet in the registry. The type information is detailed enough to enable encoding and decoding for every type. -3. The [`frame-metadata`](https://github.com/paritytech/frame-metadata){target=\_blank} crate describes the structure of the runtime based on the registry provided by the `scale-info` crate. -4. Nodes provide the RPC method `state_getMetadata` to return a complete description of all the types in the current runtime as a hex-encoded vector of SCALE-encoded bytes. - -## Retrieve Runtime Metadata - -The type information provided by the metadata enables applications to communicate with nodes using different runtime versions and across chains that expose different calls, events, types, and storage items. The metadata also allows libraries to generate a substantial portion of the code needed to communicate with a given node, enabling libraries like [`subxt`](https://github.com/paritytech/subxt){target=\_blank} to generate frontend interfaces that are specific to a target chain. - -### Use Polkadot.js - -Visit the [Polkadot.js Portal](https://polkadot.js.org/apps/#/rpc){target=\_blank} and select the **Developer** dropdown in the top banner. Select **RPC Calls** to make the call to request metadata. Follow these steps to make the RPC call: - -1. Select **state** as the endpoint to call. -2. Select **`getMetadata(at)`** as the method to call. -3. Click **Submit RPC call** to submit the call and return the metadata in JSON format. - -### Use Curl - -You can fetch the metadata for the network by calling the node's RPC endpoint. This request returns the metadata in bytes rather than human-readable JSON: - -```sh -curl -H "Content-Type: application/json" \ --d '{"id":1, "jsonrpc":"2.0", "method": "state_getMetadata"}' \ -https://rpc.polkadot.io - -``` - -### Use Subxt - -[`subxt`](https://github.com/paritytech/subxt){target=\_blank} may also be used to fetch the metadata of any data in a human-readable JSON format: - -```sh -subxt metadata --url wss://rpc.polkadot.io --format json > spec.json -``` - -Another option is to use the [`subxt` explorer web UI](https://paritytech.github.io/subxt-explorer/#/){target=\_blank}. - -## Client Applications and Metadata - -The metadata exposes the expected way to decode each type, meaning applications can send, retrieve, and process application information without manual encoding and decoding. Client applications must use the [SCALE codec library](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank} to encode and decode RPC payloads to use the metadata. Client applications use the metadata to interact with the node, parse responses, and format message payloads sent to the node. - -## Metadata Format - -Although the SCALE-encoded bytes can be decoded using the `frame-metadata` and [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} libraries, there are other tools, such as `subxt` and the Polkadot-JS API, that can convert the raw data to human-readable JSON format. - -The types and type definitions included in the metadata returned by the `state_getMetadata` RPC call depend on the runtime's metadata version. - -In general, the metadata includes the following information: - -- A constant identifying the file as containing metadata. -- The version of the metadata format used in the runtime. -- Type definitions for all types used in the runtime and generated by the `scale-info` crate. -- Pallet information for the pallets included in the runtime in the order that they are defined in the `construct_runtime` macro. - -!!!tip - Depending on the frontend library used (such as the [Polkadot API](https://papi.how/){target=\_blank}), they may format the metadata differently than the raw format shown. - -The following example illustrates a condensed and annotated section of metadata decoded and converted to JSON: - -```json -[ - 1635018093, - { - "V14": { - "types": { - "types": [{}] - }, - "pallets": [{}], - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [{}] - }, - "ty": 141 - } - } -] - -``` - -The constant `1635018093` is a magic number that identifies the file as a metadata file. The rest of the metadata is divided into the `types`, `pallets`, and `extrinsic` sections: - -- The `types` section contains an index of the types and information about each type's type signature. -- The `pallets` section contains information about each pallet in the runtime. -- The `extrinsic` section describes the type identifier and transaction format version that the runtime uses. - -Different extrinsic versions can have varying formats, especially when considering [signed transactions](/reference/parachains/blocks-transactions-fees/transactions/#signed-transactions){target=\_blank}. - -### Pallets - -The following is a condensed and annotated example of metadata for a single element in the `pallets` array (the [`sudo`](https://paritytech.github.io/polkadot-sdk/master/pallet_sudo/index.html){target=\_blank} pallet): - -```json -{ - "name": "Sudo", - "storage": { - "prefix": "Sudo", - "entries": [ - { - "name": "Key", - "modifier": "Optional", - "ty": { - "Plain": 0 - }, - "default": [0], - "docs": ["The `AccountId` of the sudo key."] - } - ] - }, - "calls": { - "ty": 117 - }, - "event": { - "ty": 42 - }, - "constants": [], - "error": { - "ty": 124 - }, - "index": 8 -} - -``` - -Every element metadata contains the name of the pallet it represents and information about its storage, calls, events, and errors. You can look up details about the definition of the calls, events, and errors by viewing the type index identifier. The type index identifier is the `u32` integer used to access the type information for that item. For example, the type index identifier for calls in the Sudo pallet is 117. If you view information for that type identifier in the `types` section of the metadata, it provides information about the available calls, including the documentation for each call. - -For example, the following is a condensed excerpt of the calls for the Sudo pallet: - -```json -{ - "id": 117, - "type": { - "path": ["pallet_sudo", "pallet", "Call"], - "params": [ - { - "name": "T", - "type": null - } - ], - "def": { - "variant": { - "variants": [ - { - "name": "sudo", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 0, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "sudo_unchecked_weight", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - }, - { - "name": "weight", - "type": 8, - "typeName": "Weight" - } - ], - "index": 1, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "set_key", - "fields": [ - { - "name": "new", - "type": 103, - "typeName": "AccountIdLookupOf" - } - ], - "index": 2, - "docs": [ - "Authenticates current sudo key, sets the given AccountId (`new`) as the new sudo" - ] - }, - { - "name": "sudo_as", - "fields": [ - { - "name": "who", - "type": 103, - "typeName": "AccountIdLookupOf" - }, - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 3, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Signed` origin from a given account" - ] - } - ] - } - } - } -} - -``` - -For each field, you can access type information and metadata for the following: - -- **Storage metadata**: Provides the information required to enable applications to get information for specific storage items. -- **Call metadata**: Includes information about the runtime calls defined by the `#[pallet]` macro including call names, arguments and documentation. -- **Event metadata**: Provides the metadata generated by the `#[pallet::event]` macro, including the name, arguments, and documentation for each pallet event. -- **Constants metadata**: Provides metadata generated by the `#[pallet::constant]` macro, including the name, type, and hex-encoded value of the constant. -- **Error metadata**: Provides metadata generated by the `#[pallet::error]` macro, including the name and documentation for each pallet error. - -!!!tip - Type identifiers change from time to time, so you should avoid relying on specific type identifiers in your applications. - -### Extrinsic - -The runtime generates extrinsic metadata and provides useful information about transaction format. When decoded, the metadata contains the transaction version and the list of signed extensions. - -For example: - -```json -{ - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [ - { - "identifier": "CheckNonZeroSender", - "ty": 132, - "additional_signed": 41 - }, - { - "identifier": "CheckSpecVersion", - "ty": 133, - "additional_signed": 4 - }, - { - "identifier": "CheckTxVersion", - "ty": 134, - "additional_signed": 4 - }, - { - "identifier": "CheckGenesis", - "ty": 135, - "additional_signed": 11 - }, - { - "identifier": "CheckMortality", - "ty": 136, - "additional_signed": 11 - }, - { - "identifier": "CheckNonce", - "ty": 138, - "additional_signed": 41 - }, - { - "identifier": "CheckWeight", - "ty": 139, - "additional_signed": 41 - }, - { - "identifier": "ChargeTransactionPayment", - "ty": 140, - "additional_signed": 41 - } - ] - }, - "ty": 141 -} - -``` - -The type system is [composite](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/frame_runtime_types/index.html){target=\_blank}, meaning each type identifier contains a reference to a specific type or to another type identifier that provides information about the associated primitive types. - -For example, you can encode the `BitVec` type, but to decode it properly, you must know the types used for the `Order` and `Store` types. To find type information for `Order` and `Store`, you can use the path in the decoded JSON to locate their type identifiers. - -## Included RPC APIs - -A standard node comes with the following APIs to interact with a node: - -- **[`AuthorApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/author/trait.AuthorApiServer.html){target=\_blank}**: Make calls into a full node, including authoring extrinsics and verifying session keys. -- **[`ChainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/chain/trait.ChainApiServer.html){target=\_blank}**: Retrieve block header and finality information. -- **[`OffchainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/offchain/trait.OffchainApiServer.html){target=\_blank}**: Make RPC calls for off-chain workers. -- **[`StateApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/state/trait.StateApiServer.html){target=\_blank}**: Query information about on-chain state such as runtime version, storage items, and proofs. -- **[`SystemApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/system/trait.SystemApiServer.html){target=\_blank}**: Retrieve information about network state, such as connected peers and node roles. - -## Additional Resources - -The following tools can help you locate and decode metadata: - -- [Subxt Explorer](https://paritytech.github.io/subxt-explorer/#/){target=\_blank} -- [Metadata Portal 🌗](https://github.com/paritytech/metadata-portal){target=\_blank} -- [De[code] Sub[strate]](https://github.com/paritytech/desub){target=\_blank} - - --- Page Title: Contract Deployment @@ -1019,280 +585,6 @@ Both REVM and PolkaVM deployments may show significant differences between gas e Both backends support contract deployment effectively, with REVM offering drop-in Ethereum compatibility and PolkaVM providing a more structured two-step approach. For the majority of use cases—deploying standard contracts like tokens or applications—both backends work seamlessly. Advanced patterns like factory contracts may require adjustment for PolkaVM, but these adaptations are straightforward with proper planning. ---- - -Page Title: Cryptography - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-cryptography.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/cryptography/ -- Summary: A concise guide to cryptography in blockchain, covering hash functions, encryption types, digital signatures, and elliptic curve applications. - -# Cryptography - -## Introduction - -Cryptography forms the backbone of blockchain technology, providing the mathematical verifiability crucial for consensus systems, data integrity, and user security. While a deep understanding of the underlying mathematical processes isn't necessary for most blockchain developers, grasping the fundamental applications of cryptography is essential. This page comprehensively overviews cryptographic implementations used across Polkadot SDK-based chains and the broader blockchain ecosystem. - -## Hash Functions - -Hash functions are fundamental to blockchain technology, creating a unique digital fingerprint for any piece of data, including simple text, images, or any other form of file. They map input data of any size to a fixed-size output (typically 32 bytes) using complex mathematical operations. Hashing is used to verify data integrity, create digital signatures, and provide a secure way to store passwords. This form of mapping is known as the ["pigeonhole principle,"](https://en.wikipedia.org/wiki/Pigeonhole_principle){target=\_blank} it is primarily implemented to efficiently and verifiably identify data from large sets. - -### Key Properties of Hash Functions - -- **Deterministic**: The same input always produces the same output. -- **Quick computation**: It's easy to calculate the hash value for any given input. -- **Pre-image resistance**: It's infeasible to generate the input data from its hash. -- **Small changes in input yield large changes in output**: Known as the ["avalanche effect"](https://en.wikipedia.org/wiki/Avalanche_effect){target=\_blank}. -- **Collision resistance**: The probabilities are extremely low to find two different inputs with the same hash. - -### Blake2 - -The Polkadot SDK utilizes Blake2, a state-of-the-art hashing method that offers: - -- Equal or greater security compared to [SHA-2](https://en.wikipedia.org/wiki/SHA-2){target=\_blank}. -- Significantly faster performance than other algorithms. - -These properties make Blake2 ideal for blockchain systems, reducing sync times for new nodes and lowering the resources required for validation. For detailed technical specifications about Blake2, see the [official Blake2 paper](https://www.blake2.net/blake2.pdf){target=\_blank}. - -## Types of Cryptography - -There are two different ways that cryptographic algorithms are implemented: symmetric cryptography and asymmetric cryptography. - -### Symmetric Cryptography - -Symmetric encryption is a branch of cryptography that isn't based on one-way functions, unlike asymmetric cryptography. It uses the same cryptographic key to encrypt plain text and decrypt the resulting ciphertext. - -Symmetric cryptography is a type of encryption that has been used throughout history, such as the Enigma Cipher and the Caesar Cipher. It is still widely used today and can be found in Web2 and Web3 applications alike. There is only one single key, and a recipient must also have access to it to access the contained information. - -#### Advantages {: #symmetric-advantages } - -- Fast and efficient for large amounts of data. -- Requires less computational power. - -#### Disadvantages {: #symmetric-disadvantages } - -- Key distribution can be challenging. -- Scalability issues in systems with many users. - -### Asymmetric Cryptography - -Asymmetric encryption is a type of cryptography that uses two different keys, known as a keypair: a public key, used to encrypt plain text, and a private counterpart, used to decrypt the ciphertext. - -The public key encrypts a fixed-length message that can only be decrypted with the recipient's private key and, sometimes, a set password. The public key can be used to cryptographically verify that the corresponding private key was used to create a piece of data without compromising the private key, such as with digital signatures. This has obvious implications for identity, ownership, and properties and is used in many different protocols across Web2 and Web3. - -#### Advantages {: #asymmetric-advantages } - -- Solves the key distribution problem. -- Enables digital signatures and secure key exchange. - -#### Disadvantages {: #asymmetric-disadvantages } - -- Slower than symmetric encryption. -- Requires more computational resources. - -### Trade-offs and Compromises - -Symmetric cryptography is faster and requires fewer bits in the key to achieve the same level of security that asymmetric cryptography provides. However, it requires a shared secret before communication can occur, which poses issues to its integrity and a potential compromise point. On the other hand, asymmetric cryptography doesn't require the secret to be shared ahead of time, allowing for far better end-user security. - -Hybrid symmetric and asymmetric cryptography is often used to overcome the engineering issues of asymmetric cryptography, as it is slower and requires more bits in the key to achieve the same level of security. It encrypts a key and then uses the comparatively lightweight symmetric cipher to do the "heavy lifting" with the message. - -## Digital Signatures - -Digital signatures are a way of verifying the authenticity of a document or message using asymmetric keypairs. They are used to ensure that a sender or signer's document or message hasn't been tampered with in transit, and for recipients to verify that the data is accurate and from the expected sender. - -Signing digital signatures only requires a low-level understanding of mathematics and cryptography. For a conceptual example -- when signing a check, it is expected that it cannot be cashed multiple times. This isn't a feature of the signature system but rather the check serialization system. The bank will check that the serial number on the check hasn't already been used. Digital signatures essentially combine these two concepts, allowing the signature to provide the serialization via a unique cryptographic fingerprint that cannot be reproduced. - -Unlike pen-and-paper signatures, knowledge of a digital signature cannot be used to create other signatures. Digital signatures are often used in bureaucratic processes, as they are more secure than simply scanning in a signature and pasting it onto a document. - -Polkadot SDK provides multiple different cryptographic schemes and is generic so that it can support anything that implements the [`Pair` trait](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Pair.html){target=\_blank}. - -### Example of Creating a Digital Signature - -The process of creating and verifying a digital signature involves several steps: - -1. The sender creates a hash of the message. -2. The hash is encrypted using the sender's private key, creating the signature. -3. The message and signature are sent to the recipient. -4. The recipient decrypts the signature using the sender's public key. -5. The recipient hashes the received message and compares it to the decrypted hash. - -If the hashes match, the signature is valid, confirming the message's integrity and the sender's identity. - -## Elliptic Curve - -Blockchain technology requires the ability to have multiple keys creating a signature for block proposal and validation. To this end, Elliptic Curve Digital Signature Algorithm (ECDSA) and Schnorr signatures are two of the most commonly used methods. While ECDSA is a far simpler implementation, Schnorr signatures are more efficient when it comes to multi-signatures. - -Schnorr signatures bring some noticeable features over the ECDSA/EdDSA schemes: - -- It is better for hierarchical deterministic key derivations. -- It allows for native multi-signature through [signature aggregation](https://bitcoincore.org/en/2017/03/23/schnorr-signature-aggregation/){target=\_blank}. -- It is generally more resistant to misuse. - -One sacrifice that is made when using Schnorr signatures over ECDSA is that both require 64 bytes, but only ECDSA signatures communicate their public key. - -### Various Implementations - -- **[ECDSA](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm){target=\_blank}**: Polkadot SDK provides an ECDSA signature scheme using the [secp256k1](https://en.bitcoin.it/wiki/Secp256k1){target=\_blank} curve. This is the same cryptographic algorithm used to secure [Bitcoin](https://en.wikipedia.org/wiki/Bitcoin){target=\_blank} and [Ethereum](https://en.wikipedia.org/wiki/Ethereum){target=\_blank}. - -- **[Ed25519](https://en.wikipedia.org/wiki/EdDSA#Ed25519){target=\_blank}**: An EdDSA signature scheme using [Curve25519](https://en.wikipedia.org/wiki/Curve25519){target=\_blank}. It is carefully engineered at several levels of design and implementation to achieve very high speeds without compromising security. - -- **[SR25519](https://research.web3.foundation/Polkadot/security/keys/accounts-more){target=\_blank}**: Based on the same underlying curve as Ed25519. However, it uses Schnorr signatures instead of the EdDSA scheme. - - ---- - -Page Title: Data Encoding - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-data-encoding.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/data-encoding/ -- Summary: SCALE codec enables fast, efficient data encoding, ideal for resource-constrained environments like Wasm, supporting custom types and compact encoding. - -# Data Encoding - -## Introduction - -The Polkadot SDK uses a lightweight and efficient encoding/decoding mechanism to optimize data transmission across the network. This mechanism, known as the _SCALE_ codec, is used for serializing and deserializing data. - -The SCALE codec enables communication between the runtime and the outer node. This mechanism is designed for high-performance, copy-free data encoding and decoding in resource-constrained environments like the Polkadot SDK [Wasm runtime](/develop/parachains/deployment/build-deterministic-runtime/#introduction){target=\_blank}. - -It is not self-describing, meaning the decoding context must fully know the encoded data types. - -Parity's libraries utilize the [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} crate (a Rust implementation of the SCALE codec) to handle encoding and decoding for interactions between RPCs and the runtime. - -The `codec` mechanism is ideal for Polkadot SDK-based chains because: - -- It is lightweight compared to generic serialization frameworks like [`serde`](https://serde.rs/){target=\_blank}, which add unnecessary bulk to binaries. -- It doesn’t rely on Rust’s `libstd`, making it compatible with `no_std` environments like Wasm runtime. -- It integrates seamlessly with Rust, allowing easy derivation of encoding and decoding logic for new types using `#[derive(Encode, Decode)]`. - -Defining a custom encoding scheme in the Polkadot SDK-based chains, rather than using an existing Rust codec library, is crucial for enabling cross-platform and multi-language support. - -## SCALE Codec - -The codec is implemented using the following traits: - -- [`Encode`](#encode) -- [`Decode`](#decode) -- [`CompactAs`](#compactas) -- [`HasCompact`](#hascompact) -- [`EncodeLike`](#encodelike) - -### Encode - -The [`Encode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Encode.html){target=\_blank} trait handles data encoding into SCALE format and includes the following key functions: - -- **`size_hint(&self) -> usize`**: Estimates the number of bytes required for encoding to prevent multiple memory allocations. This should be inexpensive and avoid complex operations. Optional if the size isn’t known. -- **`encode_to(&self, dest: &mut T)`**: Encodes the data, appending it to a destination buffer. -- **`encode(&self) -> Vec`**: Encodes the data and returns it as a byte vector. -- **`using_encoded R>(&self, f: F) -> R`**: Encodes the data and passes it to a closure, returning the result. -- **`encoded_size(&self) -> usize`**: Calculates the encoded size. Should be used when the encoded data isn’t required. - -!!!tip - For best performance, value types should override `using_encoded`, and allocating types should override `encode_to`. It's recommended to implement `size_hint` for all types where possible. - -### Decode - -The [`Decode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Decode.html){target=\_blank} trait handles decoding SCALE-encoded data back into the appropriate types: - -- **`fn decode(value: &mut I) -> Result`**: Decodes data from the SCALE format, returning an error if decoding fails. - -### CompactAs - -The [`CompactAs`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.CompactAs.html){target=\_blank} trait wraps custom types for compact encoding: - -- **`encode_as(&self) -> &Self::As`**: Encodes the type as a compact type. -- **`decode_from(_: Self::As) -> Result`**: decodes from a compact encoded type. - -### HasCompact - -The [`HasCompact`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.HasCompact.html){target=\_blank} trait indicates a type supports compact encoding. - -### EncodeLike - -The [`EncodeLike`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.EncodeLike.html){target=\_blank} trait is used to ensure multiple types that encode similarly are accepted by the same function. When using `derive`, it is automatically implemented. - -### Data Types - -The table below outlines how the Rust implementation of the Parity SCALE codec encodes different data types. - -| Type | Description | Example SCALE Decoded Value | SCALE Encoded Value | -|-------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------| -| Boolean | Boolean values are encoded using the least significant bit of a single byte. | `false` / `true` | `0x00` / `0x01` | -| Compact/general integers | A "compact" or general integer encoding is sufficient for encoding large integers (up to 2^536) and is more efficient at encoding most values than the fixed-width version. | `unsigned integer 0` / `unsigned integer 1` / `unsigned integer 42` / `unsigned integer 69` / `unsigned integer 65535` / `BigInt(100000000000000)` | `0x00` / `0x04` / `0xa8` / `0x1501` / `0xfeff0300` / `0x0b00407a10f35a` | -| Enumerations (tagged-unions) | A fixed number of variants, each mutually exclusive and potentially implying a further value or series of values. Encoded as the first byte identifying the index of the variant that the value is. Any further bytes are used to encode any data that the variant implies. Thus, no more than 256 variants are supported. | `Int(42)` and `Bool(true)` where `enum IntOrBool { Int(u8), Bool(bool) }` | `0x002a` and `0x0101` | -| Fixed-width integers | Basic integers are encoded using a fixed-width little-endian (LE) format. | `signed 8-bit integer 69` / `unsigned 16-bit integer 42` / `unsigned 32-bit integer 16777215` | `0x45` / `0x2a00` / `0xffffff00` | -| Options | One or zero values of a particular type. | `Some` / `None` | `0x01` followed by the encoded value / `0x00` | -| Results | Results are commonly used enumerations which indicate whether certain operations were successful or unsuccessful. | `Ok(42)` / `Err(false)` | `0x002a` / `0x0100` | -| Strings | Strings are Vectors of bytes (Vec) containing a valid UTF8 sequence. | | | -| Structs | For structures, the values are named, but that is irrelevant for the encoding (names are ignored - only order matters). | `SortedVecAsc::from([3, 5, 2, 8])` | `[3, 2, 5, 8] ` | -| Tuples | A fixed-size series of values, each with a possibly different but predetermined and fixed type. This is simply the concatenation of each encoded value. | Tuple of compact unsigned integer and boolean: `(3, false)` | `0x0c00` | -| Vectors (lists, series, sets) | A collection of same-typed values is encoded, prefixed with a compact encoding of the number of items, followed by each item's encoding concatenated in turn. | Vector of unsigned `16`-bit integers: `[4, 8, 15, 16, 23, 42]` | `0x18040008000f00100017002a00` | - -## Encode and Decode Rust Trait Implementations - -Here's how the `Encode` and `Decode` traits are implemented: - - -```rust -use parity_scale_codec::{Encode, Decode}; - -[derive(Debug, PartialEq, Encode, Decode)] -enum EnumType { - #[codec(index = 15)] - A, - B(u32, u64), - C { - a: u32, - b: u64, - }, -} - -let a = EnumType::A; -let b = EnumType::B(1, 2); -let c = EnumType::C { a: 1, b: 2 }; - -a.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x0f"); -}); - -b.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); - -c.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); - -let mut da: &[u8] = b"\x0f"; -assert_eq!(EnumType::decode(&mut da).ok(), Some(a)); - -let mut db: &[u8] = b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut db).ok(), Some(b)); - -let mut dc: &[u8] = b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut dc).ok(), Some(c)); - -let mut dz: &[u8] = &[0]; -assert_eq!(EnumType::decode(&mut dz).ok(), None); -``` - -## SCALE Codec Libraries - -Several SCALE codec implementations are available in various languages. Here's a list of them: - -- **AssemblyScript**: [`LimeChain/as-scale-codec`](https://github.com/LimeChain/as-scale-codec){target=\_blank} -- **C**: [`MatthewDarnell/cScale`](https://github.com/MatthewDarnell/cScale){target=\_blank} -- **C++**: [`qdrvm/scale-codec-cpp`](https://github.com/qdrvm/scale-codec-cpp){target=\_blank} -- **JavaScript**: [`polkadot-js/api`](https://github.com/polkadot-js/api){target=\_blank} -- **Dart**: [`leonardocustodio/polkadart`](https://github.com/leonardocustodio/polkadart){target=\_blank} -- **Haskell**: [`airalab/hs-web3`](https://github.com/airalab/hs-web3/tree/master/packages/scale){target=\_blank} -- **Golang**: [`itering/scale.go`](https://github.com/itering/scale.go){target=\_blank} -- **Java**: [`splix/polkaj`](https://github.com/splix/polkaj){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **Ruby**: [` wuminzhe/scale_rb`](https://github.com/wuminzhe/scale_rb){target=\_blank} -- **TypeScript**: [`parity-scale-codec-ts`](https://github.com/tjjfvi/subshape){target=\_blank}, [`scale-ts`](https://github.com/unstoppablejs/unstoppablejs/tree/main/packages/scale-ts#scale-ts){target=\_blank}, [`soramitsu/scale-codec-js-library`](https://github.com/soramitsu/scale-codec-js-library){target=\_blank}, [`subsquid/scale-codec`](https://github.com/subsquid/squid-sdk/tree/master/substrate/scale-codec){target=\_blank} - - --- Page Title: Deploy an ERC-20 to Polkadot Hub @@ -2375,370 +1667,130 @@ From here, follow the quick starts to get connected, iterate locally with your p --- -Page Title: Glossary +Page Title: Get Started with XCM -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-glossary.md -- Canonical (HTML): https://docs.polkadot.com/reference/glossary/ -- Summary: Glossary of terms used within the Polkadot ecosystem, Polkadot SDK, its subsequent libraries, and other relevant Web3 terminology. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md +- Canonical (HTML): https://docs.polkadot.com/parachains/interoperability/get-started/ +- Summary: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. -# Glossary +# Get Started with XCM -Key definitions, concepts, and terminology specific to the Polkadot ecosystem are included here. +## Introduction -Additional glossaries from around the ecosystem you might find helpful: +Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems. -- [Polkadot Wiki Glossary](https://wiki.polkadot.com/general/glossary){target=\_blank} -- [Polkadot SDK Glossary](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/glossary/index.html){target=\_blank} +With XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation. -## Authority - -The role in a blockchain that can participate in consensus mechanisms. - -- **[GRANDPA](#grandpa)**: The authorities vote on chains they consider final. -- **[Blind Assignment of Blockchain Extension](#blind-assignment-of-blockchain-extension-babe) (BABE)**: The authorities are also [block authors](#block-author). - -Authority sets can be used as a basis for consensus mechanisms such as the [Nominated Proof of Stake (NPoS)](#nominated-proof-of-stake-npos) protocol. - -## Authority Round (Aura) - -A deterministic [consensus](#consensus) protocol where block production is limited to a rotating list of [authorities](#authority) that take turns creating blocks. In authority round (Aura) consensus, most online authorities are assumed to be honest. It is often used in combination with [GRANDPA](#grandpa) as a [hybrid consensus](#hybrid-consensus) protocol. - -Learn more by reading the official [Aura consensus algorithm](https://openethereum.github.io/Aura){target=\_blank} wiki article. - -## Blind Assignment of Blockchain Extension (BABE) - -A [block authoring](#block-author) protocol similar to [Aura](#authority-round-aura), except [authorities](#authority) win [slots](#slot) based on a Verifiable Random Function (VRF) instead of the round-robin selection method. The winning authority can select a chain and submit a new block. - -Learn more by reading the official Web3 Foundation [BABE research document](https://research.web3.foundation/Polkadot/protocols/block-production/Babe){target=\_blank}. - -## Block Author - -The node responsible for the creation of a block, also called _block producers_. In a Proof of Work (PoW) blockchain, these nodes are called _miners_. - -## Byzantine Fault Tolerance (BFT) - -The ability of a distributed computer network to remain operational if a certain proportion of its nodes or [authorities](#authority) are defective or behaving maliciously. A distributed network is typically considered Byzantine fault tolerant if it can remain functional, with up to one-third of nodes assumed to be defective, offline, actively malicious, and part of a coordinated attack. - -### Byzantine Failure - -The loss of a network service due to node failures that exceed the proportion of nodes required to reach consensus. - -### Practical Byzantine Fault Tolerance (pBFT) - -An early approach to Byzantine fault tolerance (BFT), practical Byzantine fault tolerance (pBFT) systems tolerate Byzantine behavior from up to one-third of participants. - -The communication overhead for such systems is `O(n²)`, where `n` is the number of nodes (participants) in the system. - -### Preimage - -A preimage is the data that is input into a hash function to calculate a hash. Since a hash function is a [one-way function](https://en.wikipedia.org/wiki/One-way_function){target=\_blank}, the output, the hash, cannot be used to reveal the input, the preimage. - -## Call - -In the context of pallets containing functions to be dispatched to the runtime, `Call` is an enumeration data type that describes the functions that can be dispatched with one variant per pallet. A `Call` represents a [dispatch](#dispatchable) data structure object. - -## Chain Specification - -A chain specification file defines the properties required to run a node in an active or new Polkadot SDK-built network. It often contains the initial genesis runtime code, network properties (such as the network's name), the initial state for some pallets, and the boot node list. The chain specification file makes it easy to use a single Polkadot SDK codebase as the foundation for multiple independently configured chains. - -## Collator - -An [author](#block-author) of a [parachain](#parachain) network. -They aren't [authorities](#authority) in themselves, as they require a [relay chain](#relay-chain) to coordinate [consensus](#consensus). - -More details are found on the [Polkadot Collator Wiki](https://wiki.polkadot.com/learn/learn-collator/){target=\_blank}. - -## Collective - -Most often used to refer to an instance of the Collective pallet on Polkadot SDK-based networks such as [Kusama](#kusama) or [Polkadot](#polkadot) if the Collective pallet is part of the FRAME-based runtime for the network. - -## Consensus - -Consensus is the process blockchain nodes use to agree on a chain's canonical fork. It is composed of [authorship](#block-author), finality, and [fork-choice rule](#fork-choice-rulestrategy). In the Polkadot ecosystem, these three components are usually separate and the term consensus often refers specifically to authorship. - -See also [hybrid consensus](#hybrid-consensus). +## Messaging Format -## Consensus Algorithm +XCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics. -Ensures a set of [actors](#authority)—who don't necessarily trust each other—can reach an agreement about the state as the result of some computation. Most consensus algorithms assume that up to one-third of the actors or nodes can be [Byzantine fault tolerant](#byzantine-fault-tolerance-bft). +XCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing. -Consensus algorithms are generally concerned with ensuring two properties: +## The Four Principles of XCM -- **Safety**: Indicating that all honest nodes eventually agreed on the state of the chain. -- **Liveness**: Indicating the ability of the chain to keep progressing. +XCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems: -## Consensus Engine +- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes. +- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended. +- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin. +- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems. -The node subsystem responsible for consensus tasks. +These principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments. -For detailed information about the consensus strategies of the [Polkadot](#polkadot) network, see the [Polkadot Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} blog series. +## The XCM Tech Stack -See also [hybrid consensus](#hybrid-consensus). +![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp) -## Coretime +The XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels. -The time allocated for utilizing a core, measured in relay chain blocks. There are two types of coretime: *on-demand* and *bulk*. +## Core Functionalities of XCM -On-demand coretime refers to coretime acquired through bidding in near real-time for the validation of a single parachain block on one of the cores reserved specifically for on-demand orders. They are available as an on-demand coretime pool. Set of cores that are available on-demand. Cores reserved through bulk coretime could also be made available in the on-demand coretime pool, in parts or in entirety. +XCM enhances cross-consensus communication by introducing several powerful features: -Bulk coretime is a fixed duration of continuous coretime represented by an NFT that can be split, shared, or resold. It is managed by the [Broker pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_broker/index.html){target=\_blank}. +- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management. +- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification. +- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location. -## Development Phrase +The standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications. -A [mnemonic phrase](https://en.wikipedia.org/wiki/Mnemonic#For_numerical_sequences_and_mathematical_operations){target=\_blank} that is intentionally made public. +## XCM Example -Well-known development accounts, such as Alice, Bob, Charlie, Dave, Eve, and Ferdie, are generated from the same secret phrase: +The following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA). +```rust +let message = Xcm(vec![ + WithdrawAsset((Here, amount).into()), + BuyExecution { + fees: (Here, amount).into(), + weight_limit: WeightLimit::Unlimited + }, + DepositAsset { + assets: All.into(), + beneficiary: MultiLocation { + parents: 0, + interior: Junction::AccountId32 { + network: None, + id: BOB.clone().into() + }.into(), + }.into() + } +]); ``` -bottom drive obey lake curtain smoke basket hold race lonely fit walk -``` - -Many tools in the Polkadot SDK ecosystem, such as [`subkey`](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/bin/utils/subkey){target=\_blank}, allow you to implicitly specify an account using a derivation path such as `//Alice`. - -## Digest - -An extensible field of the [block header](#header) that encodes information needed by several actors in a blockchain network, including: - -- [Light clients](#light-client) for chain synchronization. -- Consensus engines for block verification. -- The runtime itself, in the case of pre-runtime digests. - -## Dispatchable - -Function objects that act as the entry points in FRAME [pallets](#pallet). Internal or external entities can call them to interact with the blockchain’s state. They are a core aspect of the runtime logic, handling [transactions](#transaction) and other state-changing operations. - -## Events - -A means of recording that some particular [state](#state) transition happened. - -In the context of [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities), events are composable data types that each [pallet](#pallet) can individually define. Events in FRAME are implemented as a set of transient storage items inspected immediately after a block has been executed and reset during block initialization. - -## Executor - -A means of executing a function call in a given [runtime](#runtime) with a set of dependencies. -There are two orchestration engines in Polkadot SDK, _WebAssembly_ and _native_. - -- The _native executor_ uses a natively compiled runtime embedded in the node to execute calls. This is a performance optimization available to up-to-date nodes. - -- The _WebAssembly executor_ uses a [Wasm](#webassembly-wasm) binary and a Wasm interpreter to execute calls. The binary is guaranteed to be up-to-date regardless of the version of the blockchain node because it is persisted in the [state](#state) of the Polkadot SDK-based chain. - -## Existential Deposit - -The minimum balance an account is allowed to have in the [Balances pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/index.html){target=\_blank}. Accounts cannot be created with a balance less than the existential deposit amount. - -If an account balance drops below this amount, the Balances pallet uses [a FRAME System API](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.dec_ref){target=\_blank} to drop its references to that account. - -If the Balances pallet reference to an account is dropped, the account can be [reaped](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.allow_death){target=\_blank}. - -## Extrinsic - -A general term for data that originates outside the runtime, is included in a block, and leads to some action. This includes user-initiated transactions and inherent transactions placed into the block by the block builder. - -It is a SCALE-encoded array typically consisting of a version number, signature, and varying data types indicating the resulting runtime function to be called. Extrinsics can take two forms: [inherents](#inherent-transactions) and [transactions](#transaction). - -For more technical details, see the [Polkadot spec](https://spec.polkadot.network/id-extrinsics){target=\_blank}. - -## Fork Choice Rule/Strategy - -A fork choice rule or strategy helps determine which chain is valid when reconciling several network forks. A common fork choice rule is the [longest chain](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/struct.LongestChain.html){target=\_blank}, in which the chain with the most blocks is selected. - -## FRAME (Framework for Runtime Aggregation of Modularized Entities) - -Enables developers to create blockchain [runtime](#runtime) environments from a modular set of components called [pallets](#pallet). It utilizes a set of procedural macros to construct runtimes. - -[Visit the Polkadot SDK docs for more details on FRAME.](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank} - -## Full Node - -A node that prunes historical states, keeping only recently finalized block states to reduce storage needs. Full nodes provide current chain state access and allow direct submission and validation of [extrinsics](#extrinsic), maintaining network decentralization. - -## Genesis Configuration - -A mechanism for specifying the initial state of a blockchain. By convention, this initial state or first block is commonly referred to as the genesis state or genesis block. The genesis configuration for Polkadot SDK-based chains is accomplished by way of a [chain specification](#chain-specification) file. - -## GRANDPA - -A deterministic finality mechanism for blockchains that is implemented in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. - -The [formal specification](https://github.com/w3f/consensus/blob/master/pdf/grandpa-old.pdf){target=\_blank} is maintained by the [Web3 Foundation](https://web3.foundation/){target=\_blank}. - -## Header - -A structure that aggregates the information used to summarize a block. Primarily, it consists of cryptographic information used by [light clients](#light-client) to get minimally secure but very efficient chain synchronization. - -## Hybrid Consensus - -A blockchain consensus protocol that consists of independent or loosely coupled mechanisms for [block production](#block-author) and finality. - -Hybrid consensus allows the chain to grow as fast as probabilistic consensus protocols, such as [Aura](#authority-round-aura), while maintaining the same level of security as deterministic finality consensus protocols, such as [GRANDPA](#grandpa). - -## Inherent Transactions - -A special type of unsigned transaction, referred to as _inherents_, that enables a block authoring node to insert information that doesn't require validation directly into a block. - -Only the block-authoring node that calls the inherent transaction function can insert data into its block. In general, validators assume the data inserted using an inherent transaction is valid and reasonable even if it can't be deterministically verified. - -## JSON-RPC - -A stateless, lightweight remote procedure call protocol encoded in JavaScript Object Notation (JSON). JSON-RPC provides a standard way to call functions on a remote system by using JSON. - -For Polkadot SDK, this protocol is implemented through the [Parity JSON-RPC](https://github.com/paritytech/jsonrpc){target=\_blank} crate. - -## Keystore - -A subsystem for managing keys for the purpose of producing new blocks. - -## Kusama - -[Kusama](https://kusama.network/){target=\_blank} is a Polkadot SDK-based blockchain that implements a design similar to the [Polkadot](#polkadot) network. - -Kusama is a [canary](https://en.wiktionary.org/wiki/canary_in_a_coal_mine){target=\_blank} network and is referred to as [Polkadot's "wild cousin."](https://wiki.polkadot.com/learn/learn-comparisons-kusama/){target=\_blank}. - -As a canary network, Kusama is expected to be more stable than a test network like [Westend](#westend) but less stable than a production network like [Polkadot](#polkadot). Kusama is controlled by its network participants and is intended to be stable enough to encourage meaningful experimentation. - -## libp2p - -A peer-to-peer networking stack that allows the use of many transport mechanisms, including WebSockets (usable in a web browser). - -Polkadot SDK uses the [Rust implementation](https://github.com/libp2p/rust-libp2p){target=\_blank} of the `libp2p` networking stack. - -## Light Client - -A type of blockchain node that doesn't store the [chain state](#state) or produce blocks. - -A light client can verify cryptographic primitives and provides a [remote procedure call (RPC)](https://en.wikipedia.org/wiki/Remote_procedure_call){target=\_blank} server, enabling blockchain users to interact with the network. -## Metadata - -Data that provides information about one or more aspects of a system. -The metadata that exposes information about a Polkadot SDK blockchain enables you to interact with that system. - -## Nominated Proof of Stake (NPoS) - -A method for determining [validators](#validator) or _[authorities](#authority)_ based on a willingness to commit their stake to the proper functioning of one or more block-producing nodes. - -## Oracle - -An entity that connects a blockchain to a non-blockchain data source. Oracles enable the blockchain to access and act upon information from existing data sources and incorporate data from non-blockchain systems and services. - -## Origin - -A [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitive that identifies the source of a [dispatched](#dispatchable) function call into the [runtime](#runtime). The FRAME System pallet defines three built-in [origins](#origin). As a [pallet](#pallet) developer, you can also define custom origins, such as those defined by the [Collective pallet](https://paritytech.github.io/substrate/master/pallet_collective/enum.RawOrigin.html){target=\_blank}. - -## Pallet - -A module that can be used to extend the capabilities of a [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities)-based [runtime](#runtime). -Pallets bundle domain-specific logic with runtime primitives like [events](#events) and [storage items](#storage-item). - -## Parachain - -A parachain is a blockchain that derives shared infrastructure and security from a _[relay chain](#relay-chain)_. -You can learn more about parachains on the [Polkadot Wiki](https://wiki.polkadot.com/learn/learn-parachains/){target=\_blank}. - -## Paseo - -Paseo TestNet provisions testing on Polkadot's "production" runtime, which means less chance of feature or code mismatch when developing parachain apps. Specifically, after the [Polkadot Technical fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} proposes a runtime upgrade for Polkadot, this TestNet is updated, giving a period where the TestNet will be ahead of Polkadot to allow for testing. - -## Polkadot - -The [Polkadot network](https://polkadot.com/){target=\_blank} is a blockchain that serves as the central hub of a heterogeneous blockchain network. It serves the role of the [relay chain](#relay-chain) and provides shared infrastructure and security to support [parachains](#parachain). - -## Polkadot Cloud - -Polkadot Cloud is a platform for deploying resilient, customizable and scalable Web3 applications through Polkadot's functionality. It encompasses the wider Polkadot network infrastructure and security layer where parachains operate. The platform enables users to launch Ethereum-compatible chains, build specialized blockchains, and flexibly manage computing resources through on-demand or bulk coretime purchases. Initially launched with basic parachain functionality, Polkadot Cloud has evolved to offer enhanced flexibility with features like coretime, elastic scaling, and async backing for improved performance. - -## Polkadot Hub - -Polkadot Hub is a Layer 1 platform that serves as the primary entry point to the Polkadot ecosystem, providing essential functionality without requiring parachain deployment. It offers core services including smart contracts, identity management, staking, governance, and interoperability with other ecosystems, making it simple and fast for both builders and users to get started in Web3. - -## PolkaVM - -PolkaVM is a custom virtual machine optimized for performance, leveraging a RISC-V-based architecture to support Solidity and any language that compiles to RISC-V. It is specifically designed for the Polkadot ecosystem, enabling smart contract deployment and execution. - -## Relay Chain - -Relay chains are blockchains that provide shared infrastructure and security to the [parachains](#parachain) in the network. In addition to providing [consensus](#consensus) capabilities, relay chains allow parachains to communicate and exchange digital assets without needing to trust one another. - -## Rococo - -A [parachain](#parachain) test network for the Polkadot network. The [Rococo](#rococo) network is a Polkadot SDK-based blockchain with an October 14, 2024 deprecation date. Development teams are encouraged to use the Paseo TestNet instead. - -## Runtime - -The runtime represents the [state transition function](#state-transition-function-stf) for a blockchain. In Polkadot SDK, the runtime is stored as a [Wasm](#webassembly-wasm) binary in the chain state. The Runtime is stored under a unique state key and can be modified during the execution of the state transition function. - -## Slot - -A fixed, equal interval of time used by consensus engines such as [Aura](#authority-round-aura) and [BABE](#blind-assignment-of-blockchain-extension-babe). In each slot, a subset of [authorities](#authority) is permitted, or obliged, to [author](#block-author) a block. - -## Sovereign Account - -The unique account identifier for each chain in the relay chain ecosystem. It is often used in cross-consensus (XCM) interactions to sign XCM messages sent to the relay chain or other chains in the ecosystem. - -The sovereign account for each chain is a root-level account that can only be accessed using the Sudo pallet or through governance. The account identifier is calculated by concatenating the Blake2 hash of a specific text string and the registered parachain identifier. - -## SS58 Address Format - -A public key address based on the Bitcoin [`Base-58-check`](https://en.bitcoin.it/wiki/Base58Check_encoding){target=\_blank} encoding. Each Polkadot SDK SS58 address uses a `base-58` encoded value to identify a specific account on a specific Polkadot SDK-based chain - -The [canonical `ss58-registry`](https://github.com/paritytech/ss58-registry){target=\_blank} provides additional details about the address format used by different Polkadot SDK-based chains, including the network prefix and website used for different networks - -## State Transition Function (STF) - -The logic of a blockchain that determines how the state changes when a block is processed. In Polkadot SDK, the state transition function is effectively equivalent to the [runtime](#runtime). - -## Storage Item - -[FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitives that provide type-safe data persistence capabilities to the [runtime](#runtime). -Learn more in the [storage items](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/index.html){target=\_blank} reference document in the Polkadot SDK. - -## Substrate - -A flexible framework for building modular, efficient, and upgradeable blockchains. Substrate is written in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language and is maintained by [Parity Technologies](https://www.parity.io/){target=\_blank}. - -## Transaction - -An [extrinsic](#extrinsic) that includes a signature that can be used to verify the account authorizing it inherently or via [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}. - -## Transaction Era - -A definable period expressed as a range of block numbers during which a transaction can be included in a block. -Transaction eras are used to protect against transaction replay attacks if an account is reaped and its replay-protecting nonce is reset to zero. - -## Trie (Patricia Merkle Tree) +The message consists of three instructions described as follows: -A data structure used to represent sets of key-value pairs and enables the items in the data set to be stored and retrieved using a cryptographic hash. Because incremental changes to the data set result in a new hash, retrieving data is efficient even if the data set is very large. With this data structure, you can also prove whether the data set includes any particular key-value pair without access to the entire data set. +- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register. -In Polkadot SDK-based blockchains, state is stored in a trie data structure that supports the efficient creation of incremental digests. This trie is exposed to the [runtime](#runtime) as [a simple key/value map](#storage-item) where both keys and values can be arbitrary byte arrays. + ```rust + WithdrawAsset((Here, amount).into()), + ``` -## Validator + - **`Here`**: The native parachain token. + - **`amount`**: The number of tokens that are transferred. -A validator is a node that participates in the consensus mechanism of the network. Its roles include block production, transaction validation, network integrity, and security maintenance. + The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register. -## WebAssembly (Wasm) +- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\_blank} of the XCM instructions. -An execution architecture that allows for the efficient, platform-neutral expression of -deterministic, machine-executable logic. + ```rust + BuyExecution { + fees: (Here, amount).into(), + weight_limit: WeightLimit::Unlimited + }, + ``` -[Wasm](https://webassembly.org/){target=\_blank} can be compiled from many languages, including -the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. Polkadot SDK-based chains use a Wasm binary to provide portable [runtimes](#runtime) that can be included as part of the chain's state. + - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight. + - **`weight_limit`**: Defines the maximum fees that can be used to buy weight. -## Weight +- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\_blank}**: Moves the remaining tokens from the holding register to Bob’s account. -A convention used in Polkadot SDK-based blockchains to measure and manage the time it takes to validate a block. -Polkadot SDK defines one unit of weight as one picosecond of execution time on reference hardware. + ```rust + DepositAsset { + assets: All.into(), + beneficiary: MultiLocation { + parents: 0, + interior: Junction::AccountId32 { + network: None, + id: BOB.clone().into() + }.into(), + }.into() + } + ``` -The maximum block weight should be equivalent to one-third of the target block time with an allocation of one-third each for: + - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited. + +This step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. -- Block construction -- Network propagation -- Import and verification +## Overview -By defining weights, you can trade-off the number of transactions per second and the hardware required to maintain the target block time appropriate for your use case. Weights are defined in the runtime, meaning you can tune them using runtime updates to keep up with hardware and software improvements. +XCM revolutionizes cross-chain communication by enabling use cases such as: -## Westend +- Token transfers between blockchains. +- Asset locking for cross-chain smart contract interactions. +- Remote execution of functions on other blockchains. -Westend is a Parity-maintained, Polkadot SDK-based blockchain that serves as a test network for the [Polkadot](#polkadot) network. +These functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. --- @@ -3165,258 +2217,60 @@ To stop the node, press `Control-C` in the terminal. --- -Page Title: Interoperability +Page Title: JSON-RPC APIs -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-interoperability.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/interoperability/ -- Summary: Explore the importance of interoperability in the Polkadot ecosystem, covering XCM, bridges, and cross-chain communication. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-json-rpc-apis.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/json-rpc-apis/ +- Summary: JSON-RPC APIs guide for Polkadot Hub, covering supported methods, parameters, and examples for interacting with the chain. -# Interoperability +# JSON-RPC APIs +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. ## Introduction -Interoperability lies at the heart of the Polkadot ecosystem, enabling communication and collaboration across a diverse range of blockchains. By bridging the gaps between parachains, relay chains, and even external networks, Polkadot unlocks the potential for truly decentralized applications, efficient resource sharing, and scalable solutions. - -Polkadot’s design ensures that blockchains can transcend their individual limitations by working together as part of a unified system. This cooperative architecture is what sets Polkadot apart in the blockchain landscape. - -## Why Interoperability Matters - -The blockchain ecosystem is inherently fragmented. Different blockchains excel in specialized domains such as finance, gaming, or supply chain management, but these chains function in isolation without interoperability. This lack of connectivity stifles the broader utility of blockchain technology. - -Interoperability solves this problem by enabling blockchains to: - -- **Collaborate across networks**: Chains can interact to share assets, functionality, and data, creating synergies that amplify their individual strengths. -- **Achieve greater scalability**: Specialized chains can offload tasks to others, optimizing performance and resource utilization. -- **Expand use-case potential**: Cross-chain applications can leverage features from multiple blockchains, unlocking novel user experiences and solutions. - -In the Polkadot ecosystem, interoperability transforms a collection of isolated chains into a cohesive, efficient network, pushing the boundaries of what blockchains can achieve together. - -## Key Mechanisms for Interoperability - -At the core of Polkadot's cross-chain collaboration are foundational technologies designed to break down barriers between networks. These mechanisms empower blockchains to communicate, share resources, and operate as a cohesive ecosystem. - -### Cross-Consensus Messaging (XCM): The Backbone of Communication +Polkadot Hub provides Ethereum compatibility through its JSON-RPC interface, allowing developers to interact with the chain using familiar Ethereum tooling and methods. This document outlines the supported [Ethereum JSON-RPC methods](https://ethereum.org/developers/docs/apis/json-rpc/#json-rpc-methods){target=\_blank} and provides examples of how to use them. -Polkadot's Cross-Consensus Messaging (XCM) is the standard framework for interaction between parachains, relay chains, and, eventually, external blockchains. XCM provides a trustless, secure messaging format for exchanging assets, sharing data, and executing cross-chain operations. +This guide uses the Polkadot Hub TestNet endpoint: -Through XCM, decentralized applications can: +```text +https://testnet-passet-hub-eth-rpc.polkadot.io +``` -- Transfer tokens and other assets across chains. -- Coordinate complex workflows that span multiple blockchains. -- Enable seamless user experiences where underlying blockchain differences are invisible. -- XCM exemplifies Polkadot’s commitment to creating a robust and interoperable ecosystem. +## Available Methods -For further information about XCM, check the [Introduction to XCM](/parachains/interoperability/get-started/){target=\_blank} article. +### eth_accounts -### Bridges: Connecting External Networks +Returns a list of addresses owned by the client. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_accounts){target=\_blank}. -While XCM enables interoperability within the Polkadot ecosystem, bridges extend this functionality to external blockchains such as Ethereum and Bitcoin. By connecting these networks, bridges allow Polkadot-based chains to access external liquidity, additional functionalities, and broader user bases. +**Parameters**: -With bridges, developers and users gain the ability to: +None. -- Integrate external assets into Polkadot-based applications. -- Combine the strengths of Polkadot’s scalability with the liquidity of other networks. -- Facilitate accurate multi-chain applications that transcend ecosystem boundaries. +**Example**: -For more information about bridges in the Polkadot ecosystem, see the [Bridge Hub](/reference/polkadot-hub/bridging/){target=\_blank} guide. +```bash title="eth_accounts" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_accounts", + "params":[], + "id":1 +}' +``` -## The Polkadot Advantage +--- -Polkadot was purpose-built for interoperability. Unlike networks that add interoperability as an afterthought, Polkadot integrates it as a fundamental design principle. This approach offers several distinct advantages: +### eth_blockNumber -- **Developer empowerment**: Polkadot’s interoperability tools allow developers to build applications that leverage multiple chains’ capabilities without added complexity. -- **Enhanced ecosystem collaboration**: Chains in Polkadot can focus on their unique strengths while contributing to the ecosystem’s overall growth. -- **Future-proofing blockchain**: By enabling seamless communication, Polkadot ensures its ecosystem can adapt to evolving demands and technologies. +Returns the number of the most recent block. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_blocknumber){target=\_blank}. -## Looking Ahead +**Parameters**: -Polkadot’s vision of interoperability extends beyond technical functionality, representing a shift towards a more collaborative blockchain landscape. By enabling chains to work together, Polkadot fosters innovation, efficiency, and accessibility, paving the way for a decentralized future where blockchains are not isolated competitors but interconnected collaborators. +None. - ---- - -Page Title: Introduction to XCM - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md -- Canonical (HTML): https://docs.polkadot.com/parachains/interoperability/get-started/ -- Summary: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. - -# Introduction to XCM - -## Introduction - -Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems. - -With XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation. - -## Messaging Format - -XCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics. - -XCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing. - -## The Four Principles of XCM - -XCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems: - -- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes. -- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended. -- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin. -- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems. - -These principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments. - -## The XCM Tech Stack - -![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp) - -The XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels. - -## Core Functionalities of XCM - -XCM enhances cross-consensus communication by introducing several powerful features: - -- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management. -- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification. -- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location. - -The standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications. - -## XCM Example - -The following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA). - -```rust -let message = Xcm(vec![ - WithdrawAsset((Here, amount).into()), - BuyExecution { - fees: (Here, amount).into(), - weight_limit: WeightLimit::Unlimited - }, - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: Junction::AccountId32 { - network: None, - id: BOB.clone().into() - }.into(), - }.into() - } -]); -``` - -The message consists of three instructions described as follows: - -- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register. - - ```rust - WithdrawAsset((Here, amount).into()), - ``` - - - **`Here`**: The native parachain token. - - **`amount`**: The number of tokens that are transferred. - - The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register. - -- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\_blank} of the XCM instructions. - - ```rust - BuyExecution { - fees: (Here, amount).into(), - weight_limit: WeightLimit::Unlimited - }, - ``` - - - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight. - - **`weight_limit`**: Defines the maximum fees that can be used to buy weight. - -- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\_blank}**: Moves the remaining tokens from the holding register to Bob’s account. - - ```rust - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: Junction::AccountId32 { - network: None, - id: BOB.clone().into() - }.into(), - }.into() - } - ``` - - - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited. - -This step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - -## Overview - -XCM revolutionizes cross-chain communication by enabling use cases such as: - -- Token transfers between blockchains. -- Asset locking for cross-chain smart contract interactions. -- Remote execution of functions on other blockchains. - -These functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - - ---- - -Page Title: JSON-RPC APIs - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-json-rpc-apis.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/json-rpc-apis/ -- Summary: JSON-RPC APIs guide for Polkadot Hub, covering supported methods, parameters, and examples for interacting with the chain. - -# JSON-RPC APIs - -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction - -Polkadot Hub provides Ethereum compatibility through its JSON-RPC interface, allowing developers to interact with the chain using familiar Ethereum tooling and methods. This document outlines the supported [Ethereum JSON-RPC methods](https://ethereum.org/developers/docs/apis/json-rpc/#json-rpc-methods){target=\_blank} and provides examples of how to use them. - -This guide uses the Polkadot Hub TestNet endpoint: - -```text -https://testnet-passet-hub-eth-rpc.polkadot.io -``` - -## Available Methods - -### eth_accounts - -Returns a list of addresses owned by the client. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_accounts){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_accounts" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_accounts", - "params":[], - "id":1 -}' -``` - ---- - -### eth_blockNumber - -Returns the number of the most recent block. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_blocknumber){target=\_blank}. - -**Parameters**: - -None. - -**Example**: +**Example**: ```bash title="eth_blockNumber" curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ @@ -4234,1350 +3088,136 @@ If an error occurs, the response will include an error object: --- -Page Title: Networks +Page Title: Overview of FRAME -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-networks.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/networks/ -- Summary: Explore Polkadot's testing and production networks, including Westend, Kusama, and Paseo, for efficient development, deployment, and testing. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime.md +- Canonical (HTML): https://docs.polkadot.com/parachains/customize-runtime/ +- Summary: Learn how Polkadot SDK’s FRAME framework simplifies blockchain development with modular pallets and support libraries for efficient runtime design. -# Networks +# Customize Your Runtime ## Introduction -The Polkadot ecosystem is built on a robust set of networks designed to enable secure and scalable development. Whether you are testing new features or deploying to live production, Polkadot offers several layers of networks tailored for each stage of the development process. From local environments to experimental networks like Kusama and community-run TestNets such as Paseo, developers can thoroughly test, iterate, and validate their applications. This guide will introduce you to Polkadot's various networks and explain how they fit into the development workflow. +A blockchain runtime is more than just a fixed set of rules—it's a dynamic foundation that you can shape to match your specific needs. With Polkadot SDK's [FRAME (Framework for Runtime Aggregation of Modularized Entities)](/reference/glossary/#frame-framework-for-runtime-aggregation-of-modularized-entities){target=\_blank}, customizing your runtime is straightforward and modular. Instead of building everything from scratch, you combine pre-built pallets with your own custom logic to create a runtime suited to your blockchain's purpose. -## Network Overview +This overview explains how runtime customization works, introduces the building blocks you'll use, and guides you through the key patterns for extending your runtime. -Polkadot's development process is structured to ensure new features and upgrades are rigorously tested before being deployed on live production networks. The progression follows a well-defined path, starting from local environments and advancing through TestNets, ultimately reaching the Polkadot MainNet. The diagram below outlines the typical progression of the Polkadot development cycle: +## Understanding Your Runtime -``` mermaid -flowchart LR - id1[Local] --> id2[Westend] --> id4[Kusama] --> id5[Polkadot] - id1[Local] --> id3[Paseo] --> id5[Polkadot] -``` +The runtime is the core logic of your blockchain—it processes transactions, manages state, and enforces the rules that govern your network. When a transaction arrives at your blockchain, the [`frame_executive`](https://paritytech.github.io/polkadot-sdk/master/frame_executive/index.html){target=\_blank} pallet receives it and routes it to the appropriate pallet for execution. -This flow ensures developers can thoroughly test and iterate without risking real tokens or affecting production networks. Testing tools like [Chopsticks](#chopsticks) and various TestNets make it easier to experiment safely before releasing to production. +Think of your runtime as a collection of specialized modules, each handling a different aspect of your blockchain. Need token balances? Use the Balances pallet. Want governance? Add the Governance pallets. Need something custom? Create your own pallet. By mixing and matching these modules, you build a runtime that's efficient, secure, and tailored to your use case. -A typical journey through the Polkadot core protocol development process might look like this: +## Runtime Architecture -1. **Local development node**: Development starts in a local environment, where developers can create, test, and iterate on upgrades or new features using a local development node. This stage allows rapid experimentation in an isolated setup without any external dependencies. +The following diagram shows how FRAME components work together to form your runtime: -2. **Westend**: After testing locally, upgrades are deployed to [Westend](#westend), Polkadot's primary TestNet. Westend simulates real-world conditions without using real tokens, making it the ideal place for rigorous feature testing before moving on to production networks. +![](/images/parachains/customize-runtime/index/frame-overview-01.webp) -3. **Kusama**: Once features have passed extensive testing on Westend, they move to Kusama, Polkadot's experimental and fast-moving "canary" network. Kusama operates as a high-fidelity testing ground with actual economic incentives, giving developers insights into how their features will perform in a real-world environment. +The main components are: -4. **Polkadot**: After passing tests on Westend and Kusama, features are considered ready for deployment to Polkadot, the live production network. +- **`frame_executive`**: Routes all incoming transactions to the correct pallet for execution. +- **Pallets**: Domain-specific modules that implement your blockchain's features and business logic. +- **`frame_system`**: Provides core runtime primitives and storage. +- **`frame_support`**: Utilities and macros that simplify pallet development. - In addition, parachain developers can leverage local TestNets like [Zombienet](#zombienet) and deploy upgrades on parachain TestNets. +## Building Blocks: Pallets -5. **Paseo**: For parachain and dApp developers, Paseo serves as a community-run TestNet that mirrors Polkadot's runtime. Like Westend for core protocol development, Paseo provides a testing ground for parachain development without affecting live networks. +[Pallets](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/pallet/index.html){target=\_blank} are the fundamental units of runtime customization. Each pallet encapsulates specific functionality and can be independently developed, tested, and integrated. -!!!note - The Rococo TestNet deprecation date was October 14, 2024. Teams should use Westend for Polkadot protocol and feature testing and Paseo for chain development-related testing. +A pallet can implement virtually any blockchain feature you need: -## Polkadot Development Networks +- Expose new transactions that users can submit. +- Store data on-chain. +- Enforce business rules and validation logic. +- Emit events to notify users of state changes. +- Handle errors gracefully. -Development and testing are crucial to building robust dApps and parachains and performing network upgrades within the Polkadot ecosystem. To achieve this, developers can leverage various networks and tools that provide a risk-free environment for experimentation and validation before deploying features to live networks. These networks help avoid the costs and risks associated with real tokens, enabling testing for functionalities like governance, cross-chain messaging, and runtime upgrades. +### Pre-Built Pallets vs. Custom Pallets -## Kusama Network +FRAME provides a comprehensive library of [pre-built pallets](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame){target=\_blank} for common blockchain features, including consensus, staking, balances, governance, and more. These pallets are battle-tested, optimized, and ready to use. -Kusama is the experimental version of Polkadot, designed for developers who want to move quickly and test their applications in a real-world environment with economic incentives. Kusama serves as a production-grade testing ground where developers can deploy features and upgrades with the pressure of game theory and economics in mind. It mirrors Polkadot but operates as a more flexible space for innovation. +However, you're not limited to pre-built functionality. When pre-built pallets don't meet your needs, you can create custom pallets with entirely custom logic. The real power of FRAME is the flexibility to use pre-built modules for standard features while building your own for unique requirements. -The native token for Kusama is KSM. For more information about KSM, visit the [Native Assets](https://wiki.polkadot.com/kusama/kusama-getting-started/){target=\_blank} page. +### Pallet Structure -## Test Networks +FRAME uses Rust macros extensively, allowing you to focus on your pallet's logic while the framework handles boilerplate and integration code. -The following test networks provide controlled environments for testing upgrades and new features. TestNet tokens are available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}. +A typical pallet looks like this: -### Westend +```rust +pub use pallet::*; -Westend is Polkadot's primary permanent TestNet. Unlike temporary test networks, Westend is not reset to the genesis block, making it an ongoing environment for testing Polkadot core features. Managed by Parity Technologies, Westend ensures that developers can test features in a real-world simulation without using actual tokens. +#[frame_support::pallet] +pub mod pallet { + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; -The native token for Westend is WND. More details about WND can be found on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_2){target=\_blank} page. + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(_); -### Paseo + #[pallet::config] // snip + #[pallet::event] // snip + #[pallet::error] // snip + #[pallet::storage] // snip + #[pallet::call] // snip +} +``` -[Paseo](https://github.com/paseo-network){target=\_blank} is a community-managed TestNet designed for parachain and dApp developers. It mirrors Polkadot's runtime and is maintained by Polkadot community members. Paseo provides a dedicated space for parachain developers to test their applications in a Polkadot-like environment without the risks associated with live networks. +Every pallet can implement these core macros: -The native token for Paseo is PAS. Additional information on PAS is available on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_1){target=\_blank} page. +- **`#[frame_support::pallet]`**: Marks your module as a FRAME pallet. +- **`#[pallet::pallet]`**: Designates the struct that holds pallet metadata. +- **`#[pallet::config]`**: Defines configuration and associated types. +- **`#[pallet::event]`**: Defines events emitted by your pallet. +- **`#[pallet::error]`**: Defines error types your pallet can return. +- **`#[pallet::storage]`**: Defines on-chain storage items. +- **`#[pallet::call]`**: Defines dispatchable functions (transactions). -## Local Test Networks +For a comprehensive reference, see the [`pallet_macros` documentation](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/index.html){target=\_blank}. -Local test networks are an essential part of the development cycle for blockchain developers using the Polkadot SDK. They allow for fast, iterative testing in controlled, private environments without connecting to public TestNets. Developers can quickly spin up local instances to experiment, debug, and validate their code before deploying to larger TestNets like Westend or Paseo. Two key tools for local network testing are Zombienet and Chopsticks. +## How Runtime Customization Works -### Zombienet +Customizing your runtime typically follows these patterns: -[Zombienet](https://github.com/paritytech/zombienet){target=\_blank} is a flexible testing framework for Polkadot SDK-based blockchains. It enables developers to create and manage ephemeral, short-lived networks. This feature makes Zombienet particularly useful for quick iterations, as it allows you to run multiple local networks concurrently, mimicking different runtime conditions. Whether you're developing a parachain or testing your custom blockchain logic, Zombienet gives you the tools to automate local testing. +**Adding Pre-Built Pallets**: Select pallets from the FRAME library and integrate them into your runtime configuration. This is the fastest way to add functionality. -Key features of Zombienet include: +**Creating Custom Pallets**: Write custom pallets for features that don't exist in the pre-built library. Custom pallets follow the same structure as pre-built ones and integrate seamlessly. -- Creating dynamic, local networks with different configurations. -- Running parachains and relay chains in a simulated environment. -- Efficient testing of network components like cross-chain messaging and governance. +**Combining Multiple Pallets**: Layer multiple pallets together to create complex behaviors. Pallets can call each other and share storage when needed. -Zombienet is ideal for developers looking to test quickly and thoroughly before moving to more resource-intensive public TestNets. +**Configuring Pallet Parameters**: Most pallets are configurable—you can adjust their behavior through configuration traits without modifying their code. -### Chopsticks +The following diagram illustrates how pallets combine to form a complete runtime: -[Chopsticks](https://github.com/AcalaNetwork/chopsticks){target=\_blank} is a tool designed to create forks of Polkadot SDK-based blockchains, allowing developers to interact with network forks as part of their testing process. This capability makes Chopsticks a powerful option for testing upgrades, runtime changes, or cross-chain applications in a forked network environment. +![](/images/parachains/customize-runtime/index/frame-overview-02.webp) -Key features of Chopsticks include: +## Starting Templates -- Forking live Polkadot SDK-based blockchains for isolated testing. -- Simulating cross-chain messages in a private, controlled setup. -- Debugging network behavior by interacting with the fork in real-time. +The easiest way to begin customizing your runtime is with a starter template. These templates provide a pre-configured foundation so you can focus on customization rather than setup. -Chopsticks provides a controlled environment for developers to safely explore the effects of runtime changes. It ensures that network behavior is tested and verified before upgrades are deployed to live networks. +- **[Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank}**: The recommended choice for most developers, it includes pre-configured pallets for common features (balances, block production, governance), a complete runtime setup, and built-in parachain consensus support. This template offers the best balance of features and learning opportunities. +- **[Polkadot SDK Minimal Template](https://github.com/paritytech/polkadot-sdk-minimal-template){target=\_blank}**: Provides a bare-bones runtime with only essential components. Choose this if you want maximum flexibility and prefer building from a clean slate. ---- +- **[Polkadot SDK Solochain Template](https://github.com/paritytech/polkadot-sdk/tree/master/templates/solochain){target=\_blank}**: Designed for building standalone blockchains with moderate features, simple consensus, and several core pallets. Use this if you want a sovereign blockchain independent of a relay chain. -Page Title: Node and Runtime - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-node-and-runtime.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/node-and-runtime/ -- Summary: Learn how Polkadot SDK-based nodes function, how the client and runtime are separated, and how they communicate using SCALE-encoded data. - -# Node and Runtime - -## Introduction - -Every blockchain platform relies on a decentralized network of computers, called nodes, that communicate with each other about transactions and blocks. In this context, a node refers to the software running on the connected devices rather than the physical or virtual machines in the network. - -Polkadot SDK-based nodes consist of two main components, each with distinct responsibilities: the client (also called node) and the runtime. - -If the system were a monolithic protocol, any modification would require updating the entire system. Instead, Polkadot achieves true upgradeability by defining an immutable meta-protocol (the client) and a protocol (the runtime) that can be upgraded independently. - -This separation gives the [Polkadot Relay Chain](/polkadot-protocol/architecture/polkadot-chain){target=\_blank} and all connected [parachains](/polkadot-protocol/architecture/parachains){target=\_blank} an evolutionary advantage over other blockchain platforms. - -## Architectural Principles - -The Polkadot SDK-based blockchain architecture is fundamentally built on two distinct yet interconnected components: - -- Client (Meta-protocol): - - Handles the foundational infrastructure of the blockchain. - - Manages runtime execution, networking, consensus, and other off-chain components. - - Provides an immutable base layer that ensures network stability. - - Upgradable only through hard forks. - -- Runtime (Protocol): - - Defines the blockchain's state transition logic. - - Determines the specific rules and behaviors of the blockchain. - - Compiled to WebAssembly (Wasm) for platform-independent execution. - - Capable of being upgraded without network-wide forking. - -### Advantages of this Architecture - -- **Forkless upgrades**: Runtime can be updated without disrupting the entire network. -- **Modularity**: Clear separation allows independent development of client and runtime. -- **Flexibility**: Enables rapid iteration and evolution of blockchain logic. -- **Performance**: WebAssembly compilation provides efficient, cross-platform execution. - -## Node (Client) - -The node, also known as the client, is the core component responsible for executing the Wasm runtime and orchestrating various essential blockchain components. It ensures the correct execution of the state transition function and manages multiple critical subsystems, including: - -- **Wasm execution**: Runs the blockchain runtime, which defines the state transition rules. -- **Database management**: Stores blockchain data. -- **Networking**: Facilitates peer-to-peer communication, block propagation, and transaction gossiping. -- **Transaction pool (Mempool)**: Manages pending transactions before they are included in a block. -- **Consensus mechanism**: Ensures agreement on the blockchain state across nodes. -- **RPC services**: Provides external interfaces for applications and users to interact with the node. - -## Runtime - -The runtime is more than just a set of rules. It's the fundamental logic engine that defines a blockchain's entire behavior. In Polkadot SDK-based blockchains, the runtime represents a complete, self-contained description of the blockchain's state transition function. - -### Characteristics - -The runtime is distinguished by three key characteristics: - -- **Business logic**: Defines the complete application-specific blockchain behavior. -- **WebAssembly compilation**: Ensures platform-independent, secure execution. -- **On-chain storage**: Stored within the blockchain's state, allowing dynamic updates. - -### Key Functions - -The runtime performs several critical functions, such as: - -- Define state transition rules. -- Implement blockchain-specific logic. -- Manage account interactions. -- Control transaction processing. -- Define governance mechanisms. -- Handle custom pallets and modules. - -## Communication Between Node and Runtime - -The client and runtime communicate exclusively using [SCALE-encoded](/polkadot-protocol/parachain-basics/data-encoding){target=\_blank} communication. This ensures efficient and compact data exchange between the two components. - -### Runtime APIs - -The Runtime API consists of well-defined functions and constants a client assumes are implemented in the Runtime Wasm blob. These APIs enable the client to interact with the runtime to execute blockchain operations and retrieve information. The client invokes these APIs to: - -- Build, execute, and finalize blocks. -- Access metadata. -- Access consensus related information. -- Handle transaction execution. - -### Host Functions - -During execution, the runtime can access certain external client functionalities via host functions. The specific functions the client exposes allow the runtime to perform operations outside the WebAssembly domain. Host functions enable the runtime to: - -- Perform cryptographic operations. -- Access the current blockchain state. -- Handle storage modifications. -- Allocate memory. - - ---- - -Page Title: On-Chain Governance Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-governance.md -- Canonical (HTML): https://docs.polkadot.com/reference/governance/ -- Summary: Discover Polkadot’s cutting-edge OpenGov system, enabling transparent, decentralized decision-making through direct democracy and flexible governance tracks. - -# On-Chain Governance - -## Introduction - -Polkadot’s governance system exemplifies decentralized decision-making, empowering its community of stakeholders to shape the network’s future through active participation. The latest evolution, OpenGov, builds on Polkadot’s foundation by providing a more inclusive and efficient governance model. - -This guide will explain the principles and structure of OpenGov and walk you through its key components, such as Origins, Tracks, and Delegation. You will learn about improvements over earlier governance systems, including streamlined voting processes and enhanced stakeholder participation. - -With OpenGov, Polkadot achieves a flexible, scalable, and democratic governance framework that allows multiple proposals to proceed simultaneously, ensuring the network evolves in alignment with its community's needs. - -## Governance Evolution - -Polkadot’s governance journey began with [Governance V1](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#governance-summary){target=\_blank}, a system that proved effective in managing treasury funds and protocol upgrades. However, it faced limitations, such as: - -- Slow voting cycles, causing delays in decision-making. -- Inflexibility in handling multiple referendums, restricting scalability. - -To address these challenges, Polkadot introduced OpenGov, a governance model designed for greater inclusivity, efficiency, and scalability. OpenGov replaces the centralized structures of Governance V1, such as the Council and Technical Committee, with a fully decentralized and dynamic framework. - -For a full comparison of the historic and current governance models, visit the [Gov1 vs. Polkadot OpenGov](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#gov1-vs-polkadot-opengov){target=\_blank} section of the Polkadot Wiki. - -## OpenGov Key Features - -OpenGov transforms Polkadot’s governance into a decentralized, stakeholder-driven model, eliminating centralized decision-making bodies like the Council. Key enhancements include: - -- **Decentralization**: Shifts all decision-making power to the public, ensuring a more democratic process. -- **Enhanced delegation**: Allows users to delegate their votes to trusted experts across specific governance tracks. -- **Simultaneous referendums**: Multiple proposals can progress at once, enabling faster decision-making. -- **Polkadot Technical Fellowship**: A broad, community-driven group replacing the centralized Technical Committee. - -This new system ensures Polkadot governance remains agile and inclusive, even as the ecosystem grows. - -## Origins and Tracks - -In OpenGov, origins and tracks are central to managing proposals and votes. - -- **Origin**: Determines the authority level of a proposal (e.g., Treasury, Root) which decides the track of all referendums from that origin. -- **Track**: Define the procedural flow of a proposal, such as voting duration, approval thresholds, and enactment timelines. - -Developers must be aware that referendums from different origins and tracks will take varying amounts of time to reach approval and enactment. The [Polkadot Technical Fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} has the option to shorten this timeline by whitelisting a proposal and allowing it to be enacted through the [Whitelist Caller](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#whitelisted-caller){target=\_blank} origin. - -Visit [Origins and Tracks Info](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#origins-and-tracks){target=\_blank} for details on current origins and tracks, associated terminology, and parameters. - -## Referendums - -In OpenGov, anyone can submit a referendum, fostering an open and participatory system. The timeline for a referendum depends on the privilege level of the origin with more significant changes offering more time for community voting and participation before enactment. - -The timeline for an individual referendum includes four distinct periods: - -- **Lead-in**: A minimum amount of time to allow for community participation, available room in the origin, and payment of the decision deposit. Voting is open during this period. -- **Decision**: Voting continues. -- **Confirmation**: Referendum must meet [approval and support](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#approval-and-support){target=\_blank} criteria during entire period to avoid rejection. -- **Enactment**: Changes approved by the referendum are executed. - -### Vote on Referendums - -Voters can vote with their tokens on each referendum. Polkadot uses a voluntary token locking mechanism, called conviction voting, as a way for voters to increase their voting power. A token holder signals they have a stronger preference for approving a proposal based upon their willingness to lock up tokens. Longer voluntary token locks are seen as a signal of continual approval and translate to increased voting weight. - -See [Voting on a Referendum](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank} for a deeper look at conviction voting and related token locks. - -### Delegate Voting Power - -The OpenGov system also supports multi-role delegations, allowing token holders to assign their voting power on different tracks to entities with expertise in those areas. - -For example, if a token holder lacks the technical knowledge to evaluate proposals on the [Root track](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#root){target=\_blank}, they can delegate their voting power for that track to an expert they trust to vote in the best interest of the network. This ensures informed decision-making across tracks while maintaining flexibility for token holders. - -Visit [Multirole Delegation](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#multirole-delegation){target=\_blank} for more details on delegating voting power. - -### Cancel a Referendum - -Polkadot OpenGov has two origins for rejecting ongoing referendums: - -- [**Referendum Canceller**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-canceller){target=\_blank}: Cancels an active referendum when non-malicious errors occur and refunds the deposits to the originators. -- [**Referendum Killer**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-killer){target=\_blank}: Used for urgent, malicious cases this origin instantly terminates an active referendum and slashes deposits. - -See [Cancelling, Killing, and Blacklisting](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#cancelling-killing--blacklisting){target=\_blank} for additional information on rejecting referendums. - -## Additional Resources - -- **[Democracy pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/democracy/src){target=\_blank}**: Handles administration of general stakeholder voting. -- **[Gov2: Polkadot’s Next Generation of Decentralised Governance](https://medium.com/polkadot-network/gov2-polkadots-next-generation-of-decentralised-governance-4d9ef657d11b){target=\_blank}**: Medium article by Gavin Wood. -- **[Polkadot Direction](https://matrix.to/#/#Polkadot-Direction:parity.io){target=\_blank}**: Matrix Element client. -- **[Polkassembly](https://polkadot.polkassembly.io/){target=\_blank}**: OpenGov dashboard and UI. -- **[Polkadot.js Apps Governance](https://polkadot.js.org/apps/#/referenda){target=\_blank}**: Overview of active referendums. - - ---- - -Page Title: Overview of FRAME - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime.md -- Canonical (HTML): https://docs.polkadot.com/parachains/customize-runtime/ -- Summary: Learn how Polkadot SDK’s FRAME framework simplifies blockchain development with modular pallets and support libraries for efficient runtime design. - -# Customize Your Runtime - -## Introduction - -A blockchain runtime is more than just a fixed set of rules—it's a dynamic foundation that you can shape to match your specific needs. With Polkadot SDK's [FRAME (Framework for Runtime Aggregation of Modularized Entities)](/reference/glossary/#frame-framework-for-runtime-aggregation-of-modularized-entities){target=\_blank}, customizing your runtime is straightforward and modular. Instead of building everything from scratch, you combine pre-built pallets with your own custom logic to create a runtime suited to your blockchain's purpose. - -This overview explains how runtime customization works, introduces the building blocks you'll use, and guides you through the key patterns for extending your runtime. - -## Understanding Your Runtime - -The runtime is the core logic of your blockchain—it processes transactions, manages state, and enforces the rules that govern your network. When a transaction arrives at your blockchain, the [`frame_executive`](https://paritytech.github.io/polkadot-sdk/master/frame_executive/index.html){target=\_blank} pallet receives it and routes it to the appropriate pallet for execution. - -Think of your runtime as a collection of specialized modules, each handling a different aspect of your blockchain. Need token balances? Use the Balances pallet. Want governance? Add the Governance pallets. Need something custom? Create your own pallet. By mixing and matching these modules, you build a runtime that's efficient, secure, and tailored to your use case. - -## Runtime Architecture - -The following diagram shows how FRAME components work together to form your runtime: - -![](/images/parachains/customize-runtime/index/frame-overview-01.webp) - -The main components are: - -- **`frame_executive`**: Routes all incoming transactions to the correct pallet for execution. -- **Pallets**: Domain-specific modules that implement your blockchain's features and business logic. -- **`frame_system`**: Provides core runtime primitives and storage. -- **`frame_support`**: Utilities and macros that simplify pallet development. - -## Building Blocks: Pallets - -[Pallets](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/pallet/index.html){target=\_blank} are the fundamental units of runtime customization. Each pallet encapsulates specific functionality and can be independently developed, tested, and integrated. - -A pallet can implement virtually any blockchain feature you need: - -- Expose new transactions that users can submit. -- Store data on-chain. -- Enforce business rules and validation logic. -- Emit events to notify users of state changes. -- Handle errors gracefully. - -### Pre-Built Pallets vs. Custom Pallets - -FRAME provides a comprehensive library of [pre-built pallets](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame){target=\_blank} for common blockchain features, including consensus, staking, balances, governance, and more. These pallets are battle-tested, optimized, and ready to use. - -However, you're not limited to pre-built functionality. When pre-built pallets don't meet your needs, you can create custom pallets with entirely custom logic. The real power of FRAME is the flexibility to use pre-built modules for standard features while building your own for unique requirements. - -### Pallet Structure - -FRAME uses Rust macros extensively, allowing you to focus on your pallet's logic while the framework handles boilerplate and integration code. - -A typical pallet looks like this: - -```rust -pub use pallet::*; - -#[frame_support::pallet] -pub mod pallet { - use frame_support::pallet_prelude::*; - use frame_system::pallet_prelude::*; - - #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] - pub struct Pallet(_); - - #[pallet::config] // snip - #[pallet::event] // snip - #[pallet::error] // snip - #[pallet::storage] // snip - #[pallet::call] // snip -} -``` - -Every pallet can implement these core macros: - -- **`#[frame_support::pallet]`**: Marks your module as a FRAME pallet. -- **`#[pallet::pallet]`**: Designates the struct that holds pallet metadata. -- **`#[pallet::config]`**: Defines configuration and associated types. -- **`#[pallet::event]`**: Defines events emitted by your pallet. -- **`#[pallet::error]`**: Defines error types your pallet can return. -- **`#[pallet::storage]`**: Defines on-chain storage items. -- **`#[pallet::call]`**: Defines dispatchable functions (transactions). - -For a comprehensive reference, see the [`pallet_macros` documentation](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/index.html){target=\_blank}. - -## How Runtime Customization Works - -Customizing your runtime typically follows these patterns: - -**Adding Pre-Built Pallets**: Select pallets from the FRAME library and integrate them into your runtime configuration. This is the fastest way to add functionality. - -**Creating Custom Pallets**: Write custom pallets for features that don't exist in the pre-built library. Custom pallets follow the same structure as pre-built ones and integrate seamlessly. - -**Combining Multiple Pallets**: Layer multiple pallets together to create complex behaviors. Pallets can call each other and share storage when needed. - -**Configuring Pallet Parameters**: Most pallets are configurable—you can adjust their behavior through configuration traits without modifying their code. - -The following diagram illustrates how pallets combine to form a complete runtime: - -![](/images/parachains/customize-runtime/index/frame-overview-02.webp) - -## Starting Templates - -The easiest way to begin customizing your runtime is with a starter template. These templates provide a pre-configured foundation so you can focus on customization rather than setup. - -- **[Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank}**: The recommended choice for most developers, it includes pre-configured pallets for common features (balances, block production, governance), a complete runtime setup, and built-in parachain consensus support. This template offers the best balance of features and learning opportunities. - -- **[Polkadot SDK Minimal Template](https://github.com/paritytech/polkadot-sdk-minimal-template){target=\_blank}**: Provides a bare-bones runtime with only essential components. Choose this if you want maximum flexibility and prefer building from a clean slate. - -- **[Polkadot SDK Solochain Template](https://github.com/paritytech/polkadot-sdk/tree/master/templates/solochain){target=\_blank}**: Designed for building standalone blockchains with moderate features, simple consensus, and several core pallets. Use this if you want a sovereign blockchain independent of a relay chain. - -- **[OpenZeppelin Runtime Templates](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\_blank}**: Provides security-focused configurations following industry best practices. The [generic-template](https://github.com/OpenZeppelin/polkadot-runtime-templates/tree/main/generic-template){target=\_blank} includes curated pallet selections and production-ready defaults—ideal if security is your top priority. - -## Key Customization Scenarios - -This section covers the most common customization patterns you'll encounter: - -- **[Add Existing Pallets to Your Runtime](/parachains/customize-runtime/add-existing-pallets/)**: Integrate pre-built pallets from the FRAME library with minimal configuration. - -- **[Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/)**: Run multiple instances of the same pallet with different configurations—useful for multi-token systems or parallel features. - -- **[Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/)**: Enable smart contract execution on your parachain using Contracts pallets. - -- **[Create Custom Pallets](/parachains/customize-runtime/pallet-development/create-a-pallet/)**: Build entirely custom pallets for features unique to your blockchain. - -- **[Test Your Runtime](/parachains/customize-runtime/pallet-development/pallet-testing/)**: Unit test pallets and mock complete runtimes to ensure everything works correctly. - - ---- - -Page Title: Overview of the Polkadot Relay Chain - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-relay-chain.md -- Canonical (HTML): https://docs.polkadot.com/reference/polkadot-hub/consensus-and-security/relay-chain/ -- Summary: Explore Polkadot's core architecture, including its multi-chain vision, shared security, and the DOT token's governance and staking roles. - -# Overview - -## Introduction - -Polkadot is a next-generation blockchain protocol designed to support a multi-chain future by enabling secure communication and interoperability between different blockchains. Built as a Layer-0 protocol, Polkadot introduces innovations like application-specific Layer-1 chains ([parachains](/polkadot-protocol/architecture/parachains/){targe=\_blank}), shared security through [Nominated Proof of Stake (NPoS)](/reference/glossary/#nominated-proof-of-stake-npos){target=\_blank}, and cross-chain interactions via its native [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank}. - -This guide covers key aspects of Polkadot’s architecture, including its high-level protocol structure, blockspace commoditization, and the role of its native token, DOT, in governance, staking, and resource allocation. - -## Polkadot 1.0 - -Polkadot 1.0 represents the state of Polkadot as of 2023, coinciding with the release of [Polkadot runtime v1.0.0](https://github.com/paritytech/polkadot/releases/tag/v1.0.0){target=\_blank}. This section will focus on Polkadot 1.0, along with philosophical insights into network resilience and blockspace. - -As a Layer-0 blockchain, Polkadot contributes to the multi-chain vision through several key innovations and initiatives, including: - -- **Application-specific Layer-1 blockchains (parachains)**: Polkadot's sharded network allows for parallel transaction processing, with shards that can have unique state transition functions, enabling custom-built L1 chains optimized for specific applications. - -- **Shared security and scalability**: L1 chains connected to Polkadot benefit from its [Nominated Proof of Stake (NPoS)](/reference/polkadot-hub/consensus-and-security/pos-consensus/#nominated-proof-of-stake){target=\_blank} system, providing security out-of-the-box without the need to bootstrap their own. - -- **Secure interoperability**: Polkadot's native interoperability enables seamless data and value exchange between parachains. This interoperability can also be used outside of the ecosystem for bridging with external networks. - -- **Resilient infrastructure**: Decentralized and scalable, Polkadot ensures ongoing support for development and community initiatives via its on-chain [treasury](https://wiki.polkadot.com/learn/learn-polkadot-opengov-treasury/){target=\_blank} and governance. - -- **Rapid L1 development**: The [Polkadot SDK](/reference/parachains/){target=\_blank} allows fast, flexible creation and deployment of Layer-1 chains. - -- **Cultivating the next generation of Web3 developers**: Polkadot supports the growth of Web3 core developers through initiatives such as. - - - [Polkadot Blockchain Academy](https://polkadot.com/blockchain-academy){target=\_blank} - - [EdX courses](https://www.edx.org/school/web3x){target=\_blank} - - Rust and Substrate courses (coming soon) - -### High-Level Architecture - -Polkadot features a chain that serves as the central component of the system. This chain is depicted as a ring encircled by several parachains that are connected to it. - -According to Polkadot's design, any blockchain that can compile to WebAssembly (Wasm) and adheres to the Parachains Protocol becomes a parachain on the Polkadot network. - -Here’s a high-level overview of the Polkadot protocol architecture: - -![](/images/reference/polkadot-hub/consensus-and-security/relay-chain/relay-chain-01.webp){ style="background:white" } - -Parachains propose blocks to Polkadot validators, who check for availability and validity before finalizing them. With the relay chain providing security, collators—full nodes of parachains—can focus on their tasks without needing strong incentives. - -The [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank} allows parachains to exchange messages freely, leveraging the chain's security for trust-free communication. - -In order to interact with chains that want to use their own finalization process (e.g., Bitcoin), Polkadot has [bridges](/reference/parachains/interoperability/#bridges-connecting-external-networks){target=\_blank} that offer two-way compatibility, meaning that transactions can be made between different parachains. - -### Polkadot's Additional Functionalities - -Historically, obtaining core slots on Polkadot chain relied upon crowdloans and auctions. Chain cores were leased through auctions for three-month periods, up to a maximum of two years. Crowdloans enabled users to securely lend funds to teams for lease deposits in exchange for pre-sale tokens, which is the only way to access slots on Polkadot 1.0. Auctions are now deprecated in favor of [coretime](/polkadot-protocol/architecture/system-chains/coretime/){target=\_blank}. - -Additionally, the chain handles [staking](https://wiki.polkadot.com/learn/learn-staking/){target=\_blank}, [accounts](/reference/parachains/accounts/){target=\_blank}, balances, and [governance](/reference/governance/){target=\_blank}. - -#### Agile Coretime - -The new and more efficient way of obtaining core on Polkadot is to go through the process of purchasing coretime. - -[Agile coretime](/reference/polkadot-hub/consensus-and-security/agile-coretime/){target=\_blank} improves the efficient use of Polkadot's network resources and offers economic flexibility for developers, extending Polkadot's capabilities far beyond the original vision outlined in the [whitepaper](https://polkadot.com/papers/Polkadot-whitepaper.pdf){target=\_blank}. - -It enables parachains to purchase monthly "bulk" allocations of coretime (the time allocated for utilizing a core, measured in Polkadot relay chain blocks), ensuring heavy-duty parachains that can author a block every six seconds with [Asynchronous Backing](https://wiki.polkadot.com/learn/learn-async-backing/#asynchronous-backing){target=\_blank} can reliably renew their coretime each month. Although six-second block times are now the default, parachains have the option of producing blocks less frequently. - -Renewal orders are prioritized over new orders, offering stability against price fluctuations and helping parachains budget more effectively for project costs. - -### Polkadot's Resilience - -Decentralization is a vital component of blockchain networks, but it comes with trade-offs: - -- An overly decentralized network may face challenges in reaching consensus and require significant energy to operate. -- Also, a network that achieves consensus quickly risks centralization, making it easier to manipulate or attack. - -A network should be decentralized enough to prevent manipulative or malicious influence. In this sense, decentralization is a tool for achieving resilience. - -Polkadot 1.0 currently achieves resilience through several strategies: - -- **Nominated Proof of Stake (NPoS)**: Ensures that the stake per validator is maximized and evenly distributed among validators. - -- **Decentralized nodes**: Designed to encourage operators to join the network. This program aims to expand and diversify the validators in the ecosystem who aim to become independent of the program during their term. Feel free to explore more about the program on the official [Decentralized Nodes](https://nodes.web3.foundation/){target=\_blank} page. - -- **On-chain treasury and governance**: Known as [OpenGov](/reference/governance/){target=\_blank}, this system allows every decision to be made through public referenda, enabling any token holder to cast a vote. - -### Polkadot's Blockspace - -Polkadot 1.0’s design allows for the commoditization of blockspace. - -Blockspace is a blockchain's capacity to finalize and commit operations, encompassing its security, computing, and storage capabilities. Its characteristics can vary across different blockchains, affecting security, flexibility, and availability. - -- **Security**: Measures the robustness of blockspace in Proof of Stake (PoS) networks linked to the stake locked on validator nodes, the variance in stake among validators, and the total number of validators. It also considers social centralization (how many validators are owned by single operators) and physical centralization (how many validators run on the same service provider). - -- **Flexibility**: Reflects the functionalities and types of data that can be stored, with high-quality data essential to avoid bottlenecks in critical processes. - -- **Availability**: Indicates how easily users can access blockspace. It should be easily accessible, allowing diverse business models to thrive, ideally regulated by a marketplace based on demand and supplemented by options for "second-hand" blockspace. - -Polkadot is built on core blockspace principles, but there's room for improvement. Tasks like balance transfers, staking, and governance are managed on the relay chain. - -Delegating these responsibilities to [system chains](/polkadot-protocol/architecture/system-chains/){target=\_blank} could enhance flexibility and allow the relay chain to concentrate on providing shared security and interoperability. - -For more information about blockspace, watch [Robert Habermeier’s interview](https://www.youtube.com/watch?v=e1vISppPwe4){target=\_blank} or read his [technical blog post](https://www.rob.tech/blog/polkadot-blockspace-over-blockchains/){target=\_blank}. - -## DOT Token - -DOT is the native token of the Polkadot network, much like BTC for Bitcoin and Ether for the Ethereum blockchain. DOT has 10 decimals, uses the Planck base unit, and has a balance type of `u128`. The same is true for Kusama's KSM token with the exception of having 12 decimals. - -### Redenomination of DOT - -Polkadot conducted a community poll, which ended on 27 July 2020 at block 888,888, to decide whether to redenominate the DOT token. The stakeholders chose to redenominate the token, changing the value of 1 DOT from 1e12 plancks to 1e10 plancks. - -Importantly, this did not affect the network's total number of base units (plancks); it only affects how a single DOT is represented. The redenomination became effective 72 hours after transfers were enabled, occurring at block 1,248,328 on 21 August 2020 around 16:50 UTC. - -### The Planck Unit - -The smallest unit of account balance on Polkadot SDK-based blockchains (such as Polkadot and Kusama) is called _Planck_, named after the Planck length, the smallest measurable distance in the physical universe. - -Similar to how BTC's smallest unit is the Satoshi and ETH's is the Wei, Polkadot's native token DOT equals 1e10 Planck, while Kusama's native token KSM equals 1e12 Planck. - -### Uses for DOT - -DOT serves three primary functions within the Polkadot network: - -- **Governance**: It is used to participate in the governance of the network. -- **Staking**: DOT is staked to support the network's operation and security. -- **Buying coretime**: Used to purchase coretime in-bulk or on-demand and access the chain to benefit from Polkadot's security and interoperability. - -Additionally, DOT can serve as a transferable token. For example, DOT, held in the treasury, can be allocated to teams developing projects that benefit the Polkadot ecosystem. - -## JAM and the Road Ahead - -The Join-Accumulate Machine (JAM) represents a transformative redesign of Polkadot's core architecture, envisioned as the successor to the current relay chain. Unlike traditional blockchain architectures, JAM introduces a unique computational model that processes work through two primary functions: - -- **Join**: Handles data integration. -- **Accumulate**: Folds computations into the chain's state. - -JAM removes many of the opinions and constraints of the current relay chain while maintaining its core security properties. Expected improvements include: - -- **Permissionless code execution**: JAM is designed to be more generic and flexible, allowing for permissionless code execution through services that can be deployed without governance approval. -- **More effective block time utilization**: JAM's efficient pipeline processing model places the prior state root in block headers instead of the posterior state root, enabling more effective utilization of block time for computations. - -This architectural evolution promises to enhance Polkadot's scalability and flexibility while maintaining robust security guarantees. JAM is planned to be rolled out to Polkadot as a single, complete upgrade rather than a stream of smaller updates. This approach seeks to minimize the developer overhead required to address any breaking changes. - - ---- - -Page Title: Parachains Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/ -- Summary: Learn about parachains, specialized blockchains on Polkadot that gain shared security and interoperability. Discover how they work and the tools to build them. - -# Parachains Overview - -## Introduction - -A parachain is a specialized blockchain that connects to the Polkadot relay chain, benefiting from shared security, interoperability, and scalability. Parachains are built using the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}, a powerful toolkit written in Rust that provides everything needed to create custom blockchain logic while integrating seamlessly with the Polkadot network. - -Unlike standalone blockchains that must bootstrap their own validator sets and security, parachains leverage Polkadot's pooled security model. This allows parachain developers to focus on their application-specific functionality rather than consensus and security infrastructure. Parachains can communicate with each other through Cross-Consensus Messaging (XCM), enabling seamless interoperability across the Polkadot ecosystem. - -Key capabilities that parachains provide include: - -- **Shared security**: Inherit security from Polkadot's validator set without maintaining your own. -- **Interoperability**: Communicate trustlessly with other parachains via XCM. -- **Scalability**: Process transactions in parallel with other parachains. -- **Customization**: Build application-specific logic tailored to your use case. -- **Upgradeability**: Upgrade runtime logic without hard forks. - -## Polkadot SDK: Parachain Architecture - -Building a parachain involves understanding and utilizing several key components of the Polkadot SDK: - -![](/images/reference/parachains/index/overview-01.webp) - -- **[Substrate](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/substrate/index.html){target=\_blank}**: The foundation providing core blockchain primitives and libraries. -- **[FRAME](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank}**: A modular framework for building your parachain's runtime logic. -- **[Cumulus](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/cumulus/index.html){target=\_blank}**: Essential libraries and pallets that enable parachain functionality. -- **[XCM (Cross Consensus Messaging)](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/xcm/index.html){target=\_blank}**: The messaging format for communicating with other parachains and the relay chain. -- **[Polkadot](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/polkadot/index.html){target=\_blank}**: The relay chain that provides security and coordination. - -### Substrate: The Foundation - -Substrate provides the core infrastructure that every parachain is built upon. It handles the low-level blockchain functionality, allowing you to focus on your application's unique features. Substrate includes implementations for networking, database management, consensus participation, and the execution environment for your runtime. - -Every Polkadot SDK node consists of two main components: - -- **Client (Host)**: Handles infrastructure services. - - - Native binary that runs on validator and collator nodes. - - Executes the Wasm-compiled runtime. - - Manages networking, database, mempool, and block production. - - Interfaces with the relay chain for validation. - -- **Runtime (State Transition Function)**: Contains your business logic. - - - Defines how your Polkadot SDK node processes transactions. - - Compiled to [Wasm](https://webassembly.org/){target=\_blank} for deterministic execution. - - Stored on-chain and upgradeable via governance. - -```mermaid -%%{init: {'flowchart': {'padding': 5, 'nodeSpacing': 50, 'rankSpacing': 10}}}%% -graph TB - classDef title font-size:20px,font-weight:bold,stroke-width:0px - classDef clientStyle font-size:16px,font-weight:bold - classDef clientSubNodeStyle margin-top:10px - classDef runtimeCallExecutorStyle padding-top:10px - - subgraph sg1[Parachain
Node] - direction TB - - I[RuntimeCall Executor] - B[Wasm Runtime - STF] - - subgraph sg2[Client] - direction TB - C[Network and Blockchain
Infrastructure Services
+ Relay Chain Interface] - end - - I --> B - end - - class sg1 title - class sg2 clientStyle - class C clientSubNodeStyle - class I runtimeCallExecutorStyle - -``` - -### FRAME: Building Blocks for Your Runtime - -FRAME provides modular components called [pallets](/reference/glossary#pallet){target=\_blank} that you can compose to build your parachain's runtime. Each pallet provides specific functionality that you can customize and configure for your needs. This modular approach allows you to quickly assemble complex functionality without writing everything from scratch. - -```mermaid -graph LR - subgraph SP["Parachain Runtime"] - direction LR - Timestamp ~~~ Aura ~~~ ParachainSystem - Balances ~~~ TransactionPayment ~~~ Sudo - subgraph Timestamp["Timestamp"] - SS1[Custom Config] - end - subgraph Aura["Aura"] - SS2[Custom Config] - end - subgraph ParachainSystem["Parachain System"] - SS3[Custom Config] - end - subgraph Balances["Balances"] - SS4[Custom Config] - end - subgraph TransactionPayment["Transaction Payment"] - SS5[Custom Config] - end - subgraph Sudo["Sudo"] - SS6[Custom Config] - end - style Timestamp stroke:#FF69B4 - style Aura stroke:#FF69B4 - style ParachainSystem stroke:#FF69B4 - style Balances stroke:#FF69B4 - style TransactionPayment stroke:#FF69B4 - style Sudo stroke:#FF69B4 - style SS1 stroke-dasharray: 5 - style SS2 stroke-dasharray: 5 - style SS3 stroke-dasharray: 5 - style SS4 stroke-dasharray: 5 - style SS5 stroke-dasharray: 5 - style SS6 stroke-dasharray: 5 - - end - subgraph AP["Available FRAME Pallets"] - direction LR - A1[Aura]~~~A2[Parachain
System]~~~A3[Transaction
Payment]~~~A4[Sudo] - B1[Identity]~~~B2[Balances]~~~B3[Assets]~~~B4[EVM] - C1[Timestamp]~~~C2[Staking]~~~C3[Contracts]~~~C4[and more...] - end - AP --> SP -``` - -### Cumulus: Parachain-Specific Functionality - -Cumulus is what transforms a Polkadot SDK-based runtime into a parachain-capable runtime. It provides the essential components for communicating with the relay chain, participating in Polkadot's consensus, and handling parachain-specific operations like block validation and collation. - -Key Cumulus components include: - -- **Parachain system pallet**: Core parachain functionality and relay chain communication. -- **Collator consensus**: Block production logic for parachain collators. -- **Relay chain interface**: APIs for interacting with the Polkadot relay chain. -- **Validation data**: Handling proof-of-validity data required by relay chain validators. - -## Where to Go Next - -Building a parachain requires understanding the relationship between your chain and the Polkadot relay chain. The Polkadot SDK provides all the tools needed to design custom runtime logic, enable cross-chain communication, and deploy your parachain to production. - -The following sections provide detailed guidance on each aspect of parachain development, from initial design through deployment and ongoing maintenance. - -
- -- Guide __Launch a Simple Parachain__ - - --- - - Walk through the complete parachain launch flow: from setup and deployment to obtaining coretime. - - [:octicons-arrow-right-24: Deploy](/parachains/launch-a-parachain/set-up-the-parachain-template/) - - -- Guide __Customize Your Runtime__ - - --- - - Design your parachain's runtime logic and choose appropriate pallets for your use case. - - [:octicons-arrow-right-24: Get Started](/parachains/customize-runtime/) - -- Guide __Interoperability__ - - --- - - Implement XCM for trustless cross-chain communication with other parachains. - - [:octicons-arrow-right-24: Learn More](/parachains/interoperability/get-started/) - -- Guide __Runtime Upgrades__ - - --- - - Upgrade your parachain's runtime without hard forks using forkless upgrade mechanisms. - - [:octicons-arrow-right-24: Maintain](/parachains/runtime-maintenance/runtime-upgrades/) - -
- - ---- - -Page Title: Polkadot SDK Accounts - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-accounts.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/accounts/ -- Summary: Learn about account structures, balances, and address formats in the Polkadot SDK, including how to manage lifecycle, references, and balances. - -# Accounts - -## Introduction - -Accounts are essential for managing identity, transactions, and governance on the network in the Polkadot SDK. Understanding these components is critical for seamless development and operation on the network, whether you're building or interacting with Polkadot-based chains. - -This page will guide you through the essential aspects of accounts, including their data structure, balance types, reference counters, and address formats. You’ll learn how accounts are managed within the runtime, how balances are categorized, and how addresses are encoded and validated. - -## Account Data Structure - -Accounts are foundational to any blockchain, and the Polkadot SDK provides a flexible management system. This section explains how the Polkadot SDK defines accounts and manages their lifecycle through data structures within the runtime. - -### Account - -The [`Account` data type](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/type.Account.html){target=\_blank} is a storage map within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank} that links an account ID to its corresponding data. This structure is fundamental for mapping account-related information within the chain. - -The code snippet below shows how accounts are defined: - -```rs - /// The full account information for a particular account ID. - #[pallet::storage] - #[pallet::getter(fn account)] - pub type Account = StorageMap< - _, - Blake2_128Concat, - T::AccountId, - AccountInfo, - ValueQuery, - >; -``` - -The preceding code block defines a storage map named `Account`. The `StorageMap` is a type of on-chain storage that maps keys to values. In the `Account` map, the key is an account ID, and the value is the account's information. Here, `T` represents the generic parameter for the runtime configuration, which is defined by the pallet's configuration trait (`Config`). - -The `StorageMap` consists of the following parameters: - -- **`_`**: Used in macro expansion and acts as a placeholder for the storage prefix type. Tells the macro to insert the default prefix during expansion. -- **`Blake2_128Concat`**: The hashing function applied to keys in the storage map. -- **`T: :AccountId`**: Represents the key type, which corresponds to the account’s unique ID. -- **`AccountInfo`**: The value type stored in the map. For each account ID, the map stores an `AccountInfo` struct containing: - - - **`T::Nonce`**: A nonce for the account, which is incremented with each transaction to ensure transaction uniqueness. - - **`T: :AccountData`**: Custom account data defined by the runtime configuration, which could include balances, locked funds, or other relevant information. - -- **`ValueQuery`**: Defines how queries to the storage map behave when no value is found; returns a default value instead of `None`. - -For a detailed explanation of storage maps, see the [`StorageMap`](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/struct.StorageMap.html){target=\_blank} entry in the Rust docs. - -### Account Info - -The `AccountInfo` structure is another key element within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank}, providing more granular details about each account's state. This structure tracks vital data, such as the number of transactions and the account’s relationships with other modules. - -```rs -/// Information of an account. -#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)] -pub struct AccountInfo { - /// The number of transactions this account has sent. - pub nonce: Nonce, - /// The number of other modules that currently depend on this account's existence. The account - /// cannot be reaped until this is zero. - pub consumers: RefCount, - /// The number of other modules that allow this account to exist. The account may not be reaped - /// until this and `sufficients` are both zero. - pub providers: RefCount, - /// The number of modules that allow this account to exist for their own purposes only. The - /// account may not be reaped until this and `providers` are both zero. - pub sufficients: RefCount, - /// The additional data that belongs to this account. Used to store the balance(s) in a lot of - /// chains. - pub data: AccountData, -} -``` - -The `AccountInfo` structure includes the following components: - -- **`nonce`**: Tracks the number of transactions initiated by the account, which ensures transaction uniqueness and prevents replay attacks. -- **`consumers`**: Counts how many other modules or pallets rely on this account’s existence. The account cannot be removed from the chain (reaped) until this count reaches zero. -- **`providers`**: Tracks how many modules permit this account’s existence. An account can only be reaped once both `providers` and `sufficients` are zero. -- **`sufficients`**: Represents the number of modules that allow the account to exist for internal purposes, independent of any other modules. -- **`AccountData`**: A flexible data structure that can be customized in the runtime configuration, usually containing balances or other user-specific data. - -This structure helps manage an account's state and prevents its premature removal while it is still referenced by other on-chain data or modules. The [`AccountInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.AccountInfo.html){target=\_blank} structure can vary as long as it satisfies the trait bounds defined by the `AccountData` associated type in the [`frame-system::pallet::Config`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/trait.Config.html){target=\_blank} trait. - -### Account Reference Counters - -Polkadot SDK uses reference counters to track an account’s dependencies across different runtime modules. These counters ensure that accounts remain active while data is associated with them. - -The reference counters include: - -- **`consumers`**: Prevents account removal while other pallets still rely on the account. -- **`providers`**: Ensures an account is active before other pallets store data related to it. -- **`sufficients`**: Indicates the account’s independence, ensuring it can exist even without a native token balance, such as when holding sufficient alternative assets. - -#### Providers Reference Counters - -The `providers` counter ensures that an account is ready to be depended upon by other runtime modules. For example, it is incremented when an account has a balance above the existential deposit, which marks the account as active. - -The system requires this reference counter to be greater than zero for the `consumers` counter to be incremented, ensuring the account is stable before any dependencies are added. - -#### Consumers Reference Counters - -The `consumers` counter ensures that the account cannot be reaped until all references to it across the runtime have been removed. This check prevents the accidental deletion of accounts that still have active on-chain data. - -It is the user’s responsibility to clear out any data from other runtime modules if they wish to remove their account and reclaim their existential deposit. - -#### Sufficients Reference Counter - -The `sufficients` counter tracks accounts that can exist independently without relying on a native account balance. This is useful for accounts holding other types of assets, like tokens, without needing a minimum balance in the native token. - -For instance, the [Assets pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_assets/index.html){target=\_blank}, may increment this counter for an account holding sufficient tokens. - -#### Account Deactivation - -In Polkadot SDK-based chains, an account is deactivated when its reference counters (such as `providers`, `consumers`, and `sufficient`) reach zero. These counters ensure the account remains active as long as other runtime modules or pallets reference it. - -When all dependencies are cleared and the counters drop to zero, the account becomes deactivated and may be removed from the chain (reaped). This is particularly important in Polkadot SDK-based blockchains, where accounts with balances below the existential deposit threshold are pruned from storage to conserve state resources. - -Each pallet that references an account has cleanup functions that decrement these counters when the pallet no longer depends on the account. Once these counters reach zero, the account is marked for deactivation. - -#### Updating Counters - -The Polkadot SDK provides runtime developers with various methods to manage account lifecycle events, such as deactivation or incrementing reference counters. These methods ensure that accounts cannot be reaped while still in use. - -The following helper functions manage these counters: - -- **`inc_consumers()`**: Increments the `consumer` reference counter for an account, signaling that another pallet depends on it. -- **`dec_consumers()`**: Decrements the `consumer` reference counter, signaling that a pallet no longer relies on the account. -- **`inc_providers()`**: Increments the `provider` reference counter, ensuring the account remains active. -- **`dec_providers()`**: Decrements the `provider` reference counter, allowing for account deactivation when no longer in use. -- **`inc_sufficients()`**: Increments the `sufficient` reference counter for accounts that hold sufficient assets. -- **`dec_sufficients()`**: Decrements the `sufficient` reference counter. - -To ensure proper account cleanup and lifecycle management, a corresponding decrement should be made for each increment action. - -The `System` pallet offers three query functions to assist developers in tracking account states: - -- **[`can_inc_consumer()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_inc_consumer){target=\_blank}**: Checks if the account can safely increment the consumer reference. -- **[`can_dec_provider()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_dec_provider){target=\_blank}**: Ensures that no consumers exist before allowing the decrement of the provider counter. -- **[`is_provider_required()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.is_provider_required){target=\_blank}**: Verifies whether the account still has any active consumer references. - -This modular and flexible system of reference counters tightly controls the lifecycle of accounts in Polkadot SDK-based blockchains, preventing the accidental removal or retention of unneeded accounts. You can refer to the [System pallet Rust docs](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html){target=\_blank} for more details. - - -## Account Balance Types - -In the Polkadot ecosystem, account balances are categorized into different types based on how the funds are utilized and their availability. These balance types determine the actions that can be performed, such as transferring tokens, paying transaction fees, or participating in governance activities. Understanding these balance types helps developers manage user accounts and implement balance-dependent logic. - -!!! note "A more efficient distribution of account balance types is in development" - Soon, pallets in the Polkadot SDK will implement the [`Fungible` trait](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} (see the [tracking issue](https://github.com/paritytech/polkadot-sdk/issues/226){target=\_blank} for more details). For example, the [`transaction-storage`](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_storage/index.html){target=\_blank} pallet changed the implementation of the [`Currency`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/currency/index.html){target=\_blank} trait (see the [Refactor transaction storage pallet to use fungible traits](https://github.com/paritytech/polkadot-sdk/pull/1800){target=\_blank} PR for further details): - - ```rust - type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; - ``` - - To the [`Fungible`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} trait: - - ```rust - type BalanceOf = <::Currency as FnInspect<::AccountId>>::Balance; - ``` - - This update will enable more efficient use of account balances, allowing the free balance to be utilized for on-chain activities such as setting proxies and managing identities. - -### Balance Types - -The five main balance types are: - -- **Free balance**: Represents the total tokens available to the account for any on-chain activity, including staking, governance, and voting. However, it may not be fully spendable or transferrable if portions of it are locked or reserved. -- **Locked balance**: Portions of the free balance that cannot be spent or transferred because they are tied up in specific activities like [staking](https://wiki.polkadot.com/learn/learn-staking/#nominating-validators){target=\_blank}, [vesting](https://wiki.polkadot.com/learn/learn-guides-transfers/#vested-transfers-with-the-polkadot-js-ui){target=\_blank}, or participating in [governance](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank}. While the tokens remain part of the free balance, they are non-transferable for the duration of the lock. -- **Reserved balance**: Funds locked by specific system actions, such as setting up an [identity](https://wiki.polkadot.com/learn/learn-identity/){target=\_blank}, creating [proxies](https://wiki.polkadot.com/learn/learn-proxies/){target=\_blank}, or submitting [deposits for governance proposals](https://wiki.polkadot.com/learn/learn-guides-polkadot-opengov/#claiming-opengov-deposits){target=\_blank}. These tokens are not part of the free balance and cannot be spent unless they are unreserved. -- **Spendable balance**: The portion of the free balance that is available for immediate spending or transfers. It is calculated by subtracting the maximum of locked or reserved amounts from the free balance, ensuring that existential deposit limits are met. -- **Untouchable balance**: Funds that cannot be directly spent or transferred but may still be utilized for on-chain activities, such as governance participation or staking. These tokens are typically tied to certain actions or locked for a specific period. - -The spendable balance is calculated as follows: - -```text -spendable = free - max(locked - reserved, ED) -``` - -Here, `free`, `locked`, and `reserved` are defined above. The `ED` represents the [existential deposit](https://wiki.polkadot.com/learn/learn-accounts/#existential-deposit-and-reaping){target=\_blank}, the minimum balance required to keep an account active and prevent it from being reaped. You may find you can't see all balance types when looking at your account via a wallet. Wallet providers often display only spendable, locked, and reserved balances. - -### Locks - -Locks are applied to an account's free balance, preventing that portion from being spent or transferred. Locks are automatically placed when an account participates in specific on-chain activities, such as staking or governance. Although multiple locks may be applied simultaneously, they do not stack. Instead, the largest lock determines the total amount of locked tokens. - -Locks follow these basic rules: - -- If different locks apply to varying amounts, the largest lock amount takes precedence. -- If multiple locks apply to the same amount, the lock with the longest duration governs when the balance can be unlocked. - -#### Locks Example - -Consider an example where an account has 80 DOT locked for both staking and governance purposes like so: - -- 80 DOT is staked with a 28-day lock period. -- 24 DOT is locked for governance with a 1x conviction and a 7-day lock period. -- 4 DOT is locked for governance with a 6x conviction and a 224-day lock period. - -In this case, the total locked amount is 80 DOT because only the largest lock (80 DOT from staking) governs the locked balance. These 80 DOT will be released at different times based on the lock durations. In this example, the 24 DOT locked for governance will be released first since the shortest lock period is seven days. The 80 DOT stake with a 28-day lock period is released next. Now, all that remains locked is the 4 DOT for governance. After 224 days, all 80 DOT (minus the existential deposit) will be free and transferable. - -![Illustration of Lock Example](/images/reference/parachains/accounts/accounts-01.webp) - -#### Edge Cases for Locks - -In scenarios where multiple convictions and lock periods are active, the lock duration and amount are determined by the longest period and largest amount. For example, if you delegate with different convictions and attempt to undelegate during an active lock period, the lock may be extended for the full amount of tokens. For a detailed discussion on edge case lock behavior, see this [Stack Exchange post](https://substrate.stackexchange.com/questions/5067/delegating-and-undelegating-during-the-lock-period-extends-it-for-the-initial-am){target=\_blank}. - -### Balance Types on Polkadot.js - -Polkadot.js provides a user-friendly interface for managing and visualizing various account balances on Polkadot and Kusama networks. When interacting with Polkadot.js, you will encounter multiple balance types that are critical for understanding how your funds are distributed and restricted. This section explains how different balances are displayed in the Polkadot.js UI and what each type represents. - -![](/images/reference/parachains/accounts/accounts-02.webp) - -The most common balance types displayed on Polkadot.js are: - -- **Total balance**: The total number of tokens available in the account. This includes all tokens, whether they are transferable, locked, reserved, or vested. However, the total balance does not always reflect what can be spent immediately. In this example, the total balance is 0.6274 KSM. - -- **Transferable balance**: Shows how many tokens are immediately available for transfer. It is calculated by subtracting the locked and reserved balances from the total balance. For example, if an account has a total balance of 0.6274 KSM and a transferable balance of 0.0106 KSM, only the latter amount can be sent or spent freely. - -- **Vested balance**: Tokens that allocated to the account but released according to a specific schedule. Vested tokens remain locked and cannot be transferred until fully vested. For example, an account with a vested balance of 0.2500 KSM means that this amount is owned but not yet transferable. - -- **Locked balance**: Tokens that are temporarily restricted from being transferred or spent. These locks typically result from participating in staking, governance, or vested transfers. In Polkadot.js, locked balances do not stack—only the largest lock is applied. For instance, if an account has 0.5500 KSM locked for governance and staking, the locked balance would display 0.5500 KSM, not the sum of all locked amounts. - -- **Reserved balance**: Refers to tokens locked for specific on-chain actions, such as setting an identity, creating a proxy, or making governance deposits. Reserved tokens are not part of the free balance, but can be freed by performing certain actions. For example, removing an identity would unreserve those funds. - -- **Bonded balance**: The tokens locked for staking purposes. Bonded tokens are not transferable until they are unbonded after the unbonding period. - -- **Redeemable balance**: The number of tokens that have completed the unbonding period and are ready to be unlocked and transferred again. For example, if an account has a redeemable balance of 0.1000 KSM, those tokens are now available for spending. - -- **Democracy balance**: Reflects the number of tokens locked for governance activities, such as voting on referenda. These tokens are locked for the duration of the governance action and are only released after the lock period ends. - -By understanding these balance types and their implications, developers and users can better manage their funds and engage with on-chain activities more effectively. - -## Address Formats - -The SS58 address format is a core component of the Polkadot SDK that enables accounts to be uniquely identified across Polkadot-based networks. This format is a modified version of Bitcoin's Base58Check encoding, specifically designed to accommodate the multi-chain nature of the Polkadot ecosystem. SS58 encoding allows each chain to define its own set of addresses while maintaining compatibility and checksum validation for security. - -### Basic Format - -SS58 addresses consist of three main components: - -```text -base58encode(concat(,
, )) -``` - -- **Address type**: A byte or set of bytes that define the network (or chain) for which the address is intended. This ensures that addresses are unique across different Polkadot SDK-based chains. -- **Address**: The public key of the account encoded as bytes. -- **Checksum**: A hash-based checksum which ensures that addresses are valid and unaltered. The checksum is derived from the concatenated address type and address components, ensuring integrity. - -The encoding process transforms the concatenated components into a Base58 string, providing a compact and human-readable format that avoids easily confused characters (e.g., zero '0', capital 'O', lowercase 'l'). This encoding function ([`encode`](https://docs.rs/bs58/latest/bs58/fn.encode.html){target=\_blank}) is implemented exactly as defined in Bitcoin and IPFS specifications, using the same alphabet as both implementations. - -For more details about the SS58 address format implementation, see the [`Ss58Codec`](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Ss58Codec.html){target=\_blank} trait in the Rust Docs. - -### Address Type - -The address type defines how an address is interpreted and to which network it belongs. Polkadot SDK uses different prefixes to distinguish between various chains and address formats: - -- **Address types `0-63`**: Simple addresses, commonly used for network identifiers. -- **Address types `64-127`**: Full addresses that support a wider range of network identifiers. -- **Address types `128-255`**: Reserved for future address format extensions. - -For example, Polkadot’s main network uses an address type of 0, while Kusama uses 2. This ensures that addresses can be used without confusion between networks. - -The address type is always encoded as part of the SS58 address, making it easy to quickly identify the network. Refer to the [SS58 registry](https://github.com/paritytech/ss58-registry){target=\_blank} for the canonical listing of all address type identifiers and how they map to Polkadot SDK-based networks. - -### Address Length - -SS58 addresses can have different lengths depending on the specific format. Address lengths range from as short as 3 to 35 bytes, depending on the complexity of the address and network requirements. This flexibility allows SS58 addresses to adapt to different chains while providing a secure encoding mechanism. - -| Total | Type | Raw account | Checksum | -|-------|------|-------------|----------| -| 3 | 1 | 1 | 1 | -| 4 | 1 | 2 | 1 | -| 5 | 1 | 2 | 2 | -| 6 | 1 | 4 | 1 | -| 7 | 1 | 4 | 2 | -| 8 | 1 | 4 | 3 | -| 9 | 1 | 4 | 4 | -| 10 | 1 | 8 | 1 | -| 11 | 1 | 8 | 2 | -| 12 | 1 | 8 | 3 | -| 13 | 1 | 8 | 4 | -| 14 | 1 | 8 | 5 | -| 15 | 1 | 8 | 6 | -| 16 | 1 | 8 | 7 | -| 17 | 1 | 8 | 8 | -| 35 | 1 | 32 | 2 | - -SS58 addresses also support different payload sizes, allowing a flexible range of account identifiers. - -### Checksum Types - -A checksum is applied to validate SS58 addresses. Polkadot SDK uses a Blake2b-512 hash function to calculate the checksum, which is appended to the address before encoding. The checksum length can vary depending on the address format (e.g., 1-byte, 2-byte, or longer), providing varying levels of validation strength. - -The checksum ensures that an address is not modified or corrupted, adding an extra layer of security for account management. - -### Validating Addresses - -SS58 addresses can be validated using the subkey command-line interface or the Polkadot.js API. These tools help ensure an address is correctly formatted and valid for the intended network. The following sections will provide an overview of how validation works with these tools. - -#### Using Subkey - -[Subkey](https://paritytech.github.io/polkadot-sdk/master/subkey/index.html){target=\_blank} is a CLI tool provided by Polkadot SDK for generating and managing keys. It can inspect and validate SS58 addresses. - -The `inspect` command gets a public key and an SS58 address from the provided secret URI. The basic syntax for the `subkey inspect` command is: - -```bash -subkey inspect [flags] [options] uri -``` - -For the `uri` command-line argument, you can specify the secret seed phrase, a hex-encoded private key, or an SS58 address. If the input is a valid address, the `subkey` program displays the corresponding hex-encoded public key, account identifier, and SS58 addresses. - -For example, to inspect the public keys derived from a secret seed phrase, you can run a command similar to the following: - -```bash -subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" -``` - -The command displays output similar to the following: - -
- subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" - Secret phrase `caution juice atom organ advance problem want pledge someone senior holiday very` is account: - Secret seed: 0xc8fa03532fb22ee1f7f6908b9c02b4e72483f0dbd66e4cd456b8f34c6230b849 - Public key (hex): 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - Public key (SS58): 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR - Account ID: 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - SS58 Address: 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR -
- -The `subkey` program assumes an address is based on a public/private key pair. If you inspect an address, the command returns the 32-byte account identifier. - -However, not all addresses in Polkadot SDK-based networks are based on keys. - -Depending on the command-line options you specify and the input you provided, the command output might also display the network for which the address has been encoded. For example: - -```bash -subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" -``` - -The command displays output similar to the following: - -
- subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" - Public Key URI `12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU` is account: - Network ID/Version: polkadot - Public key (hex): 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Account ID: 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Public key (SS58): 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU - SS58 Address: 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU -
- -#### Using Polkadot.js API - -To verify an address in JavaScript or TypeScript projects, you can use the functions built into the [Polkadot.js API](https://polkadot.js.org/docs/){target=\_blank}. For example: - -```js -// Import Polkadot.js API dependencies -const { decodeAddress, encodeAddress } = require('@polkadot/keyring'); -const { hexToU8a, isHex } = require('@polkadot/util'); - -// Specify an address to test. -const address = 'INSERT_ADDRESS_TO_TEST'; - -// Check address -const isValidSubstrateAddress = () => { - try { - encodeAddress(isHex(address) ? hexToU8a(address) : decodeAddress(address)); - - return true; - } catch (error) { - return false; - } -}; - -// Query result -const isValid = isValidSubstrateAddress(); -console.log(isValid); - -``` - -If the function returns `true`, the specified address is a valid address. - -#### Other SS58 Implementations - -Support for encoding and decoding Polkadot SDK SS58 addresses has been implemented in several other languages and libraries. - -- **Crystal**: [`wyhaines/base58.cr`](https://github.com/wyhaines/base58.cr){target=\_blank} -- **Go**: [`itering/subscan-plugin`](https://github.com/itering/subscan-plugin){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **TypeScript**: [`subsquid/squid-sdk`](https://github.com/subsquid/squid-sdk){target=\_blank} - - ---- - -Page Title: Randomness - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-randomness.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/randomness/ -- Summary: Explore the importance of randomness in PoS blockchains, focusing on Polkadot’s VRF-based approach to ensure fairness and security in validator selection. - -# Randomness - -## Introduction - -Randomness is crucial in Proof of Stake (PoS) blockchains to ensure a fair and unpredictable distribution of validator duties. However, computers are inherently deterministic, meaning the same input always produces the same output. What we typically refer to as "random" numbers on a computer are actually pseudo-random. These numbers rely on an initial "seed," which can come from external sources like [atmospheric noise](https://www.random.org/randomness/){target=\_blank}, [heart rates](https://mdpi.altmetric.com/details/47574324){target=\_blank}, or even [lava lamps](https://en.wikipedia.org/wiki/Lavarand){target=\_blank}. While this may seem random, given the same "seed," the same sequence of numbers will always be generated. - -In a global blockchain network, relying on real-world entropy for randomness isn’t feasible because these inputs vary by time and location. If nodes use different inputs, blockchains can fork. Hence, real-world randomness isn't suitable for use as a seed in blockchain systems. - -Currently, two primary methods for generating randomness in blockchains are used: [`RANDAO`](#randao) and [`VRF`](#vrf) (Verifiable Random Function). Polkadot adopts the `VRF` approach for its randomness. - -## VRF - -A Verifiable Random Function (VRF) is a cryptographic function that generates a random number and proof that ensures the submitter produced the number. This proof allows anyone to verify the validity of the random number. - -Polkadot's VRF is similar to the one used in [**Ouroboros Praos**](https://eprint.iacr.org/2017/573.pdf){target=\_blank}, which secures randomness for block production in systems like [BABE](/reference/polkadot-hub/consensus-and-security/pos-consensus/#block-production-babe){target=\_blank} (Polkadot’s block production mechanism). - -The key difference is that Polkadot's VRF doesn’t rely on a central clock—avoiding the issue of whose clock to trust. Instead, it uses its own past results and slot numbers to simulate time and determine future outcomes. - -### How VRF Works - -Slots on Polkadot are discrete units of time, each lasting six seconds, and can potentially hold a block. Multiple slots form an epoch, with 2400 slots making up one four-hour epoch. - -In each slot, validators execute a "die roll" using a VRF. The VRF uses three inputs: - -1. A "secret key," unique to each validator, is used for the die roll. -2. An epoch randomness value, derived from the hash of VRF outputs from blocks two epochs ago (N-2), so past randomness influences the current epoch (N). -3. The current slot number. - -This process helps maintain fair randomness across the network. - -Here is a graphical representation: - -![](/images/reference/parachains/randomness/randomness-01.webp) - -The VRF produces two outputs: a result (the random number) and a proof (verifying that the number was generated correctly). - -The result is checked by the validator against a protocol threshold. If it's below the threshold, the validator becomes a candidate for block production in that slot. - -The validator then attempts to create a block, submitting it along with the `PROOF` and `RESULT`. - -So, VRF can be expressed like: - -`(RESULT, PROOF) = VRF(SECRET, EPOCH_RANDOMNESS_VALUE, CURRENT_SLOT_NUMBER)` - -Put simply, performing a "VRF roll" generates a random number along with proof that the number was genuinely produced and not arbitrarily chosen. - -After executing the VRF, the `RESULT` is compared to a protocol-defined `THRESHOLD`. If the `RESULT` is below the `THRESHOLD`, the validator becomes a valid candidate to propose a block for that slot. Otherwise, the validator skips the slot. - -As a result, there may be multiple validators eligible to propose a block for a slot. In this case, the block accepted by other nodes will prevail, provided it is on the chain with the latest finalized block as determined by the GRANDPA finality gadget. It's also possible for no block producers to be available for a slot, in which case the AURA consensus takes over. AURA is a fallback mechanism that randomly selects a validator to produce a block, running in parallel with BABE and only stepping in when no block producers exist for a slot. Otherwise, it remains inactive. - -Because validators roll independently, no block candidates may appear in some slots if all roll numbers are above the threshold. - -To verify resolution of this issue and that Polkadot block times remain near constant-time, see the [PoS Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} page of this documentation. - -## RANDAO - -An alternative on-chain randomness method is Ethereum's RANDAO, where validators perform thousands of hashes on a seed and publish the final hash during a round. The collective input from all validators forms the random number, and as long as one honest validator participates, the randomness is secure. - -To enhance security, RANDAO can optionally be combined with a Verifiable Delay Function (VDF), ensuring that randomness can't be predicted or manipulated during computation. - -For more information about RANDAO, see the [Randomness - RANDAO](https://eth2book.info/capella/part2/building_blocks/randomness/){target=\_blank} section of the Upgrading Ethereum documentation. - -## VDFs - -Verifiable Delay Functions (VDFs) are time-bound computations that, even on parallel computers, take a set amount of time to complete. - -They produce a unique result that can be quickly verified publicly. When combined with RANDAO, feeding RANDAO's output into a VDF introduces a delay that nullifies an attacker's chance to influence the randomness. - -However, VDF likely requires specialized ASIC devices to run separately from standard nodes. - -!!!warning - While only one is needed to secure the system, and they will be open-source and inexpensive, running VDF devices involves significant costs without direct incentives, adding friction for blockchain users. - -## Additional Resources - -For more information about the reasoning for choices made along with proofs, see Polkadot's research on blockchain randomness and sortition in the [Block production](https://research.web3.foundation/Polkadot/protocols/block-production){target=\_blank} entry of the Polkadot Wiki. - -For a discussion with Web3 Foundation researchers about when and under what conditions Polkadot's randomness can be utilized, see the [Discussion on Randomness used in Polkadot](https://github.com/use-ink/ink/issues/57){target=\_blank} issue on GitHub. - - ---- - -Page Title: Register a Local Asset - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-token-operations-register-local-asset.md -- Canonical (HTML): https://docs.polkadot.com/chain-interactions/token-operations/register-local-asset/ -- Summary: Comprehensive guide to registering a local asset on the Asset Hub system parachain, including step-by-step instructions. - -# Register a Local Asset on Asset Hub - -## Introduction - -As detailed in the [Asset Hub Overview](/polkadot-protocol/architecture/system-chains/asset-hub){target=\_blank} page, Asset Hub accommodates two types of assets: local and foreign. Local assets are those that were created in Asset Hub and are identifiable by an integer ID. On the other hand, foreign assets originate from a sibling parachain and are identified by a Multilocation. - -This guide will take you through the steps of registering a local asset on the Asset Hub parachain. - -## Prerequisites - -Before you begin, ensure you have access to the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and a funded wallet with DOT or KSM. - -- For Polkadot Asset Hub, you would need a deposit of 10 DOT and around 0.201 DOT for the metadata. -- For Kusama Asset Hub, the deposit is 0.1 KSM and around 0.000669 KSM for the metadata. - -You need to ensure that your Asset Hub account balance is a bit more than the sum of those two deposits, which should seamlessly account for the required deposits and transaction fees. - -## Steps to Register a Local Asset - -To register a local asset on the Asset Hub parachain, follow these steps: - -1. Open the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and connect to the Asset Hub parachain using the network selector in the top left corner. - - - You may prefer to test local asset registration on TestNet before registering the asset on a MainNet hub. If you still need to set up a local testing environment, review the [Environment setup](#test-setup-environment) section for instructions. Once the local environment is set up, connect to the Local Node (Chopsticks) available on `ws://127.0.0.1:8000`. - - For the live network, connect to the **Asset Hub** parachain. Either Polkadot or Kusama Asset Hub can be selected from the dropdown list, choosing the desired RPC provider. - -2. Click on the **Network** tab on the top navigation bar and select **Assets** from the dropdown list. - - ![Access to Asset Hub through Polkadot.JS](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-01.webp) - -3. Now, you need to examine all the registered asset IDs. This step is crucial to ensure that the asset ID you are about to register is unique. Asset IDs are displayed in the **assets** column. - - ![Asset IDs on Asset Hub](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-02.webp) - -4. Once you have confirmed that the asset ID is unique, click on the **Create** button on the top right corner of the page. - - ![Create a new asset](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-03.webp) - -5. Fill in the required fields in the **Create Asset** form: - - 1. **creator account**: The account to be used for creating this asset and setting up the initial metadata. - 2. **asset name**: The descriptive name of the asset you are registering. - 3. **asset symbol**: The symbol that will be used to represent the asset. - 4. **asset decimals**: The number of decimal places for this token, with a maximum of 20 allowed through the user interface. - 5. **minimum balance**: The minimum balance for the asset. This is specified in the units and decimals as requested. - 6. **asset ID**: The selected id for the asset. This should not match an already-existing asset id. - 7. Click on the **Next** button. - - ![Create Asset Form](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-04.webp) - -6. Choose the accounts for the roles listed below: - - 1. **admin account**: The account designated for continuous administration of the token. - 2. **issuer account**: The account that will be used for issuing this token. - 3. **freezer account**: The account that will be used for performing token freezing operations. - 4. Click on the **Create** button. - - ![Admin, Issuer, Freezer accounts](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-05.webp) - -7. Click on the **Sign and Submit** button to complete the asset registration process. - - ![Sign and Submit](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-06.webp) - -## Verify Asset Registration - -After completing these steps, the asset will be successfully registered. You can now view your asset listed on the [**Assets**](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fasset-hub-polkadot-rpc.dwellir.com#/assets){target=\_blank} section of the Polkadot.js Apps interface. - -![Asset listed on Polkadot.js Apps](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-07.webp) - -!!! tip - Take into consideration that the **Assets** section’s link may differ depending on the network you are using. For the local environment, enter `ws://127.0.0.1:8000` into the **Custom Endpoint** field. - -In this way, you have successfully registered a local asset on the Asset Hub parachain. +- **[OpenZeppelin Runtime Templates](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\_blank}**: Provides security-focused configurations following industry best practices. The [generic-template](https://github.com/OpenZeppelin/polkadot-runtime-templates/tree/main/generic-template){target=\_blank} includes curated pallet selections and production-ready defaults—ideal if security is your top priority. -For an in-depth explanation about Asset Hub and its features, see the [Asset Hub](/chain-interactions/token-operations/convert-assets/){target=\_blank} entry in the Polkadot Wiki. +## Key Customization Scenarios -## Test Setup Environment +This section covers the most common customization patterns you'll encounter: -You can set up a local parachain environment to test the asset registration process before deploying it on the live network. This guide uses Chopsticks to simulate that process. For further information on chopsticks usage, refer to the [Chopsticks](/develop/toolkit/parachains/fork-chains/chopsticks/get-started){target=\_blank} documentation. +- **[Add Existing Pallets to Your Runtime](/parachains/customize-runtime/add-existing-pallets/)**: Integrate pre-built pallets from the FRAME library with minimal configuration. -To set up a test environment, execute the following command: +- **[Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/)**: Run multiple instances of the same pallet with different configurations—useful for multi-token systems or parallel features. -```bash -npx @acala-network/chopsticks \ ---config=https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/polkadot-asset-hub.yml -``` +- **[Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/)**: Enable smart contract execution on your parachain using Contracts pallets. -The above command will spawn a lazy fork of Polkadot Asset Hub with the latest block data from the network. If you need to test Kusama Asset Hub, replace `polkadot-asset-hub.yml` with `kusama-asset-hub.yml` in the command. +- **[Create Custom Pallets](/parachains/customize-runtime/pallet-development/create-a-pallet/)**: Build entirely custom pallets for features unique to your blockchain. -An Asset Hub instance is now running locally, and you can proceed with the asset registration process. Note that the local registration process does not differ from the live network process. Once you have a successful TestNet transaction, you can use the same steps to register the asset on MainNet. +- **[Test Your Runtime](/parachains/customize-runtime/pallet-development/pallet-testing/)**: Unit test pallets and mock complete runtimes to ensure everything works correctly. --- @@ -5836,507 +3476,115 @@ This page contains a list of all relevant tutorials and guides to help you get s | Title | Difficulty | Tools | Description | |---------------------------------------------------------------------------------------------------|:-----------:|--------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------| | [Deploy an ERC-20 to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/) | 🟢 Beginner | EVM Wallet, Polkadot Remix IDE | Deploy an ERC-20 token on Polkadot Hub using PolkaVM. This guide covers contract creation, compilation, deployment, and interaction via Polkadot Remix IDE. | -| [Deploy an NFT to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) | 🟢 Beginner | EVM Wallet, Polkadot Remix IDE | Deploy an NFT on Polkadot Hub using PolkaVM and OpenZeppelin. Learn how to compile, deploy, and interact with your contract using Polkadot Remix IDE. | - -## Port Ethereum DApps - -| Title | Difficulty | Tools | Description | -|-------------------------------------------------------------------------------------|:---------------:|---------|----------------------------------------------------------------------------------------------------------------------------------| -| [Deploying Uniswap V2 on Polkadot](/smart-contracts/cookbook/eth-dapps/uniswap-v2/) | 🟡 Intermediate | Hardhat | Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. | - - ---- - -Page Title: Smart Contracts Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-overview.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/overview/ -- Summary: Learn about smart contract development capabilities in the Polkadot ecosystem, either by leveraging Polkadot Hub or other alternatives. - -# Smart Contracts on Polkadot - -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction - -Polkadot offers developers multiple approaches to building and deploying smart contracts within its ecosystem. As a multi-chain network designed for interoperability, Polkadot provides various environments optimized for different developer preferences and application requirements. From native smart contract support on Polkadot Hub to specialized parachain environments, developers can choose the platform that best suits their technical needs while benefiting from Polkadot's shared security model and cross-chain messaging capabilities. - -Whether you're looking for Ethereum compatibility through EVM-based parachains like [Moonbeam](https://docs.moonbeam.network/){target=\_blank}, [Astar](https://docs.astar.network/){target=\_blank}, and [Acala](https://evmdocs.acala.network/){target=\_blank} or prefer PolkaVM-based development with [ink!](https://use.ink/docs/v6/){target=\_blank}, the Polkadot ecosystem accommodates a range of diverse developers. - -These guides explore the diverse smart contract options available in the Polkadot ecosystem, helping developers understand the unique advantages of each approach and make informed decisions about where to deploy their decentralized applications. - -## Native Smart Contracts - -### Introduction - -Polkadot Hub enables smart contract deployment and execution through PolkaVM, a cutting-edge virtual machine designed specifically for the Polkadot ecosystem. This native integration allows developers to deploy smart contracts directly on Polkadot's system chain while maintaining compatibility with Ethereum development tools and workflows. - -### Smart Contract Development - -The smart contract platform on Polkadot Hub combines _Polkadot's robust security and scalability_ with the extensive Ethereum development ecosystem. Developers can utilize familiar Ethereum libraries for contract interactions and leverage industry-standard development environments for writing and testing smart contracts. - -Polkadot Hub provides _full Ethereum JSON-RPC API compatibility_, ensuring seamless integration with existing development tools and services. This compatibility enables developers to maintain their preferred workflows while building on Polkadot's native infrastructure. - -### Technical Architecture - -PolkaVM, the underlying virtual machine, utilizes a RISC-V-based register architecture _optimized for the Polkadot ecosystem_. This design choice offers several advantages: - -- Enhanced performance for smart contract execution. -- Improved gas efficiency for complex operations. -- Native compatibility with Polkadot's runtime environment. -- Optimized storage and state management. - -### Development Tools and Resources - -Polkadot Hub supports a comprehensive suite of development tools familiar to Ethereum developers. The platform integrates with popular development frameworks, testing environments, and deployment tools. Key features include: - -- Contract development in Solidity or Rust. -- Support for standard Ethereum development libraries. -- Integration with widely used development environments. -- Access to blockchain explorers and indexing solutions. -- Compatibility with contract monitoring and management tools. - -### Cross-Chain Capabilities - -Smart contracts deployed on Polkadot Hub can leverage Polkadot's [cross-consensus messaging (XCM) protocol](/parachains/interoperability/get-started/){target=\_blank} protocol to seamlessly _transfer tokens and call functions on other blockchain networks_ within the Polkadot ecosystem, all without complex bridging infrastructure or third-party solutions. For further references, check the [Interoperability](/develop/interoperability/){target=\_blank} section. - -### Use Cases - -Polkadot Hub's smart contract platform is suitable for a wide range of applications: - -- DeFi protocols leveraging _cross-chain capabilities_. -- NFT platforms utilizing Polkadot's native token standards. -- Governance systems integrated with Polkadot's democracy mechanisms. -- Cross-chain bridges and asset management solutions. - -## Other Smart Contract Environments - -Beyond Polkadot Hub's native PolkaVM support, the ecosystem offers two main alternatives for smart contract development: - -- **EVM-compatible parachains**: Provide access to Ethereum's extensive developer ecosystem, smart contract portability, and established tooling like Hardhat, Remix, Foundry, and OpenZeppelin. The main options include Moonbeam (the first full Ethereum-compatible parachain serving as an interoperability hub), Astar (featuring dual VM support for both EVM and WebAssembly contracts), and Acala (DeFi-focused with enhanced Acala EVM+ offering advanced DeFi primitives). - -- **Rust (ink!)**: ink! is a Rust-based framework that can compile to PolkaVM. It uses [`#[ink(...)]`](https://use.ink/docs/v6/macros-attributes/){target=\_blank} attribute macros to create Polkadot SDK-compatible PolkaVM bytecode, offering strong memory safety from Rust, an advanced type system, high-performance PolkaVM execution, and platform independence with sandboxed security. - - -Each environment provides unique advantages based on developer preferences and application requirements. - -## Where to Go Next - -Developers can use their existing Ethereum development tools and connect to Polkadot Hub's RPC endpoints. The platform's Ethereum compatibility layer ensures a smooth transition for teams already building on Ethereum-compatible chains. - -Subsequent sections of this guide provide detailed information about specific development tools, advanced features, and best practices for building on Polkadot Hub. - -
- -- Guide __Libraries__ - - --- - - Explore essential libraries to optimize smart contract development and interaction. - - [:octicons-arrow-right-24: Reference](/smart-contracts/libraries/ethers-js/) - -- Guide __Dev Environments__ - - --- - - Set up your development environment for seamless contract deployment and testing. - - [:octicons-arrow-right-24: Reference](/smart-contracts/dev-environments/local-dev-node/) - -
- - ---- - -Page Title: Technical Reference Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference.md -- Canonical (HTML): https://docs.polkadot.com/reference/ -- Summary: Learn about Polkadot's technical architecture, governance framework, parachain ecosystem, and the tools you need to build and interact with the network. - -## Introduction - -The Technical Reference section provides comprehensive documentation of Polkadot's architecture, core concepts, and development tooling. Whether you're exploring how Polkadot's relay chain coordinates parachains, understanding governance mechanisms, or building applications on the network, this reference covers the technical foundations you need. - -Polkadot is a multi-chain network that enables diverse, interconnected blockchains to share security and communicate seamlessly. Understanding how these components interact from the [relay chain](/polkadot-protocol/glossary#relay-chain){target=\_blank} that validates [parachains](/polkadot-protocol/glossary#parachain){target=\_blank} to the [governance](/reference/glossary#governance){target=\_blank} mechanisms that evolve the protocol is essential for developers, validators, and network participants. - -This guide organizes technical documentation across five core areas: Polkadot Hub, Parachains, On-Chain Governance, Glossary, and Tools, each providing detailed information on different aspects of the Polkadot ecosystem. - -## Polkadot Hub - -[Polkadot Hub](/reference/polkadot-hub/){target=\_blank} is the entry point to Polkadot for all users and application developers. It provides access to essential Web3 services, including smart contracts, staking, governance, identity management, and cross-ecosystem interoperability—without requiring you to deploy or manage a parachain. - -The Hub encompasses a set of core functionality that enables developers and users to build and interact with applications on Polkadot. Key capabilities include: - -- **Smart contracts**: Deploy Ethereum-compatible smart contracts and build decentralized applications. -- **Assets and tokens**: Create, manage, and transfer fungible tokens and NFTs across the ecosystem. -- **Staking**: Participate in network security and earn rewards by staking DOT. -- **Governance**: Vote on proposals and participate in Polkadot's decentralized decision-making through OpenGov. -- **Identity services**: Register and manage on-chain identities, enabling access to governance roles and network opportunities. -- **Cross-chain interoperability**: Leverage XCM messaging to interact securely with other chains in the Polkadot ecosystem. -- **Collectives and DAOs**: Participate in governance collectives and decentralized autonomous organizations. - -## Parachains - -[Parachains](/reference/parachains/){target=\_blank} are specialized blockchains that connect to the Polkadot relay chain, inheriting its security while maintaining their own application-specific logic. The parachains documentation covers: - -- **Accounts**: Deep dive into account types, storage, and management on parachains. -- **Blocks, transactions and fees**: Understand block production, transaction inclusion, and fee mechanisms. -- **Consensus**: Learn how parachain blocks are validated and finalized through the relay chain's consensus. -- **Chain data**: Explore data structures, storage layouts, and state management. -- **Cryptography**: Study cryptographic primitives used in Polkadot SDK-based chains. -- **Data encoding**: Understand how data is encoded and decoded for blockchain compatibility. -- **Networks**: Learn about networking protocols and peer-to-peer communication. -- **Interoperability**: Discover [Cross-Consensus Messaging (XCM)](/parachains/interoperability/get-started/){target=\_blank}, the standard for cross-chain communication. -- **Randomness**: Understand how randomness is generated and used in Polkadot chains. -- **Node and runtime**: Learn about parachain nodes, runtime environments, and the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}. - -## On-Chain Governance - -[On-Chain governance](/reference/governance/){target=\_blank} is the decentralized decision-making mechanism for the Polkadot network. It manages the evolution and modification of the network's runtime logic, enabling community oversight and approval for proposed changes. The governance documentation details: - -- **OpenGov framework**: Understand Polkadot's next-generation governance system with enhanced delegation, flexible tracks, and simultaneous referendums. -- **Origins and tracks**: Learn how governance proposals are categorized, prioritized, and executed based on their privilege level and complexity. -- **Voting and delegation**: Explore conviction voting, vote delegation, and how token holders participate in governance. -- **Governance evolution**: See how Polkadot's governance has evolved from Governance V1 to the current OpenGov system. - -## Glossary - -The [Glossary](/reference/glossary/){target=\_blank} provides quick-reference definitions for Polkadot-specific terminology. Essential terms include: - -- Blockchain concepts (blocks, transactions, state) -- Consensus mechanisms (validators, collators, finality) -- Polkadot-specific terms (relay chain, parachain, XCM, FRAME) -- Network components (nodes, runtimes, storage) -- Governance terminology (origins, tracks, referendums) - -## Tools - -The [Tools](/reference/tools/){target=\_blank} section documents essential development and interaction tools for the Polkadot ecosystem: - -- **Light clients**: Lightweight solutions for interacting with the network without running full nodes. -- **JavaScript/TypeScript tools**: Libraries like [Polkadot.js API](/reference/tools/polkadot-js-api/){target=\_blank} and [PAPI](/reference/tools/papi/){target=\_blank} for building applications. -- **Rust tools**: [Polkadart](/reference/tools/polkadart/){target=\_blank} and other Rust-based libraries for SDK development. -- **Python tools**: [py-substrate-interface](/reference/tools/py-substrate-interface/){target=\_blank} for Python developers. -- **Testing and development**: Tools like [Moonwall](/reference/tools/moonwall/){target=\_blank}, [Chopsticks](/reference/tools/chopsticks/){target=\_blank}, and [Omninode](/reference/tools/omninode/){target=\_blank} for smart contract and parachain testing. -- **Indexing and monitoring**: [Sidecar](/reference/tools/sidecar/){target=\_blank} for data indexing and [Dedot](/reference/tools/dedot/){target=\_blank} for substrate interaction. -- **Cross-chain tools**: [ParaSpell](/reference/tools/paraspell/){target=\_blank} for XCM integration and asset transfers. - -## Where to Go Next - -For detailed exploration of specific areas, proceed to any of the main sections: - -
- -- Learn **Polkadot Hub** - - --- - - Understand the relay chain's role in coordinating parachains, providing shared security, and enabling governance. - - [:octicons-arrow-right-24: Reference](/reference/polkadot-hub/) - -- Learn **Parachains** - - --- - - Deep dive into parachain architecture, consensus, data structures, and building application-specific blockchains. - - [:octicons-arrow-right-24: Reference](/reference/parachains/) - -- Learn **On-Chain Governance** - - --- - - Explore Polkadot's decentralized governance framework and how to participate in network decision-making. - - [:octicons-arrow-right-24: Reference](/reference/governance/) - -- Guide **Glossary** - - --- - - Quick reference for Polkadot-specific terminology and concepts used throughout the documentation. - - [:octicons-arrow-right-24: Reference](/reference/glossary/) - -- Guide **Tools** - - --- - - Discover development tools, libraries, and frameworks for building and interacting with Polkadot. - - [:octicons-arrow-right-24: Reference](/reference/tools/) - -
- - ---- - -Page Title: Transactions - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-transactions.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/transactions/ -- Summary: Learn how to construct, submit, and validate transactions in the Polkadot SDK, covering signed, unsigned, and inherent types of transactions. - -# Transactions - -## Introduction - -Transactions are essential components of blockchain networks, enabling state changes and the execution of key operations. In the Polkadot SDK, transactions, often called extrinsics, come in multiple forms, including signed, unsigned, and inherent transactions. - -This guide walks you through the different transaction types and how they're formatted, validated, and processed within the Polkadot ecosystem. You'll also learn how to customize transaction formats and construct transactions for FRAME-based runtimes, ensuring a complete understanding of how transactions are built and executed in Polkadot SDK-based chains. - -## What Is a Transaction? - -In the Polkadot SDK, transactions represent operations that modify the chain's state, bundled into blocks for execution. The term extrinsic is often used to refer to any data that originates outside the runtime and is included in the chain. While other blockchain systems typically refer to these operations as "transactions," the Polkadot SDK adopts the broader term "extrinsic" to capture the wide variety of data types that can be added to a block. - -There are three primary types of transactions (extrinsics) in the Polkadot SDK: - -- **Signed transactions**: Signed by the submitting account, often carrying transaction fees. -- **Unsigned transactions**: Submitted without a signature, often requiring custom validation logic. -- **Inherent transactions**: Typically inserted directly into blocks by block authoring nodes, without gossiping between peers. - -Each type serves a distinct purpose, and understanding when and how to use each is key to efficiently working with the Polkadot SDK. - -### Signed Transactions - -Signed transactions require an account's signature and typically involve submitting a request to execute a runtime call. The signature serves as a form of cryptographic proof that the sender has authorized the action, using their private key. These transactions often involve a transaction fee to cover the cost of execution and incentivize block producers. - -Signed transactions are the most common type of transaction and are integral to user-driven actions, such as token transfers. For instance, when you transfer tokens from one account to another, the sending account must sign the transaction to authorize the operation. - -For example, the [`pallet_balances::Call::transfer_allow_death`](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/pallet/struct.Pallet.html#method.transfer_allow_death){target=\_blank} extrinsic in the Balances pallet allows you to transfer tokens. Since your account initiates this transaction, your account key is used to sign it. You'll also be responsible for paying the associated transaction fee, with the option to include an additional tip to incentivize faster inclusion in the block. - -### Unsigned Transactions - -Unsigned transactions do not require a signature or account-specific data from the sender. Unlike signed transactions, they do not come with any form of economic deterrent, such as fees, which makes them susceptible to spam or replay attacks. Custom validation logic must be implemented to mitigate these risks and ensure these transactions are secure. - -Unsigned transactions typically involve scenarios where including a fee or signature is unnecessary or counterproductive. However, due to the absence of fees, they require careful validation to protect the network. For example, [`pallet_im_online::Call::heartbeat`](https://paritytech.github.io/polkadot-sdk/master/pallet_im_online/pallet/struct.Pallet.html#method.heartbeat){target=\_blank} extrinsic allows validators to send a heartbeat signal, indicating they are active. Since only validators can make this call, the logic embedded in the transaction ensures that the sender is a validator, making the need for a signature or fee redundant. - -Unsigned transactions are more resource-intensive than signed ones because custom validation is required, but they play a crucial role in certain operational scenarios, especially when regular user accounts aren't involved. - -### Inherent Transactions - -Inherent transactions are a specialized type of unsigned transaction that is used primarily for block authoring. Unlike signed or other unsigned transactions, inherent transactions are added directly by block producers and are not broadcasted to the network or stored in the transaction queue. They don't require signatures or the usual validation steps and are generally used to insert system-critical data directly into blocks. - -A key example of an inherent transaction is inserting a timestamp into each block. The [`pallet_timestamp::Call::now`](https://paritytech.github.io/polkadot-sdk/master/pallet_timestamp/pallet/struct.Pallet.html#method.now-1){target=\_blank} extrinsic allows block authors to include the current time in the block they are producing. Since the block producer adds this information, there is no need for transaction validation, like signature verification. The validation in this case is done indirectly by the validators, who check whether the timestamp is within an acceptable range before finalizing the block. - -Another example is the [`paras_inherent::Call::enter`](https://paritytech.github.io/polkadot-sdk/master/polkadot_runtime_parachains/paras_inherent/pallet/struct.Pallet.html#method.enter){target=\_blank} extrinsic, which enables parachain collator nodes to send validation data to the relay chain. This inherent transaction ensures that the necessary parachain data is included in each block without the overhead of gossiped transactions. - -Inherent transactions serve a critical role in block authoring by allowing important operational data to be added directly to the chain without needing the validation processes required for standard transactions. - -## Transaction Formats - -Understanding the structure of signed and unsigned transactions is crucial for developers building on Polkadot SDK-based chains. Whether you're optimizing transaction processing, customizing formats, or interacting with the transaction pool, knowing the format of extrinsics, Polkadot's term for transactions, is essential. - -### Types of Transaction Formats - -In Polkadot SDK-based chains, extrinsics can fall into three main categories: - -- **Unchecked extrinsics**: Typically used for signed transactions that require validation. They contain a signature and additional data, such as a nonce and information for fee calculation. Unchecked extrinsics are named as such because they require validation checks before being accepted into the transaction pool. -- **Checked extrinsics**: Typically used for inherent extrinsics (unsigned transactions); these don't require signature verification. Instead, they carry information such as where the extrinsic originates and any additional data required for the block authoring process. -- **Opaque extrinsics**: Used when the format of an extrinsic is not yet fully committed or finalized. They are still decodable, but their structure can be flexible depending on the context. - -### Signed Transaction Data Structure - -A signed transaction typically includes the following components: - -- **Signature**: Verifies the authenticity of the transaction sender. -- **Call**: The actual function or method call the transaction is requesting (for example, transferring funds). -- **Nonce**: Tracks the number of prior transactions sent from the account, helping to prevent replay attacks. -- **Tip**: An optional incentive to prioritize the transaction in block inclusion. -- **Additional data**: Includes details such as spec version, block hash, and genesis hash to ensure the transaction is valid within the correct runtime and chain context. - -Here's a simplified breakdown of how signed transactions are typically constructed in a Polkadot SDK runtime: - -``` code - + + -``` - -Each part of the signed transaction has a purpose, ensuring the transaction's authenticity and context within the blockchain. - -### Signed Extensions - -Polkadot SDK also provides the concept of [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}, which allow developers to extend extrinsics with additional data or validation logic before they are included in a block. The [`SignedExtension`](https://paritytech.github.io/try-runtime-cli/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} set helps enforce custom rules or protections, such as ensuring the transaction's validity or calculating priority. - -The transaction queue regularly calls signed extensions to verify a transaction's validity before placing it in the ready queue. This safeguard ensures transactions won't fail in a block. Signed extensions are commonly used to enforce validation logic and protect the transaction pool from spam and replay attacks. - -In FRAME, a signed extension can hold any of the following types by default: - -- **[`AccountId`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/runtime/types_common/type.AccountId.html){target=\_blank}**: To encode the sender's identity. -- **[`Call`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Call){target=\_blank}**: To encode the pallet call to be dispatched. This data is used to calculate transaction fees. -- **[`AdditionalSigned`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.AdditionalSigned){target=\_blank}**: To handle any additional data to go into the signed payload allowing you to attach any custom logic prior to dispatching a transaction. -- **[`Pre`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Pre){target=\_blank}**: To encode the information that can be passed from before a call is dispatched to after it gets dispatched. - -Signed extensions can enforce checks like: - -- **[`CheckSpecVersion`](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/extensions/check_spec_version.rs.html){target=\_blank}**: Ensures the transaction is compatible with the runtime's current version. -- **[`CheckWeight`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.CheckWeight.html){target=\_blank}**: Calculates the weight (or computational cost) of the transaction, ensuring the block doesn't exceed the maximum allowed weight. - -These extensions are critical in the transaction lifecycle, ensuring that only valid and prioritized transactions are processed. - -## Transaction Construction - -Building transactions in the Polkadot SDK involves constructing a payload that can be verified, signed, and submitted for inclusion in a block. Each runtime in the Polkadot SDK has its own rules for validating and executing transactions, but there are common patterns for constructing a signed transaction. - -### Construct a Signed Transaction - -A signed transaction in the Polkadot SDK includes various pieces of data to ensure security, prevent replay attacks, and prioritize processing. Here's an overview of how to construct one: - -1. **Construct the unsigned payload**: Gather the necessary information for the call, including: - - - **Pallet index**: Identifies the pallet where the runtime function resides. - - **Function index**: Specifies the particular function to call in the pallet. - - **Parameters**: Any additional arguments required by the function call. - -2. **Create a signing payload**: Once the unsigned payload is ready, additional data must be included: - - - **Transaction nonce**: Unique identifier to prevent replay attacks. - - **Era information**: Defines how long the transaction is valid before it's dropped from the pool. - - **Block hash**: Ensures the transaction doesn't execute on the wrong chain or fork. - -3. **Sign the payload**: Using the sender's private key, sign the payload to ensure that the transaction can only be executed by the account holder. -4. **Serialize the signed payload**: Once signed, the transaction must be serialized into a binary format, ensuring the data is compact and easy to transmit over the network. -5. **Submit the serialized transaction**: Finally, submit the serialized transaction to the network, where it will enter the transaction pool and wait for processing by an authoring node. - -The following is an example of how a signed transaction might look: - -``` rust -node_runtime::UncheckedExtrinsic::new_signed( - function.clone(), // some call - sp_runtime::AccountId32::from(sender.public()).into(), // some sending account - node_runtime::Signature::Sr25519(signature.clone()), // the account's signature - extra.clone(), // the signed extensions -) -``` - -### Transaction Encoding - -Before a transaction is sent to the network, it is serialized and encoded using a structured encoding process that ensures consistency and prevents tampering: - -- **`[1]`**: Compact encoded length in bytes of the entire transaction. -- **`[2]`**: A u8 containing 1 byte to indicate whether the transaction is signed or unsigned (1 bit) and the encoded transaction version ID (7 bits). -- **`[3]`**: If signed, this field contains an account ID, an SR25519 signature, and some extra data. -- **`[4]`**: Encoded call data, including pallet and function indices and any required arguments. - -This encoded format ensures consistency and efficiency in processing transactions across the network. By adhering to this format, applications can construct valid transactions and pass them to the network for execution. - -To learn more about how compact encoding works using SCALE, see the [SCALE Codec](https://github.com/paritytech/parity-scale-codec){target=\_blank} README on GitHub. - -### Customize Transaction Construction - -Although the basic steps for constructing transactions are consistent across Polkadot SDK-based chains, developers can customize transaction formats and validation rules. For example: +| [Deploy an NFT to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) | 🟢 Beginner | EVM Wallet, Polkadot Remix IDE | Deploy an NFT on Polkadot Hub using PolkaVM and OpenZeppelin. Learn how to compile, deploy, and interact with your contract using Polkadot Remix IDE. | -- **Custom pallets**: You can define new pallets with custom function calls, each with its own parameters and validation logic. -- **Signed extensions**: Developers can implement custom extensions that modify how transactions are prioritized, validated, or included in blocks. +## Port Ethereum DApps -By leveraging Polkadot SDK's modular design, developers can create highly specialized transaction logic tailored to their chain's needs. +| Title | Difficulty | Tools | Description | +|-------------------------------------------------------------------------------------|:---------------:|---------|----------------------------------------------------------------------------------------------------------------------------------| +| [Deploying Uniswap V2 on Polkadot](/smart-contracts/cookbook/eth-dapps/uniswap-v2/) | 🟡 Intermediate | Hardhat | Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. | -## Lifecycle of a Transaction -In the Polkadot SDK, transactions are often referred to as extrinsics because the data in transactions originates outside of the runtime. These transactions contain data that initiates changes to the chain state. The most common type of extrinsic is a signed transaction, which is cryptographically verified and typically incurs a fee. This section focuses on how signed transactions are processed, validated, and ultimately included in a block. +--- -### Define Transaction Properties +Page Title: Smart Contracts Overview -The Polkadot SDK runtime defines key transaction properties, such as: +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-overview.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/overview/ +- Summary: Learn about smart contract development capabilities in the Polkadot ecosystem, either by leveraging Polkadot Hub or other alternatives. -- **Transaction validity**: Ensures the transaction meets all runtime requirements. -- **Signed or unsigned**: Identifies whether a transaction needs to be signed by an account. -- **State changes**: Determines how the transaction modifies the state of the chain. +# Smart Contracts on Polkadot -Pallets, which compose the runtime's logic, define the specific transactions that your chain supports. When a user submits a transaction, such as a token transfer, it becomes a signed transaction, verified by the user's account signature. If the account has enough funds to cover fees, the transaction is executed, and the chain's state is updated accordingly. +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. +## Introduction -### Process on a Block Authoring Node +Polkadot offers developers multiple approaches to building and deploying smart contracts within its ecosystem. As a multi-chain network designed for interoperability, Polkadot provides various environments optimized for different developer preferences and application requirements. From native smart contract support on Polkadot Hub to specialized parachain environments, developers can choose the platform that best suits their technical needs while benefiting from Polkadot's shared security model and cross-chain messaging capabilities. -In Polkadot SDK-based networks, some nodes are authorized to author blocks. These nodes validate and process transactions. When a transaction is sent to a node that can produce blocks, it undergoes a lifecycle that involves several stages, including validation and execution. Non-authoring nodes gossip the transaction across the network until an authoring node receives it. The following diagram illustrates the lifecycle of a transaction that's submitted to a network and processed by an authoring node. +Whether you're looking for Ethereum compatibility through EVM-based parachains like [Moonbeam](https://docs.moonbeam.network/){target=\_blank}, [Astar](https://docs.astar.network/){target=\_blank}, and [Acala](https://evmdocs.acala.network/){target=\_blank} or prefer PolkaVM-based development with [ink!](https://use.ink/docs/v6/){target=\_blank}, the Polkadot ecosystem accommodates a range of diverse developers. -![Transaction lifecycle diagram](/images/reference/parachains/blocks-transactions-fees/transactions/transactions-01.webp){ style="background:white" } +These guides explore the diverse smart contract options available in the Polkadot ecosystem, helping developers understand the unique advantages of each approach and make informed decisions about where to deploy their decentralized applications. -### Validate and Queue +## Native Smart Contracts -Once a transaction reaches an authoring node, it undergoes an initial validation process to ensure it meets specific conditions defined in the runtime. This validation includes checks for: +### Introduction -- **Correct nonce**: Ensures the transaction is sequentially valid for the account. -- **Sufficient funds**: Confirms the account can cover any associated transaction fees. -- **Signature validity**: Verifies that the sender's signature matches the transaction data. +Polkadot Hub enables smart contract deployment and execution through PolkaVM, a cutting-edge virtual machine designed specifically for the Polkadot ecosystem. This native integration allows developers to deploy smart contracts directly on Polkadot's system chain while maintaining compatibility with Ethereum development tools and workflows. -After these checks, valid transactions are placed in the transaction pool, where they are queued for inclusion in a block. The transaction pool regularly re-validates queued transactions to ensure they remain valid before being processed. To reach consensus, two-thirds of the nodes must agree on the order of the transactions executed and the resulting state change. Transactions are validated and queued on the local node in a transaction pool to prepare for consensus. +### Smart Contract Development -#### Transaction Pool +The smart contract platform on Polkadot Hub combines _Polkadot's robust security and scalability_ with the extensive Ethereum development ecosystem. Developers can utilize familiar Ethereum libraries for contract interactions and leverage industry-standard development environments for writing and testing smart contracts. -The transaction pool is responsible for managing valid transactions. It ensures that only transactions that pass initial validity checks are queued. Transactions that fail validation, expire, or become invalid for other reasons are removed from the pool. +Polkadot Hub provides _full Ethereum JSON-RPC API compatibility_, ensuring seamless integration with existing development tools and services. This compatibility enables developers to maintain their preferred workflows while building on Polkadot's native infrastructure. -The transaction pool organizes transactions into two queues: +### Technical Architecture -- **Ready queue**: Transactions that are valid and ready to be included in a block. -- **Future queue**: Transactions that are not yet valid but could be in the future, such as transactions with a nonce too high for the current state. +PolkaVM, the underlying virtual machine, utilizes a RISC-V-based register architecture _optimized for the Polkadot ecosystem_. This design choice offers several advantages: -Details on how the transaction pool validates transactions, including fee and signature handling, can be found in the [`validate_transaction`](https://paritytech.github.io/polkadot-sdk/master/sp_transaction_pool/runtime_api/trait.TaggedTransactionQueue.html#method.validate_transaction){target=\_blank} method. +- Enhanced performance for smart contract execution. +- Improved gas efficiency for complex operations. +- Native compatibility with Polkadot's runtime environment. +- Optimized storage and state management. -#### Invalid Transactions +### Development Tools and Resources -If a transaction is invalid, for example, due to an invalid signature or insufficient funds, it is rejected and won't be added to the block. Invalid transactions might be rejected for reasons such as: +Polkadot Hub supports a comprehensive suite of development tools familiar to Ethereum developers. The platform integrates with popular development frameworks, testing environments, and deployment tools. Key features include: -- The transaction has already been included in a block. -- The transaction's signature does not match the sender. -- The transaction is too large to fit in the current block. +- Contract development in Solidity or Rust. +- Support for standard Ethereum development libraries. +- Integration with widely used development environments. +- Access to blockchain explorers and indexing solutions. +- Compatibility with contract monitoring and management tools. -### Transaction Ordering and Priority +### Cross-Chain Capabilities -When a node is selected as the next block author, it prioritizes transactions based on weight, length, and tip amount. The goal is to fill the block with high-priority transactions without exceeding its maximum size or computational limits. Transactions are ordered as follows: +Smart contracts deployed on Polkadot Hub can leverage Polkadot's [cross-consensus messaging (XCM) protocol](/parachains/interoperability/get-started/){target=\_blank} protocol to seamlessly _transfer tokens and call functions on other blockchain networks_ within the Polkadot ecosystem, all without complex bridging infrastructure or third-party solutions. For further references, check the [Interoperability](/develop/interoperability/){target=\_blank} section. -- **Inherents first**: Inherent transactions, such as block timestamp updates, are always placed first. -- **Nonce-based ordering**: Transactions from the same account are ordered by their nonce. -- **Fee-based ordering**: Among transactions with the same nonce or priority level, those with higher fees are prioritized. +### Use Cases -### Transaction Execution +Polkadot Hub's smart contract platform is suitable for a wide range of applications: -Once a block author selects transactions from the pool, the transactions are executed in priority order. As each transaction is processed, the state changes are written directly to the chain's storage. It's important to note that these changes are not cached, meaning a failed transaction won't revert earlier state changes, which could leave the block in an inconsistent state. +- DeFi protocols leveraging _cross-chain capabilities_. +- NFT platforms utilizing Polkadot's native token standards. +- Governance systems integrated with Polkadot's democracy mechanisms. +- Cross-chain bridges and asset management solutions. -Events are also written to storage. Runtime logic should not emit an event before performing the associated actions. If the associated transaction fails after the event was emitted, the event will not revert. +## Other Smart Contract Environments -## Transaction Mortality +Beyond Polkadot Hub's native PolkaVM support, the ecosystem offers two main alternatives for smart contract development: -Transactions in the network can be configured as either mortal (with expiration) or immortal (without expiration). Every transaction payload contains a block checkpoint (reference block number and hash) and an era/validity period that determines how many blocks after the checkpoint the transaction remains valid. +- **EVM-compatible parachains**: Provide access to Ethereum's extensive developer ecosystem, smart contract portability, and established tooling like Hardhat, Remix, Foundry, and OpenZeppelin. The main options include Moonbeam (the first full Ethereum-compatible parachain serving as an interoperability hub), Astar (featuring dual VM support for both EVM and WebAssembly contracts), and Acala (DeFi-focused with enhanced Acala EVM+ offering advanced DeFi primitives). -When a transaction is submitted, the network validates it against these parameters. If the transaction is not included in a block within the specified validity window, it is automatically removed from the transaction queue. +- **Rust (ink!)**: ink! is a Rust-based framework that can compile to PolkaVM. It uses [`#[ink(...)]`](https://use.ink/docs/v6/macros-attributes/){target=\_blank} attribute macros to create Polkadot SDK-compatible PolkaVM bytecode, offering strong memory safety from Rust, an advanced type system, high-performance PolkaVM execution, and platform independence with sandboxed security. -- **Mortal transactions**: Have a finite lifespan and will expire after a specified number of blocks. For example, a transaction with a block checkpoint of 1000 and a validity period of 64 blocks will be valid from blocks 1000 to 1064. -- **Immortal transactions**: Never expire and remain valid indefinitely. To create an immortal transaction, set the block checkpoint to 0 (genesis block), use the genesis hash as a reference, and set the validity period to 0. +Each environment provides unique advantages based on developer preferences and application requirements. -However, immortal transactions pose significant security risks through replay attacks. If an account is reaped (balance drops to zero, account removed) and later re-funded, malicious actors can replay old immortal transactions. +## Where to Go Next -The blockchain maintains only a limited number of prior block hashes for reference validation, called `BlockHashCount`. If your validity period exceeds `BlockHashCount`, the effective validity period becomes the minimum of your specified period and the block hash count. +Developers can use their existing Ethereum development tools and connect to Polkadot Hub's RPC endpoints. The platform's Ethereum compatibility layer ensures a smooth transition for teams already building on Ethereum-compatible chains. -## Unique Identifiers for Extrinsics +Subsequent sections of this guide provide detailed information about specific development tools, advanced features, and best practices for building on Polkadot Hub. -Transaction hashes are **not unique identifiers** in Polkadot SDK-based chains. +
-Key differences from traditional blockchains: +- Guide __Libraries__ -- Transaction hashes serve only as fingerprints of transaction information. -- Multiple valid transactions can share the same hash. -- Hash uniqueness assumptions lead to serious issues. + --- -For example, when an account is reaped (removed due to insufficient balance) and later recreated, it resets to nonce 0, allowing identical transactions to be valid at different points: + Explore essential libraries to optimize smart contract development and interaction. -| Block | Extrinsic Index | Hash | Origin | Nonce | Call | Result | -|-------|----------------|------|-----------|-------|---------------------|-------------------------------| -| 100 | 0 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Account A reaped | -| 150 | 5 | 0x02 | Account B | 4 | Transfer 7 DOT to A | Account A created (nonce = 0) | -| 200 | 2 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Successful transaction | + [:octicons-arrow-right-24: Reference](/smart-contracts/libraries/ethers-js/) -Notice that blocks 100 and 200 contain transactions with identical hashes (0x01) but are completely different, valid operations occurring at different times. +- Guide __Dev Environments__ -Additional complexity comes from Polkadot SDK's origin abstraction. Origins can represent collectives, governance bodies, or other non-account entities that don't maintain nonces like regular accounts and might dispatch identical calls multiple times with the same hash values. Each execution occurs in different chain states with different results. + --- -The correct way to uniquely identify an extrinsic on a Polkadot SDK-based chain is to use the block ID (height or hash) and the extrinsic index. Since the Polkadot SDK defines blocks as headers plus ordered arrays of extrinsics, the index position within a canonical block provides guaranteed uniqueness. + Set up your development environment for seamless contract deployment and testing. -## Additional Resources + [:octicons-arrow-right-24: Reference](/smart-contracts/dev-environments/local-dev-node/) -For a video overview of the lifecycle of transactions and the types of transactions that exist, see the [Transaction lifecycle](https://www.youtube.com/watch?v=3pfM0GOp02c){target=\_blank} seminar from Parity Tech. +
--- @@ -6444,436 +3692,3 @@ The system maintains precise conversion mechanisms between: - Different resource metrics within the multi-dimensional model. This ensures accurate fee calculation while maintaining compatibility with existing Ethereum tools and workflows. - - ---- - -Page Title: Transactions Weights and Fees - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-fees.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/fees/ -- Summary: Overview of transaction weights and fees in Polkadot SDK chains, detailing how fees are calculated using a defined formula and runtime specifics. - -# Transactions Weights and Fees - -## Introductions - -When transactions are executed, or data is stored on-chain, the activity changes the chain's state and consumes blockchain resources. Because the resources available to a blockchain are limited, managing how operations on-chain consume them is important. In addition to being limited in practical terms, such as storage capacity, blockchain resources represent a potential attack vector for malicious users. For example, a malicious user might attempt to overload the network with messages to stop the network from producing new blocks. To protect blockchain resources from being drained or overloaded, you need to manage how they are made available and how they are consumed. The resources to be aware of include: - -- Memory usage -- Storage input and output -- Computation -- Transaction and block size -- State database size - -The Polkadot SDK provides block authors with several ways to manage access to resources and to prevent individual components of the chain from consuming too much of any single resource. Two of the most important mechanisms available to block authors are weights and transaction fees. - -[Weights](/reference/glossary/#weight){target=\_blank} manage the time it takes to validate a block and characterize the time it takes to execute the calls in the block's body. By controlling the execution time a block can consume, weights set limits on storage input, output, and computation. - -Some of the weight allowed for a block is consumed as part of the block's initialization and finalization. The weight might also be used to execute mandatory inherent extrinsic calls. To help ensure blocks don’t consume too much execution time and prevent malicious users from overloading the system with unnecessary calls, weights are combined with transaction fees. - -[Transaction fees](/reference/parachains/blocks-transactions-fees/transactions/#transaction-fees){target=\_blank} provide an economic incentive to limit execution time, computation, and the number of calls required to perform operations. Transaction fees are also used to make the blockchain economically sustainable because they are typically applied to transactions initiated by users and deducted before a transaction request is executed. - -## How Fees are Calculated - -The final fee for a transaction is calculated using the following parameters: - -- **`base fee`**: This is the minimum amount a user pays for a transaction. It is declared a base weight in the runtime and converted to a fee using the [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} conversion. -- **`weight fee`**: A fee proportional to the execution time (input and output and computation) that a transaction consumes. -- **`length fee`**: A fee proportional to the encoded length of the transaction. -- **`tip`**: An optional tip to increase the transaction’s priority, giving it a higher chance to be included in the transaction queue. - -The base fee and proportional weight and length fees constitute the inclusion fee. The inclusion fee is the minimum fee that must be available for a transaction to be included in a block. - -```text -inclusion fee = base fee + weight fee + length fee -``` - -Transaction fees are withdrawn before the transaction is executed. After the transaction is executed, the weight can be adjusted to reflect the resources used. If a transaction uses fewer resources than expected, the transaction fee is corrected, and the adjusted transaction fee is deposited. - -## Using the Transaction Payment Pallet - -The [Transaction Payment pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/transaction-payment){target=\_blank} provides the basic logic for calculating the inclusion fee. You can also use the Transaction Payment pallet to: - -- Convert a weight value into a deductible fee based on a currency type using [`Config::WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank}. -- Update the fee for the next block by defining a multiplier based on the chain’s final state at the end of the previous block using [`Config::FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank}. -- Manage the withdrawal, refund, and deposit of transaction fees using [`Config::OnChargeTransaction`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.OnChargeTransaction){target=\_blank}. - -You can learn more about these configuration traits in the [Transaction Payment documentation](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_payment/index.html){target=\_blank}. - -### Understanding the Inclusion Fee - -The formula for calculating the inclusion fee is as follows: - -```text -inclusion_fee = base_fee + length_fee + [targeted_fee_adjustment * weight_fee] -``` - -And then, for calculating the final fee: - -```text -final_fee = inclusion_fee + tip -``` - -In the first formula, the `targeted_fee_adjustment` is a multiplier that can tune the final fee based on the network’s congestion. - -- The `base_fee` derived from the base weight covers inclusion overhead like signature verification. -- The `length_fee` is a per-byte fee that is multiplied by the length of the encoded extrinsic. -- The `weight_fee` fee is calculated using two parameters: - - The `ExtrinsicBaseWeight` that is declared in the runtime and applies to all extrinsics. - - The `#[pallet::weight]` annotation that accounts for an extrinsic's complexity. - -To convert the weight to `Currency`, the runtime must define a `WeightToFee` struct that implements a conversion function, [`Convert`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/struct.Pallet.html#method.weight_to_fee){target=\_blank}. - -Note that the extrinsic sender is charged the inclusion fee before the extrinsic is invoked. The fee is deducted from the sender's balance even if the transaction fails upon execution. - -### Accounts with an Insufficient Balance - -If an account does not have a sufficient balance to pay the inclusion fee and remain alive—that is, enough to pay the inclusion fee and maintain the minimum existential deposit—then you should ensure the transaction is canceled so that no fee is deducted and the transaction does not begin execution. - -The Polkadot SDK doesn't enforce this rollback behavior. However, this scenario would be rare because the transaction queue and block-making logic perform checks to prevent it before adding an extrinsic to a block. - -### Fee Multipliers - -The inclusion fee formula always results in the same fee for the same input. However, weight can be dynamic and—based on how [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} is defined—the final fee can include some degree of variability. -The Transaction Payment pallet provides the [`FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank} configurable parameter to account for this variability. - -The Polkadot network inspires the default update function and implements a targeted adjustment in which a target saturation level of block weight is defined. If the previous block is more saturated, the fees increase slightly. Similarly, if the last block has fewer transactions than the target, fees are decreased by a small amount. For more information about fee multiplier adjustments, see the [Web3 Research Page](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank}. - -## Transactions with Special Requirements - -Inclusion fees must be computable before execution and can only represent fixed logic. Some transactions warrant limiting resources with other strategies. For example: - -- Bonds are a type of fee that might be returned or slashed after some on-chain event. For example, you might want to require users to place a bond to participate in a vote. The bond might then be returned at the end of the referendum or slashed if the voter attempted malicious behavior. -- Deposits are fees that might be returned later. For example, you might require users to pay a deposit to execute an operation that uses storage. The user’s deposit could be returned if a subsequent operation frees up storage. -- Burn operations are used to pay for a transaction based on its internal logic. For example, a transaction might burn funds from the sender if the transaction creates new storage items to pay for the increased state size. -- Limits enable you to enforce constant or configurable limits on specific operations. For example, the default [Staking pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/staking){target=\_blank} only allows nominators to nominate 16 validators to limit the complexity of the validator election process. - -It is important to note that if you query the chain for a transaction fee, it only returns the inclusion fee. - -## Default Weight Annotations - -All dispatchable functions in the Polkadot SDK must specify a weight. The way of doing that is using the annotation-based system that lets you combine fixed values for database read/write weight and/or fixed values based on benchmarks. The most basic example would look like this: - -```rust -#[pallet::weight(100_000)] -fn my_dispatchable() { - // ... -} -``` - -Note that the [`ExtrinsicBaseWeight`](https://crates.parity.io/frame_support/weights/constants/struct.ExtrinsicBaseWeight.html){target=\_blank} is automatically added to the declared weight to account for the costs of simply including an empty extrinsic into a block. - -### Weights and Database Read/Write Operations - -To make weight annotations independent of the deployed database backend, they are defined as a constant and then used in the annotations when expressing database accesses performed by the dispatchable: - -```rust -#[pallet::weight(T::DbWeight::get().reads_writes(1, 2) + 20_000)] -fn my_dispatchable() { - // ... -} -``` - -This dispatchable allows one database to read and two to write, in addition to other things that add the additional 20,000. Database access is generally every time a value declared inside the [`#[pallet::storage]`](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/attr.storage.html){target=\_blank} block is accessed. However, unique accesses are counted because after a value is accessed, it is cached, and reaccessing it does not result in a database operation. That is: - -- Multiple reads of the exact value count as one read. -- Multiple writes of the exact value count as one write. -- Multiple reads of the same value, followed by a write to that value, count as one read and one write. -- A write followed by a read-only counts as one write. - -### Dispatch Classes - -Dispatches are broken into three classes: - -- Normal -- Operational -- Mandatory - -If a dispatch is not defined as `Operational` or `Mandatory` in the weight annotation, the dispatch is identified as `Normal` by default. You can specify that the dispatchable uses another class like this: - -```rust -#[pallet::dispatch((DispatchClass::Operational))] -fn my_dispatchable() { - // ... -} -``` - -This tuple notation also allows you to specify a final argument determining whether the user is charged based on the annotated weight. If you don't specify otherwise, `Pays::Yes` is assumed: - -```rust -#[pallet::dispatch(DispatchClass::Normal, Pays::No)] -fn my_dispatchable() { - // ... -} -``` - -#### Normal Dispatches - -Dispatches in this class represent normal user-triggered transactions. These types of dispatches only consume a portion of a block's total weight limit. For information about the maximum portion of a block that can be consumed for normal dispatches, see [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Normal dispatches are sent to the transaction pool. - -#### Operational Dispatches - -Unlike normal dispatches, which represent the usage of network capabilities, operational dispatches are those that provide network capabilities. Operational dispatches can consume the entire weight limit of a block. They are not bound by the [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Dispatches in this class are given maximum priority and are exempt from paying the [`length_fee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/){target=\_blank}. - -#### Mandatory Dispatches - -Mandatory dispatches are included in a block even if they cause the block to surpass its weight limit. You can only use the mandatory dispatch class for inherent transactions that the block author submits. This dispatch class is intended to represent functions in the block validation process. Because these dispatches are always included in a block regardless of the function weight, the validation process must prevent malicious nodes from abusing the function to craft valid but impossibly heavy blocks. You can typically accomplish this by ensuring that: - -- The operation performed is always light. -- The operation can only be included in a block once. - -To make it more difficult for malicious nodes to abuse mandatory dispatches, they cannot be included in blocks that return errors. This dispatch class serves the assumption that it is better to allow an overweight block to be created than not to allow any block to be created at all. - -### Dynamic Weights - -In addition to purely fixed weights and constants, the weight calculation can consider the input arguments of a dispatchable. The weight should be trivially computable from the input arguments with some basic arithmetic: - -```rust -use frame_support:: { - dispatch:: { - DispatchClass::Normal, - Pays::Yes, - }, - weights::Weight, -}; - -#[pallet::weight(FunctionOf( - |args: (&Vec,)| args.0.len().saturating_mul(10_000), - ) -] -fn handle_users(origin, calls: Vec) { - // Do something per user -} -``` - -## Post Dispatch Weight Correction - -Depending on the execution logic, a dispatchable function might consume less weight than was prescribed pre-dispatch. To correct weight, the function declares a different return type and returns its actual weight: - -```rust -#[pallet::weight(10_000 + 500_000_000)] -fn expensive_or_cheap(input: u64) -> DispatchResultWithPostInfo { - let was_heavy = do_calculation(input); - - if (was_heavy) { - // None means "no correction" from the weight annotation. - Ok(None.into()) - } else { - // Return the actual weight consumed. - Ok(Some(10_000).into()) - } -} -``` - -## Custom Fees - -You can also define custom fee systems through custom weight functions or inclusion fee functions. - -### Custom Weights - -Instead of using the default weight annotations, you can create a custom weight calculation type using the weights module. The custom weight calculation type must implement the following traits: - -- [`WeighData`](https://crates.parity.io/frame_support/weights/trait.WeighData.html){target=\_blank} to determine the weight of the dispatch. -- [`ClassifyDispatch`](https://crates.parity.io/frame_support/weights/trait.ClassifyDispatch.html){target=\_blank} to determine the class of the dispatch. -- [`PaysFee`](https://crates.parity.io/frame_support/weights/trait.PaysFee.html){target=\_blank} to determine whether the sender of the dispatch pays fees. - -The Polkadot SDK then bundles the output information of the three traits into the [`DispatchInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_support/dispatch/struct.DispatchInfo.html){target=\_blank} struct and provides it by implementing the [`GetDispatchInfo`](https://docs.rs/frame-support/latest/frame_support/dispatch/trait.GetDispatchInfo.html){target=\_blank} for all `Call` variants and opaque extrinsic types. This is used internally by the System and Executive modules. - -`ClassifyDispatch`, `WeighData`, and `PaysFee` are generic over T, which gets resolved into the tuple of all dispatch arguments except for the origin. The following example illustrates a struct that calculates the weight as `m * len(args)`, where `m` is a given multiplier and args is the concatenated tuple of all dispatch arguments. In this example, the dispatch class is `Operational` if the transaction has more than 100 bytes of length in arguments and will pay fees if the encoded length exceeds 10 bytes. - -```rust -struct LenWeight(u32); -impl WeighData for LenWeight { - fn weigh_data(&self, target: T) -> Weight { - let multiplier = self.0; - let encoded_len = target.encode().len() as u32; - multiplier * encoded_len - } -} - -impl ClassifyDispatch for LenWeight { - fn classify_dispatch(&self, target: T) -> DispatchClass { - let encoded_len = target.encode().len() as u32; - if encoded_len > 100 { - DispatchClass::Operational - } else { - DispatchClass::Normal - } - } -} - -impl PaysFee { - fn pays_fee(&self, target: T) -> Pays { - let encoded_len = target.encode().len() as u32; - if encoded_len > 10 { - Pays::Yes - } else { - Pays::No - } - } -} -``` - -A weight calculator function can also be coerced to the final type of the argument instead of defining it as a vague type that can be encoded. The code would roughly look like this: - -```rust -struct CustomWeight; -impl WeighData<(&u32, &u64)> for CustomWeight { - fn weigh_data(&self, target: (&u32, &u64)) -> Weight { - ... - } -} - -// given a dispatch: -#[pallet::call] -impl, I: 'static> Pallet { - #[pallet::weight(CustomWeight)] - fn foo(a: u32, b: u64) { ... } -} -``` - -In this example, the `CustomWeight` can only be used in conjunction with a dispatch with a particular signature `(u32, u64)`, as opposed to `LenWeight`, which can be used with anything because there aren't any assumptions about ``. - -#### Custom Inclusion Fee - -The following example illustrates how to customize your inclusion fee. You must configure the appropriate associated types in the respective module. - -```rust -// Assume this is the balance type -type Balance = u64; - -// Assume we want all the weights to have a `100 + 2 * w` conversion to fees -struct CustomWeightToFee; -impl WeightToFee for CustomWeightToFee { - fn convert(w: Weight) -> Balance { - let a = Balance::from(100); - let b = Balance::from(2); - let w = Balance::from(w); - a + b * w - } -} - -parameter_types! { - pub const ExtrinsicBaseWeight: Weight = 10_000_000; -} - -impl frame_system::Config for Runtime { - type ExtrinsicBaseWeight = ExtrinsicBaseWeight; -} - -parameter_types! { - pub const TransactionByteFee: Balance = 10; -} - -impl transaction_payment::Config { - type TransactionByteFee = TransactionByteFee; - type WeightToFee = CustomWeightToFee; - type FeeMultiplierUpdate = TargetedFeeAdjustment; -} - -struct TargetedFeeAdjustment(sp_std::marker::PhantomData); -impl> WeightToFee for TargetedFeeAdjustment { - fn convert(multiplier: Fixed128) -> Fixed128 { - // Don't change anything. Put any fee update info here. - multiplier - } -} -``` - -## Additional Resources - -You now know the weight system, how it affects transaction fee computation, and how to specify weights for your dispatchable calls. The next step is determining the correct weight for your dispatchable operations. You can use Substrate benchmarking functions and frame-benchmarking calls to test your functions with different parameters and empirically determine the proper weight in their worst-case scenarios. - -- [Benchmark](/parachains/customize-runtime/pallet-development/benchmark-pallet/) -- [`SignedExtension`](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} -- [Custom weights for the Example pallet](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/substrate/frame/examples/basic/src/weights.rs){target=\_blank} -- [Web3 Foundation Research](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank} - - ---- - -Page Title: XCM Tools - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-xcm-tools.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/xcm-tools/ -- Summary: Explore essential XCM tools across Polkadot, crafted to enhance cross-chain functionality and integration within the ecosystem. - -# XCM Tools - -## Introduction - -As described in the [Interoperability](/develop/interoperability){target=\_blank} section, XCM (Cross-Consensus Messaging) is a protocol used in the Polkadot and Kusama ecosystems to enable communication and interaction between chains. It facilitates cross-chain communication, allowing assets, data, and messages to flow seamlessly across the ecosystem. - -As XCM is central to enabling communication between blockchains, developers need robust tools to help interact with, build, and test XCM messages. Several XCM tools simplify working with the protocol by providing libraries, frameworks, and utilities that enhance the development process, ensuring that applications built within the Polkadot ecosystem can efficiently use cross-chain functionalities. - -## Popular XCM Tools - -### Moonsong Labs XCM Tools - -[Moonsong Labs XCM Tools](https://github.com/Moonsong-Labs/xcm-tools){target=\_blank} provides a collection of scripts for managing and testing XCM operations between Polkadot SDK-based runtimes. These tools allow performing tasks like asset registration, channel setup, and XCM initialization. Key features include: - -- **Asset registration**: Registers assets, setting units per second (up-front fees), and configuring error (revert) codes. -- **XCM initializer**: Initializes XCM, sets default XCM versions, and configures revert codes for XCM-related precompiles. -- **HRMP manipulator**: Manages HRMP channel actions, including opening, accepting, or closing channels. -- **XCM-Transactor-Info-Setter**: Configures transactor information, including extra weight and fee settings. -- **Decode XCM**: Decodes XCM messages on the relay chain or parachains to help interpret cross-chain communication. - -To get started, clone the repository and install the required dependencies: - -```bash -git clone https://github.com/Moonsong-Labs/xcm-tools && -cd xcm-tools && -yarn install -``` - -For a full overview of each script, visit the [scripts](https://github.com/Moonsong-Labs/xcm-tools/tree/main/scripts){target=\_blank} directory or refer to the [official documentation](https://github.com/Moonsong-Labs/xcm-tools/blob/main/README.md){target=\_blank} on GitHub. - -### ParaSpell - -[ParaSpell](/reference/tools/paraspell/){target=\_blank} is a collection of open-source XCM tools that streamline cross-chain asset transfers and interactions across the Polkadot and Kusama ecosystems. It provides developers with an intuitive interface to build, test, and deploy interoperable dApps, featuring message composition, decoding, and practical utilities for parachain interactions that simplify debugging and cross-chain communication optimization. - -### Astar XCM Tools - -The [Astar parachain](https://github.com/AstarNetwork/Astar/tree/master){target=\_blank} offers a crate with a set of utilities for interacting with the XCM protocol. The [xcm-tools](https://github.com/AstarNetwork/Astar/tree/master/bin/xcm-tools){target=\_blank} crate provides a straightforward method for users to locate a sovereign account or calculate an XC20 asset ID. Some commands included by the xcm-tools crate allow users to perform the following tasks: - -- **Sovereign accounts**: Obtain the sovereign account address for any parachain, either on the Relay Chain or for sibling parachains, using a simple command. -- **XC20 EVM addresses**: Generate XC20-compatible Ethereum addresses for assets by entering the asset ID, making it easy to integrate assets across Ethereum-compatible environments. -- **Remote accounts**: Retrieve remote account addresses needed for multi-location compatibility, using flexible options to specify account types and parachain IDs. - -To start using these tools, clone the [Astar repository](https://github.com/AstarNetwork/Astar){target=\_blank} and compile the xcm-tools package: - -```bash -git clone https://github.com/AstarNetwork/Astar && -cd Astar && -cargo build --release -p xcm-tools -``` - -After compiling, verify the setup with the following command: - -```bash -./target/release/xcm-tools --help -``` -For more details on using Astar xcm-tools, consult the [official documentation](https://docs.astar.network/docs/learn/interoperability/xcm/integration/tools/){target=\_blank}. - -### Chopsticks - -The Chopsticks library provides XCM functionality for testing XCM messages across networks, enabling you to fork multiple parachains along with a relay chain. For further details, see the [Chopsticks documentation](/tutorials/polkadot-sdk/testing/fork-live-chains/){target=\_blank} about XCM. - -### Moonbeam XCM SDK - -The [Moonbeam XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk){target=\_blank} enables developers to easily transfer assets between chains, either between parachains or between a parachain and the relay chain, within the Polkadot/Kusama ecosystem. With the SDK, you don't need to worry about determining the [Multilocation](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#7-universal-consensus-location-identifiers){target=\_blank} of the origin or destination assets or which extrinsics are used on which networks. - -The SDK consists of two main packages: - -- **[XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/sdk){target=\_blank}**: Core SDK for executing XCM transfers between chains in the Polkadot/Kusama ecosystem. -- **[MRL SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/mrl){target=\_blank}**: Extension of the XCM SDK for transferring liquidity into and across the Polkadot ecosystem from other ecosystems like Ethereum. - -Key features include: - -- **Simplified asset transfers**: Abstracts away complex multilocation determinations and extrinsic selection. -- **Cross-ecosystem support**: Enables transfers between Polkadot/Kusama chains and external ecosystems. -- **Developer-friendly API**: Provides intuitive interfaces for cross-chain functionality. -- **Comprehensive documentation**: Includes usage guides and API references for both packages. - -For detailed usage examples and API documentation, visit the [official Moonbeam XCM SDK documentation](https://moonbeam-foundation.github.io/xcm-sdk/latest/){target=\_blank}. diff --git a/.ai/categories/parachains.md b/.ai/categories/parachains.md index 659908c58..87ce8b558 100644 --- a/.ai/categories/parachains.md +++ b/.ai/categories/parachains.md @@ -1632,440 +1632,6 @@ Once the `weights.rs` is generated, you must integrate it with your pallet. - Read the [FRAME Benchmarking and Weights](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/frame_benchmarking_weight/index.html){target=_blank} reference document, a concise guide which details how weights and benchmarking work. ---- - -Page Title: Blocks - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-blocks.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/blocks/ -- Summary: Understand how blocks are produced, validated, and imported in Polkadot SDK-based blockchains, covering initialization, finalization, and authoring processes. - -# Blocks - -## Introduction - -In the Polkadot SDK, blocks are fundamental to the functioning of the blockchain, serving as containers for [transactions](/reference/parachains/blocks-transactions-fees/transactions/){target=\_blank} and changes to the chain's state. Blocks consist of headers and an array of transactions, ensuring the integrity and validity of operations on the network. This guide explores the essential components of a block, the process of block production, and how blocks are validated and imported across the network. By understanding these concepts, developers can better grasp how blockchains maintain security, consistency, and performance within the Polkadot ecosystem. - -## What is a Block? - -In the Polkadot SDK, a block is a fundamental unit that encapsulates both the header and an array of transactions. The block header includes critical metadata to ensure the integrity and sequence of the blockchain. Here's a breakdown of its components: - -- **Block height**: Indicates the number of blocks created in the chain so far. -- **Parent hash**: The hash of the previous block, providing a link to maintain the blockchain's immutability. -- **Transaction root**: Cryptographic digest summarizing all transactions in the block. -- **State root**: A cryptographic digest representing the post-execution state. -- **Digest**: Additional information that can be attached to a block, such as consensus-related messages. - -Each transaction is part of a series that is executed according to the runtime's rules. The transaction root is a cryptographic digest of this series, which prevents alterations and enables succinct verification by light clients. This verification process allows light clients to confirm whether a transaction exists in a block with only the block header, avoiding downloading the entire block. - -## Block Production - -When an authoring node is authorized to create a new block, it selects transactions from the transaction queue based on priority. This step, known as block production, relies heavily on the executive module to manage the initialization and finalization of blocks. The process is summarized as follows: - -### Initialize Block - -The block initialization process begins with a series of function calls that prepare the block for transaction execution: - -1. **Call `on_initialize`**: The executive module calls the [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} hook from the system pallet and other runtime pallets to prepare for the block's transactions. -2. **Coordinate runtime calls**: Coordinates function calls in the order defined by the transaction queue. -3. **Verify information**: Once [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} functions are executed, the executive module checks the parent hash in the block header and the trie root to verify information is consistent. - -### Finalize Block - -Once transactions are processed, the block must be finalized before being broadcast to the network. The finalization steps are as follows: - -1. **Call `on_finalize`**: The executive module calls the [`on_finalize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_finalize){target=\_blank} hooks in each pallet to ensure any remaining state updates or checks are completed before the block is sealed and published. -2. **Verify information**: The block's digest and storage root in the header are checked against the initialized block to ensure consistency. -3. **Call `on_idle`**: The [`on_idle`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_idle){target=\_blank} hook is triggered to process any remaining tasks using the leftover weight from the block. - -## Block Authoring and Import - -Once the block is finalized, it is gossiped to other nodes in the network. Nodes follow this procedure: - -1. **Receive transactions**: The authoring node collects transactions from the network. -2. **Validate**: Transactions are checked for validity. -3. **Queue**: Valid transactions are placed in the transaction pool for execution. -4. **Execute**: State changes are made as the transactions are executed. -5. **Publish**: The finalized block is broadcast to the network. - -### Block Import Queue - -After a block is published, other nodes on the network can import it into their chain state. The block import queue is part of the outer node in every Polkadot SDK-based node and ensures incoming blocks are valid before adding them to the node's state. - -In most cases, you don't need to know details about how transactions are gossiped or how other nodes on the network import blocks. The following traits are relevant, however, if you plan to write any custom consensus logic or want a deeper dive into the block import queue: - -- **[`ImportQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.ImportQueue.html){target=\_blank}**: The trait that defines the block import queue. -- **[`Link`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Link.html){target=\_blank}**: The trait that defines the link between the block import queue and the network. -- **[`BasicQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/struct.BasicQueue.html){target=\_blank}**: A basic implementation of the block import queue. -- **[`Verifier`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Verifier.html){target=\_blank}**: The trait that defines the block verifier. -- **[`BlockImport`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/block_import/trait.BlockImport.html){target=\_blank}**: The trait that defines the block import process. - -These traits govern how blocks are validated and imported across the network, ensuring consistency and security. - -## Additional Resources - -To learn more about the block structure in the Polkadot SDK runtime, see the [`Block` reference](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.Block.html){target=\_blank} entry in the Rust Docs. - - ---- - -Page Title: Chain Data - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-chain-data.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/chain-data/ -- Summary: Learn how to expose and utilize chain data for blockchain applications. Discover runtime metadata, RPC APIs, and tools for efficient development. - -# Chain Data - -## Introduction - -Understanding and leveraging on-chain data is a fundamental aspect of blockchain development. Whether you're building frontend applications or backend systems, accessing and decoding runtime metadata is vital to interacting with the blockchain. This guide introduces you to the tools and processes for generating and retrieving metadata, explains its role in application development, and outlines the additional APIs available for interacting with a Polkadot node. By mastering these components, you can ensure seamless communication between your applications and the blockchain. - -## Application Development - -You might not be directly involved in building frontend applications as a blockchain developer. However, most applications that run on a blockchain require some form of frontend or user-facing client to enable users or other programs to access and modify the data that the blockchain stores. For example, you might develop a browser-based, mobile, or desktop application that allows users to submit transactions, post articles, view their assets, or track previous activity. The backend for that application is configured in the runtime logic for your blockchain, but the frontend client makes the runtime features accessible to your users. - -For your custom chain to be useful to others, you'll need to provide a client application that allows users to view, interact with, or update information that the blockchain keeps track of. In this article, you'll learn how to expose information about your runtime so that client applications can use it, see examples of the information exposed, and explore tools and libraries that use it. - -## Understand Metadata - -Polkadot SDK-based blockchain networks are designed to expose their runtime information, allowing developers to learn granular details regarding pallets, RPC calls, and runtime APIs. The metadata also exposes their related documentation. The chain's metadata is [SCALE-encoded](/reference/parachains/data-encoding/){target=\_blank}, allowing for the development of browser-based, mobile, or desktop applications to support the chain's runtime upgrades seamlessly. It is also possible to develop applications compatible with multiple Polkadot SDK-based chains simultaneously. - -## Expose Runtime Information as Metadata - -To interact with a node or the state of the blockchain, you need to know how to connect to the chain and access the exposed runtime features. This interaction involves a Remote Procedure Call (RPC) through a node endpoint address, commonly through a secure web socket connection. - -An application developer typically needs to know the contents of the runtime logic, including the following details: - -- Version of the runtime the application is connecting to. -- Supported APIs. -- Implemented pallets. -- Defined functions and corresponding type signatures. -- Defined custom types. -- Exposed parameters users can set. - -As the Polkadot SDK is modular and provides a composable framework for building blockchains, there are limitless opportunities to customize the schema of properties. Each runtime can be configured with its properties, including function calls and types, which can be changed over time with runtime upgrades. - -The Polkadot SDK enables you to generate the runtime metadata schema to capture information unique to a runtime. The metadata for a runtime describes the pallets in use and types defined for a specific runtime version. The metadata includes information about each pallet's storage items, functions, events, errors, and constants. The metadata also provides type definitions for any custom types included in the runtime. - -Metadata provides a complete inventory of a chain's runtime. It is key to enabling client applications to interact with the node, parse responses, and correctly format message payloads sent back to that chain. - -## Generate Metadata - -To efficiently use the blockchain's networking resources and minimize the data transmitted over the network, the metadata schema is encoded using the [Parity SCALE Codec](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank}. This encoding is done automatically through the [`scale-info`](https://docs.rs/scale-info/latest/scale_info/){target=\_blank}crate. - -At a high level, generating the metadata involves the following steps: - -1. The pallets in the runtime logic expose callable functions, types, parameters, and documentation that need to be encoded in the metadata. -2. The `scale-info` crate collects type information for the pallets in the runtime, builds a registry of the pallets that exist in a particular runtime, and the relevant types for each pallet in the registry. The type information is detailed enough to enable encoding and decoding for every type. -3. The [`frame-metadata`](https://github.com/paritytech/frame-metadata){target=\_blank} crate describes the structure of the runtime based on the registry provided by the `scale-info` crate. -4. Nodes provide the RPC method `state_getMetadata` to return a complete description of all the types in the current runtime as a hex-encoded vector of SCALE-encoded bytes. - -## Retrieve Runtime Metadata - -The type information provided by the metadata enables applications to communicate with nodes using different runtime versions and across chains that expose different calls, events, types, and storage items. The metadata also allows libraries to generate a substantial portion of the code needed to communicate with a given node, enabling libraries like [`subxt`](https://github.com/paritytech/subxt){target=\_blank} to generate frontend interfaces that are specific to a target chain. - -### Use Polkadot.js - -Visit the [Polkadot.js Portal](https://polkadot.js.org/apps/#/rpc){target=\_blank} and select the **Developer** dropdown in the top banner. Select **RPC Calls** to make the call to request metadata. Follow these steps to make the RPC call: - -1. Select **state** as the endpoint to call. -2. Select **`getMetadata(at)`** as the method to call. -3. Click **Submit RPC call** to submit the call and return the metadata in JSON format. - -### Use Curl - -You can fetch the metadata for the network by calling the node's RPC endpoint. This request returns the metadata in bytes rather than human-readable JSON: - -```sh -curl -H "Content-Type: application/json" \ --d '{"id":1, "jsonrpc":"2.0", "method": "state_getMetadata"}' \ -https://rpc.polkadot.io - -``` - -### Use Subxt - -[`subxt`](https://github.com/paritytech/subxt){target=\_blank} may also be used to fetch the metadata of any data in a human-readable JSON format: - -```sh -subxt metadata --url wss://rpc.polkadot.io --format json > spec.json -``` - -Another option is to use the [`subxt` explorer web UI](https://paritytech.github.io/subxt-explorer/#/){target=\_blank}. - -## Client Applications and Metadata - -The metadata exposes the expected way to decode each type, meaning applications can send, retrieve, and process application information without manual encoding and decoding. Client applications must use the [SCALE codec library](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank} to encode and decode RPC payloads to use the metadata. Client applications use the metadata to interact with the node, parse responses, and format message payloads sent to the node. - -## Metadata Format - -Although the SCALE-encoded bytes can be decoded using the `frame-metadata` and [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} libraries, there are other tools, such as `subxt` and the Polkadot-JS API, that can convert the raw data to human-readable JSON format. - -The types and type definitions included in the metadata returned by the `state_getMetadata` RPC call depend on the runtime's metadata version. - -In general, the metadata includes the following information: - -- A constant identifying the file as containing metadata. -- The version of the metadata format used in the runtime. -- Type definitions for all types used in the runtime and generated by the `scale-info` crate. -- Pallet information for the pallets included in the runtime in the order that they are defined in the `construct_runtime` macro. - -!!!tip - Depending on the frontend library used (such as the [Polkadot API](https://papi.how/){target=\_blank}), they may format the metadata differently than the raw format shown. - -The following example illustrates a condensed and annotated section of metadata decoded and converted to JSON: - -```json -[ - 1635018093, - { - "V14": { - "types": { - "types": [{}] - }, - "pallets": [{}], - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [{}] - }, - "ty": 141 - } - } -] - -``` - -The constant `1635018093` is a magic number that identifies the file as a metadata file. The rest of the metadata is divided into the `types`, `pallets`, and `extrinsic` sections: - -- The `types` section contains an index of the types and information about each type's type signature. -- The `pallets` section contains information about each pallet in the runtime. -- The `extrinsic` section describes the type identifier and transaction format version that the runtime uses. - -Different extrinsic versions can have varying formats, especially when considering [signed transactions](/reference/parachains/blocks-transactions-fees/transactions/#signed-transactions){target=\_blank}. - -### Pallets - -The following is a condensed and annotated example of metadata for a single element in the `pallets` array (the [`sudo`](https://paritytech.github.io/polkadot-sdk/master/pallet_sudo/index.html){target=\_blank} pallet): - -```json -{ - "name": "Sudo", - "storage": { - "prefix": "Sudo", - "entries": [ - { - "name": "Key", - "modifier": "Optional", - "ty": { - "Plain": 0 - }, - "default": [0], - "docs": ["The `AccountId` of the sudo key."] - } - ] - }, - "calls": { - "ty": 117 - }, - "event": { - "ty": 42 - }, - "constants": [], - "error": { - "ty": 124 - }, - "index": 8 -} - -``` - -Every element metadata contains the name of the pallet it represents and information about its storage, calls, events, and errors. You can look up details about the definition of the calls, events, and errors by viewing the type index identifier. The type index identifier is the `u32` integer used to access the type information for that item. For example, the type index identifier for calls in the Sudo pallet is 117. If you view information for that type identifier in the `types` section of the metadata, it provides information about the available calls, including the documentation for each call. - -For example, the following is a condensed excerpt of the calls for the Sudo pallet: - -```json -{ - "id": 117, - "type": { - "path": ["pallet_sudo", "pallet", "Call"], - "params": [ - { - "name": "T", - "type": null - } - ], - "def": { - "variant": { - "variants": [ - { - "name": "sudo", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 0, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "sudo_unchecked_weight", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - }, - { - "name": "weight", - "type": 8, - "typeName": "Weight" - } - ], - "index": 1, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "set_key", - "fields": [ - { - "name": "new", - "type": 103, - "typeName": "AccountIdLookupOf" - } - ], - "index": 2, - "docs": [ - "Authenticates current sudo key, sets the given AccountId (`new`) as the new sudo" - ] - }, - { - "name": "sudo_as", - "fields": [ - { - "name": "who", - "type": 103, - "typeName": "AccountIdLookupOf" - }, - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 3, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Signed` origin from a given account" - ] - } - ] - } - } - } -} - -``` - -For each field, you can access type information and metadata for the following: - -- **Storage metadata**: Provides the information required to enable applications to get information for specific storage items. -- **Call metadata**: Includes information about the runtime calls defined by the `#[pallet]` macro including call names, arguments and documentation. -- **Event metadata**: Provides the metadata generated by the `#[pallet::event]` macro, including the name, arguments, and documentation for each pallet event. -- **Constants metadata**: Provides metadata generated by the `#[pallet::constant]` macro, including the name, type, and hex-encoded value of the constant. -- **Error metadata**: Provides metadata generated by the `#[pallet::error]` macro, including the name and documentation for each pallet error. - -!!!tip - Type identifiers change from time to time, so you should avoid relying on specific type identifiers in your applications. - -### Extrinsic - -The runtime generates extrinsic metadata and provides useful information about transaction format. When decoded, the metadata contains the transaction version and the list of signed extensions. - -For example: - -```json -{ - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [ - { - "identifier": "CheckNonZeroSender", - "ty": 132, - "additional_signed": 41 - }, - { - "identifier": "CheckSpecVersion", - "ty": 133, - "additional_signed": 4 - }, - { - "identifier": "CheckTxVersion", - "ty": 134, - "additional_signed": 4 - }, - { - "identifier": "CheckGenesis", - "ty": 135, - "additional_signed": 11 - }, - { - "identifier": "CheckMortality", - "ty": 136, - "additional_signed": 11 - }, - { - "identifier": "CheckNonce", - "ty": 138, - "additional_signed": 41 - }, - { - "identifier": "CheckWeight", - "ty": 139, - "additional_signed": 41 - }, - { - "identifier": "ChargeTransactionPayment", - "ty": 140, - "additional_signed": 41 - } - ] - }, - "ty": 141 -} - -``` - -The type system is [composite](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/frame_runtime_types/index.html){target=\_blank}, meaning each type identifier contains a reference to a specific type or to another type identifier that provides information about the associated primitive types. - -For example, you can encode the `BitVec` type, but to decode it properly, you must know the types used for the `Order` and `Store` types. To find type information for `Order` and `Store`, you can use the path in the decoded JSON to locate their type identifiers. - -## Included RPC APIs - -A standard node comes with the following APIs to interact with a node: - -- **[`AuthorApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/author/trait.AuthorApiServer.html){target=\_blank}**: Make calls into a full node, including authoring extrinsics and verifying session keys. -- **[`ChainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/chain/trait.ChainApiServer.html){target=\_blank}**: Retrieve block header and finality information. -- **[`OffchainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/offchain/trait.OffchainApiServer.html){target=\_blank}**: Make RPC calls for off-chain workers. -- **[`StateApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/state/trait.StateApiServer.html){target=\_blank}**: Query information about on-chain state such as runtime version, storage items, and proofs. -- **[`SystemApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/system/trait.SystemApiServer.html){target=\_blank}**: Retrieve information about network state, such as connected peers and node roles. - -## Additional Resources - -The following tools can help you locate and decode metadata: - -- [Subxt Explorer](https://paritytech.github.io/subxt-explorer/#/){target=\_blank} -- [Metadata Portal 🌗](https://github.com/paritytech/metadata-portal){target=\_blank} -- [De[code] Sub[strate]](https://github.com/paritytech/desub){target=\_blank} - - --- Page Title: Contract Deployment @@ -2928,394 +2494,120 @@ These components form the foundation for developing sophisticated blockchain log --- -Page Title: Cryptography +Page Title: Deploy an ERC-20 to Polkadot Hub -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-cryptography.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/cryptography/ -- Summary: A concise guide to cryptography in blockchain, covering hash functions, encryption types, digital signatures, and elliptic curve applications. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-erc20-erc20-hardhat.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-hardhat/ +- Summary: Deploy an ERC-20 token on Polkadot Hub using PolkaVM. This guide covers contract creation, compilation, deployment, and interaction via Hardhat. -# Cryptography +# Deploy an ERC-20 to Polkadot Hub ## Introduction -Cryptography forms the backbone of blockchain technology, providing the mathematical verifiability crucial for consensus systems, data integrity, and user security. While a deep understanding of the underlying mathematical processes isn't necessary for most blockchain developers, grasping the fundamental applications of cryptography is essential. This page comprehensively overviews cryptographic implementations used across Polkadot SDK-based chains and the broader blockchain ecosystem. - -## Hash Functions - -Hash functions are fundamental to blockchain technology, creating a unique digital fingerprint for any piece of data, including simple text, images, or any other form of file. They map input data of any size to a fixed-size output (typically 32 bytes) using complex mathematical operations. Hashing is used to verify data integrity, create digital signatures, and provide a secure way to store passwords. This form of mapping is known as the ["pigeonhole principle,"](https://en.wikipedia.org/wiki/Pigeonhole_principle){target=\_blank} it is primarily implemented to efficiently and verifiably identify data from large sets. - -### Key Properties of Hash Functions - -- **Deterministic**: The same input always produces the same output. -- **Quick computation**: It's easy to calculate the hash value for any given input. -- **Pre-image resistance**: It's infeasible to generate the input data from its hash. -- **Small changes in input yield large changes in output**: Known as the ["avalanche effect"](https://en.wikipedia.org/wiki/Avalanche_effect){target=\_blank}. -- **Collision resistance**: The probabilities are extremely low to find two different inputs with the same hash. +[ERC-20](https://eips.ethereum.org/EIPS/eip-20){target=\_blank} tokens are fungible tokens commonly used for creating cryptocurrencies, governance tokens, and staking mechanisms. Polkadot Hub enables easy token deployment with Ethereum-compatible smart contracts and tools via the EVM backend. -### Blake2 +This tutorial covers deploying an ERC-20 contract on the Polkadot Hub TestNet using [Hardhat](https://hardhat.org/){target=\_blank}, an Ethereum development environment. The ERC-20 contract can be retrieved from OpenZeppelin's [GitHub repository](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20){target=\_blank} or their [Contract Wizard](https://wizard.openzeppelin.com/){target=\_blank}. -The Polkadot SDK utilizes Blake2, a state-of-the-art hashing method that offers: +## Prerequisites -- Equal or greater security compared to [SHA-2](https://en.wikipedia.org/wiki/SHA-2){target=\_blank}. -- Significantly faster performance than other algorithms. +Before starting, make sure you have: -These properties make Blake2 ideal for blockchain systems, reducing sync times for new nodes and lowering the resources required for validation. For detailed technical specifications about Blake2, see the [official Blake2 paper](https://www.blake2.net/blake2.pdf){target=\_blank}. +- Basic understanding of Solidity programming and fungible tokens. +- Node.js v22.13.1 or later. +- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. -## Types of Cryptography +## Set Up Your Project -There are two different ways that cryptographic algorithms are implemented: symmetric cryptography and asymmetric cryptography. +This tutorial uses a [Hardhat ERC-20 template](https://github.com/polkadot-developers/revm-hardhat-examples/tree/master/erc20-hardhat){target=\_blank} that contains all the necessary files. To get started, take the following steps: -### Symmetric Cryptography +1. Clone the GitHub repository locally: -Symmetric encryption is a branch of cryptography that isn't based on one-way functions, unlike asymmetric cryptography. It uses the same cryptographic key to encrypt plain text and decrypt the resulting ciphertext. + ```bash + git clone https://github.com/polkadot-developers/revm-hardhat-examples/ + cd revm-hardhat-examples/erc20-hardhat + ``` -Symmetric cryptography is a type of encryption that has been used throughout history, such as the Enigma Cipher and the Caesar Cipher. It is still widely used today and can be found in Web2 and Web3 applications alike. There is only one single key, and a recipient must also have access to it to access the contained information. +2. Install the dependencies: -#### Advantages {: #symmetric-advantages } + ```bash + npm i + ``` -- Fast and efficient for large amounts of data. -- Requires less computational power. +This will fetch all the necessary packages to help you deploy an ERC-20 with Hardhat to Polkadot. -#### Disadvantages {: #symmetric-disadvantages } +## Configure Hardhat -- Key distribution can be challenging. -- Scalability issues in systems with many users. +Once you've [setup your project](#set-up-your-project), you can configure the `hardhat.config.ts` to your needs. This tutorial has the file prepared to deploy to the Polkadot TestNet. -### Asymmetric Cryptography +To store and use private keys or network URLs, you can use Hardhat's configuration variables. This can be set via tasks in the **vars** scope. For example, to store the private key to deploy to the Polkadot TestNet, run the following command: -Asymmetric encryption is a type of cryptography that uses two different keys, known as a keypair: a public key, used to encrypt plain text, and a private counterpart, used to decrypt the ciphertext. +```bash +npx hardhat vars set TESTNET_PRIVATE_KEY +``` -The public key encrypts a fixed-length message that can only be decrypted with the recipient's private key and, sometimes, a set password. The public key can be used to cryptographically verify that the corresponding private key was used to create a piece of data without compromising the private key, such as with digital signatures. This has obvious implications for identity, ownership, and properties and is used in many different protocols across Web2 and Web3. +The command will initiate a wizard in which you'll have to enter the value to be stored: -#### Advantages {: #asymmetric-advantages } +
+ npx hardhat vars set TESTNET_PRIVATE_KEY + ✔ Enter value: · ••••••••• + The configuration variable has been stored in /Users/albertoviera/Library/Preferences/hardhat-nodejs/vars.json +
-- Solves the key distribution problem. -- Enables digital signatures and secure key exchange. +??? warning "Key Encryption" + This solution just prevents variables to be included in the code repository. You should find a solution that encrypts private keys and access them securely. -#### Disadvantages {: #asymmetric-disadvantages } +You can now use the account related to this private key by importing it into the Hardhat configuration file: -- Slower than symmetric encryption. -- Requires more computational resources. +```ts title="hardhat.config.ts" hl_lines="1 17" -### Trade-offs and Compromises +const config: HardhatUserConfig = { + solidity: { + version: "0.8.28", + settings: { + optimizer: { + enabled: true, + runs: 200, + }, + }, + }, + networks: { + polkadotTestnet: { + url: vars.get("TESTNET_URL", "http://127.0.0.1:8545"), + accounts: vars.has("TESTNET_PRIVATE_KEY") ? [vars.get("TESTNET_PRIVATE_KEY")] : [], + }, + }, + mocha: { + timeout: 40000, + }, +}; -Symmetric cryptography is faster and requires fewer bits in the key to achieve the same level of security that asymmetric cryptography provides. However, it requires a shared secret before communication can occur, which poses issues to its integrity and a potential compromise point. On the other hand, asymmetric cryptography doesn't require the secret to be shared ahead of time, allowing for far better end-user security. +export default config; +``` -Hybrid symmetric and asymmetric cryptography is often used to overcome the engineering issues of asymmetric cryptography, as it is slower and requires more bits in the key to achieve the same level of security. It encrypts a key and then uses the comparatively lightweight symmetric cipher to do the "heavy lifting" with the message. +## Compile your Contract -## Digital Signatures +Once you've configured Hardhat, you can compile the contract. -Digital signatures are a way of verifying the authenticity of a document or message using asymmetric keypairs. They are used to ensure that a sender or signer's document or message hasn't been tampered with in transit, and for recipients to verify that the data is accurate and from the expected sender. +In this tutorial, a simple ERC-20 is provided. Therefore, to compile the contract you can run the following command: -Signing digital signatures only requires a low-level understanding of mathematics and cryptography. For a conceptual example -- when signing a check, it is expected that it cannot be cashed multiple times. This isn't a feature of the signature system but rather the check serialization system. The bank will check that the serial number on the check hasn't already been used. Digital signatures essentially combine these two concepts, allowing the signature to provide the serialization via a unique cryptographic fingerprint that cannot be reproduced. +```bash +npx hardhat compile +``` -Unlike pen-and-paper signatures, knowledge of a digital signature cannot be used to create other signatures. Digital signatures are often used in bureaucratic processes, as they are more secure than simply scanning in a signature and pasting it onto a document. +If everything compiles successfully, you should see the following output: -Polkadot SDK provides multiple different cryptographic schemes and is generic so that it can support anything that implements the [`Pair` trait](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Pair.html){target=\_blank}. +
+ npx hardhat compile + Generating typings for: 23 artifacts in dir: typechain-types for target: ethers-v6 + Successfully generated 62 typings! + Compiled 21 Solidity files successfully (evm target: paris). +
-### Example of Creating a Digital Signature +## Test your Contract -The process of creating and verifying a digital signature involves several steps: +Hardhat has a native feature to test contracts. You can run tests against the local Hardhat development node, but it could have some technical differences to Polkadot. Therefore, in this tutorial, you'll be testing against the Polkadot TestNet -1. The sender creates a hash of the message. -2. The hash is encrypted using the sender's private key, creating the signature. -3. The message and signature are sent to the recipient. -4. The recipient decrypts the signature using the sender's public key. -5. The recipient hashes the received message and compares it to the decrypted hash. - -If the hashes match, the signature is valid, confirming the message's integrity and the sender's identity. - -## Elliptic Curve - -Blockchain technology requires the ability to have multiple keys creating a signature for block proposal and validation. To this end, Elliptic Curve Digital Signature Algorithm (ECDSA) and Schnorr signatures are two of the most commonly used methods. While ECDSA is a far simpler implementation, Schnorr signatures are more efficient when it comes to multi-signatures. - -Schnorr signatures bring some noticeable features over the ECDSA/EdDSA schemes: - -- It is better for hierarchical deterministic key derivations. -- It allows for native multi-signature through [signature aggregation](https://bitcoincore.org/en/2017/03/23/schnorr-signature-aggregation/){target=\_blank}. -- It is generally more resistant to misuse. - -One sacrifice that is made when using Schnorr signatures over ECDSA is that both require 64 bytes, but only ECDSA signatures communicate their public key. - -### Various Implementations - -- **[ECDSA](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm){target=\_blank}**: Polkadot SDK provides an ECDSA signature scheme using the [secp256k1](https://en.bitcoin.it/wiki/Secp256k1){target=\_blank} curve. This is the same cryptographic algorithm used to secure [Bitcoin](https://en.wikipedia.org/wiki/Bitcoin){target=\_blank} and [Ethereum](https://en.wikipedia.org/wiki/Ethereum){target=\_blank}. - -- **[Ed25519](https://en.wikipedia.org/wiki/EdDSA#Ed25519){target=\_blank}**: An EdDSA signature scheme using [Curve25519](https://en.wikipedia.org/wiki/Curve25519){target=\_blank}. It is carefully engineered at several levels of design and implementation to achieve very high speeds without compromising security. - -- **[SR25519](https://research.web3.foundation/Polkadot/security/keys/accounts-more){target=\_blank}**: Based on the same underlying curve as Ed25519. However, it uses Schnorr signatures instead of the EdDSA scheme. - - ---- - -Page Title: Data Encoding - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-data-encoding.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/data-encoding/ -- Summary: SCALE codec enables fast, efficient data encoding, ideal for resource-constrained environments like Wasm, supporting custom types and compact encoding. - -# Data Encoding - -## Introduction - -The Polkadot SDK uses a lightweight and efficient encoding/decoding mechanism to optimize data transmission across the network. This mechanism, known as the _SCALE_ codec, is used for serializing and deserializing data. - -The SCALE codec enables communication between the runtime and the outer node. This mechanism is designed for high-performance, copy-free data encoding and decoding in resource-constrained environments like the Polkadot SDK [Wasm runtime](/develop/parachains/deployment/build-deterministic-runtime/#introduction){target=\_blank}. - -It is not self-describing, meaning the decoding context must fully know the encoded data types. - -Parity's libraries utilize the [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} crate (a Rust implementation of the SCALE codec) to handle encoding and decoding for interactions between RPCs and the runtime. - -The `codec` mechanism is ideal for Polkadot SDK-based chains because: - -- It is lightweight compared to generic serialization frameworks like [`serde`](https://serde.rs/){target=\_blank}, which add unnecessary bulk to binaries. -- It doesn’t rely on Rust’s `libstd`, making it compatible with `no_std` environments like Wasm runtime. -- It integrates seamlessly with Rust, allowing easy derivation of encoding and decoding logic for new types using `#[derive(Encode, Decode)]`. - -Defining a custom encoding scheme in the Polkadot SDK-based chains, rather than using an existing Rust codec library, is crucial for enabling cross-platform and multi-language support. - -## SCALE Codec - -The codec is implemented using the following traits: - -- [`Encode`](#encode) -- [`Decode`](#decode) -- [`CompactAs`](#compactas) -- [`HasCompact`](#hascompact) -- [`EncodeLike`](#encodelike) - -### Encode - -The [`Encode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Encode.html){target=\_blank} trait handles data encoding into SCALE format and includes the following key functions: - -- **`size_hint(&self) -> usize`**: Estimates the number of bytes required for encoding to prevent multiple memory allocations. This should be inexpensive and avoid complex operations. Optional if the size isn’t known. -- **`encode_to(&self, dest: &mut T)`**: Encodes the data, appending it to a destination buffer. -- **`encode(&self) -> Vec`**: Encodes the data and returns it as a byte vector. -- **`using_encoded R>(&self, f: F) -> R`**: Encodes the data and passes it to a closure, returning the result. -- **`encoded_size(&self) -> usize`**: Calculates the encoded size. Should be used when the encoded data isn’t required. - -!!!tip - For best performance, value types should override `using_encoded`, and allocating types should override `encode_to`. It's recommended to implement `size_hint` for all types where possible. - -### Decode - -The [`Decode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Decode.html){target=\_blank} trait handles decoding SCALE-encoded data back into the appropriate types: - -- **`fn decode(value: &mut I) -> Result`**: Decodes data from the SCALE format, returning an error if decoding fails. - -### CompactAs - -The [`CompactAs`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.CompactAs.html){target=\_blank} trait wraps custom types for compact encoding: - -- **`encode_as(&self) -> &Self::As`**: Encodes the type as a compact type. -- **`decode_from(_: Self::As) -> Result`**: decodes from a compact encoded type. - -### HasCompact - -The [`HasCompact`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.HasCompact.html){target=\_blank} trait indicates a type supports compact encoding. - -### EncodeLike - -The [`EncodeLike`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.EncodeLike.html){target=\_blank} trait is used to ensure multiple types that encode similarly are accepted by the same function. When using `derive`, it is automatically implemented. - -### Data Types - -The table below outlines how the Rust implementation of the Parity SCALE codec encodes different data types. - -| Type | Description | Example SCALE Decoded Value | SCALE Encoded Value | -|-------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------| -| Boolean | Boolean values are encoded using the least significant bit of a single byte. | `false` / `true` | `0x00` / `0x01` | -| Compact/general integers | A "compact" or general integer encoding is sufficient for encoding large integers (up to 2^536) and is more efficient at encoding most values than the fixed-width version. | `unsigned integer 0` / `unsigned integer 1` / `unsigned integer 42` / `unsigned integer 69` / `unsigned integer 65535` / `BigInt(100000000000000)` | `0x00` / `0x04` / `0xa8` / `0x1501` / `0xfeff0300` / `0x0b00407a10f35a` | -| Enumerations (tagged-unions) | A fixed number of variants, each mutually exclusive and potentially implying a further value or series of values. Encoded as the first byte identifying the index of the variant that the value is. Any further bytes are used to encode any data that the variant implies. Thus, no more than 256 variants are supported. | `Int(42)` and `Bool(true)` where `enum IntOrBool { Int(u8), Bool(bool) }` | `0x002a` and `0x0101` | -| Fixed-width integers | Basic integers are encoded using a fixed-width little-endian (LE) format. | `signed 8-bit integer 69` / `unsigned 16-bit integer 42` / `unsigned 32-bit integer 16777215` | `0x45` / `0x2a00` / `0xffffff00` | -| Options | One or zero values of a particular type. | `Some` / `None` | `0x01` followed by the encoded value / `0x00` | -| Results | Results are commonly used enumerations which indicate whether certain operations were successful or unsuccessful. | `Ok(42)` / `Err(false)` | `0x002a` / `0x0100` | -| Strings | Strings are Vectors of bytes (Vec) containing a valid UTF8 sequence. | | | -| Structs | For structures, the values are named, but that is irrelevant for the encoding (names are ignored - only order matters). | `SortedVecAsc::from([3, 5, 2, 8])` | `[3, 2, 5, 8] ` | -| Tuples | A fixed-size series of values, each with a possibly different but predetermined and fixed type. This is simply the concatenation of each encoded value. | Tuple of compact unsigned integer and boolean: `(3, false)` | `0x0c00` | -| Vectors (lists, series, sets) | A collection of same-typed values is encoded, prefixed with a compact encoding of the number of items, followed by each item's encoding concatenated in turn. | Vector of unsigned `16`-bit integers: `[4, 8, 15, 16, 23, 42]` | `0x18040008000f00100017002a00` | - -## Encode and Decode Rust Trait Implementations - -Here's how the `Encode` and `Decode` traits are implemented: - - -```rust -use parity_scale_codec::{Encode, Decode}; - -[derive(Debug, PartialEq, Encode, Decode)] -enum EnumType { - #[codec(index = 15)] - A, - B(u32, u64), - C { - a: u32, - b: u64, - }, -} - -let a = EnumType::A; -let b = EnumType::B(1, 2); -let c = EnumType::C { a: 1, b: 2 }; - -a.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x0f"); -}); - -b.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); - -c.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); - -let mut da: &[u8] = b"\x0f"; -assert_eq!(EnumType::decode(&mut da).ok(), Some(a)); - -let mut db: &[u8] = b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut db).ok(), Some(b)); - -let mut dc: &[u8] = b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut dc).ok(), Some(c)); - -let mut dz: &[u8] = &[0]; -assert_eq!(EnumType::decode(&mut dz).ok(), None); -``` - -## SCALE Codec Libraries - -Several SCALE codec implementations are available in various languages. Here's a list of them: - -- **AssemblyScript**: [`LimeChain/as-scale-codec`](https://github.com/LimeChain/as-scale-codec){target=\_blank} -- **C**: [`MatthewDarnell/cScale`](https://github.com/MatthewDarnell/cScale){target=\_blank} -- **C++**: [`qdrvm/scale-codec-cpp`](https://github.com/qdrvm/scale-codec-cpp){target=\_blank} -- **JavaScript**: [`polkadot-js/api`](https://github.com/polkadot-js/api){target=\_blank} -- **Dart**: [`leonardocustodio/polkadart`](https://github.com/leonardocustodio/polkadart){target=\_blank} -- **Haskell**: [`airalab/hs-web3`](https://github.com/airalab/hs-web3/tree/master/packages/scale){target=\_blank} -- **Golang**: [`itering/scale.go`](https://github.com/itering/scale.go){target=\_blank} -- **Java**: [`splix/polkaj`](https://github.com/splix/polkaj){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **Ruby**: [` wuminzhe/scale_rb`](https://github.com/wuminzhe/scale_rb){target=\_blank} -- **TypeScript**: [`parity-scale-codec-ts`](https://github.com/tjjfvi/subshape){target=\_blank}, [`scale-ts`](https://github.com/unstoppablejs/unstoppablejs/tree/main/packages/scale-ts#scale-ts){target=\_blank}, [`soramitsu/scale-codec-js-library`](https://github.com/soramitsu/scale-codec-js-library){target=\_blank}, [`subsquid/scale-codec`](https://github.com/subsquid/squid-sdk/tree/master/substrate/scale-codec){target=\_blank} - - ---- - -Page Title: Deploy an ERC-20 to Polkadot Hub - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-erc20-erc20-hardhat.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-hardhat/ -- Summary: Deploy an ERC-20 token on Polkadot Hub using PolkaVM. This guide covers contract creation, compilation, deployment, and interaction via Hardhat. - -# Deploy an ERC-20 to Polkadot Hub - -## Introduction - -[ERC-20](https://eips.ethereum.org/EIPS/eip-20){target=\_blank} tokens are fungible tokens commonly used for creating cryptocurrencies, governance tokens, and staking mechanisms. Polkadot Hub enables easy token deployment with Ethereum-compatible smart contracts and tools via the EVM backend. - -This tutorial covers deploying an ERC-20 contract on the Polkadot Hub TestNet using [Hardhat](https://hardhat.org/){target=\_blank}, an Ethereum development environment. The ERC-20 contract can be retrieved from OpenZeppelin's [GitHub repository](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20){target=\_blank} or their [Contract Wizard](https://wizard.openzeppelin.com/){target=\_blank}. - -## Prerequisites - -Before starting, make sure you have: - -- Basic understanding of Solidity programming and fungible tokens. -- Node.js v22.13.1 or later. -- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. - -## Set Up Your Project - -This tutorial uses a [Hardhat ERC-20 template](https://github.com/polkadot-developers/revm-hardhat-examples/tree/master/erc20-hardhat){target=\_blank} that contains all the necessary files. To get started, take the following steps: - -1. Clone the GitHub repository locally: - - ```bash - git clone https://github.com/polkadot-developers/revm-hardhat-examples/ - cd revm-hardhat-examples/erc20-hardhat - ``` - -2. Install the dependencies: - - ```bash - npm i - ``` - -This will fetch all the necessary packages to help you deploy an ERC-20 with Hardhat to Polkadot. - -## Configure Hardhat - -Once you've [setup your project](#set-up-your-project), you can configure the `hardhat.config.ts` to your needs. This tutorial has the file prepared to deploy to the Polkadot TestNet. - -To store and use private keys or network URLs, you can use Hardhat's configuration variables. This can be set via tasks in the **vars** scope. For example, to store the private key to deploy to the Polkadot TestNet, run the following command: - -```bash -npx hardhat vars set TESTNET_PRIVATE_KEY -``` - -The command will initiate a wizard in which you'll have to enter the value to be stored: - -
- npx hardhat vars set TESTNET_PRIVATE_KEY - ✔ Enter value: · ••••••••• - The configuration variable has been stored in /Users/albertoviera/Library/Preferences/hardhat-nodejs/vars.json -
- -??? warning "Key Encryption" - This solution just prevents variables to be included in the code repository. You should find a solution that encrypts private keys and access them securely. - -You can now use the account related to this private key by importing it into the Hardhat configuration file: - -```ts title="hardhat.config.ts" hl_lines="1 17" - -const config: HardhatUserConfig = { - solidity: { - version: "0.8.28", - settings: { - optimizer: { - enabled: true, - runs: 200, - }, - }, - }, - networks: { - polkadotTestnet: { - url: vars.get("TESTNET_URL", "http://127.0.0.1:8545"), - accounts: vars.has("TESTNET_PRIVATE_KEY") ? [vars.get("TESTNET_PRIVATE_KEY")] : [], - }, - }, - mocha: { - timeout: 40000, - }, -}; - -export default config; -``` - -## Compile your Contract - -Once you've configured Hardhat, you can compile the contract. - -In this tutorial, a simple ERC-20 is provided. Therefore, to compile the contract you can run the following command: - -```bash -npx hardhat compile -``` - -If everything compiles successfully, you should see the following output: - -
- npx hardhat compile - Generating typings for: 23 artifacts in dir: typechain-types for target: ethers-v6 - Successfully generated 62 typings! - Compiled 21 Solidity files successfully (evm target: paris). -
- -## Test your Contract - -Hardhat has a native feature to test contracts. You can run tests against the local Hardhat development node, but it could have some technical differences to Polkadot. Therefore, in this tutorial, you'll be testing against the Polkadot TestNet - -This example has a predefined test file located in [`test/Token.test.js`](https://github.com/polkadot-developers/revm-hardhat-examples/blob/master/erc20-hardhat/test/MyToken.test.ts){target=\_blank}, that runs the following tests: +This example has a predefined test file located in [`test/Token.test.js`](https://github.com/polkadot-developers/revm-hardhat-examples/blob/master/erc20-hardhat/test/MyToken.test.ts){target=\_blank}, that runs the following tests: 1. The token was deployed by verifying its **name** and **symbol**. 2. The token has the right owner configured. @@ -4480,380 +3772,89 @@ PolkaVM differs from the EVM in two key ways that make it faster, more hardware- --- -Page Title: E2E Testing with Moonwall +Page Title: Fork a Parachain Using Chopsticks -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-moonwall.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/moonwall/ -- Summary: Enhance blockchain end-to-end testing with Moonwall's standardized environment setup, comprehensive configuration management, and simple network interactions. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-fork-a-parachain.md +- Canonical (HTML): https://docs.polkadot.com/parachains/testing/fork-a-parachain/ +- Summary: Simplify Polkadot SDK development with Chopsticks. Learn essential features, how to install Chopsticks, and how to configure local blockchain forks. -# E2E Testing with Moonwall +# Fork a Parachain Using Chopsticks ## Introduction -Moonwall is an end-to-end testing framework designed explicitly for Polkadot SDK-based blockchain networks. It addresses one of the most significant challenges in blockchain development: managing complex test environments and network configurations. +[Chopsticks](https://github.com/AcalaNetwork/chopsticks/){target=\_blank}, developed by the [Acala Foundation](https://github.com/AcalaNetwork){target=\_blank}, is a versatile tool tailored for developers working on Polkadot SDK-based blockchains. With Chopsticks, you can fork live chains locally, replay blocks to analyze extrinsics, and simulate complex scenarios like XCM interactions all without deploying to a live network. -Moonwall consolidates this complexity by providing the following: +This guide walks you through installing Chopsticks and provides information on configuring a local blockchain fork. By streamlining testing and experimentation, Chopsticks empowers developers to innovate and accelerate their blockchain projects within the Polkadot ecosystem. -- A centralized configuration management system that explicitly defines all network parameters. -- A standardized approach to environment setup across different Substrate-based chains. -- Built-in utilities for common testing scenarios and network interactions. +For additional support and information, please reach out through [GitHub Issues](https://github.com/AcalaNetwork/chopsticks/issues){target=_blank}. -Developers can focus on writing meaningful tests rather than managing infrastructure complexities or searching through documentation for configuration options. +!!! warning + Chopsticks uses [Smoldot](https://github.com/smol-dot/smoldot){target=_blank} light client, which only supports the native Polkadot SDK API. Consequently, a Chopsticks-based fork doesn't support Ethereum JSON-RPC calls, meaning you cannot use it to fork your chain and connect Metamask. ## Prerequisites Before you begin, ensure you have the following installed: -- [Node.js](https://nodejs.org/en/){target=\_blank} (version 20.10 or higher). -- A package manager such as [npm](https://www.npmjs.com/){target=\_blank}, [yarn](https://yarnpkg.com/){target=\_blank}, or [pnpm](https://pnpm.io/){target=\_blank}. - -## Install Moonwall +- [Node.js](https://nodejs.org/en/){target=\_blank}. +- A package manager such as [npm](https://www.npmjs.com/){target=\_blank}, which should be installed with Node.js by default, or [Yarn](https://yarnpkg.com/){target=\_blank}. -Moonwall can be installed globally for system-wide access or locally within specific projects. This section covers both installation methods. +## Install Chopsticks -!!! tip - This documentation corresponds to Moonwall version `5.15.0`. To avoid compatibility issues with the documented features, ensure you're using the matching version. +You can install Chopsticks globally or locally in your project. Choose the option that best fits your development workflow. This documentation explains the features of Chopsticks version `1.2.2`. Make sure you're using the correct version to match these instructions. ### Global Installation -Global installation provides system-wide access to the Moonwall CLI, making it ideal for developers working across multiple blockchain projects. Install it by running one of the following commands: - -=== "npm" - - ```bash - npm install -g @moonwall/cli@5.15.0 - ``` - -=== "pnpm" - - ```bash - pnpm -g install @moonwall/cli@5.15.0 - ``` - -=== "yarn" +To install Chopsticks globally, allowing you to use it across multiple projects, run: - ```bash - yarn global add @moonwall/cli@5.15.0 - ``` +```bash +npm i -g @acala-network/chopsticks@1.2.2 +``` -Now, you can run the `moonwall` command from your terminal. +Now, you should be able to run the `chopsticks` command from your terminal. ### Local Installation -Local installation is recommended for better dependency management and version control within a specific project. First, initialize your project: +To use Chopsticks in a specific project, first create a new directory and initialize a Node.js project: ```bash -mkdir my-moonwall-project -cd my-moonwall-project +mkdir my-chopsticks-project +cd my-chopsticks-project npm init -y ``` -Then, install it as a local dependency: - -=== "npm" - - ```bash - npm install @moonwall/cli@5.15.0 - ``` - -=== "pnpm" - - ```bash - pnpm install @moonwall/cli@5.15.0 - ``` - -=== "yarn" - - ```bash - yarn add @moonwall/cli@5.15.0 - ``` +Then, install Chopsticks as a local dependency: -## Initialize Moonwall +```bash +npm i @acala-network/chopsticks@1.2.2 +``` -The `moonwall init` command launches an interactive wizard to create your configuration file: +Finally, you can run Chopsticks using the `npx` command. To see all available options and commands, run it with the `--help` flag: ```bash -moonwall init +npx @acala-network/chopsticks --help ``` -During setup, you will see prompts for the following parameters: +## Configure Chopsticks -- **`label`**: Identifies your test configuration. -- **`global timeout`**: Maximum time (ms) for test execution. -- **`environment name`**: Name for your testing environment. -- **`network foundation`**: Type of blockchain environment to use. -- **`tests directory`**: Location of your test files. +To run Chopsticks, you need to configure some parameters. This can be set either through using a configuration file or the command line interface (CLI). The parameters that can be configured are as follows: -Select `Enter` to accept defaults or input custom values. You should see something like this: +- **`genesis`**: The link to a parachain's raw genesis file to build the fork from, instead of an endpoint. +- **`timestamp`**: Timestamp of the block to fork from. +- **`endpoint`**: The endpoint of the parachain to fork. +- **`block`**: Use to specify at which block hash or number to replay the fork. +- **`wasm-override`**: Path of the Wasm to use as the parachain runtime, instead of an endpoint's runtime. +- **`db`**: Path to the name of the file that stores or will store the parachain's database. +- **`config`**: Path or URL of the config file. +- **`port`**: The port to expose an endpoint on. +- **`build-block-mode`**: How blocks should be built in the fork: batch, manual, instant. +- **`import-storage`**: A pre-defined JSON/YAML storage path to override in the parachain's storage. +- **`allow-unresolved-imports`**: Whether to allow Wasm unresolved imports when using a Wasm to build the parachain. +- **`html`**: Include to generate storage diff preview between blocks. +- **`mock-signature-host`**: Mock signature host so that any signature starts with `0xdeadbeef` and filled by `0xcd` is considered valid. -
- moonwall init - ✔ Provide a label for the config file moonwall_config - ✔ Provide a global timeout value 30000 - ✔ Provide a name for this environment default_env - ✔ What type of network foundation is this? dev - ✔ Provide the path for where tests for this environment are kept tests/ - ? Would you like to generate this config? (no to restart from beginning) (Y/n) -
+### Configuration File -The wizard generates a `moonwall.config` file: - -```json -{ - "label": "moonwall_config", - "defaultTestTimeout": 30000, - "environments": [ - { - "name": "default_env", - "testFileDir": ["tests/"], - "foundation": { - "type": "dev" - } - } - ] -} - -``` - -The default configuration requires specific details about your blockchain node and test requirements: - -- The `foundation` object defines how your test blockchain node will be launched and managed. The dev foundation, which runs a local node binary, is used for local development. - - For more information about available options, check the [Foundations](https://moonsong-labs.github.io/moonwall/guide/intro/foundations.html){target=\_blank} section. - -- The `connections` array specifies how your tests will interact with the blockchain node. This typically includes provider configuration and endpoint details. - - A provider is a tool that allows you or your application to connect to a blockchain network and simplifies the low-level details of the process. A provider handles submitting transactions, reading state, and more. For more information on available providers, check the [Providers supported](https://moonsong-labs.github.io/moonwall/guide/intro/providers.html#providers-supported){target=\_blank} page in the Moonwall documentation. - -Here's a complete configuration example for testing a local node using Polkadot.js as a provider: - -```json -{ - "label": "moonwall_config", - "defaultTestTimeout": 30000, - "environments": [ - { - "name": "default_env", - "testFileDir": ["tests/"], - "foundation": { - "launchSpec": [ - { - "binPath": "./node-template", - "newRpcBehaviour": true, - "ports": { "rpcPort": 9944 } - } - ], - "type": "dev" - }, - "connections": [ - { - "name": "myconnection", - "type": "polkadotJs", - "endpoints": ["ws://127.0.0.1:9944"] - } - ] - } - ] -} - -``` - -## Writing Tests - -Moonwall uses the [`describeSuite`](https://github.com/Moonsong-Labs/moonwall/blob/7568048c52e9f7844f38fb4796ae9e1b9205fdaa/packages/cli/src/lib/runnerContext.ts#L65){target=\_blank} function to define test suites, like using [Mocha](https://mochajs.org/){target=\_blank}. Each test suite requires the following: - -- **`id`**: Unique identifier for the suite. -- **`title`**: Descriptive name for the suite. -- **`foundationMethods`**: Specifies the testing environment (e.g., `dev` for local node testing). -- **`testCases`**: A callback function that houses the individual test cases of this suite. - -The following example shows how to test a balance transfer between two accounts: - -```ts -import '@polkadot/api-augment'; -import { describeSuite, expect } from '@moonwall/cli'; -import { Keyring } from '@polkadot/api'; - -describeSuite({ - id: 'D1', - title: 'Demo suite', - foundationMethods: 'dev', - testCases: ({ it, context, log }) => { - it({ - id: 'T1', - title: 'Test Case', - test: async () => { - // Set up polkadot.js API and testing accounts - let api = context.polkadotJs(); - let alice = new Keyring({ type: 'sr25519' }).addFromUri('//Alice'); - let charlie = new Keyring({ type: 'sr25519' }).addFromUri('//Charlie'); - - // Query Charlie's account balance before transfer - const balanceBefore = (await api.query.system.account(charlie.address)) - .data.free; - - // Before transfer, Charlie's account balance should be 0 - expect(balanceBefore.toString()).toEqual('0'); - log('Balance before: ' + balanceBefore.toString()); - - // Transfer from Alice to Charlie - const amount = 1000000000000000; - await api.tx.balances - .transferAllowDeath(charlie.address, amount) - .signAndSend(alice); - - // Wait for the transaction to be included in a block. - // This is necessary because the balance is not updated immediately. - // Block time is 6 seconds. - await new Promise((resolve) => setTimeout(resolve, 6000)); - - // Query Charlie's account balance after transfer - const balanceAfter = (await api.query.system.account(charlie.address)) - .data.free; - - // After transfer, Charlie's account balance should be 1000000000000000 - expect(balanceAfter.toString()).toEqual(amount.toString()); - log('Balance after: ' + balanceAfter.toString()); - }, - }); - }, -}); - -``` - -This test demonstrates several key concepts: - -- Initializing the Polkadot.js API through Moonwall's context and setting up test accounts. -- Querying on-chain state. -- Executing transactions. -- Waiting for block inclusion. -- Verifying results using assertions. - -## Running the Tests - -Execute your tests using the `test` Moonwall CLI command. For the default environment setup run: - -```bash -moonwall test default_env -c moonwall.config -``` - -The test runner will output detailed results showing: - -- Test suite execution status. -- Individual test case results. -- Execution time. -- Detailed logs and error messages (if any). - -Example output: -
- moonwall test default_env -c moonwall.config - stdout | tests/test1.ts > 🗃️ D1 Demo suite > 📁 D1T1 Test Case - 2025-01-21T19:27:55.624Z test:default_env Balance before: 0 - - stdout | tests/test1.ts > 🗃️ D1 Demo suite > 📁 D1T1 Test Case - 2025-01-21T19:28:01.637Z test:default_env Balance after: 1000000000000000 - - ✓ default_env tests/test1.ts (1 test) 6443ms - ✓ 🗃️ D1 Demo suite > 📁 D1T1 Test Case 6028ms - - Test Files 1 passed (1) - Tests 1 passed (1) - Start at 16:27:53 - Duration 7.95s (transform 72ms, setup 0ms, collect 1.31s, tests 6.44s, environment 0ms, prepare 46ms) - - ✅ All tests passed -
- -## Where to Go Next - -For a comprehensive guide to Moonwall's full capabilities, available configurations, and advanced usage, see the official [Moonwall](https://moonsong-labs.github.io/moonwall/){target=\_blank} documentation. - - ---- - -Page Title: Get Started - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-fork-a-parachain.md -- Canonical (HTML): https://docs.polkadot.com/parachains/testing/fork-a-parachain/ -- Summary: Simplify Polkadot SDK development with Chopsticks. Learn essential features, how to install Chopsticks, and how to configure local blockchain forks. - -# Get Started - -## Introduction - -[Chopsticks](https://github.com/AcalaNetwork/chopsticks/){target=\_blank}, developed by the [Acala Foundation](https://github.com/AcalaNetwork){target=\_blank}, is a versatile tool tailored for developers working on Polkadot SDK-based blockchains. With Chopsticks, you can fork live chains locally, replay blocks to analyze extrinsics, and simulate complex scenarios like XCM interactions all without deploying to a live network. - -This guide walks you through installing Chopsticks and provides information on configuring a local blockchain fork. By streamlining testing and experimentation, Chopsticks empowers developers to innovate and accelerate their blockchain projects within the Polkadot ecosystem. - -For additional support and information, please reach out through [GitHub Issues](https://github.com/AcalaNetwork/chopsticks/issues){target=_blank}. - -!!! warning - Chopsticks uses [Smoldot](https://github.com/smol-dot/smoldot){target=_blank} light client, which only supports the native Polkadot SDK API. Consequently, a Chopsticks-based fork doesn't support Ethereum JSON-RPC calls, meaning you cannot use it to fork your chain and connect Metamask. - -## Prerequisites - -Before you begin, ensure you have the following installed: - -- [Node.js](https://nodejs.org/en/){target=\_blank}. -- A package manager such as [npm](https://www.npmjs.com/){target=\_blank}, which should be installed with Node.js by default, or [Yarn](https://yarnpkg.com/){target=\_blank}. - -## Install Chopsticks - -You can install Chopsticks globally or locally in your project. Choose the option that best fits your development workflow. This documentation explains the features of Chopsticks version `1.2.2`. Make sure you're using the correct version to match these instructions. - -### Global Installation - -To install Chopsticks globally, allowing you to use it across multiple projects, run: - -```bash -npm i -g @acala-network/chopsticks@1.2.2 -``` - -Now, you should be able to run the `chopsticks` command from your terminal. - -### Local Installation - -To use Chopsticks in a specific project, first create a new directory and initialize a Node.js project: - -```bash -mkdir my-chopsticks-project -cd my-chopsticks-project -npm init -y -``` - -Then, install Chopsticks as a local dependency: - -```bash -npm i @acala-network/chopsticks@1.2.2 -``` - -Finally, you can run Chopsticks using the `npx` command. To see all available options and commands, run it with the `--help` flag: - -```bash -npx @acala-network/chopsticks --help -``` - -## Configure Chopsticks - -To run Chopsticks, you need to configure some parameters. This can be set either through using a configuration file or the command line interface (CLI). The parameters that can be configured are as follows: - -- **`genesis`**: The link to a parachain's raw genesis file to build the fork from, instead of an endpoint. -- **`timestamp`**: Timestamp of the block to fork from. -- **`endpoint`**: The endpoint of the parachain to fork. -- **`block`**: Use to specify at which block hash or number to replay the fork. -- **`wasm-override`**: Path of the Wasm to use as the parachain runtime, instead of an endpoint's runtime. -- **`db`**: Path to the name of the file that stores or will store the parachain's database. -- **`config`**: Path or URL of the config file. -- **`port`**: The port to expose an endpoint on. -- **`build-block-mode`**: How blocks should be built in the fork: batch, manual, instant. -- **`import-storage`**: A pre-defined JSON/YAML storage path to override in the parachain's storage. -- **`allow-unresolved-imports`**: Whether to allow Wasm unresolved imports when using a Wasm to build the parachain. -- **`html`**: Include to generate storage diff preview between blocks. -- **`mock-signature-host`**: Mock signature host so that any signature starts with `0xdeadbeef` and filled by `0xcd` is considered valid. - -### Configuration File - -The Chopsticks source repository includes a collection of [YAML](https://yaml.org/){target=\_blank} files that can be used to set up various Polkadot SDK chains locally. You can download these configuration files from the [repository's `configs` folder](https://github.com/AcalaNetwork/chopsticks/tree/master/configs){target=\_blank}. +The Chopsticks source repository includes a collection of [YAML](https://yaml.org/){target=\_blank} files that can be used to set up various Polkadot SDK chains locally. You can download these configuration files from the [repository's `configs` folder](https://github.com/AcalaNetwork/chopsticks/tree/master/configs){target=\_blank}. An example of a configuration file for Polkadot is as follows: @@ -5066,1583 +4067,332 @@ These are the methods that can be invoked and their parameters: --- -Page Title: Get Started +Page Title: Get Started with Parachain Development -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-run-a-parachain-network.md -- Canonical (HTML): https://docs.polkadot.com/parachains/testing/run-a-parachain-network/ -- Summary: Quickly install and configure Zombienet to deploy and test Polkadot-based blockchain networks with this comprehensive getting-started guide. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-get-started.md +- Canonical (HTML): https://docs.polkadot.com/parachains/get-started/ +- Summary: Practical examples and tutorials for building and deploying Polkadot parachains, covering everything from launch to customization and cross-chain messaging. # Get Started -## Introduction - -Zombienet is a robust testing framework designed for Polkadot SDK-based blockchain networks. It enables developers to efficiently deploy and test ephemeral blockchain environments on platforms like Kubernetes, Podman, and native setups. With its simple and versatile CLI, Zombienet provides an all-in-one solution for spawning networks, running tests, and validating performance. +The following sections provide practical recipes for building parachains on Polkadot—each focused on specific development scenarios with step-by-step, hands-on examples. -This guide will outline the different installation methods for Zombienet, provide step-by-step instructions for setting up on various platforms, and highlight essential provider-specific features and requirements. +## Quick Start Guides -By following this guide, Zombienet will be up and running quickly, ready to streamline your blockchain testing and development workflows. +Quick start guides help developers set up and interact with the Polkadot parachain ecosystem using various tools and frameworks. -## Install Zombienet +| Tutorial | Tools | Description | +| :--------------------------------------------------------------------------------------------: | :----------------------------: | :---------------------------------------------------------------------: | +| [Set Up the Parachain Template](/parachains/launch-a-parachain/set-up-the-parachain-template/) | Polkadot SDK | Learn how to set up and run the Polkadot SDK Parachain Template locally | +| [Launch a Local Parachain](/parachains/testing/run-a-parachain-network/) | Zombienet, Chopsticks | Set up a local development environment for testing | +| [Connect to Polkadot](/chain-interactions/query-on-chain-data/query-sdks/) | Polkadot.js, Substrate Connect | Connect your application to Polkadot networks | +| [Fork an Existing Parachain](/parachains/testing/fork-a-parachain/) | Chopsticks | Create a local fork of a live parachain for testing | -Zombienet releases are available on the [Zombienet repository](https://github.com/paritytech/zombienet){target=\_blank}. +## Launch a Simple Parachain -Multiple options are available for installing Zombienet, depending on the user's preferences and the environment where it will be used. The following section will guide you through the installation process for each option. +Learn the fundamentals of launching and deploying a parachain to the Polkadot network. -=== "Use the executable" +| Tutorial | Description | +| :--------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------: | +| [Set Up the Parachain Template](/parachains/launch-a-parachain/set-up-the-parachain-template/) | Polkadot SDK | +| [Deploy to Polkadot](/parachains/launch-a-parachain/deploy-to-polkadot/) | Step-by-step tutorial to deploying your parachain to Polkadot | +| [Obtain Coretime](/parachains/launch-a-parachain/obtain-coretime/) | Learn how to acquire blockspace using Polkadot's coretime model (RegionX) | - Install Zombienet using executables by visiting the [latest release](https://github.com/paritytech/zombienet/releases){target=\_blank} page and selecting the appropriate asset for your operating system. You can download the executable and move it to a directory in your PATH. +## Customize Your Runtime - Each release includes executables for Linux and macOS. Executables are generated using [pkg](https://github.com/vercel/pkg){target=\_blank}, which allows the Zombienet CLI to operate without requiring Node.js to be installed. +Build custom functionality for your parachain by composing and creating pallets. - Then, ensure the downloaded file is executable: +| Tutorial | Description | +| :-------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------: | +| [Add Existing Pallets to the Runtime](/parachains/customize-runtime/add-existing-pallets/) | Integrate pre-built pallets from the FRAME ecosystem | +| [Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/) | Configure and use multiple instances of the same pallet | +| [Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/) | Enable smart contract capabilities using Contracts or EVM pallets | - ```bash - chmod +x zombienet-macos-arm64 - ``` +### Pallet Development - Finally, you can run the following command to check if the installation was successful. If so, it will display the version of the installed Zombienet: +Deep dive into creating and managing custom pallets for your parachain. - ```bash - ./zombienet-macos-arm64 version - ``` +| Tutorial | Description | +| :--------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------: | +| [Create a Custom Pallet](/parachains/customize-runtime/pallet-development/create-a-pallet/) | Build a pallet from scratch with custom logic | +| [Mock Your Runtime](/parachains/customize-runtime/pallet-development/mock-runtime/) | Set up a mock runtime environment for testing | +| [Pallet Unit Testing](/parachains/customize-runtime/pallet-development/pallet-testing/) | Write comprehensive tests for your pallet logic | +| [Add Your Custom Pallet to the Runtime](/parachains/customize-runtime/pallet-development/add-pallet-to-runtime/) | Integrate your custom pallet into your parachain runtime | +| [Benchmark the Custom Pallet](/parachains/customize-runtime/pallet-development/benchmark-pallet/) | Measure and optimize pallet performance with benchmarking | - If you want to add the `zombienet` executable to your PATH, you can move it to a directory in your PATH, such as `/usr/local/bin`: +## Testing - ```bash - mv zombienet-macos-arm64 /usr/local/bin/zombienet - ``` +Test your parachain in various environments before production deployment. - Now you can refer to the `zombienet` executable directly. +| Tutorial | Description | +| :---------------------------------------------------------------------: | :-----------------------------------------------------: | +| [Fork a Parachain](/parachains/testing/fork-a-parachain/) | Use Chopsticks to create a local fork for testing | +| [Run a Parachain Network](/parachains/testing/run-a-parachain-network/) | Launch a complete parachain test network with Zombienet | - ```bash - zombienet version - ``` +## Runtime Upgrades and Maintenance -=== "Use Nix" +Manage your parachain's lifecycle with forkless upgrades and maintenance operations. - For Nix users, the Zombienet repository provides a [`flake.nix`](https://github.com/paritytech/zombienet/blob/main/flake.nix){target=\_blank} file to install Zombienet making it easy to incorporate Zombienet into Nix-based projects. - - To install Zombienet utilizing Nix, users can run the following command, triggering the fetching of the flake and subsequently installing the Zombienet package: +| Tutorial | Description | +| :-----------------------------------------------------------------------: | :--------------------------------------------------: | +| [Runtime Upgrades](/parachains/runtime-maintenance/runtime-upgrades/) | Perform forkless runtime upgrades via governance | +| [Storage Migrations](/parachains/runtime-maintenance/storage-migrations/) | Safely migrate storage when updating runtime logic | +| [Unlock Parachains](/parachains/runtime-maintenance/unlock-parachains/) | Understand parachain lifecycle and unlock mechanisms | - ```bash - nix run github:paritytech/zombienet/INSERT_ZOMBIENET_VERSION -- \ - spawn INSERT_ZOMBIENET_CONFIG_FILE_NAME.toml - ``` +## Interoperability - Replace the `INSERT_ZOMBIENET_VERSION` with the desired version of Zombienet and the `INSERT_ZOMBIENET_CONFIG_FILE_NAME` with the name of the configuration file you want to use. +Configure your parachain for cross-chain communication using XCM (Cross-Consensus Messaging). - To run the command above, you need to have [Flakes](https://nixos.wiki/wiki/Flakes#Enable_flakes){target=\_blank} enabled. +| Tutorial | Description | +| :--------------------------------------------------------------------------------------------------------: | :----------------------------------------------------: | +| [Open HRMP Channels Between Parachains](/parachains/interoperability/channels-between-parachains/) | Establish communication channels with other parachains | +| [Open HRMP Channels with System Parachains](/parachains/interoperability/channels-with-system-parachains/) | Connect with Asset Hub and other system parachains | - Alternatively, you can also include the Zombienet binary in the PATH for the current shell using the following command: - - ```bash - nix shell github:paritytech/zombienet/INSERT_ZOMBIENET_VERSION - ``` +## Integrations -=== "Use Docker" +Integrate your parachain with essential ecosystem tools and services. - Zombienet can also be run using Docker. The Zombienet repository provides a Docker image that can be used to run the Zombienet CLI. To run Zombienet using Docker, you can use the following command: - - ```bash - docker run -it --rm \ - -v $(pwd):/home/nonroot/zombie-net/host-current-files \ - paritytech/zombienet - ``` - - The command above will run the Zombienet CLI inside a Docker container and mount the current directory to the `/home/nonroot/zombie-net/host-current-files` directory. This allows Zombienet to access the configuration file and other files in the current directory. If you want to mount a different directory, replace `$(pwd)` with the desired directory path. +| Tutorial | Description | +| :--------------------------------------------: | :----------------------------------------------------: | +| [Wallets](/parachains/integrations/wallets/) | Integrate wallet support for user interactions | +| [Indexers](/parachains/integrations/indexers/) | Set up indexing solutions for querying blockchain data | +| [Oracles](/parachains/integrations/oracles/) | Connect your parachain to off-chain data sources | - Inside the Docker container, you can run the Zombienet CLI commands. First, you need to set up Zombienet to download the necessary binaries: +## Additional Resources - ```bash - npm run zombie -- setup polkadot polkadot-parachain - ``` +- [Polkadot SDK Documentation](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/index.html) +- [Polkadot Wiki - Parachains](https://wiki.polkadot.network/docs/learn-parachains/) - After that, you need to add those binaries to the PATH: - ```bash - export PATH=/home/nonroot/zombie-net:$PATH - ``` +--- - Finally, you can run the Zombienet CLI commands. For example, to spawn a network using a specific configuration file, you can run the following command: +Page Title: Get Started with Smart Contracts - ```bash - npm run zombie -- -p native spawn host-current-files/minimal.toml - ``` +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-get-started.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/get-started/ +- Summary: Practical examples for building and deploying smart contracts on Polkadot Hub, from connecting and tooling to deployment, integrations, and precompiles. - The command above mounts the current directory to the `/workspace` directory inside the Docker container, allowing Zombienet to access the configuration file and other files in the current directory. If you want to mount a different directory, replace `$(pwd)` with the desired directory path. +# Get Started -## Providers +This resource provides quick-starts for building smart contracts on Polkadot Hub. Use the tables below to jump directly to the tools and workflows you need. -Zombienet supports different backend providers for running the nodes. At this moment, [Kubernetes](https://kubernetes.io/){target=\_blank}, [Podman](https://podman.io/){target=\_blank}, and local providers are supported, which can be declared as `kubernetes`, `podman`, or `native`, respectively. +## Quick Starts -To use a particular provider, you can specify it in the network file or use the `--provider` flag in the CLI: +Kick off development fast with curated links for connecting, funding, exploring, and deploying your first contract. -```bash -zombienet spawn network.toml --provider INSERT_PROVIDER -``` +| Quick Start | Tools | Description | +|:---------------------------------------------------------------------------------------------------:|:---------------------:|:---------------------------------------------------------------:| +| [Connect to Polkadot](/smart-contracts/connect/){target=\_blank} | Polkadot.js, MetaMask | Add the network, configure RPC, verify activity in the explorer | +| [Get Test Tokens](/smart-contracts/faucets/){target=\_blank} | - | Request test funds to deploy and interact with contracts | +| [Explore Transactions](/smart-contracts/explorers/){target=\_blank} | Subscan | Inspect transactions, logs, token transfers, and contract state | +| [Deploy with Remix](/smart-contracts/dev-environments/remix/deploy-a-contract/){target=\_blank} | Remix | One‑click browser deployment to Polkadot Hub | +| [Deploy with Foundry](/smart-contracts/dev-environments/foundry/deploy-a-contract/){target=\_blank} | Foundry | Scripted deployments and testing from the CLI | +| [Deploy with Hardhat](/smart-contracts/dev-environments/hardhat/deploy-a-contract/){target=\_blank} | Hardhat | Project scaffolding, testing, and deployments | -Alternatively, you can set the provider in the network file: +## Build and Test Locally -```toml -[settings] -provider = "INSERT_PROVIDER" -... -``` +Set up local environments and CI-friendly workflows to iterate quickly and validate changes before deploying. -It's important to note that each provider has specific requirements and associated features. The following sections cover each provider's requirements and added features. +| Build and Test Locally | Tools | Description | +|:------------------------------------------------------------------------------------------------------------:|:-----------------:|:----------------------------------------------------:| +| [Run a Local Dev Node](/smart-contracts/dev-environments/local-dev-node/){target=\_blank} | Polkadot SDK node | Spin up a local node for iterative development | +| [Remix: Get Started](/smart-contracts/dev-environments/remix/get-started/){target=\_blank} | Remix | Connect Remix to Polkadot Hub and configure accounts | +| [Remix: Verify a Contract](/smart-contracts/dev-environments/remix/verify-a-contract/){target=\_blank} | Remix | Publish verified source on explorers | +| [Foundry: Install and Config](/smart-contracts/dev-environments/foundry/install-and-config/){target=\_blank} | Foundry | Install toolchain and configure networks | +| [Foundry: Compile and Test](/smart-contracts/dev-environments/foundry/compile-and-test/){target=\_blank} | Foundry | Write and run Solidity tests locally | +| [Foundry: Verify a Contract](/smart-contracts/dev-environments/foundry/verify-a-contract/){target=\_blank} | Foundry | Verify deployed bytecode and metadata | +| [Hardhat: Install and Config](/smart-contracts/dev-environments/hardhat/install-and-config/){target=\_blank} | Hardhat | Initialize a project and configure networks | +| [Hardhat: Compile and Test](/smart-contracts/dev-environments/hardhat/compile-and-test/){target=\_blank} | Hardhat | Unit test contracts and run scripts | +| [Hardhat: Verify a Contract](/smart-contracts/dev-environments/hardhat/verify-a-contract/){target=\_blank} | Hardhat | Verify deployments on explorers | -### Kubernetes +## Ethereum Developer Resources -Kubernetes is a portable, extensible, open-source platform for managing containerized workloads and services. Zombienet is designed to be compatible with a variety of Kubernetes clusters, including: +Bridge your Ethereum knowledge with Polkadot Hub specifics: account mapping, fees, JSON‑RPC, and deployment. -- [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine){target=\_blank} -- [Docker Desktop](https://docs.docker.com/desktop/features/kubernetes/){target=\_blank} -- [kind](https://kind.sigs.k8s.io/){target=\_blank} +| Ethereum Developer Guides | Description | +|:---------------------------------------------------------------------------------------------------------:|:---------------------------------------------------------------:| +| [Accounts](/smart-contracts/for-eth-devs/accounts/){target=\_blank} | How 20‑byte Ethereum addresses map to 32‑byte Polkadot accounts | +| [Blocks, Transactions, and Fees](/smart-contracts/for-eth-devs/blocks-transactions-fees/){target=\_blank} | Transaction types, fees, and multi‑dimensional metering | +| [Gas Model](/smart-contracts/for-eth-devs/gas-model/){target=\_blank} | Gas vs. weight, proof size, and storage deposits | +| [Contract Deployment](/smart-contracts/for-eth-devs/contract-deployment/){target=\_blank} | Deployment patterns and best practices on Polkadot Hub | +| [JSON‑RPC APIs](/smart-contracts/for-eth-devs/json-rpc-apis/){target=\_blank} | Supported Ethereum JSON‑RPC methods and examples | +| [Migration](/smart-contracts/for-eth-devs/migration/){target=\_blank} | Port existing apps and tooling to Polkadot Hub | +| [Dual VM Stack](/smart-contracts/for-eth-devs/dual-vm-stack/){target=\_blank} | Overview of EVM and native execution on the Hub | -#### Requirements - -To effectively interact with your cluster, you'll need to ensure that [`kubectl`](https://kubernetes.io/docs/reference/kubectl/){target=\_blank} is installed on your system. This Kubernetes command-line tool allows you to run commands against Kubernetes clusters. If you don't have `kubectl` installed, you can follow the instructions provided in the [Kubernetes documentation](https://kubernetes.io/docs/tasks/tools/#kubectl){target=\_blank}. +## Cookbook: Hands‑on Tutorials -To create resources such as namespaces, pods, and CronJobs within the target cluster, you must grant your user or service account the appropriate permissions. These permissions are essential for managing and deploying applications effectively within Kubernetes. +Follow step‑by‑step guides that walk through common tasks and complete dApp examples. -#### Features - -If available, Zombienet uses the Prometheus operator to oversee monitoring and visibility. This configuration ensures that only essential networking-related pods are deployed. Using the Prometheus operator, Zombienet improves its ability to monitor and manage network activities within the Kubernetes cluster efficiently. +| Tutorial | Tools | Description | +|:--------------------------------------------------------------------------------------------------------:|:-------------------:|:-----------------------------------------:| +| [Deploy a Basic Contract](/smart-contracts/cookbook/smart-contracts/deploy-basic/remix/){target=\_blank} | Remix | Minimal deployment walkthrough | +| [Deploy an ERC‑20](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/){target=\_blank} | Remix, OpenZeppelin | Create, deploy, and mint a fungible token | +| [Deploy an NFT (ERC‑721)](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/){target=\_blank} | Remix, OpenZeppelin | Build and deploy an NFT collection | +| [Uniswap V2](/smart-contracts/cookbook/eth-dapps/uniswap-v2/){target=\_blank} | Hardhat | Full dApp project: compile, test, deploy | +| [Zero‑to‑Hero dApp](/smart-contracts/cookbook/dapps/zero-to-hero/){target=\_blank} | Multiple | End‑to‑end dApp patterns and practices | -### Podman +## Libraries -Podman is a daemonless container engine for developing, managing, and running Open Container Initiative (OCI) containers and container images on Linux-based systems. Zombienet supports Podman rootless as a provider on Linux machines. Although Podman has support for macOS through an internal virtual machine (VM), the Zombienet provider code requires Podman to run natively on Linux. +Choose the client libraries that fit your stack for connecting wallets and calling contracts. -#### Requirements - -To use Podman as a provider, you need to have Podman installed on your system. You can install Podman by following the instructions provided on the [Podman website](https://podman.io/getting-started/installation){target=\_blank}. +| Library | Description | +|:------------------------------------------------------------------:|:-------------------------------------------------------:| +| [Ethers.js](/smart-contracts/libraries/ethers-js/){target=\_blank} | Connect, sign, and interact with contracts using Ethers | +| [viem](/smart-contracts/libraries/viem/){target=\_blank} | Type‑safe EVM interactions and utilities | +| [Wagmi](/smart-contracts/libraries/wagmi/){target=\_blank} | React hooks for wallet connections and contract calls | +| [Web3.js](/smart-contracts/libraries/web3-js/){target=\_blank} | Web3 provider and contract APIs | +| [Web3.py](/smart-contracts/libraries/web3-py/){target=\_blank} | Python toolkit for on‑chain interactions and scripts | -#### Features - -Using Podman, Zombienet deploys additional pods to enhance the monitoring and visibility of the active network. Specifically, pods for [Prometheus](https://prometheus.io/){target=\_blank}, [Tempo](https://grafana.com/docs/tempo/latest/operations/monitor/){target=\_blank}, and [Grafana](https://grafana.com/){target=\_blank} are included in the deployment. Grafana is configured with Prometheus and Tempo as data sources. +## Integrations -Upon launching Zombienet, access to these monitoring services is facilitated through specific URLs provided in the output: +Integrate essential services like wallets, indexers, and oracles to round out your dApp. -- **Prometheus**: `http://127.0.0.1:34123` -- **Tempo**: `http://127.0.0.1:34125` -- **Grafana**: `http://127.0.0.1:41461` +| Integration | Description | +|:-------------------------------------------------------------------:|:-----------------------------------------:| +| [Wallets](/smart-contracts/integrations/wallets/){target=\_blank} | Supported wallets and configuration notes | +| [Indexers](/smart-contracts/integrations/indexers/){target=\_blank} | Index and query blockchain data | +| [Oracles](/smart-contracts/integrations/oracles/){target=\_blank} | Bring external data on‑chain | -It's important to note that Grafana is deployed with default administrator access. - -When network operations cease, either from halting a running spawn with the `Ctrl+C` command or test completion, Zombienet automatically removes all associated pods. +## Precompiles -### Local Provider +Discover precompiled system contracts available on the Hub and how to use them. -The Zombienet local provider, also called native, enables you to run nodes as local processes in your environment. +| Topic | Description | +|:------------------------------------------------------------------------:|:---------------------------------------------------:| +| [Overview of Precompiles](/smart-contracts/precompiles/){target=\_blank} | What precompiles are available on the Hub | +| [ETH Native](/smart-contracts/precompiles/eth-native/){target=\_blank} | EVM precompiles and interfaces | +| [Staking](/smart-contracts/precompiles/staking/){target=\_blank} | Interact with staking functionality via precompiles | +| [XCM](/smart-contracts/precompiles/xcm/){target=\_blank} | Cross‑chain messaging helpers for contracts | -#### Requirements - -You must have the necessary binaries for your network (such as `polkadot` and `polkadot-parachain`). These binaries should be available in your PATH, allowing Zombienet to spawn the nodes as local processes. +From here, follow the quick starts to get connected, iterate locally with your preferred tools, and use the guides, libraries, integrations, and precompiles as you grow into production‑ready dApps. If you get stuck, [open an issue](https://github.com/polkadot-developers/polkadot-docs/issues/new?template=docs-issue.yml){target=\_blank} or reach out in the community channels. -To install the necessary binaries, you can use the Zombienet CLI command: -```bash -zombienet setup polkadot polkadot-parachain -``` +--- -This command will download and prepare the necessary binaries for Zombienet's use. +Page Title: Get Started with XCM -If you need to use a custom binary, ensure the binary is available in your PATH. You can also specify the binary path in the network configuration file. The following example uses the custom [OpenZeppelin template](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\_blank}: +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md +- Canonical (HTML): https://docs.polkadot.com/parachains/interoperability/get-started/ +- Summary: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. -First, clone the OpenZeppelin template repository using the following command: +# Get Started with XCM -```bash -git clone https://github.com/OpenZeppelin/polkadot-runtime-templates \ -&& cd polkadot-runtime-templates/generic-template -``` +## Introduction -Next, run the command to build the custom binary: +Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems. -```bash -cargo build --release -``` +With XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation. -Finally, add the custom binary to your PATH as follows: +## Messaging Format -```bash -export PATH=$PATH:INSERT_PATH_TO_RUNTIME_TEMPLATES/parachain-template-node/target/release -``` +XCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics. -Alternatively, you can specify the binary path in the network configuration file. The local provider exclusively utilizes the command configuration for nodes, which supports both relative and absolute paths. You can employ the `default_command` configuration to specify the binary for spawning all nodes in the relay chain. +XCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing. -```toml -[relaychain] -chain = "rococo-local" -default_command = "./bin-v1.6.0/polkadot" +## The Four Principles of XCM -[parachain] -id = 1000 +XCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems: - [parachain.collators] - name = "collator01" - command = "./target/release/parachain-template-node" -``` +- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes. +- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended. +- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin. +- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems. -#### Features +These principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments. -The local provider does not offer any additional features. +## The XCM Tech Stack -## Configure Zombienet +![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp) -Effective network configuration is crucial for deploying and managing blockchain systems. Zombienet simplifies this process by offering versatile configuration options in both JSON and TOML formats. Whether setting up a simple test network or a complex multi-node system, Zombienet's tools provide the flexibility to customize every aspect of your network's setup. +The XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels. -The following sections will explore the structure and usage of Zombienet configuration files, explain key settings for network customization, and walk through CLI commands and flags to optimize your development workflow. +## Core Functionalities of XCM -### Configuration Files +XCM enhances cross-consensus communication by introducing several powerful features: -The network configuration file can be either JSON or TOML format. The Zombienet repository also provides a collection of [example configuration files](https://github.com/paritytech/zombienet/tree/main/examples){target=\_blank} that can be used as a reference. +- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management. +- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification. +- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location. -Each section may include provider-specific keys that aren't recognized by other providers. For example, if you use the local provider, any references to images for nodes will be disregarded. +The standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications. -### CLI Usage +## XCM Example -Zombienet provides a CLI that allows interaction with the tool. The CLI can receive commands and flags to perform different kinds of operations. These operations use the following syntax: +The following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA). -```bash -zombienet +```rust +let message = Xcm(vec![ + WithdrawAsset((Here, amount).into()), + BuyExecution { + fees: (Here, amount).into(), + weight_limit: WeightLimit::Unlimited + }, + DepositAsset { + assets: All.into(), + beneficiary: MultiLocation { + parents: 0, + interior: Junction::AccountId32 { + network: None, + id: BOB.clone().into() + }.into(), + }.into() + } +]); ``` -The following sections will guide you through the primary usage of the Zombienet CLI and the available commands and flags. +The message consists of three instructions described as follows: -#### CLI Commands +- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register. -- **`spawn `**: Spawn the network defined in the [configuration file](#configuration-files). -- **`test `**: Run tests on the spawned network using the assertions and tests defined in the [test file](/develop/toolkit/parachains/spawn-chains/zombienet/write-tests/#the-test-file){target=\_blank}. -- **`setup `**: Set up the Zombienet development environment to download and use the `polkadot` or `polkadot-parachain` executable. -- **`convert `**: Transforms a [polkadot-launch](https://github.com/paritytech/polkadot-launch){target=\_blank} configuration file with a `.js` or `.json` extension into a Zombienet configuration file. -- **`version`**: Prints Zombienet version. -- **`help`**: Prints help information. + ```rust + WithdrawAsset((Here, amount).into()), + ``` -#### CLI Flags + - **`Here`**: The native parachain token. + - **`amount`**: The number of tokens that are transferred. -You can use the following flags to customize the behavior of the CLI: + The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register. -- **`-p`, `--provider`**: Override the [provider](#providers) to use. -- **`-d`, `--dir`**: Specify a directory path for placing the network files instead of using the default temporary path. -- **`-f`, `--force`**: Force override all prompt commands. -- **`-l`, `--logType`**: Type of logging on the console. Defaults to `table`. -- **`-m`, `--monitor`**: Start as monitor and don't auto clean up network. -- **`-c`, `--spawn-concurrency`**: Number of concurrent spawning processes to launch. Defaults to `1`. -- **`-h`, `--help`**: Display help for command. - -### Settings - -Through the keyword `settings`, it's possible to define the general settings for the network. The available keys are: - -- **`global_volumes?`** ++"GlobalVolume[]"++: A list of global volumes to use. - - ??? child "`GlobalVolume` interface definition" - ```js - export interface GlobalVolume { - name: string; - fs_type: string; - mount_path: string; - } - ``` - -- **`bootnode`** ++"boolean"++: Add bootnode to network. Defaults to `true`. -- **`bootnode_domain?`** ++"string"++: Domain to use for bootnode. -- **`timeout`** ++"number"++: Global timeout to use for spawning the whole network. -- **`node_spawn_timeout?`** ++"number"++: Timeout to spawn pod/process. -- **`grafana?`** ++"boolean"++: Deploy an instance of Grafana. -- **`prometheus?`** ++"boolean"++: Deploy an instance of Prometheus. -- **`telemetry?`** ++"boolean"++: Enable telemetry for the network. -- **`jaeger_agent?`** ++"string"++: The Jaeger agent endpoint passed to the nodes. Only available on Kubernetes. -- **`tracing_collator_url?`** ++"string"++: The URL of the tracing collator used to query by the tracing assertion. Should be tempo query compatible. -- **`tracing_collator_service_name?`** ++"string"++: Service name for tempo query frontend. Only available on Kubernetes. Defaults to `tempo-tempo-distributed-query-frontend`. -- **`tracing_collator_service_namespace?`** ++"string"++: Namespace where tempo is running. Only available on Kubernetes. Defaults to `tempo`. -- **`tracing_collator_service_port?`** ++"number"++: Port of the query instance of tempo. Only available on Kubernetes. Defaults to `3100`. -- **`enable_tracing?`** ++"boolean"++: Enable the tracing system. Only available on Kubernetes. Defaults to `true`. -- **`provider`** ++"string"++: Provider to use. Default is `kubernetes`". -- **`polkadot_introspector?`** ++"boolean"++: Deploy an instance of polkadot-introspector. Only available on Podman and Kubernetes. Defaults to `false`. -- **`backchannel?`** ++"boolean"++: Deploy an instance of backchannel server. Only available on Kubernetes. Defaults to `false`. -- **`image_pull_policy?`** ++"string"++: Image pull policy to use in the network. Possible values are `Always`, `IfNotPresent`, and `Never`. -- **`local_ip?`** ++"string"++: IP used for exposing local services (rpc/metrics/monitors). Defaults to `"127.0.0.1"`. -- **`global_delay_network_global_settings?`** ++"number"++: Delay in seconds to apply to the network. -- **`node_verifier?`** ++"string"++: Specify how to verify node readiness or deactivate by using `None`. Possible values are `None` and `Metric`. Defaults to `Metric`. - -For example, the following configuration file defines a minimal example for the settings: - -=== "TOML" - - ```toml title="base-example.toml" - [settings] - timeout = 1000 - bootnode = false - provider = "kubernetes" - backchannel = false - # ... - - ``` - -=== "JSON" - - ```json title="base-example.json" - { - "settings": { - "timeout": 1000, - "bootnode": false, - "provider": "kubernetes", - "backchannel": false, - "...": {} - }, - "...": {} - } - - ``` - -### Relay Chain Configuration - -You can use the `relaychain` keyword to define further parameters for the relay chain at start-up. The available keys are: - -- **`default_command?`** ++"string"++: The default command to run. Defaults to `polkadot`. -- **`default_image?`** ++"string"++: The default Docker image to use. -- **`default_resources?`** ++"Resources"++: Represents the resource limits/reservations the nodes need by default. Only available on Kubernetes. - - ??? child "`Resources` interface definition" - ```js - export interface Resources { - resources: { - requests?: { - memory?: string; - cpu?: string; - }; - limits?: { - memory?: string; - cpu?: string; - }; - }; - } - ``` - -- **`default_db_snapshot?`** ++"string"++: The default database snapshot to use. -- **`default_prometheus_prefix`** ++"string"++: A parameter for customizing the metric's prefix. Defaults to `substrate`. -- **`default_substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version. - - ??? child "`SubstrateCliArgsVersion` enum definition" - ```js - export enum SubstrateCliArgsVersion { - V0 = 0, - V1 = 1, - V2 = 2, - V3 = 3, - } - ``` - -- **`default_keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. -- **`chain`** ++"string"++: The chain name. -- **`chain_spec_path?`** ++"string"++: Path to the chain spec file. Should be the plain version to allow customizations. -- **`chain_spec_command?`** ++"string"++: Command to generate the chain spec. It can't be used in combination with `chain_spec_path`. -- **`default_args?`** ++"string[]"++: An array of arguments to use as default to pass to the command. -- **`default_overrides?`** ++"Override[]"++: An array of overrides to upload to the node. - - ??? child "`Override` interface definition" - ```js - export interface Override { - local_path: string; - remote_name: string; - } - ``` - -- **`random_nominators_count?`** ++"number"++: If set and the stacking pallet is enabled, Zombienet will generate the input quantity of nominators and inject them into the genesis. -- **`max_nominations`** ++"number"++: The max number of nominations allowed by a nominator. Should match the value set in the runtime. Defaults to `24`. -- **`nodes?`** ++"Node[]"++: An array of nodes to spawn. It is further defined in the [Node Configuration](#node-configuration) section. -- **`node_groups?`** ++"NodeGroup[]"++: An array of node groups to spawn. It is further defined in the [Node Group Configuration](#node-group-configuration) section. -- **`total_node_in_group?`** ++"number"++: The total number of nodes in the group. Defaults to `1`. -- **`genesis`** ++"JSON"++: The genesis configuration. -- **`default_delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. - - ??? child "`DelayNetworkSettings` interface definition" - ```js - export interface DelayNetworkSettings { - latency: string; - correlation?: string; // should be parsable as float by k8s - jitter?: string; - } - ``` - -#### Node Configuration - -One specific key capable of receiving more subkeys is the `nodes` key. This key is used to define further parameters for the nodes. The available keys: - -- **`name`** ++"string"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`). -- **`image?`** ++"string"++: Override default Docker image to use for this node. -- **`command?`** ++"string"++: Override default command to run. -- **`command_with_args?`** ++"string"++: Override default command and arguments. -- **`args?`** ++"string[]"++: Arguments to be passed to the command. -- **`env?`** ++"envVars[]"++: Environment variables to set in the container. - - ??? child "`envVars` interface definition" - ```js - export interface EnvVars { - name: string; - value: string; - } - ``` - -- **`prometheus_prefix?`** ++"string"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`. -- **`db_snapshot?`** ++"string"++: Database snapshot to use. -- **`substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead. - - ??? child "`SubstrateCliArgsVersion` enum definition" - ```js - export enum SubstrateCliArgsVersion { - V0 = 0, - V1 = 1, - V2 = 2, - V3 = 3, - } - ``` - -- **`resources?`** ++"Resources"++: Represent the resources limits/reservations needed by the node. - - ??? child "`Resources` interface definition" - ```js - export interface Resources { - resources: { - requests?: { - memory?: string; - cpu?: string; - }; - limits?: { - memory?: string; - cpu?: string; - }; - }; - } - ``` - -- **`keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. -- **`validator`** ++"boolean"++: Pass the `--validator` flag to the command. Defaults to `true`. -- **`invulnerable`** ++"boolean"++: If true, add the node to invulnerables in the chain spec. Defaults to `false`. -- **`balance`** ++"number"++: Balance to set in balances for node's account. Defaults to `2000000000000`. -- **`bootnodes?`** ++"string[]"++: Array of bootnodes to use. -- **`add_to_bootnodes?`** ++"boolean"++: Add this node to the bootnode list. Defaults to `false`. -- **`ws_port?`** ++"number"++: WS port to use. -- **`rpc_port?`** ++"number"++: RPC port to use. -- **`prometheus_port?`** ++"number"++: Prometheus port to use. -- **`p2p_cert_hash?`** ++"string"++: Libp2p certhash to use with webRTC transport. -- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. - - ??? child "`DelayNetworkSettings` interface definition" - ```js - export interface DelayNetworkSettings { - latency: string; - correlation?: string; // should be parsable as float by k8s - jitter?: string; - } - ``` - -The following configuration file defines a minimal example for the relay chain, including the `nodes` key: - -=== "TOML" - - ```toml title="relaychain-example-nodes.toml" - [relaychain] - default_command = "polkadot" - default_image = "polkadot-debug:master" - chain = "rococo-local" - chain_spec_path = "INSERT_PATH_TO_CHAIN_SPEC" - default_args = ["--chain", "rococo-local"] - - [[relaychain.nodes]] - name = "alice" - validator = true - balance = 1000000000000 - - [[relaychain.nodes]] - name = "bob" - validator = true - balance = 1000000000000 - # ... - - ``` - -=== "JSON" - - ```json title="relaychain-example-nodes.json" - { - "relaychain": { - "default_command": "polkadot", - "default_image": "polkadot-debug:master", - "chain": "rococo-local", - "chain_spec_path": "INSERT_PATH_TO_CHAIN-SPEC.JSON", - "default_args": ["--chain", "rococo-local"], - "nodes": [ - { - "name": "alice", - "validator": true, - "balance": 1000000000000 - }, - { - "name": "bob", - "validator": true, - "balance": 1000000000000 - } - ] - } - } - - ``` - -#### Node Group Configuration - -The `node_groups` key defines further parameters for the node groups. The available keys are: - -- **`name`** ++"string"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`). -- **`image?`** ++"string"++: Override default Docker image to use for this node. -- **`command?`** ++"string"++: Override default command to run. -- **`args?`** ++"string[]"++: Arguments to be passed to the command. -- **`env?`** ++"envVars[]"++: Environment variables to set in the container. - - ??? child "`envVars` interface definition" - ```js - export interface EnvVars { - name: string; - value: string; - } - ``` - -- **`overrides?`** ++"Override[]"++: Array of overrides definitions. - - ??? child "`Override` interface definition" - ```js - export interface Override { - local_path: string; - remote_name: string; - } - ``` - -- **`prometheus_prefix?`** ++"string"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`. -- **`db_snapshot?`** ++"string"++: Database snapshot to use. -- **`substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead. - - ??? child "`SubstrateCliArgsVersion` enum definition" - ```js - export enum SubstrateCliArgsVersion { - V0 = 0, - V1 = 1, - V2 = 2, - V3 = 3, - } - ``` - -- **`resources?`** ++"Resources"++: Represent the resources limits/reservations needed by the node. - - ??? child "`Resources` interface definition" - ```js - export interface Resources { - resources: { - requests?: { - memory?: string; - cpu?: string; - }; - limits?: { - memory?: string; - cpu?: string; - }; - }; - } - ``` - -- **`keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. -- **`count`** ++"number | string"++: Number of nodes to launch for this group. -- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. - - ??? child "`DelayNetworkSettings` interface definition" - ```js - export interface DelayNetworkSettings { - latency: string; - correlation?: string; // should be parsable as float by k8s - jitter?: string; - } - ``` - -The following configuration file defines a minimal example for the relay chain, including the `node_groups` key: - -=== "TOML" - - ```toml title="relaychain-example-node-groups.toml" - [relaychain] - default_command = "polkadot" - default_image = "polkadot-debug:master" - chain = "rococo-local" - chain_spec_path = "INSERT_PATH_TO_CHAIN_SPEC" - default_args = ["--chain", "rococo-local"] - - [[relaychain.node_groups]] - name = "group-1" - count = 2 - image = "polkadot-debug:master" - command = "polkadot" - args = ["--chain", "rococo-local"] - # ... - - ``` - -=== "JSON" - - ```json title="relaychain-example-node-groups.json" - { - "relaychain": { - "default_command": "polkadot", - "default_image": "polkadot-debug:master", - "chain": "rococo-local", - "chain_spec_path": "INSERT_PATH_TO_CHAIN-SPEC.JSON", - "default_args": ["--chain", "rococo-local"], - "node_groups": [ - { - "name": "group-1", - "count": 2, - "image": "polkadot-debug:master", - "command": "polkadot", - "args": ["--chain", "rococo-local"] - } - ], - "...": {} - }, - "...": {} - } - - ``` - -### Parachain Configuration - -The `parachain` keyword defines further parameters for the parachain. The available keys are: - -- **`id`** ++"number"++: The id to assign to this parachain. Must be unique. -- **`chain?`** ++"string"++: The chain name. -- **`force_decorator?`** ++"string"++: Force the use of a specific decorator. -- **`genesis?`** ++"JSON"++: The genesis configuration. -- **`balance?`** ++"number"++: Balance to set in balances for parachain's account. -- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. - - ??? child "`DelayNetworkSettings` interface definition" - ```js - export interface DelayNetworkSettings { - latency: string; - correlation?: string; // should be parsable as float by k8s - jitter?: string; - } - ``` - -- **`add_to_genesis?`** ++"boolean"++: Flag to add parachain to genesis or register in runtime. Defaults to `true`. -- **`register_para?`** ++"boolean"++: Flag to specify whether the para should be registered. The `add_to_genesis` flag must be set to false for this flag to have any effect. Defaults to `true`. -- **`onboard_as_parachain?`** ++"boolean"++: Flag to specify whether the para should be onboarded as a parachain, rather than remaining a parathread. Defaults to `true`. -- **`genesis_wasm_path?`** ++"string"++: Path to the Wasm file to use. -- **`genesis_wasm_generator?`** ++"string"++: Command to generate the Wasm file. -- **`genesis_state_path?`** ++"string"++: Path to the state file to use. -- **`genesis_state_generator?`** ++"string"++: Command to generate the state file. -- **`chain_spec_path?`** ++"string"++: Path to the chain spec file. -- **`chain_spec_command?`** ++"string"++: Command to generate the chain spec. -- **`cumulus_based?`** ++"boolean"++: Flag to use cumulus command generation. Defaults to `true`. -- **`bootnodes?`** ++"string[]"++: Array of bootnodes to use. -- **`prometheus_prefix?`** ++"string"++: Parameter for customizing the metric's prefix for all parachain nodes/collators. Defaults to `substrate`. -- **`collator?`** ++"Collator"++: Further defined in the [Collator Configuration](#collator-configuration) section. -- **`collator_groups?`** ++"CollatorGroup[]"++: An array of collator groups to spawn. It is further defined in the [Collator Groups Configuration](#collator-groups-configuration) section. - -For example, the following configuration file defines a minimal example for the parachain: - -=== "TOML" - - ```toml title="parachain-example.toml" - [parachain] - id = 100 - add_to_genesis = true - cumulus_based = true - genesis_wasm_path = "INSERT_PATH_TO_WASM" - genesis_state_path = "INSERT_PATH_TO_STATE" - # ... - - ``` - -=== "JSON" - - ```json title="parachain-example.json" - { - "parachain": { - "id": 100, - "add_to_genesis": true, - "cumulus_based": true, - "genesis_wasm_path": "INSERT_PATH_TO_WASM", - "genesis_state_path": "INSERT_PATH_TO_STATE", - "...": {} - }, - "...": {} - } - - ``` - -#### Collator Configuration - -One specific key capable of receiving more subkeys is the `collator` key. This key defines further parameters for the nodes. The available keys are: - -- **`name`** ++"string"++: Name of the collator. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`). -- **`image?`** ++"string"++: Image to use for the collator. -- **`command_with_args?`** ++"string"++: Overrides both command and arguments for the collator. -- **`validator`** ++"boolean"++: Pass the `--validator` flag to the command. Defaults to `true`. -- **`invulnerable`** ++"boolean"++: If true, add the collator to invulnerables in the chain spec. Defaults to `false`. -- **`balance`** ++"number"++: Balance to set in balances for collator's account. Defaults to `2000000000000`. -- **`bootnodes?`** ++"string[]"++: Array of bootnodes to use. -- **`add_to_bootnodes?`** ++"boolean"++: Add this collator to the bootnode list. Defaults to `false`. -- **`ws_port?`** ++"number"++: WS port to use. -- **`rpc_port?`** ++"number"++: RPC port to use. -- **`prometheus_port?`** ++"number"++: Prometheus port to use. -- **`p2p_port?`** ++"number"++: P2P port to use. -- **`p2p_cert_hash?`** ++"string"++: Libp2p certhash to use with webRTC transport. -- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. - - ??? child "`DelayNetworkSettings` interface definition" - ```js - export interface DelayNetworkSettings { - latency: string; - correlation?: string; // should be parsable as float by k8s - jitter?: string; - } - ``` - -- **`command?`** ++"string"++: Override default command to run. -- **`args?`** ++"string[]"++: Arguments to be passed to the command. -- **`env?`** ++"envVars[]"++: Environment variables to set in the container. - - ??? child "`envVars` interface definition" - ```js - export interface EnvVars { - name: string; - value: string; - } - ``` - -- **`overrides?`** ++"Override[]"++: Array of overrides definitions. - - ??? child "`Override` interface definition" - ```js - export interface Override { - local_path: string; - remote_name: string; - } - ``` - -- **`prometheus_prefix?`** ++"string"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`. -- **`db_snapshot?`** ++"string"++: Database snapshot to use. -- **`substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead. - - ??? child "`SubstrateCliArgsVersion` enum definition" - ```js - export enum SubstrateCliArgsVersion { - V0 = 0, - V1 = 1, - V2 = 2, - V3 = 3, - } - ``` - -- **`resources?`** ++"Resources"++: Represent the resources limits/reservations needed by the node. - - ??? child "`Resources` interface definition" - ```js - export interface Resources { - resources: { - requests?: { - memory?: string; - cpu?: string; - }; - limits?: { - memory?: string; - cpu?: string; - }; - }; - } - ``` - -- **`keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. - -The configuration file below defines a minimal example for the collator: - -=== "TOML" - - ```toml title="collator-example.toml" - [parachain] - id = 100 - add_to_genesis = true - cumulus_based = true - genesis_wasm_path = "INSERT_PATH_TO_WASM" - genesis_state_path = "INSERT_PATH_TO_STATE" - - [[parachain.collators]] - name = "alice" - image = "polkadot-parachain" - command = "polkadot-parachain" - # ... - - ``` - -=== "JSON" - - ```json title="collator-example.json" - { - "parachain": { - "id": 100, - "add_to_genesis": true, - "cumulus_based": true, - "genesis_wasm_path": "INSERT_PATH_TO_WASM", - "genesis_state_path": "INSERT_PATH_TO_STATE", - "collators": [ - { - "name": "alice", - "image": "polkadot-parachain", - "command": "polkadot-parachain", - "...": {} - } - ] - }, - "...": {} - } - - ``` - -#### Collator Groups Configuration - -The `collator_groups` key defines further parameters for the collator groups. The available keys are: - -- **`name`** ++"string"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`). -- **`image?`** ++"string"++: Override default Docker image to use for this node. -- **`command?`** ++"string"++: Override default command to run. -- **`args?`** ++"string[]"++: Arguments to be passed to the command. -- **`env?`** ++"envVars[]"++: Environment variables to set in the container. - - ??? child "`envVars` interface definition" - ```js - export interface EnvVars { - name: string; - value: string; - } - ``` - -- **`overrides?`** ++"Override[]"++: Array of overrides definitions. - - ??? child "`Override` interface definition" - ```js - export interface Override { - local_path: string; - remote_name: string; - } - ``` - -- **`prometheus_prefix?`** ++"string"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`. -- **`db_snapshot?`** ++"string"++: Database snapshot to use. -- **`substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead. - - ??? child "`SubstrateCliArgsVersion` enum definition" - ```js - export enum SubstrateCliArgsVersion { - V0 = 0, - V1 = 1, - V2 = 2, - V3 = 3, - } - ``` - -- **`resources?`** ++"Resources"++: Represent the resources limits/reservations needed by the node. - - ??? child "`Resources` interface definition" - ```js - export interface Resources { - resources: { - requests?: { - memory?: string; - cpu?: string; - }; - limits?: { - memory?: string; - cpu?: string; - }; - }; - } - ``` - -- **`keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. -- **`count`** ++"number | string"++: Number of nodes to launch for this group. -- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. - - ??? child "`DelayNetworkSettings` interface definition" - ```js - export interface DelayNetworkSettings { - latency: string; - correlation?: string; // should be parsable as float by k8s - jitter?: string; - } - ``` - -For instance, the configuration file below defines a minimal example for the collator groups: - -=== "TOML" - - ```toml title="collator-groups-example.toml" - [parachain] - id = 100 - add_to_genesis = true - cumulus_based = true - genesis_wasm_path = "INSERT_PATH_TO_WASM" - genesis_state_path = "INSERT_PATH_TO_STATE" - - [[parachain.collator_groups]] - name = "group-1" - count = 2 - image = "polkadot-parachain" - command = "polkadot-parachain" - # ... - - ``` - -=== "JSON" - - ```json title="collator-groups-example.json" - { - "parachain": { - "id": 100, - "add_to_genesis": true, - "cumulus_based": true, - "genesis_wasm_path": "INSERT_PATH_TO_WASM", - "genesis_state_path": "INSERT_PATH_TO_STATE", - "collator_groups": [ - { - "name": "group-1", - "count": 2, - "image": "polkadot-parachain", - "command": "polkadot-parachain", - "...": {} - } - ] - }, - "...": {} - } - - ``` - -### XCM Configuration - -You can use the `hrmp_channels` keyword to define further parameters for the XCM channels at start-up. The available keys are: - -- **`hrmp_channels`** ++"HrmpChannelsConfig[]"++: Array of Horizontal Relay-routed Message Passing (HRMP) channel configurations. - - ??? child "`HrmpChannelsConfig` interface definition" - ```js - export interface HrmpChannelsConfig { - sender: number; - recipient: number; - max_capacity: number; - max_message_size: number; - } - ``` - Each of the `HrmpChannelsConfig` keys are defined as follows: - - - **`sender` ++"number"++**: Parachain ID of the sender. - - **`recipient` ++"number"++**: Parachain ID of the recipient. - - **`max_capacity` ++"number"++**: Maximum capacity of the HRMP channel. - - **`max_message_size` ++"number"++**: Maximum message size allowed in the HRMP channel. - -## Where to Go Next - -
- -- External __Zombienet Support__ - - --- - - [Parity Technologies](https://www.parity.io/){target=\_blank} has designed and developed this framework, now maintained by the Zombienet team. - - For further support and information, refer to the following contact points: - - [:octicons-arrow-right-24: Zombienet repository](https://github.com/paritytech/zombienet){target=\_blank} - - [:octicons-arrow-right-24: Element public channel](https://matrix.to/#/!FWyuEyNvIFygLnWNMh:parity.io?via=parity.io&via=matrix.org&via=web3.foundation){target=\_blank} - - -- Tutorial __Spawn a Basic Chain with Zombienet__ - - --- - - Learn to spawn, connect to and monitor a basic blockchain network with Zombienet, using customizable configurations for streamlined development and debugging. - - [:octicons-arrow-right-24: Reference](/tutorials/polkadot-sdk/testing/spawn-basic-chain/) - -
- - ---- - -Page Title: Get Started with Parachain Development - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-get-started.md -- Canonical (HTML): https://docs.polkadot.com/parachains/get-started/ -- Summary: Practical examples and tutorials for building and deploying Polkadot parachains, covering everything from launch to customization and cross-chain messaging. - -# Get Started - -The following sections provide practical recipes for building parachains on Polkadot—each focused on specific development scenarios with step-by-step, hands-on examples. - -## Quick Start Guides - -Quick start guides help developers set up and interact with the Polkadot parachain ecosystem using various tools and frameworks. - -| Tutorial | Tools | Description | -| :--------------------------------------------------------------------------------------------: | :----------------------------: | :---------------------------------------------------------------------: | -| [Set Up the Parachain Template](/parachains/launch-a-parachain/set-up-the-parachain-template/) | Polkadot SDK | Learn how to set up and run the Polkadot SDK Parachain Template locally | -| [Launch a Local Parachain](/parachains/testing/run-a-parachain-network/) | Zombienet, Chopsticks | Set up a local development environment for testing | -| [Connect to Polkadot](/chain-interactions/query-on-chain-data/query-sdks/) | Polkadot.js, Substrate Connect | Connect your application to Polkadot networks | -| [Fork an Existing Parachain](/parachains/testing/fork-a-parachain/) | Chopsticks | Create a local fork of a live parachain for testing | - -## Launch a Simple Parachain - -Learn the fundamentals of launching and deploying a parachain to the Polkadot network. - -| Tutorial | Description | -| :--------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------: | -| [Set Up the Parachain Template](/parachains/launch-a-parachain/set-up-the-parachain-template/) | Polkadot SDK | -| [Deploy to Polkadot](/parachains/launch-a-parachain/deploy-to-polkadot/) | Step-by-step tutorial to deploying your parachain to Polkadot | -| [Obtain Coretime](/parachains/launch-a-parachain/obtain-coretime/) | Learn how to acquire blockspace using Polkadot's coretime model (RegionX) | - -## Customize Your Runtime - -Build custom functionality for your parachain by composing and creating pallets. - -| Tutorial | Description | -| :-------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------: | -| [Add Existing Pallets to the Runtime](/parachains/customize-runtime/add-existing-pallets/) | Integrate pre-built pallets from the FRAME ecosystem | -| [Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/) | Configure and use multiple instances of the same pallet | -| [Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/) | Enable smart contract capabilities using Contracts or EVM pallets | - -### Pallet Development - -Deep dive into creating and managing custom pallets for your parachain. - -| Tutorial | Description | -| :--------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------: | -| [Create a Custom Pallet](/parachains/customize-runtime/pallet-development/create-a-pallet/) | Build a pallet from scratch with custom logic | -| [Mock Your Runtime](/parachains/customize-runtime/pallet-development/mock-runtime/) | Set up a mock runtime environment for testing | -| [Pallet Unit Testing](/parachains/customize-runtime/pallet-development/pallet-testing/) | Write comprehensive tests for your pallet logic | -| [Add Your Custom Pallet to the Runtime](/parachains/customize-runtime/pallet-development/add-pallet-to-runtime/) | Integrate your custom pallet into your parachain runtime | -| [Benchmark the Custom Pallet](/parachains/customize-runtime/pallet-development/benchmark-pallet/) | Measure and optimize pallet performance with benchmarking | - -## Testing - -Test your parachain in various environments before production deployment. - -| Tutorial | Description | -| :---------------------------------------------------------------------: | :-----------------------------------------------------: | -| [Fork a Parachain](/parachains/testing/fork-a-parachain/) | Use Chopsticks to create a local fork for testing | -| [Run a Parachain Network](/parachains/testing/run-a-parachain-network/) | Launch a complete parachain test network with Zombienet | - -## Runtime Upgrades and Maintenance - -Manage your parachain's lifecycle with forkless upgrades and maintenance operations. - -| Tutorial | Description | -| :-----------------------------------------------------------------------: | :--------------------------------------------------: | -| [Runtime Upgrades](/parachains/runtime-maintenance/runtime-upgrades/) | Perform forkless runtime upgrades via governance | -| [Storage Migrations](/parachains/runtime-maintenance/storage-migrations/) | Safely migrate storage when updating runtime logic | -| [Unlock Parachains](/parachains/runtime-maintenance/unlock-parachains/) | Understand parachain lifecycle and unlock mechanisms | - -## Interoperability - -Configure your parachain for cross-chain communication using XCM (Cross-Consensus Messaging). - -| Tutorial | Description | -| :--------------------------------------------------------------------------------------------------------: | :----------------------------------------------------: | -| [Open HRMP Channels Between Parachains](/parachains/interoperability/channels-between-parachains/) | Establish communication channels with other parachains | -| [Open HRMP Channels with System Parachains](/parachains/interoperability/channels-with-system-parachains/) | Connect with Asset Hub and other system parachains | - -## Integrations - -Integrate your parachain with essential ecosystem tools and services. - -| Tutorial | Description | -| :--------------------------------------------: | :----------------------------------------------------: | -| [Wallets](/parachains/integrations/wallets/) | Integrate wallet support for user interactions | -| [Indexers](/parachains/integrations/indexers/) | Set up indexing solutions for querying blockchain data | -| [Oracles](/parachains/integrations/oracles/) | Connect your parachain to off-chain data sources | - -## Additional Resources - -- [Polkadot SDK Documentation](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/index.html) -- [Polkadot Wiki - Parachains](https://wiki.polkadot.network/docs/learn-parachains/) - - ---- - -Page Title: Get Started with Smart Contracts - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-get-started.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/get-started/ -- Summary: Practical examples for building and deploying smart contracts on Polkadot Hub, from connecting and tooling to deployment, integrations, and precompiles. - -# Get Started - -This resource provides quick-starts for building smart contracts on Polkadot Hub. Use the tables below to jump directly to the tools and workflows you need. - -## Quick Starts - -Kick off development fast with curated links for connecting, funding, exploring, and deploying your first contract. - -| Quick Start | Tools | Description | -|:---------------------------------------------------------------------------------------------------:|:---------------------:|:---------------------------------------------------------------:| -| [Connect to Polkadot](/smart-contracts/connect/){target=\_blank} | Polkadot.js, MetaMask | Add the network, configure RPC, verify activity in the explorer | -| [Get Test Tokens](/smart-contracts/faucets/){target=\_blank} | - | Request test funds to deploy and interact with contracts | -| [Explore Transactions](/smart-contracts/explorers/){target=\_blank} | Subscan | Inspect transactions, logs, token transfers, and contract state | -| [Deploy with Remix](/smart-contracts/dev-environments/remix/deploy-a-contract/){target=\_blank} | Remix | One‑click browser deployment to Polkadot Hub | -| [Deploy with Foundry](/smart-contracts/dev-environments/foundry/deploy-a-contract/){target=\_blank} | Foundry | Scripted deployments and testing from the CLI | -| [Deploy with Hardhat](/smart-contracts/dev-environments/hardhat/deploy-a-contract/){target=\_blank} | Hardhat | Project scaffolding, testing, and deployments | - -## Build and Test Locally - -Set up local environments and CI-friendly workflows to iterate quickly and validate changes before deploying. - -| Build and Test Locally | Tools | Description | -|:------------------------------------------------------------------------------------------------------------:|:-----------------:|:----------------------------------------------------:| -| [Run a Local Dev Node](/smart-contracts/dev-environments/local-dev-node/){target=\_blank} | Polkadot SDK node | Spin up a local node for iterative development | -| [Remix: Get Started](/smart-contracts/dev-environments/remix/get-started/){target=\_blank} | Remix | Connect Remix to Polkadot Hub and configure accounts | -| [Remix: Verify a Contract](/smart-contracts/dev-environments/remix/verify-a-contract/){target=\_blank} | Remix | Publish verified source on explorers | -| [Foundry: Install and Config](/smart-contracts/dev-environments/foundry/install-and-config/){target=\_blank} | Foundry | Install toolchain and configure networks | -| [Foundry: Compile and Test](/smart-contracts/dev-environments/foundry/compile-and-test/){target=\_blank} | Foundry | Write and run Solidity tests locally | -| [Foundry: Verify a Contract](/smart-contracts/dev-environments/foundry/verify-a-contract/){target=\_blank} | Foundry | Verify deployed bytecode and metadata | -| [Hardhat: Install and Config](/smart-contracts/dev-environments/hardhat/install-and-config/){target=\_blank} | Hardhat | Initialize a project and configure networks | -| [Hardhat: Compile and Test](/smart-contracts/dev-environments/hardhat/compile-and-test/){target=\_blank} | Hardhat | Unit test contracts and run scripts | -| [Hardhat: Verify a Contract](/smart-contracts/dev-environments/hardhat/verify-a-contract/){target=\_blank} | Hardhat | Verify deployments on explorers | - -## Ethereum Developer Resources - -Bridge your Ethereum knowledge with Polkadot Hub specifics: account mapping, fees, JSON‑RPC, and deployment. - -| Ethereum Developer Guides | Description | -|:---------------------------------------------------------------------------------------------------------:|:---------------------------------------------------------------:| -| [Accounts](/smart-contracts/for-eth-devs/accounts/){target=\_blank} | How 20‑byte Ethereum addresses map to 32‑byte Polkadot accounts | -| [Blocks, Transactions, and Fees](/smart-contracts/for-eth-devs/blocks-transactions-fees/){target=\_blank} | Transaction types, fees, and multi‑dimensional metering | -| [Gas Model](/smart-contracts/for-eth-devs/gas-model/){target=\_blank} | Gas vs. weight, proof size, and storage deposits | -| [Contract Deployment](/smart-contracts/for-eth-devs/contract-deployment/){target=\_blank} | Deployment patterns and best practices on Polkadot Hub | -| [JSON‑RPC APIs](/smart-contracts/for-eth-devs/json-rpc-apis/){target=\_blank} | Supported Ethereum JSON‑RPC methods and examples | -| [Migration](/smart-contracts/for-eth-devs/migration/){target=\_blank} | Port existing apps and tooling to Polkadot Hub | -| [Dual VM Stack](/smart-contracts/for-eth-devs/dual-vm-stack/){target=\_blank} | Overview of EVM and native execution on the Hub | - -## Cookbook: Hands‑on Tutorials - -Follow step‑by‑step guides that walk through common tasks and complete dApp examples. - -| Tutorial | Tools | Description | -|:--------------------------------------------------------------------------------------------------------:|:-------------------:|:-----------------------------------------:| -| [Deploy a Basic Contract](/smart-contracts/cookbook/smart-contracts/deploy-basic/remix/){target=\_blank} | Remix | Minimal deployment walkthrough | -| [Deploy an ERC‑20](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/){target=\_blank} | Remix, OpenZeppelin | Create, deploy, and mint a fungible token | -| [Deploy an NFT (ERC‑721)](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/){target=\_blank} | Remix, OpenZeppelin | Build and deploy an NFT collection | -| [Uniswap V2](/smart-contracts/cookbook/eth-dapps/uniswap-v2/){target=\_blank} | Hardhat | Full dApp project: compile, test, deploy | -| [Zero‑to‑Hero dApp](/smart-contracts/cookbook/dapps/zero-to-hero/){target=\_blank} | Multiple | End‑to‑end dApp patterns and practices | - -## Libraries - -Choose the client libraries that fit your stack for connecting wallets and calling contracts. - -| Library | Description | -|:------------------------------------------------------------------:|:-------------------------------------------------------:| -| [Ethers.js](/smart-contracts/libraries/ethers-js/){target=\_blank} | Connect, sign, and interact with contracts using Ethers | -| [viem](/smart-contracts/libraries/viem/){target=\_blank} | Type‑safe EVM interactions and utilities | -| [Wagmi](/smart-contracts/libraries/wagmi/){target=\_blank} | React hooks for wallet connections and contract calls | -| [Web3.js](/smart-contracts/libraries/web3-js/){target=\_blank} | Web3 provider and contract APIs | -| [Web3.py](/smart-contracts/libraries/web3-py/){target=\_blank} | Python toolkit for on‑chain interactions and scripts | - -## Integrations - -Integrate essential services like wallets, indexers, and oracles to round out your dApp. - -| Integration | Description | -|:-------------------------------------------------------------------:|:-----------------------------------------:| -| [Wallets](/smart-contracts/integrations/wallets/){target=\_blank} | Supported wallets and configuration notes | -| [Indexers](/smart-contracts/integrations/indexers/){target=\_blank} | Index and query blockchain data | -| [Oracles](/smart-contracts/integrations/oracles/){target=\_blank} | Bring external data on‑chain | - -## Precompiles - -Discover precompiled system contracts available on the Hub and how to use them. - -| Topic | Description | -|:------------------------------------------------------------------------:|:---------------------------------------------------:| -| [Overview of Precompiles](/smart-contracts/precompiles/){target=\_blank} | What precompiles are available on the Hub | -| [ETH Native](/smart-contracts/precompiles/eth-native/){target=\_blank} | EVM precompiles and interfaces | -| [Staking](/smart-contracts/precompiles/staking/){target=\_blank} | Interact with staking functionality via precompiles | -| [XCM](/smart-contracts/precompiles/xcm/){target=\_blank} | Cross‑chain messaging helpers for contracts | - -From here, follow the quick starts to get connected, iterate locally with your preferred tools, and use the guides, libraries, integrations, and precompiles as you grow into production‑ready dApps. If you get stuck, [open an issue](https://github.com/polkadot-developers/polkadot-docs/issues/new?template=docs-issue.yml){target=\_blank} or reach out in the community channels. - - ---- - -Page Title: Glossary - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-glossary.md -- Canonical (HTML): https://docs.polkadot.com/reference/glossary/ -- Summary: Glossary of terms used within the Polkadot ecosystem, Polkadot SDK, its subsequent libraries, and other relevant Web3 terminology. - -# Glossary - -Key definitions, concepts, and terminology specific to the Polkadot ecosystem are included here. - -Additional glossaries from around the ecosystem you might find helpful: - -- [Polkadot Wiki Glossary](https://wiki.polkadot.com/general/glossary){target=\_blank} -- [Polkadot SDK Glossary](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/glossary/index.html){target=\_blank} - -## Authority - -The role in a blockchain that can participate in consensus mechanisms. - -- **[GRANDPA](#grandpa)**: The authorities vote on chains they consider final. -- **[Blind Assignment of Blockchain Extension](#blind-assignment-of-blockchain-extension-babe) (BABE)**: The authorities are also [block authors](#block-author). - -Authority sets can be used as a basis for consensus mechanisms such as the [Nominated Proof of Stake (NPoS)](#nominated-proof-of-stake-npos) protocol. - -## Authority Round (Aura) - -A deterministic [consensus](#consensus) protocol where block production is limited to a rotating list of [authorities](#authority) that take turns creating blocks. In authority round (Aura) consensus, most online authorities are assumed to be honest. It is often used in combination with [GRANDPA](#grandpa) as a [hybrid consensus](#hybrid-consensus) protocol. - -Learn more by reading the official [Aura consensus algorithm](https://openethereum.github.io/Aura){target=\_blank} wiki article. - -## Blind Assignment of Blockchain Extension (BABE) - -A [block authoring](#block-author) protocol similar to [Aura](#authority-round-aura), except [authorities](#authority) win [slots](#slot) based on a Verifiable Random Function (VRF) instead of the round-robin selection method. The winning authority can select a chain and submit a new block. - -Learn more by reading the official Web3 Foundation [BABE research document](https://research.web3.foundation/Polkadot/protocols/block-production/Babe){target=\_blank}. - -## Block Author - -The node responsible for the creation of a block, also called _block producers_. In a Proof of Work (PoW) blockchain, these nodes are called _miners_. - -## Byzantine Fault Tolerance (BFT) - -The ability of a distributed computer network to remain operational if a certain proportion of its nodes or [authorities](#authority) are defective or behaving maliciously. A distributed network is typically considered Byzantine fault tolerant if it can remain functional, with up to one-third of nodes assumed to be defective, offline, actively malicious, and part of a coordinated attack. - -### Byzantine Failure - -The loss of a network service due to node failures that exceed the proportion of nodes required to reach consensus. - -### Practical Byzantine Fault Tolerance (pBFT) - -An early approach to Byzantine fault tolerance (BFT), practical Byzantine fault tolerance (pBFT) systems tolerate Byzantine behavior from up to one-third of participants. - -The communication overhead for such systems is `O(n²)`, where `n` is the number of nodes (participants) in the system. - -### Preimage - -A preimage is the data that is input into a hash function to calculate a hash. Since a hash function is a [one-way function](https://en.wikipedia.org/wiki/One-way_function){target=\_blank}, the output, the hash, cannot be used to reveal the input, the preimage. - -## Call - -In the context of pallets containing functions to be dispatched to the runtime, `Call` is an enumeration data type that describes the functions that can be dispatched with one variant per pallet. A `Call` represents a [dispatch](#dispatchable) data structure object. - -## Chain Specification - -A chain specification file defines the properties required to run a node in an active or new Polkadot SDK-built network. It often contains the initial genesis runtime code, network properties (such as the network's name), the initial state for some pallets, and the boot node list. The chain specification file makes it easy to use a single Polkadot SDK codebase as the foundation for multiple independently configured chains. - -## Collator - -An [author](#block-author) of a [parachain](#parachain) network. -They aren't [authorities](#authority) in themselves, as they require a [relay chain](#relay-chain) to coordinate [consensus](#consensus). - -More details are found on the [Polkadot Collator Wiki](https://wiki.polkadot.com/learn/learn-collator/){target=\_blank}. - -## Collective - -Most often used to refer to an instance of the Collective pallet on Polkadot SDK-based networks such as [Kusama](#kusama) or [Polkadot](#polkadot) if the Collective pallet is part of the FRAME-based runtime for the network. - -## Consensus - -Consensus is the process blockchain nodes use to agree on a chain's canonical fork. It is composed of [authorship](#block-author), finality, and [fork-choice rule](#fork-choice-rulestrategy). In the Polkadot ecosystem, these three components are usually separate and the term consensus often refers specifically to authorship. - -See also [hybrid consensus](#hybrid-consensus). - -## Consensus Algorithm - -Ensures a set of [actors](#authority)—who don't necessarily trust each other—can reach an agreement about the state as the result of some computation. Most consensus algorithms assume that up to one-third of the actors or nodes can be [Byzantine fault tolerant](#byzantine-fault-tolerance-bft). - -Consensus algorithms are generally concerned with ensuring two properties: - -- **Safety**: Indicating that all honest nodes eventually agreed on the state of the chain. -- **Liveness**: Indicating the ability of the chain to keep progressing. - -## Consensus Engine - -The node subsystem responsible for consensus tasks. - -For detailed information about the consensus strategies of the [Polkadot](#polkadot) network, see the [Polkadot Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} blog series. - -See also [hybrid consensus](#hybrid-consensus). - -## Coretime - -The time allocated for utilizing a core, measured in relay chain blocks. There are two types of coretime: *on-demand* and *bulk*. - -On-demand coretime refers to coretime acquired through bidding in near real-time for the validation of a single parachain block on one of the cores reserved specifically for on-demand orders. They are available as an on-demand coretime pool. Set of cores that are available on-demand. Cores reserved through bulk coretime could also be made available in the on-demand coretime pool, in parts or in entirety. - -Bulk coretime is a fixed duration of continuous coretime represented by an NFT that can be split, shared, or resold. It is managed by the [Broker pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_broker/index.html){target=\_blank}. - -## Development Phrase - -A [mnemonic phrase](https://en.wikipedia.org/wiki/Mnemonic#For_numerical_sequences_and_mathematical_operations){target=\_blank} that is intentionally made public. - -Well-known development accounts, such as Alice, Bob, Charlie, Dave, Eve, and Ferdie, are generated from the same secret phrase: - -``` -bottom drive obey lake curtain smoke basket hold race lonely fit walk -``` - -Many tools in the Polkadot SDK ecosystem, such as [`subkey`](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/bin/utils/subkey){target=\_blank}, allow you to implicitly specify an account using a derivation path such as `//Alice`. - -## Digest - -An extensible field of the [block header](#header) that encodes information needed by several actors in a blockchain network, including: - -- [Light clients](#light-client) for chain synchronization. -- Consensus engines for block verification. -- The runtime itself, in the case of pre-runtime digests. - -## Dispatchable - -Function objects that act as the entry points in FRAME [pallets](#pallet). Internal or external entities can call them to interact with the blockchain’s state. They are a core aspect of the runtime logic, handling [transactions](#transaction) and other state-changing operations. - -## Events - -A means of recording that some particular [state](#state) transition happened. - -In the context of [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities), events are composable data types that each [pallet](#pallet) can individually define. Events in FRAME are implemented as a set of transient storage items inspected immediately after a block has been executed and reset during block initialization. - -## Executor - -A means of executing a function call in a given [runtime](#runtime) with a set of dependencies. -There are two orchestration engines in Polkadot SDK, _WebAssembly_ and _native_. - -- The _native executor_ uses a natively compiled runtime embedded in the node to execute calls. This is a performance optimization available to up-to-date nodes. - -- The _WebAssembly executor_ uses a [Wasm](#webassembly-wasm) binary and a Wasm interpreter to execute calls. The binary is guaranteed to be up-to-date regardless of the version of the blockchain node because it is persisted in the [state](#state) of the Polkadot SDK-based chain. - -## Existential Deposit - -The minimum balance an account is allowed to have in the [Balances pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/index.html){target=\_blank}. Accounts cannot be created with a balance less than the existential deposit amount. - -If an account balance drops below this amount, the Balances pallet uses [a FRAME System API](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.dec_ref){target=\_blank} to drop its references to that account. - -If the Balances pallet reference to an account is dropped, the account can be [reaped](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.allow_death){target=\_blank}. - -## Extrinsic - -A general term for data that originates outside the runtime, is included in a block, and leads to some action. This includes user-initiated transactions and inherent transactions placed into the block by the block builder. - -It is a SCALE-encoded array typically consisting of a version number, signature, and varying data types indicating the resulting runtime function to be called. Extrinsics can take two forms: [inherents](#inherent-transactions) and [transactions](#transaction). - -For more technical details, see the [Polkadot spec](https://spec.polkadot.network/id-extrinsics){target=\_blank}. - -## Fork Choice Rule/Strategy - -A fork choice rule or strategy helps determine which chain is valid when reconciling several network forks. A common fork choice rule is the [longest chain](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/struct.LongestChain.html){target=\_blank}, in which the chain with the most blocks is selected. - -## FRAME (Framework for Runtime Aggregation of Modularized Entities) - -Enables developers to create blockchain [runtime](#runtime) environments from a modular set of components called [pallets](#pallet). It utilizes a set of procedural macros to construct runtimes. - -[Visit the Polkadot SDK docs for more details on FRAME.](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank} - -## Full Node - -A node that prunes historical states, keeping only recently finalized block states to reduce storage needs. Full nodes provide current chain state access and allow direct submission and validation of [extrinsics](#extrinsic), maintaining network decentralization. - -## Genesis Configuration - -A mechanism for specifying the initial state of a blockchain. By convention, this initial state or first block is commonly referred to as the genesis state or genesis block. The genesis configuration for Polkadot SDK-based chains is accomplished by way of a [chain specification](#chain-specification) file. - -## GRANDPA - -A deterministic finality mechanism for blockchains that is implemented in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. - -The [formal specification](https://github.com/w3f/consensus/blob/master/pdf/grandpa-old.pdf){target=\_blank} is maintained by the [Web3 Foundation](https://web3.foundation/){target=\_blank}. - -## Header - -A structure that aggregates the information used to summarize a block. Primarily, it consists of cryptographic information used by [light clients](#light-client) to get minimally secure but very efficient chain synchronization. - -## Hybrid Consensus - -A blockchain consensus protocol that consists of independent or loosely coupled mechanisms for [block production](#block-author) and finality. - -Hybrid consensus allows the chain to grow as fast as probabilistic consensus protocols, such as [Aura](#authority-round-aura), while maintaining the same level of security as deterministic finality consensus protocols, such as [GRANDPA](#grandpa). - -## Inherent Transactions - -A special type of unsigned transaction, referred to as _inherents_, that enables a block authoring node to insert information that doesn't require validation directly into a block. - -Only the block-authoring node that calls the inherent transaction function can insert data into its block. In general, validators assume the data inserted using an inherent transaction is valid and reasonable even if it can't be deterministically verified. - -## JSON-RPC - -A stateless, lightweight remote procedure call protocol encoded in JavaScript Object Notation (JSON). JSON-RPC provides a standard way to call functions on a remote system by using JSON. - -For Polkadot SDK, this protocol is implemented through the [Parity JSON-RPC](https://github.com/paritytech/jsonrpc){target=\_blank} crate. - -## Keystore - -A subsystem for managing keys for the purpose of producing new blocks. - -## Kusama - -[Kusama](https://kusama.network/){target=\_blank} is a Polkadot SDK-based blockchain that implements a design similar to the [Polkadot](#polkadot) network. - -Kusama is a [canary](https://en.wiktionary.org/wiki/canary_in_a_coal_mine){target=\_blank} network and is referred to as [Polkadot's "wild cousin."](https://wiki.polkadot.com/learn/learn-comparisons-kusama/){target=\_blank}. - -As a canary network, Kusama is expected to be more stable than a test network like [Westend](#westend) but less stable than a production network like [Polkadot](#polkadot). Kusama is controlled by its network participants and is intended to be stable enough to encourage meaningful experimentation. - -## libp2p - -A peer-to-peer networking stack that allows the use of many transport mechanisms, including WebSockets (usable in a web browser). - -Polkadot SDK uses the [Rust implementation](https://github.com/libp2p/rust-libp2p){target=\_blank} of the `libp2p` networking stack. - -## Light Client - -A type of blockchain node that doesn't store the [chain state](#state) or produce blocks. - -A light client can verify cryptographic primitives and provides a [remote procedure call (RPC)](https://en.wikipedia.org/wiki/Remote_procedure_call){target=\_blank} server, enabling blockchain users to interact with the network. - -## Metadata - -Data that provides information about one or more aspects of a system. -The metadata that exposes information about a Polkadot SDK blockchain enables you to interact with that system. - -## Nominated Proof of Stake (NPoS) - -A method for determining [validators](#validator) or _[authorities](#authority)_ based on a willingness to commit their stake to the proper functioning of one or more block-producing nodes. - -## Oracle - -An entity that connects a blockchain to a non-blockchain data source. Oracles enable the blockchain to access and act upon information from existing data sources and incorporate data from non-blockchain systems and services. - -## Origin - -A [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitive that identifies the source of a [dispatched](#dispatchable) function call into the [runtime](#runtime). The FRAME System pallet defines three built-in [origins](#origin). As a [pallet](#pallet) developer, you can also define custom origins, such as those defined by the [Collective pallet](https://paritytech.github.io/substrate/master/pallet_collective/enum.RawOrigin.html){target=\_blank}. - -## Pallet - -A module that can be used to extend the capabilities of a [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities)-based [runtime](#runtime). -Pallets bundle domain-specific logic with runtime primitives like [events](#events) and [storage items](#storage-item). - -## Parachain - -A parachain is a blockchain that derives shared infrastructure and security from a _[relay chain](#relay-chain)_. -You can learn more about parachains on the [Polkadot Wiki](https://wiki.polkadot.com/learn/learn-parachains/){target=\_blank}. - -## Paseo - -Paseo TestNet provisions testing on Polkadot's "production" runtime, which means less chance of feature or code mismatch when developing parachain apps. Specifically, after the [Polkadot Technical fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} proposes a runtime upgrade for Polkadot, this TestNet is updated, giving a period where the TestNet will be ahead of Polkadot to allow for testing. - -## Polkadot - -The [Polkadot network](https://polkadot.com/){target=\_blank} is a blockchain that serves as the central hub of a heterogeneous blockchain network. It serves the role of the [relay chain](#relay-chain) and provides shared infrastructure and security to support [parachains](#parachain). - -## Polkadot Cloud - -Polkadot Cloud is a platform for deploying resilient, customizable and scalable Web3 applications through Polkadot's functionality. It encompasses the wider Polkadot network infrastructure and security layer where parachains operate. The platform enables users to launch Ethereum-compatible chains, build specialized blockchains, and flexibly manage computing resources through on-demand or bulk coretime purchases. Initially launched with basic parachain functionality, Polkadot Cloud has evolved to offer enhanced flexibility with features like coretime, elastic scaling, and async backing for improved performance. - -## Polkadot Hub - -Polkadot Hub is a Layer 1 platform that serves as the primary entry point to the Polkadot ecosystem, providing essential functionality without requiring parachain deployment. It offers core services including smart contracts, identity management, staking, governance, and interoperability with other ecosystems, making it simple and fast for both builders and users to get started in Web3. - -## PolkaVM - -PolkaVM is a custom virtual machine optimized for performance, leveraging a RISC-V-based architecture to support Solidity and any language that compiles to RISC-V. It is specifically designed for the Polkadot ecosystem, enabling smart contract deployment and execution. - -## Relay Chain - -Relay chains are blockchains that provide shared infrastructure and security to the [parachains](#parachain) in the network. In addition to providing [consensus](#consensus) capabilities, relay chains allow parachains to communicate and exchange digital assets without needing to trust one another. - -## Rococo - -A [parachain](#parachain) test network for the Polkadot network. The [Rococo](#rococo) network is a Polkadot SDK-based blockchain with an October 14, 2024 deprecation date. Development teams are encouraged to use the Paseo TestNet instead. - -## Runtime - -The runtime represents the [state transition function](#state-transition-function-stf) for a blockchain. In Polkadot SDK, the runtime is stored as a [Wasm](#webassembly-wasm) binary in the chain state. The Runtime is stored under a unique state key and can be modified during the execution of the state transition function. - -## Slot - -A fixed, equal interval of time used by consensus engines such as [Aura](#authority-round-aura) and [BABE](#blind-assignment-of-blockchain-extension-babe). In each slot, a subset of [authorities](#authority) is permitted, or obliged, to [author](#block-author) a block. - -## Sovereign Account - -The unique account identifier for each chain in the relay chain ecosystem. It is often used in cross-consensus (XCM) interactions to sign XCM messages sent to the relay chain or other chains in the ecosystem. - -The sovereign account for each chain is a root-level account that can only be accessed using the Sudo pallet or through governance. The account identifier is calculated by concatenating the Blake2 hash of a specific text string and the registered parachain identifier. - -## SS58 Address Format - -A public key address based on the Bitcoin [`Base-58-check`](https://en.bitcoin.it/wiki/Base58Check_encoding){target=\_blank} encoding. Each Polkadot SDK SS58 address uses a `base-58` encoded value to identify a specific account on a specific Polkadot SDK-based chain - -The [canonical `ss58-registry`](https://github.com/paritytech/ss58-registry){target=\_blank} provides additional details about the address format used by different Polkadot SDK-based chains, including the network prefix and website used for different networks - -## State Transition Function (STF) - -The logic of a blockchain that determines how the state changes when a block is processed. In Polkadot SDK, the state transition function is effectively equivalent to the [runtime](#runtime). - -## Storage Item - -[FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitives that provide type-safe data persistence capabilities to the [runtime](#runtime). -Learn more in the [storage items](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/index.html){target=\_blank} reference document in the Polkadot SDK. - -## Substrate - -A flexible framework for building modular, efficient, and upgradeable blockchains. Substrate is written in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language and is maintained by [Parity Technologies](https://www.parity.io/){target=\_blank}. - -## Transaction - -An [extrinsic](#extrinsic) that includes a signature that can be used to verify the account authorizing it inherently or via [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}. - -## Transaction Era - -A definable period expressed as a range of block numbers during which a transaction can be included in a block. -Transaction eras are used to protect against transaction replay attacks if an account is reaped and its replay-protecting nonce is reset to zero. - -## Trie (Patricia Merkle Tree) - -A data structure used to represent sets of key-value pairs and enables the items in the data set to be stored and retrieved using a cryptographic hash. Because incremental changes to the data set result in a new hash, retrieving data is efficient even if the data set is very large. With this data structure, you can also prove whether the data set includes any particular key-value pair without access to the entire data set. - -In Polkadot SDK-based blockchains, state is stored in a trie data structure that supports the efficient creation of incremental digests. This trie is exposed to the [runtime](#runtime) as [a simple key/value map](#storage-item) where both keys and values can be arbitrary byte arrays. - -## Validator - -A validator is a node that participates in the consensus mechanism of the network. Its roles include block production, transaction validation, network integrity, and security maintenance. - -## WebAssembly (Wasm) +- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\_blank} of the XCM instructions. -An execution architecture that allows for the efficient, platform-neutral expression of -deterministic, machine-executable logic. + ```rust + BuyExecution { + fees: (Here, amount).into(), + weight_limit: WeightLimit::Unlimited + }, + ``` -[Wasm](https://webassembly.org/){target=\_blank} can be compiled from many languages, including -the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. Polkadot SDK-based chains use a Wasm binary to provide portable [runtimes](#runtime) that can be included as part of the chain's state. + - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight. + - **`weight_limit`**: Defines the maximum fees that can be used to buy weight. -## Weight +- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\_blank}**: Moves the remaining tokens from the holding register to Bob’s account. -A convention used in Polkadot SDK-based blockchains to measure and manage the time it takes to validate a block. -Polkadot SDK defines one unit of weight as one picosecond of execution time on reference hardware. + ```rust + DepositAsset { + assets: All.into(), + beneficiary: MultiLocation { + parents: 0, + interior: Junction::AccountId32 { + network: None, + id: BOB.clone().into() + }.into(), + }.into() + } + ``` -The maximum block weight should be equivalent to one-third of the target block time with an allocation of one-third each for: + - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited. + +This step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. -- Block construction -- Network propagation -- Import and verification +## Overview -By defining weights, you can trade-off the number of transactions per second and the hardware required to maintain the target block time appropriate for your use case. Weights are defined in the runtime, meaning you can tune them using runtime updates to keep up with hardware and software improvements. +XCM revolutionizes cross-chain communication by enabling use cases such as: -## Westend +- Token transfers between blockchains. +- Asset locking for cross-chain smart contract interactions. +- Remote execution of functions on other blockchains. -Westend is a Parity-maintained, Polkadot SDK-based blockchain that serves as a test network for the [Polkadot](#polkadot) network. +These functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. --- @@ -7020,249 +4770,51 @@ The Polkadot SDK includes a feature-rich node called "kitchensink" located at `s From the `polkadot-sdk` root directory, start the kitchensink node in development mode: -```bash -./target/release/substrate-node --dev -``` - -The `--dev` flag enables development mode, which: - -- Runs a single-node development chain. -- Produces and finalizes blocks automatically. -- Uses pre-configured development accounts (Alice, Bob, etc.). -- Deletes all data when stopped, ensuring a clean state on restart. - - -You should see log output indicating the node is running and producing blocks, with increasing block numbers after `finalized`. - -### Interact with the Kitchensink Node - -The kitchensink node is accessible at `ws://localhost:9944`. Open [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} in your browser to explore its features and connect to the local node. - -1. Click the network icon in the top left corner. -2. Scroll to **Development** and select **Local Node**. -3. Click **Switch** to connect to your local node. - -![](/images/parachains/install-polkadot-sdk/install-polkadot-sdk-1.webp) - -Once connected, the interface updates its color scheme to indicate a successful connection to the local node. - -![](/images/parachains/install-polkadot-sdk/install-polkadot-sdk-2.webp) - -You can now explore the various pallets and features included in the kitchensink node, making it a valuable reference as you develop your own blockchain applications. - -To stop the node, press `Control-C` in the terminal. - -## Where to Go Next - -
- -- __Get Started with Parachain Development__ - - --- - - Practical examples and tutorials for building and deploying Polkadot parachains, covering everything from launch to customization and cross-chain messaging. - - [:octicons-arrow-right-24: Get Started](/parachains/get-started/) - -
- - ---- - -Page Title: Interoperability - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-interoperability.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/interoperability/ -- Summary: Explore the importance of interoperability in the Polkadot ecosystem, covering XCM, bridges, and cross-chain communication. - -# Interoperability - -## Introduction - -Interoperability lies at the heart of the Polkadot ecosystem, enabling communication and collaboration across a diverse range of blockchains. By bridging the gaps between parachains, relay chains, and even external networks, Polkadot unlocks the potential for truly decentralized applications, efficient resource sharing, and scalable solutions. - -Polkadot’s design ensures that blockchains can transcend their individual limitations by working together as part of a unified system. This cooperative architecture is what sets Polkadot apart in the blockchain landscape. - -## Why Interoperability Matters - -The blockchain ecosystem is inherently fragmented. Different blockchains excel in specialized domains such as finance, gaming, or supply chain management, but these chains function in isolation without interoperability. This lack of connectivity stifles the broader utility of blockchain technology. - -Interoperability solves this problem by enabling blockchains to: - -- **Collaborate across networks**: Chains can interact to share assets, functionality, and data, creating synergies that amplify their individual strengths. -- **Achieve greater scalability**: Specialized chains can offload tasks to others, optimizing performance and resource utilization. -- **Expand use-case potential**: Cross-chain applications can leverage features from multiple blockchains, unlocking novel user experiences and solutions. - -In the Polkadot ecosystem, interoperability transforms a collection of isolated chains into a cohesive, efficient network, pushing the boundaries of what blockchains can achieve together. - -## Key Mechanisms for Interoperability - -At the core of Polkadot's cross-chain collaboration are foundational technologies designed to break down barriers between networks. These mechanisms empower blockchains to communicate, share resources, and operate as a cohesive ecosystem. - -### Cross-Consensus Messaging (XCM): The Backbone of Communication - -Polkadot's Cross-Consensus Messaging (XCM) is the standard framework for interaction between parachains, relay chains, and, eventually, external blockchains. XCM provides a trustless, secure messaging format for exchanging assets, sharing data, and executing cross-chain operations. - -Through XCM, decentralized applications can: - -- Transfer tokens and other assets across chains. -- Coordinate complex workflows that span multiple blockchains. -- Enable seamless user experiences where underlying blockchain differences are invisible. -- XCM exemplifies Polkadot’s commitment to creating a robust and interoperable ecosystem. - -For further information about XCM, check the [Introduction to XCM](/parachains/interoperability/get-started/){target=\_blank} article. - -### Bridges: Connecting External Networks - -While XCM enables interoperability within the Polkadot ecosystem, bridges extend this functionality to external blockchains such as Ethereum and Bitcoin. By connecting these networks, bridges allow Polkadot-based chains to access external liquidity, additional functionalities, and broader user bases. - -With bridges, developers and users gain the ability to: - -- Integrate external assets into Polkadot-based applications. -- Combine the strengths of Polkadot’s scalability with the liquidity of other networks. -- Facilitate accurate multi-chain applications that transcend ecosystem boundaries. - -For more information about bridges in the Polkadot ecosystem, see the [Bridge Hub](/reference/polkadot-hub/bridging/){target=\_blank} guide. - -## The Polkadot Advantage - -Polkadot was purpose-built for interoperability. Unlike networks that add interoperability as an afterthought, Polkadot integrates it as a fundamental design principle. This approach offers several distinct advantages: - -- **Developer empowerment**: Polkadot’s interoperability tools allow developers to build applications that leverage multiple chains’ capabilities without added complexity. -- **Enhanced ecosystem collaboration**: Chains in Polkadot can focus on their unique strengths while contributing to the ecosystem’s overall growth. -- **Future-proofing blockchain**: By enabling seamless communication, Polkadot ensures its ecosystem can adapt to evolving demands and technologies. - -## Looking Ahead - -Polkadot’s vision of interoperability extends beyond technical functionality, representing a shift towards a more collaborative blockchain landscape. By enabling chains to work together, Polkadot fosters innovation, efficiency, and accessibility, paving the way for a decentralized future where blockchains are not isolated competitors but interconnected collaborators. - - ---- - -Page Title: Introduction to XCM - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md -- Canonical (HTML): https://docs.polkadot.com/parachains/interoperability/get-started/ -- Summary: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. - -# Introduction to XCM - -## Introduction - -Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems. - -With XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation. - -## Messaging Format - -XCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics. - -XCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing. - -## The Four Principles of XCM - -XCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems: - -- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes. -- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended. -- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin. -- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems. - -These principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments. - -## The XCM Tech Stack - -![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp) - -The XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels. - -## Core Functionalities of XCM - -XCM enhances cross-consensus communication by introducing several powerful features: - -- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management. -- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification. -- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location. - -The standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications. +```bash +./target/release/substrate-node --dev +``` -## XCM Example +The `--dev` flag enables development mode, which: -The following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA). +- Runs a single-node development chain. +- Produces and finalizes blocks automatically. +- Uses pre-configured development accounts (Alice, Bob, etc.). +- Deletes all data when stopped, ensuring a clean state on restart. -```rust -let message = Xcm(vec![ - WithdrawAsset((Here, amount).into()), - BuyExecution { - fees: (Here, amount).into(), - weight_limit: WeightLimit::Unlimited - }, - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: Junction::AccountId32 { - network: None, - id: BOB.clone().into() - }.into(), - }.into() - } -]); -``` -The message consists of three instructions described as follows: +You should see log output indicating the node is running and producing blocks, with increasing block numbers after `finalized`. -- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register. +### Interact with the Kitchensink Node - ```rust - WithdrawAsset((Here, amount).into()), - ``` +The kitchensink node is accessible at `ws://localhost:9944`. Open [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} in your browser to explore its features and connect to the local node. - - **`Here`**: The native parachain token. - - **`amount`**: The number of tokens that are transferred. +1. Click the network icon in the top left corner. +2. Scroll to **Development** and select **Local Node**. +3. Click **Switch** to connect to your local node. - The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register. +![](/images/parachains/install-polkadot-sdk/install-polkadot-sdk-1.webp) -- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\_blank} of the XCM instructions. +Once connected, the interface updates its color scheme to indicate a successful connection to the local node. - ```rust - BuyExecution { - fees: (Here, amount).into(), - weight_limit: WeightLimit::Unlimited - }, - ``` +![](/images/parachains/install-polkadot-sdk/install-polkadot-sdk-2.webp) - - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight. - - **`weight_limit`**: Defines the maximum fees that can be used to buy weight. +You can now explore the various pallets and features included in the kitchensink node, making it a valuable reference as you develop your own blockchain applications. -- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\_blank}**: Moves the remaining tokens from the holding register to Bob’s account. +To stop the node, press `Control-C` in the terminal. - ```rust - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: Junction::AccountId32 { - network: None, - id: BOB.clone().into() - }.into(), - }.into() - } - ``` +## Where to Go Next - - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited. - -This step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. +
-## Overview +- __Get Started with Parachain Development__ -XCM revolutionizes cross-chain communication by enabling use cases such as: + --- -- Token transfers between blockchains. -- Asset locking for cross-chain smart contract interactions. -- Remote execution of functions on other blockchains. + Practical examples and tutorials for building and deploying Polkadot parachains, covering everything from launch to customization and cross-chain messaging. -These functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. + [:octicons-arrow-right-24: Get Started](/parachains/get-started/) + +
--- @@ -8136,92 +5688,6 @@ If an error occurs, the response will include an error object: ``` ---- - -Page Title: Light Clients - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-light-clients.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/light-clients/ -- Summary: Light clients enable secure and efficient blockchain interaction without running a full node. Learn everything you need to know about light clients on Polkadot. - -# Light Clients - -## Introduction - -Light clients enable secure and efficient blockchain interaction without running a full node. They provide a trust-minimized alternative to JSON-RPC by verifying data through cryptographic proofs rather than blindly trusting remote nodes. - -This guide covers: - -- What light clients are and how they work. -- Their advantages compared to full nodes and JSON-RPC. -- Available implementations in the Polkadot ecosystem. -- How to use light clients in your applications. - -Light clients are particularly valuable for resource-constrained environments and applications requiring secure, decentralized blockchain access without the overhead of maintaining full nodes. - -!!!note "Light node or light client?" - The terms _light node_ and _light client_ are interchangeable. Both refer to a blockchain client that syncs without downloading the entire blockchain state. All nodes in a blockchain network are fundamentally clients, engaging in peer-to-peer communication. - -## Light Clients Workflow - -Unlike JSON-RPC interfaces, where an application must maintain a list of providers or rely on a single node, light clients are not limited to or dependent on a single node. They use cryptographic proofs to verify the blockchain's state, ensuring it is up-to-date and accurate. By verifying only block headers, light clients avoid syncing the entire state, making them ideal for resource-constrained environments. - -```mermaid -flowchart LR -DAPP([dApp])-- Query Account Info -->LC([Light Client]) -LC -- Request --> FN(((Full Node))) -LC -- Response --> DAPP -FN -- Response (validated via Merkle proof) --> LC -``` - -In the diagram above, the decentralized application queries on-chain account information through the light client. The light client runs as part of the application and requires minimal memory and computational resources. It uses Merkle proofs to verify the state retrieved from a full node in a trust-minimized manner. Polkadot-compatible light clients utilize [warp syncing](https://spec.polkadot.network/sect-lightclient#sect-sync-warp-lightclient){target=\_blank}, which downloads only block headers. - -Light clients can quickly verify the blockchain's state, including [GRANDPA finality](/polkadot-protocol/glossary#grandpa){target=\_blank} justifications. - -!!!note "What does it mean to be trust-minimized?" - _Trust-minimized_ means that the light client does not need to fully trust the full node from which it retrieves the state. This is achieved through the use of Merkle proofs, which allow the light client to verify the correctness of the state by checking the Merkle tree root. - -## JSON-RPC and Light Client Comparison - -Another common method of communication between a user interface (UI) and a node is through the JSON-RPC protocol. Generally, the UI retrieves information from the node, fetches network or [pallet](/polkadot-protocol/glossary#pallet){target=\_blank} data, and interacts with the blockchain. This is typically done in one of two ways: - -- **User-controlled nodes**: The UI connects to a node client installed on the user's machine. - - These nodes are secure, but installation and maintenance can be inconvenient. -- **Publicly accessible nodes**: The UI connects to a third-party-owned publicly accessible node client. - - These nodes are convenient but centralized and less secure. Applications must maintain a list of backup nodes in case the primary node becomes unavailable. - -While light clients still communicate with [full nodes](/polkadot-protocol/glossary#full-node), they offer significant advantages for applications requiring a secure alternative to running a full node: - -| Full Node | Light Client | -| :---------------------------------------------------------------------------------------------: | :------------------------------------------------------------: | -| Fully verifies all blocks of the chain | Verifies only the authenticity of blocks | -| Stores previous block data and the chain's storage in a database | Does not require a database | -| Installation, maintenance, and execution are resource-intensive and require technical expertise | No installation is typically included as part of the application | - -## Using Light Clients - -The [`smoldot`](https://github.com/smol-dot/smoldot){target=\_blank} client is the cornerstone of light client implementation for Polkadot SDK-based chains. It provides the primitives needed to build light clients and is also integrated into libraries such as [PAPI](#papi-light-client-support). - -### PAPI Light Client Support - -The [Polkadot API (PAPI)](/develop/toolkit/api-libraries/papi){target=\_blank} library natively supports light client configurations powered by [`smoldot`](https://github.com/smol-dot/smoldot){target=\_blank}. This allows developers to connect to multiple chains simultaneously using a light client. - -### Substrate Connect - Browser Extension - -The [Substrate Connect browser extension](https://www.npmjs.com/package/@substrate/connect-extension-protocol){target=\_blank} enables end-users to interact with applications connected to multiple blockchains or to connect their own blockchains to supported applications. - -Establishing a sufficient number of peers can be challenging due to browser limitations on WebSocket connections from HTTPS pages, as many nodes require TLS. The Substrate Connect browser extension addresses this limitation by keeping chains synced in the background, enabling faster application performance. - -Substrate Connect automatically detects whether the user has the extension installed. If not, an in-page Wasm light client is created for them. - -## Resources - -- [What is a light client and why you should care?](https://medium.com/paritytech/what-is-a-light-client-and-why-you-should-care-75f813ae2670){target=\_blank} -- [Introducing Substrate Connect: Browser-Based Light Clients for Connecting to Substrate Chains](https://www.parity.io/blog/introducing-substrate-connect){target=\_blank} -- [Substrate Connect GitHub Repository](https://github.com/paritytech/substrate-connect/tree/master/projects/extension){target=\_blank} -- [Light Clients - Polkadot Specification](https://spec.polkadot.network/sect-lightclient){target=\_blank} - - --- Page Title: Mock Your Runtime @@ -8563,204 +6029,6 @@ The mock runtime with a genesis configuration is essential for test-driven devel ---- - -Page Title: Networks - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-networks.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/networks/ -- Summary: Explore Polkadot's testing and production networks, including Westend, Kusama, and Paseo, for efficient development, deployment, and testing. - -# Networks - -## Introduction - -The Polkadot ecosystem is built on a robust set of networks designed to enable secure and scalable development. Whether you are testing new features or deploying to live production, Polkadot offers several layers of networks tailored for each stage of the development process. From local environments to experimental networks like Kusama and community-run TestNets such as Paseo, developers can thoroughly test, iterate, and validate their applications. This guide will introduce you to Polkadot's various networks and explain how they fit into the development workflow. - -## Network Overview - -Polkadot's development process is structured to ensure new features and upgrades are rigorously tested before being deployed on live production networks. The progression follows a well-defined path, starting from local environments and advancing through TestNets, ultimately reaching the Polkadot MainNet. The diagram below outlines the typical progression of the Polkadot development cycle: - -``` mermaid -flowchart LR - id1[Local] --> id2[Westend] --> id4[Kusama] --> id5[Polkadot] - id1[Local] --> id3[Paseo] --> id5[Polkadot] -``` - -This flow ensures developers can thoroughly test and iterate without risking real tokens or affecting production networks. Testing tools like [Chopsticks](#chopsticks) and various TestNets make it easier to experiment safely before releasing to production. - -A typical journey through the Polkadot core protocol development process might look like this: - -1. **Local development node**: Development starts in a local environment, where developers can create, test, and iterate on upgrades or new features using a local development node. This stage allows rapid experimentation in an isolated setup without any external dependencies. - -2. **Westend**: After testing locally, upgrades are deployed to [Westend](#westend), Polkadot's primary TestNet. Westend simulates real-world conditions without using real tokens, making it the ideal place for rigorous feature testing before moving on to production networks. - -3. **Kusama**: Once features have passed extensive testing on Westend, they move to Kusama, Polkadot's experimental and fast-moving "canary" network. Kusama operates as a high-fidelity testing ground with actual economic incentives, giving developers insights into how their features will perform in a real-world environment. - -4. **Polkadot**: After passing tests on Westend and Kusama, features are considered ready for deployment to Polkadot, the live production network. - - In addition, parachain developers can leverage local TestNets like [Zombienet](#zombienet) and deploy upgrades on parachain TestNets. - -5. **Paseo**: For parachain and dApp developers, Paseo serves as a community-run TestNet that mirrors Polkadot's runtime. Like Westend for core protocol development, Paseo provides a testing ground for parachain development without affecting live networks. - -!!!note - The Rococo TestNet deprecation date was October 14, 2024. Teams should use Westend for Polkadot protocol and feature testing and Paseo for chain development-related testing. - -## Polkadot Development Networks - -Development and testing are crucial to building robust dApps and parachains and performing network upgrades within the Polkadot ecosystem. To achieve this, developers can leverage various networks and tools that provide a risk-free environment for experimentation and validation before deploying features to live networks. These networks help avoid the costs and risks associated with real tokens, enabling testing for functionalities like governance, cross-chain messaging, and runtime upgrades. - -## Kusama Network - -Kusama is the experimental version of Polkadot, designed for developers who want to move quickly and test their applications in a real-world environment with economic incentives. Kusama serves as a production-grade testing ground where developers can deploy features and upgrades with the pressure of game theory and economics in mind. It mirrors Polkadot but operates as a more flexible space for innovation. - -The native token for Kusama is KSM. For more information about KSM, visit the [Native Assets](https://wiki.polkadot.com/kusama/kusama-getting-started/){target=\_blank} page. - -## Test Networks - -The following test networks provide controlled environments for testing upgrades and new features. TestNet tokens are available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}. - -### Westend - -Westend is Polkadot's primary permanent TestNet. Unlike temporary test networks, Westend is not reset to the genesis block, making it an ongoing environment for testing Polkadot core features. Managed by Parity Technologies, Westend ensures that developers can test features in a real-world simulation without using actual tokens. - -The native token for Westend is WND. More details about WND can be found on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_2){target=\_blank} page. - -### Paseo - -[Paseo](https://github.com/paseo-network){target=\_blank} is a community-managed TestNet designed for parachain and dApp developers. It mirrors Polkadot's runtime and is maintained by Polkadot community members. Paseo provides a dedicated space for parachain developers to test their applications in a Polkadot-like environment without the risks associated with live networks. - -The native token for Paseo is PAS. Additional information on PAS is available on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_1){target=\_blank} page. - -## Local Test Networks - -Local test networks are an essential part of the development cycle for blockchain developers using the Polkadot SDK. They allow for fast, iterative testing in controlled, private environments without connecting to public TestNets. Developers can quickly spin up local instances to experiment, debug, and validate their code before deploying to larger TestNets like Westend or Paseo. Two key tools for local network testing are Zombienet and Chopsticks. - -### Zombienet - -[Zombienet](https://github.com/paritytech/zombienet){target=\_blank} is a flexible testing framework for Polkadot SDK-based blockchains. It enables developers to create and manage ephemeral, short-lived networks. This feature makes Zombienet particularly useful for quick iterations, as it allows you to run multiple local networks concurrently, mimicking different runtime conditions. Whether you're developing a parachain or testing your custom blockchain logic, Zombienet gives you the tools to automate local testing. - -Key features of Zombienet include: - -- Creating dynamic, local networks with different configurations. -- Running parachains and relay chains in a simulated environment. -- Efficient testing of network components like cross-chain messaging and governance. - -Zombienet is ideal for developers looking to test quickly and thoroughly before moving to more resource-intensive public TestNets. - -### Chopsticks - -[Chopsticks](https://github.com/AcalaNetwork/chopsticks){target=\_blank} is a tool designed to create forks of Polkadot SDK-based blockchains, allowing developers to interact with network forks as part of their testing process. This capability makes Chopsticks a powerful option for testing upgrades, runtime changes, or cross-chain applications in a forked network environment. - -Key features of Chopsticks include: - -- Forking live Polkadot SDK-based blockchains for isolated testing. -- Simulating cross-chain messages in a private, controlled setup. -- Debugging network behavior by interacting with the fork in real-time. - -Chopsticks provides a controlled environment for developers to safely explore the effects of runtime changes. It ensures that network behavior is tested and verified before upgrades are deployed to live networks. - - ---- - -Page Title: Node and Runtime - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-node-and-runtime.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/node-and-runtime/ -- Summary: Learn how Polkadot SDK-based nodes function, how the client and runtime are separated, and how they communicate using SCALE-encoded data. - -# Node and Runtime - -## Introduction - -Every blockchain platform relies on a decentralized network of computers, called nodes, that communicate with each other about transactions and blocks. In this context, a node refers to the software running on the connected devices rather than the physical or virtual machines in the network. - -Polkadot SDK-based nodes consist of two main components, each with distinct responsibilities: the client (also called node) and the runtime. - -If the system were a monolithic protocol, any modification would require updating the entire system. Instead, Polkadot achieves true upgradeability by defining an immutable meta-protocol (the client) and a protocol (the runtime) that can be upgraded independently. - -This separation gives the [Polkadot Relay Chain](/polkadot-protocol/architecture/polkadot-chain){target=\_blank} and all connected [parachains](/polkadot-protocol/architecture/parachains){target=\_blank} an evolutionary advantage over other blockchain platforms. - -## Architectural Principles - -The Polkadot SDK-based blockchain architecture is fundamentally built on two distinct yet interconnected components: - -- Client (Meta-protocol): - - Handles the foundational infrastructure of the blockchain. - - Manages runtime execution, networking, consensus, and other off-chain components. - - Provides an immutable base layer that ensures network stability. - - Upgradable only through hard forks. - -- Runtime (Protocol): - - Defines the blockchain's state transition logic. - - Determines the specific rules and behaviors of the blockchain. - - Compiled to WebAssembly (Wasm) for platform-independent execution. - - Capable of being upgraded without network-wide forking. - -### Advantages of this Architecture - -- **Forkless upgrades**: Runtime can be updated without disrupting the entire network. -- **Modularity**: Clear separation allows independent development of client and runtime. -- **Flexibility**: Enables rapid iteration and evolution of blockchain logic. -- **Performance**: WebAssembly compilation provides efficient, cross-platform execution. - -## Node (Client) - -The node, also known as the client, is the core component responsible for executing the Wasm runtime and orchestrating various essential blockchain components. It ensures the correct execution of the state transition function and manages multiple critical subsystems, including: - -- **Wasm execution**: Runs the blockchain runtime, which defines the state transition rules. -- **Database management**: Stores blockchain data. -- **Networking**: Facilitates peer-to-peer communication, block propagation, and transaction gossiping. -- **Transaction pool (Mempool)**: Manages pending transactions before they are included in a block. -- **Consensus mechanism**: Ensures agreement on the blockchain state across nodes. -- **RPC services**: Provides external interfaces for applications and users to interact with the node. - -## Runtime - -The runtime is more than just a set of rules. It's the fundamental logic engine that defines a blockchain's entire behavior. In Polkadot SDK-based blockchains, the runtime represents a complete, self-contained description of the blockchain's state transition function. - -### Characteristics - -The runtime is distinguished by three key characteristics: - -- **Business logic**: Defines the complete application-specific blockchain behavior. -- **WebAssembly compilation**: Ensures platform-independent, secure execution. -- **On-chain storage**: Stored within the blockchain's state, allowing dynamic updates. - -### Key Functions - -The runtime performs several critical functions, such as: - -- Define state transition rules. -- Implement blockchain-specific logic. -- Manage account interactions. -- Control transaction processing. -- Define governance mechanisms. -- Handle custom pallets and modules. - -## Communication Between Node and Runtime - -The client and runtime communicate exclusively using [SCALE-encoded](/polkadot-protocol/parachain-basics/data-encoding){target=\_blank} communication. This ensures efficient and compact data exchange between the two components. - -### Runtime APIs - -The Runtime API consists of well-defined functions and constants a client assumes are implemented in the Runtime Wasm blob. These APIs enable the client to interact with the runtime to execute blockchain operations and retrieve information. The client invokes these APIs to: - -- Build, execute, and finalize blocks. -- Access metadata. -- Access consensus related information. -- Handle transaction execution. - -### Host Functions - -During execution, the runtime can access certain external client functionalities via host functions. The specific functions the client exposes allow the runtime to perform operations outside the WebAssembly domain. Host functions enable the runtime to: - -- Perform cryptographic operations. -- Access the current blockchain state. -- Handle storage modifications. -- Allocate memory. - - --- Page Title: Obtain Coretime @@ -8929,109 +6197,15 @@ With your core purchased, you now need to assign your parachain to it for block 8. Sign and submit the transaction. -Once confirmed, your parachain will be assigned to the core and should begin producing blocks (provided your collator is running and synced with the relay chain). - -## Next Steps - -Your parachain is now set up for block production. Consider the following: - -- **Monitor your collator**: Keep your collator node running and monitor its performance. -- **Plan coretime renewal**: If using bulk coretime, plan to renew your core before the current lease expires. -- **Explore runtime upgrades**: Once comfortable with your setup, explore how to upgrade your parachain's runtime without interrupting block production. - - ---- - -Page Title: On-Chain Governance Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-governance.md -- Canonical (HTML): https://docs.polkadot.com/reference/governance/ -- Summary: Discover Polkadot’s cutting-edge OpenGov system, enabling transparent, decentralized decision-making through direct democracy and flexible governance tracks. - -# On-Chain Governance - -## Introduction - -Polkadot’s governance system exemplifies decentralized decision-making, empowering its community of stakeholders to shape the network’s future through active participation. The latest evolution, OpenGov, builds on Polkadot’s foundation by providing a more inclusive and efficient governance model. - -This guide will explain the principles and structure of OpenGov and walk you through its key components, such as Origins, Tracks, and Delegation. You will learn about improvements over earlier governance systems, including streamlined voting processes and enhanced stakeholder participation. - -With OpenGov, Polkadot achieves a flexible, scalable, and democratic governance framework that allows multiple proposals to proceed simultaneously, ensuring the network evolves in alignment with its community's needs. - -## Governance Evolution - -Polkadot’s governance journey began with [Governance V1](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#governance-summary){target=\_blank}, a system that proved effective in managing treasury funds and protocol upgrades. However, it faced limitations, such as: - -- Slow voting cycles, causing delays in decision-making. -- Inflexibility in handling multiple referendums, restricting scalability. - -To address these challenges, Polkadot introduced OpenGov, a governance model designed for greater inclusivity, efficiency, and scalability. OpenGov replaces the centralized structures of Governance V1, such as the Council and Technical Committee, with a fully decentralized and dynamic framework. - -For a full comparison of the historic and current governance models, visit the [Gov1 vs. Polkadot OpenGov](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#gov1-vs-polkadot-opengov){target=\_blank} section of the Polkadot Wiki. - -## OpenGov Key Features - -OpenGov transforms Polkadot’s governance into a decentralized, stakeholder-driven model, eliminating centralized decision-making bodies like the Council. Key enhancements include: - -- **Decentralization**: Shifts all decision-making power to the public, ensuring a more democratic process. -- **Enhanced delegation**: Allows users to delegate their votes to trusted experts across specific governance tracks. -- **Simultaneous referendums**: Multiple proposals can progress at once, enabling faster decision-making. -- **Polkadot Technical Fellowship**: A broad, community-driven group replacing the centralized Technical Committee. - -This new system ensures Polkadot governance remains agile and inclusive, even as the ecosystem grows. - -## Origins and Tracks - -In OpenGov, origins and tracks are central to managing proposals and votes. - -- **Origin**: Determines the authority level of a proposal (e.g., Treasury, Root) which decides the track of all referendums from that origin. -- **Track**: Define the procedural flow of a proposal, such as voting duration, approval thresholds, and enactment timelines. - -Developers must be aware that referendums from different origins and tracks will take varying amounts of time to reach approval and enactment. The [Polkadot Technical Fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} has the option to shorten this timeline by whitelisting a proposal and allowing it to be enacted through the [Whitelist Caller](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#whitelisted-caller){target=\_blank} origin. - -Visit [Origins and Tracks Info](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#origins-and-tracks){target=\_blank} for details on current origins and tracks, associated terminology, and parameters. - -## Referendums - -In OpenGov, anyone can submit a referendum, fostering an open and participatory system. The timeline for a referendum depends on the privilege level of the origin with more significant changes offering more time for community voting and participation before enactment. - -The timeline for an individual referendum includes four distinct periods: - -- **Lead-in**: A minimum amount of time to allow for community participation, available room in the origin, and payment of the decision deposit. Voting is open during this period. -- **Decision**: Voting continues. -- **Confirmation**: Referendum must meet [approval and support](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#approval-and-support){target=\_blank} criteria during entire period to avoid rejection. -- **Enactment**: Changes approved by the referendum are executed. - -### Vote on Referendums - -Voters can vote with their tokens on each referendum. Polkadot uses a voluntary token locking mechanism, called conviction voting, as a way for voters to increase their voting power. A token holder signals they have a stronger preference for approving a proposal based upon their willingness to lock up tokens. Longer voluntary token locks are seen as a signal of continual approval and translate to increased voting weight. - -See [Voting on a Referendum](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank} for a deeper look at conviction voting and related token locks. - -### Delegate Voting Power - -The OpenGov system also supports multi-role delegations, allowing token holders to assign their voting power on different tracks to entities with expertise in those areas. - -For example, if a token holder lacks the technical knowledge to evaluate proposals on the [Root track](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#root){target=\_blank}, they can delegate their voting power for that track to an expert they trust to vote in the best interest of the network. This ensures informed decision-making across tracks while maintaining flexibility for token holders. - -Visit [Multirole Delegation](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#multirole-delegation){target=\_blank} for more details on delegating voting power. - -### Cancel a Referendum - -Polkadot OpenGov has two origins for rejecting ongoing referendums: - -- [**Referendum Canceller**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-canceller){target=\_blank}: Cancels an active referendum when non-malicious errors occur and refunds the deposits to the originators. -- [**Referendum Killer**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-killer){target=\_blank}: Used for urgent, malicious cases this origin instantly terminates an active referendum and slashes deposits. +Once confirmed, your parachain will be assigned to the core and should begin producing blocks (provided your collator is running and synced with the relay chain). -See [Cancelling, Killing, and Blacklisting](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#cancelling-killing--blacklisting){target=\_blank} for additional information on rejecting referendums. +## Next Steps -## Additional Resources +Your parachain is now set up for block production. Consider the following: -- **[Democracy pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/democracy/src){target=\_blank}**: Handles administration of general stakeholder voting. -- **[Gov2: Polkadot’s Next Generation of Decentralised Governance](https://medium.com/polkadot-network/gov2-polkadots-next-generation-of-decentralised-governance-4d9ef657d11b){target=\_blank}**: Medium article by Gavin Wood. -- **[Polkadot Direction](https://matrix.to/#/#Polkadot-Direction:parity.io){target=\_blank}**: Matrix Element client. -- **[Polkassembly](https://polkadot.polkassembly.io/){target=\_blank}**: OpenGov dashboard and UI. -- **[Polkadot.js Apps Governance](https://polkadot.js.org/apps/#/referenda){target=\_blank}**: Overview of active referendums. +- **Monitor your collator**: Keep your collator node running and monitor its performance. +- **Plan coretime renewal**: If using bulk coretime, plan to renew your core before the current lease expires. +- **Explore runtime upgrades**: Once comfortable with your setup, explore how to upgrade your parachain's runtime without interrupting block production. --- @@ -9519,152 +6693,6 @@ This section covers the most common customization patterns you'll encounter: - **[Test Your Runtime](/parachains/customize-runtime/pallet-development/pallet-testing/)**: Unit test pallets and mock complete runtimes to ensure everything works correctly. ---- - -Page Title: Overview of the Polkadot Relay Chain - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-relay-chain.md -- Canonical (HTML): https://docs.polkadot.com/reference/polkadot-hub/consensus-and-security/relay-chain/ -- Summary: Explore Polkadot's core architecture, including its multi-chain vision, shared security, and the DOT token's governance and staking roles. - -# Overview - -## Introduction - -Polkadot is a next-generation blockchain protocol designed to support a multi-chain future by enabling secure communication and interoperability between different blockchains. Built as a Layer-0 protocol, Polkadot introduces innovations like application-specific Layer-1 chains ([parachains](/polkadot-protocol/architecture/parachains/){targe=\_blank}), shared security through [Nominated Proof of Stake (NPoS)](/reference/glossary/#nominated-proof-of-stake-npos){target=\_blank}, and cross-chain interactions via its native [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank}. - -This guide covers key aspects of Polkadot’s architecture, including its high-level protocol structure, blockspace commoditization, and the role of its native token, DOT, in governance, staking, and resource allocation. - -## Polkadot 1.0 - -Polkadot 1.0 represents the state of Polkadot as of 2023, coinciding with the release of [Polkadot runtime v1.0.0](https://github.com/paritytech/polkadot/releases/tag/v1.0.0){target=\_blank}. This section will focus on Polkadot 1.0, along with philosophical insights into network resilience and blockspace. - -As a Layer-0 blockchain, Polkadot contributes to the multi-chain vision through several key innovations and initiatives, including: - -- **Application-specific Layer-1 blockchains (parachains)**: Polkadot's sharded network allows for parallel transaction processing, with shards that can have unique state transition functions, enabling custom-built L1 chains optimized for specific applications. - -- **Shared security and scalability**: L1 chains connected to Polkadot benefit from its [Nominated Proof of Stake (NPoS)](/reference/polkadot-hub/consensus-and-security/pos-consensus/#nominated-proof-of-stake){target=\_blank} system, providing security out-of-the-box without the need to bootstrap their own. - -- **Secure interoperability**: Polkadot's native interoperability enables seamless data and value exchange between parachains. This interoperability can also be used outside of the ecosystem for bridging with external networks. - -- **Resilient infrastructure**: Decentralized and scalable, Polkadot ensures ongoing support for development and community initiatives via its on-chain [treasury](https://wiki.polkadot.com/learn/learn-polkadot-opengov-treasury/){target=\_blank} and governance. - -- **Rapid L1 development**: The [Polkadot SDK](/reference/parachains/){target=\_blank} allows fast, flexible creation and deployment of Layer-1 chains. - -- **Cultivating the next generation of Web3 developers**: Polkadot supports the growth of Web3 core developers through initiatives such as. - - - [Polkadot Blockchain Academy](https://polkadot.com/blockchain-academy){target=\_blank} - - [EdX courses](https://www.edx.org/school/web3x){target=\_blank} - - Rust and Substrate courses (coming soon) - -### High-Level Architecture - -Polkadot features a chain that serves as the central component of the system. This chain is depicted as a ring encircled by several parachains that are connected to it. - -According to Polkadot's design, any blockchain that can compile to WebAssembly (Wasm) and adheres to the Parachains Protocol becomes a parachain on the Polkadot network. - -Here’s a high-level overview of the Polkadot protocol architecture: - -![](/images/reference/polkadot-hub/consensus-and-security/relay-chain/relay-chain-01.webp){ style="background:white" } - -Parachains propose blocks to Polkadot validators, who check for availability and validity before finalizing them. With the relay chain providing security, collators—full nodes of parachains—can focus on their tasks without needing strong incentives. - -The [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank} allows parachains to exchange messages freely, leveraging the chain's security for trust-free communication. - -In order to interact with chains that want to use their own finalization process (e.g., Bitcoin), Polkadot has [bridges](/reference/parachains/interoperability/#bridges-connecting-external-networks){target=\_blank} that offer two-way compatibility, meaning that transactions can be made between different parachains. - -### Polkadot's Additional Functionalities - -Historically, obtaining core slots on Polkadot chain relied upon crowdloans and auctions. Chain cores were leased through auctions for three-month periods, up to a maximum of two years. Crowdloans enabled users to securely lend funds to teams for lease deposits in exchange for pre-sale tokens, which is the only way to access slots on Polkadot 1.0. Auctions are now deprecated in favor of [coretime](/polkadot-protocol/architecture/system-chains/coretime/){target=\_blank}. - -Additionally, the chain handles [staking](https://wiki.polkadot.com/learn/learn-staking/){target=\_blank}, [accounts](/reference/parachains/accounts/){target=\_blank}, balances, and [governance](/reference/governance/){target=\_blank}. - -#### Agile Coretime - -The new and more efficient way of obtaining core on Polkadot is to go through the process of purchasing coretime. - -[Agile coretime](/reference/polkadot-hub/consensus-and-security/agile-coretime/){target=\_blank} improves the efficient use of Polkadot's network resources and offers economic flexibility for developers, extending Polkadot's capabilities far beyond the original vision outlined in the [whitepaper](https://polkadot.com/papers/Polkadot-whitepaper.pdf){target=\_blank}. - -It enables parachains to purchase monthly "bulk" allocations of coretime (the time allocated for utilizing a core, measured in Polkadot relay chain blocks), ensuring heavy-duty parachains that can author a block every six seconds with [Asynchronous Backing](https://wiki.polkadot.com/learn/learn-async-backing/#asynchronous-backing){target=\_blank} can reliably renew their coretime each month. Although six-second block times are now the default, parachains have the option of producing blocks less frequently. - -Renewal orders are prioritized over new orders, offering stability against price fluctuations and helping parachains budget more effectively for project costs. - -### Polkadot's Resilience - -Decentralization is a vital component of blockchain networks, but it comes with trade-offs: - -- An overly decentralized network may face challenges in reaching consensus and require significant energy to operate. -- Also, a network that achieves consensus quickly risks centralization, making it easier to manipulate or attack. - -A network should be decentralized enough to prevent manipulative or malicious influence. In this sense, decentralization is a tool for achieving resilience. - -Polkadot 1.0 currently achieves resilience through several strategies: - -- **Nominated Proof of Stake (NPoS)**: Ensures that the stake per validator is maximized and evenly distributed among validators. - -- **Decentralized nodes**: Designed to encourage operators to join the network. This program aims to expand and diversify the validators in the ecosystem who aim to become independent of the program during their term. Feel free to explore more about the program on the official [Decentralized Nodes](https://nodes.web3.foundation/){target=\_blank} page. - -- **On-chain treasury and governance**: Known as [OpenGov](/reference/governance/){target=\_blank}, this system allows every decision to be made through public referenda, enabling any token holder to cast a vote. - -### Polkadot's Blockspace - -Polkadot 1.0’s design allows for the commoditization of blockspace. - -Blockspace is a blockchain's capacity to finalize and commit operations, encompassing its security, computing, and storage capabilities. Its characteristics can vary across different blockchains, affecting security, flexibility, and availability. - -- **Security**: Measures the robustness of blockspace in Proof of Stake (PoS) networks linked to the stake locked on validator nodes, the variance in stake among validators, and the total number of validators. It also considers social centralization (how many validators are owned by single operators) and physical centralization (how many validators run on the same service provider). - -- **Flexibility**: Reflects the functionalities and types of data that can be stored, with high-quality data essential to avoid bottlenecks in critical processes. - -- **Availability**: Indicates how easily users can access blockspace. It should be easily accessible, allowing diverse business models to thrive, ideally regulated by a marketplace based on demand and supplemented by options for "second-hand" blockspace. - -Polkadot is built on core blockspace principles, but there's room for improvement. Tasks like balance transfers, staking, and governance are managed on the relay chain. - -Delegating these responsibilities to [system chains](/polkadot-protocol/architecture/system-chains/){target=\_blank} could enhance flexibility and allow the relay chain to concentrate on providing shared security and interoperability. - -For more information about blockspace, watch [Robert Habermeier’s interview](https://www.youtube.com/watch?v=e1vISppPwe4){target=\_blank} or read his [technical blog post](https://www.rob.tech/blog/polkadot-blockspace-over-blockchains/){target=\_blank}. - -## DOT Token - -DOT is the native token of the Polkadot network, much like BTC for Bitcoin and Ether for the Ethereum blockchain. DOT has 10 decimals, uses the Planck base unit, and has a balance type of `u128`. The same is true for Kusama's KSM token with the exception of having 12 decimals. - -### Redenomination of DOT - -Polkadot conducted a community poll, which ended on 27 July 2020 at block 888,888, to decide whether to redenominate the DOT token. The stakeholders chose to redenominate the token, changing the value of 1 DOT from 1e12 plancks to 1e10 plancks. - -Importantly, this did not affect the network's total number of base units (plancks); it only affects how a single DOT is represented. The redenomination became effective 72 hours after transfers were enabled, occurring at block 1,248,328 on 21 August 2020 around 16:50 UTC. - -### The Planck Unit - -The smallest unit of account balance on Polkadot SDK-based blockchains (such as Polkadot and Kusama) is called _Planck_, named after the Planck length, the smallest measurable distance in the physical universe. - -Similar to how BTC's smallest unit is the Satoshi and ETH's is the Wei, Polkadot's native token DOT equals 1e10 Planck, while Kusama's native token KSM equals 1e12 Planck. - -### Uses for DOT - -DOT serves three primary functions within the Polkadot network: - -- **Governance**: It is used to participate in the governance of the network. -- **Staking**: DOT is staked to support the network's operation and security. -- **Buying coretime**: Used to purchase coretime in-bulk or on-demand and access the chain to benefit from Polkadot's security and interoperability. - -Additionally, DOT can serve as a transferable token. For example, DOT, held in the treasury, can be allocated to teams developing projects that benefit the Polkadot ecosystem. - -## JAM and the Road Ahead - -The Join-Accumulate Machine (JAM) represents a transformative redesign of Polkadot's core architecture, envisioned as the successor to the current relay chain. Unlike traditional blockchain architectures, JAM introduces a unique computational model that processes work through two primary functions: - -- **Join**: Handles data integration. -- **Accumulate**: Folds computations into the chain's state. - -JAM removes many of the opinions and constraints of the current relay chain while maintaining its core security properties. Expected improvements include: - -- **Permissionless code execution**: JAM is designed to be more generic and flexible, allowing for permissionless code execution through services that can be deployed without governance approval. -- **More effective block time utilization**: JAM's efficient pipeline processing model places the prior state root in block headers instead of the posterior state root, enabling more effective utilization of block time for computations. - -This architectural evolution promises to enhance Polkadot's scalability and flexibility while maintaining robust security guarantees. JAM is planned to be rolled out to Polkadot as a single, complete upgrade rather than a stream of smaller updates. This approach seeks to minimize the developer overhead required to address any breaking changes. - - --- Page Title: Pallet Testing @@ -9803,968 +6831,1013 @@ Some key considerations are: --- -Page Title: Parachains Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/ -- Summary: Learn about parachains, specialized blockchains on Polkadot that gain shared security and interoperability. Discover how they work and the tools to build them. - -# Parachains Overview - -## Introduction - -A parachain is a specialized blockchain that connects to the Polkadot relay chain, benefiting from shared security, interoperability, and scalability. Parachains are built using the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}, a powerful toolkit written in Rust that provides everything needed to create custom blockchain logic while integrating seamlessly with the Polkadot network. - -Unlike standalone blockchains that must bootstrap their own validator sets and security, parachains leverage Polkadot's pooled security model. This allows parachain developers to focus on their application-specific functionality rather than consensus and security infrastructure. Parachains can communicate with each other through Cross-Consensus Messaging (XCM), enabling seamless interoperability across the Polkadot ecosystem. - -Key capabilities that parachains provide include: - -- **Shared security**: Inherit security from Polkadot's validator set without maintaining your own. -- **Interoperability**: Communicate trustlessly with other parachains via XCM. -- **Scalability**: Process transactions in parallel with other parachains. -- **Customization**: Build application-specific logic tailored to your use case. -- **Upgradeability**: Upgrade runtime logic without hard forks. - -## Polkadot SDK: Parachain Architecture - -Building a parachain involves understanding and utilizing several key components of the Polkadot SDK: - -![](/images/reference/parachains/index/overview-01.webp) - -- **[Substrate](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/substrate/index.html){target=\_blank}**: The foundation providing core blockchain primitives and libraries. -- **[FRAME](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank}**: A modular framework for building your parachain's runtime logic. -- **[Cumulus](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/cumulus/index.html){target=\_blank}**: Essential libraries and pallets that enable parachain functionality. -- **[XCM (Cross Consensus Messaging)](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/xcm/index.html){target=\_blank}**: The messaging format for communicating with other parachains and the relay chain. -- **[Polkadot](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/polkadot/index.html){target=\_blank}**: The relay chain that provides security and coordination. - -### Substrate: The Foundation - -Substrate provides the core infrastructure that every parachain is built upon. It handles the low-level blockchain functionality, allowing you to focus on your application's unique features. Substrate includes implementations for networking, database management, consensus participation, and the execution environment for your runtime. - -Every Polkadot SDK node consists of two main components: - -- **Client (Host)**: Handles infrastructure services. - - - Native binary that runs on validator and collator nodes. - - Executes the Wasm-compiled runtime. - - Manages networking, database, mempool, and block production. - - Interfaces with the relay chain for validation. - -- **Runtime (State Transition Function)**: Contains your business logic. - - - Defines how your Polkadot SDK node processes transactions. - - Compiled to [Wasm](https://webassembly.org/){target=\_blank} for deterministic execution. - - Stored on-chain and upgradeable via governance. - -```mermaid -%%{init: {'flowchart': {'padding': 5, 'nodeSpacing': 50, 'rankSpacing': 10}}}%% -graph TB - classDef title font-size:20px,font-weight:bold,stroke-width:0px - classDef clientStyle font-size:16px,font-weight:bold - classDef clientSubNodeStyle margin-top:10px - classDef runtimeCallExecutorStyle padding-top:10px - - subgraph sg1[Parachain
Node] - direction TB - - I[RuntimeCall Executor] - B[Wasm Runtime - STF] - - subgraph sg2[Client] - direction TB - C[Network and Blockchain
Infrastructure Services
+ Relay Chain Interface] - end - - I --> B - end - - class sg1 title - class sg2 clientStyle - class C clientSubNodeStyle - class I runtimeCallExecutorStyle - -``` - -### FRAME: Building Blocks for Your Runtime - -FRAME provides modular components called [pallets](/reference/glossary#pallet){target=\_blank} that you can compose to build your parachain's runtime. Each pallet provides specific functionality that you can customize and configure for your needs. This modular approach allows you to quickly assemble complex functionality without writing everything from scratch. - -```mermaid -graph LR - subgraph SP["Parachain Runtime"] - direction LR - Timestamp ~~~ Aura ~~~ ParachainSystem - Balances ~~~ TransactionPayment ~~~ Sudo - subgraph Timestamp["Timestamp"] - SS1[Custom Config] - end - subgraph Aura["Aura"] - SS2[Custom Config] - end - subgraph ParachainSystem["Parachain System"] - SS3[Custom Config] - end - subgraph Balances["Balances"] - SS4[Custom Config] - end - subgraph TransactionPayment["Transaction Payment"] - SS5[Custom Config] - end - subgraph Sudo["Sudo"] - SS6[Custom Config] - end - style Timestamp stroke:#FF69B4 - style Aura stroke:#FF69B4 - style ParachainSystem stroke:#FF69B4 - style Balances stroke:#FF69B4 - style TransactionPayment stroke:#FF69B4 - style Sudo stroke:#FF69B4 - style SS1 stroke-dasharray: 5 - style SS2 stroke-dasharray: 5 - style SS3 stroke-dasharray: 5 - style SS4 stroke-dasharray: 5 - style SS5 stroke-dasharray: 5 - style SS6 stroke-dasharray: 5 - - end - subgraph AP["Available FRAME Pallets"] - direction LR - A1[Aura]~~~A2[Parachain
System]~~~A3[Transaction
Payment]~~~A4[Sudo] - B1[Identity]~~~B2[Balances]~~~B3[Assets]~~~B4[EVM] - C1[Timestamp]~~~C2[Staking]~~~C3[Contracts]~~~C4[and more...] - end - AP --> SP -``` - -### Cumulus: Parachain-Specific Functionality - -Cumulus is what transforms a Polkadot SDK-based runtime into a parachain-capable runtime. It provides the essential components for communicating with the relay chain, participating in Polkadot's consensus, and handling parachain-specific operations like block validation and collation. - -Key Cumulus components include: - -- **Parachain system pallet**: Core parachain functionality and relay chain communication. -- **Collator consensus**: Block production logic for parachain collators. -- **Relay chain interface**: APIs for interacting with the Polkadot relay chain. -- **Validation data**: Handling proof-of-validity data required by relay chain validators. - -## Where to Go Next - -Building a parachain requires understanding the relationship between your chain and the Polkadot relay chain. The Polkadot SDK provides all the tools needed to design custom runtime logic, enable cross-chain communication, and deploy your parachain to production. - -The following sections provide detailed guidance on each aspect of parachain development, from initial design through deployment and ongoing maintenance. - -
- -- Guide __Launch a Simple Parachain__ - - --- - - Walk through the complete parachain launch flow: from setup and deployment to obtaining coretime. - - [:octicons-arrow-right-24: Deploy](/parachains/launch-a-parachain/set-up-the-parachain-template/) - - -- Guide __Customize Your Runtime__ - - --- - - Design your parachain's runtime logic and choose appropriate pallets for your use case. - - [:octicons-arrow-right-24: Get Started](/parachains/customize-runtime/) - -- Guide __Interoperability__ - - --- - - Implement XCM for trustless cross-chain communication with other parachains. - - [:octicons-arrow-right-24: Learn More](/parachains/interoperability/get-started/) - -- Guide __Runtime Upgrades__ - - --- - - Upgrade your parachain's runtime without hard forks using forkless upgrade mechanisms. - - [:octicons-arrow-right-24: Maintain](/parachains/runtime-maintenance/runtime-upgrades/) - -
- - ---- - -Page Title: Polkadot Omni Node +Page Title: Run a Parachain Network -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-omninode.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/omninode/ -- Summary: Run parachain nodes easily with the polkadot-omni-node, a white-labeled binary that can run parachain nodes using a single pre-built solution. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-run-a-parachain-network.md +- Canonical (HTML): https://docs.polkadot.com/parachains/testing/run-a-parachain-network/ +- Summary: Quickly install and configure Zombienet to deploy and test Polkadot-based blockchain networks with this comprehensive getting-started guide. -# Polkadot Omni Node +# Run a Parachain Network Using Zombienet ## Introduction -The [`polkadot-omni-node`](https://crates.io/crates/polkadot-omni-node/0.7.0){target=\_blank} crate is a versatile, pre-built binary designed to simplify running parachains in the Polkadot ecosystem. Unlike traditional node binaries that are tightly coupled to specific runtime code, the `polkadot-omni-node` operates using an external [chain specification](/polkadot-protocol/glossary#chain-specification){target=\_blank} file, allowing it to adapt dynamically to different parachains. - -This approach enables it to act as a white-labeled node binary, capable of running most parachains that do not require custom node-level logic or extensions. Developers can leverage this flexibility to test, deploy, or operate parachain nodes without maintaining a dedicated codebase for each network. - -This guide provides step-by-step instructions for installing the `polkadot-omni-node`, obtaining a chain specification, and spinning up a parachain node. - -## Prerequisites - -Before getting started, ensure you have the following prerequisites: - -- **[Rust](https://rust-lang.org/tools/install/){target=\_blank}**: Required to build and install the `polkadot-omni-node` binary. - -Ensure Rust's `cargo` command is available in your terminal by running: - -```bash -cargo --version -``` - -## Install Polkadot Omni Node - -To install `polkadot-omni-node` globally using `cargo`, run: - -```bash -cargo install --locked polkadot-omni-node@0.7.0 -``` - -This command downloads and installs version 0.7.0 of the binary, making it available system-wide. - -To confirm the installation, run: - -```bash -polkadot-omni-node --version -``` - -You should see the installed version number printed to the terminal, confirming a successful installation. - -## Obtain Chain Specifications - -The `polkadot-omni-node` binary uses a chain specification file to configure and launch a parachain node. This file defines the parachain's genesis state and network settings. - -The most common source for official chain specifications is the [`paritytech/chainspecs`](https://github.com/paritytech/chainspecs){target=\_blank} repository. These specifications are also browsable in a user-friendly format via the [Chainspec Collection](https://paritytech.github.io/chainspecs/){target=\_blank} website. - -To obtain a chain specification: - -1. Visit the [Chainspec Collection](https://paritytech.github.io/chainspecs/){target=\_blank} website. -2. Find the parachain you want to run. -3. Click the chain spec to open it. -4. Copy the JSON content and save it locally as a `.json` file, e.g., `chain_spec.json`. - -## Run a Parachain Full Node - -Once you've installed `polkadot-omni-node` and saved the appropriate chain specification file, you can start a full node for your chosen parachain. - -To see all available flags and configuration options, run: - -```bash -polkadot-omni-node --help -``` - -To launch the node, run the following command, replacing `./INSERT_PARACHAIN_CHAIN_SPEC.json` with the actual path to your saved chain spec file. - -This command will: - -- Load the chain specification. -- Initialize the node using the provided network configuration. -- Begin syncing with the parachain network. - -```bash -polkadot-omni-node --chain ./INSERT_PARACHAIN_CHAIN_SPEC.json --sync warp -``` - -- The `--chain` flag tells the `polkadot-omni-node` which parachain to run by pointing to its chain specification file. -- The `--sync warp` flag enables warp sync, allowing the node to quickly catch up to the latest finalized state. Historical blocks are fetched in the background as the node continues operating. - -Once started, the node will begin connecting to peers and syncing with the network. You’ll see logs in your terminal reflecting its progress. - -## Interact with the Node - -By default, `polkadot-omni-node` exposes a WebSocket endpoint at `ws://localhost:9944`, which you can use to interact with the running node. You can connect using: - -- **[Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank}**: A web-based interface for exploring and interacting with Polkadot SDK-based chains. -- Custom scripts using compatible [libraries](/develop/toolkit/api-libraries/){target=\_blank}. - -Once connected, you can review blocks, call extrinsics, inspect storage, and interact with the runtime. - -## Parachain Compatibility - -The `polkadot-omni-node` is designed to work with most parachains out of the box; however, your parachain's runtime must meet specific requirements and follow certain conventions to be compatible. This section outlines what your runtime needs to implement and configure to work seamlessly with the `polkadot-omni-node`: - -- Your runtime must implement the required runtime APIs (see below). -- Your runtime must include and configure the required pallets. - -The [`parachain-template`](https://github.com/paritytech/polkadot-sdk-parachain-template/tree/v0.0.4){target=_blank} provides a complete reference implementation that is fully compatible with the `polkadot-omni-node`. You can use it as a starting point or reference for ensuring your runtime meets all compatibility requirements. - -### Required Runtime APIs - -Your parachain runtime must implement the following runtime APIs for the `polkadot-omni-node` to function properly: - -- **GetParachainInfo Runtime API**: The omni-node requires the [`GetParachainInfo`](https://paritytech.github.io/polkadot-sdk/master/cumulus_primitives_core/trait.GetParachainInfo.html){target=\_blank} runtime API to identify and configure the parachain correctly. This API provides the parachain ID to the node. - - ```rust title="runtime/src/apis.rs" - impl cumulus_primitives_core::GetParachainInfo for Runtime { - fn parachain_id() -> cumulus_primitives_core::ParaId { - // Return your parachain ID - ParachainInfo::parachain_id() - } - } - ``` - -- **Aura Runtime API**: For consensus, the `polkadot-omni-node` expects the [Aura runtime API](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/runtime/apis/trait.AuraApi.html){target=\_blank} to be implemented. - - ```rust title="runtime/src/apis.rs" - impl sp_consensus_aura::AuraApi for Runtime { - fn slot_duration() -> sp_consensus_aura::SlotDuration { - sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION) - } - - fn authorities() -> Vec { - Aura::authorities().into_inner() - } - } - ``` - -### Required Pallets +Zombienet is a robust testing framework designed for Polkadot SDK-based blockchain networks. It enables developers to efficiently deploy and test ephemeral blockchain environments on platforms like Kubernetes, Podman, and native setups. With its simple and versatile CLI, Zombienet provides an all-in-one solution for spawning networks, running tests, and validating performance. -Your runtime must include and properly configure the following pallets: +This guide will outline the different installation methods for Zombienet, provide step-by-step instructions for setting up on various platforms, and highlight essential provider-specific features and requirements. -- **System Pallet**: The System pallet ([`frame-system`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/prelude/frame_system/index.html){target=\_blank}) is fundamental and must be configured with appropriate types. +By following this guide, Zombienet will be up and running quickly, ready to streamline your blockchain testing and development workflows. - ```rust title="runtime/src/lib.rs" - #[frame_support::runtime] - impl frame_system::Config for Runtime { - type Block = Block; - type BlockNumber = BlockNumber; - // ... other configurations - } +## Install Zombienet - // Must be named "System" for omni-node compatibility - pub type System = frame_system::Pallet; - ``` +Zombienet releases are available on the [Zombienet repository](https://github.com/paritytech/zombienet){target=\_blank}. -- **ParachainSystem Pallet**: This pallet ([`cumulus-pallet-parachain-system`](https://paritytech.github.io/polkadot-sdk/master/cumulus_pallet_parachain_system/index.html){target=\_blank}) enables parachain functionality and handles low-level details of being a parachain. +Multiple options are available for installing Zombienet, depending on the user's preferences and the environment where it will be used. The following section will guide you through the installation process for each option. - ```rust title="runtime/src/lib.rs" - impl cumulus_pallet_parachain_system::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type OnSystemEvent = (); - // ... other configurations - } +=== "Use the executable" - // Must be named "ParachainSystem" for omni-node compatibility - pub type ParachainSystem = cumulus_pallet_parachain_system::Pallet; - ``` + Install Zombienet using executables by visiting the [latest release](https://github.com/paritytech/zombienet/releases){target=\_blank} page and selecting the appropriate asset for your operating system. You can download the executable and move it to a directory in your PATH. -- **Aura Pallet**: For block authoring consensus ([`pallet-aura`](https://paritytech.github.io/polkadot-sdk/master/pallet_aura/index.html){target=\_blank}). + Each release includes executables for Linux and macOS. Executables are generated using [pkg](https://github.com/vercel/pkg){target=\_blank}, which allows the Zombienet CLI to operate without requiring Node.js to be installed. - ```rust title="runtime/src/lib.rs" - impl pallet_aura::Config for Runtime { - type AuthorityId = AuraId; - type DisabledValidators = (); - type MaxAuthorities = MaxAuthorities; - type AllowMultipleBlocksPerSlot = ConstBool; - } + Then, ensure the downloaded file is executable: - pub type Aura = pallet_aura::Pallet; + ```bash + chmod +x zombienet-macos-arm64 ``` -- **ParachainInfo Pallet**: Provides parachain metadata ([`parachain-info`](https://paritytech.github.io/polkadot-sdk/master/staging_parachain_info/index.html){target=\_blank}). - - ```rust title="runtime/src/lib.rs" - impl parachain_info::Config for Runtime {} + Finally, you can run the following command to check if the installation was successful. If so, it will display the version of the installed Zombienet: - pub type ParachainInfo = parachain_info::Pallet; + ```bash + ./zombienet-macos-arm64 version ``` -If you're migrating an existing parachain to use the `polkadot-omni-node`, you may need to perform runtime upgrades to add the required runtime APIs and pallets. Follow the standard parachain [runtime upgrade](/parachains/runtime-maintenance/runtime-upgrades/){target=\_blank} procedures to implement these changes on your live network. - - ---- - -Page Title: Polkadot SDK Accounts - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-accounts.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/accounts/ -- Summary: Learn about account structures, balances, and address formats in the Polkadot SDK, including how to manage lifecycle, references, and balances. - -# Accounts - -## Introduction - -Accounts are essential for managing identity, transactions, and governance on the network in the Polkadot SDK. Understanding these components is critical for seamless development and operation on the network, whether you're building or interacting with Polkadot-based chains. - -This page will guide you through the essential aspects of accounts, including their data structure, balance types, reference counters, and address formats. You’ll learn how accounts are managed within the runtime, how balances are categorized, and how addresses are encoded and validated. - -## Account Data Structure - -Accounts are foundational to any blockchain, and the Polkadot SDK provides a flexible management system. This section explains how the Polkadot SDK defines accounts and manages their lifecycle through data structures within the runtime. - -### Account - -The [`Account` data type](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/type.Account.html){target=\_blank} is a storage map within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank} that links an account ID to its corresponding data. This structure is fundamental for mapping account-related information within the chain. - -The code snippet below shows how accounts are defined: + If you want to add the `zombienet` executable to your PATH, you can move it to a directory in your PATH, such as `/usr/local/bin`: -```rs - /// The full account information for a particular account ID. - #[pallet::storage] - #[pallet::getter(fn account)] - pub type Account = StorageMap< - _, - Blake2_128Concat, - T::AccountId, - AccountInfo, - ValueQuery, - >; -``` + ```bash + mv zombienet-macos-arm64 /usr/local/bin/zombienet + ``` -The preceding code block defines a storage map named `Account`. The `StorageMap` is a type of on-chain storage that maps keys to values. In the `Account` map, the key is an account ID, and the value is the account's information. Here, `T` represents the generic parameter for the runtime configuration, which is defined by the pallet's configuration trait (`Config`). + Now you can refer to the `zombienet` executable directly. -The `StorageMap` consists of the following parameters: + ```bash + zombienet version + ``` -- **`_`**: Used in macro expansion and acts as a placeholder for the storage prefix type. Tells the macro to insert the default prefix during expansion. -- **`Blake2_128Concat`**: The hashing function applied to keys in the storage map. -- **`T: :AccountId`**: Represents the key type, which corresponds to the account’s unique ID. -- **`AccountInfo`**: The value type stored in the map. For each account ID, the map stores an `AccountInfo` struct containing: +=== "Use Nix" - - **`T::Nonce`**: A nonce for the account, which is incremented with each transaction to ensure transaction uniqueness. - - **`T: :AccountData`**: Custom account data defined by the runtime configuration, which could include balances, locked funds, or other relevant information. + For Nix users, the Zombienet repository provides a [`flake.nix`](https://github.com/paritytech/zombienet/blob/main/flake.nix){target=\_blank} file to install Zombienet making it easy to incorporate Zombienet into Nix-based projects. -- **`ValueQuery`**: Defines how queries to the storage map behave when no value is found; returns a default value instead of `None`. - -For a detailed explanation of storage maps, see the [`StorageMap`](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/struct.StorageMap.html){target=\_blank} entry in the Rust docs. - -### Account Info - -The `AccountInfo` structure is another key element within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank}, providing more granular details about each account's state. This structure tracks vital data, such as the number of transactions and the account’s relationships with other modules. - -```rs -/// Information of an account. -#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)] -pub struct AccountInfo { - /// The number of transactions this account has sent. - pub nonce: Nonce, - /// The number of other modules that currently depend on this account's existence. The account - /// cannot be reaped until this is zero. - pub consumers: RefCount, - /// The number of other modules that allow this account to exist. The account may not be reaped - /// until this and `sufficients` are both zero. - pub providers: RefCount, - /// The number of modules that allow this account to exist for their own purposes only. The - /// account may not be reaped until this and `providers` are both zero. - pub sufficients: RefCount, - /// The additional data that belongs to this account. Used to store the balance(s) in a lot of - /// chains. - pub data: AccountData, -} -``` + To install Zombienet utilizing Nix, users can run the following command, triggering the fetching of the flake and subsequently installing the Zombienet package: -The `AccountInfo` structure includes the following components: + ```bash + nix run github:paritytech/zombienet/INSERT_ZOMBIENET_VERSION -- \ + spawn INSERT_ZOMBIENET_CONFIG_FILE_NAME.toml + ``` -- **`nonce`**: Tracks the number of transactions initiated by the account, which ensures transaction uniqueness and prevents replay attacks. -- **`consumers`**: Counts how many other modules or pallets rely on this account’s existence. The account cannot be removed from the chain (reaped) until this count reaches zero. -- **`providers`**: Tracks how many modules permit this account’s existence. An account can only be reaped once both `providers` and `sufficients` are zero. -- **`sufficients`**: Represents the number of modules that allow the account to exist for internal purposes, independent of any other modules. -- **`AccountData`**: A flexible data structure that can be customized in the runtime configuration, usually containing balances or other user-specific data. + Replace the `INSERT_ZOMBIENET_VERSION` with the desired version of Zombienet and the `INSERT_ZOMBIENET_CONFIG_FILE_NAME` with the name of the configuration file you want to use. -This structure helps manage an account's state and prevents its premature removal while it is still referenced by other on-chain data or modules. The [`AccountInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.AccountInfo.html){target=\_blank} structure can vary as long as it satisfies the trait bounds defined by the `AccountData` associated type in the [`frame-system::pallet::Config`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/trait.Config.html){target=\_blank} trait. + To run the command above, you need to have [Flakes](https://nixos.wiki/wiki/Flakes#Enable_flakes){target=\_blank} enabled. -### Account Reference Counters + Alternatively, you can also include the Zombienet binary in the PATH for the current shell using the following command: + + ```bash + nix shell github:paritytech/zombienet/INSERT_ZOMBIENET_VERSION + ``` -Polkadot SDK uses reference counters to track an account’s dependencies across different runtime modules. These counters ensure that accounts remain active while data is associated with them. +=== "Use Docker" -The reference counters include: + Zombienet can also be run using Docker. The Zombienet repository provides a Docker image that can be used to run the Zombienet CLI. To run Zombienet using Docker, you can use the following command: -- **`consumers`**: Prevents account removal while other pallets still rely on the account. -- **`providers`**: Ensures an account is active before other pallets store data related to it. -- **`sufficients`**: Indicates the account’s independence, ensuring it can exist even without a native token balance, such as when holding sufficient alternative assets. + ```bash + docker run -it --rm \ + -v $(pwd):/home/nonroot/zombie-net/host-current-files \ + paritytech/zombienet + ``` -#### Providers Reference Counters + The command above will run the Zombienet CLI inside a Docker container and mount the current directory to the `/home/nonroot/zombie-net/host-current-files` directory. This allows Zombienet to access the configuration file and other files in the current directory. If you want to mount a different directory, replace `$(pwd)` with the desired directory path. -The `providers` counter ensures that an account is ready to be depended upon by other runtime modules. For example, it is incremented when an account has a balance above the existential deposit, which marks the account as active. + Inside the Docker container, you can run the Zombienet CLI commands. First, you need to set up Zombienet to download the necessary binaries: -The system requires this reference counter to be greater than zero for the `consumers` counter to be incremented, ensuring the account is stable before any dependencies are added. + ```bash + npm run zombie -- setup polkadot polkadot-parachain + ``` -#### Consumers Reference Counters + After that, you need to add those binaries to the PATH: -The `consumers` counter ensures that the account cannot be reaped until all references to it across the runtime have been removed. This check prevents the accidental deletion of accounts that still have active on-chain data. + ```bash + export PATH=/home/nonroot/zombie-net:$PATH + ``` -It is the user’s responsibility to clear out any data from other runtime modules if they wish to remove their account and reclaim their existential deposit. + Finally, you can run the Zombienet CLI commands. For example, to spawn a network using a specific configuration file, you can run the following command: -#### Sufficients Reference Counter + ```bash + npm run zombie -- -p native spawn host-current-files/minimal.toml + ``` -The `sufficients` counter tracks accounts that can exist independently without relying on a native account balance. This is useful for accounts holding other types of assets, like tokens, without needing a minimum balance in the native token. + The command above mounts the current directory to the `/workspace` directory inside the Docker container, allowing Zombienet to access the configuration file and other files in the current directory. If you want to mount a different directory, replace `$(pwd)` with the desired directory path. -For instance, the [Assets pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_assets/index.html){target=\_blank}, may increment this counter for an account holding sufficient tokens. +## Providers -#### Account Deactivation +Zombienet supports different backend providers for running the nodes. At this moment, [Kubernetes](https://kubernetes.io/){target=\_blank}, [Podman](https://podman.io/){target=\_blank}, and local providers are supported, which can be declared as `kubernetes`, `podman`, or `native`, respectively. -In Polkadot SDK-based chains, an account is deactivated when its reference counters (such as `providers`, `consumers`, and `sufficient`) reach zero. These counters ensure the account remains active as long as other runtime modules or pallets reference it. +To use a particular provider, you can specify it in the network file or use the `--provider` flag in the CLI: -When all dependencies are cleared and the counters drop to zero, the account becomes deactivated and may be removed from the chain (reaped). This is particularly important in Polkadot SDK-based blockchains, where accounts with balances below the existential deposit threshold are pruned from storage to conserve state resources. +```bash +zombienet spawn network.toml --provider INSERT_PROVIDER +``` -Each pallet that references an account has cleanup functions that decrement these counters when the pallet no longer depends on the account. Once these counters reach zero, the account is marked for deactivation. +Alternatively, you can set the provider in the network file: -#### Updating Counters +```toml +[settings] +provider = "INSERT_PROVIDER" +... +``` -The Polkadot SDK provides runtime developers with various methods to manage account lifecycle events, such as deactivation or incrementing reference counters. These methods ensure that accounts cannot be reaped while still in use. +It's important to note that each provider has specific requirements and associated features. The following sections cover each provider's requirements and added features. -The following helper functions manage these counters: +### Kubernetes -- **`inc_consumers()`**: Increments the `consumer` reference counter for an account, signaling that another pallet depends on it. -- **`dec_consumers()`**: Decrements the `consumer` reference counter, signaling that a pallet no longer relies on the account. -- **`inc_providers()`**: Increments the `provider` reference counter, ensuring the account remains active. -- **`dec_providers()`**: Decrements the `provider` reference counter, allowing for account deactivation when no longer in use. -- **`inc_sufficients()`**: Increments the `sufficient` reference counter for accounts that hold sufficient assets. -- **`dec_sufficients()`**: Decrements the `sufficient` reference counter. +Kubernetes is a portable, extensible, open-source platform for managing containerized workloads and services. Zombienet is designed to be compatible with a variety of Kubernetes clusters, including: -To ensure proper account cleanup and lifecycle management, a corresponding decrement should be made for each increment action. +- [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine){target=\_blank} +- [Docker Desktop](https://docs.docker.com/desktop/features/kubernetes/){target=\_blank} +- [kind](https://kind.sigs.k8s.io/){target=\_blank} -The `System` pallet offers three query functions to assist developers in tracking account states: +#### Requirements + +To effectively interact with your cluster, you'll need to ensure that [`kubectl`](https://kubernetes.io/docs/reference/kubectl/){target=\_blank} is installed on your system. This Kubernetes command-line tool allows you to run commands against Kubernetes clusters. If you don't have `kubectl` installed, you can follow the instructions provided in the [Kubernetes documentation](https://kubernetes.io/docs/tasks/tools/#kubectl){target=\_blank}. -- **[`can_inc_consumer()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_inc_consumer){target=\_blank}**: Checks if the account can safely increment the consumer reference. -- **[`can_dec_provider()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_dec_provider){target=\_blank}**: Ensures that no consumers exist before allowing the decrement of the provider counter. -- **[`is_provider_required()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.is_provider_required){target=\_blank}**: Verifies whether the account still has any active consumer references. +To create resources such as namespaces, pods, and CronJobs within the target cluster, you must grant your user or service account the appropriate permissions. These permissions are essential for managing and deploying applications effectively within Kubernetes. -This modular and flexible system of reference counters tightly controls the lifecycle of accounts in Polkadot SDK-based blockchains, preventing the accidental removal or retention of unneeded accounts. You can refer to the [System pallet Rust docs](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html){target=\_blank} for more details. +#### Features +If available, Zombienet uses the Prometheus operator to oversee monitoring and visibility. This configuration ensures that only essential networking-related pods are deployed. Using the Prometheus operator, Zombienet improves its ability to monitor and manage network activities within the Kubernetes cluster efficiently. -## Account Balance Types +### Podman -In the Polkadot ecosystem, account balances are categorized into different types based on how the funds are utilized and their availability. These balance types determine the actions that can be performed, such as transferring tokens, paying transaction fees, or participating in governance activities. Understanding these balance types helps developers manage user accounts and implement balance-dependent logic. +Podman is a daemonless container engine for developing, managing, and running Open Container Initiative (OCI) containers and container images on Linux-based systems. Zombienet supports Podman rootless as a provider on Linux machines. Although Podman has support for macOS through an internal virtual machine (VM), the Zombienet provider code requires Podman to run natively on Linux. -!!! note "A more efficient distribution of account balance types is in development" - Soon, pallets in the Polkadot SDK will implement the [`Fungible` trait](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} (see the [tracking issue](https://github.com/paritytech/polkadot-sdk/issues/226){target=\_blank} for more details). For example, the [`transaction-storage`](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_storage/index.html){target=\_blank} pallet changed the implementation of the [`Currency`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/currency/index.html){target=\_blank} trait (see the [Refactor transaction storage pallet to use fungible traits](https://github.com/paritytech/polkadot-sdk/pull/1800){target=\_blank} PR for further details): +#### Requirements + +To use Podman as a provider, you need to have Podman installed on your system. You can install Podman by following the instructions provided on the [Podman website](https://podman.io/getting-started/installation){target=\_blank}. - ```rust - type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; - ``` +#### Features - To the [`Fungible`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} trait: +Using Podman, Zombienet deploys additional pods to enhance the monitoring and visibility of the active network. Specifically, pods for [Prometheus](https://prometheus.io/){target=\_blank}, [Tempo](https://grafana.com/docs/tempo/latest/operations/monitor/){target=\_blank}, and [Grafana](https://grafana.com/){target=\_blank} are included in the deployment. Grafana is configured with Prometheus and Tempo as data sources. - ```rust - type BalanceOf = <::Currency as FnInspect<::AccountId>>::Balance; - ``` +Upon launching Zombienet, access to these monitoring services is facilitated through specific URLs provided in the output: + +- **Prometheus**: `http://127.0.0.1:34123` +- **Tempo**: `http://127.0.0.1:34125` +- **Grafana**: `http://127.0.0.1:41461` + +It's important to note that Grafana is deployed with default administrator access. - This update will enable more efficient use of account balances, allowing the free balance to be utilized for on-chain activities such as setting proxies and managing identities. +When network operations cease, either from halting a running spawn with the `Ctrl+C` command or test completion, Zombienet automatically removes all associated pods. -### Balance Types +### Local Provider -The five main balance types are: +The Zombienet local provider, also called native, enables you to run nodes as local processes in your environment. -- **Free balance**: Represents the total tokens available to the account for any on-chain activity, including staking, governance, and voting. However, it may not be fully spendable or transferrable if portions of it are locked or reserved. -- **Locked balance**: Portions of the free balance that cannot be spent or transferred because they are tied up in specific activities like [staking](https://wiki.polkadot.com/learn/learn-staking/#nominating-validators){target=\_blank}, [vesting](https://wiki.polkadot.com/learn/learn-guides-transfers/#vested-transfers-with-the-polkadot-js-ui){target=\_blank}, or participating in [governance](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank}. While the tokens remain part of the free balance, they are non-transferable for the duration of the lock. -- **Reserved balance**: Funds locked by specific system actions, such as setting up an [identity](https://wiki.polkadot.com/learn/learn-identity/){target=\_blank}, creating [proxies](https://wiki.polkadot.com/learn/learn-proxies/){target=\_blank}, or submitting [deposits for governance proposals](https://wiki.polkadot.com/learn/learn-guides-polkadot-opengov/#claiming-opengov-deposits){target=\_blank}. These tokens are not part of the free balance and cannot be spent unless they are unreserved. -- **Spendable balance**: The portion of the free balance that is available for immediate spending or transfers. It is calculated by subtracting the maximum of locked or reserved amounts from the free balance, ensuring that existential deposit limits are met. -- **Untouchable balance**: Funds that cannot be directly spent or transferred but may still be utilized for on-chain activities, such as governance participation or staking. These tokens are typically tied to certain actions or locked for a specific period. +#### Requirements + +You must have the necessary binaries for your network (such as `polkadot` and `polkadot-parachain`). These binaries should be available in your PATH, allowing Zombienet to spawn the nodes as local processes. -The spendable balance is calculated as follows: +To install the necessary binaries, you can use the Zombienet CLI command: -```text -spendable = free - max(locked - reserved, ED) +```bash +zombienet setup polkadot polkadot-parachain ``` -Here, `free`, `locked`, and `reserved` are defined above. The `ED` represents the [existential deposit](https://wiki.polkadot.com/learn/learn-accounts/#existential-deposit-and-reaping){target=\_blank}, the minimum balance required to keep an account active and prevent it from being reaped. You may find you can't see all balance types when looking at your account via a wallet. Wallet providers often display only spendable, locked, and reserved balances. +This command will download and prepare the necessary binaries for Zombienet's use. + +If you need to use a custom binary, ensure the binary is available in your PATH. You can also specify the binary path in the network configuration file. The following example uses the custom [OpenZeppelin template](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\_blank}: + +First, clone the OpenZeppelin template repository using the following command: + +```bash +git clone https://github.com/OpenZeppelin/polkadot-runtime-templates \ +&& cd polkadot-runtime-templates/generic-template +``` -### Locks +Next, run the command to build the custom binary: -Locks are applied to an account's free balance, preventing that portion from being spent or transferred. Locks are automatically placed when an account participates in specific on-chain activities, such as staking or governance. Although multiple locks may be applied simultaneously, they do not stack. Instead, the largest lock determines the total amount of locked tokens. +```bash +cargo build --release +``` -Locks follow these basic rules: +Finally, add the custom binary to your PATH as follows: -- If different locks apply to varying amounts, the largest lock amount takes precedence. -- If multiple locks apply to the same amount, the lock with the longest duration governs when the balance can be unlocked. +```bash +export PATH=$PATH:INSERT_PATH_TO_RUNTIME_TEMPLATES/parachain-template-node/target/release +``` -#### Locks Example +Alternatively, you can specify the binary path in the network configuration file. The local provider exclusively utilizes the command configuration for nodes, which supports both relative and absolute paths. You can employ the `default_command` configuration to specify the binary for spawning all nodes in the relay chain. -Consider an example where an account has 80 DOT locked for both staking and governance purposes like so: +```toml +[relaychain] +chain = "rococo-local" +default_command = "./bin-v1.6.0/polkadot" -- 80 DOT is staked with a 28-day lock period. -- 24 DOT is locked for governance with a 1x conviction and a 7-day lock period. -- 4 DOT is locked for governance with a 6x conviction and a 224-day lock period. +[parachain] +id = 1000 -In this case, the total locked amount is 80 DOT because only the largest lock (80 DOT from staking) governs the locked balance. These 80 DOT will be released at different times based on the lock durations. In this example, the 24 DOT locked for governance will be released first since the shortest lock period is seven days. The 80 DOT stake with a 28-day lock period is released next. Now, all that remains locked is the 4 DOT for governance. After 224 days, all 80 DOT (minus the existential deposit) will be free and transferable. + [parachain.collators] + name = "collator01" + command = "./target/release/parachain-template-node" +``` -![Illustration of Lock Example](/images/reference/parachains/accounts/accounts-01.webp) +#### Features -#### Edge Cases for Locks +The local provider does not offer any additional features. -In scenarios where multiple convictions and lock periods are active, the lock duration and amount are determined by the longest period and largest amount. For example, if you delegate with different convictions and attempt to undelegate during an active lock period, the lock may be extended for the full amount of tokens. For a detailed discussion on edge case lock behavior, see this [Stack Exchange post](https://substrate.stackexchange.com/questions/5067/delegating-and-undelegating-during-the-lock-period-extends-it-for-the-initial-am){target=\_blank}. +## Configure Zombienet -### Balance Types on Polkadot.js +Effective network configuration is crucial for deploying and managing blockchain systems. Zombienet simplifies this process by offering versatile configuration options in both JSON and TOML formats. Whether setting up a simple test network or a complex multi-node system, Zombienet's tools provide the flexibility to customize every aspect of your network's setup. -Polkadot.js provides a user-friendly interface for managing and visualizing various account balances on Polkadot and Kusama networks. When interacting with Polkadot.js, you will encounter multiple balance types that are critical for understanding how your funds are distributed and restricted. This section explains how different balances are displayed in the Polkadot.js UI and what each type represents. +The following sections will explore the structure and usage of Zombienet configuration files, explain key settings for network customization, and walk through CLI commands and flags to optimize your development workflow. -![](/images/reference/parachains/accounts/accounts-02.webp) +### Configuration Files -The most common balance types displayed on Polkadot.js are: +The network configuration file can be either JSON or TOML format. The Zombienet repository also provides a collection of [example configuration files](https://github.com/paritytech/zombienet/tree/main/examples){target=\_blank} that can be used as a reference. -- **Total balance**: The total number of tokens available in the account. This includes all tokens, whether they are transferable, locked, reserved, or vested. However, the total balance does not always reflect what can be spent immediately. In this example, the total balance is 0.6274 KSM. +Each section may include provider-specific keys that aren't recognized by other providers. For example, if you use the local provider, any references to images for nodes will be disregarded. -- **Transferable balance**: Shows how many tokens are immediately available for transfer. It is calculated by subtracting the locked and reserved balances from the total balance. For example, if an account has a total balance of 0.6274 KSM and a transferable balance of 0.0106 KSM, only the latter amount can be sent or spent freely. +### CLI Usage -- **Vested balance**: Tokens that allocated to the account but released according to a specific schedule. Vested tokens remain locked and cannot be transferred until fully vested. For example, an account with a vested balance of 0.2500 KSM means that this amount is owned but not yet transferable. +Zombienet provides a CLI that allows interaction with the tool. The CLI can receive commands and flags to perform different kinds of operations. These operations use the following syntax: -- **Locked balance**: Tokens that are temporarily restricted from being transferred or spent. These locks typically result from participating in staking, governance, or vested transfers. In Polkadot.js, locked balances do not stack—only the largest lock is applied. For instance, if an account has 0.5500 KSM locked for governance and staking, the locked balance would display 0.5500 KSM, not the sum of all locked amounts. +```bash +zombienet +``` -- **Reserved balance**: Refers to tokens locked for specific on-chain actions, such as setting an identity, creating a proxy, or making governance deposits. Reserved tokens are not part of the free balance, but can be freed by performing certain actions. For example, removing an identity would unreserve those funds. +The following sections will guide you through the primary usage of the Zombienet CLI and the available commands and flags. -- **Bonded balance**: The tokens locked for staking purposes. Bonded tokens are not transferable until they are unbonded after the unbonding period. +#### CLI Commands -- **Redeemable balance**: The number of tokens that have completed the unbonding period and are ready to be unlocked and transferred again. For example, if an account has a redeemable balance of 0.1000 KSM, those tokens are now available for spending. +- **`spawn `**: Spawn the network defined in the [configuration file](#configuration-files). +- **`test `**: Run tests on the spawned network using the assertions and tests defined in the [test file](/develop/toolkit/parachains/spawn-chains/zombienet/write-tests/#the-test-file){target=\_blank}. +- **`setup `**: Set up the Zombienet development environment to download and use the `polkadot` or `polkadot-parachain` executable. +- **`convert `**: Transforms a [polkadot-launch](https://github.com/paritytech/polkadot-launch){target=\_blank} configuration file with a `.js` or `.json` extension into a Zombienet configuration file. +- **`version`**: Prints Zombienet version. +- **`help`**: Prints help information. -- **Democracy balance**: Reflects the number of tokens locked for governance activities, such as voting on referenda. These tokens are locked for the duration of the governance action and are only released after the lock period ends. +#### CLI Flags -By understanding these balance types and their implications, developers and users can better manage their funds and engage with on-chain activities more effectively. +You can use the following flags to customize the behavior of the CLI: -## Address Formats +- **`-p`, `--provider`**: Override the [provider](#providers) to use. +- **`-d`, `--dir`**: Specify a directory path for placing the network files instead of using the default temporary path. +- **`-f`, `--force`**: Force override all prompt commands. +- **`-l`, `--logType`**: Type of logging on the console. Defaults to `table`. +- **`-m`, `--monitor`**: Start as monitor and don't auto clean up network. +- **`-c`, `--spawn-concurrency`**: Number of concurrent spawning processes to launch. Defaults to `1`. +- **`-h`, `--help`**: Display help for command. -The SS58 address format is a core component of the Polkadot SDK that enables accounts to be uniquely identified across Polkadot-based networks. This format is a modified version of Bitcoin's Base58Check encoding, specifically designed to accommodate the multi-chain nature of the Polkadot ecosystem. SS58 encoding allows each chain to define its own set of addresses while maintaining compatibility and checksum validation for security. +### Settings -### Basic Format +Through the keyword `settings`, it's possible to define the general settings for the network. The available keys are: -SS58 addresses consist of three main components: +- **`global_volumes?`** ++"GlobalVolume[]"++: A list of global volumes to use. -```text -base58encode(concat(,
, )) -``` + ??? child "`GlobalVolume` interface definition" + ```js + export interface GlobalVolume { + name: string; + fs_type: string; + mount_path: string; + } + ``` -- **Address type**: A byte or set of bytes that define the network (or chain) for which the address is intended. This ensures that addresses are unique across different Polkadot SDK-based chains. -- **Address**: The public key of the account encoded as bytes. -- **Checksum**: A hash-based checksum which ensures that addresses are valid and unaltered. The checksum is derived from the concatenated address type and address components, ensuring integrity. +- **`bootnode`** ++"boolean"++: Add bootnode to network. Defaults to `true`. +- **`bootnode_domain?`** ++"string"++: Domain to use for bootnode. +- **`timeout`** ++"number"++: Global timeout to use for spawning the whole network. +- **`node_spawn_timeout?`** ++"number"++: Timeout to spawn pod/process. +- **`grafana?`** ++"boolean"++: Deploy an instance of Grafana. +- **`prometheus?`** ++"boolean"++: Deploy an instance of Prometheus. +- **`telemetry?`** ++"boolean"++: Enable telemetry for the network. +- **`jaeger_agent?`** ++"string"++: The Jaeger agent endpoint passed to the nodes. Only available on Kubernetes. +- **`tracing_collator_url?`** ++"string"++: The URL of the tracing collator used to query by the tracing assertion. Should be tempo query compatible. +- **`tracing_collator_service_name?`** ++"string"++: Service name for tempo query frontend. Only available on Kubernetes. Defaults to `tempo-tempo-distributed-query-frontend`. +- **`tracing_collator_service_namespace?`** ++"string"++: Namespace where tempo is running. Only available on Kubernetes. Defaults to `tempo`. +- **`tracing_collator_service_port?`** ++"number"++: Port of the query instance of tempo. Only available on Kubernetes. Defaults to `3100`. +- **`enable_tracing?`** ++"boolean"++: Enable the tracing system. Only available on Kubernetes. Defaults to `true`. +- **`provider`** ++"string"++: Provider to use. Default is `kubernetes`". +- **`polkadot_introspector?`** ++"boolean"++: Deploy an instance of polkadot-introspector. Only available on Podman and Kubernetes. Defaults to `false`. +- **`backchannel?`** ++"boolean"++: Deploy an instance of backchannel server. Only available on Kubernetes. Defaults to `false`. +- **`image_pull_policy?`** ++"string"++: Image pull policy to use in the network. Possible values are `Always`, `IfNotPresent`, and `Never`. +- **`local_ip?`** ++"string"++: IP used for exposing local services (rpc/metrics/monitors). Defaults to `"127.0.0.1"`. +- **`global_delay_network_global_settings?`** ++"number"++: Delay in seconds to apply to the network. +- **`node_verifier?`** ++"string"++: Specify how to verify node readiness or deactivate by using `None`. Possible values are `None` and `Metric`. Defaults to `Metric`. -The encoding process transforms the concatenated components into a Base58 string, providing a compact and human-readable format that avoids easily confused characters (e.g., zero '0', capital 'O', lowercase 'l'). This encoding function ([`encode`](https://docs.rs/bs58/latest/bs58/fn.encode.html){target=\_blank}) is implemented exactly as defined in Bitcoin and IPFS specifications, using the same alphabet as both implementations. +For example, the following configuration file defines a minimal example for the settings: -For more details about the SS58 address format implementation, see the [`Ss58Codec`](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Ss58Codec.html){target=\_blank} trait in the Rust Docs. +=== "TOML" -### Address Type + ```toml title="base-example.toml" + [settings] + timeout = 1000 + bootnode = false + provider = "kubernetes" + backchannel = false + # ... -The address type defines how an address is interpreted and to which network it belongs. Polkadot SDK uses different prefixes to distinguish between various chains and address formats: + ``` -- **Address types `0-63`**: Simple addresses, commonly used for network identifiers. -- **Address types `64-127`**: Full addresses that support a wider range of network identifiers. -- **Address types `128-255`**: Reserved for future address format extensions. +=== "JSON" -For example, Polkadot’s main network uses an address type of 0, while Kusama uses 2. This ensures that addresses can be used without confusion between networks. + ```json title="base-example.json" + { + "settings": { + "timeout": 1000, + "bootnode": false, + "provider": "kubernetes", + "backchannel": false, + "...": {} + }, + "...": {} + } -The address type is always encoded as part of the SS58 address, making it easy to quickly identify the network. Refer to the [SS58 registry](https://github.com/paritytech/ss58-registry){target=\_blank} for the canonical listing of all address type identifiers and how they map to Polkadot SDK-based networks. + ``` -### Address Length +### Relay Chain Configuration -SS58 addresses can have different lengths depending on the specific format. Address lengths range from as short as 3 to 35 bytes, depending on the complexity of the address and network requirements. This flexibility allows SS58 addresses to adapt to different chains while providing a secure encoding mechanism. +You can use the `relaychain` keyword to define further parameters for the relay chain at start-up. The available keys are: -| Total | Type | Raw account | Checksum | -|-------|------|-------------|----------| -| 3 | 1 | 1 | 1 | -| 4 | 1 | 2 | 1 | -| 5 | 1 | 2 | 2 | -| 6 | 1 | 4 | 1 | -| 7 | 1 | 4 | 2 | -| 8 | 1 | 4 | 3 | -| 9 | 1 | 4 | 4 | -| 10 | 1 | 8 | 1 | -| 11 | 1 | 8 | 2 | -| 12 | 1 | 8 | 3 | -| 13 | 1 | 8 | 4 | -| 14 | 1 | 8 | 5 | -| 15 | 1 | 8 | 6 | -| 16 | 1 | 8 | 7 | -| 17 | 1 | 8 | 8 | -| 35 | 1 | 32 | 2 | +- **`default_command?`** ++"string"++: The default command to run. Defaults to `polkadot`. +- **`default_image?`** ++"string"++: The default Docker image to use. +- **`default_resources?`** ++"Resources"++: Represents the resource limits/reservations the nodes need by default. Only available on Kubernetes. -SS58 addresses also support different payload sizes, allowing a flexible range of account identifiers. + ??? child "`Resources` interface definition" + ```js + export interface Resources { + resources: { + requests?: { + memory?: string; + cpu?: string; + }; + limits?: { + memory?: string; + cpu?: string; + }; + }; + } + ``` -### Checksum Types +- **`default_db_snapshot?`** ++"string"++: The default database snapshot to use. +- **`default_prometheus_prefix`** ++"string"++: A parameter for customizing the metric's prefix. Defaults to `substrate`. +- **`default_substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version. -A checksum is applied to validate SS58 addresses. Polkadot SDK uses a Blake2b-512 hash function to calculate the checksum, which is appended to the address before encoding. The checksum length can vary depending on the address format (e.g., 1-byte, 2-byte, or longer), providing varying levels of validation strength. + ??? child "`SubstrateCliArgsVersion` enum definition" + ```js + export enum SubstrateCliArgsVersion { + V0 = 0, + V1 = 1, + V2 = 2, + V3 = 3, + } + ``` -The checksum ensures that an address is not modified or corrupted, adding an extra layer of security for account management. +- **`default_keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. +- **`chain`** ++"string"++: The chain name. +- **`chain_spec_path?`** ++"string"++: Path to the chain spec file. Should be the plain version to allow customizations. +- **`chain_spec_command?`** ++"string"++: Command to generate the chain spec. It can't be used in combination with `chain_spec_path`. +- **`default_args?`** ++"string[]"++: An array of arguments to use as default to pass to the command. +- **`default_overrides?`** ++"Override[]"++: An array of overrides to upload to the node. -### Validating Addresses + ??? child "`Override` interface definition" + ```js + export interface Override { + local_path: string; + remote_name: string; + } + ``` -SS58 addresses can be validated using the subkey command-line interface or the Polkadot.js API. These tools help ensure an address is correctly formatted and valid for the intended network. The following sections will provide an overview of how validation works with these tools. +- **`random_nominators_count?`** ++"number"++: If set and the stacking pallet is enabled, Zombienet will generate the input quantity of nominators and inject them into the genesis. +- **`max_nominations`** ++"number"++: The max number of nominations allowed by a nominator. Should match the value set in the runtime. Defaults to `24`. +- **`nodes?`** ++"Node[]"++: An array of nodes to spawn. It is further defined in the [Node Configuration](#node-configuration) section. +- **`node_groups?`** ++"NodeGroup[]"++: An array of node groups to spawn. It is further defined in the [Node Group Configuration](#node-group-configuration) section. +- **`total_node_in_group?`** ++"number"++: The total number of nodes in the group. Defaults to `1`. +- **`genesis`** ++"JSON"++: The genesis configuration. +- **`default_delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. -#### Using Subkey + ??? child "`DelayNetworkSettings` interface definition" + ```js + export interface DelayNetworkSettings { + latency: string; + correlation?: string; // should be parsable as float by k8s + jitter?: string; + } + ``` -[Subkey](https://paritytech.github.io/polkadot-sdk/master/subkey/index.html){target=\_blank} is a CLI tool provided by Polkadot SDK for generating and managing keys. It can inspect and validate SS58 addresses. +#### Node Configuration -The `inspect` command gets a public key and an SS58 address from the provided secret URI. The basic syntax for the `subkey inspect` command is: +One specific key capable of receiving more subkeys is the `nodes` key. This key is used to define further parameters for the nodes. The available keys: -```bash -subkey inspect [flags] [options] uri -``` +- **`name`** ++"string"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`). +- **`image?`** ++"string"++: Override default Docker image to use for this node. +- **`command?`** ++"string"++: Override default command to run. +- **`command_with_args?`** ++"string"++: Override default command and arguments. +- **`args?`** ++"string[]"++: Arguments to be passed to the command. +- **`env?`** ++"envVars[]"++: Environment variables to set in the container. -For the `uri` command-line argument, you can specify the secret seed phrase, a hex-encoded private key, or an SS58 address. If the input is a valid address, the `subkey` program displays the corresponding hex-encoded public key, account identifier, and SS58 addresses. + ??? child "`envVars` interface definition" + ```js + export interface EnvVars { + name: string; + value: string; + } + ``` -For example, to inspect the public keys derived from a secret seed phrase, you can run a command similar to the following: +- **`prometheus_prefix?`** ++"string"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`. +- **`db_snapshot?`** ++"string"++: Database snapshot to use. +- **`substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead. -```bash -subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" -``` + ??? child "`SubstrateCliArgsVersion` enum definition" + ```js + export enum SubstrateCliArgsVersion { + V0 = 0, + V1 = 1, + V2 = 2, + V3 = 3, + } + ``` -The command displays output similar to the following: +- **`resources?`** ++"Resources"++: Represent the resources limits/reservations needed by the node. -
- subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" - Secret phrase `caution juice atom organ advance problem want pledge someone senior holiday very` is account: - Secret seed: 0xc8fa03532fb22ee1f7f6908b9c02b4e72483f0dbd66e4cd456b8f34c6230b849 - Public key (hex): 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - Public key (SS58): 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR - Account ID: 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - SS58 Address: 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR -
+ ??? child "`Resources` interface definition" + ```js + export interface Resources { + resources: { + requests?: { + memory?: string; + cpu?: string; + }; + limits?: { + memory?: string; + cpu?: string; + }; + }; + } + ``` -The `subkey` program assumes an address is based on a public/private key pair. If you inspect an address, the command returns the 32-byte account identifier. +- **`keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. +- **`validator`** ++"boolean"++: Pass the `--validator` flag to the command. Defaults to `true`. +- **`invulnerable`** ++"boolean"++: If true, add the node to invulnerables in the chain spec. Defaults to `false`. +- **`balance`** ++"number"++: Balance to set in balances for node's account. Defaults to `2000000000000`. +- **`bootnodes?`** ++"string[]"++: Array of bootnodes to use. +- **`add_to_bootnodes?`** ++"boolean"++: Add this node to the bootnode list. Defaults to `false`. +- **`ws_port?`** ++"number"++: WS port to use. +- **`rpc_port?`** ++"number"++: RPC port to use. +- **`prometheus_port?`** ++"number"++: Prometheus port to use. +- **`p2p_cert_hash?`** ++"string"++: Libp2p certhash to use with webRTC transport. +- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. -However, not all addresses in Polkadot SDK-based networks are based on keys. + ??? child "`DelayNetworkSettings` interface definition" + ```js + export interface DelayNetworkSettings { + latency: string; + correlation?: string; // should be parsable as float by k8s + jitter?: string; + } + ``` -Depending on the command-line options you specify and the input you provided, the command output might also display the network for which the address has been encoded. For example: +The following configuration file defines a minimal example for the relay chain, including the `nodes` key: -```bash -subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" -``` +=== "TOML" -The command displays output similar to the following: + ```toml title="relaychain-example-nodes.toml" + [relaychain] + default_command = "polkadot" + default_image = "polkadot-debug:master" + chain = "rococo-local" + chain_spec_path = "INSERT_PATH_TO_CHAIN_SPEC" + default_args = ["--chain", "rococo-local"] -
- subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" - Public Key URI `12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU` is account: - Network ID/Version: polkadot - Public key (hex): 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Account ID: 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Public key (SS58): 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU - SS58 Address: 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU -
+ [[relaychain.nodes]] + name = "alice" + validator = true + balance = 1000000000000 -#### Using Polkadot.js API + [[relaychain.nodes]] + name = "bob" + validator = true + balance = 1000000000000 + # ... -To verify an address in JavaScript or TypeScript projects, you can use the functions built into the [Polkadot.js API](https://polkadot.js.org/docs/){target=\_blank}. For example: + ``` -```js -// Import Polkadot.js API dependencies -const { decodeAddress, encodeAddress } = require('@polkadot/keyring'); -const { hexToU8a, isHex } = require('@polkadot/util'); +=== "JSON" -// Specify an address to test. -const address = 'INSERT_ADDRESS_TO_TEST'; + ```json title="relaychain-example-nodes.json" + { + "relaychain": { + "default_command": "polkadot", + "default_image": "polkadot-debug:master", + "chain": "rococo-local", + "chain_spec_path": "INSERT_PATH_TO_CHAIN-SPEC.JSON", + "default_args": ["--chain", "rococo-local"], + "nodes": [ + { + "name": "alice", + "validator": true, + "balance": 1000000000000 + }, + { + "name": "bob", + "validator": true, + "balance": 1000000000000 + } + ] + } + } -// Check address -const isValidSubstrateAddress = () => { - try { - encodeAddress(isHex(address) ? hexToU8a(address) : decodeAddress(address)); + ``` - return true; - } catch (error) { - return false; - } -}; +#### Node Group Configuration -// Query result -const isValid = isValidSubstrateAddress(); -console.log(isValid); +The `node_groups` key defines further parameters for the node groups. The available keys are: -``` +- **`name`** ++"string"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`). +- **`image?`** ++"string"++: Override default Docker image to use for this node. +- **`command?`** ++"string"++: Override default command to run. +- **`args?`** ++"string[]"++: Arguments to be passed to the command. +- **`env?`** ++"envVars[]"++: Environment variables to set in the container. + + ??? child "`envVars` interface definition" + ```js + export interface EnvVars { + name: string; + value: string; + } + ``` -If the function returns `true`, the specified address is a valid address. +- **`overrides?`** ++"Override[]"++: Array of overrides definitions. -#### Other SS58 Implementations + ??? child "`Override` interface definition" + ```js + export interface Override { + local_path: string; + remote_name: string; + } + ``` -Support for encoding and decoding Polkadot SDK SS58 addresses has been implemented in several other languages and libraries. +- **`prometheus_prefix?`** ++"string"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`. +- **`db_snapshot?`** ++"string"++: Database snapshot to use. +- **`substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead. -- **Crystal**: [`wyhaines/base58.cr`](https://github.com/wyhaines/base58.cr){target=\_blank} -- **Go**: [`itering/subscan-plugin`](https://github.com/itering/subscan-plugin){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **TypeScript**: [`subsquid/squid-sdk`](https://github.com/subsquid/squid-sdk){target=\_blank} + ??? child "`SubstrateCliArgsVersion` enum definition" + ```js + export enum SubstrateCliArgsVersion { + V0 = 0, + V1 = 1, + V2 = 2, + V3 = 3, + } + ``` +- **`resources?`** ++"Resources"++: Represent the resources limits/reservations needed by the node. ---- + ??? child "`Resources` interface definition" + ```js + export interface Resources { + resources: { + requests?: { + memory?: string; + cpu?: string; + }; + limits?: { + memory?: string; + cpu?: string; + }; + }; + } + ``` -Page Title: Randomness +- **`keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. +- **`count`** ++"number | string"++: Number of nodes to launch for this group. +- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-randomness.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/randomness/ -- Summary: Explore the importance of randomness in PoS blockchains, focusing on Polkadot’s VRF-based approach to ensure fairness and security in validator selection. + ??? child "`DelayNetworkSettings` interface definition" + ```js + export interface DelayNetworkSettings { + latency: string; + correlation?: string; // should be parsable as float by k8s + jitter?: string; + } + ``` -# Randomness +The following configuration file defines a minimal example for the relay chain, including the `node_groups` key: -## Introduction +=== "TOML" -Randomness is crucial in Proof of Stake (PoS) blockchains to ensure a fair and unpredictable distribution of validator duties. However, computers are inherently deterministic, meaning the same input always produces the same output. What we typically refer to as "random" numbers on a computer are actually pseudo-random. These numbers rely on an initial "seed," which can come from external sources like [atmospheric noise](https://www.random.org/randomness/){target=\_blank}, [heart rates](https://mdpi.altmetric.com/details/47574324){target=\_blank}, or even [lava lamps](https://en.wikipedia.org/wiki/Lavarand){target=\_blank}. While this may seem random, given the same "seed," the same sequence of numbers will always be generated. + ```toml title="relaychain-example-node-groups.toml" + [relaychain] + default_command = "polkadot" + default_image = "polkadot-debug:master" + chain = "rococo-local" + chain_spec_path = "INSERT_PATH_TO_CHAIN_SPEC" + default_args = ["--chain", "rococo-local"] -In a global blockchain network, relying on real-world entropy for randomness isn’t feasible because these inputs vary by time and location. If nodes use different inputs, blockchains can fork. Hence, real-world randomness isn't suitable for use as a seed in blockchain systems. + [[relaychain.node_groups]] + name = "group-1" + count = 2 + image = "polkadot-debug:master" + command = "polkadot" + args = ["--chain", "rococo-local"] + # ... -Currently, two primary methods for generating randomness in blockchains are used: [`RANDAO`](#randao) and [`VRF`](#vrf) (Verifiable Random Function). Polkadot adopts the `VRF` approach for its randomness. + ``` -## VRF +=== "JSON" -A Verifiable Random Function (VRF) is a cryptographic function that generates a random number and proof that ensures the submitter produced the number. This proof allows anyone to verify the validity of the random number. + ```json title="relaychain-example-node-groups.json" + { + "relaychain": { + "default_command": "polkadot", + "default_image": "polkadot-debug:master", + "chain": "rococo-local", + "chain_spec_path": "INSERT_PATH_TO_CHAIN-SPEC.JSON", + "default_args": ["--chain", "rococo-local"], + "node_groups": [ + { + "name": "group-1", + "count": 2, + "image": "polkadot-debug:master", + "command": "polkadot", + "args": ["--chain", "rococo-local"] + } + ], + "...": {} + }, + "...": {} + } -Polkadot's VRF is similar to the one used in [**Ouroboros Praos**](https://eprint.iacr.org/2017/573.pdf){target=\_blank}, which secures randomness for block production in systems like [BABE](/reference/polkadot-hub/consensus-and-security/pos-consensus/#block-production-babe){target=\_blank} (Polkadot’s block production mechanism). + ``` -The key difference is that Polkadot's VRF doesn’t rely on a central clock—avoiding the issue of whose clock to trust. Instead, it uses its own past results and slot numbers to simulate time and determine future outcomes. +### Parachain Configuration -### How VRF Works +The `parachain` keyword defines further parameters for the parachain. The available keys are: -Slots on Polkadot are discrete units of time, each lasting six seconds, and can potentially hold a block. Multiple slots form an epoch, with 2400 slots making up one four-hour epoch. +- **`id`** ++"number"++: The id to assign to this parachain. Must be unique. +- **`chain?`** ++"string"++: The chain name. +- **`force_decorator?`** ++"string"++: Force the use of a specific decorator. +- **`genesis?`** ++"JSON"++: The genesis configuration. +- **`balance?`** ++"number"++: Balance to set in balances for parachain's account. +- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. -In each slot, validators execute a "die roll" using a VRF. The VRF uses three inputs: + ??? child "`DelayNetworkSettings` interface definition" + ```js + export interface DelayNetworkSettings { + latency: string; + correlation?: string; // should be parsable as float by k8s + jitter?: string; + } + ``` -1. A "secret key," unique to each validator, is used for the die roll. -2. An epoch randomness value, derived from the hash of VRF outputs from blocks two epochs ago (N-2), so past randomness influences the current epoch (N). -3. The current slot number. +- **`add_to_genesis?`** ++"boolean"++: Flag to add parachain to genesis or register in runtime. Defaults to `true`. +- **`register_para?`** ++"boolean"++: Flag to specify whether the para should be registered. The `add_to_genesis` flag must be set to false for this flag to have any effect. Defaults to `true`. +- **`onboard_as_parachain?`** ++"boolean"++: Flag to specify whether the para should be onboarded as a parachain, rather than remaining a parathread. Defaults to `true`. +- **`genesis_wasm_path?`** ++"string"++: Path to the Wasm file to use. +- **`genesis_wasm_generator?`** ++"string"++: Command to generate the Wasm file. +- **`genesis_state_path?`** ++"string"++: Path to the state file to use. +- **`genesis_state_generator?`** ++"string"++: Command to generate the state file. +- **`chain_spec_path?`** ++"string"++: Path to the chain spec file. +- **`chain_spec_command?`** ++"string"++: Command to generate the chain spec. +- **`cumulus_based?`** ++"boolean"++: Flag to use cumulus command generation. Defaults to `true`. +- **`bootnodes?`** ++"string[]"++: Array of bootnodes to use. +- **`prometheus_prefix?`** ++"string"++: Parameter for customizing the metric's prefix for all parachain nodes/collators. Defaults to `substrate`. +- **`collator?`** ++"Collator"++: Further defined in the [Collator Configuration](#collator-configuration) section. +- **`collator_groups?`** ++"CollatorGroup[]"++: An array of collator groups to spawn. It is further defined in the [Collator Groups Configuration](#collator-groups-configuration) section. + +For example, the following configuration file defines a minimal example for the parachain: -This process helps maintain fair randomness across the network. +=== "TOML" -Here is a graphical representation: + ```toml title="parachain-example.toml" + [parachain] + id = 100 + add_to_genesis = true + cumulus_based = true + genesis_wasm_path = "INSERT_PATH_TO_WASM" + genesis_state_path = "INSERT_PATH_TO_STATE" + # ... -![](/images/reference/parachains/randomness/randomness-01.webp) + ``` -The VRF produces two outputs: a result (the random number) and a proof (verifying that the number was generated correctly). +=== "JSON" -The result is checked by the validator against a protocol threshold. If it's below the threshold, the validator becomes a candidate for block production in that slot. + ```json title="parachain-example.json" + { + "parachain": { + "id": 100, + "add_to_genesis": true, + "cumulus_based": true, + "genesis_wasm_path": "INSERT_PATH_TO_WASM", + "genesis_state_path": "INSERT_PATH_TO_STATE", + "...": {} + }, + "...": {} + } -The validator then attempts to create a block, submitting it along with the `PROOF` and `RESULT`. + ``` -So, VRF can be expressed like: +#### Collator Configuration -`(RESULT, PROOF) = VRF(SECRET, EPOCH_RANDOMNESS_VALUE, CURRENT_SLOT_NUMBER)` +One specific key capable of receiving more subkeys is the `collator` key. This key defines further parameters for the nodes. The available keys are: -Put simply, performing a "VRF roll" generates a random number along with proof that the number was genuinely produced and not arbitrarily chosen. +- **`name`** ++"string"++: Name of the collator. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`). +- **`image?`** ++"string"++: Image to use for the collator. +- **`command_with_args?`** ++"string"++: Overrides both command and arguments for the collator. +- **`validator`** ++"boolean"++: Pass the `--validator` flag to the command. Defaults to `true`. +- **`invulnerable`** ++"boolean"++: If true, add the collator to invulnerables in the chain spec. Defaults to `false`. +- **`balance`** ++"number"++: Balance to set in balances for collator's account. Defaults to `2000000000000`. +- **`bootnodes?`** ++"string[]"++: Array of bootnodes to use. +- **`add_to_bootnodes?`** ++"boolean"++: Add this collator to the bootnode list. Defaults to `false`. +- **`ws_port?`** ++"number"++: WS port to use. +- **`rpc_port?`** ++"number"++: RPC port to use. +- **`prometheus_port?`** ++"number"++: Prometheus port to use. +- **`p2p_port?`** ++"number"++: P2P port to use. +- **`p2p_cert_hash?`** ++"string"++: Libp2p certhash to use with webRTC transport. +- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. -After executing the VRF, the `RESULT` is compared to a protocol-defined `THRESHOLD`. If the `RESULT` is below the `THRESHOLD`, the validator becomes a valid candidate to propose a block for that slot. Otherwise, the validator skips the slot. + ??? child "`DelayNetworkSettings` interface definition" + ```js + export interface DelayNetworkSettings { + latency: string; + correlation?: string; // should be parsable as float by k8s + jitter?: string; + } + ``` -As a result, there may be multiple validators eligible to propose a block for a slot. In this case, the block accepted by other nodes will prevail, provided it is on the chain with the latest finalized block as determined by the GRANDPA finality gadget. It's also possible for no block producers to be available for a slot, in which case the AURA consensus takes over. AURA is a fallback mechanism that randomly selects a validator to produce a block, running in parallel with BABE and only stepping in when no block producers exist for a slot. Otherwise, it remains inactive. +- **`command?`** ++"string"++: Override default command to run. +- **`args?`** ++"string[]"++: Arguments to be passed to the command. +- **`env?`** ++"envVars[]"++: Environment variables to set in the container. -Because validators roll independently, no block candidates may appear in some slots if all roll numbers are above the threshold. + ??? child "`envVars` interface definition" + ```js + export interface EnvVars { + name: string; + value: string; + } + ``` -To verify resolution of this issue and that Polkadot block times remain near constant-time, see the [PoS Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} page of this documentation. +- **`overrides?`** ++"Override[]"++: Array of overrides definitions. -## RANDAO + ??? child "`Override` interface definition" + ```js + export interface Override { + local_path: string; + remote_name: string; + } + ``` -An alternative on-chain randomness method is Ethereum's RANDAO, where validators perform thousands of hashes on a seed and publish the final hash during a round. The collective input from all validators forms the random number, and as long as one honest validator participates, the randomness is secure. +- **`prometheus_prefix?`** ++"string"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`. +- **`db_snapshot?`** ++"string"++: Database snapshot to use. +- **`substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead. -To enhance security, RANDAO can optionally be combined with a Verifiable Delay Function (VDF), ensuring that randomness can't be predicted or manipulated during computation. + ??? child "`SubstrateCliArgsVersion` enum definition" + ```js + export enum SubstrateCliArgsVersion { + V0 = 0, + V1 = 1, + V2 = 2, + V3 = 3, + } + ``` -For more information about RANDAO, see the [Randomness - RANDAO](https://eth2book.info/capella/part2/building_blocks/randomness/){target=\_blank} section of the Upgrading Ethereum documentation. +- **`resources?`** ++"Resources"++: Represent the resources limits/reservations needed by the node. -## VDFs + ??? child "`Resources` interface definition" + ```js + export interface Resources { + resources: { + requests?: { + memory?: string; + cpu?: string; + }; + limits?: { + memory?: string; + cpu?: string; + }; + }; + } + ``` -Verifiable Delay Functions (VDFs) are time-bound computations that, even on parallel computers, take a set amount of time to complete. +- **`keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. -They produce a unique result that can be quickly verified publicly. When combined with RANDAO, feeding RANDAO's output into a VDF introduces a delay that nullifies an attacker's chance to influence the randomness. +The configuration file below defines a minimal example for the collator: -However, VDF likely requires specialized ASIC devices to run separately from standard nodes. +=== "TOML" -!!!warning - While only one is needed to secure the system, and they will be open-source and inexpensive, running VDF devices involves significant costs without direct incentives, adding friction for blockchain users. + ```toml title="collator-example.toml" + [parachain] + id = 100 + add_to_genesis = true + cumulus_based = true + genesis_wasm_path = "INSERT_PATH_TO_WASM" + genesis_state_path = "INSERT_PATH_TO_STATE" -## Additional Resources + [[parachain.collators]] + name = "alice" + image = "polkadot-parachain" + command = "polkadot-parachain" + # ... -For more information about the reasoning for choices made along with proofs, see Polkadot's research on blockchain randomness and sortition in the [Block production](https://research.web3.foundation/Polkadot/protocols/block-production){target=\_blank} entry of the Polkadot Wiki. + ``` -For a discussion with Web3 Foundation researchers about when and under what conditions Polkadot's randomness can be utilized, see the [Discussion on Randomness used in Polkadot](https://github.com/use-ink/ink/issues/57){target=\_blank} issue on GitHub. +=== "JSON" + ```json title="collator-example.json" + { + "parachain": { + "id": 100, + "add_to_genesis": true, + "cumulus_based": true, + "genesis_wasm_path": "INSERT_PATH_TO_WASM", + "genesis_state_path": "INSERT_PATH_TO_STATE", + "collators": [ + { + "name": "alice", + "image": "polkadot-parachain", + "command": "polkadot-parachain", + "...": {} + } + ] + }, + "...": {} + } ---- + ``` -Page Title: Register a Local Asset +#### Collator Groups Configuration -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-token-operations-register-local-asset.md -- Canonical (HTML): https://docs.polkadot.com/chain-interactions/token-operations/register-local-asset/ -- Summary: Comprehensive guide to registering a local asset on the Asset Hub system parachain, including step-by-step instructions. +The `collator_groups` key defines further parameters for the collator groups. The available keys are: -# Register a Local Asset on Asset Hub +- **`name`** ++"string"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`). +- **`image?`** ++"string"++: Override default Docker image to use for this node. +- **`command?`** ++"string"++: Override default command to run. +- **`args?`** ++"string[]"++: Arguments to be passed to the command. +- **`env?`** ++"envVars[]"++: Environment variables to set in the container. -## Introduction + ??? child "`envVars` interface definition" + ```js + export interface EnvVars { + name: string; + value: string; + } + ``` -As detailed in the [Asset Hub Overview](/polkadot-protocol/architecture/system-chains/asset-hub){target=\_blank} page, Asset Hub accommodates two types of assets: local and foreign. Local assets are those that were created in Asset Hub and are identifiable by an integer ID. On the other hand, foreign assets originate from a sibling parachain and are identified by a Multilocation. +- **`overrides?`** ++"Override[]"++: Array of overrides definitions. -This guide will take you through the steps of registering a local asset on the Asset Hub parachain. + ??? child "`Override` interface definition" + ```js + export interface Override { + local_path: string; + remote_name: string; + } + ``` -## Prerequisites +- **`prometheus_prefix?`** ++"string"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`. +- **`db_snapshot?`** ++"string"++: Database snapshot to use. +- **`substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead. -Before you begin, ensure you have access to the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and a funded wallet with DOT or KSM. + ??? child "`SubstrateCliArgsVersion` enum definition" + ```js + export enum SubstrateCliArgsVersion { + V0 = 0, + V1 = 1, + V2 = 2, + V3 = 3, + } + ``` -- For Polkadot Asset Hub, you would need a deposit of 10 DOT and around 0.201 DOT for the metadata. -- For Kusama Asset Hub, the deposit is 0.1 KSM and around 0.000669 KSM for the metadata. +- **`resources?`** ++"Resources"++: Represent the resources limits/reservations needed by the node. -You need to ensure that your Asset Hub account balance is a bit more than the sum of those two deposits, which should seamlessly account for the required deposits and transaction fees. + ??? child "`Resources` interface definition" + ```js + export interface Resources { + resources: { + requests?: { + memory?: string; + cpu?: string; + }; + limits?: { + memory?: string; + cpu?: string; + }; + }; + } + ``` -## Steps to Register a Local Asset +- **`keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. +- **`count`** ++"number | string"++: Number of nodes to launch for this group. +- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. -To register a local asset on the Asset Hub parachain, follow these steps: + ??? child "`DelayNetworkSettings` interface definition" + ```js + export interface DelayNetworkSettings { + latency: string; + correlation?: string; // should be parsable as float by k8s + jitter?: string; + } + ``` -1. Open the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and connect to the Asset Hub parachain using the network selector in the top left corner. +For instance, the configuration file below defines a minimal example for the collator groups: - - You may prefer to test local asset registration on TestNet before registering the asset on a MainNet hub. If you still need to set up a local testing environment, review the [Environment setup](#test-setup-environment) section for instructions. Once the local environment is set up, connect to the Local Node (Chopsticks) available on `ws://127.0.0.1:8000`. - - For the live network, connect to the **Asset Hub** parachain. Either Polkadot or Kusama Asset Hub can be selected from the dropdown list, choosing the desired RPC provider. +=== "TOML" -2. Click on the **Network** tab on the top navigation bar and select **Assets** from the dropdown list. + ```toml title="collator-groups-example.toml" + [parachain] + id = 100 + add_to_genesis = true + cumulus_based = true + genesis_wasm_path = "INSERT_PATH_TO_WASM" + genesis_state_path = "INSERT_PATH_TO_STATE" - ![Access to Asset Hub through Polkadot.JS](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-01.webp) + [[parachain.collator_groups]] + name = "group-1" + count = 2 + image = "polkadot-parachain" + command = "polkadot-parachain" + # ... -3. Now, you need to examine all the registered asset IDs. This step is crucial to ensure that the asset ID you are about to register is unique. Asset IDs are displayed in the **assets** column. + ``` - ![Asset IDs on Asset Hub](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-02.webp) +=== "JSON" -4. Once you have confirmed that the asset ID is unique, click on the **Create** button on the top right corner of the page. + ```json title="collator-groups-example.json" + { + "parachain": { + "id": 100, + "add_to_genesis": true, + "cumulus_based": true, + "genesis_wasm_path": "INSERT_PATH_TO_WASM", + "genesis_state_path": "INSERT_PATH_TO_STATE", + "collator_groups": [ + { + "name": "group-1", + "count": 2, + "image": "polkadot-parachain", + "command": "polkadot-parachain", + "...": {} + } + ] + }, + "...": {} + } - ![Create a new asset](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-03.webp) + ``` -5. Fill in the required fields in the **Create Asset** form: +### XCM Configuration - 1. **creator account**: The account to be used for creating this asset and setting up the initial metadata. - 2. **asset name**: The descriptive name of the asset you are registering. - 3. **asset symbol**: The symbol that will be used to represent the asset. - 4. **asset decimals**: The number of decimal places for this token, with a maximum of 20 allowed through the user interface. - 5. **minimum balance**: The minimum balance for the asset. This is specified in the units and decimals as requested. - 6. **asset ID**: The selected id for the asset. This should not match an already-existing asset id. - 7. Click on the **Next** button. - - ![Create Asset Form](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-04.webp) +You can use the `hrmp_channels` keyword to define further parameters for the XCM channels at start-up. The available keys are: -6. Choose the accounts for the roles listed below: +- **`hrmp_channels`** ++"HrmpChannelsConfig[]"++: Array of Horizontal Relay-routed Message Passing (HRMP) channel configurations. - 1. **admin account**: The account designated for continuous administration of the token. - 2. **issuer account**: The account that will be used for issuing this token. - 3. **freezer account**: The account that will be used for performing token freezing operations. - 4. Click on the **Create** button. + ??? child "`HrmpChannelsConfig` interface definition" + ```js + export interface HrmpChannelsConfig { + sender: number; + recipient: number; + max_capacity: number; + max_message_size: number; + } + ``` + Each of the `HrmpChannelsConfig` keys are defined as follows: - ![Admin, Issuer, Freezer accounts](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-05.webp) + - **`sender` ++"number"++**: Parachain ID of the sender. + - **`recipient` ++"number"++**: Parachain ID of the recipient. + - **`max_capacity` ++"number"++**: Maximum capacity of the HRMP channel. + - **`max_message_size` ++"number"++**: Maximum message size allowed in the HRMP channel. -7. Click on the **Sign and Submit** button to complete the asset registration process. +## Where to Go Next - ![Sign and Submit](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-06.webp) +
-## Verify Asset Registration +- External __Zombienet Support__ -After completing these steps, the asset will be successfully registered. You can now view your asset listed on the [**Assets**](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fasset-hub-polkadot-rpc.dwellir.com#/assets){target=\_blank} section of the Polkadot.js Apps interface. + --- -![Asset listed on Polkadot.js Apps](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-07.webp) + [Parity Technologies](https://www.parity.io/){target=\_blank} has designed and developed this framework, now maintained by the Zombienet team. -!!! tip - Take into consideration that the **Assets** section’s link may differ depending on the network you are using. For the local environment, enter `ws://127.0.0.1:8000` into the **Custom Endpoint** field. + For further support and information, refer to the following contact points: -In this way, you have successfully registered a local asset on the Asset Hub parachain. + [:octicons-arrow-right-24: Zombienet repository](https://github.com/paritytech/zombienet){target=\_blank} -For an in-depth explanation about Asset Hub and its features, see the [Asset Hub](/chain-interactions/token-operations/convert-assets/){target=\_blank} entry in the Polkadot Wiki. + [:octicons-arrow-right-24: Element public channel](https://matrix.to/#/!FWyuEyNvIFygLnWNMh:parity.io?via=parity.io&via=matrix.org&via=web3.foundation){target=\_blank} -## Test Setup Environment -You can set up a local parachain environment to test the asset registration process before deploying it on the live network. This guide uses Chopsticks to simulate that process. For further information on chopsticks usage, refer to the [Chopsticks](/develop/toolkit/parachains/fork-chains/chopsticks/get-started){target=\_blank} documentation. +- Tutorial __Spawn a Basic Chain with Zombienet__ -To set up a test environment, execute the following command: + --- -```bash -npx @acala-network/chopsticks \ ---config=https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/polkadot-asset-hub.yml -``` + Learn to spawn, connect to and monitor a basic blockchain network with Zombienet, using customizable configurations for streamlined development and debugging. -The above command will spawn a lazy fork of Polkadot Asset Hub with the latest block data from the network. If you need to test Kusama Asset Hub, replace `polkadot-asset-hub.yml` with `kusama-asset-hub.yml` in the command. + [:octicons-arrow-right-24: Reference](/tutorials/polkadot-sdk/testing/spawn-basic-chain/) -An Asset Hub instance is now running locally, and you can proceed with the asset registration process. Note that the local registration process does not differ from the live network process. Once you have a successful TestNet transaction, you can use the same steps to register the asset on MainNet. +
--- @@ -11471,480 +8544,88 @@ Examine the following migration example that transforms a simple `StorageValue` /// [`VersionedMigration`](frame_support::migrations::VersionedMigration), which ensures that: /// - The migration only runs once when the on-chain storage version is 0 /// - The on-chain storage version is updated to `1` after the migration executes - /// - Reads/Writes from checking/settings the on-chain storage version are accounted for - pub type MigrateV0ToV1 = frame_support::migrations::VersionedMigration< - 0, // The migration will only execute when the on-chain storage version is 0 - 1, // The on-chain storage version will be set to 1 after the migration is complete - InnerMigrateV0ToV1, - crate::pallet::Pallet, - ::DbWeight, - >; - ``` - -### Migration Organization - -Best practices recommend organizing migrations in a separate module within your pallet. Here's the recommended file structure: - -```plain -my-pallet/ -├── src/ -│ ├── lib.rs # Main pallet implementation -│ └── migrations/ # All migration-related code -│ ├── mod.rs # Migrations module definition -│ ├── v1.rs # V0 -> V1 migration -│ └── v2.rs # V1 -> V2 migration -└── Cargo.toml -``` - -This structure provides several benefits: - -- Separates migration logic from core pallet functionality. -- Makes migrations easier to test and maintain. -- Provides explicit versioning of storage changes. -- Simplifies the addition of future migrations. - -### Scheduling Migrations - -To execute migrations during a runtime upgrade, you must configure them in your runtime's Executive pallet. Add your migrations in `runtime/src/lib.rs`: - -```rust -/// Tuple of migrations (structs that implement `OnRuntimeUpgrade`) -type Migrations = ( - pallet_my_pallet::migrations::v1::Migration, - // More migrations can be added here -); -pub type Executive = frame_executive::Executive< - Runtime, - Block, - frame_system::ChainContext, - Runtime, - AllPalletsWithSystem, - Migrations, // Include migrations here ->; - -``` - -## Single-Block Migrations - -Single-block migrations execute their logic within one block immediately following a runtime upgrade. They run as part of the runtime upgrade process through the `OnRuntimeUpgrade` trait implementation and must be completed before any other runtime logic executes. - -While single-block migrations are straightforward to implement and provide immediate data transformation, they carry significant risks. The most critical consideration is that they must complete within one block's weight limits. This is especially crucial for parachains, where exceeding block weight limits will brick the chain. - -Use single-block migrations only when you can guarantee: - -- The migration has a bounded execution time. -- Weight calculations are thoroughly tested. -- Total weight will never exceed block limits. - -For a complete implementation example of a single-block migration, refer to the [single-block migration example]( https://paritytech.github.io/polkadot-sdk/master/pallet_example_single_block_migrations/index.html){target=\_blank} in the Polkadot SDK documentation. - -## Multi Block Migrations - -Multi-block migrations distribute the migration workload across multiple blocks, providing a safer approach for production environments. The migration state is tracked in storage, allowing the process to pause and resume across blocks. - -This approach is essential for production networks and parachains as the risk of exceeding block weight limits is eliminated. Multi-block migrations can safely handle large storage collections, unbounded data structures, and complex nested data types where weight consumption might be unpredictable. - -Multi-block migrations are ideal when dealing with: - -- Large-scale storage migrations. -- Unbounded storage items or collections. -- Complex data structures with uncertain weight costs. - -The primary trade-off is increased implementation complexity, as you must manage the migration state and handle partial completion scenarios. However, multi-block migrations' significant safety benefits and operational reliability are typically worth the increased complexity. - -For a complete implementation example of multi-block migrations, refer to the [official example](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/examples/multi-block-migrations){target=\_blank} in the Polkadot SDK. - - ---- - -Page Title: Technical Reference Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference.md -- Canonical (HTML): https://docs.polkadot.com/reference/ -- Summary: Learn about Polkadot's technical architecture, governance framework, parachain ecosystem, and the tools you need to build and interact with the network. - -## Introduction - -The Technical Reference section provides comprehensive documentation of Polkadot's architecture, core concepts, and development tooling. Whether you're exploring how Polkadot's relay chain coordinates parachains, understanding governance mechanisms, or building applications on the network, this reference covers the technical foundations you need. - -Polkadot is a multi-chain network that enables diverse, interconnected blockchains to share security and communicate seamlessly. Understanding how these components interact from the [relay chain](/polkadot-protocol/glossary#relay-chain){target=\_blank} that validates [parachains](/polkadot-protocol/glossary#parachain){target=\_blank} to the [governance](/reference/glossary#governance){target=\_blank} mechanisms that evolve the protocol is essential for developers, validators, and network participants. - -This guide organizes technical documentation across five core areas: Polkadot Hub, Parachains, On-Chain Governance, Glossary, and Tools, each providing detailed information on different aspects of the Polkadot ecosystem. - -## Polkadot Hub - -[Polkadot Hub](/reference/polkadot-hub/){target=\_blank} is the entry point to Polkadot for all users and application developers. It provides access to essential Web3 services, including smart contracts, staking, governance, identity management, and cross-ecosystem interoperability—without requiring you to deploy or manage a parachain. - -The Hub encompasses a set of core functionality that enables developers and users to build and interact with applications on Polkadot. Key capabilities include: - -- **Smart contracts**: Deploy Ethereum-compatible smart contracts and build decentralized applications. -- **Assets and tokens**: Create, manage, and transfer fungible tokens and NFTs across the ecosystem. -- **Staking**: Participate in network security and earn rewards by staking DOT. -- **Governance**: Vote on proposals and participate in Polkadot's decentralized decision-making through OpenGov. -- **Identity services**: Register and manage on-chain identities, enabling access to governance roles and network opportunities. -- **Cross-chain interoperability**: Leverage XCM messaging to interact securely with other chains in the Polkadot ecosystem. -- **Collectives and DAOs**: Participate in governance collectives and decentralized autonomous organizations. - -## Parachains - -[Parachains](/reference/parachains/){target=\_blank} are specialized blockchains that connect to the Polkadot relay chain, inheriting its security while maintaining their own application-specific logic. The parachains documentation covers: - -- **Accounts**: Deep dive into account types, storage, and management on parachains. -- **Blocks, transactions and fees**: Understand block production, transaction inclusion, and fee mechanisms. -- **Consensus**: Learn how parachain blocks are validated and finalized through the relay chain's consensus. -- **Chain data**: Explore data structures, storage layouts, and state management. -- **Cryptography**: Study cryptographic primitives used in Polkadot SDK-based chains. -- **Data encoding**: Understand how data is encoded and decoded for blockchain compatibility. -- **Networks**: Learn about networking protocols and peer-to-peer communication. -- **Interoperability**: Discover [Cross-Consensus Messaging (XCM)](/parachains/interoperability/get-started/){target=\_blank}, the standard for cross-chain communication. -- **Randomness**: Understand how randomness is generated and used in Polkadot chains. -- **Node and runtime**: Learn about parachain nodes, runtime environments, and the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}. - -## On-Chain Governance - -[On-Chain governance](/reference/governance/){target=\_blank} is the decentralized decision-making mechanism for the Polkadot network. It manages the evolution and modification of the network's runtime logic, enabling community oversight and approval for proposed changes. The governance documentation details: - -- **OpenGov framework**: Understand Polkadot's next-generation governance system with enhanced delegation, flexible tracks, and simultaneous referendums. -- **Origins and tracks**: Learn how governance proposals are categorized, prioritized, and executed based on their privilege level and complexity. -- **Voting and delegation**: Explore conviction voting, vote delegation, and how token holders participate in governance. -- **Governance evolution**: See how Polkadot's governance has evolved from Governance V1 to the current OpenGov system. - -## Glossary - -The [Glossary](/reference/glossary/){target=\_blank} provides quick-reference definitions for Polkadot-specific terminology. Essential terms include: - -- Blockchain concepts (blocks, transactions, state) -- Consensus mechanisms (validators, collators, finality) -- Polkadot-specific terms (relay chain, parachain, XCM, FRAME) -- Network components (nodes, runtimes, storage) -- Governance terminology (origins, tracks, referendums) - -## Tools - -The [Tools](/reference/tools/){target=\_blank} section documents essential development and interaction tools for the Polkadot ecosystem: - -- **Light clients**: Lightweight solutions for interacting with the network without running full nodes. -- **JavaScript/TypeScript tools**: Libraries like [Polkadot.js API](/reference/tools/polkadot-js-api/){target=\_blank} and [PAPI](/reference/tools/papi/){target=\_blank} for building applications. -- **Rust tools**: [Polkadart](/reference/tools/polkadart/){target=\_blank} and other Rust-based libraries for SDK development. -- **Python tools**: [py-substrate-interface](/reference/tools/py-substrate-interface/){target=\_blank} for Python developers. -- **Testing and development**: Tools like [Moonwall](/reference/tools/moonwall/){target=\_blank}, [Chopsticks](/reference/tools/chopsticks/){target=\_blank}, and [Omninode](/reference/tools/omninode/){target=\_blank} for smart contract and parachain testing. -- **Indexing and monitoring**: [Sidecar](/reference/tools/sidecar/){target=\_blank} for data indexing and [Dedot](/reference/tools/dedot/){target=\_blank} for substrate interaction. -- **Cross-chain tools**: [ParaSpell](/reference/tools/paraspell/){target=\_blank} for XCM integration and asset transfers. - -## Where to Go Next - -For detailed exploration of specific areas, proceed to any of the main sections: - -
- -- Learn **Polkadot Hub** - - --- - - Understand the relay chain's role in coordinating parachains, providing shared security, and enabling governance. - - [:octicons-arrow-right-24: Reference](/reference/polkadot-hub/) - -- Learn **Parachains** - - --- - - Deep dive into parachain architecture, consensus, data structures, and building application-specific blockchains. - - [:octicons-arrow-right-24: Reference](/reference/parachains/) - -- Learn **On-Chain Governance** - - --- - - Explore Polkadot's decentralized governance framework and how to participate in network decision-making. - - [:octicons-arrow-right-24: Reference](/reference/governance/) - -- Guide **Glossary** - - --- - - Quick reference for Polkadot-specific terminology and concepts used throughout the documentation. - - [:octicons-arrow-right-24: Reference](/reference/glossary/) - -- Guide **Tools** - - --- - - Discover development tools, libraries, and frameworks for building and interacting with Polkadot. - - [:octicons-arrow-right-24: Reference](/reference/tools/) - -
- - ---- - -Page Title: Transactions - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-transactions.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/transactions/ -- Summary: Learn how to construct, submit, and validate transactions in the Polkadot SDK, covering signed, unsigned, and inherent types of transactions. - -# Transactions - -## Introduction - -Transactions are essential components of blockchain networks, enabling state changes and the execution of key operations. In the Polkadot SDK, transactions, often called extrinsics, come in multiple forms, including signed, unsigned, and inherent transactions. - -This guide walks you through the different transaction types and how they're formatted, validated, and processed within the Polkadot ecosystem. You'll also learn how to customize transaction formats and construct transactions for FRAME-based runtimes, ensuring a complete understanding of how transactions are built and executed in Polkadot SDK-based chains. - -## What Is a Transaction? - -In the Polkadot SDK, transactions represent operations that modify the chain's state, bundled into blocks for execution. The term extrinsic is often used to refer to any data that originates outside the runtime and is included in the chain. While other blockchain systems typically refer to these operations as "transactions," the Polkadot SDK adopts the broader term "extrinsic" to capture the wide variety of data types that can be added to a block. - -There are three primary types of transactions (extrinsics) in the Polkadot SDK: - -- **Signed transactions**: Signed by the submitting account, often carrying transaction fees. -- **Unsigned transactions**: Submitted without a signature, often requiring custom validation logic. -- **Inherent transactions**: Typically inserted directly into blocks by block authoring nodes, without gossiping between peers. - -Each type serves a distinct purpose, and understanding when and how to use each is key to efficiently working with the Polkadot SDK. - -### Signed Transactions - -Signed transactions require an account's signature and typically involve submitting a request to execute a runtime call. The signature serves as a form of cryptographic proof that the sender has authorized the action, using their private key. These transactions often involve a transaction fee to cover the cost of execution and incentivize block producers. - -Signed transactions are the most common type of transaction and are integral to user-driven actions, such as token transfers. For instance, when you transfer tokens from one account to another, the sending account must sign the transaction to authorize the operation. - -For example, the [`pallet_balances::Call::transfer_allow_death`](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/pallet/struct.Pallet.html#method.transfer_allow_death){target=\_blank} extrinsic in the Balances pallet allows you to transfer tokens. Since your account initiates this transaction, your account key is used to sign it. You'll also be responsible for paying the associated transaction fee, with the option to include an additional tip to incentivize faster inclusion in the block. - -### Unsigned Transactions - -Unsigned transactions do not require a signature or account-specific data from the sender. Unlike signed transactions, they do not come with any form of economic deterrent, such as fees, which makes them susceptible to spam or replay attacks. Custom validation logic must be implemented to mitigate these risks and ensure these transactions are secure. - -Unsigned transactions typically involve scenarios where including a fee or signature is unnecessary or counterproductive. However, due to the absence of fees, they require careful validation to protect the network. For example, [`pallet_im_online::Call::heartbeat`](https://paritytech.github.io/polkadot-sdk/master/pallet_im_online/pallet/struct.Pallet.html#method.heartbeat){target=\_blank} extrinsic allows validators to send a heartbeat signal, indicating they are active. Since only validators can make this call, the logic embedded in the transaction ensures that the sender is a validator, making the need for a signature or fee redundant. - -Unsigned transactions are more resource-intensive than signed ones because custom validation is required, but they play a crucial role in certain operational scenarios, especially when regular user accounts aren't involved. - -### Inherent Transactions - -Inherent transactions are a specialized type of unsigned transaction that is used primarily for block authoring. Unlike signed or other unsigned transactions, inherent transactions are added directly by block producers and are not broadcasted to the network or stored in the transaction queue. They don't require signatures or the usual validation steps and are generally used to insert system-critical data directly into blocks. - -A key example of an inherent transaction is inserting a timestamp into each block. The [`pallet_timestamp::Call::now`](https://paritytech.github.io/polkadot-sdk/master/pallet_timestamp/pallet/struct.Pallet.html#method.now-1){target=\_blank} extrinsic allows block authors to include the current time in the block they are producing. Since the block producer adds this information, there is no need for transaction validation, like signature verification. The validation in this case is done indirectly by the validators, who check whether the timestamp is within an acceptable range before finalizing the block. - -Another example is the [`paras_inherent::Call::enter`](https://paritytech.github.io/polkadot-sdk/master/polkadot_runtime_parachains/paras_inherent/pallet/struct.Pallet.html#method.enter){target=\_blank} extrinsic, which enables parachain collator nodes to send validation data to the relay chain. This inherent transaction ensures that the necessary parachain data is included in each block without the overhead of gossiped transactions. - -Inherent transactions serve a critical role in block authoring by allowing important operational data to be added directly to the chain without needing the validation processes required for standard transactions. - -## Transaction Formats - -Understanding the structure of signed and unsigned transactions is crucial for developers building on Polkadot SDK-based chains. Whether you're optimizing transaction processing, customizing formats, or interacting with the transaction pool, knowing the format of extrinsics, Polkadot's term for transactions, is essential. - -### Types of Transaction Formats - -In Polkadot SDK-based chains, extrinsics can fall into three main categories: - -- **Unchecked extrinsics**: Typically used for signed transactions that require validation. They contain a signature and additional data, such as a nonce and information for fee calculation. Unchecked extrinsics are named as such because they require validation checks before being accepted into the transaction pool. -- **Checked extrinsics**: Typically used for inherent extrinsics (unsigned transactions); these don't require signature verification. Instead, they carry information such as where the extrinsic originates and any additional data required for the block authoring process. -- **Opaque extrinsics**: Used when the format of an extrinsic is not yet fully committed or finalized. They are still decodable, but their structure can be flexible depending on the context. - -### Signed Transaction Data Structure - -A signed transaction typically includes the following components: - -- **Signature**: Verifies the authenticity of the transaction sender. -- **Call**: The actual function or method call the transaction is requesting (for example, transferring funds). -- **Nonce**: Tracks the number of prior transactions sent from the account, helping to prevent replay attacks. -- **Tip**: An optional incentive to prioritize the transaction in block inclusion. -- **Additional data**: Includes details such as spec version, block hash, and genesis hash to ensure the transaction is valid within the correct runtime and chain context. - -Here's a simplified breakdown of how signed transactions are typically constructed in a Polkadot SDK runtime: - -``` code - + + -``` - -Each part of the signed transaction has a purpose, ensuring the transaction's authenticity and context within the blockchain. - -### Signed Extensions - -Polkadot SDK also provides the concept of [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}, which allow developers to extend extrinsics with additional data or validation logic before they are included in a block. The [`SignedExtension`](https://paritytech.github.io/try-runtime-cli/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} set helps enforce custom rules or protections, such as ensuring the transaction's validity or calculating priority. - -The transaction queue regularly calls signed extensions to verify a transaction's validity before placing it in the ready queue. This safeguard ensures transactions won't fail in a block. Signed extensions are commonly used to enforce validation logic and protect the transaction pool from spam and replay attacks. - -In FRAME, a signed extension can hold any of the following types by default: - -- **[`AccountId`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/runtime/types_common/type.AccountId.html){target=\_blank}**: To encode the sender's identity. -- **[`Call`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Call){target=\_blank}**: To encode the pallet call to be dispatched. This data is used to calculate transaction fees. -- **[`AdditionalSigned`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.AdditionalSigned){target=\_blank}**: To handle any additional data to go into the signed payload allowing you to attach any custom logic prior to dispatching a transaction. -- **[`Pre`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Pre){target=\_blank}**: To encode the information that can be passed from before a call is dispatched to after it gets dispatched. - -Signed extensions can enforce checks like: - -- **[`CheckSpecVersion`](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/extensions/check_spec_version.rs.html){target=\_blank}**: Ensures the transaction is compatible with the runtime's current version. -- **[`CheckWeight`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.CheckWeight.html){target=\_blank}**: Calculates the weight (or computational cost) of the transaction, ensuring the block doesn't exceed the maximum allowed weight. - -These extensions are critical in the transaction lifecycle, ensuring that only valid and prioritized transactions are processed. - -## Transaction Construction - -Building transactions in the Polkadot SDK involves constructing a payload that can be verified, signed, and submitted for inclusion in a block. Each runtime in the Polkadot SDK has its own rules for validating and executing transactions, but there are common patterns for constructing a signed transaction. - -### Construct a Signed Transaction - -A signed transaction in the Polkadot SDK includes various pieces of data to ensure security, prevent replay attacks, and prioritize processing. Here's an overview of how to construct one: - -1. **Construct the unsigned payload**: Gather the necessary information for the call, including: - - - **Pallet index**: Identifies the pallet where the runtime function resides. - - **Function index**: Specifies the particular function to call in the pallet. - - **Parameters**: Any additional arguments required by the function call. - -2. **Create a signing payload**: Once the unsigned payload is ready, additional data must be included: - - - **Transaction nonce**: Unique identifier to prevent replay attacks. - - **Era information**: Defines how long the transaction is valid before it's dropped from the pool. - - **Block hash**: Ensures the transaction doesn't execute on the wrong chain or fork. - -3. **Sign the payload**: Using the sender's private key, sign the payload to ensure that the transaction can only be executed by the account holder. -4. **Serialize the signed payload**: Once signed, the transaction must be serialized into a binary format, ensuring the data is compact and easy to transmit over the network. -5. **Submit the serialized transaction**: Finally, submit the serialized transaction to the network, where it will enter the transaction pool and wait for processing by an authoring node. - -The following is an example of how a signed transaction might look: - -``` rust -node_runtime::UncheckedExtrinsic::new_signed( - function.clone(), // some call - sp_runtime::AccountId32::from(sender.public()).into(), // some sending account - node_runtime::Signature::Sr25519(signature.clone()), // the account's signature - extra.clone(), // the signed extensions -) -``` - -### Transaction Encoding - -Before a transaction is sent to the network, it is serialized and encoded using a structured encoding process that ensures consistency and prevents tampering: - -- **`[1]`**: Compact encoded length in bytes of the entire transaction. -- **`[2]`**: A u8 containing 1 byte to indicate whether the transaction is signed or unsigned (1 bit) and the encoded transaction version ID (7 bits). -- **`[3]`**: If signed, this field contains an account ID, an SR25519 signature, and some extra data. -- **`[4]`**: Encoded call data, including pallet and function indices and any required arguments. - -This encoded format ensures consistency and efficiency in processing transactions across the network. By adhering to this format, applications can construct valid transactions and pass them to the network for execution. - -To learn more about how compact encoding works using SCALE, see the [SCALE Codec](https://github.com/paritytech/parity-scale-codec){target=\_blank} README on GitHub. - -### Customize Transaction Construction - -Although the basic steps for constructing transactions are consistent across Polkadot SDK-based chains, developers can customize transaction formats and validation rules. For example: - -- **Custom pallets**: You can define new pallets with custom function calls, each with its own parameters and validation logic. -- **Signed extensions**: Developers can implement custom extensions that modify how transactions are prioritized, validated, or included in blocks. - -By leveraging Polkadot SDK's modular design, developers can create highly specialized transaction logic tailored to their chain's needs. - -## Lifecycle of a Transaction - -In the Polkadot SDK, transactions are often referred to as extrinsics because the data in transactions originates outside of the runtime. These transactions contain data that initiates changes to the chain state. The most common type of extrinsic is a signed transaction, which is cryptographically verified and typically incurs a fee. This section focuses on how signed transactions are processed, validated, and ultimately included in a block. - -### Define Transaction Properties - -The Polkadot SDK runtime defines key transaction properties, such as: - -- **Transaction validity**: Ensures the transaction meets all runtime requirements. -- **Signed or unsigned**: Identifies whether a transaction needs to be signed by an account. -- **State changes**: Determines how the transaction modifies the state of the chain. - -Pallets, which compose the runtime's logic, define the specific transactions that your chain supports. When a user submits a transaction, such as a token transfer, it becomes a signed transaction, verified by the user's account signature. If the account has enough funds to cover fees, the transaction is executed, and the chain's state is updated accordingly. - -### Process on a Block Authoring Node - -In Polkadot SDK-based networks, some nodes are authorized to author blocks. These nodes validate and process transactions. When a transaction is sent to a node that can produce blocks, it undergoes a lifecycle that involves several stages, including validation and execution. Non-authoring nodes gossip the transaction across the network until an authoring node receives it. The following diagram illustrates the lifecycle of a transaction that's submitted to a network and processed by an authoring node. - -![Transaction lifecycle diagram](/images/reference/parachains/blocks-transactions-fees/transactions/transactions-01.webp){ style="background:white" } - -### Validate and Queue - -Once a transaction reaches an authoring node, it undergoes an initial validation process to ensure it meets specific conditions defined in the runtime. This validation includes checks for: - -- **Correct nonce**: Ensures the transaction is sequentially valid for the account. -- **Sufficient funds**: Confirms the account can cover any associated transaction fees. -- **Signature validity**: Verifies that the sender's signature matches the transaction data. - -After these checks, valid transactions are placed in the transaction pool, where they are queued for inclusion in a block. The transaction pool regularly re-validates queued transactions to ensure they remain valid before being processed. To reach consensus, two-thirds of the nodes must agree on the order of the transactions executed and the resulting state change. Transactions are validated and queued on the local node in a transaction pool to prepare for consensus. - -#### Transaction Pool - -The transaction pool is responsible for managing valid transactions. It ensures that only transactions that pass initial validity checks are queued. Transactions that fail validation, expire, or become invalid for other reasons are removed from the pool. - -The transaction pool organizes transactions into two queues: - -- **Ready queue**: Transactions that are valid and ready to be included in a block. -- **Future queue**: Transactions that are not yet valid but could be in the future, such as transactions with a nonce too high for the current state. - -Details on how the transaction pool validates transactions, including fee and signature handling, can be found in the [`validate_transaction`](https://paritytech.github.io/polkadot-sdk/master/sp_transaction_pool/runtime_api/trait.TaggedTransactionQueue.html#method.validate_transaction){target=\_blank} method. - -#### Invalid Transactions - -If a transaction is invalid, for example, due to an invalid signature or insufficient funds, it is rejected and won't be added to the block. Invalid transactions might be rejected for reasons such as: - -- The transaction has already been included in a block. -- The transaction's signature does not match the sender. -- The transaction is too large to fit in the current block. - -### Transaction Ordering and Priority - -When a node is selected as the next block author, it prioritizes transactions based on weight, length, and tip amount. The goal is to fill the block with high-priority transactions without exceeding its maximum size or computational limits. Transactions are ordered as follows: + /// - Reads/Writes from checking/settings the on-chain storage version are accounted for + pub type MigrateV0ToV1 = frame_support::migrations::VersionedMigration< + 0, // The migration will only execute when the on-chain storage version is 0 + 1, // The on-chain storage version will be set to 1 after the migration is complete + InnerMigrateV0ToV1, + crate::pallet::Pallet, + ::DbWeight, + >; + ``` -- **Inherents first**: Inherent transactions, such as block timestamp updates, are always placed first. -- **Nonce-based ordering**: Transactions from the same account are ordered by their nonce. -- **Fee-based ordering**: Among transactions with the same nonce or priority level, those with higher fees are prioritized. +### Migration Organization -### Transaction Execution +Best practices recommend organizing migrations in a separate module within your pallet. Here's the recommended file structure: -Once a block author selects transactions from the pool, the transactions are executed in priority order. As each transaction is processed, the state changes are written directly to the chain's storage. It's important to note that these changes are not cached, meaning a failed transaction won't revert earlier state changes, which could leave the block in an inconsistent state. +```plain +my-pallet/ +├── src/ +│ ├── lib.rs # Main pallet implementation +│ └── migrations/ # All migration-related code +│ ├── mod.rs # Migrations module definition +│ ├── v1.rs # V0 -> V1 migration +│ └── v2.rs # V1 -> V2 migration +└── Cargo.toml +``` -Events are also written to storage. Runtime logic should not emit an event before performing the associated actions. If the associated transaction fails after the event was emitted, the event will not revert. +This structure provides several benefits: -## Transaction Mortality +- Separates migration logic from core pallet functionality. +- Makes migrations easier to test and maintain. +- Provides explicit versioning of storage changes. +- Simplifies the addition of future migrations. -Transactions in the network can be configured as either mortal (with expiration) or immortal (without expiration). Every transaction payload contains a block checkpoint (reference block number and hash) and an era/validity period that determines how many blocks after the checkpoint the transaction remains valid. +### Scheduling Migrations -When a transaction is submitted, the network validates it against these parameters. If the transaction is not included in a block within the specified validity window, it is automatically removed from the transaction queue. +To execute migrations during a runtime upgrade, you must configure them in your runtime's Executive pallet. Add your migrations in `runtime/src/lib.rs`: -- **Mortal transactions**: Have a finite lifespan and will expire after a specified number of blocks. For example, a transaction with a block checkpoint of 1000 and a validity period of 64 blocks will be valid from blocks 1000 to 1064. +```rust +/// Tuple of migrations (structs that implement `OnRuntimeUpgrade`) +type Migrations = ( + pallet_my_pallet::migrations::v1::Migration, + // More migrations can be added here +); +pub type Executive = frame_executive::Executive< + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsWithSystem, + Migrations, // Include migrations here +>; -- **Immortal transactions**: Never expire and remain valid indefinitely. To create an immortal transaction, set the block checkpoint to 0 (genesis block), use the genesis hash as a reference, and set the validity period to 0. +``` -However, immortal transactions pose significant security risks through replay attacks. If an account is reaped (balance drops to zero, account removed) and later re-funded, malicious actors can replay old immortal transactions. +## Single-Block Migrations -The blockchain maintains only a limited number of prior block hashes for reference validation, called `BlockHashCount`. If your validity period exceeds `BlockHashCount`, the effective validity period becomes the minimum of your specified period and the block hash count. +Single-block migrations execute their logic within one block immediately following a runtime upgrade. They run as part of the runtime upgrade process through the `OnRuntimeUpgrade` trait implementation and must be completed before any other runtime logic executes. -## Unique Identifiers for Extrinsics +While single-block migrations are straightforward to implement and provide immediate data transformation, they carry significant risks. The most critical consideration is that they must complete within one block's weight limits. This is especially crucial for parachains, where exceeding block weight limits will brick the chain. -Transaction hashes are **not unique identifiers** in Polkadot SDK-based chains. +Use single-block migrations only when you can guarantee: -Key differences from traditional blockchains: +- The migration has a bounded execution time. +- Weight calculations are thoroughly tested. +- Total weight will never exceed block limits. -- Transaction hashes serve only as fingerprints of transaction information. -- Multiple valid transactions can share the same hash. -- Hash uniqueness assumptions lead to serious issues. +For a complete implementation example of a single-block migration, refer to the [single-block migration example]( https://paritytech.github.io/polkadot-sdk/master/pallet_example_single_block_migrations/index.html){target=\_blank} in the Polkadot SDK documentation. -For example, when an account is reaped (removed due to insufficient balance) and later recreated, it resets to nonce 0, allowing identical transactions to be valid at different points: +## Multi Block Migrations -| Block | Extrinsic Index | Hash | Origin | Nonce | Call | Result | -|-------|----------------|------|-----------|-------|---------------------|-------------------------------| -| 100 | 0 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Account A reaped | -| 150 | 5 | 0x02 | Account B | 4 | Transfer 7 DOT to A | Account A created (nonce = 0) | -| 200 | 2 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Successful transaction | +Multi-block migrations distribute the migration workload across multiple blocks, providing a safer approach for production environments. The migration state is tracked in storage, allowing the process to pause and resume across blocks. -Notice that blocks 100 and 200 contain transactions with identical hashes (0x01) but are completely different, valid operations occurring at different times. +This approach is essential for production networks and parachains as the risk of exceeding block weight limits is eliminated. Multi-block migrations can safely handle large storage collections, unbounded data structures, and complex nested data types where weight consumption might be unpredictable. -Additional complexity comes from Polkadot SDK's origin abstraction. Origins can represent collectives, governance bodies, or other non-account entities that don't maintain nonces like regular accounts and might dispatch identical calls multiple times with the same hash values. Each execution occurs in different chain states with different results. +Multi-block migrations are ideal when dealing with: -The correct way to uniquely identify an extrinsic on a Polkadot SDK-based chain is to use the block ID (height or hash) and the extrinsic index. Since the Polkadot SDK defines blocks as headers plus ordered arrays of extrinsics, the index position within a canonical block provides guaranteed uniqueness. +- Large-scale storage migrations. +- Unbounded storage items or collections. +- Complex data structures with uncertain weight costs. -## Additional Resources +The primary trade-off is increased implementation complexity, as you must manage the migration state and handle partial completion scenarios. However, multi-block migrations' significant safety benefits and operational reliability are typically worth the increased complexity. -For a video overview of the lifecycle of transactions and the types of transactions that exist, see the [Transaction lifecycle](https://www.youtube.com/watch?v=3pfM0GOp02c){target=\_blank} seminar from Parity Tech. +For a complete implementation example of multi-block migrations, refer to the [official example](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/examples/multi-block-migrations){target=\_blank} in the Polkadot SDK. --- @@ -12054,351 +8735,6 @@ The system maintains precise conversion mechanisms between: This ensures accurate fee calculation while maintaining compatibility with existing Ethereum tools and workflows. ---- - -Page Title: Transactions Weights and Fees - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-fees.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/fees/ -- Summary: Overview of transaction weights and fees in Polkadot SDK chains, detailing how fees are calculated using a defined formula and runtime specifics. - -# Transactions Weights and Fees - -## Introductions - -When transactions are executed, or data is stored on-chain, the activity changes the chain's state and consumes blockchain resources. Because the resources available to a blockchain are limited, managing how operations on-chain consume them is important. In addition to being limited in practical terms, such as storage capacity, blockchain resources represent a potential attack vector for malicious users. For example, a malicious user might attempt to overload the network with messages to stop the network from producing new blocks. To protect blockchain resources from being drained or overloaded, you need to manage how they are made available and how they are consumed. The resources to be aware of include: - -- Memory usage -- Storage input and output -- Computation -- Transaction and block size -- State database size - -The Polkadot SDK provides block authors with several ways to manage access to resources and to prevent individual components of the chain from consuming too much of any single resource. Two of the most important mechanisms available to block authors are weights and transaction fees. - -[Weights](/reference/glossary/#weight){target=\_blank} manage the time it takes to validate a block and characterize the time it takes to execute the calls in the block's body. By controlling the execution time a block can consume, weights set limits on storage input, output, and computation. - -Some of the weight allowed for a block is consumed as part of the block's initialization and finalization. The weight might also be used to execute mandatory inherent extrinsic calls. To help ensure blocks don’t consume too much execution time and prevent malicious users from overloading the system with unnecessary calls, weights are combined with transaction fees. - -[Transaction fees](/reference/parachains/blocks-transactions-fees/transactions/#transaction-fees){target=\_blank} provide an economic incentive to limit execution time, computation, and the number of calls required to perform operations. Transaction fees are also used to make the blockchain economically sustainable because they are typically applied to transactions initiated by users and deducted before a transaction request is executed. - -## How Fees are Calculated - -The final fee for a transaction is calculated using the following parameters: - -- **`base fee`**: This is the minimum amount a user pays for a transaction. It is declared a base weight in the runtime and converted to a fee using the [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} conversion. -- **`weight fee`**: A fee proportional to the execution time (input and output and computation) that a transaction consumes. -- **`length fee`**: A fee proportional to the encoded length of the transaction. -- **`tip`**: An optional tip to increase the transaction’s priority, giving it a higher chance to be included in the transaction queue. - -The base fee and proportional weight and length fees constitute the inclusion fee. The inclusion fee is the minimum fee that must be available for a transaction to be included in a block. - -```text -inclusion fee = base fee + weight fee + length fee -``` - -Transaction fees are withdrawn before the transaction is executed. After the transaction is executed, the weight can be adjusted to reflect the resources used. If a transaction uses fewer resources than expected, the transaction fee is corrected, and the adjusted transaction fee is deposited. - -## Using the Transaction Payment Pallet - -The [Transaction Payment pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/transaction-payment){target=\_blank} provides the basic logic for calculating the inclusion fee. You can also use the Transaction Payment pallet to: - -- Convert a weight value into a deductible fee based on a currency type using [`Config::WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank}. -- Update the fee for the next block by defining a multiplier based on the chain’s final state at the end of the previous block using [`Config::FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank}. -- Manage the withdrawal, refund, and deposit of transaction fees using [`Config::OnChargeTransaction`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.OnChargeTransaction){target=\_blank}. - -You can learn more about these configuration traits in the [Transaction Payment documentation](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_payment/index.html){target=\_blank}. - -### Understanding the Inclusion Fee - -The formula for calculating the inclusion fee is as follows: - -```text -inclusion_fee = base_fee + length_fee + [targeted_fee_adjustment * weight_fee] -``` - -And then, for calculating the final fee: - -```text -final_fee = inclusion_fee + tip -``` - -In the first formula, the `targeted_fee_adjustment` is a multiplier that can tune the final fee based on the network’s congestion. - -- The `base_fee` derived from the base weight covers inclusion overhead like signature verification. -- The `length_fee` is a per-byte fee that is multiplied by the length of the encoded extrinsic. -- The `weight_fee` fee is calculated using two parameters: - - The `ExtrinsicBaseWeight` that is declared in the runtime and applies to all extrinsics. - - The `#[pallet::weight]` annotation that accounts for an extrinsic's complexity. - -To convert the weight to `Currency`, the runtime must define a `WeightToFee` struct that implements a conversion function, [`Convert`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/struct.Pallet.html#method.weight_to_fee){target=\_blank}. - -Note that the extrinsic sender is charged the inclusion fee before the extrinsic is invoked. The fee is deducted from the sender's balance even if the transaction fails upon execution. - -### Accounts with an Insufficient Balance - -If an account does not have a sufficient balance to pay the inclusion fee and remain alive—that is, enough to pay the inclusion fee and maintain the minimum existential deposit—then you should ensure the transaction is canceled so that no fee is deducted and the transaction does not begin execution. - -The Polkadot SDK doesn't enforce this rollback behavior. However, this scenario would be rare because the transaction queue and block-making logic perform checks to prevent it before adding an extrinsic to a block. - -### Fee Multipliers - -The inclusion fee formula always results in the same fee for the same input. However, weight can be dynamic and—based on how [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} is defined—the final fee can include some degree of variability. -The Transaction Payment pallet provides the [`FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank} configurable parameter to account for this variability. - -The Polkadot network inspires the default update function and implements a targeted adjustment in which a target saturation level of block weight is defined. If the previous block is more saturated, the fees increase slightly. Similarly, if the last block has fewer transactions than the target, fees are decreased by a small amount. For more information about fee multiplier adjustments, see the [Web3 Research Page](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank}. - -## Transactions with Special Requirements - -Inclusion fees must be computable before execution and can only represent fixed logic. Some transactions warrant limiting resources with other strategies. For example: - -- Bonds are a type of fee that might be returned or slashed after some on-chain event. For example, you might want to require users to place a bond to participate in a vote. The bond might then be returned at the end of the referendum or slashed if the voter attempted malicious behavior. -- Deposits are fees that might be returned later. For example, you might require users to pay a deposit to execute an operation that uses storage. The user’s deposit could be returned if a subsequent operation frees up storage. -- Burn operations are used to pay for a transaction based on its internal logic. For example, a transaction might burn funds from the sender if the transaction creates new storage items to pay for the increased state size. -- Limits enable you to enforce constant or configurable limits on specific operations. For example, the default [Staking pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/staking){target=\_blank} only allows nominators to nominate 16 validators to limit the complexity of the validator election process. - -It is important to note that if you query the chain for a transaction fee, it only returns the inclusion fee. - -## Default Weight Annotations - -All dispatchable functions in the Polkadot SDK must specify a weight. The way of doing that is using the annotation-based system that lets you combine fixed values for database read/write weight and/or fixed values based on benchmarks. The most basic example would look like this: - -```rust -#[pallet::weight(100_000)] -fn my_dispatchable() { - // ... -} -``` - -Note that the [`ExtrinsicBaseWeight`](https://crates.parity.io/frame_support/weights/constants/struct.ExtrinsicBaseWeight.html){target=\_blank} is automatically added to the declared weight to account for the costs of simply including an empty extrinsic into a block. - -### Weights and Database Read/Write Operations - -To make weight annotations independent of the deployed database backend, they are defined as a constant and then used in the annotations when expressing database accesses performed by the dispatchable: - -```rust -#[pallet::weight(T::DbWeight::get().reads_writes(1, 2) + 20_000)] -fn my_dispatchable() { - // ... -} -``` - -This dispatchable allows one database to read and two to write, in addition to other things that add the additional 20,000. Database access is generally every time a value declared inside the [`#[pallet::storage]`](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/attr.storage.html){target=\_blank} block is accessed. However, unique accesses are counted because after a value is accessed, it is cached, and reaccessing it does not result in a database operation. That is: - -- Multiple reads of the exact value count as one read. -- Multiple writes of the exact value count as one write. -- Multiple reads of the same value, followed by a write to that value, count as one read and one write. -- A write followed by a read-only counts as one write. - -### Dispatch Classes - -Dispatches are broken into three classes: - -- Normal -- Operational -- Mandatory - -If a dispatch is not defined as `Operational` or `Mandatory` in the weight annotation, the dispatch is identified as `Normal` by default. You can specify that the dispatchable uses another class like this: - -```rust -#[pallet::dispatch((DispatchClass::Operational))] -fn my_dispatchable() { - // ... -} -``` - -This tuple notation also allows you to specify a final argument determining whether the user is charged based on the annotated weight. If you don't specify otherwise, `Pays::Yes` is assumed: - -```rust -#[pallet::dispatch(DispatchClass::Normal, Pays::No)] -fn my_dispatchable() { - // ... -} -``` - -#### Normal Dispatches - -Dispatches in this class represent normal user-triggered transactions. These types of dispatches only consume a portion of a block's total weight limit. For information about the maximum portion of a block that can be consumed for normal dispatches, see [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Normal dispatches are sent to the transaction pool. - -#### Operational Dispatches - -Unlike normal dispatches, which represent the usage of network capabilities, operational dispatches are those that provide network capabilities. Operational dispatches can consume the entire weight limit of a block. They are not bound by the [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Dispatches in this class are given maximum priority and are exempt from paying the [`length_fee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/){target=\_blank}. - -#### Mandatory Dispatches - -Mandatory dispatches are included in a block even if they cause the block to surpass its weight limit. You can only use the mandatory dispatch class for inherent transactions that the block author submits. This dispatch class is intended to represent functions in the block validation process. Because these dispatches are always included in a block regardless of the function weight, the validation process must prevent malicious nodes from abusing the function to craft valid but impossibly heavy blocks. You can typically accomplish this by ensuring that: - -- The operation performed is always light. -- The operation can only be included in a block once. - -To make it more difficult for malicious nodes to abuse mandatory dispatches, they cannot be included in blocks that return errors. This dispatch class serves the assumption that it is better to allow an overweight block to be created than not to allow any block to be created at all. - -### Dynamic Weights - -In addition to purely fixed weights and constants, the weight calculation can consider the input arguments of a dispatchable. The weight should be trivially computable from the input arguments with some basic arithmetic: - -```rust -use frame_support:: { - dispatch:: { - DispatchClass::Normal, - Pays::Yes, - }, - weights::Weight, -}; - -#[pallet::weight(FunctionOf( - |args: (&Vec,)| args.0.len().saturating_mul(10_000), - ) -] -fn handle_users(origin, calls: Vec) { - // Do something per user -} -``` - -## Post Dispatch Weight Correction - -Depending on the execution logic, a dispatchable function might consume less weight than was prescribed pre-dispatch. To correct weight, the function declares a different return type and returns its actual weight: - -```rust -#[pallet::weight(10_000 + 500_000_000)] -fn expensive_or_cheap(input: u64) -> DispatchResultWithPostInfo { - let was_heavy = do_calculation(input); - - if (was_heavy) { - // None means "no correction" from the weight annotation. - Ok(None.into()) - } else { - // Return the actual weight consumed. - Ok(Some(10_000).into()) - } -} -``` - -## Custom Fees - -You can also define custom fee systems through custom weight functions or inclusion fee functions. - -### Custom Weights - -Instead of using the default weight annotations, you can create a custom weight calculation type using the weights module. The custom weight calculation type must implement the following traits: - -- [`WeighData`](https://crates.parity.io/frame_support/weights/trait.WeighData.html){target=\_blank} to determine the weight of the dispatch. -- [`ClassifyDispatch`](https://crates.parity.io/frame_support/weights/trait.ClassifyDispatch.html){target=\_blank} to determine the class of the dispatch. -- [`PaysFee`](https://crates.parity.io/frame_support/weights/trait.PaysFee.html){target=\_blank} to determine whether the sender of the dispatch pays fees. - -The Polkadot SDK then bundles the output information of the three traits into the [`DispatchInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_support/dispatch/struct.DispatchInfo.html){target=\_blank} struct and provides it by implementing the [`GetDispatchInfo`](https://docs.rs/frame-support/latest/frame_support/dispatch/trait.GetDispatchInfo.html){target=\_blank} for all `Call` variants and opaque extrinsic types. This is used internally by the System and Executive modules. - -`ClassifyDispatch`, `WeighData`, and `PaysFee` are generic over T, which gets resolved into the tuple of all dispatch arguments except for the origin. The following example illustrates a struct that calculates the weight as `m * len(args)`, where `m` is a given multiplier and args is the concatenated tuple of all dispatch arguments. In this example, the dispatch class is `Operational` if the transaction has more than 100 bytes of length in arguments and will pay fees if the encoded length exceeds 10 bytes. - -```rust -struct LenWeight(u32); -impl WeighData for LenWeight { - fn weigh_data(&self, target: T) -> Weight { - let multiplier = self.0; - let encoded_len = target.encode().len() as u32; - multiplier * encoded_len - } -} - -impl ClassifyDispatch for LenWeight { - fn classify_dispatch(&self, target: T) -> DispatchClass { - let encoded_len = target.encode().len() as u32; - if encoded_len > 100 { - DispatchClass::Operational - } else { - DispatchClass::Normal - } - } -} - -impl PaysFee { - fn pays_fee(&self, target: T) -> Pays { - let encoded_len = target.encode().len() as u32; - if encoded_len > 10 { - Pays::Yes - } else { - Pays::No - } - } -} -``` - -A weight calculator function can also be coerced to the final type of the argument instead of defining it as a vague type that can be encoded. The code would roughly look like this: - -```rust -struct CustomWeight; -impl WeighData<(&u32, &u64)> for CustomWeight { - fn weigh_data(&self, target: (&u32, &u64)) -> Weight { - ... - } -} - -// given a dispatch: -#[pallet::call] -impl, I: 'static> Pallet { - #[pallet::weight(CustomWeight)] - fn foo(a: u32, b: u64) { ... } -} -``` - -In this example, the `CustomWeight` can only be used in conjunction with a dispatch with a particular signature `(u32, u64)`, as opposed to `LenWeight`, which can be used with anything because there aren't any assumptions about ``. - -#### Custom Inclusion Fee - -The following example illustrates how to customize your inclusion fee. You must configure the appropriate associated types in the respective module. - -```rust -// Assume this is the balance type -type Balance = u64; - -// Assume we want all the weights to have a `100 + 2 * w` conversion to fees -struct CustomWeightToFee; -impl WeightToFee for CustomWeightToFee { - fn convert(w: Weight) -> Balance { - let a = Balance::from(100); - let b = Balance::from(2); - let w = Balance::from(w); - a + b * w - } -} - -parameter_types! { - pub const ExtrinsicBaseWeight: Weight = 10_000_000; -} - -impl frame_system::Config for Runtime { - type ExtrinsicBaseWeight = ExtrinsicBaseWeight; -} - -parameter_types! { - pub const TransactionByteFee: Balance = 10; -} - -impl transaction_payment::Config { - type TransactionByteFee = TransactionByteFee; - type WeightToFee = CustomWeightToFee; - type FeeMultiplierUpdate = TargetedFeeAdjustment; -} - -struct TargetedFeeAdjustment(sp_std::marker::PhantomData); -impl> WeightToFee for TargetedFeeAdjustment { - fn convert(multiplier: Fixed128) -> Fixed128 { - // Don't change anything. Put any fee update info here. - multiplier - } -} -``` - -## Additional Resources - -You now know the weight system, how it affects transaction fee computation, and how to specify weights for your dispatchable calls. The next step is determining the correct weight for your dispatchable operations. You can use Substrate benchmarking functions and frame-benchmarking calls to test your functions with different parameters and empirically determine the proper weight in their worst-case scenarios. - -- [Benchmark](/parachains/customize-runtime/pallet-development/benchmark-pallet/) -- [`SignedExtension`](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} -- [Custom weights for the Example pallet](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/substrate/frame/examples/basic/src/weights.rs){target=\_blank} -- [Web3 Foundation Research](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank} - - --- Page Title: Unlock a Parachain @@ -12556,91 +8892,3 @@ Here's how to submit this XCM using Astar (Parachain 2006) as an example: After submitting the transaction, wait for it to be finalized and then verify that your parachain has been successfully unlocked by following the steps described in the [Check if the Parachain is Locked](#check-if-the-parachain-is-locked) section. If the parachain shows as unlocked, your operation has been successful. If it still appears locked, verify that your XCM transaction was processed correctly and consider troubleshooting the XCM built. ![](/images/parachains/runtime-maintenance/unlock-parachains/unlock-parachain-6.webp) - - ---- - -Page Title: XCM Tools - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-xcm-tools.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/xcm-tools/ -- Summary: Explore essential XCM tools across Polkadot, crafted to enhance cross-chain functionality and integration within the ecosystem. - -# XCM Tools - -## Introduction - -As described in the [Interoperability](/develop/interoperability){target=\_blank} section, XCM (Cross-Consensus Messaging) is a protocol used in the Polkadot and Kusama ecosystems to enable communication and interaction between chains. It facilitates cross-chain communication, allowing assets, data, and messages to flow seamlessly across the ecosystem. - -As XCM is central to enabling communication between blockchains, developers need robust tools to help interact with, build, and test XCM messages. Several XCM tools simplify working with the protocol by providing libraries, frameworks, and utilities that enhance the development process, ensuring that applications built within the Polkadot ecosystem can efficiently use cross-chain functionalities. - -## Popular XCM Tools - -### Moonsong Labs XCM Tools - -[Moonsong Labs XCM Tools](https://github.com/Moonsong-Labs/xcm-tools){target=\_blank} provides a collection of scripts for managing and testing XCM operations between Polkadot SDK-based runtimes. These tools allow performing tasks like asset registration, channel setup, and XCM initialization. Key features include: - -- **Asset registration**: Registers assets, setting units per second (up-front fees), and configuring error (revert) codes. -- **XCM initializer**: Initializes XCM, sets default XCM versions, and configures revert codes for XCM-related precompiles. -- **HRMP manipulator**: Manages HRMP channel actions, including opening, accepting, or closing channels. -- **XCM-Transactor-Info-Setter**: Configures transactor information, including extra weight and fee settings. -- **Decode XCM**: Decodes XCM messages on the relay chain or parachains to help interpret cross-chain communication. - -To get started, clone the repository and install the required dependencies: - -```bash -git clone https://github.com/Moonsong-Labs/xcm-tools && -cd xcm-tools && -yarn install -``` - -For a full overview of each script, visit the [scripts](https://github.com/Moonsong-Labs/xcm-tools/tree/main/scripts){target=\_blank} directory or refer to the [official documentation](https://github.com/Moonsong-Labs/xcm-tools/blob/main/README.md){target=\_blank} on GitHub. - -### ParaSpell - -[ParaSpell](/reference/tools/paraspell/){target=\_blank} is a collection of open-source XCM tools that streamline cross-chain asset transfers and interactions across the Polkadot and Kusama ecosystems. It provides developers with an intuitive interface to build, test, and deploy interoperable dApps, featuring message composition, decoding, and practical utilities for parachain interactions that simplify debugging and cross-chain communication optimization. - -### Astar XCM Tools - -The [Astar parachain](https://github.com/AstarNetwork/Astar/tree/master){target=\_blank} offers a crate with a set of utilities for interacting with the XCM protocol. The [xcm-tools](https://github.com/AstarNetwork/Astar/tree/master/bin/xcm-tools){target=\_blank} crate provides a straightforward method for users to locate a sovereign account or calculate an XC20 asset ID. Some commands included by the xcm-tools crate allow users to perform the following tasks: - -- **Sovereign accounts**: Obtain the sovereign account address for any parachain, either on the Relay Chain or for sibling parachains, using a simple command. -- **XC20 EVM addresses**: Generate XC20-compatible Ethereum addresses for assets by entering the asset ID, making it easy to integrate assets across Ethereum-compatible environments. -- **Remote accounts**: Retrieve remote account addresses needed for multi-location compatibility, using flexible options to specify account types and parachain IDs. - -To start using these tools, clone the [Astar repository](https://github.com/AstarNetwork/Astar){target=\_blank} and compile the xcm-tools package: - -```bash -git clone https://github.com/AstarNetwork/Astar && -cd Astar && -cargo build --release -p xcm-tools -``` - -After compiling, verify the setup with the following command: - -```bash -./target/release/xcm-tools --help -``` -For more details on using Astar xcm-tools, consult the [official documentation](https://docs.astar.network/docs/learn/interoperability/xcm/integration/tools/){target=\_blank}. - -### Chopsticks - -The Chopsticks library provides XCM functionality for testing XCM messages across networks, enabling you to fork multiple parachains along with a relay chain. For further details, see the [Chopsticks documentation](/tutorials/polkadot-sdk/testing/fork-live-chains/){target=\_blank} about XCM. - -### Moonbeam XCM SDK - -The [Moonbeam XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk){target=\_blank} enables developers to easily transfer assets between chains, either between parachains or between a parachain and the relay chain, within the Polkadot/Kusama ecosystem. With the SDK, you don't need to worry about determining the [Multilocation](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#7-universal-consensus-location-identifiers){target=\_blank} of the origin or destination assets or which extrinsics are used on which networks. - -The SDK consists of two main packages: - -- **[XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/sdk){target=\_blank}**: Core SDK for executing XCM transfers between chains in the Polkadot/Kusama ecosystem. -- **[MRL SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/mrl){target=\_blank}**: Extension of the XCM SDK for transferring liquidity into and across the Polkadot ecosystem from other ecosystems like Ethereum. - -Key features include: - -- **Simplified asset transfers**: Abstracts away complex multilocation determinations and extrinsic selection. -- **Cross-ecosystem support**: Enables transfers between Polkadot/Kusama chains and external ecosystems. -- **Developer-friendly API**: Provides intuitive interfaces for cross-chain functionality. -- **Comprehensive documentation**: Includes usage guides and API references for both packages. - -For detailed usage examples and API documentation, visit the [official Moonbeam XCM SDK documentation](https://moonbeam-foundation.github.io/xcm-sdk/latest/){target=\_blank}. diff --git a/.ai/categories/polkadot-protocol.md b/.ai/categories/polkadot-protocol.md index a118a0ac9..77b27d7a5 100644 --- a/.ai/categories/polkadot-protocol.md +++ b/.ai/categories/polkadot-protocol.md @@ -476,5883 +476,2748 @@ Launch your parachain locally and start producing blocks: --- -Page Title: Agile Coretime +Page Title: Contract Deployment -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-agile-coretime.md -- Canonical (HTML): https://docs.polkadot.com/reference/polkadot-hub/consensus-and-security/agile-coretime/ -- Summary: Explore the efficient scheduling mechanisms to access Polkadot cores to produce blockspace continuously or on-demand. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-contract-deployment.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/contract-deployment/ +- Summary: Compare deployment flows for REVM and PVM-based smart contracts on the Polkadot Hub. Includes single-step REVM flows and PVM’s two-step deployment model. -# Agile Coretime +# Contract Deployment ## Introduction -Agile Coretime is the [scheduling](https://en.wikipedia.org/wiki/Scheduling_(computing)){target=\_blank} framework on Polkadot that lets parachains efficiently access cores, which comprise an active validator set tasked with parablock validation. As the first blockchain to enable a flexible scheduling system for blockspace production, Polkadot offers unparalleled adaptability for parachains. - -``` mermaid -graph TB - A[Cores Designation] - B[Bulk Coretime] - C[On-Demand Coretime] - A --continuous--> B - A --flexible--> C -``` - -Cores can be designated to a parachain either continuously through [bulk coretime](#bulk-coretime) or dynamically via [on-demand coretime](#on-demand-coretime). Additionally, Polkadot supports scheduling multiple cores in parallel through [elastic scaling](https://wiki.polkadot.com/learn/learn-elastic-scaling/){target=\_blank}, which is a feature under active development on Polkadot. This flexibility empowers parachains to optimize their resource usage and block production according to their unique needs. - -In this guide, you'll learn how bulk coretime enables continuous core access with features like interlacing and splitting, and how on-demand coretime provides flexible, pay-per-use scheduling for parachains. For a deep dive on Agile Coretime and its terminology, refer to the [Wiki doc](https://wiki.polkadot.com/learn/learn-agile-coretime/#introduction-to-agile-coretime){target=\_blank}. - -## Bulk Coretime - -Bulk coretime is a fixed duration of continuous coretime represented by an NFT that can be purchased through [coretime sales](#coretime-sales) in DOT and can be split, shared, or resold. Currently, the duration of bulk coretime is set to 28 days. Coretime purchased in bulk and assigned to a single parachain is eligible for a price-capped renewal, providing a form of rent-controlled access, which is important for predicting the running costs in the near future. Suppose the bulk coretime is [interlaced](#coretime-interlacing) or [split](#coretime-splitting) or is kept idle without assigning it to a parachain. In that case, it will be ineligible for the price-capped renewal. - -### Coretime Interlacing - -It is the action of dividing bulk coretime across multiple parachains that produce blocks spaced uniformly in time. For example, think of multiple parachains taking turns producing blocks, demonstrating a simple form of interlacing. This feature can be used by parachains with a low transaction volume and need not continuously produce blocks. - -### Coretime Splitting - -It is the action of dividing bulk coretime into multiple contiguous regions. This feature can be used by parachains that need to produce blocks continuously but do not require the whole 28 days of bulk coretime and require only part of it. - -## On-Demand Coretime - -Polkadot has dedicated cores assigned to provide core time on demand. These cores are excluded from the coretime sales and are reserved for on-demand parachains, which pay in DOT per block. - +Polkadot's smart contract platform supports two distinct virtual machine backends: Rust Ethereum Virtual Machine (REVM) and PolkaVM. Each backend has its own deployment characteristics and optimization strategies. REVM provides full Ethereum compatibility with familiar single-step deployment, while the RISC-V-based PolkaVM uses a more structured two-step approach optimized for its architecture. Understanding these differences ensures smooth deployment regardless of which backend you choose for your smart contracts. ---- +## REVM Deployment -Page Title: Asset Hub +The REVM backend enables seamless deployment of Ethereum contracts without modification. Contracts deploy exactly as they would on Ethereum, using familiar tools and workflows. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-assets-and-smart-contracts.md -- Canonical (HTML): https://docs.polkadot.com/reference/polkadot-hub/assets-and-smart-contracts/ -- Summary: Learn about Asset Hub in Polkadot, managing on-chain assets, foreign asset integration, and using XCM for cross-chain asset transfers. +With REVM, deployment mirrors the Ethereum flow exactly including: -# Asset Hub +- Contracts are bundled and deployed in a single transaction. +- Factory contracts can create new contracts at runtime. +- Runtime code generation, including inline assembly, is supported. +- Existing familiar tools like Hardhat, Foundry, and Remix work out of the box. -## Introduction +## PolkaVM Deployment -The Asset Hub is a critical component in the Polkadot ecosystem, enabling the management of fungible and non-fungible assets across the network. Since the relay chain focuses on maintaining security and consensus without direct asset management, Asset Hub provides a streamlined platform for creating, managing, and using on-chain assets in a fee-efficient manner. This guide outlines the core features of Asset Hub, including how it handles asset operations, cross-chain transfers, and asset integration using XCM, as well as essential tools like [API Sidecar](#api-sidecar) and [`TxWrapper`](#txwrapper) for developers working with on-chain assets. +PolkaVM implements a fundamentally different deployment model optimized for its RISC-V architecture. While simple contract deployments work seamlessly, advanced patterns like factory contracts require understanding the two-step deployment process. -## Assets Basics +### Standard Contract Deployment -In the Polkadot ecosystem, the relay chain does not natively support additional assets beyond its native token (DOT for Polkadot, KSM for Kusama). The Asset Hub parachain on Polkadot and Kusama provides a fungible and non-fungible assets framework. Asset Hub allows developers and users to create, manage, and use assets across the ecosystem. +For most use cases, such as deploying ERC-20 tokens, NFT collections, or standalone contracts, deployment is transparent and requires no special steps. The [Revive compiler](https://github.com/paritytech/revive){target=\_blank} handles the deployment process automatically when using standard Solidity patterns. -Asset creators can use Asset Hub to track their asset issuance across multiple parachains and manage assets through operations such as minting, burning, and transferring. Projects that need a standardized method of handling on-chain assets will find this particularly useful. The fungible asset interface provided by Asset Hub closely resembles Ethereum's ERC-20 standard but is directly integrated into Polkadot's runtime, making it more efficient in terms of speed and transaction fees. +### Two-Step Deployment Model -Integrating with Asset Hub offers several key benefits, particularly for infrastructure providers and users: +PolkaVM separates contract deployment into distinct phases: -- **Support for non-native on-chain assets**: Asset Hub enables seamless asset creation and management, allowing projects to develop tokens or assets that can interact with the broader ecosystem. -- **Lower transaction fees**: Asset Hub offers significantly lower transaction costs—approximately one-tenth of the fees on the relay chain, providing cost-efficiency for regular operations. -- **Reduced deposit requirements**: Depositing assets in Asset Hub is more accessible, with deposit requirements that are around one one-hundredth of those on the relay chain. -- **Payment of transaction fees with non-native assets**: Users can pay transaction fees in assets other than the native token (DOT or KSM), offering more flexibility for developers and users. +1. **Code upload**: Contract bytecode must be uploaded to the chain before instantiation. +2. **Contract instantiation**: Contracts are created by referencing previously uploaded code via its hash. -Assets created on the Asset Hub are stored as part of a map, where each asset has a unique ID that links to information about the asset, including details like: +This architecture differs from the EVM's bundled approach and has important implications for specific deployment patterns. -- The management team. -- The total supply. -- The number of accounts holding the asset. -- **Sufficiency for account existence**: Whether the asset alone is enough to maintain an account without a native token balance. -- The metadata of the asset, including its name, symbol, and the number of decimals for representation. +### Factory Pattern Considerations -Some assets can be regarded as sufficient to maintain an account's existence, meaning that users can create accounts on the network without needing a native token balance (i.e., no existential deposit required). Developers can also set minimum balances for their assets. If an account's balance drops below the minimum, the balance is considered dust and may be cleared. +The common EVM pattern, where contracts dynamically create other contracts, requires adaptation for PolkaVM as follows: -## Assets Pallet +**EVM Factory Pattern:** +```solidity +// This works on REVM but requires modification for PolkaVM +contract Factory { + function createToken() public returns (address) { + // EVM bundles bytecode in the factory + return address(new Token()); + } +} +``` -The Polkadot SDK's Assets pallet is a powerful module designated for creating and managing fungible asset classes with a fixed supply. It offers a secure and flexible way to issue, transfer, freeze, and destroy assets. The pallet supports various operations and includes permissioned and non-permissioned functions to cater to simple and advanced use cases. +**PolkaVM Requirements:** -Visit the [Assets Pallet Rust docs](https://paritytech.github.io/polkadot-sdk/master/pallet_assets/index.html){target=\_blank} for more in-depth information. +- **Pre-upload dependent contracts**: All contracts that will be instantiated at runtime must be uploaded to the chain before the factory attempts to create them. +- **Code hash references**: Factory contracts work with pre-uploaded code hashes rather than embedding bytecode. +- **No runtime code generation**: Dynamic bytecode generation is not supported due to PolkaVM's RISC-V format. -### Key Features +### Migration Strategy for Factory Contracts -Key features of the Assets pallet include: +When migrating factory contracts from Ethereum to PolkaVM: -- **Asset issuance**: Allows the creation of a new asset, where the total supply is assigned to the creator's account. -- **Asset transfer**: Enables transferring assets between accounts while maintaining a balance in both accounts. -- **Asset freezing**: Prevents transfers of a specific asset from one account, locking it from further transactions. -- **Asset destruction**: Allows accounts to burn or destroy their holdings, removing those assets from circulation. -- **Non-custodial transfers**: A non-custodial mechanism to enable one account to approve a transfer of assets on behalf of another. +1. **Identify all contracts**: Determine which contracts will be instantiated at runtime. +2. **Upload dependencies first**: Deploy all dependent contracts to the chain before deploying the factory. +3. **Use on-chain constructors**: Leverage PolkaVM's on-chain constructor feature for flexible instantiation. +4. **Avoid assembly creation**: Don't use `create` or `create2` opcodes in assembly blocks for manual deployment. -### Main Functions +### Architecture-Specific Limitations -The Assets pallet provides a broad interface for managing fungible assets. Some of the main dispatchable functions include: +PolkaVM's deployment model creates several specific constraints: -- **`create()`**: Create a new asset class by placing a deposit, applicable when asset creation is permissionless. -- **`issue()`**: Mint a fixed supply of a new asset and assign it to the creator's account. -- **`transfer()`**: Transfer a specified amount of an asset between two accounts. -- **`approve_transfer()`**: Approve a non-custodial transfer, allowing a third party to move assets between accounts. -- **`destroy()`**: Destroy an entire asset class, removing it permanently from the chain. -- **`freeze()` and `thaw()`**: Administrators or privileged users can lock or unlock assets from being transferred. +- **`EXTCODECOPY` limitations**: Contracts using `EXTCODECOPY` to manipulate code at runtime will encounter issues. +- **Runtime code modification**: Patterns that construct and mutate contract code on-the-fly are not supported. +- **Assembly-based factories**: Factory contracts written in YUL assembly that generate code at runtime will fail with `CodeNotFound` errors. -For a full list of dispatchable and privileged functions, see the [dispatchables Rust docs](https://docs.rs/pallet-assets/latest/pallet_assets/pallet/enum.Call.html){target=\_blank}. +These patterns are rare in practice and typically require dropping down to assembly, making them non-issues for standard Solidity development. -### Querying Functions +### On-Chain Constructors -The Assets pallet exposes several key querying functions that developers can interact with programmatically. These functions allow you to query asset information and perform operations essential for managing assets across accounts. The two main querying functions are: +PolkaVM provides on-chain constructors as an elegant alternative to runtime code modification: -- **`balance(asset_id, account)`**: Retrieves the balance of a given asset for a specified account. Useful for checking the holdings of an asset class across different accounts. +- Enable contract instantiation without runtime code generation. +- Support flexible initialization patterns. +- Maintain separation between code upload and contract creation. +- Provide predictable deployment costs. -- **`total_supply(asset_id)`**: Returns the total supply of the asset identified by `asset_id`. Allows users to verify how much of the asset exists on-chain. +## Gas Estimation vs Actual Consumption -In addition to these basic functions, other utility functions are available for querying asset metadata and performing asset transfers. You can view the complete list of querying functions in the [Struct Pallet Rust docs](https://docs.rs/pallet-assets/latest/pallet_assets/pallet/struct.Pallet.html){target=\_blank}. +Both REVM and PolkaVM deployments may show significant differences between gas estimation and actual consumption. You might see estimates that are several times higher than the actual gas consumed (often around 30% of the estimate). This is normal behavior because pre-dispatch estimation cannot distinguish between computation weight and storage deposits, leading to conservative overestimation. Contract deployments are particularly affected as they consume significant storage deposits for code storage. -### Permission Models and Roles +## Deployment Comparison -The Assets pallet incorporates a robust permission model, enabling control over who can perform specific operations like minting, transferring, or freezing assets. The key roles within the permission model are: +| Feature | REVM Backend | PolkaVM Backend | +|:-------:|:-------------:|:----------------:| +| **Deployment Model** | Single-step bundled | Two-step upload and instantiate | +| **Factory Patterns** | Direct runtime creation | Requires pre-uploaded code | +| **Code Bundling** | Bytecode in transaction | Code hash references | +| **Runtime Codegen** | Fully supported | Not supported | +| **Simple Contracts** | No modifications needed | No modifications needed | +| **Assembly Creation** | Supported | Discouraged, limited support | -- **Admin**: Can freeze (preventing transfers) and forcibly transfer assets between accounts. Admins also have the power to reduce the balance of an asset class across arbitrary accounts. They manage the more sensitive and administrative aspects of the asset class. -- **Issuer**: Responsible for minting new tokens. When new assets are created, the Issuer is the account that controls their distribution to other accounts. -- **Freezer**: Can lock the transfer of assets from an account, preventing the account holder from moving their balance. This function is useful for freezing accounts involved in disputes or fraud. -- **Owner**: Has overarching control, including destroying an entire asset class. Owners can also set or update the Issuer, Freezer, and Admin roles. +## Conclusion -These permissions provide fine-grained control over assets, enabling developers and asset managers to ensure secure, controlled operations. Each of these roles is crucial for managing asset lifecycles and ensuring that assets are used appropriately across the network. +Both backends support contract deployment effectively, with REVM offering drop-in Ethereum compatibility and PolkaVM providing a more structured two-step approach. For the majority of use cases—deploying standard contracts like tokens or applications—both backends work seamlessly. Advanced patterns like factory contracts may require adjustment for PolkaVM, but these adaptations are straightforward with proper planning. -### Asset Freezing -The Assets pallet allows you to freeze assets. This feature prevents transfers or spending from a specific account, effectively locking the balance of an asset class until it is explicitly unfrozen. Asset freezing is beneficial when assets are restricted due to security concerns or disputes. +--- -Freezing assets is controlled by the Freezer role, as mentioned earlier. Only the account with the Freezer privilege can perform these operations. Here are the key freezing functions: +Page Title: Deploy an ERC-20 to Polkadot Hub -- **`freeze(asset_id, account)`**: Locks the specified asset of the account. While the asset is frozen, no transfers can be made from the frozen account. -- **`thaw(asset_id, account)`**: Corresponding function for unfreezing, allowing the asset to be transferred again. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-erc20-erc20-hardhat.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-hardhat/ +- Summary: Deploy an ERC-20 token on Polkadot Hub using PolkaVM. This guide covers contract creation, compilation, deployment, and interaction via Hardhat. -This approach enables secure and flexible asset management, providing administrators the tools to control asset movement in special circumstances. +# Deploy an ERC-20 to Polkadot Hub -### Non-Custodial Transfers (Approval API) +## Introduction -The Assets pallet also supports non-custodial transfers through the Approval API. This feature allows one account to approve another account to transfer a specific amount of its assets to a third-party recipient without granting full control over the account's balance. Non-custodial transfers enable secure transactions where trust is required between multiple parties. +[ERC-20](https://eips.ethereum.org/EIPS/eip-20){target=\_blank} tokens are fungible tokens commonly used for creating cryptocurrencies, governance tokens, and staking mechanisms. Polkadot Hub enables easy token deployment with Ethereum-compatible smart contracts and tools via the EVM backend. -Here's a brief overview of the key functions for non-custodial asset transfers: +This tutorial covers deploying an ERC-20 contract on the Polkadot Hub TestNet using [Hardhat](https://hardhat.org/){target=\_blank}, an Ethereum development environment. The ERC-20 contract can be retrieved from OpenZeppelin's [GitHub repository](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20){target=\_blank} or their [Contract Wizard](https://wizard.openzeppelin.com/){target=\_blank}. -- **`approve_transfer(asset_id, delegate, amount)`**: Approves a delegate to transfer up to a certain amount of the asset on behalf of the original account holder. -- **`cancel_approval(asset_id, delegate)`**: Cancels a previous approval for the delegate. Once canceled, the delegate no longer has permission to transfer the approved amount. -- **`transfer_approved(asset_id, owner, recipient, amount)`**: Executes the approved asset transfer from the owner’s account to the recipient. The delegate account can call this function once approval is granted. +## Prerequisites -These delegated operations make it easier to manage multi-step transactions and dApps that require complex asset flows between participants. +Before starting, make sure you have: -## Foreign Assets +- Basic understanding of Solidity programming and fungible tokens. +- Node.js v22.13.1 or later. +- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. -Foreign assets in Asset Hub refer to assets originating from external blockchains or parachains that are registered in the Asset Hub. These assets are typically native tokens from other parachains within the Polkadot ecosystem or bridged tokens from external blockchains such as Ethereum. +## Set Up Your Project -Once a foreign asset is registered in the Asset Hub by its originating blockchain's root origin, users are able to send these tokens to the Asset Hub and interact with them as they would any other asset within the Polkadot ecosystem. +This tutorial uses a [Hardhat ERC-20 template](https://github.com/polkadot-developers/revm-hardhat-examples/tree/master/erc20-hardhat){target=\_blank} that contains all the necessary files. To get started, take the following steps: -### Handling Foreign Assets +1. Clone the GitHub repository locally: -The Foreign Assets pallet, an instance of the Assets pallet, manages these assets. Since foreign assets are integrated into the same interface as native assets, developers can use the same functionalities, such as transferring and querying balances. However, there are important distinctions when dealing with foreign assets. + ```bash + git clone https://github.com/polkadot-developers/revm-hardhat-examples/ + cd revm-hardhat-examples/erc20-hardhat + ``` -- **Asset identifier**: Unlike native assets, foreign assets are identified using an XCM Multilocation rather than a simple numeric `AssetId`. This multilocation identifier represents the cross-chain location of the asset and provides a standardized way to reference it across different parachains and relay chains. +2. Install the dependencies: -- **Transfers**: Once registered in the Asset Hub, foreign assets can be transferred between accounts, just like native assets. Users can also send these assets back to their originating blockchain if supported by the relevant cross-chain messaging mechanisms. + ```bash + npm i + ``` -## Integration +This will fetch all the necessary packages to help you deploy an ERC-20 with Hardhat to Polkadot. -Asset Hub supports a variety of integration tools that make it easy for developers to manage assets and interact with the blockchain in their applications. The tools and libraries provided by Parity Technologies enable streamlined operations, such as querying asset information, building transactions, and monitoring cross-chain asset transfers. +## Configure Hardhat -Developers can integrate Asset Hub into their projects using these core tools: +Once you've [setup your project](#set-up-your-project), you can configure the `hardhat.config.ts` to your needs. This tutorial has the file prepared to deploy to the Polkadot TestNet. -### API Sidecar +To store and use private keys or network URLs, you can use Hardhat's configuration variables. This can be set via tasks in the **vars** scope. For example, to store the private key to deploy to the Polkadot TestNet, run the following command: -[API Sidecar](https://github.com/paritytech/substrate-api-sidecar){target=\_blank} is a RESTful service that can be deployed alongside Polkadot and Kusama nodes. It provides endpoints to retrieve real-time blockchain data, including asset information. When used with Asset Hub, Sidecar allows querying: +```bash +npx hardhat vars set TESTNET_PRIVATE_KEY +``` -- **Asset look-ups**: Retrieve specific assets using `AssetId`. -- **Asset balances**: View the balance of a particular asset on Asset Hub. +The command will initiate a wizard in which you'll have to enter the value to be stored: -Public instances of API Sidecar connected to Asset Hub are available, such as: +
+ npx hardhat vars set TESTNET_PRIVATE_KEY + ✔ Enter value: · ••••••••• + The configuration variable has been stored in /Users/albertoviera/Library/Preferences/hardhat-nodejs/vars.json +
-- [Polkadot Asset Hub Sidecar](https://polkadot-asset-hub-public-sidecar.parity-chains.parity.io/){target=\_blank} -- [Kusama Asset Hub Sidecar](https://kusama-asset-hub-public-sidecar.parity-chains.parity.io/){target=\_blank} +??? warning "Key Encryption" + This solution just prevents variables to be included in the code repository. You should find a solution that encrypts private keys and access them securely. -These public instances are primarily for ad-hoc testing and quick checks. +You can now use the account related to this private key by importing it into the Hardhat configuration file: -### TxWrapper +```ts title="hardhat.config.ts" hl_lines="1 17" -[`TxWrapper`](https://github.com/paritytech/txwrapper-core){target=\_blank} is a library that simplifies constructing and signing transactions for Polkadot SDK-based chains, including Polkadot and Kusama. This tool includes support for working with Asset Hub, enabling developers to: +const config: HardhatUserConfig = { + solidity: { + version: "0.8.28", + settings: { + optimizer: { + enabled: true, + runs: 200, + }, + }, + }, + networks: { + polkadotTestnet: { + url: vars.get("TESTNET_URL", "http://127.0.0.1:8545"), + accounts: vars.has("TESTNET_PRIVATE_KEY") ? [vars.get("TESTNET_PRIVATE_KEY")] : [], + }, + }, + mocha: { + timeout: 40000, + }, +}; -- Construct offline transactions. -- Leverage asset-specific functions such as minting, burning, and transferring assets. +export default config; +``` -`TxWrapper` provides the flexibility needed to integrate asset operations into custom applications while maintaining the security and efficiency of Polkadot's transaction model. +## Compile your Contract +Once you've configured Hardhat, you can compile the contract. -### Parachain Node +In this tutorial, a simple ERC-20 is provided. Therefore, to compile the contract you can run the following command: -To fully leverage the Asset Hub's functionality, developers will need to run a system parachain node. Setting up an Asset Hub node allows users to interact with the parachain in real time, syncing data and participating in the broader Polkadot ecosystem. Guidelines for setting up an [Asset Hub node](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/cumulus#asset-hub-){target=\_blank} are available in the Parity documentation. +```bash +npx hardhat compile +``` -Using these integration tools, developers can manage assets seamlessly and integrate Asset Hub functionality into their applications, leveraging Polkadot's powerful infrastructure. +If everything compiles successfully, you should see the following output: -## XCM Transfer Monitoring +
+ npx hardhat compile + Generating typings for: 23 artifacts in dir: typechain-types for target: ethers-v6 + Successfully generated 62 typings! + Compiled 21 Solidity files successfully (evm target: paris). +
-Since Asset Hub facilitates cross-chain asset transfers across the Polkadot ecosystem, XCM transfer monitoring becomes an essential practice for developers and infrastructure providers. This section outlines how to monitor the cross-chain movement of assets between parachains, the relay chain, and other systems. +## Test your Contract -### Monitor XCM Deposits +Hardhat has a native feature to test contracts. You can run tests against the local Hardhat development node, but it could have some technical differences to Polkadot. Therefore, in this tutorial, you'll be testing against the Polkadot TestNet -As assets move between chains, tracking the cross-chain transfers in real time is crucial. Whether assets are transferred via a teleport from system parachains or through a reserve-backed transfer from any other parachain, each transfer emits a relevant event (such as the `balances.minted` event). +This example has a predefined test file located in [`test/Token.test.js`](https://github.com/polkadot-developers/revm-hardhat-examples/blob/master/erc20-hardhat/test/MyToken.test.ts){target=\_blank}, that runs the following tests: -To ensure accurate monitoring of these events: +1. The token was deployed by verifying its **name** and **symbol**. +2. The token has the right owner configured. +3. The token has an initial supply of zero. +4. The owner can mint tokens. +5. The total supply is increased after a mint. +6. Perform multiple mints to different addresses and checks the balance of each address and the new total supply. -- **Track XCM deposits**: Query every new block created in the relay chain or Asset Hub, loop through the events array, and filter for any `balances.minted` events which confirm the asset was successfully transferred to the account. -- **Track event origins**: Each `balances.minted` event points to a specific address. By monitoring this, service providers can verify that assets have arrived in the correct account. +To run the test, you can execute the following command: -### Track XCM Information Back to the Source +```bash +npx hardhat test --network polkadotTestnet +``` -While the `balances.minted` event confirms the arrival of assets, there may be instances where you need to trace the origin of the cross-chain message that triggered the event. In such cases, you can: +If tests are successful, you should see the following logs: -1. Query the relevant chain at the block where the `balances.minted` event was emitted. -2. Look for a `messageQueue(Processed)` event within that block's initialization. This event contains a parameter (`Id`) that identifies the cross-chain message received by the relay chain or Asset Hub. You can use this `Id` to trace the message back to its origin chain, offering full visibility of the asset transfer's journey. +
+ npx hardhat test --network polkadotTestnet + +   MyToken +     Deployment +       ✔ Should have correct name and symbol +       ✔ Should set the right owner +       ✔ Should have zero initial supply +     Minting +       ✔ Should allow owner to mint tokens +       ✔ Should increase total supply on mint +     Multiple mints +       ✔ Should correctly track balance after multiple mints + +   6 passing (369ms) +
-### Practical Monitoring Examples +## Deploy your Contract -The preceding sections outline the process of monitoring XCM deposits to specific accounts and then tracing back the origin of these deposits. The process of tracking an XCM transfer and the specific events to monitor may vary based on the direction of the XCM message. Here are some examples to showcase the slight differences: +With the Hardhat configuration file ready, the private key stored as a variable under **vars**, and the contract compiled, you can proceed to deploy the contract to a given network. In this tutorial, you are deploying it to the Polkadot TestNet. -- **Transfer from parachain to relay chain**: Track `parachainsystem(UpwardMessageSent)` on the parachain and `messagequeue(Processed)` on the relay chain. -- **Transfer from relay chain to parachain**: Track `xcmPallet(sent)` on the relay chain and `dmpqueue(ExecutedDownward)` on the parachain. -- **Transfer between parachains**: Track `xcmpqueue(XcmpMessageSent)` on the system parachain and `xcmpqueue(Success)` on the destination parachain. +To deploy the contract, run the following command: -### Monitor for Failed XCM Transfers +```bash +npx hardhat ignition deploy ./ignition/modules/MyToken.ts --network polkadotTestnet +``` -Sometimes, XCM transfers may fail due to liquidity or other errors. Failed transfers emit specific error events, which are key to resolving issues in asset transfers. Monitoring for these failure events helps catch issues before they affect asset balances. +You'll need to confirm the target network (by chain ID): -- **Relay chain to system parachain**: Look for the `dmpqueue(ExecutedDownward)` event on the parachain with an `Incomplete` outcome and an error type such as `UntrustedReserveLocation`. -- **Parachain to parachain**: Monitor for `xcmpqueue(Fail)` on the destination parachain with error types like `TooExpensive`. +
+ npx hardhat ignition deploy ./ignition/modules/MyToken.ts --network polkadotTestnet + ✔ Confirm deploy to network polkadotTestnet (420420420)? … yes +   + Hardhat Ignition 🚀 +   + Deploying [ TokenModule ] +   + Batch #1 + Executed TokenModule#MyToken +   + Batch #2 + Executed TokenModule#MyToken.mint +   + [ TokenModule ] successfully deployed 🚀 +   + Deployed Addresses +   + TokenModule#MyToken - 0xc01Ee7f10EA4aF4673cFff62710E1D7792aBa8f3 +
-For detailed error management in XCM, see Gavin Wood's blog post on [XCM Execution and Error Management](https://polkadot.com/blog/xcm-part-three-execution-and-error-management/){target=\_blank}. +And that is it! You've successfully deployed an ERC-20 token contract to the Polkadot TestNet using Hardhat. ## Where to Go Next
-- Tutorial __Register a Local Asset__ - - --- - - Comprehensive guide to registering a local asset on the Asset Hub system parachain, including step-by-step instructions. - - [:octicons-arrow-right-24: Reference](/chain-interactions/token-operations/register-local-asset/) - -- Tutorial __Register a Foreign Asset__ - - --- - - An in-depth guide to registering a foreign asset on the Asset Hub parachain, providing clear, step-by-step instructions. - - [:octicons-arrow-right-24: Reference](/chain-interactions/token-operations/register-foreign-asset/) - -- Tutorial __Convert Assets__ +- Guide __Deploy an NFT with Remix__ --- - A guide detailing the step-by-step process of converting assets on Asset Hub, helping users efficiently navigate asset management on the platform. + Walk through deploying an ERC-721 Non-Fungible Token (NFT) using OpenZeppelin's battle-tested NFT implementation and Remix. - [:octicons-arrow-right-24: Reference](/chain-interactions/token-operations/convert-assets/) + [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/)
--- -Page Title: Blocks +Page Title: Deploy an ERC-20 to Polkadot Hub -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-blocks.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/blocks/ -- Summary: Understand how blocks are produced, validated, and imported in Polkadot SDK-based blockchains, covering initialization, finalization, and authoring processes. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-erc20-erc20-remix.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix/ +- Summary: Deploy an ERC-20 token contract on Polkadot Hub. This guide covers contract creation, compilation, deployment, and interaction via the Remix IDE. -# Blocks +# Deploy an ERC-20 to Polkadot Hub ## Introduction -In the Polkadot SDK, blocks are fundamental to the functioning of the blockchain, serving as containers for [transactions](/reference/parachains/blocks-transactions-fees/transactions/){target=\_blank} and changes to the chain's state. Blocks consist of headers and an array of transactions, ensuring the integrity and validity of operations on the network. This guide explores the essential components of a block, the process of block production, and how blocks are validated and imported across the network. By understanding these concepts, developers can better grasp how blockchains maintain security, consistency, and performance within the Polkadot ecosystem. - -## What is a Block? - -In the Polkadot SDK, a block is a fundamental unit that encapsulates both the header and an array of transactions. The block header includes critical metadata to ensure the integrity and sequence of the blockchain. Here's a breakdown of its components: +[ERC-20](https://eips.ethereum.org/EIPS/eip-20){target=\_blank} tokens are fungible tokens commonly used for creating cryptocurrencies, governance tokens, and staking mechanisms. Polkadot Hub enables easy token deployment with Ethereum-compatible smart contracts and tools via the EVM backend. -- **Block height**: Indicates the number of blocks created in the chain so far. -- **Parent hash**: The hash of the previous block, providing a link to maintain the blockchain's immutability. -- **Transaction root**: Cryptographic digest summarizing all transactions in the block. -- **State root**: A cryptographic digest representing the post-execution state. -- **Digest**: Additional information that can be attached to a block, such as consensus-related messages. +This tutorial covers deploying an ERC-20 contract on the Polkadot Hub TestNet using [Remix IDE](https://remix.ethereum.org/){target=\_blank}, a web-based development tool. The ERC-20 contract can be retrieved from OpenZeppelin's [GitHub repository](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20){target=\_blank} or their [Contract Wizard](https://wizard.openzeppelin.com/){target=\_blank}. -Each transaction is part of a series that is executed according to the runtime's rules. The transaction root is a cryptographic digest of this series, which prevents alterations and enables succinct verification by light clients. This verification process allows light clients to confirm whether a transaction exists in a block with only the block header, avoiding downloading the entire block. +## Prerequisites -## Block Production +Before starting, make sure you have: -When an authoring node is authorized to create a new block, it selects transactions from the transaction queue based on priority. This step, known as block production, relies heavily on the executive module to manage the initialization and finalization of blocks. The process is summarized as follows: +- Basic understanding of Solidity programming and fungible tokens. +- An EVM-compatible wallet [connected to Polkadot Hub](/smart-contracts/integrations/wallets){target=\_blank}. This example utilizes [MetaMask](https://metamask.io/){target=\_blank}. +- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. -### Initialize Block +## Create Your Contract -The block initialization process begins with a series of function calls that prepare the block for transaction execution: +To create the ERC-20 contract, you can follow the steps below: -1. **Call `on_initialize`**: The executive module calls the [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} hook from the system pallet and other runtime pallets to prepare for the block's transactions. -2. **Coordinate runtime calls**: Coordinates function calls in the order defined by the transaction queue. -3. **Verify information**: Once [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} functions are executed, the executive module checks the parent hash in the block header and the trie root to verify information is consistent. +1. Navigate to the [Polkadot Remix IDE](https://remix.polkadot.io){target=\_blank}. +2. Click in the **Create new file** button under the **contracts** folder, and name your contract as `MyToken.sol`. -### Finalize Block + ![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-1.webp) -Once transactions are processed, the block must be finalized before being broadcast to the network. The finalization steps are as follows: +3. Now, paste the following ERC-20 contract code into the editor: -1. **Call `on_finalize`**: The executive module calls the [`on_finalize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_finalize){target=\_blank} hooks in each pallet to ensure any remaining state updates or checks are completed before the block is sealed and published. -2. **Verify information**: The block's digest and storage root in the header are checked against the initialized block to ensure consistency. -3. **Call `on_idle`**: The [`on_idle`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_idle){target=\_blank} hook is triggered to process any remaining tasks using the leftover weight from the block. + ```solidity title="MyToken.sol" + // SPDX-License-Identifier: MIT + // Compatible with OpenZeppelin Contracts ^5.4.0 + pragma solidity ^0.8.27; -## Block Authoring and Import - -Once the block is finalized, it is gossiped to other nodes in the network. Nodes follow this procedure: - -1. **Receive transactions**: The authoring node collects transactions from the network. -2. **Validate**: Transactions are checked for validity. -3. **Queue**: Valid transactions are placed in the transaction pool for execution. -4. **Execute**: State changes are made as the transactions are executed. -5. **Publish**: The finalized block is broadcast to the network. - -### Block Import Queue - -After a block is published, other nodes on the network can import it into their chain state. The block import queue is part of the outer node in every Polkadot SDK-based node and ensures incoming blocks are valid before adding them to the node's state. - -In most cases, you don't need to know details about how transactions are gossiped or how other nodes on the network import blocks. The following traits are relevant, however, if you plan to write any custom consensus logic or want a deeper dive into the block import queue: + import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; + import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol"; + import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; -- **[`ImportQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.ImportQueue.html){target=\_blank}**: The trait that defines the block import queue. -- **[`Link`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Link.html){target=\_blank}**: The trait that defines the link between the block import queue and the network. -- **[`BasicQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/struct.BasicQueue.html){target=\_blank}**: A basic implementation of the block import queue. -- **[`Verifier`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Verifier.html){target=\_blank}**: The trait that defines the block verifier. -- **[`BlockImport`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/block_import/trait.BlockImport.html){target=\_blank}**: The trait that defines the block import process. + contract MyToken is ERC20, Ownable, ERC20Permit { + constructor(address initialOwner) + ERC20("MyToken", "MTK") + Ownable(initialOwner) + ERC20Permit("MyToken") + {} -These traits govern how blocks are validated and imported across the network, ensuring consistency and security. + function mint(address to, uint256 amount) public onlyOwner { + _mint(to, amount); + } + } + ``` -## Additional Resources + The key components of the code above are: -To learn more about the block structure in the Polkadot SDK runtime, see the [`Block` reference](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.Block.html){target=\_blank} entry in the Rust Docs. + - Contract imports: + - **[`ERC20.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20/ERC20.sol){target=\_blank}**: The base contract for fungible tokens, implementing core functionality like transfers, approvals, and balance tracking. + - **[`ERC20Permit.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20/extensions/ERC20Permit.sol){target=\_blank}**: [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612){target=\_blank} extension for ERC-20 that adds the [permit function](https://docs.openzeppelin.com/contracts/5.x/api/token/erc20#ERC20Permit-permit-address-address-uint256-uint256-uint8-bytes32-bytes32-){target=\_blank}, allowing approvals via off-chain signatures (no on-chain tx from the holder). Manages nonces and EIP-712 domain separator and updates allowances when a valid signature is presented. + - **[`Ownable.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/access/Ownable.sol){target=\_blank}**: Provides basic authorization control, ensuring only the contract owner can mint new tokens. + + - Constructor parameters: ---- + - **`initialOwner`**: Sets the address that will have administrative rights over the contract. + - **`"MyToken"`**: The full name of your token. + - **`"MTK"`**: The symbol representing your token in wallets and exchanges. -Page Title: Bridge Hub + - Key functions: -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-bridging.md -- Canonical (HTML): https://docs.polkadot.com/reference/polkadot-hub/bridging/ -- Summary: Learn about the Bridge Hub system parachain, a parachain that facilitates the interactions from Polkadot to the rest of Web3. + - **`mint(address to, uint256 amount)`**: Allows the contract owner to create new tokens for any address. The amount should include 18 decimals (e.g., 1 token = 1000000000000000000). + - Inherited [Standard ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/){target=\_blank} functions: + - **`transfer(address recipient, uint256 amount)`**: Sends a specified amount of tokens to another address. + - **`approve(address spender, uint256 amount)`**: Grants permission for another address to spend a specific number of tokens on behalf of the token owner. + - **`transferFrom(address sender, address recipient, uint256 amount)`**: Transfers tokens from one address to another, if previously approved. + - **`balanceOf(address account)`**: Returns the token balance of a specific address. + - **`allowance(address owner, address spender)`**: Checks how many tokens an address is allowed to spend on behalf of another address. -# Bridge Hub + !!! tip + Use the [OpenZeppelin Contracts Wizard](https://wizard.openzeppelin.com/){target=\_blank} to generate customized smart contracts quickly. Simply configure your contract, copy the generated code, and paste it into the Remix IDE for deployment. Below is an example of an ERC-20 token contract created with it: -## Introduction + ![Screenshot of the OpenZeppelin Contracts Wizard showing an ERC-20 contract configuration.](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-2.webp) + -The Bridge Hub system parachain plays a crucial role in facilitating trustless interactions between Polkadot, Kusama, Ethereum, and other blockchain ecosystems. By implementing on-chain light clients and supporting protocols like BEEFY and GRANDPA, Bridge Hub ensures seamless message transmission and state verification across chains. It also provides essential [pallets](/reference/glossary/#pallet){target=\_blank} for sending and receiving messages, making it a cornerstone of Polkadot’s interoperability framework. With built-in support for XCM (Cross-Consensus Messaging), Bridge Hub enables secure, efficient communication between diverse blockchain networks. +## Compile -This guide covers the architecture, components, and deployment of the Bridge Hub system. You'll explore its trustless bridging mechanisms, key pallets for various blockchains, and specific implementations like Snowbridge and the Polkadot <> Kusama bridge. By the end, you'll understand how Bridge Hub enhances connectivity within the Polkadot ecosystem and beyond. +The compilation transforms your Solidity source code into bytecode that can be deployed on the blockchain. During this process, the compiler checks your contract for syntax errors, ensures type safety, and generates the machine-readable instructions needed for blockchain execution. -## Trustless Bridging +To compile your contract, ensure you have it opened in the Remix IDE Editor, and follow the instructions below: -Bridge Hub provides a mode of trustless bridging through its implementation of on-chain light clients and trustless relayers. Trustless bridges are essentially two one-way bridges, where each chain has a method of verifying the state of the other in a trustless manner through consensus proofs. In this context, "trustless" refers to the lack of need to trust a human when interacting with various system components. Trustless systems are based instead on trusting mathematics, cryptography, and code. The target chain and source chain both provide ways of verifying one another's state and actions (such as a transfer) based on the consensus and finality of both chains rather than an external mechanism controlled by a third party. +1. Select the **Solidity Compiler** plugin from the left panel. +2. Click the **Compile MyToken.sol** button. +3. If the compilation succeeded, you'll see a green checkmark indicating success in the **Solidity Compiler** icon. -[BEEFY (Bridge Efficiency Enabling Finality Yielder)](/reference/polkadot-hub/consensus-and-security/pos-consensus/#bridging-beefy){target=\_blank} is instrumental in this solution. It provides a more efficient way to verify the consensus on the relay chain. It allows the participants in a network to verify finality proofs, meaning a remote chain like Ethereum can verify the state of Polkadot at a given block height. +![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-3.gif) -For example, the Ethereum and Polkadot bridging solution that [Snowbridge](https://docs.snowbridge.network/){target=\_blank} implements involves two light clients: one which verifies the state of Polkadot and the other which verifies the state of Ethereum. The light client for Polkadot is implemented in the runtime as a pallet, whereas the light client for Ethereum is implemented as a smart contract on the beacon chain. +## Deploy -## Bridging Components +Deployment is the process of publishing your compiled smart contract to the blockchain, making it permanently available for interaction. During deployment, you'll create a new instance of your contract on the blockchain, which involves: -In any given Bridge Hub implementation (Kusama, Polkadot, or other relay chains), there are a few primary pallets that are utilized: +1. Select the **Deploy & Run Transactions** plugin from the left panel. +2. Configure the deployment settings: + 1. From the **ENVIRONMENT** dropdown, select **Injected Provider - MetaMask** (check the [Deploying Contracts](/smart-contracts/dev-environments/remix/deploy-a-contract/){target=\_blank} section of the Remix IDE guide for more details). + 2. (Optional) From the **ACCOUNT** dropdown, select the acccount you want to use for the deploy. -- **[Pallet Bridge GRANDPA](https://paritytech.github.io/polkadot-sdk/master/pallet_bridge_grandpa/index.html){target=\_blank}**: An on-chain GRANDPA light client for Substrate based chains. -- **[Pallet Bridge Parachains](https://paritytech.github.io/polkadot-sdk/master/pallet_bridge_parachains/index.html){target=\_blank}**: A finality module for parachains. -- **[Pallet Bridge Messages](https://paritytech.github.io/polkadot-sdk/master/pallet_bridge_messages/index.html){target=\_blank}**: A pallet which allows sending, receiving, and tracking of inbound and outbound messages. -- **[Pallet XCM Bridge](https://paritytech.github.io/polkadot-sdk/master/pallet_xcm_bridge_hub/index.html){target=\_blank}**: A pallet which, with the Bridge Messages pallet, adds XCM support to bridge pallets. +3. Configure the contract parameters: + 1. Enter the address that will own the deployed token contract. + 2. Click the **Deploy** button to initiate the deployment. -### Ethereum-Specific Support +4. **MetaMask will pop up**: Review the transaction details. Click **Confirm** to deploy your contract. +5. If the deployment process succeeded, you will see the transaction details in the terminal, including the contract address and deployment transaction hash. -Bridge Hub also has a set of components and pallets that support a bridge between Polkadot and Ethereum through [Snowbridge](https://github.com/Snowfork/snowbridge){target=\_blank}. +![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-4.gif) -To view the complete list of which pallets are included in Bridge Hub, visit the Subscan [Runtime Modules](https://bridgehub-polkadot.subscan.io/runtime){target=\_blank} page. Alternatively, the source code for those pallets can be found in the Polkadot SDK [Snowbridge Pallets](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/bridges/snowbridge/pallets){target=\_blank} repository. +## Interact with Your Contract -## Deployed Bridges +Once deployed, you can interact with your contract through Remix. Find your contract under **Deployed/Unpinned Contracts**, and click it to expand the available methods. In this example, you'll mint some tokens to a given address: -- [**Snowbridge**](https://wiki.polkadot.com/learn/learn-snowbridge/){target=\_blank}: A general-purpose, trustless bridge between Polkadot and Ethereum. -- [**Hyperbridge**](https://wiki.polkadot.com/learn/learn-hyperbridge/){target=\_blank}: A cross-chain solution built as an interoperability coprocessor, providing state-proof-based interoperability across all blockchains. -- [**Polkadot <> Kusama Bridge**](https://wiki.polkadot.com/learn/learn-dot-ksm-bridge/){target=\_blank}: A bridge that utilizes relayers to bridge the Polkadot and Kusama relay chains trustlessly. +1. Expand the **mint** function: + 1. Enter the recipient address and the amount (remember to add 18 zeros for 1 whole token). + 2. Click **transact**. -## Where to Go Next +2. Click **Approve** to confirm the transaction in the MetaMask popup. -- Go over the Bridge Hub README in the Polkadot SDK [Bridge-hub Parachains](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/cumulus/parachains/runtimes/bridge-hubs/README.md){target=\_blank} repository. -- Take a deeper dive into bridging architecture in the Polkadot SDK [High-Level Bridge](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/bridges/docs/high-level-overview.md){target=\_blank} documentation. -- Read more about [BEEFY and Bridging in the Polkadot Wiki](/reference/polkadot-hub/consensus-and-security/pos-consensus/#bridging-beefy){target=\_blank}. +3. If the transaction succeeds, you will see a green check mark in the terminal. +4. You can also call the **balanceOf** function by passing the address of the **mint** call to confirm the new balance. ---- +![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-5.gif) -Page Title: Chain Data -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-chain-data.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/chain-data/ -- Summary: Learn how to expose and utilize chain data for blockchain applications. Discover runtime metadata, RPC APIs, and tools for efficient development. +Other standard functions you can use: -# Chain Data +- **`transfer(address to, uint256 amount)`**: Send tokens to another address. +- **`approve(address spender, uint256 amount)`**: Allow another address to spend your tokens. -## Introduction +Feel free to explore and interact with the contract's other functions using the same approach: select the method, provide any required parameters, and confirm the transaction in MetaMask when needed. -Understanding and leveraging on-chain data is a fundamental aspect of blockchain development. Whether you're building frontend applications or backend systems, accessing and decoding runtime metadata is vital to interacting with the blockchain. This guide introduces you to the tools and processes for generating and retrieving metadata, explains its role in application development, and outlines the additional APIs available for interacting with a Polkadot node. By mastering these components, you can ensure seamless communication between your applications and the blockchain. +## Where to Go Next -## Application Development +
-You might not be directly involved in building frontend applications as a blockchain developer. However, most applications that run on a blockchain require some form of frontend or user-facing client to enable users or other programs to access and modify the data that the blockchain stores. For example, you might develop a browser-based, mobile, or desktop application that allows users to submit transactions, post articles, view their assets, or track previous activity. The backend for that application is configured in the runtime logic for your blockchain, but the frontend client makes the runtime features accessible to your users. +- Guide __Deploy an NFT with Remix__ -For your custom chain to be useful to others, you'll need to provide a client application that allows users to view, interact with, or update information that the blockchain keeps track of. In this article, you'll learn how to expose information about your runtime so that client applications can use it, see examples of the information exposed, and explore tools and libraries that use it. + --- -## Understand Metadata + Walk through deploying an ERC-721 Non-Fungible Token (NFT) using OpenZeppelin's battle-tested NFT implementation and Remix. -Polkadot SDK-based blockchain networks are designed to expose their runtime information, allowing developers to learn granular details regarding pallets, RPC calls, and runtime APIs. The metadata also exposes their related documentation. The chain's metadata is [SCALE-encoded](/reference/parachains/data-encoding/){target=\_blank}, allowing for the development of browser-based, mobile, or desktop applications to support the chain's runtime upgrades seamlessly. It is also possible to develop applications compatible with multiple Polkadot SDK-based chains simultaneously. + [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) -## Expose Runtime Information as Metadata +
-To interact with a node or the state of the blockchain, you need to know how to connect to the chain and access the exposed runtime features. This interaction involves a Remote Procedure Call (RPC) through a node endpoint address, commonly through a secure web socket connection. -An application developer typically needs to know the contents of the runtime logic, including the following details: +--- -- Version of the runtime the application is connecting to. -- Supported APIs. -- Implemented pallets. -- Defined functions and corresponding type signatures. -- Defined custom types. -- Exposed parameters users can set. +Page Title: Deploy an NFT to Polkadot Hub with Foundry -As the Polkadot SDK is modular and provides a composable framework for building blockchains, there are limitless opportunities to customize the schema of properties. Each runtime can be configured with its properties, including function calls and types, which can be changed over time with runtime upgrades. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-.foundry.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/.foundry/ +- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub using Foundry, a Rust toolkit with high-performance compilation. -The Polkadot SDK enables you to generate the runtime metadata schema to capture information unique to a runtime. The metadata for a runtime describes the pallets in use and types defined for a specific runtime version. The metadata includes information about each pallet's storage items, functions, events, errors, and constants. The metadata also provides type definitions for any custom types included in the runtime. +# Deploy an NFT with Foundry -Metadata provides a complete inventory of a chain's runtime. It is key to enabling client applications to interact with the node, parse responses, and correctly format message payloads sent back to that chain. +## Introduction -## Generate Metadata +Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. -To efficiently use the blockchain's networking resources and minimize the data transmitted over the network, the metadata schema is encoded using the [Parity SCALE Codec](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank}. This encoding is done automatically through the [`scale-info`](https://docs.rs/scale-info/latest/scale_info/){target=\_blank}crate. +This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. It showcases a secure approach using [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and the [Foundry](https://getfoundry.sh/){target=\_blank} toolchain. Foundry, a fast, Rust-written toolkit, ensures high-performance compilation and is fully compatible with the Hub’s EVM environment via standard Solidity compilation. -At a high level, generating the metadata involves the following steps: +## Prerequisites -1. The pallets in the runtime logic expose callable functions, types, parameters, and documentation that need to be encoded in the metadata. -2. The `scale-info` crate collects type information for the pallets in the runtime, builds a registry of the pallets that exist in a particular runtime, and the relevant types for each pallet in the registry. The type information is detailed enough to enable encoding and decoding for every type. -3. The [`frame-metadata`](https://github.com/paritytech/frame-metadata){target=\_blank} crate describes the structure of the runtime based on the registry provided by the `scale-info` crate. -4. Nodes provide the RPC method `state_getMetadata` to return a complete description of all the types in the current runtime as a hex-encoded vector of SCALE-encoded bytes. +- Basic understanding of Solidity programming and NFT standards. +- Test tokens for gas fees (available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}). See the [step-by-step instructions](/smart-contracts/faucet/#get-test-tokens){target=\_blank}. +- A wallet with a private key for signing transactions. -## Retrieve Runtime Metadata +## Set Up Your Project -The type information provided by the metadata enables applications to communicate with nodes using different runtime versions and across chains that expose different calls, events, types, and storage items. The metadata also allows libraries to generate a substantial portion of the code needed to communicate with a given node, enabling libraries like [`subxt`](https://github.com/paritytech/subxt){target=\_blank} to generate frontend interfaces that are specific to a target chain. +To get started, take the following steps: -### Use Polkadot.js +1. Install Foundry: -Visit the [Polkadot.js Portal](https://polkadot.js.org/apps/#/rpc){target=\_blank} and select the **Developer** dropdown in the top banner. Select **RPC Calls** to make the call to request metadata. Follow these steps to make the RPC call: + ```bash + curl -L https://foundry.paradigm.xyz | bash + foundryup + ``` -1. Select **state** as the endpoint to call. -2. Select **`getMetadata(at)`** as the method to call. -3. Click **Submit RPC call** to submit the call and return the metadata in JSON format. +2. Initialize your project: -### Use Curl + ```bash + forge init foundry-nft-deployment + cd foundry-nft-deployment + ``` -You can fetch the metadata for the network by calling the node's RPC endpoint. This request returns the metadata in bytes rather than human-readable JSON: +3. Install OpenZeppelin contracts: -```sh -curl -H "Content-Type: application/json" \ --d '{"id":1, "jsonrpc":"2.0", "method": "state_getMetadata"}' \ -https://rpc.polkadot.io + ```bash + forge install OpenZeppelin/openzeppelin-contracts + ``` -``` +## Configure Foundry -### Use Subxt +Edit `foundry.toml`: -[`subxt`](https://github.com/paritytech/subxt){target=\_blank} may also be used to fetch the metadata of any data in a human-readable JSON format: +```toml title="foundry.toml" +[profile.default] +src = "src" +out = "out" +libs = ["lib"] +remappings = ['@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/'] -```sh -subxt metadata --url wss://rpc.polkadot.io --format json > spec.json +[rpc_endpoints] +polkadot_hub_testnet = "https://testnet-passet-hub-eth-rpc.polkadot.io" ``` -Another option is to use the [`subxt` explorer web UI](https://paritytech.github.io/subxt-explorer/#/){target=\_blank}. - -## Client Applications and Metadata - -The metadata exposes the expected way to decode each type, meaning applications can send, retrieve, and process application information without manual encoding and decoding. Client applications must use the [SCALE codec library](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank} to encode and decode RPC payloads to use the metadata. Client applications use the metadata to interact with the node, parse responses, and format message payloads sent to the node. - -## Metadata Format - -Although the SCALE-encoded bytes can be decoded using the `frame-metadata` and [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} libraries, there are other tools, such as `subxt` and the Polkadot-JS API, that can convert the raw data to human-readable JSON format. +## Create Your Contract -The types and type definitions included in the metadata returned by the `state_getMetadata` RPC call depend on the runtime's metadata version. +Create `src/MyNFT.sol`: -In general, the metadata includes the following information: +```solidity title="src/MyNFT.sol" +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; -- A constant identifying the file as containing metadata. -- The version of the metadata format used in the runtime. -- Type definitions for all types used in the runtime and generated by the `scale-info` crate. -- Pallet information for the pallets included in the runtime in the order that they are defined in the `construct_runtime` macro. +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/access/Ownable.sol"; -!!!tip - Depending on the frontend library used (such as the [Polkadot API](https://papi.how/){target=\_blank}), they may format the metadata differently than the raw format shown. +contract MyNFT is ERC721, Ownable { + uint256 private _nextTokenId; -The following example illustrates a condensed and annotated section of metadata decoded and converted to JSON: + constructor(address initialOwner) + ERC721("MyToken", "MTK") + Ownable(initialOwner) + {} -```json -[ - 1635018093, - { - "V14": { - "types": { - "types": [{}] - }, - "pallets": [{}], - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [{}] - }, - "ty": 141 - } + function safeMint(address to) public onlyOwner { + uint256 tokenId = _nextTokenId++; + _safeMint(to, tokenId); } -] - -``` - -The constant `1635018093` is a magic number that identifies the file as a metadata file. The rest of the metadata is divided into the `types`, `pallets`, and `extrinsic` sections: - -- The `types` section contains an index of the types and information about each type's type signature. -- The `pallets` section contains information about each pallet in the runtime. -- The `extrinsic` section describes the type identifier and transaction format version that the runtime uses. - -Different extrinsic versions can have varying formats, especially when considering [signed transactions](/reference/parachains/blocks-transactions-fees/transactions/#signed-transactions){target=\_blank}. - -### Pallets - -The following is a condensed and annotated example of metadata for a single element in the `pallets` array (the [`sudo`](https://paritytech.github.io/polkadot-sdk/master/pallet_sudo/index.html){target=\_blank} pallet): - -```json -{ - "name": "Sudo", - "storage": { - "prefix": "Sudo", - "entries": [ - { - "name": "Key", - "modifier": "Optional", - "ty": { - "Plain": 0 - }, - "default": [0], - "docs": ["The `AccountId` of the sudo key."] - } - ] - }, - "calls": { - "ty": 117 - }, - "event": { - "ty": 42 - }, - "constants": [], - "error": { - "ty": 124 - }, - "index": 8 } - ``` -Every element metadata contains the name of the pallet it represents and information about its storage, calls, events, and errors. You can look up details about the definition of the calls, events, and errors by viewing the type index identifier. The type index identifier is the `u32` integer used to access the type information for that item. For example, the type index identifier for calls in the Sudo pallet is 117. If you view information for that type identifier in the `types` section of the metadata, it provides information about the available calls, including the documentation for each call. +## Compile -For example, the following is a condensed excerpt of the calls for the Sudo pallet: +```bash +forge build +``` -```json -{ - "id": 117, - "type": { - "path": ["pallet_sudo", "pallet", "Call"], - "params": [ - { - "name": "T", - "type": null - } - ], - "def": { - "variant": { - "variants": [ - { - "name": "sudo", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 0, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "sudo_unchecked_weight", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - }, - { - "name": "weight", - "type": 8, - "typeName": "Weight" - } - ], - "index": 1, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "set_key", - "fields": [ - { - "name": "new", - "type": 103, - "typeName": "AccountIdLookupOf" - } - ], - "index": 2, - "docs": [ - "Authenticates current sudo key, sets the given AccountId (`new`) as the new sudo" - ] - }, - { - "name": "sudo_as", - "fields": [ - { - "name": "who", - "type": 103, - "typeName": "AccountIdLookupOf" - }, - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 3, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Signed` origin from a given account" - ] - } - ] - } - } - } -} +Verify the compilation by inspecting the bytecode: +```bash +forge inspect MyNFT bytecode ``` -For each field, you can access type information and metadata for the following: - -- **Storage metadata**: Provides the information required to enable applications to get information for specific storage items. -- **Call metadata**: Includes information about the runtime calls defined by the `#[pallet]` macro including call names, arguments and documentation. -- **Event metadata**: Provides the metadata generated by the `#[pallet::event]` macro, including the name, arguments, and documentation for each pallet event. -- **Constants metadata**: Provides metadata generated by the `#[pallet::constant]` macro, including the name, type, and hex-encoded value of the constant. -- **Error metadata**: Provides metadata generated by the `#[pallet::error]` macro, including the name and documentation for each pallet error. +## Deploy -!!!tip - Type identifiers change from time to time, so you should avoid relying on specific type identifiers in your applications. +Deploy to Polkadot Hub TestNet: -### Extrinsic +```bash +forge create MyNFT \ + --rpc-url polkadot_hub_testnet \ + --private-key YOUR_PRIVATE_KEY \ + --constructor-args YOUR_OWNER_ADDRESS \ + --broadcast +``` -The runtime generates extrinsic metadata and provides useful information about transaction format. When decoded, the metadata contains the transaction version and the list of signed extensions. +Replace `YOUR_PRIVATE_KEY` with your private key and `YOUR_OWNER_ADDRESS` with the address that will own the NFT contract. -For example: +## Where to Go Next -```json -{ - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [ - { - "identifier": "CheckNonZeroSender", - "ty": 132, - "additional_signed": 41 - }, - { - "identifier": "CheckSpecVersion", - "ty": 133, - "additional_signed": 4 - }, - { - "identifier": "CheckTxVersion", - "ty": 134, - "additional_signed": 4 - }, - { - "identifier": "CheckGenesis", - "ty": 135, - "additional_signed": 11 - }, - { - "identifier": "CheckMortality", - "ty": 136, - "additional_signed": 11 - }, - { - "identifier": "CheckNonce", - "ty": 138, - "additional_signed": 41 - }, - { - "identifier": "CheckWeight", - "ty": 139, - "additional_signed": 41 - }, - { - "identifier": "ChargeTransactionPayment", - "ty": 140, - "additional_signed": 41 - } - ] - }, - "ty": 141 -} +
-``` +- Guide __Verify Your Contract__ -The type system is [composite](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/frame_runtime_types/index.html){target=\_blank}, meaning each type identifier contains a reference to a specific type or to another type identifier that provides information about the associated primitive types. + --- -For example, you can encode the `BitVec` type, but to decode it properly, you must know the types used for the `Order` and `Store` types. To find type information for `Order` and `Store`, you can use the path in the decoded JSON to locate their type identifiers. + Now that you've deployed an NFT contract, learn how to verify it with Foundry. -## Included RPC APIs + [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/foundry/verify-a-contract/) -A standard node comes with the following APIs to interact with a node: +- Guide __Deploy an ERC-20__ -- **[`AuthorApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/author/trait.AuthorApiServer.html){target=\_blank}**: Make calls into a full node, including authoring extrinsics and verifying session keys. -- **[`ChainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/chain/trait.ChainApiServer.html){target=\_blank}**: Retrieve block header and finality information. -- **[`OffchainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/offchain/trait.OffchainApiServer.html){target=\_blank}**: Make RPC calls for off-chain workers. -- **[`StateApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/state/trait.StateApiServer.html){target=\_blank}**: Query information about on-chain state such as runtime version, storage items, and proofs. -- **[`SystemApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/system/trait.SystemApiServer.html){target=\_blank}**: Retrieve information about network state, such as connected peers and node roles. + --- -## Additional Resources + Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Foundry. -The following tools can help you locate and decode metadata: + [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/foundry/) -- [Subxt Explorer](https://paritytech.github.io/subxt-explorer/#/){target=\_blank} -- [Metadata Portal 🌗](https://github.com/paritytech/metadata-portal){target=\_blank} -- [De[code] Sub[strate]](https://github.com/paritytech/desub){target=\_blank} +
--- -Page Title: Collectives Chain - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-collectives-and-daos.md -- Canonical (HTML): https://docs.polkadot.com/reference/polkadot-hub/collectives-and-daos/ -- Summary: Learn how the Collectives chain provides infrastructure for governance organizations, enabling decentralized network stewardship and decision-making. - -## Introduction +Page Title: Deploy an NFT to Polkadot Hub with Hardhat -Established through [Referendum 81](https://polkadot-old.polkassembly.io/referendum/81){target=\_blank}, the Collectives chain operates as a dedicated parachain exclusive to the Polkadot network with no counterpart on Kusama. This specialized infrastructure provides a foundation for various on-chain governance groups essential to Polkadot's ecosystem. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-hardhat.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/hardhat/ +- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub with Hardhat, a comprehenive development environment with built-in deployment capabilities. -The architecture enables entire networks to function as unified entities, allowing them to present cohesive positions and participate in cross-network governance through [Bridge Hub](/polkadot-protocol/architecture/system-chains/bridge-hub){target=\_blank}. This capability represents a fundamental advancement in Web3 principles, eliminating dependencies on traditional third-party intermediaries such as legal systems or jurisdictional authorities. +# Deploy an NFT with Hardhat -## Key Collectives +## Introduction -The Collectives chain hosts several important governance bodies: +Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. -- [**Polkadot Technical Fellowship**](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank}: A self-governing assembly of protocol experts and developers who oversee technical aspects of the Polkadot and Kusama networks. The Fellowship operates both on-chain through the collectives system and off-chain via GitHub repositories, public discussion forums, and monthly development calls that are publicly accessible. +This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. You'll use [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and [Hardhat](https://hardhat.org/docs/getting-started){target=\_blank}, a comprehensive development environment with built-in testing, debugging, and deployment capabilities. Hardhat uses standard Solidity compilation to generate EVM bytecode, making it fully compatible with Polkadot Hub's EVM environment. -- [**Polkadot Alliance**](https://wiki.polkadot.com/general/glossary/#polkadot-alliance){target=\_blank}: A consortium founded by seven leading parachain projects (Acala, Astar, Interlay, Kilt, Moonbeam, Phala, and Subscan) to establish development standards and ethical guidelines within the ecosystem. This ranked collective, comprised of "Fellows" and "Allies," focuses on promoting best practices and identifying potential bad actors. Membership is primarily designed for organizations, projects, and other networks rather than individuals. +## Prerequisites -These collectives serve as pillars of Polkadot's decentralized governance model, enabling community-driven decision-making and establishing technical standards that shape the network's evolution. Through structured on-chain representation, they provide transparent mechanisms for ecosystem development while maintaining the core Web3 principles of trustlessness and decentralization. +- Basic understanding of Solidity programming and NFT standards. +- Node.js v22.13.1 or later. +- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. +- A wallet with a private key for signing transactions. +## Set Up Your Project ---- +Take the following steps to get started: -Page Title: Contract Deployment +1. Initialize your Hardhat project: -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-contract-deployment.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/contract-deployment/ -- Summary: Compare deployment flows for REVM and PVM-based smart contracts on the Polkadot Hub. Includes single-step REVM flows and PVM’s two-step deployment model. + ```bash + mkdir hardhat-nft-deployment + cd hardhat-nft-deployment + npx hardhat --init + ``` -# Contract Deployment +2. Install OpenZeppelin contracts: -## Introduction + ```bash + npm install @openzeppelin/contracts + ``` -Polkadot's smart contract platform supports two distinct virtual machine backends: Rust Ethereum Virtual Machine (REVM) and PolkaVM. Each backend has its own deployment characteristics and optimization strategies. REVM provides full Ethereum compatibility with familiar single-step deployment, while the RISC-V-based PolkaVM uses a more structured two-step approach optimized for its architecture. Understanding these differences ensures smooth deployment regardless of which backend you choose for your smart contracts. +## Configure Hardhat -## REVM Deployment +Edit `hardhat.config.ts`: -The REVM backend enables seamless deployment of Ethereum contracts without modification. Contracts deploy exactly as they would on Ethereum, using familiar tools and workflows. +```typescript title="hardhat.config.ts" +import type { HardhatUserConfig } from 'hardhat/config'; -With REVM, deployment mirrors the Ethereum flow exactly including: +import hardhatToolboxViemPlugin from '@nomicfoundation/hardhat-toolbox-viem'; +import { configVariable } from 'hardhat/config'; -- Contracts are bundled and deployed in a single transaction. -- Factory contracts can create new contracts at runtime. -- Runtime code generation, including inline assembly, is supported. -- Existing familiar tools like Hardhat, Foundry, and Remix work out of the box. - -## PolkaVM Deployment - -PolkaVM implements a fundamentally different deployment model optimized for its RISC-V architecture. While simple contract deployments work seamlessly, advanced patterns like factory contracts require understanding the two-step deployment process. +const config: HardhatUserConfig = { + plugins: [hardhatToolboxViemPlugin], + solidity: { + profiles: { + default: { + version: '0.8.28', + }, + production: { + version: '0.8.28', + settings: { + optimizer: { + enabled: true, + runs: 200, + }, + }, + }, + }, + }, + networks: { + hardhatMainnet: { + type: 'edr-simulated', + chainType: 'l1', + }, + hardhatOp: { + type: 'edr-simulated', + chainType: 'op', + }, + sepolia: { + type: 'http', + chainType: 'l1', + url: configVariable('SEPOLIA_RPC_URL'), + accounts: [configVariable('SEPOLIA_PRIVATE_KEY')], + }, + polkadotHubTestnet: { + type: 'http', + url: 'https://testnet-passet-hub-eth-rpc.polkadot.io', + chainId: 420420422, + accounts: [configVariable('PRIVATE_KEY')], + }, + }, +}; -### Standard Contract Deployment +export default config; +``` -For most use cases, such as deploying ERC-20 tokens, NFT collections, or standalone contracts, deployment is transparent and requires no special steps. The [Revive compiler](https://github.com/paritytech/revive){target=\_blank} handles the deployment process automatically when using standard Solidity patterns. +!!! tip + Learn how to use Hardhat's [Config Variables](https://hardhat.org/docs/learn-more/configuration-variables){target=\_blank} to handle your private keys in a secure way. -### Two-Step Deployment Model +## Create Your Contract -PolkaVM separates contract deployment into distinct phases: +Create `contracts/MyNFT.sol`: -1. **Code upload**: Contract bytecode must be uploaded to the chain before instantiation. -2. **Contract instantiation**: Contracts are created by referencing previously uploaded code via its hash. +```solidity title="contracts/MyNFT.sol" +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; -This architecture differs from the EVM's bundled approach and has important implications for specific deployment patterns. +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/access/Ownable.sol"; -### Factory Pattern Considerations +contract MyNFT is ERC721, Ownable { + uint256 private _nextTokenId; -The common EVM pattern, where contracts dynamically create other contracts, requires adaptation for PolkaVM as follows: + constructor(address initialOwner) + ERC721("MyToken", "MTK") + Ownable(initialOwner) + {} -**EVM Factory Pattern:** -```solidity -// This works on REVM but requires modification for PolkaVM -contract Factory { - function createToken() public returns (address) { - // EVM bundles bytecode in the factory - return address(new Token()); + function safeMint(address to) public onlyOwner { + uint256 tokenId = _nextTokenId++; + _safeMint(to, tokenId); } } ``` -**PolkaVM Requirements:** - -- **Pre-upload dependent contracts**: All contracts that will be instantiated at runtime must be uploaded to the chain before the factory attempts to create them. -- **Code hash references**: Factory contracts work with pre-uploaded code hashes rather than embedding bytecode. -- **No runtime code generation**: Dynamic bytecode generation is not supported due to PolkaVM's RISC-V format. - -### Migration Strategy for Factory Contracts - -When migrating factory contracts from Ethereum to PolkaVM: - -1. **Identify all contracts**: Determine which contracts will be instantiated at runtime. -2. **Upload dependencies first**: Deploy all dependent contracts to the chain before deploying the factory. -3. **Use on-chain constructors**: Leverage PolkaVM's on-chain constructor feature for flexible instantiation. -4. **Avoid assembly creation**: Don't use `create` or `create2` opcodes in assembly blocks for manual deployment. - -### Architecture-Specific Limitations +## Compile -PolkaVM's deployment model creates several specific constraints: +```bash +npx hardhat compile +``` -- **`EXTCODECOPY` limitations**: Contracts using `EXTCODECOPY` to manipulate code at runtime will encounter issues. -- **Runtime code modification**: Patterns that construct and mutate contract code on-the-fly are not supported. -- **Assembly-based factories**: Factory contracts written in YUL assembly that generate code at runtime will fail with `CodeNotFound` errors. +## Set Up Deployment -These patterns are rare in practice and typically require dropping down to assembly, making them non-issues for standard Solidity development. +Create a deployment module in `ignition/modules/MyNFT.ts`: -### On-Chain Constructors +```typescript title="ignition/modules/MyNFT.ts" +import { buildModule } from '@nomicfoundation/hardhat-ignition/modules'; -PolkaVM provides on-chain constructors as an elegant alternative to runtime code modification: +export default buildModule('MyNFTModule', (m) => { + const initialOwner = m.getParameter('initialOwner', 'INSERT_OWNER_ADDRESS'); + const myNFT = m.contract('MyNFT', [initialOwner]); + return { myNFT }; +}); +``` -- Enable contract instantiation without runtime code generation. -- Support flexible initialization patterns. -- Maintain separation between code upload and contract creation. -- Provide predictable deployment costs. +Replace `INSERT_OWNER_ADDRESS` with your desired owner address. -## Gas Estimation vs Actual Consumption +## Deploy -Both REVM and PolkaVM deployments may show significant differences between gas estimation and actual consumption. You might see estimates that are several times higher than the actual gas consumed (often around 30% of the estimate). This is normal behavior because pre-dispatch estimation cannot distinguish between computation weight and storage deposits, leading to conservative overestimation. Contract deployments are particularly affected as they consume significant storage deposits for code storage. +Deploy to Polkadot Hub TestNet: -## Deployment Comparison +```bash +npx hardhat ignition deploy ignition/modules/MyNFT.ts --network polkadotHubTestnet +``` -| Feature | REVM Backend | PolkaVM Backend | -|:-------:|:-------------:|:----------------:| -| **Deployment Model** | Single-step bundled | Two-step upload and instantiate | -| **Factory Patterns** | Direct runtime creation | Requires pre-uploaded code | -| **Code Bundling** | Bytecode in transaction | Code hash references | -| **Runtime Codegen** | Fully supported | Not supported | -| **Simple Contracts** | No modifications needed | No modifications needed | -| **Assembly Creation** | Supported | Discouraged, limited support | +## Where to Go Next -## Conclusion +
-Both backends support contract deployment effectively, with REVM offering drop-in Ethereum compatibility and PolkaVM providing a more structured two-step approach. For the majority of use cases—deploying standard contracts like tokens or applications—both backends work seamlessly. Advanced patterns like factory contracts may require adjustment for PolkaVM, but these adaptations are straightforward with proper planning. +- Guide __Verify Your Contract__ + --- ---- + Now that you've deployed an NFT contract, learn how to verify it with Hardhat. -Page Title: Cryptography + [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/hardhat/verify-a-contract/) -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-cryptography.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/cryptography/ -- Summary: A concise guide to cryptography in blockchain, covering hash functions, encryption types, digital signatures, and elliptic curve applications. -# Cryptography +- Guide __Deploy an ERC-20__ -## Introduction + --- -Cryptography forms the backbone of blockchain technology, providing the mathematical verifiability crucial for consensus systems, data integrity, and user security. While a deep understanding of the underlying mathematical processes isn't necessary for most blockchain developers, grasping the fundamental applications of cryptography is essential. This page comprehensively overviews cryptographic implementations used across Polkadot SDK-based chains and the broader blockchain ecosystem. + Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Hardhat. -## Hash Functions + [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/hardhat/) -Hash functions are fundamental to blockchain technology, creating a unique digital fingerprint for any piece of data, including simple text, images, or any other form of file. They map input data of any size to a fixed-size output (typically 32 bytes) using complex mathematical operations. Hashing is used to verify data integrity, create digital signatures, and provide a secure way to store passwords. This form of mapping is known as the ["pigeonhole principle,"](https://en.wikipedia.org/wiki/Pigeonhole_principle){target=\_blank} it is primarily implemented to efficiently and verifiably identify data from large sets. +
-### Key Properties of Hash Functions -- **Deterministic**: The same input always produces the same output. -- **Quick computation**: It's easy to calculate the hash value for any given input. -- **Pre-image resistance**: It's infeasible to generate the input data from its hash. -- **Small changes in input yield large changes in output**: Known as the ["avalanche effect"](https://en.wikipedia.org/wiki/Avalanche_effect){target=\_blank}. -- **Collision resistance**: The probabilities are extremely low to find two different inputs with the same hash. +--- -### Blake2 +Page Title: Deploy an NFT to Polkadot Hub with Remix -The Polkadot SDK utilizes Blake2, a state-of-the-art hashing method that offers: +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-remix.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/ +- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub using Remix, a browser-based IDE for quick prototyping and learning. -- Equal or greater security compared to [SHA-2](https://en.wikipedia.org/wiki/SHA-2){target=\_blank}. -- Significantly faster performance than other algorithms. +# Deploy an NFT with Remix -These properties make Blake2 ideal for blockchain systems, reducing sync times for new nodes and lowering the resources required for validation. For detailed technical specifications about Blake2, see the [official Blake2 paper](https://www.blake2.net/blake2.pdf){target=\_blank}. +## Introduction -## Types of Cryptography +Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. -There are two different ways that cryptographic algorithms are implemented: symmetric cryptography and asymmetric cryptography. +This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. You'll use [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and [Remix](https://remix.ethereum.org/){target=\_blank}, a visual, browser-based environment perfect for rapid prototyping and learning. It requires no local installation and provides an intuitive interface for contract development. -### Symmetric Cryptography +## Prerequisites -Symmetric encryption is a branch of cryptography that isn't based on one-way functions, unlike asymmetric cryptography. It uses the same cryptographic key to encrypt plain text and decrypt the resulting ciphertext. +- Basic understanding of Solidity programming and NFT standards. +- Test tokens for gas fees (available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}). See the [step-by-step instructions](/smart-contracts/faucet/#get-test-tokens){target=\_blank} +- A wallet with a private key for signing transactions. -Symmetric cryptography is a type of encryption that has been used throughout history, such as the Enigma Cipher and the Caesar Cipher. It is still widely used today and can be found in Web2 and Web3 applications alike. There is only one single key, and a recipient must also have access to it to access the contained information. +## Access Remix -#### Advantages {: #symmetric-advantages } +Navigate to [Remix](https://remix.ethereum.org/){target=\_blank} in your web browser. -- Fast and efficient for large amounts of data. -- Requires less computational power. +The interface will load with a default workspace containing sample contracts. In this interface, you can access a file explorer, edit your code, interact with various plugins for development, and use a terminal. -#### Disadvantages {: #symmetric-disadvantages } +## Create Your Contract -- Key distribution can be challenging. -- Scalability issues in systems with many users. +1. Create a new file `contracts/MyNFT.sol`. +2. Paste the following code: -### Asymmetric Cryptography + ```solidity title="contracts/MyNFT.sol" + // SPDX-License-Identifier: MIT + pragma solidity ^0.8.20; -Asymmetric encryption is a type of cryptography that uses two different keys, known as a keypair: a public key, used to encrypt plain text, and a private counterpart, used to decrypt the ciphertext. + import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; + import "@openzeppelin/contracts/access/Ownable.sol"; -The public key encrypts a fixed-length message that can only be decrypted with the recipient's private key and, sometimes, a set password. The public key can be used to cryptographically verify that the corresponding private key was used to create a piece of data without compromising the private key, such as with digital signatures. This has obvious implications for identity, ownership, and properties and is used in many different protocols across Web2 and Web3. + contract MyNFT is ERC721, Ownable { + uint256 private _nextTokenId; -#### Advantages {: #asymmetric-advantages } + constructor(address initialOwner) + ERC721("MyToken", "MTK") + Ownable(initialOwner) + {} -- Solves the key distribution problem. -- Enables digital signatures and secure key exchange. + function safeMint(address to) public onlyOwner { + uint256 tokenId = _nextTokenId++; + _safeMint(to, tokenId); + } + } + ``` -#### Disadvantages {: #asymmetric-disadvantages } +![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-01.webp) -- Slower than symmetric encryption. -- Requires more computational resources. +## Compile -### Trade-offs and Compromises +1. Navigate to the **Solidity Compiler** tab (third icon in the left sidebar). +2. Click **Compile MyNFT.sol** or press `Ctrl+S`. -Symmetric cryptography is faster and requires fewer bits in the key to achieve the same level of security that asymmetric cryptography provides. However, it requires a shared secret before communication can occur, which poses issues to its integrity and a potential compromise point. On the other hand, asymmetric cryptography doesn't require the secret to be shared ahead of time, allowing for far better end-user security. +![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-02.webp) -Hybrid symmetric and asymmetric cryptography is often used to overcome the engineering issues of asymmetric cryptography, as it is slower and requires more bits in the key to achieve the same level of security. It encrypts a key and then uses the comparatively lightweight symmetric cipher to do the "heavy lifting" with the message. +Compilation errors and warnings appear in the terminal panel at the bottom of the screen. -## Digital Signatures +## Deploy -Digital signatures are a way of verifying the authenticity of a document or message using asymmetric keypairs. They are used to ensure that a sender or signer's document or message hasn't been tampered with in transit, and for recipients to verify that the data is accurate and from the expected sender. +1. Navigate to the **Deploy & Run Transactions** tab. +2. Click the **Environment** dropdown, select **Browser Extension**, and click on **Injected Provider - MetaMask**. -Signing digital signatures only requires a low-level understanding of mathematics and cryptography. For a conceptual example -- when signing a check, it is expected that it cannot be cashed multiple times. This isn't a feature of the signature system but rather the check serialization system. The bank will check that the serial number on the check hasn't already been used. Digital signatures essentially combine these two concepts, allowing the signature to provide the serialization via a unique cryptographic fingerprint that cannot be reproduced. + ![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-03.webp) -Unlike pen-and-paper signatures, knowledge of a digital signature cannot be used to create other signatures. Digital signatures are often used in bureaucratic processes, as they are more secure than simply scanning in a signature and pasting it onto a document. +3. In the deploy section, enter the initial owner address in the constructor parameter field. +4. Click **Deploy**. -Polkadot SDK provides multiple different cryptographic schemes and is generic so that it can support anything that implements the [`Pair` trait](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Pair.html){target=\_blank}. + ![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-04.webp) -### Example of Creating a Digital Signature +5. Approve the transaction in your MetaMask wallet. -The process of creating and verifying a digital signature involves several steps: +Your deployed contract will appear in the **Deployed Contracts** section, ready for interaction. -1. The sender creates a hash of the message. -2. The hash is encrypted using the sender's private key, creating the signature. -3. The message and signature are sent to the recipient. -4. The recipient decrypts the signature using the sender's public key. -5. The recipient hashes the received message and compares it to the decrypted hash. +## Where to Go Next -If the hashes match, the signature is valid, confirming the message's integrity and the sender's identity. +
-## Elliptic Curve +- Guide __Verify Your Contract__ -Blockchain technology requires the ability to have multiple keys creating a signature for block proposal and validation. To this end, Elliptic Curve Digital Signature Algorithm (ECDSA) and Schnorr signatures are two of the most commonly used methods. While ECDSA is a far simpler implementation, Schnorr signatures are more efficient when it comes to multi-signatures. + --- -Schnorr signatures bring some noticeable features over the ECDSA/EdDSA schemes: + Now that you've deployed an NFT contract, learn how to verify it with Remix. -- It is better for hierarchical deterministic key derivations. -- It allows for native multi-signature through [signature aggregation](https://bitcoincore.org/en/2017/03/23/schnorr-signature-aggregation/){target=\_blank}. -- It is generally more resistant to misuse. + [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/remix/verify-a-contract/) -One sacrifice that is made when using Schnorr signatures over ECDSA is that both require 64 bytes, but only ECDSA signatures communicate their public key. +- Guide __Deploy an ERC-20__ -### Various Implementations + --- -- **[ECDSA](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm){target=\_blank}**: Polkadot SDK provides an ECDSA signature scheme using the [secp256k1](https://en.bitcoin.it/wiki/Secp256k1){target=\_blank} curve. This is the same cryptographic algorithm used to secure [Bitcoin](https://en.wikipedia.org/wiki/Bitcoin){target=\_blank} and [Ethereum](https://en.wikipedia.org/wiki/Ethereum){target=\_blank}. + Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Remix. -- **[Ed25519](https://en.wikipedia.org/wiki/EdDSA#Ed25519){target=\_blank}**: An EdDSA signature scheme using [Curve25519](https://en.wikipedia.org/wiki/Curve25519){target=\_blank}. It is carefully engineered at several levels of design and implementation to achieve very high speeds without compromising security. + [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/) -- **[SR25519](https://research.web3.foundation/Polkadot/security/keys/accounts-more){target=\_blank}**: Based on the same underlying curve as Ed25519. However, it uses Schnorr signatures instead of the EdDSA scheme. +
--- -Page Title: Data Encoding +Page Title: Dual Virtual Machine Stack -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-data-encoding.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/data-encoding/ -- Summary: SCALE codec enables fast, efficient data encoding, ideal for resource-constrained environments like Wasm, supporting custom types and compact encoding. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-dual-vm-stack.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/dual-vm-stack/ +- Summary: Compare Polkadot’s dual smart contract VMs—REVM for EVM compatibility and PolkaVM for RISC-V performance, flexibility, and efficiency. -# Data Encoding +# Dual Virtual Machine Stack +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. ## Introduction -The Polkadot SDK uses a lightweight and efficient encoding/decoding mechanism to optimize data transmission across the network. This mechanism, known as the _SCALE_ codec, is used for serializing and deserializing data. - -The SCALE codec enables communication between the runtime and the outer node. This mechanism is designed for high-performance, copy-free data encoding and decoding in resource-constrained environments like the Polkadot SDK [Wasm runtime](/develop/parachains/deployment/build-deterministic-runtime/#introduction){target=\_blank}. - -It is not self-describing, meaning the decoding context must fully know the encoded data types. - -Parity's libraries utilize the [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} crate (a Rust implementation of the SCALE codec) to handle encoding and decoding for interactions between RPCs and the runtime. - -The `codec` mechanism is ideal for Polkadot SDK-based chains because: - -- It is lightweight compared to generic serialization frameworks like [`serde`](https://serde.rs/){target=\_blank}, which add unnecessary bulk to binaries. -- It doesn’t rely on Rust’s `libstd`, making it compatible with `no_std` environments like Wasm runtime. -- It integrates seamlessly with Rust, allowing easy derivation of encoding and decoding logic for new types using `#[derive(Encode, Decode)]`. - -Defining a custom encoding scheme in the Polkadot SDK-based chains, rather than using an existing Rust codec library, is crucial for enabling cross-platform and multi-language support. - -## SCALE Codec - -The codec is implemented using the following traits: - -- [`Encode`](#encode) -- [`Decode`](#decode) -- [`CompactAs`](#compactas) -- [`HasCompact`](#hascompact) -- [`EncodeLike`](#encodelike) - -### Encode +Polkadot's smart contract platform supports two distinct virtual machine (VM) architectures, providing developers with flexibility in selecting the optimal execution backend for their specific needs. This approach strikes a balance between immediate Ethereum compatibility and long-term innovation, enabling developers to deploy either unmodified (Ethereum Virtual Machine) EVM contracts using Rust Ethereum Virtual Machine (REVM) or optimize for higher performance using PolkaVM (PVM). -The [`Encode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Encode.html){target=\_blank} trait handles data encoding into SCALE format and includes the following key functions: +Both VM options share common infrastructure, including RPC interfaces, tooling support, and precompiles. The following sections compare architectures and guide you in selecting the best VM for your project's needs. -- **`size_hint(&self) -> usize`**: Estimates the number of bytes required for encoding to prevent multiple memory allocations. This should be inexpensive and avoid complex operations. Optional if the size isn’t known. -- **`encode_to(&self, dest: &mut T)`**: Encodes the data, appending it to a destination buffer. -- **`encode(&self) -> Vec`**: Encodes the data and returns it as a byte vector. -- **`using_encoded R>(&self, f: F) -> R`**: Encodes the data and passes it to a closure, returning the result. -- **`encoded_size(&self) -> usize`**: Calculates the encoded size. Should be used when the encoded data isn’t required. +## Migrate from EVM -!!!tip - For best performance, value types should override `using_encoded`, and allocating types should override `encode_to`. It's recommended to implement `size_hint` for all types where possible. +The [REVM backend](https://github.com/bluealloy/revm){target=\_blank} integrates a complete Rust implementation of the EVM, enabling Solidity contracts to run unchanged on Polkadot's smart contract platform. -### Decode +REVM allows developers to use their existing Ethereum tooling and infrastructure to build on Polkadot. Choose REVM to: -The [`Decode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Decode.html){target=\_blank} trait handles decoding SCALE-encoded data back into the appropriate types: +- Migrate existing Ethereum contracts without modifications. +- Retain exact EVM behavior for audit tools. +- Use developer tools that rely upon inspecting EVM bytecode. +- Prioritize rapid deployment over optimization. +- Work with established Ethereum infrastructure and tooling to build on Polkadot. -- **`fn decode(value: &mut I) -> Result`**: Decodes data from the SCALE format, returning an error if decoding fails. +REVM enables Ethereum developers to seamlessly migrate to Polkadot, achieving performance and fee improvements without modifying their existing contracts or developer tooling stack. -### CompactAs +## Upgrade to PolkaVM -The [`CompactAs`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.CompactAs.html){target=\_blank} trait wraps custom types for compact encoding: +[**PolkaVM**](https://github.com/paritytech/polkavm){target=\_blank} is a custom virtual machine optimized for performance with [RISC-V-based](https://en.wikipedia.org/wiki/RISC-V){target=\_blank} architecture, supporting Solidity and additional high-performance languages. It serves as the core execution environment, integrated directly within the runtime. Choose the PolkaVM for: -- **`encode_as(&self) -> &Self::As`**: Encodes the type as a compact type. -- **`decode_from(_: Self::As) -> Result`**: decodes from a compact encoded type. +- An efficient interpreter for immediate code execution. +- A planned [Just In Time (JIT)](https://en.wikipedia.org/wiki/Just-in-time_compilation){target=\_blank} compiler for optimized performance. +- Dual-mode execution capability, allowing selection of the most appropriate backend for specific workloads. +- Optimized performance for short-running contract calls through the interpreter. -### HasCompact +The interpreter remains particularly beneficial for contracts with minimal code execution, as it enables immediate code execution through lazy interpretation. -The [`HasCompact`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.HasCompact.html){target=\_blank} trait indicates a type supports compact encoding. +## Architecture -### EncodeLike +The following key components of PolkaVM work together to enable Ethereum compatibility on Polkadot-based chains. -The [`EncodeLike`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.EncodeLike.html){target=\_blank} trait is used to ensure multiple types that encode similarly are accepted by the same function. When using `derive`, it is automatically implemented. +### Revive Pallet -### Data Types +[**`pallet_revive`**](https://paritytech.github.io/polkadot-sdk/master/pallet_revive/index.html){target=\_blank} is a runtime module that executes smart contracts by adding extrinsics, runtime APIs, and logic to convert Ethereum-style transactions into formats compatible with Polkadot SDK-based blockchains. It processes Ethereum-style transactions through the following workflow: -The table below outlines how the Rust implementation of the Parity SCALE codec encodes different data types. - -| Type | Description | Example SCALE Decoded Value | SCALE Encoded Value | -|-------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------| -| Boolean | Boolean values are encoded using the least significant bit of a single byte. | `false` / `true` | `0x00` / `0x01` | -| Compact/general integers | A "compact" or general integer encoding is sufficient for encoding large integers (up to 2^536) and is more efficient at encoding most values than the fixed-width version. | `unsigned integer 0` / `unsigned integer 1` / `unsigned integer 42` / `unsigned integer 69` / `unsigned integer 65535` / `BigInt(100000000000000)` | `0x00` / `0x04` / `0xa8` / `0x1501` / `0xfeff0300` / `0x0b00407a10f35a` | -| Enumerations (tagged-unions) | A fixed number of variants, each mutually exclusive and potentially implying a further value or series of values. Encoded as the first byte identifying the index of the variant that the value is. Any further bytes are used to encode any data that the variant implies. Thus, no more than 256 variants are supported. | `Int(42)` and `Bool(true)` where `enum IntOrBool { Int(u8), Bool(bool) }` | `0x002a` and `0x0101` | -| Fixed-width integers | Basic integers are encoded using a fixed-width little-endian (LE) format. | `signed 8-bit integer 69` / `unsigned 16-bit integer 42` / `unsigned 32-bit integer 16777215` | `0x45` / `0x2a00` / `0xffffff00` | -| Options | One or zero values of a particular type. | `Some` / `None` | `0x01` followed by the encoded value / `0x00` | -| Results | Results are commonly used enumerations which indicate whether certain operations were successful or unsuccessful. | `Ok(42)` / `Err(false)` | `0x002a` / `0x0100` | -| Strings | Strings are Vectors of bytes (Vec) containing a valid UTF8 sequence. | | | -| Structs | For structures, the values are named, but that is irrelevant for the encoding (names are ignored - only order matters). | `SortedVecAsc::from([3, 5, 2, 8])` | `[3, 2, 5, 8] ` | -| Tuples | A fixed-size series of values, each with a possibly different but predetermined and fixed type. This is simply the concatenation of each encoded value. | Tuple of compact unsigned integer and boolean: `(3, false)` | `0x0c00` | -| Vectors (lists, series, sets) | A collection of same-typed values is encoded, prefixed with a compact encoding of the number of items, followed by each item's encoding concatenated in turn. | Vector of unsigned `16`-bit integers: `[4, 8, 15, 16, 23, 42]` | `0x18040008000f00100017002a00` | - -## Encode and Decode Rust Trait Implementations - -Here's how the `Encode` and `Decode` traits are implemented: - - -```rust -use parity_scale_codec::{Encode, Decode}; - -[derive(Debug, PartialEq, Encode, Decode)] -enum EnumType { - #[codec(index = 15)] - A, - B(u32, u64), - C { - a: u32, - b: u64, - }, -} - -let a = EnumType::A; -let b = EnumType::B(1, 2); -let c = EnumType::C { a: 1, b: 2 }; - -a.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x0f"); -}); - -b.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); - -c.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); - -let mut da: &[u8] = b"\x0f"; -assert_eq!(EnumType::decode(&mut da).ok(), Some(a)); - -let mut db: &[u8] = b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut db).ok(), Some(b)); - -let mut dc: &[u8] = b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut dc).ok(), Some(c)); - -let mut dz: &[u8] = &[0]; -assert_eq!(EnumType::decode(&mut dz).ok(), None); -``` - -## SCALE Codec Libraries - -Several SCALE codec implementations are available in various languages. Here's a list of them: - -- **AssemblyScript**: [`LimeChain/as-scale-codec`](https://github.com/LimeChain/as-scale-codec){target=\_blank} -- **C**: [`MatthewDarnell/cScale`](https://github.com/MatthewDarnell/cScale){target=\_blank} -- **C++**: [`qdrvm/scale-codec-cpp`](https://github.com/qdrvm/scale-codec-cpp){target=\_blank} -- **JavaScript**: [`polkadot-js/api`](https://github.com/polkadot-js/api){target=\_blank} -- **Dart**: [`leonardocustodio/polkadart`](https://github.com/leonardocustodio/polkadart){target=\_blank} -- **Haskell**: [`airalab/hs-web3`](https://github.com/airalab/hs-web3/tree/master/packages/scale){target=\_blank} -- **Golang**: [`itering/scale.go`](https://github.com/itering/scale.go){target=\_blank} -- **Java**: [`splix/polkaj`](https://github.com/splix/polkaj){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **Ruby**: [` wuminzhe/scale_rb`](https://github.com/wuminzhe/scale_rb){target=\_blank} -- **TypeScript**: [`parity-scale-codec-ts`](https://github.com/tjjfvi/subshape){target=\_blank}, [`scale-ts`](https://github.com/unstoppablejs/unstoppablejs/tree/main/packages/scale-ts#scale-ts){target=\_blank}, [`soramitsu/scale-codec-js-library`](https://github.com/soramitsu/scale-codec-js-library){target=\_blank}, [`subsquid/scale-codec`](https://github.com/subsquid/squid-sdk/tree/master/substrate/scale-codec){target=\_blank} - - ---- - -Page Title: Deploy an ERC-20 to Polkadot Hub - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-erc20-erc20-hardhat.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-hardhat/ -- Summary: Deploy an ERC-20 token on Polkadot Hub using PolkaVM. This guide covers contract creation, compilation, deployment, and interaction via Hardhat. - -# Deploy an ERC-20 to Polkadot Hub - -## Introduction - -[ERC-20](https://eips.ethereum.org/EIPS/eip-20){target=\_blank} tokens are fungible tokens commonly used for creating cryptocurrencies, governance tokens, and staking mechanisms. Polkadot Hub enables easy token deployment with Ethereum-compatible smart contracts and tools via the EVM backend. - -This tutorial covers deploying an ERC-20 contract on the Polkadot Hub TestNet using [Hardhat](https://hardhat.org/){target=\_blank}, an Ethereum development environment. The ERC-20 contract can be retrieved from OpenZeppelin's [GitHub repository](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20){target=\_blank} or their [Contract Wizard](https://wizard.openzeppelin.com/){target=\_blank}. - -## Prerequisites - -Before starting, make sure you have: - -- Basic understanding of Solidity programming and fungible tokens. -- Node.js v22.13.1 or later. -- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. - -## Set Up Your Project - -This tutorial uses a [Hardhat ERC-20 template](https://github.com/polkadot-developers/revm-hardhat-examples/tree/master/erc20-hardhat){target=\_blank} that contains all the necessary files. To get started, take the following steps: - -1. Clone the GitHub repository locally: - - ```bash - git clone https://github.com/polkadot-developers/revm-hardhat-examples/ - cd revm-hardhat-examples/erc20-hardhat - ``` - -2. Install the dependencies: - - ```bash - npm i - ``` - -This will fetch all the necessary packages to help you deploy an ERC-20 with Hardhat to Polkadot. - -## Configure Hardhat - -Once you've [setup your project](#set-up-your-project), you can configure the `hardhat.config.ts` to your needs. This tutorial has the file prepared to deploy to the Polkadot TestNet. - -To store and use private keys or network URLs, you can use Hardhat's configuration variables. This can be set via tasks in the **vars** scope. For example, to store the private key to deploy to the Polkadot TestNet, run the following command: - -```bash -npx hardhat vars set TESTNET_PRIVATE_KEY -``` - -The command will initiate a wizard in which you'll have to enter the value to be stored: - -
- npx hardhat vars set TESTNET_PRIVATE_KEY - ✔ Enter value: · ••••••••• - The configuration variable has been stored in /Users/albertoviera/Library/Preferences/hardhat-nodejs/vars.json -
- -??? warning "Key Encryption" - This solution just prevents variables to be included in the code repository. You should find a solution that encrypts private keys and access them securely. - -You can now use the account related to this private key by importing it into the Hardhat configuration file: - -```ts title="hardhat.config.ts" hl_lines="1 17" - -const config: HardhatUserConfig = { - solidity: { - version: "0.8.28", - settings: { - optimizer: { - enabled: true, - runs: 200, - }, - }, - }, - networks: { - polkadotTestnet: { - url: vars.get("TESTNET_URL", "http://127.0.0.1:8545"), - accounts: vars.has("TESTNET_PRIVATE_KEY") ? [vars.get("TESTNET_PRIVATE_KEY")] : [], - }, - }, - mocha: { - timeout: 40000, - }, -}; - -export default config; -``` - -## Compile your Contract - -Once you've configured Hardhat, you can compile the contract. - -In this tutorial, a simple ERC-20 is provided. Therefore, to compile the contract you can run the following command: - -```bash -npx hardhat compile -``` - -If everything compiles successfully, you should see the following output: - -
- npx hardhat compile - Generating typings for: 23 artifacts in dir: typechain-types for target: ethers-v6 - Successfully generated 62 typings! - Compiled 21 Solidity files successfully (evm target: paris). -
- -## Test your Contract - -Hardhat has a native feature to test contracts. You can run tests against the local Hardhat development node, but it could have some technical differences to Polkadot. Therefore, in this tutorial, you'll be testing against the Polkadot TestNet - -This example has a predefined test file located in [`test/Token.test.js`](https://github.com/polkadot-developers/revm-hardhat-examples/blob/master/erc20-hardhat/test/MyToken.test.ts){target=\_blank}, that runs the following tests: - -1. The token was deployed by verifying its **name** and **symbol**. -2. The token has the right owner configured. -3. The token has an initial supply of zero. -4. The owner can mint tokens. -5. The total supply is increased after a mint. -6. Perform multiple mints to different addresses and checks the balance of each address and the new total supply. - -To run the test, you can execute the following command: - -```bash -npx hardhat test --network polkadotTestnet -``` - -If tests are successful, you should see the following logs: - -
- npx hardhat test --network polkadotTestnet - -   MyToken -     Deployment -       ✔ Should have correct name and symbol -       ✔ Should set the right owner -       ✔ Should have zero initial supply -     Minting -       ✔ Should allow owner to mint tokens -       ✔ Should increase total supply on mint -     Multiple mints -       ✔ Should correctly track balance after multiple mints - -   6 passing (369ms) -
- -## Deploy your Contract - -With the Hardhat configuration file ready, the private key stored as a variable under **vars**, and the contract compiled, you can proceed to deploy the contract to a given network. In this tutorial, you are deploying it to the Polkadot TestNet. - -To deploy the contract, run the following command: - -```bash -npx hardhat ignition deploy ./ignition/modules/MyToken.ts --network polkadotTestnet -``` - -You'll need to confirm the target network (by chain ID): - -
- npx hardhat ignition deploy ./ignition/modules/MyToken.ts --network polkadotTestnet - ✔ Confirm deploy to network polkadotTestnet (420420420)? … yes -   - Hardhat Ignition 🚀 -   - Deploying [ TokenModule ] -   - Batch #1 - Executed TokenModule#MyToken -   - Batch #2 - Executed TokenModule#MyToken.mint -   - [ TokenModule ] successfully deployed 🚀 -   - Deployed Addresses -   - TokenModule#MyToken - 0xc01Ee7f10EA4aF4673cFff62710E1D7792aBa8f3 -
- -And that is it! You've successfully deployed an ERC-20 token contract to the Polkadot TestNet using Hardhat. - -## Where to Go Next - -
- -- Guide __Deploy an NFT with Remix__ - - --- - - Walk through deploying an ERC-721 Non-Fungible Token (NFT) using OpenZeppelin's battle-tested NFT implementation and Remix. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) - -
- - ---- - -Page Title: Deploy an ERC-20 to Polkadot Hub - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-erc20-erc20-remix.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix/ -- Summary: Deploy an ERC-20 token contract on Polkadot Hub. This guide covers contract creation, compilation, deployment, and interaction via the Remix IDE. - -# Deploy an ERC-20 to Polkadot Hub - -## Introduction - -[ERC-20](https://eips.ethereum.org/EIPS/eip-20){target=\_blank} tokens are fungible tokens commonly used for creating cryptocurrencies, governance tokens, and staking mechanisms. Polkadot Hub enables easy token deployment with Ethereum-compatible smart contracts and tools via the EVM backend. - -This tutorial covers deploying an ERC-20 contract on the Polkadot Hub TestNet using [Remix IDE](https://remix.ethereum.org/){target=\_blank}, a web-based development tool. The ERC-20 contract can be retrieved from OpenZeppelin's [GitHub repository](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20){target=\_blank} or their [Contract Wizard](https://wizard.openzeppelin.com/){target=\_blank}. - -## Prerequisites - -Before starting, make sure you have: - -- Basic understanding of Solidity programming and fungible tokens. -- An EVM-compatible wallet [connected to Polkadot Hub](/smart-contracts/integrations/wallets){target=\_blank}. This example utilizes [MetaMask](https://metamask.io/){target=\_blank}. -- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. - -## Create Your Contract - -To create the ERC-20 contract, you can follow the steps below: - -1. Navigate to the [Polkadot Remix IDE](https://remix.polkadot.io){target=\_blank}. -2. Click in the **Create new file** button under the **contracts** folder, and name your contract as `MyToken.sol`. - - ![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-1.webp) - -3. Now, paste the following ERC-20 contract code into the editor: - - ```solidity title="MyToken.sol" - // SPDX-License-Identifier: MIT - // Compatible with OpenZeppelin Contracts ^5.4.0 - pragma solidity ^0.8.27; - - import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol"; - import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; - - contract MyToken is ERC20, Ownable, ERC20Permit { - constructor(address initialOwner) - ERC20("MyToken", "MTK") - Ownable(initialOwner) - ERC20Permit("MyToken") - {} - - function mint(address to, uint256 amount) public onlyOwner { - _mint(to, amount); - } - } - ``` - - The key components of the code above are: - - - Contract imports: - - - **[`ERC20.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20/ERC20.sol){target=\_blank}**: The base contract for fungible tokens, implementing core functionality like transfers, approvals, and balance tracking. - - **[`ERC20Permit.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20/extensions/ERC20Permit.sol){target=\_blank}**: [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612){target=\_blank} extension for ERC-20 that adds the [permit function](https://docs.openzeppelin.com/contracts/5.x/api/token/erc20#ERC20Permit-permit-address-address-uint256-uint256-uint8-bytes32-bytes32-){target=\_blank}, allowing approvals via off-chain signatures (no on-chain tx from the holder). Manages nonces and EIP-712 domain separator and updates allowances when a valid signature is presented. - - **[`Ownable.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/access/Ownable.sol){target=\_blank}**: Provides basic authorization control, ensuring only the contract owner can mint new tokens. - - - Constructor parameters: - - - **`initialOwner`**: Sets the address that will have administrative rights over the contract. - - **`"MyToken"`**: The full name of your token. - - **`"MTK"`**: The symbol representing your token in wallets and exchanges. - - - Key functions: - - - **`mint(address to, uint256 amount)`**: Allows the contract owner to create new tokens for any address. The amount should include 18 decimals (e.g., 1 token = 1000000000000000000). - - Inherited [Standard ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/){target=\_blank} functions: - - **`transfer(address recipient, uint256 amount)`**: Sends a specified amount of tokens to another address. - - **`approve(address spender, uint256 amount)`**: Grants permission for another address to spend a specific number of tokens on behalf of the token owner. - - **`transferFrom(address sender, address recipient, uint256 amount)`**: Transfers tokens from one address to another, if previously approved. - - **`balanceOf(address account)`**: Returns the token balance of a specific address. - - **`allowance(address owner, address spender)`**: Checks how many tokens an address is allowed to spend on behalf of another address. - - !!! tip - Use the [OpenZeppelin Contracts Wizard](https://wizard.openzeppelin.com/){target=\_blank} to generate customized smart contracts quickly. Simply configure your contract, copy the generated code, and paste it into the Remix IDE for deployment. Below is an example of an ERC-20 token contract created with it: - - ![Screenshot of the OpenZeppelin Contracts Wizard showing an ERC-20 contract configuration.](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-2.webp) - - -## Compile - -The compilation transforms your Solidity source code into bytecode that can be deployed on the blockchain. During this process, the compiler checks your contract for syntax errors, ensures type safety, and generates the machine-readable instructions needed for blockchain execution. - -To compile your contract, ensure you have it opened in the Remix IDE Editor, and follow the instructions below: - -1. Select the **Solidity Compiler** plugin from the left panel. -2. Click the **Compile MyToken.sol** button. -3. If the compilation succeeded, you'll see a green checkmark indicating success in the **Solidity Compiler** icon. - -![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-3.gif) - -## Deploy - -Deployment is the process of publishing your compiled smart contract to the blockchain, making it permanently available for interaction. During deployment, you'll create a new instance of your contract on the blockchain, which involves: - -1. Select the **Deploy & Run Transactions** plugin from the left panel. -2. Configure the deployment settings: - 1. From the **ENVIRONMENT** dropdown, select **Injected Provider - MetaMask** (check the [Deploying Contracts](/smart-contracts/dev-environments/remix/deploy-a-contract/){target=\_blank} section of the Remix IDE guide for more details). - 2. (Optional) From the **ACCOUNT** dropdown, select the acccount you want to use for the deploy. - -3. Configure the contract parameters: - 1. Enter the address that will own the deployed token contract. - 2. Click the **Deploy** button to initiate the deployment. - -4. **MetaMask will pop up**: Review the transaction details. Click **Confirm** to deploy your contract. -5. If the deployment process succeeded, you will see the transaction details in the terminal, including the contract address and deployment transaction hash. - -![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-4.gif) - -## Interact with Your Contract - -Once deployed, you can interact with your contract through Remix. Find your contract under **Deployed/Unpinned Contracts**, and click it to expand the available methods. In this example, you'll mint some tokens to a given address: - -1. Expand the **mint** function: - 1. Enter the recipient address and the amount (remember to add 18 zeros for 1 whole token). - 2. Click **transact**. - -2. Click **Approve** to confirm the transaction in the MetaMask popup. - -3. If the transaction succeeds, you will see a green check mark in the terminal. - -4. You can also call the **balanceOf** function by passing the address of the **mint** call to confirm the new balance. - -![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-5.gif) - - -Other standard functions you can use: - -- **`transfer(address to, uint256 amount)`**: Send tokens to another address. -- **`approve(address spender, uint256 amount)`**: Allow another address to spend your tokens. - -Feel free to explore and interact with the contract's other functions using the same approach: select the method, provide any required parameters, and confirm the transaction in MetaMask when needed. - -## Where to Go Next - -
- -- Guide __Deploy an NFT with Remix__ - - --- - - Walk through deploying an ERC-721 Non-Fungible Token (NFT) using OpenZeppelin's battle-tested NFT implementation and Remix. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) - -
- - ---- - -Page Title: Deploy an NFT to Polkadot Hub with Foundry - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-.foundry.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/.foundry/ -- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub using Foundry, a Rust toolkit with high-performance compilation. - -# Deploy an NFT with Foundry - -## Introduction - -Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. - -This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. It showcases a secure approach using [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and the [Foundry](https://getfoundry.sh/){target=\_blank} toolchain. Foundry, a fast, Rust-written toolkit, ensures high-performance compilation and is fully compatible with the Hub’s EVM environment via standard Solidity compilation. - -## Prerequisites - -- Basic understanding of Solidity programming and NFT standards. -- Test tokens for gas fees (available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}). See the [step-by-step instructions](/smart-contracts/faucet/#get-test-tokens){target=\_blank}. -- A wallet with a private key for signing transactions. - -## Set Up Your Project - -To get started, take the following steps: - -1. Install Foundry: - - ```bash - curl -L https://foundry.paradigm.xyz | bash - foundryup - ``` - -2. Initialize your project: - - ```bash - forge init foundry-nft-deployment - cd foundry-nft-deployment - ``` - -3. Install OpenZeppelin contracts: - - ```bash - forge install OpenZeppelin/openzeppelin-contracts - ``` - -## Configure Foundry - -Edit `foundry.toml`: - -```toml title="foundry.toml" -[profile.default] -src = "src" -out = "out" -libs = ["lib"] -remappings = ['@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/'] - -[rpc_endpoints] -polkadot_hub_testnet = "https://testnet-passet-hub-eth-rpc.polkadot.io" -``` - -## Create Your Contract - -Create `src/MyNFT.sol`: - -```solidity title="src/MyNFT.sol" -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.20; - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "@openzeppelin/contracts/access/Ownable.sol"; - -contract MyNFT is ERC721, Ownable { - uint256 private _nextTokenId; - - constructor(address initialOwner) - ERC721("MyToken", "MTK") - Ownable(initialOwner) - {} - - function safeMint(address to) public onlyOwner { - uint256 tokenId = _nextTokenId++; - _safeMint(to, tokenId); - } -} -``` - -## Compile - -```bash -forge build -``` - -Verify the compilation by inspecting the bytecode: - -```bash -forge inspect MyNFT bytecode -``` - -## Deploy - -Deploy to Polkadot Hub TestNet: - -```bash -forge create MyNFT \ - --rpc-url polkadot_hub_testnet \ - --private-key YOUR_PRIVATE_KEY \ - --constructor-args YOUR_OWNER_ADDRESS \ - --broadcast -``` - -Replace `YOUR_PRIVATE_KEY` with your private key and `YOUR_OWNER_ADDRESS` with the address that will own the NFT contract. - -## Where to Go Next - -
- -- Guide __Verify Your Contract__ - - --- - - Now that you've deployed an NFT contract, learn how to verify it with Foundry. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/foundry/verify-a-contract/) - -- Guide __Deploy an ERC-20__ - - --- - - Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Foundry. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/foundry/) - -
- - ---- - -Page Title: Deploy an NFT to Polkadot Hub with Hardhat - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-hardhat.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/hardhat/ -- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub with Hardhat, a comprehenive development environment with built-in deployment capabilities. - -# Deploy an NFT with Hardhat - -## Introduction - -Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. - -This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. You'll use [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and [Hardhat](https://hardhat.org/docs/getting-started){target=\_blank}, a comprehensive development environment with built-in testing, debugging, and deployment capabilities. Hardhat uses standard Solidity compilation to generate EVM bytecode, making it fully compatible with Polkadot Hub's EVM environment. - -## Prerequisites - -- Basic understanding of Solidity programming and NFT standards. -- Node.js v22.13.1 or later. -- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. -- A wallet with a private key for signing transactions. - -## Set Up Your Project - -Take the following steps to get started: - -1. Initialize your Hardhat project: - - ```bash - mkdir hardhat-nft-deployment - cd hardhat-nft-deployment - npx hardhat --init - ``` - -2. Install OpenZeppelin contracts: - - ```bash - npm install @openzeppelin/contracts - ``` - -## Configure Hardhat - -Edit `hardhat.config.ts`: - -```typescript title="hardhat.config.ts" -import type { HardhatUserConfig } from 'hardhat/config'; - -import hardhatToolboxViemPlugin from '@nomicfoundation/hardhat-toolbox-viem'; -import { configVariable } from 'hardhat/config'; - -const config: HardhatUserConfig = { - plugins: [hardhatToolboxViemPlugin], - solidity: { - profiles: { - default: { - version: '0.8.28', - }, - production: { - version: '0.8.28', - settings: { - optimizer: { - enabled: true, - runs: 200, - }, - }, - }, - }, - }, - networks: { - hardhatMainnet: { - type: 'edr-simulated', - chainType: 'l1', - }, - hardhatOp: { - type: 'edr-simulated', - chainType: 'op', - }, - sepolia: { - type: 'http', - chainType: 'l1', - url: configVariable('SEPOLIA_RPC_URL'), - accounts: [configVariable('SEPOLIA_PRIVATE_KEY')], - }, - polkadotHubTestnet: { - type: 'http', - url: 'https://testnet-passet-hub-eth-rpc.polkadot.io', - chainId: 420420422, - accounts: [configVariable('PRIVATE_KEY')], - }, - }, -}; - -export default config; -``` - -!!! tip - Learn how to use Hardhat's [Config Variables](https://hardhat.org/docs/learn-more/configuration-variables){target=\_blank} to handle your private keys in a secure way. - -## Create Your Contract - -Create `contracts/MyNFT.sol`: - -```solidity title="contracts/MyNFT.sol" -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.20; - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "@openzeppelin/contracts/access/Ownable.sol"; - -contract MyNFT is ERC721, Ownable { - uint256 private _nextTokenId; - - constructor(address initialOwner) - ERC721("MyToken", "MTK") - Ownable(initialOwner) - {} - - function safeMint(address to) public onlyOwner { - uint256 tokenId = _nextTokenId++; - _safeMint(to, tokenId); - } -} -``` - -## Compile - -```bash -npx hardhat compile -``` - -## Set Up Deployment - -Create a deployment module in `ignition/modules/MyNFT.ts`: - -```typescript title="ignition/modules/MyNFT.ts" -import { buildModule } from '@nomicfoundation/hardhat-ignition/modules'; - -export default buildModule('MyNFTModule', (m) => { - const initialOwner = m.getParameter('initialOwner', 'INSERT_OWNER_ADDRESS'); - const myNFT = m.contract('MyNFT', [initialOwner]); - return { myNFT }; -}); -``` - -Replace `INSERT_OWNER_ADDRESS` with your desired owner address. - -## Deploy - -Deploy to Polkadot Hub TestNet: - -```bash -npx hardhat ignition deploy ignition/modules/MyNFT.ts --network polkadotHubTestnet -``` - -## Where to Go Next - -
- -- Guide __Verify Your Contract__ - - --- - - Now that you've deployed an NFT contract, learn how to verify it with Hardhat. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/hardhat/verify-a-contract/) - - -- Guide __Deploy an ERC-20__ - - --- - - Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Hardhat. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/hardhat/) - -
- - ---- - -Page Title: Deploy an NFT to Polkadot Hub with Remix - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-remix.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/ -- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub using Remix, a browser-based IDE for quick prototyping and learning. - -# Deploy an NFT with Remix - -## Introduction - -Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. - -This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. You'll use [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and [Remix](https://remix.ethereum.org/){target=\_blank}, a visual, browser-based environment perfect for rapid prototyping and learning. It requires no local installation and provides an intuitive interface for contract development. - -## Prerequisites - -- Basic understanding of Solidity programming and NFT standards. -- Test tokens for gas fees (available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}). See the [step-by-step instructions](/smart-contracts/faucet/#get-test-tokens){target=\_blank} -- A wallet with a private key for signing transactions. - -## Access Remix - -Navigate to [Remix](https://remix.ethereum.org/){target=\_blank} in your web browser. - -The interface will load with a default workspace containing sample contracts. In this interface, you can access a file explorer, edit your code, interact with various plugins for development, and use a terminal. - -## Create Your Contract - -1. Create a new file `contracts/MyNFT.sol`. -2. Paste the following code: - - ```solidity title="contracts/MyNFT.sol" - // SPDX-License-Identifier: MIT - pragma solidity ^0.8.20; - - import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; - import "@openzeppelin/contracts/access/Ownable.sol"; - - contract MyNFT is ERC721, Ownable { - uint256 private _nextTokenId; - - constructor(address initialOwner) - ERC721("MyToken", "MTK") - Ownable(initialOwner) - {} - - function safeMint(address to) public onlyOwner { - uint256 tokenId = _nextTokenId++; - _safeMint(to, tokenId); - } - } - ``` - -![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-01.webp) - -## Compile - -1. Navigate to the **Solidity Compiler** tab (third icon in the left sidebar). -2. Click **Compile MyNFT.sol** or press `Ctrl+S`. - -![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-02.webp) - -Compilation errors and warnings appear in the terminal panel at the bottom of the screen. - -## Deploy - -1. Navigate to the **Deploy & Run Transactions** tab. -2. Click the **Environment** dropdown, select **Browser Extension**, and click on **Injected Provider - MetaMask**. - - ![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-03.webp) - -3. In the deploy section, enter the initial owner address in the constructor parameter field. -4. Click **Deploy**. - - ![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-04.webp) - -5. Approve the transaction in your MetaMask wallet. - -Your deployed contract will appear in the **Deployed Contracts** section, ready for interaction. - -## Where to Go Next - -
- -- Guide __Verify Your Contract__ - - --- - - Now that you've deployed an NFT contract, learn how to verify it with Remix. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/remix/verify-a-contract/) - -- Guide __Deploy an ERC-20__ - - --- - - Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Remix. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/) - -
- - ---- - -Page Title: Dual Virtual Machine Stack - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-dual-vm-stack.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/dual-vm-stack/ -- Summary: Compare Polkadot’s dual smart contract VMs—REVM for EVM compatibility and PolkaVM for RISC-V performance, flexibility, and efficiency. - -# Dual Virtual Machine Stack - -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction - -Polkadot's smart contract platform supports two distinct virtual machine (VM) architectures, providing developers with flexibility in selecting the optimal execution backend for their specific needs. This approach strikes a balance between immediate Ethereum compatibility and long-term innovation, enabling developers to deploy either unmodified (Ethereum Virtual Machine) EVM contracts using Rust Ethereum Virtual Machine (REVM) or optimize for higher performance using PolkaVM (PVM). - -Both VM options share common infrastructure, including RPC interfaces, tooling support, and precompiles. The following sections compare architectures and guide you in selecting the best VM for your project's needs. - -## Migrate from EVM - -The [REVM backend](https://github.com/bluealloy/revm){target=\_blank} integrates a complete Rust implementation of the EVM, enabling Solidity contracts to run unchanged on Polkadot's smart contract platform. - -REVM allows developers to use their existing Ethereum tooling and infrastructure to build on Polkadot. Choose REVM to: - -- Migrate existing Ethereum contracts without modifications. -- Retain exact EVM behavior for audit tools. -- Use developer tools that rely upon inspecting EVM bytecode. -- Prioritize rapid deployment over optimization. -- Work with established Ethereum infrastructure and tooling to build on Polkadot. - -REVM enables Ethereum developers to seamlessly migrate to Polkadot, achieving performance and fee improvements without modifying their existing contracts or developer tooling stack. - -## Upgrade to PolkaVM - -[**PolkaVM**](https://github.com/paritytech/polkavm){target=\_blank} is a custom virtual machine optimized for performance with [RISC-V-based](https://en.wikipedia.org/wiki/RISC-V){target=\_blank} architecture, supporting Solidity and additional high-performance languages. It serves as the core execution environment, integrated directly within the runtime. Choose the PolkaVM for: - -- An efficient interpreter for immediate code execution. -- A planned [Just In Time (JIT)](https://en.wikipedia.org/wiki/Just-in-time_compilation){target=\_blank} compiler for optimized performance. -- Dual-mode execution capability, allowing selection of the most appropriate backend for specific workloads. -- Optimized performance for short-running contract calls through the interpreter. - -The interpreter remains particularly beneficial for contracts with minimal code execution, as it enables immediate code execution through lazy interpretation. - -## Architecture - -The following key components of PolkaVM work together to enable Ethereum compatibility on Polkadot-based chains. - -### Revive Pallet - -[**`pallet_revive`**](https://paritytech.github.io/polkadot-sdk/master/pallet_revive/index.html){target=\_blank} is a runtime module that executes smart contracts by adding extrinsics, runtime APIs, and logic to convert Ethereum-style transactions into formats compatible with Polkadot SDK-based blockchains. It processes Ethereum-style transactions through the following workflow: - -```mermaid -sequenceDiagram - participant User as User/dApp - participant Proxy as Ethereum JSON RPC Proxy - participant Chain as Blockchain Node - participant Pallet as pallet_revive - - User->>Proxy: Submit Ethereum Transaction - Proxy->>Chain: Repackage as Polkadot Compatible Transaction - Chain->>Pallet: Process Transaction - Pallet->>Pallet: Decode Ethereum Transaction - Pallet->>Pallet: Execute Contract via PolkaVM - Pallet->>Chain: Return Results - Chain->>Proxy: Forward Results - Proxy->>User: Return Ethereum-compatible Response -``` - -This proxy-based approach eliminates the need for node binary modifications, maintaining compatibility across different client implementations. Preserving the original Ethereum transaction payload simplifies the adaptation of existing tools, which can continue processing familiar transaction formats. - -### PolkaVM Design Fundamentals - -PolkaVM differs from the EVM in two key ways that make it faster, more hardware-efficient, and easier to extend: - -- **Register-based design**: Instead of a stack machine, PolkaVM uses a RISC-V–style register model. This design: - - - Uses a fixed set of registers to pass arguments, not an infinite stack. - - Maps cleanly to real hardware like x86-64. - - Simplifies compilation and boosts runtime efficiency. - - Enables tighter control over register allocation and performance tuning. - -- **64-bit word size**: PolkaVM runs on a native 64-bit word size, aligning directly with modern CPUs. This design: - - - Executes arithmetic operations with direct hardware support. - - Maintains compatibility with Solidity’s 256-bit types via YUL translation. - - Accelerates computation-heavy workloads through native word alignment. - - Integrates easily with low-level, performance-focused components. - -## Where To Go Next - -
- -- Learn __Contract Deployment__ - - --- - - Learn how REVM and PVM compare for compiling and deploying smart contracts. - - [:octicons-arrow-right-24: Reference](/smart-contracts/for-eth-devs/contract-deployment/) - -
- - ---- - -Page Title: Elastic Scaling - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-consensus-elastic-scaling.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/consensus/elastic-scaling/ -- Summary: Learn how elastic scaling in Polkadot boosts parachain throughput, reduces latency, and supports dynamic, cost-efficient resource allocation. - -# Elastic Scaling - -## Introduction - -Polkadot's architecture delivers scalability and security through its shared security model, where the relay chain coordinates and validates multiple parallel chains. - -Elastic scaling enhances this architecture by allowing parachains to utilize multiple computational cores simultaneously, breaking the previous 1:1 relationship between parachain and relay chain blocks. - -This technical advancement enables parachains to process multiple blocks within a single relay chain block, significantly increasing throughput capabilities. By leveraging [Agile Coretime](/polkadot-protocol/architecture/polkadot-chain/agile-coretime){target=\_blank}, parachains can dynamically adjust their processing capacity based on demand, creating an efficient and responsive infrastructure for high-throughput applications. - -## How Elastic Scaling Works - -Elastic scaling enables parachains to process multiple blocks in parallel by utilizing additional cores on the relay chain. This section provides a technical analysis of the performance advantages and details of the implementation. - -Consider a parachain that needs to process four consecutive parablocks. With traditional single-core allocation, the validation process follows a strictly sequential pattern. Each parablock undergoes a two-phase process on the relay chain: - -1. **Backing phase**: Validators create and distribute validity statements. -2. **Inclusion phase**: The parablock is included in the relay chain after availability verification. - -Throughout the following diagrams, specific notation is used to represent different components of the system: - -- **R1, R2, ...**: Relay chain blocks (produced at ~6-second intervals). -- **P1, P2, ...**: Parachain blocks that need validation and inclusion. -- **C1, C2, ...**: Cores on the relay chain. - -In the single-core scenario (assuming a 6-second relay chain block time), processing four parablocks requires approximately 30 seconds: - -```mermaid -sequenceDiagram - participant R1 as R1 - participant R2 as R2 - participant R3 as R3 - participant R4 as R4 - participant R5 as R5 - - Note over R1,R5: Single Core Scenario - - rect rgb(200, 220, 240) - Note right of R1: Core C1 - R1->>R1: Back P1 - R2->>R2: Include P1 - R2->>R2: Back P2 - R3->>R3: Include P2 - R3->>R3: Back P3 - R4->>R4: Include P3 - R4->>R4: Back P4 - R5->>R5: Include P4 - end -``` - -With elastic scaling utilizing two cores simultaneously, the same four parablocks can be processed in approximately 18 seconds: - -```mermaid -sequenceDiagram - participant R1 as R1 - participant R2 as R2 - participant R3 as R3 - participant R4 as R4 - participant R5 as R5 - - Note over R1,R3: Multi-Core Scenario - - rect rgb(200, 220, 240) - Note right of R1: Core C1 - R1->>R1: Back P1 - R2->>R2: Include P1 - R2->>R2: Back P2 - R3->>R3: Include P2 - end - - rect rgb(220, 200, 240) - Note right of R1: Core C2 - R1->>R1: Back P3 - R2->>R2: Include P3 - R2->>R2: Back P4 - R3->>R3: Include P4 - end -``` - -To help interpret the sequence diagrams above, note the following key elements: - -- The horizontal axis represents time progression through relay chain blocks (R1-R5). -- Each colored rectangle shows processing on a specific core (C1 or C2). -- In the single-core scenario, all blocks must be processed sequentially on one core. -- In the multi-core scenario, blocks are processed in parallel across multiple cores, reducing total time. - -The relay chain processes these multiple parablocks as independent validation units during the backing, availability, and approval phases. However, during inclusion, it verifies that their state roots align properly to maintain chain consistency. - -From an implementation perspective: - -- **Parachain side**: Collators must increase their block production rate to utilize multiple cores fully. -- **Validation process**: Each core operates independently, but with coordinated state verification. -- **Resource management**: Cores are dynamically allocated based on parachain requirements. -- **State consistency**: While backed and processed in parallel, the parablocks maintain sequential state transitions. - -## Benefits of Elastic Scaling - -- **Increased throughput**: Multiple concurrent cores enable parachains to process transactions at multiples of their previous capacity. By allowing multiple parachain blocks to be validated within each relay chain block cycle, applications can achieve significantly higher transaction volumes. - -- **Lower latency**: Transaction finality improves substantially with multi-core processing. Parachains currently achieve 2-second latency with three cores, with projected improvements to 500ms using 12 cores, enabling near-real-time application responsiveness. - -- **Resource efficiency**: Applications acquire computational resources precisely matched to their needs, eliminating wasteful over-provisioning. Coretime can be purchased at granular intervals (blocks, hours, days), creating cost-effective operations, particularly for applications with variable transaction patterns. - -- **Scalable growth**: New applications can launch with minimal initial resource commitment and scale dynamically as adoption increases. This eliminates the traditional paradox of either over-allocating resources (increasing costs) or under-allocating (degrading performance) during growth phases. - -- **Workload distribution**: Parachains intelligently distribute workloads across cores during peak demand periods and release resources when traffic subsides. Paired with secondary coretime markets, this ensures maximum resource utilization across the entire network ecosystem. - -- **Reliable performance**: End-users experience reliable application performance regardless of network congestion levels. Applications maintain responsiveness even during traffic spikes, eliminating performance degradation that commonly impacts blockchain applications during high-demand periods. - -## Use Cases - -Elastic scaling enables applications to dynamically adjust their resource consumption based on real-time demand. This is especially valuable for decentralized applications where usage patterns can be highly variable. The following examples illustrate common scenarios where elastic scaling delivers significant performance and cost-efficiency benefits. - -### Handling Sudden Traffic Spikes - -Many decentralized applications experience unpredictable, high-volume traffic bursts, especially in gaming, DeFi protocols, NFT auctions, messaging platforms, and social media. Elastic scaling allows these systems to acquire additional coretime during peak usage and release it during quieter periods, ensuring responsiveness without incurring constant high infrastructure costs. - -### Supporting Early-Stage Growth - -Startups and new projects often begin with uncertain or volatile demand. With elastic scaling, teams can launch with minimal compute resources (e.g., a single core) and gradually scale as adoption increases. This prevents overprovisioning and enables cost-efficient growth until the application is ready for more permanent or horizontal scaling. - -### Scaling Massive IoT Networks - -Internet of Things (IoT) applications often involve processing data from millions of devices in real time. Elastic scaling supports this need by enabling high-throughput transaction processing as demand fluctuates. Combined with Polkadot’s shared security model, it provides a reliable and privacy-preserving foundation for large-scale IoT deployments. - -### Powering Real-Time, Low-Latency Systems - -Applications like payment processors, trading platforms, gaming engines, or real-time data feeds require fast, consistent performance. Elastic scaling can reduce execution latency during demand spikes, helping ensure low-latency, reliable service even under heavy load. - - ---- - -Page Title: Get Started with Parachain Development - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-get-started.md -- Canonical (HTML): https://docs.polkadot.com/parachains/get-started/ -- Summary: Practical examples and tutorials for building and deploying Polkadot parachains, covering everything from launch to customization and cross-chain messaging. - -# Get Started - -The following sections provide practical recipes for building parachains on Polkadot—each focused on specific development scenarios with step-by-step, hands-on examples. - -## Quick Start Guides - -Quick start guides help developers set up and interact with the Polkadot parachain ecosystem using various tools and frameworks. - -| Tutorial | Tools | Description | -| :--------------------------------------------------------------------------------------------: | :----------------------------: | :---------------------------------------------------------------------: | -| [Set Up the Parachain Template](/parachains/launch-a-parachain/set-up-the-parachain-template/) | Polkadot SDK | Learn how to set up and run the Polkadot SDK Parachain Template locally | -| [Launch a Local Parachain](/parachains/testing/run-a-parachain-network/) | Zombienet, Chopsticks | Set up a local development environment for testing | -| [Connect to Polkadot](/chain-interactions/query-on-chain-data/query-sdks/) | Polkadot.js, Substrate Connect | Connect your application to Polkadot networks | -| [Fork an Existing Parachain](/parachains/testing/fork-a-parachain/) | Chopsticks | Create a local fork of a live parachain for testing | - -## Launch a Simple Parachain - -Learn the fundamentals of launching and deploying a parachain to the Polkadot network. - -| Tutorial | Description | -| :--------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------: | -| [Set Up the Parachain Template](/parachains/launch-a-parachain/set-up-the-parachain-template/) | Polkadot SDK | -| [Deploy to Polkadot](/parachains/launch-a-parachain/deploy-to-polkadot/) | Step-by-step tutorial to deploying your parachain to Polkadot | -| [Obtain Coretime](/parachains/launch-a-parachain/obtain-coretime/) | Learn how to acquire blockspace using Polkadot's coretime model (RegionX) | - -## Customize Your Runtime - -Build custom functionality for your parachain by composing and creating pallets. - -| Tutorial | Description | -| :-------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------: | -| [Add Existing Pallets to the Runtime](/parachains/customize-runtime/add-existing-pallets/) | Integrate pre-built pallets from the FRAME ecosystem | -| [Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/) | Configure and use multiple instances of the same pallet | -| [Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/) | Enable smart contract capabilities using Contracts or EVM pallets | - -### Pallet Development - -Deep dive into creating and managing custom pallets for your parachain. - -| Tutorial | Description | -| :--------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------: | -| [Create a Custom Pallet](/parachains/customize-runtime/pallet-development/create-a-pallet/) | Build a pallet from scratch with custom logic | -| [Mock Your Runtime](/parachains/customize-runtime/pallet-development/mock-runtime/) | Set up a mock runtime environment for testing | -| [Pallet Unit Testing](/parachains/customize-runtime/pallet-development/pallet-testing/) | Write comprehensive tests for your pallet logic | -| [Add Your Custom Pallet to the Runtime](/parachains/customize-runtime/pallet-development/add-pallet-to-runtime/) | Integrate your custom pallet into your parachain runtime | -| [Benchmark the Custom Pallet](/parachains/customize-runtime/pallet-development/benchmark-pallet/) | Measure and optimize pallet performance with benchmarking | - -## Testing - -Test your parachain in various environments before production deployment. - -| Tutorial | Description | -| :---------------------------------------------------------------------: | :-----------------------------------------------------: | -| [Fork a Parachain](/parachains/testing/fork-a-parachain/) | Use Chopsticks to create a local fork for testing | -| [Run a Parachain Network](/parachains/testing/run-a-parachain-network/) | Launch a complete parachain test network with Zombienet | - -## Runtime Upgrades and Maintenance - -Manage your parachain's lifecycle with forkless upgrades and maintenance operations. - -| Tutorial | Description | -| :-----------------------------------------------------------------------: | :--------------------------------------------------: | -| [Runtime Upgrades](/parachains/runtime-maintenance/runtime-upgrades/) | Perform forkless runtime upgrades via governance | -| [Storage Migrations](/parachains/runtime-maintenance/storage-migrations/) | Safely migrate storage when updating runtime logic | -| [Unlock Parachains](/parachains/runtime-maintenance/unlock-parachains/) | Understand parachain lifecycle and unlock mechanisms | - -## Interoperability - -Configure your parachain for cross-chain communication using XCM (Cross-Consensus Messaging). - -| Tutorial | Description | -| :--------------------------------------------------------------------------------------------------------: | :----------------------------------------------------: | -| [Open HRMP Channels Between Parachains](/parachains/interoperability/channels-between-parachains/) | Establish communication channels with other parachains | -| [Open HRMP Channels with System Parachains](/parachains/interoperability/channels-with-system-parachains/) | Connect with Asset Hub and other system parachains | - -## Integrations - -Integrate your parachain with essential ecosystem tools and services. - -| Tutorial | Description | -| :--------------------------------------------: | :----------------------------------------------------: | -| [Wallets](/parachains/integrations/wallets/) | Integrate wallet support for user interactions | -| [Indexers](/parachains/integrations/indexers/) | Set up indexing solutions for querying blockchain data | -| [Oracles](/parachains/integrations/oracles/) | Connect your parachain to off-chain data sources | - -## Additional Resources - -- [Polkadot SDK Documentation](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/index.html) -- [Polkadot Wiki - Parachains](https://wiki.polkadot.network/docs/learn-parachains/) - - ---- - -Page Title: Get Started with Smart Contracts - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-get-started.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/get-started/ -- Summary: Practical examples for building and deploying smart contracts on Polkadot Hub, from connecting and tooling to deployment, integrations, and precompiles. - -# Get Started - -This resource provides quick-starts for building smart contracts on Polkadot Hub. Use the tables below to jump directly to the tools and workflows you need. - -## Quick Starts - -Kick off development fast with curated links for connecting, funding, exploring, and deploying your first contract. - -| Quick Start | Tools | Description | -|:---------------------------------------------------------------------------------------------------:|:---------------------:|:---------------------------------------------------------------:| -| [Connect to Polkadot](/smart-contracts/connect/){target=\_blank} | Polkadot.js, MetaMask | Add the network, configure RPC, verify activity in the explorer | -| [Get Test Tokens](/smart-contracts/faucets/){target=\_blank} | - | Request test funds to deploy and interact with contracts | -| [Explore Transactions](/smart-contracts/explorers/){target=\_blank} | Subscan | Inspect transactions, logs, token transfers, and contract state | -| [Deploy with Remix](/smart-contracts/dev-environments/remix/deploy-a-contract/){target=\_blank} | Remix | One‑click browser deployment to Polkadot Hub | -| [Deploy with Foundry](/smart-contracts/dev-environments/foundry/deploy-a-contract/){target=\_blank} | Foundry | Scripted deployments and testing from the CLI | -| [Deploy with Hardhat](/smart-contracts/dev-environments/hardhat/deploy-a-contract/){target=\_blank} | Hardhat | Project scaffolding, testing, and deployments | - -## Build and Test Locally - -Set up local environments and CI-friendly workflows to iterate quickly and validate changes before deploying. - -| Build and Test Locally | Tools | Description | -|:------------------------------------------------------------------------------------------------------------:|:-----------------:|:----------------------------------------------------:| -| [Run a Local Dev Node](/smart-contracts/dev-environments/local-dev-node/){target=\_blank} | Polkadot SDK node | Spin up a local node for iterative development | -| [Remix: Get Started](/smart-contracts/dev-environments/remix/get-started/){target=\_blank} | Remix | Connect Remix to Polkadot Hub and configure accounts | -| [Remix: Verify a Contract](/smart-contracts/dev-environments/remix/verify-a-contract/){target=\_blank} | Remix | Publish verified source on explorers | -| [Foundry: Install and Config](/smart-contracts/dev-environments/foundry/install-and-config/){target=\_blank} | Foundry | Install toolchain and configure networks | -| [Foundry: Compile and Test](/smart-contracts/dev-environments/foundry/compile-and-test/){target=\_blank} | Foundry | Write and run Solidity tests locally | -| [Foundry: Verify a Contract](/smart-contracts/dev-environments/foundry/verify-a-contract/){target=\_blank} | Foundry | Verify deployed bytecode and metadata | -| [Hardhat: Install and Config](/smart-contracts/dev-environments/hardhat/install-and-config/){target=\_blank} | Hardhat | Initialize a project and configure networks | -| [Hardhat: Compile and Test](/smart-contracts/dev-environments/hardhat/compile-and-test/){target=\_blank} | Hardhat | Unit test contracts and run scripts | -| [Hardhat: Verify a Contract](/smart-contracts/dev-environments/hardhat/verify-a-contract/){target=\_blank} | Hardhat | Verify deployments on explorers | - -## Ethereum Developer Resources - -Bridge your Ethereum knowledge with Polkadot Hub specifics: account mapping, fees, JSON‑RPC, and deployment. - -| Ethereum Developer Guides | Description | -|:---------------------------------------------------------------------------------------------------------:|:---------------------------------------------------------------:| -| [Accounts](/smart-contracts/for-eth-devs/accounts/){target=\_blank} | How 20‑byte Ethereum addresses map to 32‑byte Polkadot accounts | -| [Blocks, Transactions, and Fees](/smart-contracts/for-eth-devs/blocks-transactions-fees/){target=\_blank} | Transaction types, fees, and multi‑dimensional metering | -| [Gas Model](/smart-contracts/for-eth-devs/gas-model/){target=\_blank} | Gas vs. weight, proof size, and storage deposits | -| [Contract Deployment](/smart-contracts/for-eth-devs/contract-deployment/){target=\_blank} | Deployment patterns and best practices on Polkadot Hub | -| [JSON‑RPC APIs](/smart-contracts/for-eth-devs/json-rpc-apis/){target=\_blank} | Supported Ethereum JSON‑RPC methods and examples | -| [Migration](/smart-contracts/for-eth-devs/migration/){target=\_blank} | Port existing apps and tooling to Polkadot Hub | -| [Dual VM Stack](/smart-contracts/for-eth-devs/dual-vm-stack/){target=\_blank} | Overview of EVM and native execution on the Hub | - -## Cookbook: Hands‑on Tutorials - -Follow step‑by‑step guides that walk through common tasks and complete dApp examples. - -| Tutorial | Tools | Description | -|:--------------------------------------------------------------------------------------------------------:|:-------------------:|:-----------------------------------------:| -| [Deploy a Basic Contract](/smart-contracts/cookbook/smart-contracts/deploy-basic/remix/){target=\_blank} | Remix | Minimal deployment walkthrough | -| [Deploy an ERC‑20](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/){target=\_blank} | Remix, OpenZeppelin | Create, deploy, and mint a fungible token | -| [Deploy an NFT (ERC‑721)](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/){target=\_blank} | Remix, OpenZeppelin | Build and deploy an NFT collection | -| [Uniswap V2](/smart-contracts/cookbook/eth-dapps/uniswap-v2/){target=\_blank} | Hardhat | Full dApp project: compile, test, deploy | -| [Zero‑to‑Hero dApp](/smart-contracts/cookbook/dapps/zero-to-hero/){target=\_blank} | Multiple | End‑to‑end dApp patterns and practices | - -## Libraries - -Choose the client libraries that fit your stack for connecting wallets and calling contracts. - -| Library | Description | -|:------------------------------------------------------------------:|:-------------------------------------------------------:| -| [Ethers.js](/smart-contracts/libraries/ethers-js/){target=\_blank} | Connect, sign, and interact with contracts using Ethers | -| [viem](/smart-contracts/libraries/viem/){target=\_blank} | Type‑safe EVM interactions and utilities | -| [Wagmi](/smart-contracts/libraries/wagmi/){target=\_blank} | React hooks for wallet connections and contract calls | -| [Web3.js](/smart-contracts/libraries/web3-js/){target=\_blank} | Web3 provider and contract APIs | -| [Web3.py](/smart-contracts/libraries/web3-py/){target=\_blank} | Python toolkit for on‑chain interactions and scripts | - -## Integrations - -Integrate essential services like wallets, indexers, and oracles to round out your dApp. - -| Integration | Description | -|:-------------------------------------------------------------------:|:-----------------------------------------:| -| [Wallets](/smart-contracts/integrations/wallets/){target=\_blank} | Supported wallets and configuration notes | -| [Indexers](/smart-contracts/integrations/indexers/){target=\_blank} | Index and query blockchain data | -| [Oracles](/smart-contracts/integrations/oracles/){target=\_blank} | Bring external data on‑chain | - -## Precompiles - -Discover precompiled system contracts available on the Hub and how to use them. - -| Topic | Description | -|:------------------------------------------------------------------------:|:---------------------------------------------------:| -| [Overview of Precompiles](/smart-contracts/precompiles/){target=\_blank} | What precompiles are available on the Hub | -| [ETH Native](/smart-contracts/precompiles/eth-native/){target=\_blank} | EVM precompiles and interfaces | -| [Staking](/smart-contracts/precompiles/staking/){target=\_blank} | Interact with staking functionality via precompiles | -| [XCM](/smart-contracts/precompiles/xcm/){target=\_blank} | Cross‑chain messaging helpers for contracts | - -From here, follow the quick starts to get connected, iterate locally with your preferred tools, and use the guides, libraries, integrations, and precompiles as you grow into production‑ready dApps. If you get stuck, [open an issue](https://github.com/polkadot-developers/polkadot-docs/issues/new?template=docs-issue.yml){target=\_blank} or reach out in the community channels. - - ---- - -Page Title: Glossary - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-glossary.md -- Canonical (HTML): https://docs.polkadot.com/reference/glossary/ -- Summary: Glossary of terms used within the Polkadot ecosystem, Polkadot SDK, its subsequent libraries, and other relevant Web3 terminology. - -# Glossary - -Key definitions, concepts, and terminology specific to the Polkadot ecosystem are included here. - -Additional glossaries from around the ecosystem you might find helpful: - -- [Polkadot Wiki Glossary](https://wiki.polkadot.com/general/glossary){target=\_blank} -- [Polkadot SDK Glossary](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/glossary/index.html){target=\_blank} - -## Authority - -The role in a blockchain that can participate in consensus mechanisms. - -- **[GRANDPA](#grandpa)**: The authorities vote on chains they consider final. -- **[Blind Assignment of Blockchain Extension](#blind-assignment-of-blockchain-extension-babe) (BABE)**: The authorities are also [block authors](#block-author). - -Authority sets can be used as a basis for consensus mechanisms such as the [Nominated Proof of Stake (NPoS)](#nominated-proof-of-stake-npos) protocol. - -## Authority Round (Aura) - -A deterministic [consensus](#consensus) protocol where block production is limited to a rotating list of [authorities](#authority) that take turns creating blocks. In authority round (Aura) consensus, most online authorities are assumed to be honest. It is often used in combination with [GRANDPA](#grandpa) as a [hybrid consensus](#hybrid-consensus) protocol. - -Learn more by reading the official [Aura consensus algorithm](https://openethereum.github.io/Aura){target=\_blank} wiki article. - -## Blind Assignment of Blockchain Extension (BABE) - -A [block authoring](#block-author) protocol similar to [Aura](#authority-round-aura), except [authorities](#authority) win [slots](#slot) based on a Verifiable Random Function (VRF) instead of the round-robin selection method. The winning authority can select a chain and submit a new block. - -Learn more by reading the official Web3 Foundation [BABE research document](https://research.web3.foundation/Polkadot/protocols/block-production/Babe){target=\_blank}. - -## Block Author - -The node responsible for the creation of a block, also called _block producers_. In a Proof of Work (PoW) blockchain, these nodes are called _miners_. - -## Byzantine Fault Tolerance (BFT) - -The ability of a distributed computer network to remain operational if a certain proportion of its nodes or [authorities](#authority) are defective or behaving maliciously. A distributed network is typically considered Byzantine fault tolerant if it can remain functional, with up to one-third of nodes assumed to be defective, offline, actively malicious, and part of a coordinated attack. - -### Byzantine Failure - -The loss of a network service due to node failures that exceed the proportion of nodes required to reach consensus. - -### Practical Byzantine Fault Tolerance (pBFT) - -An early approach to Byzantine fault tolerance (BFT), practical Byzantine fault tolerance (pBFT) systems tolerate Byzantine behavior from up to one-third of participants. - -The communication overhead for such systems is `O(n²)`, where `n` is the number of nodes (participants) in the system. - -### Preimage - -A preimage is the data that is input into a hash function to calculate a hash. Since a hash function is a [one-way function](https://en.wikipedia.org/wiki/One-way_function){target=\_blank}, the output, the hash, cannot be used to reveal the input, the preimage. - -## Call - -In the context of pallets containing functions to be dispatched to the runtime, `Call` is an enumeration data type that describes the functions that can be dispatched with one variant per pallet. A `Call` represents a [dispatch](#dispatchable) data structure object. - -## Chain Specification - -A chain specification file defines the properties required to run a node in an active or new Polkadot SDK-built network. It often contains the initial genesis runtime code, network properties (such as the network's name), the initial state for some pallets, and the boot node list. The chain specification file makes it easy to use a single Polkadot SDK codebase as the foundation for multiple independently configured chains. - -## Collator - -An [author](#block-author) of a [parachain](#parachain) network. -They aren't [authorities](#authority) in themselves, as they require a [relay chain](#relay-chain) to coordinate [consensus](#consensus). - -More details are found on the [Polkadot Collator Wiki](https://wiki.polkadot.com/learn/learn-collator/){target=\_blank}. - -## Collective - -Most often used to refer to an instance of the Collective pallet on Polkadot SDK-based networks such as [Kusama](#kusama) or [Polkadot](#polkadot) if the Collective pallet is part of the FRAME-based runtime for the network. - -## Consensus - -Consensus is the process blockchain nodes use to agree on a chain's canonical fork. It is composed of [authorship](#block-author), finality, and [fork-choice rule](#fork-choice-rulestrategy). In the Polkadot ecosystem, these three components are usually separate and the term consensus often refers specifically to authorship. - -See also [hybrid consensus](#hybrid-consensus). - -## Consensus Algorithm - -Ensures a set of [actors](#authority)—who don't necessarily trust each other—can reach an agreement about the state as the result of some computation. Most consensus algorithms assume that up to one-third of the actors or nodes can be [Byzantine fault tolerant](#byzantine-fault-tolerance-bft). - -Consensus algorithms are generally concerned with ensuring two properties: - -- **Safety**: Indicating that all honest nodes eventually agreed on the state of the chain. -- **Liveness**: Indicating the ability of the chain to keep progressing. - -## Consensus Engine - -The node subsystem responsible for consensus tasks. - -For detailed information about the consensus strategies of the [Polkadot](#polkadot) network, see the [Polkadot Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} blog series. - -See also [hybrid consensus](#hybrid-consensus). - -## Coretime - -The time allocated for utilizing a core, measured in relay chain blocks. There are two types of coretime: *on-demand* and *bulk*. - -On-demand coretime refers to coretime acquired through bidding in near real-time for the validation of a single parachain block on one of the cores reserved specifically for on-demand orders. They are available as an on-demand coretime pool. Set of cores that are available on-demand. Cores reserved through bulk coretime could also be made available in the on-demand coretime pool, in parts or in entirety. - -Bulk coretime is a fixed duration of continuous coretime represented by an NFT that can be split, shared, or resold. It is managed by the [Broker pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_broker/index.html){target=\_blank}. - -## Development Phrase - -A [mnemonic phrase](https://en.wikipedia.org/wiki/Mnemonic#For_numerical_sequences_and_mathematical_operations){target=\_blank} that is intentionally made public. - -Well-known development accounts, such as Alice, Bob, Charlie, Dave, Eve, and Ferdie, are generated from the same secret phrase: - -``` -bottom drive obey lake curtain smoke basket hold race lonely fit walk -``` - -Many tools in the Polkadot SDK ecosystem, such as [`subkey`](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/bin/utils/subkey){target=\_blank}, allow you to implicitly specify an account using a derivation path such as `//Alice`. - -## Digest - -An extensible field of the [block header](#header) that encodes information needed by several actors in a blockchain network, including: - -- [Light clients](#light-client) for chain synchronization. -- Consensus engines for block verification. -- The runtime itself, in the case of pre-runtime digests. - -## Dispatchable - -Function objects that act as the entry points in FRAME [pallets](#pallet). Internal or external entities can call them to interact with the blockchain’s state. They are a core aspect of the runtime logic, handling [transactions](#transaction) and other state-changing operations. - -## Events - -A means of recording that some particular [state](#state) transition happened. - -In the context of [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities), events are composable data types that each [pallet](#pallet) can individually define. Events in FRAME are implemented as a set of transient storage items inspected immediately after a block has been executed and reset during block initialization. - -## Executor - -A means of executing a function call in a given [runtime](#runtime) with a set of dependencies. -There are two orchestration engines in Polkadot SDK, _WebAssembly_ and _native_. - -- The _native executor_ uses a natively compiled runtime embedded in the node to execute calls. This is a performance optimization available to up-to-date nodes. - -- The _WebAssembly executor_ uses a [Wasm](#webassembly-wasm) binary and a Wasm interpreter to execute calls. The binary is guaranteed to be up-to-date regardless of the version of the blockchain node because it is persisted in the [state](#state) of the Polkadot SDK-based chain. - -## Existential Deposit - -The minimum balance an account is allowed to have in the [Balances pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/index.html){target=\_blank}. Accounts cannot be created with a balance less than the existential deposit amount. - -If an account balance drops below this amount, the Balances pallet uses [a FRAME System API](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.dec_ref){target=\_blank} to drop its references to that account. - -If the Balances pallet reference to an account is dropped, the account can be [reaped](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.allow_death){target=\_blank}. - -## Extrinsic - -A general term for data that originates outside the runtime, is included in a block, and leads to some action. This includes user-initiated transactions and inherent transactions placed into the block by the block builder. - -It is a SCALE-encoded array typically consisting of a version number, signature, and varying data types indicating the resulting runtime function to be called. Extrinsics can take two forms: [inherents](#inherent-transactions) and [transactions](#transaction). - -For more technical details, see the [Polkadot spec](https://spec.polkadot.network/id-extrinsics){target=\_blank}. - -## Fork Choice Rule/Strategy - -A fork choice rule or strategy helps determine which chain is valid when reconciling several network forks. A common fork choice rule is the [longest chain](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/struct.LongestChain.html){target=\_blank}, in which the chain with the most blocks is selected. - -## FRAME (Framework for Runtime Aggregation of Modularized Entities) - -Enables developers to create blockchain [runtime](#runtime) environments from a modular set of components called [pallets](#pallet). It utilizes a set of procedural macros to construct runtimes. - -[Visit the Polkadot SDK docs for more details on FRAME.](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank} - -## Full Node - -A node that prunes historical states, keeping only recently finalized block states to reduce storage needs. Full nodes provide current chain state access and allow direct submission and validation of [extrinsics](#extrinsic), maintaining network decentralization. - -## Genesis Configuration - -A mechanism for specifying the initial state of a blockchain. By convention, this initial state or first block is commonly referred to as the genesis state or genesis block. The genesis configuration for Polkadot SDK-based chains is accomplished by way of a [chain specification](#chain-specification) file. - -## GRANDPA - -A deterministic finality mechanism for blockchains that is implemented in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. - -The [formal specification](https://github.com/w3f/consensus/blob/master/pdf/grandpa-old.pdf){target=\_blank} is maintained by the [Web3 Foundation](https://web3.foundation/){target=\_blank}. - -## Header - -A structure that aggregates the information used to summarize a block. Primarily, it consists of cryptographic information used by [light clients](#light-client) to get minimally secure but very efficient chain synchronization. - -## Hybrid Consensus - -A blockchain consensus protocol that consists of independent or loosely coupled mechanisms for [block production](#block-author) and finality. - -Hybrid consensus allows the chain to grow as fast as probabilistic consensus protocols, such as [Aura](#authority-round-aura), while maintaining the same level of security as deterministic finality consensus protocols, such as [GRANDPA](#grandpa). - -## Inherent Transactions - -A special type of unsigned transaction, referred to as _inherents_, that enables a block authoring node to insert information that doesn't require validation directly into a block. - -Only the block-authoring node that calls the inherent transaction function can insert data into its block. In general, validators assume the data inserted using an inherent transaction is valid and reasonable even if it can't be deterministically verified. - -## JSON-RPC - -A stateless, lightweight remote procedure call protocol encoded in JavaScript Object Notation (JSON). JSON-RPC provides a standard way to call functions on a remote system by using JSON. - -For Polkadot SDK, this protocol is implemented through the [Parity JSON-RPC](https://github.com/paritytech/jsonrpc){target=\_blank} crate. - -## Keystore - -A subsystem for managing keys for the purpose of producing new blocks. - -## Kusama - -[Kusama](https://kusama.network/){target=\_blank} is a Polkadot SDK-based blockchain that implements a design similar to the [Polkadot](#polkadot) network. - -Kusama is a [canary](https://en.wiktionary.org/wiki/canary_in_a_coal_mine){target=\_blank} network and is referred to as [Polkadot's "wild cousin."](https://wiki.polkadot.com/learn/learn-comparisons-kusama/){target=\_blank}. - -As a canary network, Kusama is expected to be more stable than a test network like [Westend](#westend) but less stable than a production network like [Polkadot](#polkadot). Kusama is controlled by its network participants and is intended to be stable enough to encourage meaningful experimentation. - -## libp2p - -A peer-to-peer networking stack that allows the use of many transport mechanisms, including WebSockets (usable in a web browser). - -Polkadot SDK uses the [Rust implementation](https://github.com/libp2p/rust-libp2p){target=\_blank} of the `libp2p` networking stack. - -## Light Client - -A type of blockchain node that doesn't store the [chain state](#state) or produce blocks. - -A light client can verify cryptographic primitives and provides a [remote procedure call (RPC)](https://en.wikipedia.org/wiki/Remote_procedure_call){target=\_blank} server, enabling blockchain users to interact with the network. - -## Metadata - -Data that provides information about one or more aspects of a system. -The metadata that exposes information about a Polkadot SDK blockchain enables you to interact with that system. - -## Nominated Proof of Stake (NPoS) - -A method for determining [validators](#validator) or _[authorities](#authority)_ based on a willingness to commit their stake to the proper functioning of one or more block-producing nodes. - -## Oracle - -An entity that connects a blockchain to a non-blockchain data source. Oracles enable the blockchain to access and act upon information from existing data sources and incorporate data from non-blockchain systems and services. - -## Origin - -A [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitive that identifies the source of a [dispatched](#dispatchable) function call into the [runtime](#runtime). The FRAME System pallet defines three built-in [origins](#origin). As a [pallet](#pallet) developer, you can also define custom origins, such as those defined by the [Collective pallet](https://paritytech.github.io/substrate/master/pallet_collective/enum.RawOrigin.html){target=\_blank}. - -## Pallet - -A module that can be used to extend the capabilities of a [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities)-based [runtime](#runtime). -Pallets bundle domain-specific logic with runtime primitives like [events](#events) and [storage items](#storage-item). - -## Parachain - -A parachain is a blockchain that derives shared infrastructure and security from a _[relay chain](#relay-chain)_. -You can learn more about parachains on the [Polkadot Wiki](https://wiki.polkadot.com/learn/learn-parachains/){target=\_blank}. - -## Paseo - -Paseo TestNet provisions testing on Polkadot's "production" runtime, which means less chance of feature or code mismatch when developing parachain apps. Specifically, after the [Polkadot Technical fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} proposes a runtime upgrade for Polkadot, this TestNet is updated, giving a period where the TestNet will be ahead of Polkadot to allow for testing. - -## Polkadot - -The [Polkadot network](https://polkadot.com/){target=\_blank} is a blockchain that serves as the central hub of a heterogeneous blockchain network. It serves the role of the [relay chain](#relay-chain) and provides shared infrastructure and security to support [parachains](#parachain). - -## Polkadot Cloud - -Polkadot Cloud is a platform for deploying resilient, customizable and scalable Web3 applications through Polkadot's functionality. It encompasses the wider Polkadot network infrastructure and security layer where parachains operate. The platform enables users to launch Ethereum-compatible chains, build specialized blockchains, and flexibly manage computing resources through on-demand or bulk coretime purchases. Initially launched with basic parachain functionality, Polkadot Cloud has evolved to offer enhanced flexibility with features like coretime, elastic scaling, and async backing for improved performance. - -## Polkadot Hub - -Polkadot Hub is a Layer 1 platform that serves as the primary entry point to the Polkadot ecosystem, providing essential functionality without requiring parachain deployment. It offers core services including smart contracts, identity management, staking, governance, and interoperability with other ecosystems, making it simple and fast for both builders and users to get started in Web3. - -## PolkaVM - -PolkaVM is a custom virtual machine optimized for performance, leveraging a RISC-V-based architecture to support Solidity and any language that compiles to RISC-V. It is specifically designed for the Polkadot ecosystem, enabling smart contract deployment and execution. - -## Relay Chain - -Relay chains are blockchains that provide shared infrastructure and security to the [parachains](#parachain) in the network. In addition to providing [consensus](#consensus) capabilities, relay chains allow parachains to communicate and exchange digital assets without needing to trust one another. - -## Rococo - -A [parachain](#parachain) test network for the Polkadot network. The [Rococo](#rococo) network is a Polkadot SDK-based blockchain with an October 14, 2024 deprecation date. Development teams are encouraged to use the Paseo TestNet instead. - -## Runtime - -The runtime represents the [state transition function](#state-transition-function-stf) for a blockchain. In Polkadot SDK, the runtime is stored as a [Wasm](#webassembly-wasm) binary in the chain state. The Runtime is stored under a unique state key and can be modified during the execution of the state transition function. - -## Slot - -A fixed, equal interval of time used by consensus engines such as [Aura](#authority-round-aura) and [BABE](#blind-assignment-of-blockchain-extension-babe). In each slot, a subset of [authorities](#authority) is permitted, or obliged, to [author](#block-author) a block. - -## Sovereign Account - -The unique account identifier for each chain in the relay chain ecosystem. It is often used in cross-consensus (XCM) interactions to sign XCM messages sent to the relay chain or other chains in the ecosystem. - -The sovereign account for each chain is a root-level account that can only be accessed using the Sudo pallet or through governance. The account identifier is calculated by concatenating the Blake2 hash of a specific text string and the registered parachain identifier. - -## SS58 Address Format - -A public key address based on the Bitcoin [`Base-58-check`](https://en.bitcoin.it/wiki/Base58Check_encoding){target=\_blank} encoding. Each Polkadot SDK SS58 address uses a `base-58` encoded value to identify a specific account on a specific Polkadot SDK-based chain - -The [canonical `ss58-registry`](https://github.com/paritytech/ss58-registry){target=\_blank} provides additional details about the address format used by different Polkadot SDK-based chains, including the network prefix and website used for different networks - -## State Transition Function (STF) - -The logic of a blockchain that determines how the state changes when a block is processed. In Polkadot SDK, the state transition function is effectively equivalent to the [runtime](#runtime). - -## Storage Item - -[FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitives that provide type-safe data persistence capabilities to the [runtime](#runtime). -Learn more in the [storage items](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/index.html){target=\_blank} reference document in the Polkadot SDK. - -## Substrate - -A flexible framework for building modular, efficient, and upgradeable blockchains. Substrate is written in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language and is maintained by [Parity Technologies](https://www.parity.io/){target=\_blank}. - -## Transaction - -An [extrinsic](#extrinsic) that includes a signature that can be used to verify the account authorizing it inherently or via [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}. - -## Transaction Era - -A definable period expressed as a range of block numbers during which a transaction can be included in a block. -Transaction eras are used to protect against transaction replay attacks if an account is reaped and its replay-protecting nonce is reset to zero. - -## Trie (Patricia Merkle Tree) - -A data structure used to represent sets of key-value pairs and enables the items in the data set to be stored and retrieved using a cryptographic hash. Because incremental changes to the data set result in a new hash, retrieving data is efficient even if the data set is very large. With this data structure, you can also prove whether the data set includes any particular key-value pair without access to the entire data set. - -In Polkadot SDK-based blockchains, state is stored in a trie data structure that supports the efficient creation of incremental digests. This trie is exposed to the [runtime](#runtime) as [a simple key/value map](#storage-item) where both keys and values can be arbitrary byte arrays. - -## Validator - -A validator is a node that participates in the consensus mechanism of the network. Its roles include block production, transaction validation, network integrity, and security maintenance. - -## WebAssembly (Wasm) - -An execution architecture that allows for the efficient, platform-neutral expression of -deterministic, machine-executable logic. - -[Wasm](https://webassembly.org/){target=\_blank} can be compiled from many languages, including -the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. Polkadot SDK-based chains use a Wasm binary to provide portable [runtimes](#runtime) that can be included as part of the chain's state. - -## Weight - -A convention used in Polkadot SDK-based blockchains to measure and manage the time it takes to validate a block. -Polkadot SDK defines one unit of weight as one picosecond of execution time on reference hardware. - -The maximum block weight should be equivalent to one-third of the target block time with an allocation of one-third each for: - -- Block construction -- Network propagation -- Import and verification - -By defining weights, you can trade-off the number of transactions per second and the hardware required to maintain the target block time appropriate for your use case. Weights are defined in the runtime, meaning you can tune them using runtime updates to keep up with hardware and software improvements. - -## Westend - -Westend is a Parity-maintained, Polkadot SDK-based blockchain that serves as a test network for the [Polkadot](#polkadot) network. - - ---- - -Page Title: Install Polkadot SDK - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-install-polkadot-sdk.md -- Canonical (HTML): https://docs.polkadot.com/parachains/install-polkadot-sdk/ -- Summary: Install all required Polkadot SDK dependencies, set up the SDK itself, and verify that it runs correctly on your machine. - -# Install Polkadot SDK - -This guide provides step-by-step instructions for installing the Polkadot SDK on macOS, Linux, and Windows. The installation process consists of two main parts: - -- **Installing dependencies**: Setting up Rust, required system packages, and development tools. -- **Building the Polkadot SDK**: Cloning and compiling the Polkadot SDK repository. - -Follow the appropriate section for your operating system to ensure all necessary tools are installed and configured properly. - -## Install Dependencies: macOS - -You can install Rust and set up a Substrate development environment on Apple macOS computers with Intel or Apple M1 processors. - -### Before You Begin {: #before-you-begin-mac-os } - -Before you install Rust and set up your development environment on macOS, verify that your computer meets the following basic requirements: - -- Operating system version is 10.7 Lion or later. -- Processor speed of at least 2 GHz. Note that 3 GHz is recommended. -- Memory of at least 8 GB RAM. Note that 16 GB is recommended. -- Storage of at least 10 GB of available space. -- Broadband Internet connection. - -### Install Homebrew - -In most cases, you should use Homebrew to install and manage packages on macOS computers. If you don't already have Homebrew installed on your local computer, you should download and install it before continuing. - -To install Homebrew: - -1. Open the Terminal application. -2. Download and install Homebrew by running the following command: - - ```bash - /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" - ``` - -3. Verify Homebrew has been successfully installed by running the following command: - - ```bash - brew --version - ``` - - The command displays output similar to the following: - -
- brew --version - Homebrew 4.3.15 -
- -### Support for Apple Silicon - -Protobuf must be installed before the build process can begin. To install it, run the following command: - -```bash -brew install protobuf -``` - -### Install Required Packages and Rust {: #install-required-packages-and-rust-mac-os } - -Because the blockchain requires standard cryptography to support the generation of public/private key pairs and the validation of transaction signatures, you must also have a package that provides cryptography, such as `openssl`. - -To install `openssl` and the Rust toolchain on macOS: - -1. Open the Terminal application. -2. Ensure you have an updated version of Homebrew by running the following command: - - ```bash - brew update - ``` - -3. Install the `openssl` package by running the following command: - - ```bash - brew install openssl - ``` - -4. Download the `rustup` installation program and use it to install Rust by running the following command: - - ```bash - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh - ``` - -5. Follow the prompts displayed to proceed with a default installation. -6. Update your current shell to include Cargo by running the following command: - - ```bash - source ~/.cargo/env - ``` - -7. Configure the Rust toolchain to default to the latest stable version by running the following commands: - - ```bash - rustup default stable - rustup update - rustup target add wasm32-unknown-unknown - rustup component add rust-src - ``` - -8. Install `cmake` using the following command: - - ```bash - brew install cmake - ``` - -9. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). - -## Install Dependencies: Linux - -Rust supports most Linux distributions. Depending on the specific distribution and version of the operating system you use, you might need to add some software dependencies to your environment. In general, your development environment should include a linker or a C-compatible compiler, such as `clang`, and an appropriate integrated development environment (IDE). - -### Before You Begin {: #before-you-begin-linux } - -Check the documentation for your operating system for information about the installed packages and how to download and install any additional packages you might need. For example, if you use Ubuntu, you can use the Ubuntu Advanced Packaging Tool (`apt`) to install the `build-essential` package: - -```bash -sudo apt install build-essential -``` - -At a minimum, you need the following packages before you install Rust: - -```text -clang curl git make -``` - -Because the blockchain requires standard cryptography to support the generation of public/private key pairs and the validation of transaction signatures, you must also have a package that provides cryptography, such as `libssl-dev` or `openssl-devel`. - -### Install Required Packages and Rust {: #install-required-packages-and-rust-linux } - -To install the Rust toolchain on Linux: - -1. Open a terminal shell. -2. Check the packages installed on the local computer by running the appropriate package management command for your Linux distribution. -3. Add any package dependencies you are missing to your local development environment by running the appropriate package management command for your Linux distribution: - - === "Ubuntu" - - ```bash - sudo apt install --assume-yes git clang curl libssl-dev protobuf-compiler - ``` - - === "Debian" - - ```sh - sudo apt install --assume-yes git clang curl libssl-dev llvm libudev-dev make protobuf-compiler - ``` - - === "Arch" - - ```sh - pacman -Syu --needed --noconfirm curl git clang make protobuf - ``` - - === "Fedora" - - ```sh - sudo dnf update - sudo dnf install clang curl git openssl-devel make protobuf-compiler - ``` - - === "OpenSUSE" - - ```sh - sudo zypper install clang curl git openssl-devel llvm-devel libudev-devel make protobuf - ``` - - Remember that different distributions might use different package managers and bundle packages in different ways. For example, depending on your installation selections, Ubuntu Desktop and Ubuntu Server might have different packages and different requirements. However, the packages listed in the command-line examples are applicable to many common Linux distributions, including Debian, Linux Mint, MX Linux, and Elementary OS. - -4. Download the `rustup` installation program and use it to install Rust by running the following command: - - ```bash - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh - ``` - -5. Follow the prompts displayed to proceed with a default installation. -6. Update your current shell to include Cargo by running the following command: - - ```bash - source $HOME/.cargo/env - ``` - -7. Verify your installation by running the following command: - - ```bash - rustc --version - ``` - -8. Configure the Rust toolchain to default to the latest stable version by running the following commands: - - ```bash - rustup default stable - rustup update - rustup target add wasm32-unknown-unknown - rustup component add rust-src - ``` - -9. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). - -## Install Dependencies: Windows (WSL) - -In general, UNIX-based operating systems—like macOS or Linux—provide a better development environment for building Substrate-based blockchains. - -However, suppose your local computer uses Microsoft Windows instead of a UNIX-based operating system. In that case, you can configure it with additional software to make it a suitable development environment for building Substrate-based blockchains. To prepare a development environment on a Microsoft Windows computer, you can use Windows Subsystem for Linux (WSL) to emulate a UNIX operating environment. - -### Before You Begin {: #before-you-begin-windows-wls } - -Before installing on Microsoft Windows, verify the following basic requirements: - -- You have a computer running a supported Microsoft Windows operating system: - - **For Windows desktop**: You must be running Microsoft Windows 10, version 2004 or later, or Microsoft Windows 11 to install WSL. - - **For Windows server**: You must be running Microsoft Windows Server 2019, or later, to install WSL on a server operating system. -- You have a good internet connection and access to a shell terminal on your local computer. - -### Set Up Windows Subsystem for Linux - -WSL enables you to emulate a Linux environment on a computer that uses the Windows operating system. The primary advantage of this approach for Substrate development is that you can use all of the code and command-line examples as described in the Substrate documentation. For example, you can run common commands—such as `ls` and `ps`—unmodified. By using WSL, you can avoid configuring a virtual machine image or a dual-boot operating system. - -To prepare a development environment using WSL: - -1. Check your Windows version and build number to see if WSL is enabled by default. - - If you have Microsoft Windows 10, version 2004 (Build 19041 and higher), or Microsoft Windows 11, WSL is available by default and you can continue to the next step. - - If you have an older version of Microsoft Windows installed, see the [WSL manual installation steps for older versions](https://learn.microsoft.com/en-us/windows/wsl/install-manual){target=\_blank}. If you are installing on an older version of Microsoft Windows, you can download and install WLS 2 if your computer has Windows 10, version 1903 or higher. - -2. Select **Windows PowerShell** or **Command Prompt** from the **Start** menu, right-click, then **Run as administrator**. - -3. In the PowerShell or Command Prompt terminal, run the following command: - - ```bash - wsl --install - ``` - - This command enables the required WSL 2 components that are part of the Windows operating system, downloads the latest Linux kernel, and installs the Ubuntu Linux distribution by default. - - If you want to review the other Linux distributions available, run the following command: - - ```bash - wsl --list --online - ``` - -4. After the distribution is downloaded, close the terminal. - -5. Click the **Start** menu, select **Shut down or sign out**, then click **Restart** to restart the computer. - - Restarting the computer is required to start the installation of the Linux distribution. It can take a few minutes for the installation to complete after you restart. - - For more information about setting up WSL as a development environment, see the [Set up a WSL development environment](https://learn.microsoft.com/en-us/windows/wsl/setup/environment){target=\_blank} docs. - -### Install Required Packages and Rust {: #install-required-packages-and-rust-windows-wls } - -To install the Rust toolchain on WSL: - -1. Click the **Start** menu, then select **Ubuntu**. -2. Type a UNIX user name to create a user account. -3. Type a password for your UNIX user, then retype the password to confirm it. -4. Download the latest updates for the Ubuntu distribution using the Ubuntu Advanced Packaging Tool (`apt`) by running the following command: - - ```bash - sudo apt update - ``` - -5. Add the required packages for the Ubuntu distribution by running the following command: - - ```bash - sudo apt install --assume-yes git clang curl libssl-dev llvm libudev-dev make protobuf-compiler - ``` - -6. Download the `rustup` installation program and use it to install Rust for the Ubuntu distribution by running the following command: - - ```bash - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh - ``` - -7. Follow the prompts displayed to proceed with a default installation. - -8. Update your current shell to include Cargo by running the following command: - - ```bash - source ~/.cargo/env - ``` - -9. Verify your installation by running the following command: - - ```bash - rustc --version - ``` - -10. Configure the Rust toolchain to use the latest stable version as the default toolchain by running the following commands: - - ```bash - rustup default stable - rustup update - rustup target add wasm32-unknown-unknown - rustup component add rust-src - ``` - -11. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). - -## Build the Polkadot SDK - -After installing all dependencies, you can now clone and compile the Polkadot SDK repository to verify your setup. - -### Clone the Polkadot SDK - -1. Clone the Polkadot SDK repository: - - ```bash - git clone https://github.com/paritytech/polkadot-sdk.git - ``` - -2. Navigate into the project directory: - - ```bash - cd polkadot-sdk - ``` - -### Compile the Polkadot SDK - -Compile the entire Polkadot SDK repository to ensure your environment is properly configured: - -```bash -cargo build --release --locked -``` - -!!!note - This initial compilation will take significant time, depending on your machine specifications. It compiles all components of the Polkadot SDK to verify your toolchain is correctly configured. - -### Verify the Build - -Once the build completes successfully, verify the installation by checking the compiled binaries: - -```bash -ls target/release -``` - -You should see several binaries, including: - -- `polkadot`: The Polkadot relay chain node. -- `polkadot-parachain`: The parachain collator node. -- `polkadot-omni-node`:The omni node for running parachains. -- `substrate-node`: The kitchensink node with many pre-configured pallets. - -Verify the Polkadot binary works by checking its version: - -```bash -./target/release/polkadot --version -``` - -This should display version information similar to: - -```bash -polkadot 1.16.0-1234abcd567 -``` - -If you see the version output without errors, your development environment is correctly configured and ready for Polkadot SDK development! - -## Optional: Run the Kitchensink Node - -The Polkadot SDK includes a feature-rich node called "kitchensink" located at `substrate/bin/node`. This node comes pre-configured with many pallets and features from the Polkadot SDK, making it an excellent reference for exploring capabilities and understanding how different components work together. - -!!!note - If you've already compiled the Polkadot SDK in the previous step, the `substrate-node` binary is already built and ready to use. You can skip directly to running the node. - -### Run the Kitchensink Node in Development Mode - -From the `polkadot-sdk` root directory, start the kitchensink node in development mode: - -```bash -./target/release/substrate-node --dev -``` - -The `--dev` flag enables development mode, which: - -- Runs a single-node development chain. -- Produces and finalizes blocks automatically. -- Uses pre-configured development accounts (Alice, Bob, etc.). -- Deletes all data when stopped, ensuring a clean state on restart. - - -You should see log output indicating the node is running and producing blocks, with increasing block numbers after `finalized`. - -### Interact with the Kitchensink Node - -The kitchensink node is accessible at `ws://localhost:9944`. Open [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} in your browser to explore its features and connect to the local node. - -1. Click the network icon in the top left corner. -2. Scroll to **Development** and select **Local Node**. -3. Click **Switch** to connect to your local node. - -![](/images/parachains/install-polkadot-sdk/install-polkadot-sdk-1.webp) - -Once connected, the interface updates its color scheme to indicate a successful connection to the local node. - -![](/images/parachains/install-polkadot-sdk/install-polkadot-sdk-2.webp) - -You can now explore the various pallets and features included in the kitchensink node, making it a valuable reference as you develop your own blockchain applications. - -To stop the node, press `Control-C` in the terminal. - -## Where to Go Next - -
- -- __Get Started with Parachain Development__ - - --- - - Practical examples and tutorials for building and deploying Polkadot parachains, covering everything from launch to customization and cross-chain messaging. - - [:octicons-arrow-right-24: Get Started](/parachains/get-started/) - -
- - ---- - -Page Title: Interoperability - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-interoperability.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/interoperability/ -- Summary: Explore the importance of interoperability in the Polkadot ecosystem, covering XCM, bridges, and cross-chain communication. - -# Interoperability - -## Introduction - -Interoperability lies at the heart of the Polkadot ecosystem, enabling communication and collaboration across a diverse range of blockchains. By bridging the gaps between parachains, relay chains, and even external networks, Polkadot unlocks the potential for truly decentralized applications, efficient resource sharing, and scalable solutions. - -Polkadot’s design ensures that blockchains can transcend their individual limitations by working together as part of a unified system. This cooperative architecture is what sets Polkadot apart in the blockchain landscape. - -## Why Interoperability Matters - -The blockchain ecosystem is inherently fragmented. Different blockchains excel in specialized domains such as finance, gaming, or supply chain management, but these chains function in isolation without interoperability. This lack of connectivity stifles the broader utility of blockchain technology. - -Interoperability solves this problem by enabling blockchains to: - -- **Collaborate across networks**: Chains can interact to share assets, functionality, and data, creating synergies that amplify their individual strengths. -- **Achieve greater scalability**: Specialized chains can offload tasks to others, optimizing performance and resource utilization. -- **Expand use-case potential**: Cross-chain applications can leverage features from multiple blockchains, unlocking novel user experiences and solutions. - -In the Polkadot ecosystem, interoperability transforms a collection of isolated chains into a cohesive, efficient network, pushing the boundaries of what blockchains can achieve together. - -## Key Mechanisms for Interoperability - -At the core of Polkadot's cross-chain collaboration are foundational technologies designed to break down barriers between networks. These mechanisms empower blockchains to communicate, share resources, and operate as a cohesive ecosystem. - -### Cross-Consensus Messaging (XCM): The Backbone of Communication - -Polkadot's Cross-Consensus Messaging (XCM) is the standard framework for interaction between parachains, relay chains, and, eventually, external blockchains. XCM provides a trustless, secure messaging format for exchanging assets, sharing data, and executing cross-chain operations. - -Through XCM, decentralized applications can: - -- Transfer tokens and other assets across chains. -- Coordinate complex workflows that span multiple blockchains. -- Enable seamless user experiences where underlying blockchain differences are invisible. -- XCM exemplifies Polkadot’s commitment to creating a robust and interoperable ecosystem. - -For further information about XCM, check the [Introduction to XCM](/parachains/interoperability/get-started/){target=\_blank} article. - -### Bridges: Connecting External Networks - -While XCM enables interoperability within the Polkadot ecosystem, bridges extend this functionality to external blockchains such as Ethereum and Bitcoin. By connecting these networks, bridges allow Polkadot-based chains to access external liquidity, additional functionalities, and broader user bases. - -With bridges, developers and users gain the ability to: - -- Integrate external assets into Polkadot-based applications. -- Combine the strengths of Polkadot’s scalability with the liquidity of other networks. -- Facilitate accurate multi-chain applications that transcend ecosystem boundaries. - -For more information about bridges in the Polkadot ecosystem, see the [Bridge Hub](/reference/polkadot-hub/bridging/){target=\_blank} guide. - -## The Polkadot Advantage - -Polkadot was purpose-built for interoperability. Unlike networks that add interoperability as an afterthought, Polkadot integrates it as a fundamental design principle. This approach offers several distinct advantages: - -- **Developer empowerment**: Polkadot’s interoperability tools allow developers to build applications that leverage multiple chains’ capabilities without added complexity. -- **Enhanced ecosystem collaboration**: Chains in Polkadot can focus on their unique strengths while contributing to the ecosystem’s overall growth. -- **Future-proofing blockchain**: By enabling seamless communication, Polkadot ensures its ecosystem can adapt to evolving demands and technologies. - -## Looking Ahead - -Polkadot’s vision of interoperability extends beyond technical functionality, representing a shift towards a more collaborative blockchain landscape. By enabling chains to work together, Polkadot fosters innovation, efficiency, and accessibility, paving the way for a decentralized future where blockchains are not isolated competitors but interconnected collaborators. - - ---- - -Page Title: Introduction to XCM - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md -- Canonical (HTML): https://docs.polkadot.com/parachains/interoperability/get-started/ -- Summary: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. - -# Introduction to XCM - -## Introduction - -Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems. - -With XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation. - -## Messaging Format - -XCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics. - -XCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing. - -## The Four Principles of XCM - -XCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems: - -- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes. -- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended. -- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin. -- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems. - -These principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments. - -## The XCM Tech Stack - -![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp) - -The XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels. - -## Core Functionalities of XCM - -XCM enhances cross-consensus communication by introducing several powerful features: - -- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management. -- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification. -- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location. - -The standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications. - -## XCM Example - -The following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA). - -```rust -let message = Xcm(vec![ - WithdrawAsset((Here, amount).into()), - BuyExecution { - fees: (Here, amount).into(), - weight_limit: WeightLimit::Unlimited - }, - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: Junction::AccountId32 { - network: None, - id: BOB.clone().into() - }.into(), - }.into() - } -]); -``` - -The message consists of three instructions described as follows: - -- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register. - - ```rust - WithdrawAsset((Here, amount).into()), - ``` - - - **`Here`**: The native parachain token. - - **`amount`**: The number of tokens that are transferred. - - The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register. - -- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\_blank} of the XCM instructions. - - ```rust - BuyExecution { - fees: (Here, amount).into(), - weight_limit: WeightLimit::Unlimited - }, - ``` - - - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight. - - **`weight_limit`**: Defines the maximum fees that can be used to buy weight. - -- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\_blank}**: Moves the remaining tokens from the holding register to Bob’s account. - - ```rust - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: Junction::AccountId32 { - network: None, - id: BOB.clone().into() - }.into(), - }.into() - } - ``` - - - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited. - -This step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - -## Overview - -XCM revolutionizes cross-chain communication by enabling use cases such as: - -- Token transfers between blockchains. -- Asset locking for cross-chain smart contract interactions. -- Remote execution of functions on other blockchains. - -These functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - - ---- - -Page Title: JSON-RPC APIs - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-json-rpc-apis.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/json-rpc-apis/ -- Summary: JSON-RPC APIs guide for Polkadot Hub, covering supported methods, parameters, and examples for interacting with the chain. - -# JSON-RPC APIs - -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction - -Polkadot Hub provides Ethereum compatibility through its JSON-RPC interface, allowing developers to interact with the chain using familiar Ethereum tooling and methods. This document outlines the supported [Ethereum JSON-RPC methods](https://ethereum.org/developers/docs/apis/json-rpc/#json-rpc-methods){target=\_blank} and provides examples of how to use them. - -This guide uses the Polkadot Hub TestNet endpoint: - -```text -https://testnet-passet-hub-eth-rpc.polkadot.io -``` - -## Available Methods - -### eth_accounts - -Returns a list of addresses owned by the client. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_accounts){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_accounts" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_accounts", - "params":[], - "id":1 -}' -``` - ---- - -### eth_blockNumber - -Returns the number of the most recent block. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_blocknumber){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_blockNumber" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_blockNumber", - "params":[], - "id":1 -}' -``` - ---- - -### eth_call - -Executes a new message call immediately without creating a transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_call){target=\_blank}. - -**Parameters**: - -- **`transaction` ++"object"++**: The transaction call object. - - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - -**Example**: - -```bash title="eth_call" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_call", - "params":[{ - "to": "INSERT_RECIPIENT_ADDRESS", - "data": "INSERT_ENCODED_CALL" - }, "INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_RECIPIENT_ADDRESS`, `INSERT_ENCODED_CALL`, and `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_chainId - -Returns the chain ID used for signing transactions. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_chainid){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_chainId" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_chainId", - "params":[], - "id":1 -}' -``` - ---- - -### eth_estimateGas - -Estimates gas required for a transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_estimategas){target=\_blank}. - -**Parameters**: - -- **`transaction` ++"object"++**: The transaction call object. - - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - -**Example**: - -```bash title="eth_estimateGas" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_estimateGas", - "params":[{ - "to": "INSERT_RECIPIENT_ADDRESS", - "data": "INSERT_ENCODED_FUNCTION_CALL" - }], - "id":1 -}' -``` - -Ensure to replace the `INSERT_RECIPIENT_ADDRESS` and `INSERT_ENCODED_CALL` with the proper values. - ---- - -### eth_gasPrice - -Returns the current gas price in Wei. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gasprice){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_gasPrice" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_gasPrice", - "params":[], - "id":1 -}' -``` - ---- - -### eth_getBalance - -Returns the balance of a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getbalance){target=\_blank}. - -**Parameters**: - -- **`address` ++"string"++**: Address to query balance. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - -**Example**: - -```bash title="eth_getBalance" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getBalance", - "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_getBlockByHash - -Returns information about a block by its hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblockbyhash){target=\_blank}. - -**Parameters**: - -- **`blockHash` ++"string"++**: The hash of the block to retrieve. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`fullTransactions` ++"boolean"++**: If `true`, returns full transaction details; if `false`, returns only transaction hashes. - -**Example**: - -```bash title="eth_getBlockByHash" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getBlockByHash", - "params":["INSERT_BLOCK_HASH", INSERT_BOOLEAN], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_HASH` and `INSERT_BOOLEAN` with the proper values. - ---- - -### eth_getBlockByNumber - -Returns information about a block by its number. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblockbynumber){target=\_blank}. - -**Parameters**: - -- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -- **`fullTransactions` ++"boolean"++**: If `true`, returns full transaction details; if `false`, returns only transaction hashes. - -**Example**: - -```bash title="eth_getBlockByNumber" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getBlockByNumber", - "params":["INSERT_BLOCK_VALUE", INSERT_BOOLEAN], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_VALUE` and `INSERT_BOOLEAN` with the proper values. - ---- - -### eth_getBlockTransactionCountByNumber - -Returns the number of transactions in a block from a block number. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber){target=\_blank}. - -**Parameters**: - -- **`blockValue` ++"string"++**: The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - -**Example**: - -```bash title="eth_getBlockTransactionCountByNumber" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getBlockTransactionCountByNumber", - "params":["INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_getBlockTransactionCountByHash - -Returns the number of transactions in a block from a block hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash){target=\_blank}. - -**Parameters**: - -- **`blockHash` ++"string"++**: The hash of the block to retrieve. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getBlockTransactionCountByHash" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getBlockTransactionCountByHash", - "params":["INSERT_BLOCK_HASH"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_HASH` with the proper values. - ---- - -### eth_getCode - -Returns the code at a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getcode){target=\_blank}. - -**Parameters**: - -- **`address` ++"string"++**: Contract or account address to query code. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). - -**Example**: - -```bash title="eth_getCode" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getCode", - "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_getLogs - -Returns an array of all logs matching a given filter object. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getlogs){target=\_blank}. - -**Parameters**: - -- **`filter` ++"object"++**: The filter object. - - **`fromBlock` ++"string"++**: (Optional) Block number or tag to start from. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - - **`toBlock` ++"string"++**: (Optional) Block number or tag to end at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - - **`address` ++"string" or "array of strings"++**: (Optional) Contract address or a list of addresses from which to get logs. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`topics` ++"array of strings"++**: (Optional) Array of topics for filtering logs. Each topic can be a single [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string or an array of such strings (meaning OR). - - **`blockhash` ++"string"++**: (Optional) Hash of a specific block. Cannot be used with `fromBlock` or `toBlock`. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getLogs" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getLogs", - "params":[{ - "fromBlock": "latest", - "toBlock": "latest" - }], - "id":1 -}' -``` - ---- - -### eth_getStorageAt - -Returns the value from a storage position at a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getstorageat){target=\_blank}. - -**Parameters**: - -- **`address` ++"string"++**: Contract or account address to query code. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`storageKey` ++"string"++**: Position in storage to retrieve data from. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). - -**Example**: - -```bash title="eth_getStorageAt" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getStorageAt", - "params":["INSERT_ADDRESS", "INSERT_STORAGE_KEY", "INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_ADDRESS`, `INSERT_STORAGE_KEY`, and `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_getTransactionCount - -Returns the number of transactions sent from an address (nonce). [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactioncount){target=\_blank}. - -**Parameters**: - -- **`address` ++"string"++**: Address to query balance. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). - -**Example**: - -```bash title="eth_getTransactionCount" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getTransactionCount", - "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_getTransactionByHash - -Returns information about a transaction by its hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyhash){target=\_blank}. - -**Parameters**: - -- **`transactionHash` ++"string"++**: The hash of the transaction. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getTransactionByHash" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getTransactionByHash", - "params":["INSERT_TRANSACTION_HASH"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper values. - ---- - -### eth_getTransactionByBlockNumberAndIndex - -Returns information about a transaction by block number and transaction index. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyblocknumberandindex){target=\_blank}. - -**Parameters**: - -- **`blockValue` ++"string"++**: The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -- **`transactionIndex` ++"string"++**: The index of the transaction in the block. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getTransactionByBlockNumberAndIndex" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getTransactionByBlockNumberAndIndex", - "params":["INSERT_BLOCK_VALUE", "INSERT_TRANSACTION_INDEX"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_VALUE` and `INSERT_TRANSACTION_INDEX` with the proper values. - ---- - -### eth_getTransactionByBlockHashAndIndex - -Returns information about a transaction by block hash and transaction index. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyblockhashandindex){target=\_blank}. - -**Parameters**: - -- **`blockHash` ++"string"++**: The hash of the block. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`transactionIndex` ++"string"++**: The index of the transaction in the block. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getTransactionByBlockHashAndIndex" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getTransactionByBlockHashAndIndex", - "params":["INSERT_BLOCK_HASH", "INSERT_TRANSACTION_INDEX"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_HASH` and `INSERT_TRANSACTION_INDEX` with the proper values. - ---- - -### eth_getTransactionReceipt - -Returns the receipt of a transaction by transaction hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionreceipt){target=\_blank}. - -**Parameters**: - -- **`transactionHash` ++"string"++**: The hash of the transaction. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getTransactionReceipt" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getTransactionReceipt", - "params":["INSERT_TRANSACTION_HASH"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper values. - ---- - -### eth_maxPriorityFeePerGas - -Returns an estimate of the current priority fee per gas, in Wei, to be included in a block. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_maxPriorityFeePerGas" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_maxPriorityFeePerGas", - "params":[], - "id":1 -}' -``` - ---- - -### eth_sendRawTransaction - -Submits a raw transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_sendrawtransaction){target=\_blank}. - -**Parameters**: - -- **`callData` ++"string"++**: Signed transaction data. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_sendRawTransaction" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_sendRawTransaction", - "params":["INSERT_CALL_DATA"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_CALL_DATA` with the proper values. - ---- - -### eth_sendTransaction - -Creates and sends a new transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_sendtransaction){target=\_blank}. - -**Parameters**: - -- **`transaction` ++"object"++**: The transaction object. - - **`from` ++"string"++**: Address sending the transaction. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`to` ++"string"++**: (Optional) Recipient address. No need to provide this value when deploying a contract. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`gas` ++"string"++**: (optional, default: `90000`) gas limit for execution. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`gasPrice` ++"string"++**: (Optional) Gas price per unit. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`value` ++"string"++**: (Optional) Amount of Ether to send. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`data` ++"string"++**: (Optional) Contract bytecode or encoded method call. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`nonce` ++"string"++**: (Optional) Transaction nonce. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_sendTransaction" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_sendTransaction", - "params":[{ - "from": "INSERT_SENDER_ADDRESS", - "to": "INSERT_RECIPIENT_ADDRESS", - "gas": "INSERT_GAS_LIMIT", - "gasPrice": "INSERT_GAS_PRICE", - "value": "INSERT_VALUE", - "input": "INSERT_INPUT_DATA", - "nonce": "INSERT_NONCE" - }], - "id":1 -}' -``` - -Ensure to replace the `INSERT_SENDER_ADDRESS`, `INSERT_RECIPIENT_ADDRESS`, `INSERT_GAS_LIMIT`, `INSERT_GAS_PRICE`, `INSERT_VALUE`, `INSERT_INPUT_DATA`, and `INSERT_NONCE` with the proper values. - ---- - -### eth_syncing - -Returns an object with syncing data or `false` if not syncing. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_syncing){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_syncing" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_syncing", - "params":[], - "id":1 -}' -``` - ---- - -### net_listening - -Returns `true` if the client is currently listening for network connections, otherwise `false`. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#net_listening){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="net_listening" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"net_listening", - "params":[], - "id":1 -}' -``` - ---- - -### net_peerCount - -Returns the number of peers currently connected to the client. - -**Parameters**: - -None. - -**Example**: - -```bash title="net_peerCount" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"net_peerCount", - "params":[], - "id":1 -}' -``` - ---- - -### net_version - -Returns the current network ID as a string. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#net_version){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="net_version" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"net_version", - "params":[], - "id":1 -}' -``` - ---- - -### system_health - -Returns information about the health of the system. - -**Parameters**: - -None. - -**Example**: - -```bash title="system_health" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"system_health", - "params":[], - "id":1 -}' -``` - ---- - -### web3_clientVersion - -Returns the current client version. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#web3_clientversion){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="web3_clientVersion" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"web3_clientVersion", - "params":[], - "id":1 -}' -``` - ---- - -### debug_traceBlockByNumber - -Traces a block's execution by its number and returns a detailed execution trace for each transaction. - -**Parameters**: - -- **`blockValue` ++"string"++**: The block number or tag to trace. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -- **`options` ++"object"++**: (Optional) An object containing tracer options. - - **`tracer` ++"string"++**: The name of the tracer to use (e.g., `"callTracer"`, `"opTracer"`). - - Other tracer-specific options may be supported. - -**Example**: - -```bash title="debug_traceBlockByNumber" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"debug_traceBlockByNumber", - "params":["INSERT_BLOCK_VALUE", {"tracer": "callTracer"}], - "id":1 -}' -``` - -Ensure to replace `INSERT_BLOCK_VALUE` with a proper block number if needed. - ---- - -### debug_traceTransaction - -Traces the execution of a single transaction by its hash and returns a detailed execution trace. - -**Parameters**: - -- **`transactionHash` ++"string"++**: The hash of the transaction to trace. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`options` ++"object"++**: (Optional) An object containing tracer options (e.g., `tracer: "callTracer"`). - -**Example**: - -```bash title="debug_traceTransaction" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"debug_traceTransaction", - "params":["INSERT_TRANSACTION_HASH", {"tracer": "callTracer"}], - "id":1 -}' -``` - -Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper value. - ---- - -### debug_traceCall - -Executes a new message call and returns a detailed execution trace without creating a transaction on the blockchain. - -**Parameters**: - -- **`transaction` ++"object"++**: The transaction call object, similar to `eth_call` parameters. - - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -- **`options` ++"object"++**: (Optional) An object containing tracer options (e.g., `tracer: "callTracer"`). - -**Example**: - -```bash title="debug_traceCall" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"debug_traceCall", - "params":[{ - "from": "INSERT_SENDER_ADDRESS", - "to": "INSERT_RECIPIENT_ADDRESS", - "data": "INSERT_ENCODED_CALL" - }, "INSERT_BLOCK_VALUE", {"tracer": "callTracer"}], - "id":1 -}' -``` - -Ensure to replace the `INSERT_SENDER_ADDRESS`, `INSERT_RECIPIENT_ADDRESS`, `INSERT_ENCODED_CALL`, and `INSERT_BLOCK_VALUE` with the proper value. - ---- - -## Response Format - -All responses follow the standard JSON-RPC 2.0 format: - -```json -{ - "jsonrpc": "2.0", - "id": 1, - "result": ... // The return value varies by method -} -``` - -## Error Handling - -If an error occurs, the response will include an error object: - -```json -{ - "jsonrpc": "2.0", - "id": 1, - "error": { - "code": -32000, - "message": "Error message here" - } -} -``` - - ---- - -Page Title: Networks - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-networks.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/networks/ -- Summary: Explore Polkadot's testing and production networks, including Westend, Kusama, and Paseo, for efficient development, deployment, and testing. - -# Networks - -## Introduction - -The Polkadot ecosystem is built on a robust set of networks designed to enable secure and scalable development. Whether you are testing new features or deploying to live production, Polkadot offers several layers of networks tailored for each stage of the development process. From local environments to experimental networks like Kusama and community-run TestNets such as Paseo, developers can thoroughly test, iterate, and validate their applications. This guide will introduce you to Polkadot's various networks and explain how they fit into the development workflow. - -## Network Overview - -Polkadot's development process is structured to ensure new features and upgrades are rigorously tested before being deployed on live production networks. The progression follows a well-defined path, starting from local environments and advancing through TestNets, ultimately reaching the Polkadot MainNet. The diagram below outlines the typical progression of the Polkadot development cycle: - -``` mermaid -flowchart LR - id1[Local] --> id2[Westend] --> id4[Kusama] --> id5[Polkadot] - id1[Local] --> id3[Paseo] --> id5[Polkadot] +```mermaid +sequenceDiagram + participant User as User/dApp + participant Proxy as Ethereum JSON RPC Proxy + participant Chain as Blockchain Node + participant Pallet as pallet_revive + + User->>Proxy: Submit Ethereum Transaction + Proxy->>Chain: Repackage as Polkadot Compatible Transaction + Chain->>Pallet: Process Transaction + Pallet->>Pallet: Decode Ethereum Transaction + Pallet->>Pallet: Execute Contract via PolkaVM + Pallet->>Chain: Return Results + Chain->>Proxy: Forward Results + Proxy->>User: Return Ethereum-compatible Response ``` -This flow ensures developers can thoroughly test and iterate without risking real tokens or affecting production networks. Testing tools like [Chopsticks](#chopsticks) and various TestNets make it easier to experiment safely before releasing to production. - -A typical journey through the Polkadot core protocol development process might look like this: - -1. **Local development node**: Development starts in a local environment, where developers can create, test, and iterate on upgrades or new features using a local development node. This stage allows rapid experimentation in an isolated setup without any external dependencies. - -2. **Westend**: After testing locally, upgrades are deployed to [Westend](#westend), Polkadot's primary TestNet. Westend simulates real-world conditions without using real tokens, making it the ideal place for rigorous feature testing before moving on to production networks. - -3. **Kusama**: Once features have passed extensive testing on Westend, they move to Kusama, Polkadot's experimental and fast-moving "canary" network. Kusama operates as a high-fidelity testing ground with actual economic incentives, giving developers insights into how their features will perform in a real-world environment. - -4. **Polkadot**: After passing tests on Westend and Kusama, features are considered ready for deployment to Polkadot, the live production network. - - In addition, parachain developers can leverage local TestNets like [Zombienet](#zombienet) and deploy upgrades on parachain TestNets. - -5. **Paseo**: For parachain and dApp developers, Paseo serves as a community-run TestNet that mirrors Polkadot's runtime. Like Westend for core protocol development, Paseo provides a testing ground for parachain development without affecting live networks. - -!!!note - The Rococo TestNet deprecation date was October 14, 2024. Teams should use Westend for Polkadot protocol and feature testing and Paseo for chain development-related testing. - -## Polkadot Development Networks - -Development and testing are crucial to building robust dApps and parachains and performing network upgrades within the Polkadot ecosystem. To achieve this, developers can leverage various networks and tools that provide a risk-free environment for experimentation and validation before deploying features to live networks. These networks help avoid the costs and risks associated with real tokens, enabling testing for functionalities like governance, cross-chain messaging, and runtime upgrades. - -## Kusama Network - -Kusama is the experimental version of Polkadot, designed for developers who want to move quickly and test their applications in a real-world environment with economic incentives. Kusama serves as a production-grade testing ground where developers can deploy features and upgrades with the pressure of game theory and economics in mind. It mirrors Polkadot but operates as a more flexible space for innovation. - -The native token for Kusama is KSM. For more information about KSM, visit the [Native Assets](https://wiki.polkadot.com/kusama/kusama-getting-started/){target=\_blank} page. - -## Test Networks - -The following test networks provide controlled environments for testing upgrades and new features. TestNet tokens are available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}. - -### Westend - -Westend is Polkadot's primary permanent TestNet. Unlike temporary test networks, Westend is not reset to the genesis block, making it an ongoing environment for testing Polkadot core features. Managed by Parity Technologies, Westend ensures that developers can test features in a real-world simulation without using actual tokens. - -The native token for Westend is WND. More details about WND can be found on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_2){target=\_blank} page. - -### Paseo - -[Paseo](https://github.com/paseo-network){target=\_blank} is a community-managed TestNet designed for parachain and dApp developers. It mirrors Polkadot's runtime and is maintained by Polkadot community members. Paseo provides a dedicated space for parachain developers to test their applications in a Polkadot-like environment without the risks associated with live networks. +This proxy-based approach eliminates the need for node binary modifications, maintaining compatibility across different client implementations. Preserving the original Ethereum transaction payload simplifies the adaptation of existing tools, which can continue processing familiar transaction formats. -The native token for Paseo is PAS. Additional information on PAS is available on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_1){target=\_blank} page. +### PolkaVM Design Fundamentals -## Local Test Networks +PolkaVM differs from the EVM in two key ways that make it faster, more hardware-efficient, and easier to extend: -Local test networks are an essential part of the development cycle for blockchain developers using the Polkadot SDK. They allow for fast, iterative testing in controlled, private environments without connecting to public TestNets. Developers can quickly spin up local instances to experiment, debug, and validate their code before deploying to larger TestNets like Westend or Paseo. Two key tools for local network testing are Zombienet and Chopsticks. +- **Register-based design**: Instead of a stack machine, PolkaVM uses a RISC-V–style register model. This design: -### Zombienet + - Uses a fixed set of registers to pass arguments, not an infinite stack. + - Maps cleanly to real hardware like x86-64. + - Simplifies compilation and boosts runtime efficiency. + - Enables tighter control over register allocation and performance tuning. -[Zombienet](https://github.com/paritytech/zombienet){target=\_blank} is a flexible testing framework for Polkadot SDK-based blockchains. It enables developers to create and manage ephemeral, short-lived networks. This feature makes Zombienet particularly useful for quick iterations, as it allows you to run multiple local networks concurrently, mimicking different runtime conditions. Whether you're developing a parachain or testing your custom blockchain logic, Zombienet gives you the tools to automate local testing. +- **64-bit word size**: PolkaVM runs on a native 64-bit word size, aligning directly with modern CPUs. This design: -Key features of Zombienet include: + - Executes arithmetic operations with direct hardware support. + - Maintains compatibility with Solidity’s 256-bit types via YUL translation. + - Accelerates computation-heavy workloads through native word alignment. + - Integrates easily with low-level, performance-focused components. -- Creating dynamic, local networks with different configurations. -- Running parachains and relay chains in a simulated environment. -- Efficient testing of network components like cross-chain messaging and governance. +## Where To Go Next -Zombienet is ideal for developers looking to test quickly and thoroughly before moving to more resource-intensive public TestNets. +
-### Chopsticks +- Learn __Contract Deployment__ -[Chopsticks](https://github.com/AcalaNetwork/chopsticks){target=\_blank} is a tool designed to create forks of Polkadot SDK-based blockchains, allowing developers to interact with network forks as part of their testing process. This capability makes Chopsticks a powerful option for testing upgrades, runtime changes, or cross-chain applications in a forked network environment. + --- -Key features of Chopsticks include: + Learn how REVM and PVM compare for compiling and deploying smart contracts. -- Forking live Polkadot SDK-based blockchains for isolated testing. -- Simulating cross-chain messages in a private, controlled setup. -- Debugging network behavior by interacting with the fork in real-time. + [:octicons-arrow-right-24: Reference](/smart-contracts/for-eth-devs/contract-deployment/) -Chopsticks provides a controlled environment for developers to safely explore the effects of runtime changes. It ensures that network behavior is tested and verified before upgrades are deployed to live networks. +
--- -Page Title: Node and Runtime - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-node-and-runtime.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/node-and-runtime/ -- Summary: Learn how Polkadot SDK-based nodes function, how the client and runtime are separated, and how they communicate using SCALE-encoded data. - -# Node and Runtime - -## Introduction - -Every blockchain platform relies on a decentralized network of computers, called nodes, that communicate with each other about transactions and blocks. In this context, a node refers to the software running on the connected devices rather than the physical or virtual machines in the network. - -Polkadot SDK-based nodes consist of two main components, each with distinct responsibilities: the client (also called node) and the runtime. - -If the system were a monolithic protocol, any modification would require updating the entire system. Instead, Polkadot achieves true upgradeability by defining an immutable meta-protocol (the client) and a protocol (the runtime) that can be upgraded independently. - -This separation gives the [Polkadot Relay Chain](/polkadot-protocol/architecture/polkadot-chain){target=\_blank} and all connected [parachains](/polkadot-protocol/architecture/parachains){target=\_blank} an evolutionary advantage over other blockchain platforms. - -## Architectural Principles - -The Polkadot SDK-based blockchain architecture is fundamentally built on two distinct yet interconnected components: - -- Client (Meta-protocol): - - Handles the foundational infrastructure of the blockchain. - - Manages runtime execution, networking, consensus, and other off-chain components. - - Provides an immutable base layer that ensures network stability. - - Upgradable only through hard forks. - -- Runtime (Protocol): - - Defines the blockchain's state transition logic. - - Determines the specific rules and behaviors of the blockchain. - - Compiled to WebAssembly (Wasm) for platform-independent execution. - - Capable of being upgraded without network-wide forking. - -### Advantages of this Architecture - -- **Forkless upgrades**: Runtime can be updated without disrupting the entire network. -- **Modularity**: Clear separation allows independent development of client and runtime. -- **Flexibility**: Enables rapid iteration and evolution of blockchain logic. -- **Performance**: WebAssembly compilation provides efficient, cross-platform execution. - -## Node (Client) - -The node, also known as the client, is the core component responsible for executing the Wasm runtime and orchestrating various essential blockchain components. It ensures the correct execution of the state transition function and manages multiple critical subsystems, including: +Page Title: Get Started with Parachain Development -- **Wasm execution**: Runs the blockchain runtime, which defines the state transition rules. -- **Database management**: Stores blockchain data. -- **Networking**: Facilitates peer-to-peer communication, block propagation, and transaction gossiping. -- **Transaction pool (Mempool)**: Manages pending transactions before they are included in a block. -- **Consensus mechanism**: Ensures agreement on the blockchain state across nodes. -- **RPC services**: Provides external interfaces for applications and users to interact with the node. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-get-started.md +- Canonical (HTML): https://docs.polkadot.com/parachains/get-started/ +- Summary: Practical examples and tutorials for building and deploying Polkadot parachains, covering everything from launch to customization and cross-chain messaging. -## Runtime +# Get Started -The runtime is more than just a set of rules. It's the fundamental logic engine that defines a blockchain's entire behavior. In Polkadot SDK-based blockchains, the runtime represents a complete, self-contained description of the blockchain's state transition function. +The following sections provide practical recipes for building parachains on Polkadot—each focused on specific development scenarios with step-by-step, hands-on examples. -### Characteristics +## Quick Start Guides -The runtime is distinguished by three key characteristics: +Quick start guides help developers set up and interact with the Polkadot parachain ecosystem using various tools and frameworks. -- **Business logic**: Defines the complete application-specific blockchain behavior. -- **WebAssembly compilation**: Ensures platform-independent, secure execution. -- **On-chain storage**: Stored within the blockchain's state, allowing dynamic updates. +| Tutorial | Tools | Description | +| :--------------------------------------------------------------------------------------------: | :----------------------------: | :---------------------------------------------------------------------: | +| [Set Up the Parachain Template](/parachains/launch-a-parachain/set-up-the-parachain-template/) | Polkadot SDK | Learn how to set up and run the Polkadot SDK Parachain Template locally | +| [Launch a Local Parachain](/parachains/testing/run-a-parachain-network/) | Zombienet, Chopsticks | Set up a local development environment for testing | +| [Connect to Polkadot](/chain-interactions/query-on-chain-data/query-sdks/) | Polkadot.js, Substrate Connect | Connect your application to Polkadot networks | +| [Fork an Existing Parachain](/parachains/testing/fork-a-parachain/) | Chopsticks | Create a local fork of a live parachain for testing | -### Key Functions +## Launch a Simple Parachain -The runtime performs several critical functions, such as: +Learn the fundamentals of launching and deploying a parachain to the Polkadot network. -- Define state transition rules. -- Implement blockchain-specific logic. -- Manage account interactions. -- Control transaction processing. -- Define governance mechanisms. -- Handle custom pallets and modules. +| Tutorial | Description | +| :--------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------: | +| [Set Up the Parachain Template](/parachains/launch-a-parachain/set-up-the-parachain-template/) | Polkadot SDK | +| [Deploy to Polkadot](/parachains/launch-a-parachain/deploy-to-polkadot/) | Step-by-step tutorial to deploying your parachain to Polkadot | +| [Obtain Coretime](/parachains/launch-a-parachain/obtain-coretime/) | Learn how to acquire blockspace using Polkadot's coretime model (RegionX) | -## Communication Between Node and Runtime +## Customize Your Runtime -The client and runtime communicate exclusively using [SCALE-encoded](/polkadot-protocol/parachain-basics/data-encoding){target=\_blank} communication. This ensures efficient and compact data exchange between the two components. +Build custom functionality for your parachain by composing and creating pallets. -### Runtime APIs +| Tutorial | Description | +| :-------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------: | +| [Add Existing Pallets to the Runtime](/parachains/customize-runtime/add-existing-pallets/) | Integrate pre-built pallets from the FRAME ecosystem | +| [Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/) | Configure and use multiple instances of the same pallet | +| [Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/) | Enable smart contract capabilities using Contracts or EVM pallets | -The Runtime API consists of well-defined functions and constants a client assumes are implemented in the Runtime Wasm blob. These APIs enable the client to interact with the runtime to execute blockchain operations and retrieve information. The client invokes these APIs to: +### Pallet Development -- Build, execute, and finalize blocks. -- Access metadata. -- Access consensus related information. -- Handle transaction execution. +Deep dive into creating and managing custom pallets for your parachain. -### Host Functions +| Tutorial | Description | +| :--------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------: | +| [Create a Custom Pallet](/parachains/customize-runtime/pallet-development/create-a-pallet/) | Build a pallet from scratch with custom logic | +| [Mock Your Runtime](/parachains/customize-runtime/pallet-development/mock-runtime/) | Set up a mock runtime environment for testing | +| [Pallet Unit Testing](/parachains/customize-runtime/pallet-development/pallet-testing/) | Write comprehensive tests for your pallet logic | +| [Add Your Custom Pallet to the Runtime](/parachains/customize-runtime/pallet-development/add-pallet-to-runtime/) | Integrate your custom pallet into your parachain runtime | +| [Benchmark the Custom Pallet](/parachains/customize-runtime/pallet-development/benchmark-pallet/) | Measure and optimize pallet performance with benchmarking | -During execution, the runtime can access certain external client functionalities via host functions. The specific functions the client exposes allow the runtime to perform operations outside the WebAssembly domain. Host functions enable the runtime to: +## Testing -- Perform cryptographic operations. -- Access the current blockchain state. -- Handle storage modifications. -- Allocate memory. +Test your parachain in various environments before production deployment. +| Tutorial | Description | +| :---------------------------------------------------------------------: | :-----------------------------------------------------: | +| [Fork a Parachain](/parachains/testing/fork-a-parachain/) | Use Chopsticks to create a local fork for testing | +| [Run a Parachain Network](/parachains/testing/run-a-parachain-network/) | Launch a complete parachain test network with Zombienet | ---- +## Runtime Upgrades and Maintenance -Page Title: On-Chain Governance Overview +Manage your parachain's lifecycle with forkless upgrades and maintenance operations. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-governance.md -- Canonical (HTML): https://docs.polkadot.com/reference/governance/ -- Summary: Discover Polkadot’s cutting-edge OpenGov system, enabling transparent, decentralized decision-making through direct democracy and flexible governance tracks. +| Tutorial | Description | +| :-----------------------------------------------------------------------: | :--------------------------------------------------: | +| [Runtime Upgrades](/parachains/runtime-maintenance/runtime-upgrades/) | Perform forkless runtime upgrades via governance | +| [Storage Migrations](/parachains/runtime-maintenance/storage-migrations/) | Safely migrate storage when updating runtime logic | +| [Unlock Parachains](/parachains/runtime-maintenance/unlock-parachains/) | Understand parachain lifecycle and unlock mechanisms | -# On-Chain Governance +## Interoperability -## Introduction +Configure your parachain for cross-chain communication using XCM (Cross-Consensus Messaging). -Polkadot’s governance system exemplifies decentralized decision-making, empowering its community of stakeholders to shape the network’s future through active participation. The latest evolution, OpenGov, builds on Polkadot’s foundation by providing a more inclusive and efficient governance model. +| Tutorial | Description | +| :--------------------------------------------------------------------------------------------------------: | :----------------------------------------------------: | +| [Open HRMP Channels Between Parachains](/parachains/interoperability/channels-between-parachains/) | Establish communication channels with other parachains | +| [Open HRMP Channels with System Parachains](/parachains/interoperability/channels-with-system-parachains/) | Connect with Asset Hub and other system parachains | -This guide will explain the principles and structure of OpenGov and walk you through its key components, such as Origins, Tracks, and Delegation. You will learn about improvements over earlier governance systems, including streamlined voting processes and enhanced stakeholder participation. +## Integrations -With OpenGov, Polkadot achieves a flexible, scalable, and democratic governance framework that allows multiple proposals to proceed simultaneously, ensuring the network evolves in alignment with its community's needs. +Integrate your parachain with essential ecosystem tools and services. -## Governance Evolution +| Tutorial | Description | +| :--------------------------------------------: | :----------------------------------------------------: | +| [Wallets](/parachains/integrations/wallets/) | Integrate wallet support for user interactions | +| [Indexers](/parachains/integrations/indexers/) | Set up indexing solutions for querying blockchain data | +| [Oracles](/parachains/integrations/oracles/) | Connect your parachain to off-chain data sources | -Polkadot’s governance journey began with [Governance V1](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#governance-summary){target=\_blank}, a system that proved effective in managing treasury funds and protocol upgrades. However, it faced limitations, such as: +## Additional Resources -- Slow voting cycles, causing delays in decision-making. -- Inflexibility in handling multiple referendums, restricting scalability. +- [Polkadot SDK Documentation](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/index.html) +- [Polkadot Wiki - Parachains](https://wiki.polkadot.network/docs/learn-parachains/) -To address these challenges, Polkadot introduced OpenGov, a governance model designed for greater inclusivity, efficiency, and scalability. OpenGov replaces the centralized structures of Governance V1, such as the Council and Technical Committee, with a fully decentralized and dynamic framework. -For a full comparison of the historic and current governance models, visit the [Gov1 vs. Polkadot OpenGov](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#gov1-vs-polkadot-opengov){target=\_blank} section of the Polkadot Wiki. +--- -## OpenGov Key Features +Page Title: Get Started with Smart Contracts -OpenGov transforms Polkadot’s governance into a decentralized, stakeholder-driven model, eliminating centralized decision-making bodies like the Council. Key enhancements include: +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-get-started.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/get-started/ +- Summary: Practical examples for building and deploying smart contracts on Polkadot Hub, from connecting and tooling to deployment, integrations, and precompiles. -- **Decentralization**: Shifts all decision-making power to the public, ensuring a more democratic process. -- **Enhanced delegation**: Allows users to delegate their votes to trusted experts across specific governance tracks. -- **Simultaneous referendums**: Multiple proposals can progress at once, enabling faster decision-making. -- **Polkadot Technical Fellowship**: A broad, community-driven group replacing the centralized Technical Committee. +# Get Started -This new system ensures Polkadot governance remains agile and inclusive, even as the ecosystem grows. +This resource provides quick-starts for building smart contracts on Polkadot Hub. Use the tables below to jump directly to the tools and workflows you need. -## Origins and Tracks +## Quick Starts -In OpenGov, origins and tracks are central to managing proposals and votes. +Kick off development fast with curated links for connecting, funding, exploring, and deploying your first contract. -- **Origin**: Determines the authority level of a proposal (e.g., Treasury, Root) which decides the track of all referendums from that origin. -- **Track**: Define the procedural flow of a proposal, such as voting duration, approval thresholds, and enactment timelines. +| Quick Start | Tools | Description | +|:---------------------------------------------------------------------------------------------------:|:---------------------:|:---------------------------------------------------------------:| +| [Connect to Polkadot](/smart-contracts/connect/){target=\_blank} | Polkadot.js, MetaMask | Add the network, configure RPC, verify activity in the explorer | +| [Get Test Tokens](/smart-contracts/faucets/){target=\_blank} | - | Request test funds to deploy and interact with contracts | +| [Explore Transactions](/smart-contracts/explorers/){target=\_blank} | Subscan | Inspect transactions, logs, token transfers, and contract state | +| [Deploy with Remix](/smart-contracts/dev-environments/remix/deploy-a-contract/){target=\_blank} | Remix | One‑click browser deployment to Polkadot Hub | +| [Deploy with Foundry](/smart-contracts/dev-environments/foundry/deploy-a-contract/){target=\_blank} | Foundry | Scripted deployments and testing from the CLI | +| [Deploy with Hardhat](/smart-contracts/dev-environments/hardhat/deploy-a-contract/){target=\_blank} | Hardhat | Project scaffolding, testing, and deployments | -Developers must be aware that referendums from different origins and tracks will take varying amounts of time to reach approval and enactment. The [Polkadot Technical Fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} has the option to shorten this timeline by whitelisting a proposal and allowing it to be enacted through the [Whitelist Caller](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#whitelisted-caller){target=\_blank} origin. +## Build and Test Locally -Visit [Origins and Tracks Info](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#origins-and-tracks){target=\_blank} for details on current origins and tracks, associated terminology, and parameters. +Set up local environments and CI-friendly workflows to iterate quickly and validate changes before deploying. -## Referendums +| Build and Test Locally | Tools | Description | +|:------------------------------------------------------------------------------------------------------------:|:-----------------:|:----------------------------------------------------:| +| [Run a Local Dev Node](/smart-contracts/dev-environments/local-dev-node/){target=\_blank} | Polkadot SDK node | Spin up a local node for iterative development | +| [Remix: Get Started](/smart-contracts/dev-environments/remix/get-started/){target=\_blank} | Remix | Connect Remix to Polkadot Hub and configure accounts | +| [Remix: Verify a Contract](/smart-contracts/dev-environments/remix/verify-a-contract/){target=\_blank} | Remix | Publish verified source on explorers | +| [Foundry: Install and Config](/smart-contracts/dev-environments/foundry/install-and-config/){target=\_blank} | Foundry | Install toolchain and configure networks | +| [Foundry: Compile and Test](/smart-contracts/dev-environments/foundry/compile-and-test/){target=\_blank} | Foundry | Write and run Solidity tests locally | +| [Foundry: Verify a Contract](/smart-contracts/dev-environments/foundry/verify-a-contract/){target=\_blank} | Foundry | Verify deployed bytecode and metadata | +| [Hardhat: Install and Config](/smart-contracts/dev-environments/hardhat/install-and-config/){target=\_blank} | Hardhat | Initialize a project and configure networks | +| [Hardhat: Compile and Test](/smart-contracts/dev-environments/hardhat/compile-and-test/){target=\_blank} | Hardhat | Unit test contracts and run scripts | +| [Hardhat: Verify a Contract](/smart-contracts/dev-environments/hardhat/verify-a-contract/){target=\_blank} | Hardhat | Verify deployments on explorers | -In OpenGov, anyone can submit a referendum, fostering an open and participatory system. The timeline for a referendum depends on the privilege level of the origin with more significant changes offering more time for community voting and participation before enactment. +## Ethereum Developer Resources -The timeline for an individual referendum includes four distinct periods: +Bridge your Ethereum knowledge with Polkadot Hub specifics: account mapping, fees, JSON‑RPC, and deployment. -- **Lead-in**: A minimum amount of time to allow for community participation, available room in the origin, and payment of the decision deposit. Voting is open during this period. -- **Decision**: Voting continues. -- **Confirmation**: Referendum must meet [approval and support](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#approval-and-support){target=\_blank} criteria during entire period to avoid rejection. -- **Enactment**: Changes approved by the referendum are executed. +| Ethereum Developer Guides | Description | +|:---------------------------------------------------------------------------------------------------------:|:---------------------------------------------------------------:| +| [Accounts](/smart-contracts/for-eth-devs/accounts/){target=\_blank} | How 20‑byte Ethereum addresses map to 32‑byte Polkadot accounts | +| [Blocks, Transactions, and Fees](/smart-contracts/for-eth-devs/blocks-transactions-fees/){target=\_blank} | Transaction types, fees, and multi‑dimensional metering | +| [Gas Model](/smart-contracts/for-eth-devs/gas-model/){target=\_blank} | Gas vs. weight, proof size, and storage deposits | +| [Contract Deployment](/smart-contracts/for-eth-devs/contract-deployment/){target=\_blank} | Deployment patterns and best practices on Polkadot Hub | +| [JSON‑RPC APIs](/smart-contracts/for-eth-devs/json-rpc-apis/){target=\_blank} | Supported Ethereum JSON‑RPC methods and examples | +| [Migration](/smart-contracts/for-eth-devs/migration/){target=\_blank} | Port existing apps and tooling to Polkadot Hub | +| [Dual VM Stack](/smart-contracts/for-eth-devs/dual-vm-stack/){target=\_blank} | Overview of EVM and native execution on the Hub | -### Vote on Referendums +## Cookbook: Hands‑on Tutorials -Voters can vote with their tokens on each referendum. Polkadot uses a voluntary token locking mechanism, called conviction voting, as a way for voters to increase their voting power. A token holder signals they have a stronger preference for approving a proposal based upon their willingness to lock up tokens. Longer voluntary token locks are seen as a signal of continual approval and translate to increased voting weight. +Follow step‑by‑step guides that walk through common tasks and complete dApp examples. -See [Voting on a Referendum](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank} for a deeper look at conviction voting and related token locks. +| Tutorial | Tools | Description | +|:--------------------------------------------------------------------------------------------------------:|:-------------------:|:-----------------------------------------:| +| [Deploy a Basic Contract](/smart-contracts/cookbook/smart-contracts/deploy-basic/remix/){target=\_blank} | Remix | Minimal deployment walkthrough | +| [Deploy an ERC‑20](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/){target=\_blank} | Remix, OpenZeppelin | Create, deploy, and mint a fungible token | +| [Deploy an NFT (ERC‑721)](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/){target=\_blank} | Remix, OpenZeppelin | Build and deploy an NFT collection | +| [Uniswap V2](/smart-contracts/cookbook/eth-dapps/uniswap-v2/){target=\_blank} | Hardhat | Full dApp project: compile, test, deploy | +| [Zero‑to‑Hero dApp](/smart-contracts/cookbook/dapps/zero-to-hero/){target=\_blank} | Multiple | End‑to‑end dApp patterns and practices | -### Delegate Voting Power +## Libraries -The OpenGov system also supports multi-role delegations, allowing token holders to assign their voting power on different tracks to entities with expertise in those areas. +Choose the client libraries that fit your stack for connecting wallets and calling contracts. -For example, if a token holder lacks the technical knowledge to evaluate proposals on the [Root track](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#root){target=\_blank}, they can delegate their voting power for that track to an expert they trust to vote in the best interest of the network. This ensures informed decision-making across tracks while maintaining flexibility for token holders. +| Library | Description | +|:------------------------------------------------------------------:|:-------------------------------------------------------:| +| [Ethers.js](/smart-contracts/libraries/ethers-js/){target=\_blank} | Connect, sign, and interact with contracts using Ethers | +| [viem](/smart-contracts/libraries/viem/){target=\_blank} | Type‑safe EVM interactions and utilities | +| [Wagmi](/smart-contracts/libraries/wagmi/){target=\_blank} | React hooks for wallet connections and contract calls | +| [Web3.js](/smart-contracts/libraries/web3-js/){target=\_blank} | Web3 provider and contract APIs | +| [Web3.py](/smart-contracts/libraries/web3-py/){target=\_blank} | Python toolkit for on‑chain interactions and scripts | -Visit [Multirole Delegation](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#multirole-delegation){target=\_blank} for more details on delegating voting power. +## Integrations -### Cancel a Referendum +Integrate essential services like wallets, indexers, and oracles to round out your dApp. -Polkadot OpenGov has two origins for rejecting ongoing referendums: +| Integration | Description | +|:-------------------------------------------------------------------:|:-----------------------------------------:| +| [Wallets](/smart-contracts/integrations/wallets/){target=\_blank} | Supported wallets and configuration notes | +| [Indexers](/smart-contracts/integrations/indexers/){target=\_blank} | Index and query blockchain data | +| [Oracles](/smart-contracts/integrations/oracles/){target=\_blank} | Bring external data on‑chain | -- [**Referendum Canceller**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-canceller){target=\_blank}: Cancels an active referendum when non-malicious errors occur and refunds the deposits to the originators. -- [**Referendum Killer**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-killer){target=\_blank}: Used for urgent, malicious cases this origin instantly terminates an active referendum and slashes deposits. +## Precompiles -See [Cancelling, Killing, and Blacklisting](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#cancelling-killing--blacklisting){target=\_blank} for additional information on rejecting referendums. +Discover precompiled system contracts available on the Hub and how to use them. -## Additional Resources +| Topic | Description | +|:------------------------------------------------------------------------:|:---------------------------------------------------:| +| [Overview of Precompiles](/smart-contracts/precompiles/){target=\_blank} | What precompiles are available on the Hub | +| [ETH Native](/smart-contracts/precompiles/eth-native/){target=\_blank} | EVM precompiles and interfaces | +| [Staking](/smart-contracts/precompiles/staking/){target=\_blank} | Interact with staking functionality via precompiles | +| [XCM](/smart-contracts/precompiles/xcm/){target=\_blank} | Cross‑chain messaging helpers for contracts | -- **[Democracy pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/democracy/src){target=\_blank}**: Handles administration of general stakeholder voting. -- **[Gov2: Polkadot’s Next Generation of Decentralised Governance](https://medium.com/polkadot-network/gov2-polkadots-next-generation-of-decentralised-governance-4d9ef657d11b){target=\_blank}**: Medium article by Gavin Wood. -- **[Polkadot Direction](https://matrix.to/#/#Polkadot-Direction:parity.io){target=\_blank}**: Matrix Element client. -- **[Polkassembly](https://polkadot.polkassembly.io/){target=\_blank}**: OpenGov dashboard and UI. -- **[Polkadot.js Apps Governance](https://polkadot.js.org/apps/#/referenda){target=\_blank}**: Overview of active referendums. +From here, follow the quick starts to get connected, iterate locally with your preferred tools, and use the guides, libraries, integrations, and precompiles as you grow into production‑ready dApps. If you get stuck, [open an issue](https://github.com/polkadot-developers/polkadot-docs/issues/new?template=docs-issue.yml){target=\_blank} or reach out in the community channels. --- -Page Title: Origins and Tracks +Page Title: Get Started with XCM -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-governance-origins-tracks.md -- Canonical (HTML): https://docs.polkadot.com/reference/governance/origins-tracks/ -- Summary: Explore Polkadot's OpenGov origins and tracks system, defining privilege levels, decision processes, and tailored pathways for network proposals. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md +- Canonical (HTML): https://docs.polkadot.com/parachains/interoperability/get-started/ +- Summary: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. -# Origins and Tracks +# Get Started with XCM ## Introduction -Polkadot's OpenGov system empowers decentralized decision-making and active community participation by tailoring the governance process to the impact of proposed changes. Through a system of origins and tracks, OpenGov ensures that every referendum receives the appropriate scrutiny, balancing security, inclusivity, and efficiency. - -This guide will help you understand the role of origins in classifying proposals by privilege and priority. You will learn how tracks guide proposals through tailored stages like voting, confirmation, and enactment and how to select the correct origin for your referendum to align with community expectations and network governance. - -Origins and tracks are vital in streamlining the governance workflow and maintaining Polkadot's resilience and adaptability. - -## Origins - -Origins are the foundation of Polkadot's OpenGov governance system. They categorize proposals by privilege and define their decision-making rules. Each origin corresponds to a specific level of importance and risk, guiding how referendums progress through the governance process. - -- High-privilege origins like Root Origin govern critical network changes, such as core software upgrades. -- Lower-privilege origins like Small Spender handle minor requests, such as community project funding under 10,000 DOT. - -Proposers select an origin based on the nature of their referendum. Origins determine parameters like approval thresholds, required deposits, and timeframes for voting and confirmation. Each origin is paired with a track, which acts as a roadmap for the proposal's lifecycle, including preparation, voting, and enactment. - -For a detailed list of origins and their associated parameters, see the [Polkadot OpenGov Origins](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/){target=\_blank} entry in the Polkadot Wiki. +Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems. -## Tracks +With XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation. -Tracks define a referendum's journey from submission to enactment, tailoring governance parameters to the impact of proposed changes. Each track operates independently and includes several key stages: +## Messaging Format -- **Preparation**: Time for community discussion before voting begins. -- **Voting**: Period for token holders to cast their votes. -- **Decision**: Finalization of results and determination of the proposal's outcome. -- **Confirmation**: Period to verify sustained community support before enactment. -- **Enactment**: Final waiting period before the proposal takes effect. +XCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics. -Tracks customize these stages with parameters like decision deposit requirements, voting durations, and approval thresholds, ensuring proposals from each origin receive the required scrutiny and process. For example, a runtime upgrade in the Root Origin track will have longer timeframes and stricter thresholds than a treasury request in the Small Spender track. +XCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing. -## Additional Resources +## The Four Principles of XCM -- For a list of origins and tracks for Polkadot and Kusama, including associated parameters, see the [Origins and Tracks Info](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#origins-and-tracks-info){target=\_blank} entry in the Polkadot Wiki. +XCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems: -- For a deeper dive into the approval and support system, see the [Approval and Support](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#approval-and-support){target=\_blank} entry of the Polkadot Wiki. +- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes. +- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended. +- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin. +- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems. +These principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments. ---- +## The XCM Tech Stack -Page Title: Overview of FRAME +![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp) -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime.md -- Canonical (HTML): https://docs.polkadot.com/parachains/customize-runtime/ -- Summary: Learn how Polkadot SDK’s FRAME framework simplifies blockchain development with modular pallets and support libraries for efficient runtime design. +The XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels. -# Customize Your Runtime +## Core Functionalities of XCM -## Introduction +XCM enhances cross-consensus communication by introducing several powerful features: -A blockchain runtime is more than just a fixed set of rules—it's a dynamic foundation that you can shape to match your specific needs. With Polkadot SDK's [FRAME (Framework for Runtime Aggregation of Modularized Entities)](/reference/glossary/#frame-framework-for-runtime-aggregation-of-modularized-entities){target=\_blank}, customizing your runtime is straightforward and modular. Instead of building everything from scratch, you combine pre-built pallets with your own custom logic to create a runtime suited to your blockchain's purpose. +- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management. +- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification. +- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location. -This overview explains how runtime customization works, introduces the building blocks you'll use, and guides you through the key patterns for extending your runtime. +The standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications. -## Understanding Your Runtime +## XCM Example -The runtime is the core logic of your blockchain—it processes transactions, manages state, and enforces the rules that govern your network. When a transaction arrives at your blockchain, the [`frame_executive`](https://paritytech.github.io/polkadot-sdk/master/frame_executive/index.html){target=\_blank} pallet receives it and routes it to the appropriate pallet for execution. +The following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA). -Think of your runtime as a collection of specialized modules, each handling a different aspect of your blockchain. Need token balances? Use the Balances pallet. Want governance? Add the Governance pallets. Need something custom? Create your own pallet. By mixing and matching these modules, you build a runtime that's efficient, secure, and tailored to your use case. +```rust +let message = Xcm(vec![ + WithdrawAsset((Here, amount).into()), + BuyExecution { + fees: (Here, amount).into(), + weight_limit: WeightLimit::Unlimited + }, + DepositAsset { + assets: All.into(), + beneficiary: MultiLocation { + parents: 0, + interior: Junction::AccountId32 { + network: None, + id: BOB.clone().into() + }.into(), + }.into() + } +]); +``` -## Runtime Architecture +The message consists of three instructions described as follows: -The following diagram shows how FRAME components work together to form your runtime: +- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register. -![](/images/parachains/customize-runtime/index/frame-overview-01.webp) + ```rust + WithdrawAsset((Here, amount).into()), + ``` -The main components are: + - **`Here`**: The native parachain token. + - **`amount`**: The number of tokens that are transferred. -- **`frame_executive`**: Routes all incoming transactions to the correct pallet for execution. -- **Pallets**: Domain-specific modules that implement your blockchain's features and business logic. -- **`frame_system`**: Provides core runtime primitives and storage. -- **`frame_support`**: Utilities and macros that simplify pallet development. + The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register. -## Building Blocks: Pallets +- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\_blank} of the XCM instructions. -[Pallets](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/pallet/index.html){target=\_blank} are the fundamental units of runtime customization. Each pallet encapsulates specific functionality and can be independently developed, tested, and integrated. + ```rust + BuyExecution { + fees: (Here, amount).into(), + weight_limit: WeightLimit::Unlimited + }, + ``` -A pallet can implement virtually any blockchain feature you need: + - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight. + - **`weight_limit`**: Defines the maximum fees that can be used to buy weight. -- Expose new transactions that users can submit. -- Store data on-chain. -- Enforce business rules and validation logic. -- Emit events to notify users of state changes. -- Handle errors gracefully. +- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\_blank}**: Moves the remaining tokens from the holding register to Bob’s account. -### Pre-Built Pallets vs. Custom Pallets + ```rust + DepositAsset { + assets: All.into(), + beneficiary: MultiLocation { + parents: 0, + interior: Junction::AccountId32 { + network: None, + id: BOB.clone().into() + }.into(), + }.into() + } + ``` -FRAME provides a comprehensive library of [pre-built pallets](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame){target=\_blank} for common blockchain features, including consensus, staking, balances, governance, and more. These pallets are battle-tested, optimized, and ready to use. + - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited. + +This step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. -However, you're not limited to pre-built functionality. When pre-built pallets don't meet your needs, you can create custom pallets with entirely custom logic. The real power of FRAME is the flexibility to use pre-built modules for standard features while building your own for unique requirements. +## Overview -### Pallet Structure +XCM revolutionizes cross-chain communication by enabling use cases such as: -FRAME uses Rust macros extensively, allowing you to focus on your pallet's logic while the framework handles boilerplate and integration code. +- Token transfers between blockchains. +- Asset locking for cross-chain smart contract interactions. +- Remote execution of functions on other blockchains. -A typical pallet looks like this: +These functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. -```rust -pub use pallet::*; -#[frame_support::pallet] -pub mod pallet { - use frame_support::pallet_prelude::*; - use frame_system::pallet_prelude::*; +--- - #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] - pub struct Pallet(_); +Page Title: Install Polkadot SDK - #[pallet::config] // snip - #[pallet::event] // snip - #[pallet::error] // snip - #[pallet::storage] // snip - #[pallet::call] // snip -} -``` +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-install-polkadot-sdk.md +- Canonical (HTML): https://docs.polkadot.com/parachains/install-polkadot-sdk/ +- Summary: Install all required Polkadot SDK dependencies, set up the SDK itself, and verify that it runs correctly on your machine. -Every pallet can implement these core macros: +# Install Polkadot SDK -- **`#[frame_support::pallet]`**: Marks your module as a FRAME pallet. -- **`#[pallet::pallet]`**: Designates the struct that holds pallet metadata. -- **`#[pallet::config]`**: Defines configuration and associated types. -- **`#[pallet::event]`**: Defines events emitted by your pallet. -- **`#[pallet::error]`**: Defines error types your pallet can return. -- **`#[pallet::storage]`**: Defines on-chain storage items. -- **`#[pallet::call]`**: Defines dispatchable functions (transactions). +This guide provides step-by-step instructions for installing the Polkadot SDK on macOS, Linux, and Windows. The installation process consists of two main parts: -For a comprehensive reference, see the [`pallet_macros` documentation](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/index.html){target=\_blank}. +- **Installing dependencies**: Setting up Rust, required system packages, and development tools. +- **Building the Polkadot SDK**: Cloning and compiling the Polkadot SDK repository. -## How Runtime Customization Works +Follow the appropriate section for your operating system to ensure all necessary tools are installed and configured properly. -Customizing your runtime typically follows these patterns: +## Install Dependencies: macOS -**Adding Pre-Built Pallets**: Select pallets from the FRAME library and integrate them into your runtime configuration. This is the fastest way to add functionality. +You can install Rust and set up a Substrate development environment on Apple macOS computers with Intel or Apple M1 processors. -**Creating Custom Pallets**: Write custom pallets for features that don't exist in the pre-built library. Custom pallets follow the same structure as pre-built ones and integrate seamlessly. +### Before You Begin {: #before-you-begin-mac-os } -**Combining Multiple Pallets**: Layer multiple pallets together to create complex behaviors. Pallets can call each other and share storage when needed. +Before you install Rust and set up your development environment on macOS, verify that your computer meets the following basic requirements: -**Configuring Pallet Parameters**: Most pallets are configurable—you can adjust their behavior through configuration traits without modifying their code. +- Operating system version is 10.7 Lion or later. +- Processor speed of at least 2 GHz. Note that 3 GHz is recommended. +- Memory of at least 8 GB RAM. Note that 16 GB is recommended. +- Storage of at least 10 GB of available space. +- Broadband Internet connection. -The following diagram illustrates how pallets combine to form a complete runtime: +### Install Homebrew -![](/images/parachains/customize-runtime/index/frame-overview-02.webp) +In most cases, you should use Homebrew to install and manage packages on macOS computers. If you don't already have Homebrew installed on your local computer, you should download and install it before continuing. -## Starting Templates +To install Homebrew: -The easiest way to begin customizing your runtime is with a starter template. These templates provide a pre-configured foundation so you can focus on customization rather than setup. +1. Open the Terminal application. +2. Download and install Homebrew by running the following command: -- **[Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank}**: The recommended choice for most developers, it includes pre-configured pallets for common features (balances, block production, governance), a complete runtime setup, and built-in parachain consensus support. This template offers the best balance of features and learning opportunities. + ```bash + /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" + ``` -- **[Polkadot SDK Minimal Template](https://github.com/paritytech/polkadot-sdk-minimal-template){target=\_blank}**: Provides a bare-bones runtime with only essential components. Choose this if you want maximum flexibility and prefer building from a clean slate. +3. Verify Homebrew has been successfully installed by running the following command: -- **[Polkadot SDK Solochain Template](https://github.com/paritytech/polkadot-sdk/tree/master/templates/solochain){target=\_blank}**: Designed for building standalone blockchains with moderate features, simple consensus, and several core pallets. Use this if you want a sovereign blockchain independent of a relay chain. + ```bash + brew --version + ``` -- **[OpenZeppelin Runtime Templates](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\_blank}**: Provides security-focused configurations following industry best practices. The [generic-template](https://github.com/OpenZeppelin/polkadot-runtime-templates/tree/main/generic-template){target=\_blank} includes curated pallet selections and production-ready defaults—ideal if security is your top priority. + The command displays output similar to the following: -## Key Customization Scenarios +
+ brew --version + Homebrew 4.3.15 +
-This section covers the most common customization patterns you'll encounter: +### Support for Apple Silicon -- **[Add Existing Pallets to Your Runtime](/parachains/customize-runtime/add-existing-pallets/)**: Integrate pre-built pallets from the FRAME library with minimal configuration. +Protobuf must be installed before the build process can begin. To install it, run the following command: -- **[Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/)**: Run multiple instances of the same pallet with different configurations—useful for multi-token systems or parallel features. +```bash +brew install protobuf +``` -- **[Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/)**: Enable smart contract execution on your parachain using Contracts pallets. +### Install Required Packages and Rust {: #install-required-packages-and-rust-mac-os } -- **[Create Custom Pallets](/parachains/customize-runtime/pallet-development/create-a-pallet/)**: Build entirely custom pallets for features unique to your blockchain. +Because the blockchain requires standard cryptography to support the generation of public/private key pairs and the validation of transaction signatures, you must also have a package that provides cryptography, such as `openssl`. -- **[Test Your Runtime](/parachains/customize-runtime/pallet-development/pallet-testing/)**: Unit test pallets and mock complete runtimes to ensure everything works correctly. +To install `openssl` and the Rust toolchain on macOS: +1. Open the Terminal application. +2. Ensure you have an updated version of Homebrew by running the following command: ---- + ```bash + brew update + ``` -Page Title: Overview of the Polkadot Relay Chain +3. Install the `openssl` package by running the following command: -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-relay-chain.md -- Canonical (HTML): https://docs.polkadot.com/reference/polkadot-hub/consensus-and-security/relay-chain/ -- Summary: Explore Polkadot's core architecture, including its multi-chain vision, shared security, and the DOT token's governance and staking roles. + ```bash + brew install openssl + ``` -# Overview +4. Download the `rustup` installation program and use it to install Rust by running the following command: -## Introduction + ```bash + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh + ``` -Polkadot is a next-generation blockchain protocol designed to support a multi-chain future by enabling secure communication and interoperability between different blockchains. Built as a Layer-0 protocol, Polkadot introduces innovations like application-specific Layer-1 chains ([parachains](/polkadot-protocol/architecture/parachains/){targe=\_blank}), shared security through [Nominated Proof of Stake (NPoS)](/reference/glossary/#nominated-proof-of-stake-npos){target=\_blank}, and cross-chain interactions via its native [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank}. +5. Follow the prompts displayed to proceed with a default installation. +6. Update your current shell to include Cargo by running the following command: -This guide covers key aspects of Polkadot’s architecture, including its high-level protocol structure, blockspace commoditization, and the role of its native token, DOT, in governance, staking, and resource allocation. + ```bash + source ~/.cargo/env + ``` -## Polkadot 1.0 +7. Configure the Rust toolchain to default to the latest stable version by running the following commands: -Polkadot 1.0 represents the state of Polkadot as of 2023, coinciding with the release of [Polkadot runtime v1.0.0](https://github.com/paritytech/polkadot/releases/tag/v1.0.0){target=\_blank}. This section will focus on Polkadot 1.0, along with philosophical insights into network resilience and blockspace. + ```bash + rustup default stable + rustup update + rustup target add wasm32-unknown-unknown + rustup component add rust-src + ``` -As a Layer-0 blockchain, Polkadot contributes to the multi-chain vision through several key innovations and initiatives, including: +8. Install `cmake` using the following command: -- **Application-specific Layer-1 blockchains (parachains)**: Polkadot's sharded network allows for parallel transaction processing, with shards that can have unique state transition functions, enabling custom-built L1 chains optimized for specific applications. + ```bash + brew install cmake + ``` -- **Shared security and scalability**: L1 chains connected to Polkadot benefit from its [Nominated Proof of Stake (NPoS)](/reference/polkadot-hub/consensus-and-security/pos-consensus/#nominated-proof-of-stake){target=\_blank} system, providing security out-of-the-box without the need to bootstrap their own. +9. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). -- **Secure interoperability**: Polkadot's native interoperability enables seamless data and value exchange between parachains. This interoperability can also be used outside of the ecosystem for bridging with external networks. +## Install Dependencies: Linux -- **Resilient infrastructure**: Decentralized and scalable, Polkadot ensures ongoing support for development and community initiatives via its on-chain [treasury](https://wiki.polkadot.com/learn/learn-polkadot-opengov-treasury/){target=\_blank} and governance. +Rust supports most Linux distributions. Depending on the specific distribution and version of the operating system you use, you might need to add some software dependencies to your environment. In general, your development environment should include a linker or a C-compatible compiler, such as `clang`, and an appropriate integrated development environment (IDE). -- **Rapid L1 development**: The [Polkadot SDK](/reference/parachains/){target=\_blank} allows fast, flexible creation and deployment of Layer-1 chains. +### Before You Begin {: #before-you-begin-linux } -- **Cultivating the next generation of Web3 developers**: Polkadot supports the growth of Web3 core developers through initiatives such as. +Check the documentation for your operating system for information about the installed packages and how to download and install any additional packages you might need. For example, if you use Ubuntu, you can use the Ubuntu Advanced Packaging Tool (`apt`) to install the `build-essential` package: - - [Polkadot Blockchain Academy](https://polkadot.com/blockchain-academy){target=\_blank} - - [EdX courses](https://www.edx.org/school/web3x){target=\_blank} - - Rust and Substrate courses (coming soon) +```bash +sudo apt install build-essential +``` -### High-Level Architecture +At a minimum, you need the following packages before you install Rust: -Polkadot features a chain that serves as the central component of the system. This chain is depicted as a ring encircled by several parachains that are connected to it. +```text +clang curl git make +``` -According to Polkadot's design, any blockchain that can compile to WebAssembly (Wasm) and adheres to the Parachains Protocol becomes a parachain on the Polkadot network. +Because the blockchain requires standard cryptography to support the generation of public/private key pairs and the validation of transaction signatures, you must also have a package that provides cryptography, such as `libssl-dev` or `openssl-devel`. -Here’s a high-level overview of the Polkadot protocol architecture: +### Install Required Packages and Rust {: #install-required-packages-and-rust-linux } -![](/images/reference/polkadot-hub/consensus-and-security/relay-chain/relay-chain-01.webp){ style="background:white" } +To install the Rust toolchain on Linux: -Parachains propose blocks to Polkadot validators, who check for availability and validity before finalizing them. With the relay chain providing security, collators—full nodes of parachains—can focus on their tasks without needing strong incentives. +1. Open a terminal shell. +2. Check the packages installed on the local computer by running the appropriate package management command for your Linux distribution. +3. Add any package dependencies you are missing to your local development environment by running the appropriate package management command for your Linux distribution: -The [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank} allows parachains to exchange messages freely, leveraging the chain's security for trust-free communication. + === "Ubuntu" -In order to interact with chains that want to use their own finalization process (e.g., Bitcoin), Polkadot has [bridges](/reference/parachains/interoperability/#bridges-connecting-external-networks){target=\_blank} that offer two-way compatibility, meaning that transactions can be made between different parachains. + ```bash + sudo apt install --assume-yes git clang curl libssl-dev protobuf-compiler + ``` -### Polkadot's Additional Functionalities + === "Debian" -Historically, obtaining core slots on Polkadot chain relied upon crowdloans and auctions. Chain cores were leased through auctions for three-month periods, up to a maximum of two years. Crowdloans enabled users to securely lend funds to teams for lease deposits in exchange for pre-sale tokens, which is the only way to access slots on Polkadot 1.0. Auctions are now deprecated in favor of [coretime](/polkadot-protocol/architecture/system-chains/coretime/){target=\_blank}. + ```sh + sudo apt install --assume-yes git clang curl libssl-dev llvm libudev-dev make protobuf-compiler + ``` -Additionally, the chain handles [staking](https://wiki.polkadot.com/learn/learn-staking/){target=\_blank}, [accounts](/reference/parachains/accounts/){target=\_blank}, balances, and [governance](/reference/governance/){target=\_blank}. + === "Arch" -#### Agile Coretime + ```sh + pacman -Syu --needed --noconfirm curl git clang make protobuf + ``` -The new and more efficient way of obtaining core on Polkadot is to go through the process of purchasing coretime. + === "Fedora" -[Agile coretime](/reference/polkadot-hub/consensus-and-security/agile-coretime/){target=\_blank} improves the efficient use of Polkadot's network resources and offers economic flexibility for developers, extending Polkadot's capabilities far beyond the original vision outlined in the [whitepaper](https://polkadot.com/papers/Polkadot-whitepaper.pdf){target=\_blank}. + ```sh + sudo dnf update + sudo dnf install clang curl git openssl-devel make protobuf-compiler + ``` -It enables parachains to purchase monthly "bulk" allocations of coretime (the time allocated for utilizing a core, measured in Polkadot relay chain blocks), ensuring heavy-duty parachains that can author a block every six seconds with [Asynchronous Backing](https://wiki.polkadot.com/learn/learn-async-backing/#asynchronous-backing){target=\_blank} can reliably renew their coretime each month. Although six-second block times are now the default, parachains have the option of producing blocks less frequently. + === "OpenSUSE" -Renewal orders are prioritized over new orders, offering stability against price fluctuations and helping parachains budget more effectively for project costs. + ```sh + sudo zypper install clang curl git openssl-devel llvm-devel libudev-devel make protobuf + ``` -### Polkadot's Resilience + Remember that different distributions might use different package managers and bundle packages in different ways. For example, depending on your installation selections, Ubuntu Desktop and Ubuntu Server might have different packages and different requirements. However, the packages listed in the command-line examples are applicable to many common Linux distributions, including Debian, Linux Mint, MX Linux, and Elementary OS. -Decentralization is a vital component of blockchain networks, but it comes with trade-offs: +4. Download the `rustup` installation program and use it to install Rust by running the following command: -- An overly decentralized network may face challenges in reaching consensus and require significant energy to operate. -- Also, a network that achieves consensus quickly risks centralization, making it easier to manipulate or attack. + ```bash + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh + ``` -A network should be decentralized enough to prevent manipulative or malicious influence. In this sense, decentralization is a tool for achieving resilience. +5. Follow the prompts displayed to proceed with a default installation. +6. Update your current shell to include Cargo by running the following command: -Polkadot 1.0 currently achieves resilience through several strategies: + ```bash + source $HOME/.cargo/env + ``` -- **Nominated Proof of Stake (NPoS)**: Ensures that the stake per validator is maximized and evenly distributed among validators. +7. Verify your installation by running the following command: -- **Decentralized nodes**: Designed to encourage operators to join the network. This program aims to expand and diversify the validators in the ecosystem who aim to become independent of the program during their term. Feel free to explore more about the program on the official [Decentralized Nodes](https://nodes.web3.foundation/){target=\_blank} page. + ```bash + rustc --version + ``` -- **On-chain treasury and governance**: Known as [OpenGov](/reference/governance/){target=\_blank}, this system allows every decision to be made through public referenda, enabling any token holder to cast a vote. +8. Configure the Rust toolchain to default to the latest stable version by running the following commands: -### Polkadot's Blockspace + ```bash + rustup default stable + rustup update + rustup target add wasm32-unknown-unknown + rustup component add rust-src + ``` -Polkadot 1.0’s design allows for the commoditization of blockspace. +9. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). -Blockspace is a blockchain's capacity to finalize and commit operations, encompassing its security, computing, and storage capabilities. Its characteristics can vary across different blockchains, affecting security, flexibility, and availability. +## Install Dependencies: Windows (WSL) -- **Security**: Measures the robustness of blockspace in Proof of Stake (PoS) networks linked to the stake locked on validator nodes, the variance in stake among validators, and the total number of validators. It also considers social centralization (how many validators are owned by single operators) and physical centralization (how many validators run on the same service provider). +In general, UNIX-based operating systems—like macOS or Linux—provide a better development environment for building Substrate-based blockchains. -- **Flexibility**: Reflects the functionalities and types of data that can be stored, with high-quality data essential to avoid bottlenecks in critical processes. +However, suppose your local computer uses Microsoft Windows instead of a UNIX-based operating system. In that case, you can configure it with additional software to make it a suitable development environment for building Substrate-based blockchains. To prepare a development environment on a Microsoft Windows computer, you can use Windows Subsystem for Linux (WSL) to emulate a UNIX operating environment. -- **Availability**: Indicates how easily users can access blockspace. It should be easily accessible, allowing diverse business models to thrive, ideally regulated by a marketplace based on demand and supplemented by options for "second-hand" blockspace. +### Before You Begin {: #before-you-begin-windows-wls } -Polkadot is built on core blockspace principles, but there's room for improvement. Tasks like balance transfers, staking, and governance are managed on the relay chain. +Before installing on Microsoft Windows, verify the following basic requirements: -Delegating these responsibilities to [system chains](/polkadot-protocol/architecture/system-chains/){target=\_blank} could enhance flexibility and allow the relay chain to concentrate on providing shared security and interoperability. +- You have a computer running a supported Microsoft Windows operating system: + - **For Windows desktop**: You must be running Microsoft Windows 10, version 2004 or later, or Microsoft Windows 11 to install WSL. + - **For Windows server**: You must be running Microsoft Windows Server 2019, or later, to install WSL on a server operating system. +- You have a good internet connection and access to a shell terminal on your local computer. -For more information about blockspace, watch [Robert Habermeier’s interview](https://www.youtube.com/watch?v=e1vISppPwe4){target=\_blank} or read his [technical blog post](https://www.rob.tech/blog/polkadot-blockspace-over-blockchains/){target=\_blank}. +### Set Up Windows Subsystem for Linux -## DOT Token +WSL enables you to emulate a Linux environment on a computer that uses the Windows operating system. The primary advantage of this approach for Substrate development is that you can use all of the code and command-line examples as described in the Substrate documentation. For example, you can run common commands—such as `ls` and `ps`—unmodified. By using WSL, you can avoid configuring a virtual machine image or a dual-boot operating system. -DOT is the native token of the Polkadot network, much like BTC for Bitcoin and Ether for the Ethereum blockchain. DOT has 10 decimals, uses the Planck base unit, and has a balance type of `u128`. The same is true for Kusama's KSM token with the exception of having 12 decimals. +To prepare a development environment using WSL: -### Redenomination of DOT - -Polkadot conducted a community poll, which ended on 27 July 2020 at block 888,888, to decide whether to redenominate the DOT token. The stakeholders chose to redenominate the token, changing the value of 1 DOT from 1e12 plancks to 1e10 plancks. +1. Check your Windows version and build number to see if WSL is enabled by default. -Importantly, this did not affect the network's total number of base units (plancks); it only affects how a single DOT is represented. The redenomination became effective 72 hours after transfers were enabled, occurring at block 1,248,328 on 21 August 2020 around 16:50 UTC. + If you have Microsoft Windows 10, version 2004 (Build 19041 and higher), or Microsoft Windows 11, WSL is available by default and you can continue to the next step. -### The Planck Unit + If you have an older version of Microsoft Windows installed, see the [WSL manual installation steps for older versions](https://learn.microsoft.com/en-us/windows/wsl/install-manual){target=\_blank}. If you are installing on an older version of Microsoft Windows, you can download and install WLS 2 if your computer has Windows 10, version 1903 or higher. -The smallest unit of account balance on Polkadot SDK-based blockchains (such as Polkadot and Kusama) is called _Planck_, named after the Planck length, the smallest measurable distance in the physical universe. +2. Select **Windows PowerShell** or **Command Prompt** from the **Start** menu, right-click, then **Run as administrator**. -Similar to how BTC's smallest unit is the Satoshi and ETH's is the Wei, Polkadot's native token DOT equals 1e10 Planck, while Kusama's native token KSM equals 1e12 Planck. +3. In the PowerShell or Command Prompt terminal, run the following command: -### Uses for DOT + ```bash + wsl --install + ``` -DOT serves three primary functions within the Polkadot network: + This command enables the required WSL 2 components that are part of the Windows operating system, downloads the latest Linux kernel, and installs the Ubuntu Linux distribution by default. -- **Governance**: It is used to participate in the governance of the network. -- **Staking**: DOT is staked to support the network's operation and security. -- **Buying coretime**: Used to purchase coretime in-bulk or on-demand and access the chain to benefit from Polkadot's security and interoperability. + If you want to review the other Linux distributions available, run the following command: -Additionally, DOT can serve as a transferable token. For example, DOT, held in the treasury, can be allocated to teams developing projects that benefit the Polkadot ecosystem. + ```bash + wsl --list --online + ``` -## JAM and the Road Ahead +4. After the distribution is downloaded, close the terminal. -The Join-Accumulate Machine (JAM) represents a transformative redesign of Polkadot's core architecture, envisioned as the successor to the current relay chain. Unlike traditional blockchain architectures, JAM introduces a unique computational model that processes work through two primary functions: +5. Click the **Start** menu, select **Shut down or sign out**, then click **Restart** to restart the computer. -- **Join**: Handles data integration. -- **Accumulate**: Folds computations into the chain's state. + Restarting the computer is required to start the installation of the Linux distribution. It can take a few minutes for the installation to complete after you restart. -JAM removes many of the opinions and constraints of the current relay chain while maintaining its core security properties. Expected improvements include: + For more information about setting up WSL as a development environment, see the [Set up a WSL development environment](https://learn.microsoft.com/en-us/windows/wsl/setup/environment){target=\_blank} docs. -- **Permissionless code execution**: JAM is designed to be more generic and flexible, allowing for permissionless code execution through services that can be deployed without governance approval. -- **More effective block time utilization**: JAM's efficient pipeline processing model places the prior state root in block headers instead of the posterior state root, enabling more effective utilization of block time for computations. +### Install Required Packages and Rust {: #install-required-packages-and-rust-windows-wls } -This architectural evolution promises to enhance Polkadot's scalability and flexibility while maintaining robust security guarantees. JAM is planned to be rolled out to Polkadot as a single, complete upgrade rather than a stream of smaller updates. This approach seeks to minimize the developer overhead required to address any breaking changes. +To install the Rust toolchain on WSL: +1. Click the **Start** menu, then select **Ubuntu**. +2. Type a UNIX user name to create a user account. +3. Type a password for your UNIX user, then retype the password to confirm it. +4. Download the latest updates for the Ubuntu distribution using the Ubuntu Advanced Packaging Tool (`apt`) by running the following command: ---- + ```bash + sudo apt update + ``` -Page Title: Parachains Overview +5. Add the required packages for the Ubuntu distribution by running the following command: -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/ -- Summary: Learn about parachains, specialized blockchains on Polkadot that gain shared security and interoperability. Discover how they work and the tools to build them. + ```bash + sudo apt install --assume-yes git clang curl libssl-dev llvm libudev-dev make protobuf-compiler + ``` -# Parachains Overview +6. Download the `rustup` installation program and use it to install Rust for the Ubuntu distribution by running the following command: -## Introduction + ```bash + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh + ``` -A parachain is a specialized blockchain that connects to the Polkadot relay chain, benefiting from shared security, interoperability, and scalability. Parachains are built using the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}, a powerful toolkit written in Rust that provides everything needed to create custom blockchain logic while integrating seamlessly with the Polkadot network. +7. Follow the prompts displayed to proceed with a default installation. -Unlike standalone blockchains that must bootstrap their own validator sets and security, parachains leverage Polkadot's pooled security model. This allows parachain developers to focus on their application-specific functionality rather than consensus and security infrastructure. Parachains can communicate with each other through Cross-Consensus Messaging (XCM), enabling seamless interoperability across the Polkadot ecosystem. +8. Update your current shell to include Cargo by running the following command: -Key capabilities that parachains provide include: + ```bash + source ~/.cargo/env + ``` -- **Shared security**: Inherit security from Polkadot's validator set without maintaining your own. -- **Interoperability**: Communicate trustlessly with other parachains via XCM. -- **Scalability**: Process transactions in parallel with other parachains. -- **Customization**: Build application-specific logic tailored to your use case. -- **Upgradeability**: Upgrade runtime logic without hard forks. +9. Verify your installation by running the following command: -## Polkadot SDK: Parachain Architecture + ```bash + rustc --version + ``` -Building a parachain involves understanding and utilizing several key components of the Polkadot SDK: +10. Configure the Rust toolchain to use the latest stable version as the default toolchain by running the following commands: -![](/images/reference/parachains/index/overview-01.webp) + ```bash + rustup default stable + rustup update + rustup target add wasm32-unknown-unknown + rustup component add rust-src + ``` -- **[Substrate](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/substrate/index.html){target=\_blank}**: The foundation providing core blockchain primitives and libraries. -- **[FRAME](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank}**: A modular framework for building your parachain's runtime logic. -- **[Cumulus](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/cumulus/index.html){target=\_blank}**: Essential libraries and pallets that enable parachain functionality. -- **[XCM (Cross Consensus Messaging)](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/xcm/index.html){target=\_blank}**: The messaging format for communicating with other parachains and the relay chain. -- **[Polkadot](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/polkadot/index.html){target=\_blank}**: The relay chain that provides security and coordination. +11. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). -### Substrate: The Foundation +## Build the Polkadot SDK -Substrate provides the core infrastructure that every parachain is built upon. It handles the low-level blockchain functionality, allowing you to focus on your application's unique features. Substrate includes implementations for networking, database management, consensus participation, and the execution environment for your runtime. +After installing all dependencies, you can now clone and compile the Polkadot SDK repository to verify your setup. -Every Polkadot SDK node consists of two main components: +### Clone the Polkadot SDK -- **Client (Host)**: Handles infrastructure services. +1. Clone the Polkadot SDK repository: - - Native binary that runs on validator and collator nodes. - - Executes the Wasm-compiled runtime. - - Manages networking, database, mempool, and block production. - - Interfaces with the relay chain for validation. + ```bash + git clone https://github.com/paritytech/polkadot-sdk.git + ``` -- **Runtime (State Transition Function)**: Contains your business logic. +2. Navigate into the project directory: - - Defines how your Polkadot SDK node processes transactions. - - Compiled to [Wasm](https://webassembly.org/){target=\_blank} for deterministic execution. - - Stored on-chain and upgradeable via governance. + ```bash + cd polkadot-sdk + ``` -```mermaid -%%{init: {'flowchart': {'padding': 5, 'nodeSpacing': 50, 'rankSpacing': 10}}}%% -graph TB - classDef title font-size:20px,font-weight:bold,stroke-width:0px - classDef clientStyle font-size:16px,font-weight:bold - classDef clientSubNodeStyle margin-top:10px - classDef runtimeCallExecutorStyle padding-top:10px +### Compile the Polkadot SDK - subgraph sg1[Parachain
Node] - direction TB +Compile the entire Polkadot SDK repository to ensure your environment is properly configured: - I[RuntimeCall Executor] - B[Wasm Runtime - STF] +```bash +cargo build --release --locked +``` - subgraph sg2[Client] - direction TB - C[Network and Blockchain
Infrastructure Services
+ Relay Chain Interface] - end +!!!note + This initial compilation will take significant time, depending on your machine specifications. It compiles all components of the Polkadot SDK to verify your toolchain is correctly configured. - I --> B - end +### Verify the Build - class sg1 title - class sg2 clientStyle - class C clientSubNodeStyle - class I runtimeCallExecutorStyle +Once the build completes successfully, verify the installation by checking the compiled binaries: +```bash +ls target/release ``` -### FRAME: Building Blocks for Your Runtime +You should see several binaries, including: + +- `polkadot`: The Polkadot relay chain node. +- `polkadot-parachain`: The parachain collator node. +- `polkadot-omni-node`:The omni node for running parachains. +- `substrate-node`: The kitchensink node with many pre-configured pallets. -FRAME provides modular components called [pallets](/reference/glossary#pallet){target=\_blank} that you can compose to build your parachain's runtime. Each pallet provides specific functionality that you can customize and configure for your needs. This modular approach allows you to quickly assemble complex functionality without writing everything from scratch. +Verify the Polkadot binary works by checking its version: -```mermaid -graph LR - subgraph SP["Parachain Runtime"] - direction LR - Timestamp ~~~ Aura ~~~ ParachainSystem - Balances ~~~ TransactionPayment ~~~ Sudo - subgraph Timestamp["Timestamp"] - SS1[Custom Config] - end - subgraph Aura["Aura"] - SS2[Custom Config] - end - subgraph ParachainSystem["Parachain System"] - SS3[Custom Config] - end - subgraph Balances["Balances"] - SS4[Custom Config] - end - subgraph TransactionPayment["Transaction Payment"] - SS5[Custom Config] - end - subgraph Sudo["Sudo"] - SS6[Custom Config] - end - style Timestamp stroke:#FF69B4 - style Aura stroke:#FF69B4 - style ParachainSystem stroke:#FF69B4 - style Balances stroke:#FF69B4 - style TransactionPayment stroke:#FF69B4 - style Sudo stroke:#FF69B4 - style SS1 stroke-dasharray: 5 - style SS2 stroke-dasharray: 5 - style SS3 stroke-dasharray: 5 - style SS4 stroke-dasharray: 5 - style SS5 stroke-dasharray: 5 - style SS6 stroke-dasharray: 5 - - end - subgraph AP["Available FRAME Pallets"] - direction LR - A1[Aura]~~~A2[Parachain
System]~~~A3[Transaction
Payment]~~~A4[Sudo] - B1[Identity]~~~B2[Balances]~~~B3[Assets]~~~B4[EVM] - C1[Timestamp]~~~C2[Staking]~~~C3[Contracts]~~~C4[and more...] - end - AP --> SP +```bash +./target/release/polkadot --version +``` + +This should display version information similar to: + +```bash +polkadot 1.16.0-1234abcd567 ``` -### Cumulus: Parachain-Specific Functionality +If you see the version output without errors, your development environment is correctly configured and ready for Polkadot SDK development! -Cumulus is what transforms a Polkadot SDK-based runtime into a parachain-capable runtime. It provides the essential components for communicating with the relay chain, participating in Polkadot's consensus, and handling parachain-specific operations like block validation and collation. +## Optional: Run the Kitchensink Node -Key Cumulus components include: +The Polkadot SDK includes a feature-rich node called "kitchensink" located at `substrate/bin/node`. This node comes pre-configured with many pallets and features from the Polkadot SDK, making it an excellent reference for exploring capabilities and understanding how different components work together. -- **Parachain system pallet**: Core parachain functionality and relay chain communication. -- **Collator consensus**: Block production logic for parachain collators. -- **Relay chain interface**: APIs for interacting with the Polkadot relay chain. -- **Validation data**: Handling proof-of-validity data required by relay chain validators. +!!!note + If you've already compiled the Polkadot SDK in the previous step, the `substrate-node` binary is already built and ready to use. You can skip directly to running the node. -## Where to Go Next +### Run the Kitchensink Node in Development Mode -Building a parachain requires understanding the relationship between your chain and the Polkadot relay chain. The Polkadot SDK provides all the tools needed to design custom runtime logic, enable cross-chain communication, and deploy your parachain to production. +From the `polkadot-sdk` root directory, start the kitchensink node in development mode: -The following sections provide detailed guidance on each aspect of parachain development, from initial design through deployment and ongoing maintenance. +```bash +./target/release/substrate-node --dev +``` -
+The `--dev` flag enables development mode, which: -- Guide __Launch a Simple Parachain__ +- Runs a single-node development chain. +- Produces and finalizes blocks automatically. +- Uses pre-configured development accounts (Alice, Bob, etc.). +- Deletes all data when stopped, ensuring a clean state on restart. - --- - Walk through the complete parachain launch flow: from setup and deployment to obtaining coretime. +You should see log output indicating the node is running and producing blocks, with increasing block numbers after `finalized`. - [:octicons-arrow-right-24: Deploy](/parachains/launch-a-parachain/set-up-the-parachain-template/) +### Interact with the Kitchensink Node +The kitchensink node is accessible at `ws://localhost:9944`. Open [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} in your browser to explore its features and connect to the local node. -- Guide __Customize Your Runtime__ +1. Click the network icon in the top left corner. +2. Scroll to **Development** and select **Local Node**. +3. Click **Switch** to connect to your local node. - --- +![](/images/parachains/install-polkadot-sdk/install-polkadot-sdk-1.webp) - Design your parachain's runtime logic and choose appropriate pallets for your use case. +Once connected, the interface updates its color scheme to indicate a successful connection to the local node. - [:octicons-arrow-right-24: Get Started](/parachains/customize-runtime/) +![](/images/parachains/install-polkadot-sdk/install-polkadot-sdk-2.webp) -- Guide __Interoperability__ +You can now explore the various pallets and features included in the kitchensink node, making it a valuable reference as you develop your own blockchain applications. - --- +To stop the node, press `Control-C` in the terminal. - Implement XCM for trustless cross-chain communication with other parachains. +## Where to Go Next - [:octicons-arrow-right-24: Learn More](/parachains/interoperability/get-started/) +
-- Guide __Runtime Upgrades__ +- __Get Started with Parachain Development__ --- - Upgrade your parachain's runtime without hard forks using forkless upgrade mechanisms. - - [:octicons-arrow-right-24: Maintain](/parachains/runtime-maintenance/runtime-upgrades/) + Practical examples and tutorials for building and deploying Polkadot parachains, covering everything from launch to customization and cross-chain messaging. + [:octicons-arrow-right-24: Get Started](/parachains/get-started/) +
--- -Page Title: People Chain +Page Title: JSON-RPC APIs -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-people-and-identity.md -- Canonical (HTML): https://docs.polkadot.com/reference/polkadot-hub/people-and-identity/ -- Summary: Learn how People chain secures decentralized identity management, empowering users to control and verify digital identities without central authorities. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-json-rpc-apis.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/json-rpc-apis/ +- Summary: JSON-RPC APIs guide for Polkadot Hub, covering supported methods, parameters, and examples for interacting with the chain. -# People Chain +# JSON-RPC APIs +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. ## Introduction -People chain is a specialized parachain within the Polkadot ecosystem dedicated to secure, decentralized identity management. - -This solution empowers users to create, control, and verify their digital identities without reliance on centralized authorities. By prioritizing user sovereignty and data privacy, People chain establishes a foundation for trusted interactions throughout the Polkadot ecosystem while returning control of personal information to individuals. - -## Identity Management System - -People chain provides a comprehensive identity framework allowing users to: - -- Establish verifiable on-chain identities. -- Control disclosure of personal information. -- Receive verification from trusted registrars. -- Link multiple accounts under a unified identity. - -Users must reserve funds in a bond to store their information on chain. These funds are locked, not spent, and returned when the identity is cleared. - -### Sub-Identities - -The platform supports hierarchical identity structures through sub-accounts: - -- Primary accounts can establish up to 100 linked sub-accounts. -- Each sub-account maintains its own distinct identity. -- All sub-accounts require a separate bond deposit. +Polkadot Hub provides Ethereum compatibility through its JSON-RPC interface, allowing developers to interact with the chain using familiar Ethereum tooling and methods. This document outlines the supported [Ethereum JSON-RPC methods](https://ethereum.org/developers/docs/apis/json-rpc/#json-rpc-methods){target=\_blank} and provides examples of how to use them. -## Verification Process +This guide uses the Polkadot Hub TestNet endpoint: -### Judgment Requests +```text +https://testnet-passet-hub-eth-rpc.polkadot.io +``` -After establishing an on-chain identity, users can request verification from [registrars](#registrars): +## Available Methods -1. Users specify the maximum fee they're willing to pay for judgment. -2. Only registrars whose fees fall below this threshold can provide verification. -3. Registrars assess the provided information and issue a judgment. +### eth_accounts -### Judgment Classifications +Returns a list of addresses owned by the client. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_accounts){target=\_blank}. -Registrars can assign the following confidence levels to identity information: +**Parameters**: -- **Unknown**: Default status; no judgment rendered yet. -- **Reasonable**: Data appears valid but without formal verification (standard for most verified identities). -- **Known good**: Information certified correct through formal verification (requires documentation; limited to registrars). -- **Out of date**: Previously verified information that requires updating. -- **Low quality**: Imprecise information requiring correction. -- **Erroneous**: Incorrect information, potentially indicating fraudulent intent. +None. -A temporary "Fee Paid" status indicates judgment in progress. Both "Fee Paid" and "Erroneous" statuses lock identity information from modification until resolved. +**Example**: -### Registrars +```bash title="eth_accounts" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_accounts", + "params":[], + "id":1 +}' +``` -Registrars serve as trusted verification authorities within the People chain ecosystem. These entities validate user identities and provide attestations that build trust in the network. +--- -- Registrars set specific fees for their verification services. -- They can specialize in verifying particular identity fields. -- Verification costs vary based on complexity and thoroughness. +### eth_blockNumber -When requesting verification, users specify their maximum acceptable fee. Only registrars whose fees fall below this threshold can provide judgment. Upon completing the verification process, the user pays the registrar's fee, and the registrar issues an appropriate confidence level classification based on their assessment. +Returns the number of the most recent block. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_blocknumber){target=\_blank}. -Multiple registrars operate across the Polkadot and People chain ecosystems, each with unique specializations and fee structures. To request verification: +**Parameters**: -1. Research available registrars and their verification requirements. -2. Contact your chosen registrar directly through their specified channels. -3. Submit required documentation according to their verification process. -4. Pay the associated verification fee. +None. -You must contact specific registrars individually to request judgment. Each registrar maintains its own verification procedures and communication channels. +**Example**: -## Where to Go Next +```bash title="eth_blockNumber" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_blockNumber", + "params":[], + "id":1 +}' +``` -
+--- -- External __Polkadot.js Guides about Identity__ +### eth_call - --- +Executes a new message call immediately without creating a transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_call){target=\_blank}. - Step-by-step instructions for managing identities through the Polkadot.js interface, with practical examples and visual guides. +**Parameters**: - [:octicons-arrow-right-24: Reference](https://wiki.polkadot.com/learn/learn-guides-identity/) +- **`transaction` ++"object"++**: The transaction call object. + - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -- External __How to Set and Clear an Identity__ +**Example**: - --- +```bash title="eth_call" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_call", + "params":[{ + "to": "INSERT_RECIPIENT_ADDRESS", + "data": "INSERT_ENCODED_CALL" + }, "INSERT_BLOCK_VALUE"], + "id":1 +}' +``` - Practical walkthrough covering identity setup and removal process on People chain. +Ensure to replace the `INSERT_RECIPIENT_ADDRESS`, `INSERT_ENCODED_CALL`, and `INSERT_BLOCK_VALUE` with the proper values. - [:octicons-arrow-right-24: Reference](https://support.polkadot.network/support/solutions/articles/65000181981-how-to-set-and-clear-an-identity) +--- -- External __People Chain Runtime Implementation__ +### eth_chainId - --- +Returns the chain ID used for signing transactions. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_chainid){target=\_blank}. - Source code for the People chain runtime, detailing the technical architecture of decentralized identity management. +**Parameters**: - [:octicons-arrow-right-24: Reference](https://github.com/polkadot-fellows/runtimes/tree/main/system-parachains/people) +None. -
+**Example**: +```bash title="eth_chainId" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_chainId", + "params":[], + "id":1 +}' +``` --- -Page Title: Polkadot SDK Accounts - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-accounts.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/accounts/ -- Summary: Learn about account structures, balances, and address formats in the Polkadot SDK, including how to manage lifecycle, references, and balances. - -# Accounts - -## Introduction - -Accounts are essential for managing identity, transactions, and governance on the network in the Polkadot SDK. Understanding these components is critical for seamless development and operation on the network, whether you're building or interacting with Polkadot-based chains. - -This page will guide you through the essential aspects of accounts, including their data structure, balance types, reference counters, and address formats. You’ll learn how accounts are managed within the runtime, how balances are categorized, and how addresses are encoded and validated. - -## Account Data Structure +### eth_estimateGas -Accounts are foundational to any blockchain, and the Polkadot SDK provides a flexible management system. This section explains how the Polkadot SDK defines accounts and manages their lifecycle through data structures within the runtime. +Estimates gas required for a transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_estimategas){target=\_blank}. -### Account +**Parameters**: -The [`Account` data type](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/type.Account.html){target=\_blank} is a storage map within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank} that links an account ID to its corresponding data. This structure is fundamental for mapping account-related information within the chain. +- **`transaction` ++"object"++**: The transaction call object. + - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -The code snippet below shows how accounts are defined: +**Example**: -```rs - /// The full account information for a particular account ID. - #[pallet::storage] - #[pallet::getter(fn account)] - pub type Account = StorageMap< - _, - Blake2_128Concat, - T::AccountId, - AccountInfo, - ValueQuery, - >; +```bash title="eth_estimateGas" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_estimateGas", + "params":[{ + "to": "INSERT_RECIPIENT_ADDRESS", + "data": "INSERT_ENCODED_FUNCTION_CALL" + }], + "id":1 +}' ``` -The preceding code block defines a storage map named `Account`. The `StorageMap` is a type of on-chain storage that maps keys to values. In the `Account` map, the key is an account ID, and the value is the account's information. Here, `T` represents the generic parameter for the runtime configuration, which is defined by the pallet's configuration trait (`Config`). - -The `StorageMap` consists of the following parameters: - -- **`_`**: Used in macro expansion and acts as a placeholder for the storage prefix type. Tells the macro to insert the default prefix during expansion. -- **`Blake2_128Concat`**: The hashing function applied to keys in the storage map. -- **`T: :AccountId`**: Represents the key type, which corresponds to the account’s unique ID. -- **`AccountInfo`**: The value type stored in the map. For each account ID, the map stores an `AccountInfo` struct containing: - - - **`T::Nonce`**: A nonce for the account, which is incremented with each transaction to ensure transaction uniqueness. - - **`T: :AccountData`**: Custom account data defined by the runtime configuration, which could include balances, locked funds, or other relevant information. - -- **`ValueQuery`**: Defines how queries to the storage map behave when no value is found; returns a default value instead of `None`. - -For a detailed explanation of storage maps, see the [`StorageMap`](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/struct.StorageMap.html){target=\_blank} entry in the Rust docs. - -### Account Info - -The `AccountInfo` structure is another key element within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank}, providing more granular details about each account's state. This structure tracks vital data, such as the number of transactions and the account’s relationships with other modules. - -```rs -/// Information of an account. -#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)] -pub struct AccountInfo { - /// The number of transactions this account has sent. - pub nonce: Nonce, - /// The number of other modules that currently depend on this account's existence. The account - /// cannot be reaped until this is zero. - pub consumers: RefCount, - /// The number of other modules that allow this account to exist. The account may not be reaped - /// until this and `sufficients` are both zero. - pub providers: RefCount, - /// The number of modules that allow this account to exist for their own purposes only. The - /// account may not be reaped until this and `providers` are both zero. - pub sufficients: RefCount, - /// The additional data that belongs to this account. Used to store the balance(s) in a lot of - /// chains. - pub data: AccountData, -} -``` +Ensure to replace the `INSERT_RECIPIENT_ADDRESS` and `INSERT_ENCODED_CALL` with the proper values. -The `AccountInfo` structure includes the following components: +--- -- **`nonce`**: Tracks the number of transactions initiated by the account, which ensures transaction uniqueness and prevents replay attacks. -- **`consumers`**: Counts how many other modules or pallets rely on this account’s existence. The account cannot be removed from the chain (reaped) until this count reaches zero. -- **`providers`**: Tracks how many modules permit this account’s existence. An account can only be reaped once both `providers` and `sufficients` are zero. -- **`sufficients`**: Represents the number of modules that allow the account to exist for internal purposes, independent of any other modules. -- **`AccountData`**: A flexible data structure that can be customized in the runtime configuration, usually containing balances or other user-specific data. +### eth_gasPrice -This structure helps manage an account's state and prevents its premature removal while it is still referenced by other on-chain data or modules. The [`AccountInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.AccountInfo.html){target=\_blank} structure can vary as long as it satisfies the trait bounds defined by the `AccountData` associated type in the [`frame-system::pallet::Config`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/trait.Config.html){target=\_blank} trait. +Returns the current gas price in Wei. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gasprice){target=\_blank}. -### Account Reference Counters +**Parameters**: -Polkadot SDK uses reference counters to track an account’s dependencies across different runtime modules. These counters ensure that accounts remain active while data is associated with them. +None. -The reference counters include: +**Example**: -- **`consumers`**: Prevents account removal while other pallets still rely on the account. -- **`providers`**: Ensures an account is active before other pallets store data related to it. -- **`sufficients`**: Indicates the account’s independence, ensuring it can exist even without a native token balance, such as when holding sufficient alternative assets. +```bash title="eth_gasPrice" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_gasPrice", + "params":[], + "id":1 +}' +``` -#### Providers Reference Counters +--- -The `providers` counter ensures that an account is ready to be depended upon by other runtime modules. For example, it is incremented when an account has a balance above the existential deposit, which marks the account as active. +### eth_getBalance -The system requires this reference counter to be greater than zero for the `consumers` counter to be incremented, ensuring the account is stable before any dependencies are added. +Returns the balance of a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getbalance){target=\_blank}. -#### Consumers Reference Counters +**Parameters**: -The `consumers` counter ensures that the account cannot be reaped until all references to it across the runtime have been removed. This check prevents the accidental deletion of accounts that still have active on-chain data. +- **`address` ++"string"++**: Address to query balance. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -It is the user’s responsibility to clear out any data from other runtime modules if they wish to remove their account and reclaim their existential deposit. +**Example**: -#### Sufficients Reference Counter +```bash title="eth_getBalance" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getBalance", + "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], + "id":1 +}' +``` -The `sufficients` counter tracks accounts that can exist independently without relying on a native account balance. This is useful for accounts holding other types of assets, like tokens, without needing a minimum balance in the native token. +Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. -For instance, the [Assets pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_assets/index.html){target=\_blank}, may increment this counter for an account holding sufficient tokens. +--- -#### Account Deactivation +### eth_getBlockByHash -In Polkadot SDK-based chains, an account is deactivated when its reference counters (such as `providers`, `consumers`, and `sufficient`) reach zero. These counters ensure the account remains active as long as other runtime modules or pallets reference it. +Returns information about a block by its hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblockbyhash){target=\_blank}. -When all dependencies are cleared and the counters drop to zero, the account becomes deactivated and may be removed from the chain (reaped). This is particularly important in Polkadot SDK-based blockchains, where accounts with balances below the existential deposit threshold are pruned from storage to conserve state resources. +**Parameters**: -Each pallet that references an account has cleanup functions that decrement these counters when the pallet no longer depends on the account. Once these counters reach zero, the account is marked for deactivation. +- **`blockHash` ++"string"++**: The hash of the block to retrieve. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`fullTransactions` ++"boolean"++**: If `true`, returns full transaction details; if `false`, returns only transaction hashes. -#### Updating Counters +**Example**: -The Polkadot SDK provides runtime developers with various methods to manage account lifecycle events, such as deactivation or incrementing reference counters. These methods ensure that accounts cannot be reaped while still in use. +```bash title="eth_getBlockByHash" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getBlockByHash", + "params":["INSERT_BLOCK_HASH", INSERT_BOOLEAN], + "id":1 +}' +``` -The following helper functions manage these counters: +Ensure to replace the `INSERT_BLOCK_HASH` and `INSERT_BOOLEAN` with the proper values. -- **`inc_consumers()`**: Increments the `consumer` reference counter for an account, signaling that another pallet depends on it. -- **`dec_consumers()`**: Decrements the `consumer` reference counter, signaling that a pallet no longer relies on the account. -- **`inc_providers()`**: Increments the `provider` reference counter, ensuring the account remains active. -- **`dec_providers()`**: Decrements the `provider` reference counter, allowing for account deactivation when no longer in use. -- **`inc_sufficients()`**: Increments the `sufficient` reference counter for accounts that hold sufficient assets. -- **`dec_sufficients()`**: Decrements the `sufficient` reference counter. +--- -To ensure proper account cleanup and lifecycle management, a corresponding decrement should be made for each increment action. +### eth_getBlockByNumber -The `System` pallet offers three query functions to assist developers in tracking account states: +Returns information about a block by its number. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblockbynumber){target=\_blank}. -- **[`can_inc_consumer()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_inc_consumer){target=\_blank}**: Checks if the account can safely increment the consumer reference. -- **[`can_dec_provider()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_dec_provider){target=\_blank}**: Ensures that no consumers exist before allowing the decrement of the provider counter. -- **[`is_provider_required()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.is_provider_required){target=\_blank}**: Verifies whether the account still has any active consumer references. +**Parameters**: -This modular and flexible system of reference counters tightly controls the lifecycle of accounts in Polkadot SDK-based blockchains, preventing the accidental removal or retention of unneeded accounts. You can refer to the [System pallet Rust docs](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html){target=\_blank} for more details. - +- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. +- **`fullTransactions` ++"boolean"++**: If `true`, returns full transaction details; if `false`, returns only transaction hashes. -## Account Balance Types +**Example**: -In the Polkadot ecosystem, account balances are categorized into different types based on how the funds are utilized and their availability. These balance types determine the actions that can be performed, such as transferring tokens, paying transaction fees, or participating in governance activities. Understanding these balance types helps developers manage user accounts and implement balance-dependent logic. +```bash title="eth_getBlockByNumber" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getBlockByNumber", + "params":["INSERT_BLOCK_VALUE", INSERT_BOOLEAN], + "id":1 +}' +``` -!!! note "A more efficient distribution of account balance types is in development" - Soon, pallets in the Polkadot SDK will implement the [`Fungible` trait](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} (see the [tracking issue](https://github.com/paritytech/polkadot-sdk/issues/226){target=\_blank} for more details). For example, the [`transaction-storage`](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_storage/index.html){target=\_blank} pallet changed the implementation of the [`Currency`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/currency/index.html){target=\_blank} trait (see the [Refactor transaction storage pallet to use fungible traits](https://github.com/paritytech/polkadot-sdk/pull/1800){target=\_blank} PR for further details): +Ensure to replace the `INSERT_BLOCK_VALUE` and `INSERT_BOOLEAN` with the proper values. - ```rust - type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; - ``` - - To the [`Fungible`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} trait: +--- - ```rust - type BalanceOf = <::Currency as FnInspect<::AccountId>>::Balance; - ``` - - This update will enable more efficient use of account balances, allowing the free balance to be utilized for on-chain activities such as setting proxies and managing identities. +### eth_getBlockTransactionCountByNumber -### Balance Types +Returns the number of transactions in a block from a block number. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber){target=\_blank}. -The five main balance types are: +**Parameters**: -- **Free balance**: Represents the total tokens available to the account for any on-chain activity, including staking, governance, and voting. However, it may not be fully spendable or transferrable if portions of it are locked or reserved. -- **Locked balance**: Portions of the free balance that cannot be spent or transferred because they are tied up in specific activities like [staking](https://wiki.polkadot.com/learn/learn-staking/#nominating-validators){target=\_blank}, [vesting](https://wiki.polkadot.com/learn/learn-guides-transfers/#vested-transfers-with-the-polkadot-js-ui){target=\_blank}, or participating in [governance](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank}. While the tokens remain part of the free balance, they are non-transferable for the duration of the lock. -- **Reserved balance**: Funds locked by specific system actions, such as setting up an [identity](https://wiki.polkadot.com/learn/learn-identity/){target=\_blank}, creating [proxies](https://wiki.polkadot.com/learn/learn-proxies/){target=\_blank}, or submitting [deposits for governance proposals](https://wiki.polkadot.com/learn/learn-guides-polkadot-opengov/#claiming-opengov-deposits){target=\_blank}. These tokens are not part of the free balance and cannot be spent unless they are unreserved. -- **Spendable balance**: The portion of the free balance that is available for immediate spending or transfers. It is calculated by subtracting the maximum of locked or reserved amounts from the free balance, ensuring that existential deposit limits are met. -- **Untouchable balance**: Funds that cannot be directly spent or transferred but may still be utilized for on-chain activities, such as governance participation or staking. These tokens are typically tied to certain actions or locked for a specific period. +- **`blockValue` ++"string"++**: The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -The spendable balance is calculated as follows: +**Example**: -```text -spendable = free - max(locked - reserved, ED) +```bash title="eth_getBlockTransactionCountByNumber" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getBlockTransactionCountByNumber", + "params":["INSERT_BLOCK_VALUE"], + "id":1 +}' ``` -Here, `free`, `locked`, and `reserved` are defined above. The `ED` represents the [existential deposit](https://wiki.polkadot.com/learn/learn-accounts/#existential-deposit-and-reaping){target=\_blank}, the minimum balance required to keep an account active and prevent it from being reaped. You may find you can't see all balance types when looking at your account via a wallet. Wallet providers often display only spendable, locked, and reserved balances. +Ensure to replace the `INSERT_BLOCK_VALUE` with the proper values. + +--- -### Locks +### eth_getBlockTransactionCountByHash -Locks are applied to an account's free balance, preventing that portion from being spent or transferred. Locks are automatically placed when an account participates in specific on-chain activities, such as staking or governance. Although multiple locks may be applied simultaneously, they do not stack. Instead, the largest lock determines the total amount of locked tokens. +Returns the number of transactions in a block from a block hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash){target=\_blank}. -Locks follow these basic rules: +**Parameters**: -- If different locks apply to varying amounts, the largest lock amount takes precedence. -- If multiple locks apply to the same amount, the lock with the longest duration governs when the balance can be unlocked. +- **`blockHash` ++"string"++**: The hash of the block to retrieve. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -#### Locks Example +**Example**: -Consider an example where an account has 80 DOT locked for both staking and governance purposes like so: +```bash title="eth_getBlockTransactionCountByHash" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getBlockTransactionCountByHash", + "params":["INSERT_BLOCK_HASH"], + "id":1 +}' +``` -- 80 DOT is staked with a 28-day lock period. -- 24 DOT is locked for governance with a 1x conviction and a 7-day lock period. -- 4 DOT is locked for governance with a 6x conviction and a 224-day lock period. +Ensure to replace the `INSERT_BLOCK_HASH` with the proper values. -In this case, the total locked amount is 80 DOT because only the largest lock (80 DOT from staking) governs the locked balance. These 80 DOT will be released at different times based on the lock durations. In this example, the 24 DOT locked for governance will be released first since the shortest lock period is seven days. The 80 DOT stake with a 28-day lock period is released next. Now, all that remains locked is the 4 DOT for governance. After 224 days, all 80 DOT (minus the existential deposit) will be free and transferable. +--- -![Illustration of Lock Example](/images/reference/parachains/accounts/accounts-01.webp) +### eth_getCode -#### Edge Cases for Locks +Returns the code at a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getcode){target=\_blank}. -In scenarios where multiple convictions and lock periods are active, the lock duration and amount are determined by the longest period and largest amount. For example, if you delegate with different convictions and attempt to undelegate during an active lock period, the lock may be extended for the full amount of tokens. For a detailed discussion on edge case lock behavior, see this [Stack Exchange post](https://substrate.stackexchange.com/questions/5067/delegating-and-undelegating-during-the-lock-period-extends-it-for-the-initial-am){target=\_blank}. +**Parameters**: -### Balance Types on Polkadot.js +- **`address` ++"string"++**: Contract or account address to query code. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). -Polkadot.js provides a user-friendly interface for managing and visualizing various account balances on Polkadot and Kusama networks. When interacting with Polkadot.js, you will encounter multiple balance types that are critical for understanding how your funds are distributed and restricted. This section explains how different balances are displayed in the Polkadot.js UI and what each type represents. +**Example**: -![](/images/reference/parachains/accounts/accounts-02.webp) +```bash title="eth_getCode" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getCode", + "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], + "id":1 +}' +``` -The most common balance types displayed on Polkadot.js are: +Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. -- **Total balance**: The total number of tokens available in the account. This includes all tokens, whether they are transferable, locked, reserved, or vested. However, the total balance does not always reflect what can be spent immediately. In this example, the total balance is 0.6274 KSM. +--- -- **Transferable balance**: Shows how many tokens are immediately available for transfer. It is calculated by subtracting the locked and reserved balances from the total balance. For example, if an account has a total balance of 0.6274 KSM and a transferable balance of 0.0106 KSM, only the latter amount can be sent or spent freely. +### eth_getLogs -- **Vested balance**: Tokens that allocated to the account but released according to a specific schedule. Vested tokens remain locked and cannot be transferred until fully vested. For example, an account with a vested balance of 0.2500 KSM means that this amount is owned but not yet transferable. +Returns an array of all logs matching a given filter object. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getlogs){target=\_blank}. -- **Locked balance**: Tokens that are temporarily restricted from being transferred or spent. These locks typically result from participating in staking, governance, or vested transfers. In Polkadot.js, locked balances do not stack—only the largest lock is applied. For instance, if an account has 0.5500 KSM locked for governance and staking, the locked balance would display 0.5500 KSM, not the sum of all locked amounts. +**Parameters**: -- **Reserved balance**: Refers to tokens locked for specific on-chain actions, such as setting an identity, creating a proxy, or making governance deposits. Reserved tokens are not part of the free balance, but can be freed by performing certain actions. For example, removing an identity would unreserve those funds. +- **`filter` ++"object"++**: The filter object. + - **`fromBlock` ++"string"++**: (Optional) Block number or tag to start from. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. + - **`toBlock` ++"string"++**: (Optional) Block number or tag to end at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. + - **`address` ++"string" or "array of strings"++**: (Optional) Contract address or a list of addresses from which to get logs. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`topics` ++"array of strings"++**: (Optional) Array of topics for filtering logs. Each topic can be a single [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string or an array of such strings (meaning OR). + - **`blockhash` ++"string"++**: (Optional) Hash of a specific block. Cannot be used with `fromBlock` or `toBlock`. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **Bonded balance**: The tokens locked for staking purposes. Bonded tokens are not transferable until they are unbonded after the unbonding period. +**Example**: -- **Redeemable balance**: The number of tokens that have completed the unbonding period and are ready to be unlocked and transferred again. For example, if an account has a redeemable balance of 0.1000 KSM, those tokens are now available for spending. +```bash title="eth_getLogs" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getLogs", + "params":[{ + "fromBlock": "latest", + "toBlock": "latest" + }], + "id":1 +}' +``` -- **Democracy balance**: Reflects the number of tokens locked for governance activities, such as voting on referenda. These tokens are locked for the duration of the governance action and are only released after the lock period ends. +--- -By understanding these balance types and their implications, developers and users can better manage their funds and engage with on-chain activities more effectively. +### eth_getStorageAt -## Address Formats +Returns the value from a storage position at a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getstorageat){target=\_blank}. -The SS58 address format is a core component of the Polkadot SDK that enables accounts to be uniquely identified across Polkadot-based networks. This format is a modified version of Bitcoin's Base58Check encoding, specifically designed to accommodate the multi-chain nature of the Polkadot ecosystem. SS58 encoding allows each chain to define its own set of addresses while maintaining compatibility and checksum validation for security. +**Parameters**: -### Basic Format +- **`address` ++"string"++**: Contract or account address to query code. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`storageKey` ++"string"++**: Position in storage to retrieve data from. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). -SS58 addresses consist of three main components: +**Example**: -```text -base58encode(concat(,
, )) +```bash title="eth_getStorageAt" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getStorageAt", + "params":["INSERT_ADDRESS", "INSERT_STORAGE_KEY", "INSERT_BLOCK_VALUE"], + "id":1 +}' ``` -- **Address type**: A byte or set of bytes that define the network (or chain) for which the address is intended. This ensures that addresses are unique across different Polkadot SDK-based chains. -- **Address**: The public key of the account encoded as bytes. -- **Checksum**: A hash-based checksum which ensures that addresses are valid and unaltered. The checksum is derived from the concatenated address type and address components, ensuring integrity. +Ensure to replace the `INSERT_ADDRESS`, `INSERT_STORAGE_KEY`, and `INSERT_BLOCK_VALUE` with the proper values. -The encoding process transforms the concatenated components into a Base58 string, providing a compact and human-readable format that avoids easily confused characters (e.g., zero '0', capital 'O', lowercase 'l'). This encoding function ([`encode`](https://docs.rs/bs58/latest/bs58/fn.encode.html){target=\_blank}) is implemented exactly as defined in Bitcoin and IPFS specifications, using the same alphabet as both implementations. +--- -For more details about the SS58 address format implementation, see the [`Ss58Codec`](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Ss58Codec.html){target=\_blank} trait in the Rust Docs. +### eth_getTransactionCount -### Address Type +Returns the number of transactions sent from an address (nonce). [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactioncount){target=\_blank}. -The address type defines how an address is interpreted and to which network it belongs. Polkadot SDK uses different prefixes to distinguish between various chains and address formats: +**Parameters**: -- **Address types `0-63`**: Simple addresses, commonly used for network identifiers. -- **Address types `64-127`**: Full addresses that support a wider range of network identifiers. -- **Address types `128-255`**: Reserved for future address format extensions. +- **`address` ++"string"++**: Address to query balance. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). -For example, Polkadot’s main network uses an address type of 0, while Kusama uses 2. This ensures that addresses can be used without confusion between networks. +**Example**: -The address type is always encoded as part of the SS58 address, making it easy to quickly identify the network. Refer to the [SS58 registry](https://github.com/paritytech/ss58-registry){target=\_blank} for the canonical listing of all address type identifiers and how they map to Polkadot SDK-based networks. +```bash title="eth_getTransactionCount" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getTransactionCount", + "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], + "id":1 +}' +``` -### Address Length +Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. -SS58 addresses can have different lengths depending on the specific format. Address lengths range from as short as 3 to 35 bytes, depending on the complexity of the address and network requirements. This flexibility allows SS58 addresses to adapt to different chains while providing a secure encoding mechanism. +--- -| Total | Type | Raw account | Checksum | -|-------|------|-------------|----------| -| 3 | 1 | 1 | 1 | -| 4 | 1 | 2 | 1 | -| 5 | 1 | 2 | 2 | -| 6 | 1 | 4 | 1 | -| 7 | 1 | 4 | 2 | -| 8 | 1 | 4 | 3 | -| 9 | 1 | 4 | 4 | -| 10 | 1 | 8 | 1 | -| 11 | 1 | 8 | 2 | -| 12 | 1 | 8 | 3 | -| 13 | 1 | 8 | 4 | -| 14 | 1 | 8 | 5 | -| 15 | 1 | 8 | 6 | -| 16 | 1 | 8 | 7 | -| 17 | 1 | 8 | 8 | -| 35 | 1 | 32 | 2 | +### eth_getTransactionByHash -SS58 addresses also support different payload sizes, allowing a flexible range of account identifiers. +Returns information about a transaction by its hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyhash){target=\_blank}. -### Checksum Types +**Parameters**: -A checksum is applied to validate SS58 addresses. Polkadot SDK uses a Blake2b-512 hash function to calculate the checksum, which is appended to the address before encoding. The checksum length can vary depending on the address format (e.g., 1-byte, 2-byte, or longer), providing varying levels of validation strength. +- **`transactionHash` ++"string"++**: The hash of the transaction. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -The checksum ensures that an address is not modified or corrupted, adding an extra layer of security for account management. +**Example**: -### Validating Addresses +```bash title="eth_getTransactionByHash" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getTransactionByHash", + "params":["INSERT_TRANSACTION_HASH"], + "id":1 +}' +``` -SS58 addresses can be validated using the subkey command-line interface or the Polkadot.js API. These tools help ensure an address is correctly formatted and valid for the intended network. The following sections will provide an overview of how validation works with these tools. +Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper values. -#### Using Subkey +--- -[Subkey](https://paritytech.github.io/polkadot-sdk/master/subkey/index.html){target=\_blank} is a CLI tool provided by Polkadot SDK for generating and managing keys. It can inspect and validate SS58 addresses. +### eth_getTransactionByBlockNumberAndIndex -The `inspect` command gets a public key and an SS58 address from the provided secret URI. The basic syntax for the `subkey inspect` command is: +Returns information about a transaction by block number and transaction index. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyblocknumberandindex){target=\_blank}. -```bash -subkey inspect [flags] [options] uri -``` +**Parameters**: -For the `uri` command-line argument, you can specify the secret seed phrase, a hex-encoded private key, or an SS58 address. If the input is a valid address, the `subkey` program displays the corresponding hex-encoded public key, account identifier, and SS58 addresses. +- **`blockValue` ++"string"++**: The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. +- **`transactionIndex` ++"string"++**: The index of the transaction in the block. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -For example, to inspect the public keys derived from a secret seed phrase, you can run a command similar to the following: +**Example**: -```bash -subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" +```bash title="eth_getTransactionByBlockNumberAndIndex" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getTransactionByBlockNumberAndIndex", + "params":["INSERT_BLOCK_VALUE", "INSERT_TRANSACTION_INDEX"], + "id":1 +}' ``` -The command displays output similar to the following: +Ensure to replace the `INSERT_BLOCK_VALUE` and `INSERT_TRANSACTION_INDEX` with the proper values. -
- subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" - Secret phrase `caution juice atom organ advance problem want pledge someone senior holiday very` is account: - Secret seed: 0xc8fa03532fb22ee1f7f6908b9c02b4e72483f0dbd66e4cd456b8f34c6230b849 - Public key (hex): 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - Public key (SS58): 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR - Account ID: 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - SS58 Address: 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR -
+--- -The `subkey` program assumes an address is based on a public/private key pair. If you inspect an address, the command returns the 32-byte account identifier. +### eth_getTransactionByBlockHashAndIndex -However, not all addresses in Polkadot SDK-based networks are based on keys. +Returns information about a transaction by block hash and transaction index. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyblockhashandindex){target=\_blank}. -Depending on the command-line options you specify and the input you provided, the command output might also display the network for which the address has been encoded. For example: +**Parameters**: -```bash -subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" -``` +- **`blockHash` ++"string"++**: The hash of the block. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`transactionIndex` ++"string"++**: The index of the transaction in the block. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -The command displays output similar to the following: +**Example**: -
- subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" - Public Key URI `12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU` is account: - Network ID/Version: polkadot - Public key (hex): 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Account ID: 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Public key (SS58): 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU - SS58 Address: 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU -
+```bash title="eth_getTransactionByBlockHashAndIndex" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getTransactionByBlockHashAndIndex", + "params":["INSERT_BLOCK_HASH", "INSERT_TRANSACTION_INDEX"], + "id":1 +}' +``` -#### Using Polkadot.js API +Ensure to replace the `INSERT_BLOCK_HASH` and `INSERT_TRANSACTION_INDEX` with the proper values. -To verify an address in JavaScript or TypeScript projects, you can use the functions built into the [Polkadot.js API](https://polkadot.js.org/docs/){target=\_blank}. For example: +--- -```js -// Import Polkadot.js API dependencies -const { decodeAddress, encodeAddress } = require('@polkadot/keyring'); -const { hexToU8a, isHex } = require('@polkadot/util'); +### eth_getTransactionReceipt -// Specify an address to test. -const address = 'INSERT_ADDRESS_TO_TEST'; +Returns the receipt of a transaction by transaction hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionreceipt){target=\_blank}. -// Check address -const isValidSubstrateAddress = () => { - try { - encodeAddress(isHex(address) ? hexToU8a(address) : decodeAddress(address)); +**Parameters**: - return true; - } catch (error) { - return false; - } -}; +- **`transactionHash` ++"string"++**: The hash of the transaction. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -// Query result -const isValid = isValidSubstrateAddress(); -console.log(isValid); +**Example**: +```bash title="eth_getTransactionReceipt" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getTransactionReceipt", + "params":["INSERT_TRANSACTION_HASH"], + "id":1 +}' ``` -If the function returns `true`, the specified address is a valid address. +Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper values. + +--- + +### eth_maxPriorityFeePerGas + +Returns an estimate of the current priority fee per gas, in Wei, to be included in a block. -#### Other SS58 Implementations +**Parameters**: -Support for encoding and decoding Polkadot SDK SS58 addresses has been implemented in several other languages and libraries. +None. -- **Crystal**: [`wyhaines/base58.cr`](https://github.com/wyhaines/base58.cr){target=\_blank} -- **Go**: [`itering/subscan-plugin`](https://github.com/itering/subscan-plugin){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **TypeScript**: [`subsquid/squid-sdk`](https://github.com/subsquid/squid-sdk){target=\_blank} +**Example**: +```bash title="eth_maxPriorityFeePerGas" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_maxPriorityFeePerGas", + "params":[], + "id":1 +}' +``` --- -Page Title: Proof of Stake Consensus +### eth_sendRawTransaction + +Submits a raw transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_sendrawtransaction){target=\_blank}. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-pos-consensus.md -- Canonical (HTML): https://docs.polkadot.com/reference/polkadot-hub/consensus-and-security/pos-consensus/ -- Summary: Explore Polkadot's consensus protocols for secure, scalable, and decentralized network operation, including NPoS, BABE, GRANDPA, and BEEFY. +**Parameters**: -# Proof of Stake Consensus +- **`callData` ++"string"++**: Signed transaction data. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -## Introduction +**Example**: -Polkadot's Proof of Stake consensus model leverages a unique hybrid approach by design to promote decentralized and secure network operations. In traditional Proof of Stake (PoS) systems, a node's ability to validate transactions is tied to its token holdings, which can lead to centralization risks and limited validator participation. Polkadot addresses these concerns through its [Nominated Proof of Stake (NPoS)](/reference/glossary/#nominated-proof-of-stake-npos){target=\_blank} model and a combination of advanced consensus mechanisms to ensure efficient block production and strong finality guarantees. This combination enables the Polkadot network to scale while maintaining security and decentralization. +```bash title="eth_sendRawTransaction" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_sendRawTransaction", + "params":["INSERT_CALL_DATA"], + "id":1 +}' +``` -## Nominated Proof of Stake +Ensure to replace the `INSERT_CALL_DATA` with the proper values. -Polkadot uses Nominated Proof of Stake (NPoS) to select the validator set and secure the network. This model is designed to maximize decentralization and security by balancing the roles of [validators](https://wiki.polkadot.com/learn/learn-validator/){target=\_blank} and [nominators](https://wiki.polkadot.com/learn/learn-nominator/){target=\_blank}. +--- -- **Validators**: Play a key role in maintaining the network's integrity. They produce new blocks, validate parachain blocks, and ensure the finality of transactions across the relay chain. -- **Nominators**: Support the network by selecting validators to back with their stake. This mechanism allows users who don't want to run a validator node to still participate in securing the network and earn rewards based on the validators they support. +### eth_sendTransaction -In Polkadot's NPoS system, nominators can delegate their tokens to trusted validators, giving them voting power in selecting validators while spreading security responsibilities across the network. +Creates and sends a new transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_sendtransaction){target=\_blank}. -## Hybrid Consensus +**Parameters**: -Polkadot employs a hybrid consensus model that combines two key protocols: a finality gadget called [GRANDPA](#finality-gadget-grandpa) and a block production mechanism known as [BABE](#block-production-babe). This hybrid approach enables the network to benefit from both rapid block production and provable finality, ensuring security and performance. +- **`transaction` ++"object"++**: The transaction object. + - **`from` ++"string"++**: Address sending the transaction. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`to` ++"string"++**: (Optional) Recipient address. No need to provide this value when deploying a contract. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`gas` ++"string"++**: (optional, default: `90000`) gas limit for execution. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`gasPrice` ++"string"++**: (Optional) Gas price per unit. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`value` ++"string"++**: (Optional) Amount of Ether to send. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`data` ++"string"++**: (Optional) Contract bytecode or encoded method call. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`nonce` ++"string"++**: (Optional) Transaction nonce. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -The hybrid consensus model has some key advantages: +**Example**: -- **Probabilistic finality**: With BABE constantly producing new blocks, Polkadot ensures that the network continues to make progress, even when a final decision has not yet been reached on which chain is the true canonical chain. +```bash title="eth_sendTransaction" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_sendTransaction", + "params":[{ + "from": "INSERT_SENDER_ADDRESS", + "to": "INSERT_RECIPIENT_ADDRESS", + "gas": "INSERT_GAS_LIMIT", + "gasPrice": "INSERT_GAS_PRICE", + "value": "INSERT_VALUE", + "input": "INSERT_INPUT_DATA", + "nonce": "INSERT_NONCE" + }], + "id":1 +}' +``` -- **Provable finality**: GRANDPA guarantees that once a block is finalized, it can never be reverted, ensuring that all network participants agree on the finalized chain. +Ensure to replace the `INSERT_SENDER_ADDRESS`, `INSERT_RECIPIENT_ADDRESS`, `INSERT_GAS_LIMIT`, `INSERT_GAS_PRICE`, `INSERT_VALUE`, `INSERT_INPUT_DATA`, and `INSERT_NONCE` with the proper values. -By using separate protocols for block production and finality, Polkadot can achieve rapid block creation and strong guarantees of finality while avoiding the typical trade-offs seen in traditional consensus mechanisms. +--- -## Block Production - BABE +### eth_syncing -Blind Assignment for Blockchain Extension (BABE) is Polkadot's block production mechanism, working with GRANDPA to ensure blocks are produced consistently across the network. As validators participate in BABE, they are assigned block production slots through a randomness-based lottery system. This helps determine which validator is responsible for producing a block at a given time. BABE shares similarities with [Ouroboros Praos](https://eprint.iacr.org/2017/573.pdf){target=\_blank} but differs in key aspects like chain selection rules and slot timing. +Returns an object with syncing data or `false` if not syncing. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_syncing){target=\_blank}. -Key features of BABE include: +**Parameters**: -- **Epochs and slots**: BABE operates in phases called epochs, each of which is divided into slots (around 6 seconds per slot). Validators are assigned slots at the beginning of each epoch based on stake and randomness. +None. -- **Randomized block production**: Validators enter a lottery to determine which will produce a block in a specific slot. This randomness is sourced from the relay chain's [randomness cycle](/reference/parachains/randomness/){target=\_blank}. +**Example**: -- **Multiple block producers per slot**: In some cases, more than one validator might win the lottery for the same slot, resulting in multiple blocks being produced. These blocks are broadcasted, and the network's fork choice rule helps decide which chain to follow. +```bash title="eth_syncing" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_syncing", + "params":[], + "id":1 +}' +``` -- **Handling empty slots**: If no validators win the lottery for a slot, a secondary selection algorithm ensures that a block is still produced. Validators selected through this method always produce a block, ensuring no slots are skipped. +--- -BABE's combination of randomness and slot allocation creates a secure, decentralized system for consistent block production while also allowing for fork resolution when multiple validators produce blocks for the same slot. +### net_listening -### Validator Participation +Returns `true` if the client is currently listening for network connections, otherwise `false`. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#net_listening){target=\_blank}. -In BABE, validators participate in a lottery for every slot to determine whether they are responsible for producing a block during that slot. This process's randomness ensures a decentralized and unpredictable block production mechanism. +**Parameters**: -There are two lottery outcomes for any given slot that initiate additional processes: +None. -- **Multiple validators in a slot**: Due to the randomness, multiple validators can be selected to produce a block for the same slot. When this happens, each validator produces a block and broadcasts it to the network resulting in a race condition. The network's topology and latency then determine which block reaches the majority of nodes first. BABE allows both chains to continue building until the finalization process resolves which one becomes canonical. The [Fork Choice](#fork-choice) rule is then used to decide which chain the network should follow. +**Example**: -- **No validators in a slot**: On occasions when no validator is selected by the lottery, a [secondary validator selection algorithm](https://spec.polkadot.network/sect-block-production#defn-babe-secondary-slots){target=\_blank} steps in. This backup ensures that a block is still produced, preventing skipped slots. However, if the primary block produced by a verifiable random function [(VRF)-selected](/reference/parachains/randomness/#vrf){target=\_blank} validator exists for that slot, the secondary block will be ignored. As a result, every slot will have either a primary or a secondary block. +```bash title="net_listening" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"net_listening", + "params":[], + "id":1 +}' +``` -This design ensures continuous block production, even in cases of multiple competing validators or an absence of selected validators. +--- -### Additional Resources +### net_peerCount -For further technical insights about BABE, including cryptographic details and formal proofs, see the [BABE paper](https://research.web3.foundation/Polkadot/protocols/block-production/Babe){target=\_blank} from Web3 Foundation. +Returns the number of peers currently connected to the client. -For BABE technical definitions, constants, and formulas, see the [Block Production Lottery](https://spec.polkadot.network/sect-block-production#sect-block-production-lottery){target=\_blank} section of the Polkadot Protocol Specification. +**Parameters**: -## Finality Gadget - GRANDPA +None. -GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) serves as the finality gadget for Polkadot's relay chain. Operating alongside the BABE block production mechanism, it ensures provable finality, giving participants confidence that blocks finalized by GRANDPA cannot be reverted. +**Example**: -Key features of GRANDPA include: +```bash title="net_peerCount" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"net_peerCount", + "params":[], + "id":1 +}' +``` -- **Independent finality service**: GRANDPA runs separately from the block production process, operating in parallel to ensure seamless finalization. -- **Chain-based finalization**: Instead of finalizing one block at a time, GRANDPA finalizes entire chains, speeding up the process significantly. -- **Batch finalization**: Can finalize multiple blocks in a single round, enhancing efficiency and minimizing delays in the network. -- **Partial synchrony tolerance**: GRANDPA works effectively in a partially synchronous network environment, managing both asynchronous and synchronous conditions. -- **Byzantine fault tolerance**: Can handle up to 1/5 Byzantine (malicious) nodes, ensuring the system remains secure even when faced with adversarial behavior. +--- -??? note "What is GHOST?" - [GHOST (Greedy Heaviest-Observed Subtree)](https://eprint.iacr.org/2018/104.pdf){target=\blank} is a consensus protocol used in blockchain networks to select the heaviest branch in a block tree. Unlike traditional longest-chain rules, GHOST can more efficiently handle high block production rates by considering the weight of subtrees rather than just the chain length. +### net_version -### Probabilistic vs. Provable Finality +Returns the current network ID as a string. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#net_version){target=\_blank}. -In traditional Proof of Work (PoW) blockchains, finality is probabilistic. As blocks are added to the chain, the probability that a block is final increases, but it can never be guaranteed. Eventual consensus means that all nodes will agree on a single version of the blockchain over time, but this process can be unpredictable and slow. +**Parameters**: -Conversely, GRANDPA provides provable finality, which means that once a block is finalized, it is irreversible. By using Byzantine fault-tolerant agreements, GRANDPA finalizes blocks more efficiently and securely than probabilistic mechanisms like Nakamoto consensus. Like Ethereum's Casper the Friendly Finality Gadget (FFG), GRANDPA ensures that finalized blocks cannot be reverted, offering stronger consensus guarantees. +None. -### Additional Resources +**Example**: -For technical insights, including formal proofs and detailed algorithms, see the [GRANDPA paper](https://github.com/w3f/consensus/blob/master/pdf/grandpa.pdf){target=\_blank} from Web3 Foundation. +```bash title="net_version" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"net_version", + "params":[], + "id":1 +}' +``` -For a deeper look at the code behind GRANDPA, see the following GitHub repositories: +--- -- [GRANDPA Rust implementation](https://github.com/paritytech/finality-grandpa){target=\_blank} -- [GRANDPA Pallet](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/substrate/frame/grandpa/src/lib.rs){target=\_blank} +### system_health -## Fork Choice +Returns information about the health of the system. -The fork choice of the relay chain combines BABE and GRANDPA: +**Parameters**: -1. BABE must always build on the chain that GRANDPA has finalized. -2. When there are forks after the finalized head, BABE builds on the chain with the most primary blocks to provide probabilistic finality. +None. -![Fork choice diagram](/images/reference/polkadot-hub/consensus-and-security/pos-consensus/consensus-protocols-01.webp) +**Example**: -In the preceding diagram, finalized blocks are black, and non-finalized blocks are yellow. Primary blocks are labeled '1', and secondary blocks are labeled '2.' The topmost chain is the longest chain originating from the last finalized block, but it is not selected because it only has one primary block at the time of evaluation. In comparison, the one below it originates from the last finalized block and has three primary blocks. +```bash title="system_health" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"system_health", + "params":[], + "id":1 +}' +``` -### Additional Resources +--- -To learn more about how BABE and GRANDPA work together to produce and finalize blocks on Kusama, see this [Block Production and Finalization in Polkadot](https://youtu.be/FiEAnVECa8c){target=\_blank} talk from Web3 Foundation's Bill Laboon. +### web3_clientVersion -For an in-depth academic discussion about Polkadot's hybrid consensus model, see this [Block Production and Finalization in Polkadot: Understanding the BABE and GRANDPA Protocols](https://www.youtube.com/watch?v=1CuTSluL7v4&t=4s){target=\_blank} MIT Cryptoeconomic Systems 2020 talk by Web3 Foundation's Bill Laboon. +Returns the current client version. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#web3_clientversion){target=\_blank}. -## Bridging - BEEFY +**Parameters**: -Bridge Efficiency Enabling Finality Yielder (BEEFY) is a specialized protocol that extends the finality guarantees provided by GRANDPA. It is specifically designed to facilitate efficient bridging between Polkadot relay chains (such as Polkadot and Kusama) and external blockchains like Ethereum. While GRANDPA is well-suited for finalizing blocks within Polkadot, it has limitations when bridging external chains that weren't built with Polkadot's interoperability features in mind. BEEFY addresses these limitations by ensuring other networks can efficiently verify finality proofs. +None. -Key features of BEEFY include: +**Example**: -- **Efficient finality proof verification**: BEEFY enables external networks to easily verify Polkadot finality proofs, ensuring seamless communication between chains. -- **Merkle Mountain Ranges (MMR)**: This data structure is used to efficiently store and transmit proofs between chains, optimizing data storage and reducing transmission overhead. -- **ECDSA signature schemes**: BEEFY uses ECDSA signatures, which are widely supported on Ethereum and other EVM-based chains, making integration with these ecosystems smoother. -- **Light client optimization**: BEEFY reduces the computational burden on light clients by allowing them to check for a super-majority of validator votes rather than needing to process all validator signatures, improving performance. +```bash title="web3_clientVersion" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"web3_clientVersion", + "params":[], + "id":1 +}' +``` -### Additional Resources +--- -For BEEFY technical definitions, constants, and formulas, see the [Bridge design (BEEFY)](https://spec.polkadot.network/sect-finality#sect-grandpa-beefy){target=\_blank} section of the Polkadot Protocol Specification. +### debug_traceBlockByNumber +Traces a block's execution by its number and returns a detailed execution trace for each transaction. ---- +**Parameters**: -Page Title: Randomness +- **`blockValue` ++"string"++**: The block number or tag to trace. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. +- **`options` ++"object"++**: (Optional) An object containing tracer options. + - **`tracer` ++"string"++**: The name of the tracer to use (e.g., `"callTracer"`, `"opTracer"`). + - Other tracer-specific options may be supported. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-randomness.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/randomness/ -- Summary: Explore the importance of randomness in PoS blockchains, focusing on Polkadot’s VRF-based approach to ensure fairness and security in validator selection. +**Example**: -# Randomness +```bash title="debug_traceBlockByNumber" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"debug_traceBlockByNumber", + "params":["INSERT_BLOCK_VALUE", {"tracer": "callTracer"}], + "id":1 +}' +``` -## Introduction +Ensure to replace `INSERT_BLOCK_VALUE` with a proper block number if needed. -Randomness is crucial in Proof of Stake (PoS) blockchains to ensure a fair and unpredictable distribution of validator duties. However, computers are inherently deterministic, meaning the same input always produces the same output. What we typically refer to as "random" numbers on a computer are actually pseudo-random. These numbers rely on an initial "seed," which can come from external sources like [atmospheric noise](https://www.random.org/randomness/){target=\_blank}, [heart rates](https://mdpi.altmetric.com/details/47574324){target=\_blank}, or even [lava lamps](https://en.wikipedia.org/wiki/Lavarand){target=\_blank}. While this may seem random, given the same "seed," the same sequence of numbers will always be generated. +--- -In a global blockchain network, relying on real-world entropy for randomness isn’t feasible because these inputs vary by time and location. If nodes use different inputs, blockchains can fork. Hence, real-world randomness isn't suitable for use as a seed in blockchain systems. +### debug_traceTransaction -Currently, two primary methods for generating randomness in blockchains are used: [`RANDAO`](#randao) and [`VRF`](#vrf) (Verifiable Random Function). Polkadot adopts the `VRF` approach for its randomness. +Traces the execution of a single transaction by its hash and returns a detailed execution trace. -## VRF +**Parameters**: -A Verifiable Random Function (VRF) is a cryptographic function that generates a random number and proof that ensures the submitter produced the number. This proof allows anyone to verify the validity of the random number. +- **`transactionHash` ++"string"++**: The hash of the transaction to trace. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`options` ++"object"++**: (Optional) An object containing tracer options (e.g., `tracer: "callTracer"`). -Polkadot's VRF is similar to the one used in [**Ouroboros Praos**](https://eprint.iacr.org/2017/573.pdf){target=\_blank}, which secures randomness for block production in systems like [BABE](/reference/polkadot-hub/consensus-and-security/pos-consensus/#block-production-babe){target=\_blank} (Polkadot’s block production mechanism). +**Example**: -The key difference is that Polkadot's VRF doesn’t rely on a central clock—avoiding the issue of whose clock to trust. Instead, it uses its own past results and slot numbers to simulate time and determine future outcomes. +```bash title="debug_traceTransaction" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"debug_traceTransaction", + "params":["INSERT_TRANSACTION_HASH", {"tracer": "callTracer"}], + "id":1 +}' +``` -### How VRF Works +Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper value. -Slots on Polkadot are discrete units of time, each lasting six seconds, and can potentially hold a block. Multiple slots form an epoch, with 2400 slots making up one four-hour epoch. +--- -In each slot, validators execute a "die roll" using a VRF. The VRF uses three inputs: +### debug_traceCall -1. A "secret key," unique to each validator, is used for the die roll. -2. An epoch randomness value, derived from the hash of VRF outputs from blocks two epochs ago (N-2), so past randomness influences the current epoch (N). -3. The current slot number. +Executes a new message call and returns a detailed execution trace without creating a transaction on the blockchain. -This process helps maintain fair randomness across the network. +**Parameters**: -Here is a graphical representation: +- **`transaction` ++"object"++**: The transaction call object, similar to `eth_call` parameters. + - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. +- **`options` ++"object"++**: (Optional) An object containing tracer options (e.g., `tracer: "callTracer"`). -![](/images/reference/parachains/randomness/randomness-01.webp) +**Example**: -The VRF produces two outputs: a result (the random number) and a proof (verifying that the number was generated correctly). +```bash title="debug_traceCall" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"debug_traceCall", + "params":[{ + "from": "INSERT_SENDER_ADDRESS", + "to": "INSERT_RECIPIENT_ADDRESS", + "data": "INSERT_ENCODED_CALL" + }, "INSERT_BLOCK_VALUE", {"tracer": "callTracer"}], + "id":1 +}' +``` -The result is checked by the validator against a protocol threshold. If it's below the threshold, the validator becomes a candidate for block production in that slot. +Ensure to replace the `INSERT_SENDER_ADDRESS`, `INSERT_RECIPIENT_ADDRESS`, `INSERT_ENCODED_CALL`, and `INSERT_BLOCK_VALUE` with the proper value. -The validator then attempts to create a block, submitting it along with the `PROOF` and `RESULT`. +--- -So, VRF can be expressed like: +## Response Format -`(RESULT, PROOF) = VRF(SECRET, EPOCH_RANDOMNESS_VALUE, CURRENT_SLOT_NUMBER)` +All responses follow the standard JSON-RPC 2.0 format: -Put simply, performing a "VRF roll" generates a random number along with proof that the number was genuinely produced and not arbitrarily chosen. +```json +{ + "jsonrpc": "2.0", + "id": 1, + "result": ... // The return value varies by method +} +``` -After executing the VRF, the `RESULT` is compared to a protocol-defined `THRESHOLD`. If the `RESULT` is below the `THRESHOLD`, the validator becomes a valid candidate to propose a block for that slot. Otherwise, the validator skips the slot. +## Error Handling -As a result, there may be multiple validators eligible to propose a block for a slot. In this case, the block accepted by other nodes will prevail, provided it is on the chain with the latest finalized block as determined by the GRANDPA finality gadget. It's also possible for no block producers to be available for a slot, in which case the AURA consensus takes over. AURA is a fallback mechanism that randomly selects a validator to produce a block, running in parallel with BABE and only stepping in when no block producers exist for a slot. Otherwise, it remains inactive. +If an error occurs, the response will include an error object: -Because validators roll independently, no block candidates may appear in some slots if all roll numbers are above the threshold. +```json +{ + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32000, + "message": "Error message here" + } +} +``` -To verify resolution of this issue and that Polkadot block times remain near constant-time, see the [PoS Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} page of this documentation. -## RANDAO +--- -An alternative on-chain randomness method is Ethereum's RANDAO, where validators perform thousands of hashes on a seed and publish the final hash during a round. The collective input from all validators forms the random number, and as long as one honest validator participates, the randomness is secure. +Page Title: Overview of FRAME -To enhance security, RANDAO can optionally be combined with a Verifiable Delay Function (VDF), ensuring that randomness can't be predicted or manipulated during computation. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime.md +- Canonical (HTML): https://docs.polkadot.com/parachains/customize-runtime/ +- Summary: Learn how Polkadot SDK’s FRAME framework simplifies blockchain development with modular pallets and support libraries for efficient runtime design. -For more information about RANDAO, see the [Randomness - RANDAO](https://eth2book.info/capella/part2/building_blocks/randomness/){target=\_blank} section of the Upgrading Ethereum documentation. +# Customize Your Runtime -## VDFs +## Introduction -Verifiable Delay Functions (VDFs) are time-bound computations that, even on parallel computers, take a set amount of time to complete. +A blockchain runtime is more than just a fixed set of rules—it's a dynamic foundation that you can shape to match your specific needs. With Polkadot SDK's [FRAME (Framework for Runtime Aggregation of Modularized Entities)](/reference/glossary/#frame-framework-for-runtime-aggregation-of-modularized-entities){target=\_blank}, customizing your runtime is straightforward and modular. Instead of building everything from scratch, you combine pre-built pallets with your own custom logic to create a runtime suited to your blockchain's purpose. -They produce a unique result that can be quickly verified publicly. When combined with RANDAO, feeding RANDAO's output into a VDF introduces a delay that nullifies an attacker's chance to influence the randomness. +This overview explains how runtime customization works, introduces the building blocks you'll use, and guides you through the key patterns for extending your runtime. -However, VDF likely requires specialized ASIC devices to run separately from standard nodes. +## Understanding Your Runtime -!!!warning - While only one is needed to secure the system, and they will be open-source and inexpensive, running VDF devices involves significant costs without direct incentives, adding friction for blockchain users. +The runtime is the core logic of your blockchain—it processes transactions, manages state, and enforces the rules that govern your network. When a transaction arrives at your blockchain, the [`frame_executive`](https://paritytech.github.io/polkadot-sdk/master/frame_executive/index.html){target=\_blank} pallet receives it and routes it to the appropriate pallet for execution. -## Additional Resources +Think of your runtime as a collection of specialized modules, each handling a different aspect of your blockchain. Need token balances? Use the Balances pallet. Want governance? Add the Governance pallets. Need something custom? Create your own pallet. By mixing and matching these modules, you build a runtime that's efficient, secure, and tailored to your use case. -For more information about the reasoning for choices made along with proofs, see Polkadot's research on blockchain randomness and sortition in the [Block production](https://research.web3.foundation/Polkadot/protocols/block-production){target=\_blank} entry of the Polkadot Wiki. +## Runtime Architecture -For a discussion with Web3 Foundation researchers about when and under what conditions Polkadot's randomness can be utilized, see the [Discussion on Randomness used in Polkadot](https://github.com/use-ink/ink/issues/57){target=\_blank} issue on GitHub. +The following diagram shows how FRAME components work together to form your runtime: +![](/images/parachains/customize-runtime/index/frame-overview-01.webp) ---- +The main components are: -Page Title: Register a Local Asset +- **`frame_executive`**: Routes all incoming transactions to the correct pallet for execution. +- **Pallets**: Domain-specific modules that implement your blockchain's features and business logic. +- **`frame_system`**: Provides core runtime primitives and storage. +- **`frame_support`**: Utilities and macros that simplify pallet development. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-token-operations-register-local-asset.md -- Canonical (HTML): https://docs.polkadot.com/chain-interactions/token-operations/register-local-asset/ -- Summary: Comprehensive guide to registering a local asset on the Asset Hub system parachain, including step-by-step instructions. +## Building Blocks: Pallets -# Register a Local Asset on Asset Hub +[Pallets](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/pallet/index.html){target=\_blank} are the fundamental units of runtime customization. Each pallet encapsulates specific functionality and can be independently developed, tested, and integrated. -## Introduction +A pallet can implement virtually any blockchain feature you need: -As detailed in the [Asset Hub Overview](/polkadot-protocol/architecture/system-chains/asset-hub){target=\_blank} page, Asset Hub accommodates two types of assets: local and foreign. Local assets are those that were created in Asset Hub and are identifiable by an integer ID. On the other hand, foreign assets originate from a sibling parachain and are identified by a Multilocation. +- Expose new transactions that users can submit. +- Store data on-chain. +- Enforce business rules and validation logic. +- Emit events to notify users of state changes. +- Handle errors gracefully. -This guide will take you through the steps of registering a local asset on the Asset Hub parachain. +### Pre-Built Pallets vs. Custom Pallets -## Prerequisites +FRAME provides a comprehensive library of [pre-built pallets](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame){target=\_blank} for common blockchain features, including consensus, staking, balances, governance, and more. These pallets are battle-tested, optimized, and ready to use. -Before you begin, ensure you have access to the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and a funded wallet with DOT or KSM. +However, you're not limited to pre-built functionality. When pre-built pallets don't meet your needs, you can create custom pallets with entirely custom logic. The real power of FRAME is the flexibility to use pre-built modules for standard features while building your own for unique requirements. -- For Polkadot Asset Hub, you would need a deposit of 10 DOT and around 0.201 DOT for the metadata. -- For Kusama Asset Hub, the deposit is 0.1 KSM and around 0.000669 KSM for the metadata. +### Pallet Structure -You need to ensure that your Asset Hub account balance is a bit more than the sum of those two deposits, which should seamlessly account for the required deposits and transaction fees. +FRAME uses Rust macros extensively, allowing you to focus on your pallet's logic while the framework handles boilerplate and integration code. -## Steps to Register a Local Asset +A typical pallet looks like this: -To register a local asset on the Asset Hub parachain, follow these steps: +```rust +pub use pallet::*; -1. Open the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and connect to the Asset Hub parachain using the network selector in the top left corner. +#[frame_support::pallet] +pub mod pallet { + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; - - You may prefer to test local asset registration on TestNet before registering the asset on a MainNet hub. If you still need to set up a local testing environment, review the [Environment setup](#test-setup-environment) section for instructions. Once the local environment is set up, connect to the Local Node (Chopsticks) available on `ws://127.0.0.1:8000`. - - For the live network, connect to the **Asset Hub** parachain. Either Polkadot or Kusama Asset Hub can be selected from the dropdown list, choosing the desired RPC provider. + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(_); -2. Click on the **Network** tab on the top navigation bar and select **Assets** from the dropdown list. + #[pallet::config] // snip + #[pallet::event] // snip + #[pallet::error] // snip + #[pallet::storage] // snip + #[pallet::call] // snip +} +``` - ![Access to Asset Hub through Polkadot.JS](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-01.webp) +Every pallet can implement these core macros: -3. Now, you need to examine all the registered asset IDs. This step is crucial to ensure that the asset ID you are about to register is unique. Asset IDs are displayed in the **assets** column. +- **`#[frame_support::pallet]`**: Marks your module as a FRAME pallet. +- **`#[pallet::pallet]`**: Designates the struct that holds pallet metadata. +- **`#[pallet::config]`**: Defines configuration and associated types. +- **`#[pallet::event]`**: Defines events emitted by your pallet. +- **`#[pallet::error]`**: Defines error types your pallet can return. +- **`#[pallet::storage]`**: Defines on-chain storage items. +- **`#[pallet::call]`**: Defines dispatchable functions (transactions). - ![Asset IDs on Asset Hub](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-02.webp) +For a comprehensive reference, see the [`pallet_macros` documentation](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/index.html){target=\_blank}. -4. Once you have confirmed that the asset ID is unique, click on the **Create** button on the top right corner of the page. +## How Runtime Customization Works - ![Create a new asset](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-03.webp) +Customizing your runtime typically follows these patterns: -5. Fill in the required fields in the **Create Asset** form: +**Adding Pre-Built Pallets**: Select pallets from the FRAME library and integrate them into your runtime configuration. This is the fastest way to add functionality. - 1. **creator account**: The account to be used for creating this asset and setting up the initial metadata. - 2. **asset name**: The descriptive name of the asset you are registering. - 3. **asset symbol**: The symbol that will be used to represent the asset. - 4. **asset decimals**: The number of decimal places for this token, with a maximum of 20 allowed through the user interface. - 5. **minimum balance**: The minimum balance for the asset. This is specified in the units and decimals as requested. - 6. **asset ID**: The selected id for the asset. This should not match an already-existing asset id. - 7. Click on the **Next** button. - - ![Create Asset Form](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-04.webp) +**Creating Custom Pallets**: Write custom pallets for features that don't exist in the pre-built library. Custom pallets follow the same structure as pre-built ones and integrate seamlessly. -6. Choose the accounts for the roles listed below: +**Combining Multiple Pallets**: Layer multiple pallets together to create complex behaviors. Pallets can call each other and share storage when needed. - 1. **admin account**: The account designated for continuous administration of the token. - 2. **issuer account**: The account that will be used for issuing this token. - 3. **freezer account**: The account that will be used for performing token freezing operations. - 4. Click on the **Create** button. +**Configuring Pallet Parameters**: Most pallets are configurable—you can adjust their behavior through configuration traits without modifying their code. - ![Admin, Issuer, Freezer accounts](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-05.webp) +The following diagram illustrates how pallets combine to form a complete runtime: -7. Click on the **Sign and Submit** button to complete the asset registration process. +![](/images/parachains/customize-runtime/index/frame-overview-02.webp) - ![Sign and Submit](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-06.webp) +## Starting Templates -## Verify Asset Registration +The easiest way to begin customizing your runtime is with a starter template. These templates provide a pre-configured foundation so you can focus on customization rather than setup. -After completing these steps, the asset will be successfully registered. You can now view your asset listed on the [**Assets**](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fasset-hub-polkadot-rpc.dwellir.com#/assets){target=\_blank} section of the Polkadot.js Apps interface. +- **[Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank}**: The recommended choice for most developers, it includes pre-configured pallets for common features (balances, block production, governance), a complete runtime setup, and built-in parachain consensus support. This template offers the best balance of features and learning opportunities. -![Asset listed on Polkadot.js Apps](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-07.webp) +- **[Polkadot SDK Minimal Template](https://github.com/paritytech/polkadot-sdk-minimal-template){target=\_blank}**: Provides a bare-bones runtime with only essential components. Choose this if you want maximum flexibility and prefer building from a clean slate. -!!! tip - Take into consideration that the **Assets** section’s link may differ depending on the network you are using. For the local environment, enter `ws://127.0.0.1:8000` into the **Custom Endpoint** field. +- **[Polkadot SDK Solochain Template](https://github.com/paritytech/polkadot-sdk/tree/master/templates/solochain){target=\_blank}**: Designed for building standalone blockchains with moderate features, simple consensus, and several core pallets. Use this if you want a sovereign blockchain independent of a relay chain. -In this way, you have successfully registered a local asset on the Asset Hub parachain. +- **[OpenZeppelin Runtime Templates](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\_blank}**: Provides security-focused configurations following industry best practices. The [generic-template](https://github.com/OpenZeppelin/polkadot-runtime-templates/tree/main/generic-template){target=\_blank} includes curated pallet selections and production-ready defaults—ideal if security is your top priority. -For an in-depth explanation about Asset Hub and its features, see the [Asset Hub](/chain-interactions/token-operations/convert-assets/){target=\_blank} entry in the Polkadot Wiki. +## Key Customization Scenarios -## Test Setup Environment +This section covers the most common customization patterns you'll encounter: -You can set up a local parachain environment to test the asset registration process before deploying it on the live network. This guide uses Chopsticks to simulate that process. For further information on chopsticks usage, refer to the [Chopsticks](/develop/toolkit/parachains/fork-chains/chopsticks/get-started){target=\_blank} documentation. +- **[Add Existing Pallets to Your Runtime](/parachains/customize-runtime/add-existing-pallets/)**: Integrate pre-built pallets from the FRAME library with minimal configuration. -To set up a test environment, execute the following command: +- **[Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/)**: Run multiple instances of the same pallet with different configurations—useful for multi-token systems or parallel features. -```bash -npx @acala-network/chopsticks \ ---config=https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/polkadot-asset-hub.yml -``` +- **[Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/)**: Enable smart contract execution on your parachain using Contracts pallets. -The above command will spawn a lazy fork of Polkadot Asset Hub with the latest block data from the network. If you need to test Kusama Asset Hub, replace `polkadot-asset-hub.yml` with `kusama-asset-hub.yml` in the command. +- **[Create Custom Pallets](/parachains/customize-runtime/pallet-development/create-a-pallet/)**: Build entirely custom pallets for features unique to your blockchain. -An Asset Hub instance is now running locally, and you can proceed with the asset registration process. Note that the local registration process does not differ from the live network process. Once you have a successful TestNet transaction, you can use the same steps to register the asset on MainNet. +- **[Test Your Runtime](/parachains/customize-runtime/pallet-development/pallet-testing/)**: Unit test pallets and mock complete runtimes to ensure everything works correctly. --- @@ -6611,507 +3476,115 @@ This page contains a list of all relevant tutorials and guides to help you get s | Title | Difficulty | Tools | Description | |---------------------------------------------------------------------------------------------------|:-----------:|--------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------| | [Deploy an ERC-20 to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/) | 🟢 Beginner | EVM Wallet, Polkadot Remix IDE | Deploy an ERC-20 token on Polkadot Hub using PolkaVM. This guide covers contract creation, compilation, deployment, and interaction via Polkadot Remix IDE. | -| [Deploy an NFT to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) | 🟢 Beginner | EVM Wallet, Polkadot Remix IDE | Deploy an NFT on Polkadot Hub using PolkaVM and OpenZeppelin. Learn how to compile, deploy, and interact with your contract using Polkadot Remix IDE. | - -## Port Ethereum DApps - -| Title | Difficulty | Tools | Description | -|-------------------------------------------------------------------------------------|:---------------:|---------|----------------------------------------------------------------------------------------------------------------------------------| -| [Deploying Uniswap V2 on Polkadot](/smart-contracts/cookbook/eth-dapps/uniswap-v2/) | 🟡 Intermediate | Hardhat | Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. | - - ---- - -Page Title: Smart Contracts Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-overview.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/overview/ -- Summary: Learn about smart contract development capabilities in the Polkadot ecosystem, either by leveraging Polkadot Hub or other alternatives. - -# Smart Contracts on Polkadot - -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction - -Polkadot offers developers multiple approaches to building and deploying smart contracts within its ecosystem. As a multi-chain network designed for interoperability, Polkadot provides various environments optimized for different developer preferences and application requirements. From native smart contract support on Polkadot Hub to specialized parachain environments, developers can choose the platform that best suits their technical needs while benefiting from Polkadot's shared security model and cross-chain messaging capabilities. - -Whether you're looking for Ethereum compatibility through EVM-based parachains like [Moonbeam](https://docs.moonbeam.network/){target=\_blank}, [Astar](https://docs.astar.network/){target=\_blank}, and [Acala](https://evmdocs.acala.network/){target=\_blank} or prefer PolkaVM-based development with [ink!](https://use.ink/docs/v6/){target=\_blank}, the Polkadot ecosystem accommodates a range of diverse developers. - -These guides explore the diverse smart contract options available in the Polkadot ecosystem, helping developers understand the unique advantages of each approach and make informed decisions about where to deploy their decentralized applications. - -## Native Smart Contracts - -### Introduction - -Polkadot Hub enables smart contract deployment and execution through PolkaVM, a cutting-edge virtual machine designed specifically for the Polkadot ecosystem. This native integration allows developers to deploy smart contracts directly on Polkadot's system chain while maintaining compatibility with Ethereum development tools and workflows. - -### Smart Contract Development - -The smart contract platform on Polkadot Hub combines _Polkadot's robust security and scalability_ with the extensive Ethereum development ecosystem. Developers can utilize familiar Ethereum libraries for contract interactions and leverage industry-standard development environments for writing and testing smart contracts. - -Polkadot Hub provides _full Ethereum JSON-RPC API compatibility_, ensuring seamless integration with existing development tools and services. This compatibility enables developers to maintain their preferred workflows while building on Polkadot's native infrastructure. - -### Technical Architecture - -PolkaVM, the underlying virtual machine, utilizes a RISC-V-based register architecture _optimized for the Polkadot ecosystem_. This design choice offers several advantages: - -- Enhanced performance for smart contract execution. -- Improved gas efficiency for complex operations. -- Native compatibility with Polkadot's runtime environment. -- Optimized storage and state management. - -### Development Tools and Resources - -Polkadot Hub supports a comprehensive suite of development tools familiar to Ethereum developers. The platform integrates with popular development frameworks, testing environments, and deployment tools. Key features include: - -- Contract development in Solidity or Rust. -- Support for standard Ethereum development libraries. -- Integration with widely used development environments. -- Access to blockchain explorers and indexing solutions. -- Compatibility with contract monitoring and management tools. - -### Cross-Chain Capabilities - -Smart contracts deployed on Polkadot Hub can leverage Polkadot's [cross-consensus messaging (XCM) protocol](/parachains/interoperability/get-started/){target=\_blank} protocol to seamlessly _transfer tokens and call functions on other blockchain networks_ within the Polkadot ecosystem, all without complex bridging infrastructure or third-party solutions. For further references, check the [Interoperability](/develop/interoperability/){target=\_blank} section. - -### Use Cases - -Polkadot Hub's smart contract platform is suitable for a wide range of applications: - -- DeFi protocols leveraging _cross-chain capabilities_. -- NFT platforms utilizing Polkadot's native token standards. -- Governance systems integrated with Polkadot's democracy mechanisms. -- Cross-chain bridges and asset management solutions. - -## Other Smart Contract Environments - -Beyond Polkadot Hub's native PolkaVM support, the ecosystem offers two main alternatives for smart contract development: - -- **EVM-compatible parachains**: Provide access to Ethereum's extensive developer ecosystem, smart contract portability, and established tooling like Hardhat, Remix, Foundry, and OpenZeppelin. The main options include Moonbeam (the first full Ethereum-compatible parachain serving as an interoperability hub), Astar (featuring dual VM support for both EVM and WebAssembly contracts), and Acala (DeFi-focused with enhanced Acala EVM+ offering advanced DeFi primitives). - -- **Rust (ink!)**: ink! is a Rust-based framework that can compile to PolkaVM. It uses [`#[ink(...)]`](https://use.ink/docs/v6/macros-attributes/){target=\_blank} attribute macros to create Polkadot SDK-compatible PolkaVM bytecode, offering strong memory safety from Rust, an advanced type system, high-performance PolkaVM execution, and platform independence with sandboxed security. - - -Each environment provides unique advantages based on developer preferences and application requirements. - -## Where to Go Next - -Developers can use their existing Ethereum development tools and connect to Polkadot Hub's RPC endpoints. The platform's Ethereum compatibility layer ensures a smooth transition for teams already building on Ethereum-compatible chains. - -Subsequent sections of this guide provide detailed information about specific development tools, advanced features, and best practices for building on Polkadot Hub. - -
- -- Guide __Libraries__ - - --- - - Explore essential libraries to optimize smart contract development and interaction. - - [:octicons-arrow-right-24: Reference](/smart-contracts/libraries/ethers-js/) - -- Guide __Dev Environments__ - - --- - - Set up your development environment for seamless contract deployment and testing. - - [:octicons-arrow-right-24: Reference](/smart-contracts/dev-environments/local-dev-node/) - -
- - ---- - -Page Title: Technical Reference Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference.md -- Canonical (HTML): https://docs.polkadot.com/reference/ -- Summary: Learn about Polkadot's technical architecture, governance framework, parachain ecosystem, and the tools you need to build and interact with the network. - -## Introduction - -The Technical Reference section provides comprehensive documentation of Polkadot's architecture, core concepts, and development tooling. Whether you're exploring how Polkadot's relay chain coordinates parachains, understanding governance mechanisms, or building applications on the network, this reference covers the technical foundations you need. - -Polkadot is a multi-chain network that enables diverse, interconnected blockchains to share security and communicate seamlessly. Understanding how these components interact from the [relay chain](/polkadot-protocol/glossary#relay-chain){target=\_blank} that validates [parachains](/polkadot-protocol/glossary#parachain){target=\_blank} to the [governance](/reference/glossary#governance){target=\_blank} mechanisms that evolve the protocol is essential for developers, validators, and network participants. - -This guide organizes technical documentation across five core areas: Polkadot Hub, Parachains, On-Chain Governance, Glossary, and Tools, each providing detailed information on different aspects of the Polkadot ecosystem. - -## Polkadot Hub - -[Polkadot Hub](/reference/polkadot-hub/){target=\_blank} is the entry point to Polkadot for all users and application developers. It provides access to essential Web3 services, including smart contracts, staking, governance, identity management, and cross-ecosystem interoperability—without requiring you to deploy or manage a parachain. - -The Hub encompasses a set of core functionality that enables developers and users to build and interact with applications on Polkadot. Key capabilities include: - -- **Smart contracts**: Deploy Ethereum-compatible smart contracts and build decentralized applications. -- **Assets and tokens**: Create, manage, and transfer fungible tokens and NFTs across the ecosystem. -- **Staking**: Participate in network security and earn rewards by staking DOT. -- **Governance**: Vote on proposals and participate in Polkadot's decentralized decision-making through OpenGov. -- **Identity services**: Register and manage on-chain identities, enabling access to governance roles and network opportunities. -- **Cross-chain interoperability**: Leverage XCM messaging to interact securely with other chains in the Polkadot ecosystem. -- **Collectives and DAOs**: Participate in governance collectives and decentralized autonomous organizations. - -## Parachains - -[Parachains](/reference/parachains/){target=\_blank} are specialized blockchains that connect to the Polkadot relay chain, inheriting its security while maintaining their own application-specific logic. The parachains documentation covers: - -- **Accounts**: Deep dive into account types, storage, and management on parachains. -- **Blocks, transactions and fees**: Understand block production, transaction inclusion, and fee mechanisms. -- **Consensus**: Learn how parachain blocks are validated and finalized through the relay chain's consensus. -- **Chain data**: Explore data structures, storage layouts, and state management. -- **Cryptography**: Study cryptographic primitives used in Polkadot SDK-based chains. -- **Data encoding**: Understand how data is encoded and decoded for blockchain compatibility. -- **Networks**: Learn about networking protocols and peer-to-peer communication. -- **Interoperability**: Discover [Cross-Consensus Messaging (XCM)](/parachains/interoperability/get-started/){target=\_blank}, the standard for cross-chain communication. -- **Randomness**: Understand how randomness is generated and used in Polkadot chains. -- **Node and runtime**: Learn about parachain nodes, runtime environments, and the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}. - -## On-Chain Governance - -[On-Chain governance](/reference/governance/){target=\_blank} is the decentralized decision-making mechanism for the Polkadot network. It manages the evolution and modification of the network's runtime logic, enabling community oversight and approval for proposed changes. The governance documentation details: - -- **OpenGov framework**: Understand Polkadot's next-generation governance system with enhanced delegation, flexible tracks, and simultaneous referendums. -- **Origins and tracks**: Learn how governance proposals are categorized, prioritized, and executed based on their privilege level and complexity. -- **Voting and delegation**: Explore conviction voting, vote delegation, and how token holders participate in governance. -- **Governance evolution**: See how Polkadot's governance has evolved from Governance V1 to the current OpenGov system. - -## Glossary - -The [Glossary](/reference/glossary/){target=\_blank} provides quick-reference definitions for Polkadot-specific terminology. Essential terms include: - -- Blockchain concepts (blocks, transactions, state) -- Consensus mechanisms (validators, collators, finality) -- Polkadot-specific terms (relay chain, parachain, XCM, FRAME) -- Network components (nodes, runtimes, storage) -- Governance terminology (origins, tracks, referendums) - -## Tools - -The [Tools](/reference/tools/){target=\_blank} section documents essential development and interaction tools for the Polkadot ecosystem: - -- **Light clients**: Lightweight solutions for interacting with the network without running full nodes. -- **JavaScript/TypeScript tools**: Libraries like [Polkadot.js API](/reference/tools/polkadot-js-api/){target=\_blank} and [PAPI](/reference/tools/papi/){target=\_blank} for building applications. -- **Rust tools**: [Polkadart](/reference/tools/polkadart/){target=\_blank} and other Rust-based libraries for SDK development. -- **Python tools**: [py-substrate-interface](/reference/tools/py-substrate-interface/){target=\_blank} for Python developers. -- **Testing and development**: Tools like [Moonwall](/reference/tools/moonwall/){target=\_blank}, [Chopsticks](/reference/tools/chopsticks/){target=\_blank}, and [Omninode](/reference/tools/omninode/){target=\_blank} for smart contract and parachain testing. -- **Indexing and monitoring**: [Sidecar](/reference/tools/sidecar/){target=\_blank} for data indexing and [Dedot](/reference/tools/dedot/){target=\_blank} for substrate interaction. -- **Cross-chain tools**: [ParaSpell](/reference/tools/paraspell/){target=\_blank} for XCM integration and asset transfers. - -## Where to Go Next - -For detailed exploration of specific areas, proceed to any of the main sections: - -
- -- Learn **Polkadot Hub** - - --- - - Understand the relay chain's role in coordinating parachains, providing shared security, and enabling governance. - - [:octicons-arrow-right-24: Reference](/reference/polkadot-hub/) - -- Learn **Parachains** - - --- - - Deep dive into parachain architecture, consensus, data structures, and building application-specific blockchains. - - [:octicons-arrow-right-24: Reference](/reference/parachains/) - -- Learn **On-Chain Governance** - - --- - - Explore Polkadot's decentralized governance framework and how to participate in network decision-making. - - [:octicons-arrow-right-24: Reference](/reference/governance/) - -- Guide **Glossary** - - --- - - Quick reference for Polkadot-specific terminology and concepts used throughout the documentation. - - [:octicons-arrow-right-24: Reference](/reference/glossary/) - -- Guide **Tools** - - --- - - Discover development tools, libraries, and frameworks for building and interacting with Polkadot. - - [:octicons-arrow-right-24: Reference](/reference/tools/) - -
- - ---- - -Page Title: Transactions - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-transactions.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/transactions/ -- Summary: Learn how to construct, submit, and validate transactions in the Polkadot SDK, covering signed, unsigned, and inherent types of transactions. - -# Transactions - -## Introduction - -Transactions are essential components of blockchain networks, enabling state changes and the execution of key operations. In the Polkadot SDK, transactions, often called extrinsics, come in multiple forms, including signed, unsigned, and inherent transactions. - -This guide walks you through the different transaction types and how they're formatted, validated, and processed within the Polkadot ecosystem. You'll also learn how to customize transaction formats and construct transactions for FRAME-based runtimes, ensuring a complete understanding of how transactions are built and executed in Polkadot SDK-based chains. - -## What Is a Transaction? - -In the Polkadot SDK, transactions represent operations that modify the chain's state, bundled into blocks for execution. The term extrinsic is often used to refer to any data that originates outside the runtime and is included in the chain. While other blockchain systems typically refer to these operations as "transactions," the Polkadot SDK adopts the broader term "extrinsic" to capture the wide variety of data types that can be added to a block. - -There are three primary types of transactions (extrinsics) in the Polkadot SDK: - -- **Signed transactions**: Signed by the submitting account, often carrying transaction fees. -- **Unsigned transactions**: Submitted without a signature, often requiring custom validation logic. -- **Inherent transactions**: Typically inserted directly into blocks by block authoring nodes, without gossiping between peers. - -Each type serves a distinct purpose, and understanding when and how to use each is key to efficiently working with the Polkadot SDK. - -### Signed Transactions - -Signed transactions require an account's signature and typically involve submitting a request to execute a runtime call. The signature serves as a form of cryptographic proof that the sender has authorized the action, using their private key. These transactions often involve a transaction fee to cover the cost of execution and incentivize block producers. - -Signed transactions are the most common type of transaction and are integral to user-driven actions, such as token transfers. For instance, when you transfer tokens from one account to another, the sending account must sign the transaction to authorize the operation. - -For example, the [`pallet_balances::Call::transfer_allow_death`](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/pallet/struct.Pallet.html#method.transfer_allow_death){target=\_blank} extrinsic in the Balances pallet allows you to transfer tokens. Since your account initiates this transaction, your account key is used to sign it. You'll also be responsible for paying the associated transaction fee, with the option to include an additional tip to incentivize faster inclusion in the block. - -### Unsigned Transactions - -Unsigned transactions do not require a signature or account-specific data from the sender. Unlike signed transactions, they do not come with any form of economic deterrent, such as fees, which makes them susceptible to spam or replay attacks. Custom validation logic must be implemented to mitigate these risks and ensure these transactions are secure. - -Unsigned transactions typically involve scenarios where including a fee or signature is unnecessary or counterproductive. However, due to the absence of fees, they require careful validation to protect the network. For example, [`pallet_im_online::Call::heartbeat`](https://paritytech.github.io/polkadot-sdk/master/pallet_im_online/pallet/struct.Pallet.html#method.heartbeat){target=\_blank} extrinsic allows validators to send a heartbeat signal, indicating they are active. Since only validators can make this call, the logic embedded in the transaction ensures that the sender is a validator, making the need for a signature or fee redundant. - -Unsigned transactions are more resource-intensive than signed ones because custom validation is required, but they play a crucial role in certain operational scenarios, especially when regular user accounts aren't involved. - -### Inherent Transactions - -Inherent transactions are a specialized type of unsigned transaction that is used primarily for block authoring. Unlike signed or other unsigned transactions, inherent transactions are added directly by block producers and are not broadcasted to the network or stored in the transaction queue. They don't require signatures or the usual validation steps and are generally used to insert system-critical data directly into blocks. - -A key example of an inherent transaction is inserting a timestamp into each block. The [`pallet_timestamp::Call::now`](https://paritytech.github.io/polkadot-sdk/master/pallet_timestamp/pallet/struct.Pallet.html#method.now-1){target=\_blank} extrinsic allows block authors to include the current time in the block they are producing. Since the block producer adds this information, there is no need for transaction validation, like signature verification. The validation in this case is done indirectly by the validators, who check whether the timestamp is within an acceptable range before finalizing the block. - -Another example is the [`paras_inherent::Call::enter`](https://paritytech.github.io/polkadot-sdk/master/polkadot_runtime_parachains/paras_inherent/pallet/struct.Pallet.html#method.enter){target=\_blank} extrinsic, which enables parachain collator nodes to send validation data to the relay chain. This inherent transaction ensures that the necessary parachain data is included in each block without the overhead of gossiped transactions. - -Inherent transactions serve a critical role in block authoring by allowing important operational data to be added directly to the chain without needing the validation processes required for standard transactions. - -## Transaction Formats - -Understanding the structure of signed and unsigned transactions is crucial for developers building on Polkadot SDK-based chains. Whether you're optimizing transaction processing, customizing formats, or interacting with the transaction pool, knowing the format of extrinsics, Polkadot's term for transactions, is essential. - -### Types of Transaction Formats - -In Polkadot SDK-based chains, extrinsics can fall into three main categories: - -- **Unchecked extrinsics**: Typically used for signed transactions that require validation. They contain a signature and additional data, such as a nonce and information for fee calculation. Unchecked extrinsics are named as such because they require validation checks before being accepted into the transaction pool. -- **Checked extrinsics**: Typically used for inherent extrinsics (unsigned transactions); these don't require signature verification. Instead, they carry information such as where the extrinsic originates and any additional data required for the block authoring process. -- **Opaque extrinsics**: Used when the format of an extrinsic is not yet fully committed or finalized. They are still decodable, but their structure can be flexible depending on the context. - -### Signed Transaction Data Structure - -A signed transaction typically includes the following components: - -- **Signature**: Verifies the authenticity of the transaction sender. -- **Call**: The actual function or method call the transaction is requesting (for example, transferring funds). -- **Nonce**: Tracks the number of prior transactions sent from the account, helping to prevent replay attacks. -- **Tip**: An optional incentive to prioritize the transaction in block inclusion. -- **Additional data**: Includes details such as spec version, block hash, and genesis hash to ensure the transaction is valid within the correct runtime and chain context. - -Here's a simplified breakdown of how signed transactions are typically constructed in a Polkadot SDK runtime: - -``` code - + + -``` - -Each part of the signed transaction has a purpose, ensuring the transaction's authenticity and context within the blockchain. - -### Signed Extensions - -Polkadot SDK also provides the concept of [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}, which allow developers to extend extrinsics with additional data or validation logic before they are included in a block. The [`SignedExtension`](https://paritytech.github.io/try-runtime-cli/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} set helps enforce custom rules or protections, such as ensuring the transaction's validity or calculating priority. - -The transaction queue regularly calls signed extensions to verify a transaction's validity before placing it in the ready queue. This safeguard ensures transactions won't fail in a block. Signed extensions are commonly used to enforce validation logic and protect the transaction pool from spam and replay attacks. - -In FRAME, a signed extension can hold any of the following types by default: - -- **[`AccountId`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/runtime/types_common/type.AccountId.html){target=\_blank}**: To encode the sender's identity. -- **[`Call`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Call){target=\_blank}**: To encode the pallet call to be dispatched. This data is used to calculate transaction fees. -- **[`AdditionalSigned`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.AdditionalSigned){target=\_blank}**: To handle any additional data to go into the signed payload allowing you to attach any custom logic prior to dispatching a transaction. -- **[`Pre`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Pre){target=\_blank}**: To encode the information that can be passed from before a call is dispatched to after it gets dispatched. - -Signed extensions can enforce checks like: - -- **[`CheckSpecVersion`](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/extensions/check_spec_version.rs.html){target=\_blank}**: Ensures the transaction is compatible with the runtime's current version. -- **[`CheckWeight`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.CheckWeight.html){target=\_blank}**: Calculates the weight (or computational cost) of the transaction, ensuring the block doesn't exceed the maximum allowed weight. - -These extensions are critical in the transaction lifecycle, ensuring that only valid and prioritized transactions are processed. - -## Transaction Construction - -Building transactions in the Polkadot SDK involves constructing a payload that can be verified, signed, and submitted for inclusion in a block. Each runtime in the Polkadot SDK has its own rules for validating and executing transactions, but there are common patterns for constructing a signed transaction. - -### Construct a Signed Transaction - -A signed transaction in the Polkadot SDK includes various pieces of data to ensure security, prevent replay attacks, and prioritize processing. Here's an overview of how to construct one: - -1. **Construct the unsigned payload**: Gather the necessary information for the call, including: - - - **Pallet index**: Identifies the pallet where the runtime function resides. - - **Function index**: Specifies the particular function to call in the pallet. - - **Parameters**: Any additional arguments required by the function call. - -2. **Create a signing payload**: Once the unsigned payload is ready, additional data must be included: - - - **Transaction nonce**: Unique identifier to prevent replay attacks. - - **Era information**: Defines how long the transaction is valid before it's dropped from the pool. - - **Block hash**: Ensures the transaction doesn't execute on the wrong chain or fork. - -3. **Sign the payload**: Using the sender's private key, sign the payload to ensure that the transaction can only be executed by the account holder. -4. **Serialize the signed payload**: Once signed, the transaction must be serialized into a binary format, ensuring the data is compact and easy to transmit over the network. -5. **Submit the serialized transaction**: Finally, submit the serialized transaction to the network, where it will enter the transaction pool and wait for processing by an authoring node. - -The following is an example of how a signed transaction might look: - -``` rust -node_runtime::UncheckedExtrinsic::new_signed( - function.clone(), // some call - sp_runtime::AccountId32::from(sender.public()).into(), // some sending account - node_runtime::Signature::Sr25519(signature.clone()), // the account's signature - extra.clone(), // the signed extensions -) -``` - -### Transaction Encoding - -Before a transaction is sent to the network, it is serialized and encoded using a structured encoding process that ensures consistency and prevents tampering: - -- **`[1]`**: Compact encoded length in bytes of the entire transaction. -- **`[2]`**: A u8 containing 1 byte to indicate whether the transaction is signed or unsigned (1 bit) and the encoded transaction version ID (7 bits). -- **`[3]`**: If signed, this field contains an account ID, an SR25519 signature, and some extra data. -- **`[4]`**: Encoded call data, including pallet and function indices and any required arguments. - -This encoded format ensures consistency and efficiency in processing transactions across the network. By adhering to this format, applications can construct valid transactions and pass them to the network for execution. - -To learn more about how compact encoding works using SCALE, see the [SCALE Codec](https://github.com/paritytech/parity-scale-codec){target=\_blank} README on GitHub. - -### Customize Transaction Construction - -Although the basic steps for constructing transactions are consistent across Polkadot SDK-based chains, developers can customize transaction formats and validation rules. For example: +| [Deploy an NFT to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) | 🟢 Beginner | EVM Wallet, Polkadot Remix IDE | Deploy an NFT on Polkadot Hub using PolkaVM and OpenZeppelin. Learn how to compile, deploy, and interact with your contract using Polkadot Remix IDE. | -- **Custom pallets**: You can define new pallets with custom function calls, each with its own parameters and validation logic. -- **Signed extensions**: Developers can implement custom extensions that modify how transactions are prioritized, validated, or included in blocks. +## Port Ethereum DApps -By leveraging Polkadot SDK's modular design, developers can create highly specialized transaction logic tailored to their chain's needs. +| Title | Difficulty | Tools | Description | +|-------------------------------------------------------------------------------------|:---------------:|---------|----------------------------------------------------------------------------------------------------------------------------------| +| [Deploying Uniswap V2 on Polkadot](/smart-contracts/cookbook/eth-dapps/uniswap-v2/) | 🟡 Intermediate | Hardhat | Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. | -## Lifecycle of a Transaction -In the Polkadot SDK, transactions are often referred to as extrinsics because the data in transactions originates outside of the runtime. These transactions contain data that initiates changes to the chain state. The most common type of extrinsic is a signed transaction, which is cryptographically verified and typically incurs a fee. This section focuses on how signed transactions are processed, validated, and ultimately included in a block. +--- -### Define Transaction Properties +Page Title: Smart Contracts Overview -The Polkadot SDK runtime defines key transaction properties, such as: +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-overview.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/overview/ +- Summary: Learn about smart contract development capabilities in the Polkadot ecosystem, either by leveraging Polkadot Hub or other alternatives. -- **Transaction validity**: Ensures the transaction meets all runtime requirements. -- **Signed or unsigned**: Identifies whether a transaction needs to be signed by an account. -- **State changes**: Determines how the transaction modifies the state of the chain. +# Smart Contracts on Polkadot -Pallets, which compose the runtime's logic, define the specific transactions that your chain supports. When a user submits a transaction, such as a token transfer, it becomes a signed transaction, verified by the user's account signature. If the account has enough funds to cover fees, the transaction is executed, and the chain's state is updated accordingly. +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. +## Introduction -### Process on a Block Authoring Node +Polkadot offers developers multiple approaches to building and deploying smart contracts within its ecosystem. As a multi-chain network designed for interoperability, Polkadot provides various environments optimized for different developer preferences and application requirements. From native smart contract support on Polkadot Hub to specialized parachain environments, developers can choose the platform that best suits their technical needs while benefiting from Polkadot's shared security model and cross-chain messaging capabilities. -In Polkadot SDK-based networks, some nodes are authorized to author blocks. These nodes validate and process transactions. When a transaction is sent to a node that can produce blocks, it undergoes a lifecycle that involves several stages, including validation and execution. Non-authoring nodes gossip the transaction across the network until an authoring node receives it. The following diagram illustrates the lifecycle of a transaction that's submitted to a network and processed by an authoring node. +Whether you're looking for Ethereum compatibility through EVM-based parachains like [Moonbeam](https://docs.moonbeam.network/){target=\_blank}, [Astar](https://docs.astar.network/){target=\_blank}, and [Acala](https://evmdocs.acala.network/){target=\_blank} or prefer PolkaVM-based development with [ink!](https://use.ink/docs/v6/){target=\_blank}, the Polkadot ecosystem accommodates a range of diverse developers. -![Transaction lifecycle diagram](/images/reference/parachains/blocks-transactions-fees/transactions/transactions-01.webp){ style="background:white" } +These guides explore the diverse smart contract options available in the Polkadot ecosystem, helping developers understand the unique advantages of each approach and make informed decisions about where to deploy their decentralized applications. -### Validate and Queue +## Native Smart Contracts -Once a transaction reaches an authoring node, it undergoes an initial validation process to ensure it meets specific conditions defined in the runtime. This validation includes checks for: +### Introduction -- **Correct nonce**: Ensures the transaction is sequentially valid for the account. -- **Sufficient funds**: Confirms the account can cover any associated transaction fees. -- **Signature validity**: Verifies that the sender's signature matches the transaction data. +Polkadot Hub enables smart contract deployment and execution through PolkaVM, a cutting-edge virtual machine designed specifically for the Polkadot ecosystem. This native integration allows developers to deploy smart contracts directly on Polkadot's system chain while maintaining compatibility with Ethereum development tools and workflows. -After these checks, valid transactions are placed in the transaction pool, where they are queued for inclusion in a block. The transaction pool regularly re-validates queued transactions to ensure they remain valid before being processed. To reach consensus, two-thirds of the nodes must agree on the order of the transactions executed and the resulting state change. Transactions are validated and queued on the local node in a transaction pool to prepare for consensus. +### Smart Contract Development -#### Transaction Pool +The smart contract platform on Polkadot Hub combines _Polkadot's robust security and scalability_ with the extensive Ethereum development ecosystem. Developers can utilize familiar Ethereum libraries for contract interactions and leverage industry-standard development environments for writing and testing smart contracts. -The transaction pool is responsible for managing valid transactions. It ensures that only transactions that pass initial validity checks are queued. Transactions that fail validation, expire, or become invalid for other reasons are removed from the pool. +Polkadot Hub provides _full Ethereum JSON-RPC API compatibility_, ensuring seamless integration with existing development tools and services. This compatibility enables developers to maintain their preferred workflows while building on Polkadot's native infrastructure. -The transaction pool organizes transactions into two queues: +### Technical Architecture -- **Ready queue**: Transactions that are valid and ready to be included in a block. -- **Future queue**: Transactions that are not yet valid but could be in the future, such as transactions with a nonce too high for the current state. +PolkaVM, the underlying virtual machine, utilizes a RISC-V-based register architecture _optimized for the Polkadot ecosystem_. This design choice offers several advantages: -Details on how the transaction pool validates transactions, including fee and signature handling, can be found in the [`validate_transaction`](https://paritytech.github.io/polkadot-sdk/master/sp_transaction_pool/runtime_api/trait.TaggedTransactionQueue.html#method.validate_transaction){target=\_blank} method. +- Enhanced performance for smart contract execution. +- Improved gas efficiency for complex operations. +- Native compatibility with Polkadot's runtime environment. +- Optimized storage and state management. -#### Invalid Transactions +### Development Tools and Resources -If a transaction is invalid, for example, due to an invalid signature or insufficient funds, it is rejected and won't be added to the block. Invalid transactions might be rejected for reasons such as: +Polkadot Hub supports a comprehensive suite of development tools familiar to Ethereum developers. The platform integrates with popular development frameworks, testing environments, and deployment tools. Key features include: -- The transaction has already been included in a block. -- The transaction's signature does not match the sender. -- The transaction is too large to fit in the current block. +- Contract development in Solidity or Rust. +- Support for standard Ethereum development libraries. +- Integration with widely used development environments. +- Access to blockchain explorers and indexing solutions. +- Compatibility with contract monitoring and management tools. -### Transaction Ordering and Priority +### Cross-Chain Capabilities -When a node is selected as the next block author, it prioritizes transactions based on weight, length, and tip amount. The goal is to fill the block with high-priority transactions without exceeding its maximum size or computational limits. Transactions are ordered as follows: +Smart contracts deployed on Polkadot Hub can leverage Polkadot's [cross-consensus messaging (XCM) protocol](/parachains/interoperability/get-started/){target=\_blank} protocol to seamlessly _transfer tokens and call functions on other blockchain networks_ within the Polkadot ecosystem, all without complex bridging infrastructure or third-party solutions. For further references, check the [Interoperability](/develop/interoperability/){target=\_blank} section. -- **Inherents first**: Inherent transactions, such as block timestamp updates, are always placed first. -- **Nonce-based ordering**: Transactions from the same account are ordered by their nonce. -- **Fee-based ordering**: Among transactions with the same nonce or priority level, those with higher fees are prioritized. +### Use Cases -### Transaction Execution +Polkadot Hub's smart contract platform is suitable for a wide range of applications: -Once a block author selects transactions from the pool, the transactions are executed in priority order. As each transaction is processed, the state changes are written directly to the chain's storage. It's important to note that these changes are not cached, meaning a failed transaction won't revert earlier state changes, which could leave the block in an inconsistent state. +- DeFi protocols leveraging _cross-chain capabilities_. +- NFT platforms utilizing Polkadot's native token standards. +- Governance systems integrated with Polkadot's democracy mechanisms. +- Cross-chain bridges and asset management solutions. -Events are also written to storage. Runtime logic should not emit an event before performing the associated actions. If the associated transaction fails after the event was emitted, the event will not revert. +## Other Smart Contract Environments -## Transaction Mortality +Beyond Polkadot Hub's native PolkaVM support, the ecosystem offers two main alternatives for smart contract development: -Transactions in the network can be configured as either mortal (with expiration) or immortal (without expiration). Every transaction payload contains a block checkpoint (reference block number and hash) and an era/validity period that determines how many blocks after the checkpoint the transaction remains valid. +- **EVM-compatible parachains**: Provide access to Ethereum's extensive developer ecosystem, smart contract portability, and established tooling like Hardhat, Remix, Foundry, and OpenZeppelin. The main options include Moonbeam (the first full Ethereum-compatible parachain serving as an interoperability hub), Astar (featuring dual VM support for both EVM and WebAssembly contracts), and Acala (DeFi-focused with enhanced Acala EVM+ offering advanced DeFi primitives). -When a transaction is submitted, the network validates it against these parameters. If the transaction is not included in a block within the specified validity window, it is automatically removed from the transaction queue. +- **Rust (ink!)**: ink! is a Rust-based framework that can compile to PolkaVM. It uses [`#[ink(...)]`](https://use.ink/docs/v6/macros-attributes/){target=\_blank} attribute macros to create Polkadot SDK-compatible PolkaVM bytecode, offering strong memory safety from Rust, an advanced type system, high-performance PolkaVM execution, and platform independence with sandboxed security. -- **Mortal transactions**: Have a finite lifespan and will expire after a specified number of blocks. For example, a transaction with a block checkpoint of 1000 and a validity period of 64 blocks will be valid from blocks 1000 to 1064. -- **Immortal transactions**: Never expire and remain valid indefinitely. To create an immortal transaction, set the block checkpoint to 0 (genesis block), use the genesis hash as a reference, and set the validity period to 0. +Each environment provides unique advantages based on developer preferences and application requirements. -However, immortal transactions pose significant security risks through replay attacks. If an account is reaped (balance drops to zero, account removed) and later re-funded, malicious actors can replay old immortal transactions. +## Where to Go Next -The blockchain maintains only a limited number of prior block hashes for reference validation, called `BlockHashCount`. If your validity period exceeds `BlockHashCount`, the effective validity period becomes the minimum of your specified period and the block hash count. +Developers can use their existing Ethereum development tools and connect to Polkadot Hub's RPC endpoints. The platform's Ethereum compatibility layer ensures a smooth transition for teams already building on Ethereum-compatible chains. -## Unique Identifiers for Extrinsics +Subsequent sections of this guide provide detailed information about specific development tools, advanced features, and best practices for building on Polkadot Hub. -Transaction hashes are **not unique identifiers** in Polkadot SDK-based chains. +
-Key differences from traditional blockchains: +- Guide __Libraries__ -- Transaction hashes serve only as fingerprints of transaction information. -- Multiple valid transactions can share the same hash. -- Hash uniqueness assumptions lead to serious issues. + --- -For example, when an account is reaped (removed due to insufficient balance) and later recreated, it resets to nonce 0, allowing identical transactions to be valid at different points: + Explore essential libraries to optimize smart contract development and interaction. -| Block | Extrinsic Index | Hash | Origin | Nonce | Call | Result | -|-------|----------------|------|-----------|-------|---------------------|-------------------------------| -| 100 | 0 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Account A reaped | -| 150 | 5 | 0x02 | Account B | 4 | Transfer 7 DOT to A | Account A created (nonce = 0) | -| 200 | 2 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Successful transaction | + [:octicons-arrow-right-24: Reference](/smart-contracts/libraries/ethers-js/) -Notice that blocks 100 and 200 contain transactions with identical hashes (0x01) but are completely different, valid operations occurring at different times. +- Guide __Dev Environments__ -Additional complexity comes from Polkadot SDK's origin abstraction. Origins can represent collectives, governance bodies, or other non-account entities that don't maintain nonces like regular accounts and might dispatch identical calls multiple times with the same hash values. Each execution occurs in different chain states with different results. + --- -The correct way to uniquely identify an extrinsic on a Polkadot SDK-based chain is to use the block ID (height or hash) and the extrinsic index. Since the Polkadot SDK defines blocks as headers plus ordered arrays of extrinsics, the index position within a canonical block provides guaranteed uniqueness. + Set up your development environment for seamless contract deployment and testing. -## Additional Resources + [:octicons-arrow-right-24: Reference](/smart-contracts/dev-environments/local-dev-node/) -For a video overview of the lifecycle of transactions and the types of transactions that exist, see the [Transaction lifecycle](https://www.youtube.com/watch?v=3pfM0GOp02c){target=\_blank} seminar from Parity Tech. +
--- @@ -7219,436 +3692,3 @@ The system maintains precise conversion mechanisms between: - Different resource metrics within the multi-dimensional model. This ensures accurate fee calculation while maintaining compatibility with existing Ethereum tools and workflows. - - ---- - -Page Title: Transactions Weights and Fees - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-fees.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/fees/ -- Summary: Overview of transaction weights and fees in Polkadot SDK chains, detailing how fees are calculated using a defined formula and runtime specifics. - -# Transactions Weights and Fees - -## Introductions - -When transactions are executed, or data is stored on-chain, the activity changes the chain's state and consumes blockchain resources. Because the resources available to a blockchain are limited, managing how operations on-chain consume them is important. In addition to being limited in practical terms, such as storage capacity, blockchain resources represent a potential attack vector for malicious users. For example, a malicious user might attempt to overload the network with messages to stop the network from producing new blocks. To protect blockchain resources from being drained or overloaded, you need to manage how they are made available and how they are consumed. The resources to be aware of include: - -- Memory usage -- Storage input and output -- Computation -- Transaction and block size -- State database size - -The Polkadot SDK provides block authors with several ways to manage access to resources and to prevent individual components of the chain from consuming too much of any single resource. Two of the most important mechanisms available to block authors are weights and transaction fees. - -[Weights](/reference/glossary/#weight){target=\_blank} manage the time it takes to validate a block and characterize the time it takes to execute the calls in the block's body. By controlling the execution time a block can consume, weights set limits on storage input, output, and computation. - -Some of the weight allowed for a block is consumed as part of the block's initialization and finalization. The weight might also be used to execute mandatory inherent extrinsic calls. To help ensure blocks don’t consume too much execution time and prevent malicious users from overloading the system with unnecessary calls, weights are combined with transaction fees. - -[Transaction fees](/reference/parachains/blocks-transactions-fees/transactions/#transaction-fees){target=\_blank} provide an economic incentive to limit execution time, computation, and the number of calls required to perform operations. Transaction fees are also used to make the blockchain economically sustainable because they are typically applied to transactions initiated by users and deducted before a transaction request is executed. - -## How Fees are Calculated - -The final fee for a transaction is calculated using the following parameters: - -- **`base fee`**: This is the minimum amount a user pays for a transaction. It is declared a base weight in the runtime and converted to a fee using the [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} conversion. -- **`weight fee`**: A fee proportional to the execution time (input and output and computation) that a transaction consumes. -- **`length fee`**: A fee proportional to the encoded length of the transaction. -- **`tip`**: An optional tip to increase the transaction’s priority, giving it a higher chance to be included in the transaction queue. - -The base fee and proportional weight and length fees constitute the inclusion fee. The inclusion fee is the minimum fee that must be available for a transaction to be included in a block. - -```text -inclusion fee = base fee + weight fee + length fee -``` - -Transaction fees are withdrawn before the transaction is executed. After the transaction is executed, the weight can be adjusted to reflect the resources used. If a transaction uses fewer resources than expected, the transaction fee is corrected, and the adjusted transaction fee is deposited. - -## Using the Transaction Payment Pallet - -The [Transaction Payment pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/transaction-payment){target=\_blank} provides the basic logic for calculating the inclusion fee. You can also use the Transaction Payment pallet to: - -- Convert a weight value into a deductible fee based on a currency type using [`Config::WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank}. -- Update the fee for the next block by defining a multiplier based on the chain’s final state at the end of the previous block using [`Config::FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank}. -- Manage the withdrawal, refund, and deposit of transaction fees using [`Config::OnChargeTransaction`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.OnChargeTransaction){target=\_blank}. - -You can learn more about these configuration traits in the [Transaction Payment documentation](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_payment/index.html){target=\_blank}. - -### Understanding the Inclusion Fee - -The formula for calculating the inclusion fee is as follows: - -```text -inclusion_fee = base_fee + length_fee + [targeted_fee_adjustment * weight_fee] -``` - -And then, for calculating the final fee: - -```text -final_fee = inclusion_fee + tip -``` - -In the first formula, the `targeted_fee_adjustment` is a multiplier that can tune the final fee based on the network’s congestion. - -- The `base_fee` derived from the base weight covers inclusion overhead like signature verification. -- The `length_fee` is a per-byte fee that is multiplied by the length of the encoded extrinsic. -- The `weight_fee` fee is calculated using two parameters: - - The `ExtrinsicBaseWeight` that is declared in the runtime and applies to all extrinsics. - - The `#[pallet::weight]` annotation that accounts for an extrinsic's complexity. - -To convert the weight to `Currency`, the runtime must define a `WeightToFee` struct that implements a conversion function, [`Convert`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/struct.Pallet.html#method.weight_to_fee){target=\_blank}. - -Note that the extrinsic sender is charged the inclusion fee before the extrinsic is invoked. The fee is deducted from the sender's balance even if the transaction fails upon execution. - -### Accounts with an Insufficient Balance - -If an account does not have a sufficient balance to pay the inclusion fee and remain alive—that is, enough to pay the inclusion fee and maintain the minimum existential deposit—then you should ensure the transaction is canceled so that no fee is deducted and the transaction does not begin execution. - -The Polkadot SDK doesn't enforce this rollback behavior. However, this scenario would be rare because the transaction queue and block-making logic perform checks to prevent it before adding an extrinsic to a block. - -### Fee Multipliers - -The inclusion fee formula always results in the same fee for the same input. However, weight can be dynamic and—based on how [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} is defined—the final fee can include some degree of variability. -The Transaction Payment pallet provides the [`FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank} configurable parameter to account for this variability. - -The Polkadot network inspires the default update function and implements a targeted adjustment in which a target saturation level of block weight is defined. If the previous block is more saturated, the fees increase slightly. Similarly, if the last block has fewer transactions than the target, fees are decreased by a small amount. For more information about fee multiplier adjustments, see the [Web3 Research Page](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank}. - -## Transactions with Special Requirements - -Inclusion fees must be computable before execution and can only represent fixed logic. Some transactions warrant limiting resources with other strategies. For example: - -- Bonds are a type of fee that might be returned or slashed after some on-chain event. For example, you might want to require users to place a bond to participate in a vote. The bond might then be returned at the end of the referendum or slashed if the voter attempted malicious behavior. -- Deposits are fees that might be returned later. For example, you might require users to pay a deposit to execute an operation that uses storage. The user’s deposit could be returned if a subsequent operation frees up storage. -- Burn operations are used to pay for a transaction based on its internal logic. For example, a transaction might burn funds from the sender if the transaction creates new storage items to pay for the increased state size. -- Limits enable you to enforce constant or configurable limits on specific operations. For example, the default [Staking pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/staking){target=\_blank} only allows nominators to nominate 16 validators to limit the complexity of the validator election process. - -It is important to note that if you query the chain for a transaction fee, it only returns the inclusion fee. - -## Default Weight Annotations - -All dispatchable functions in the Polkadot SDK must specify a weight. The way of doing that is using the annotation-based system that lets you combine fixed values for database read/write weight and/or fixed values based on benchmarks. The most basic example would look like this: - -```rust -#[pallet::weight(100_000)] -fn my_dispatchable() { - // ... -} -``` - -Note that the [`ExtrinsicBaseWeight`](https://crates.parity.io/frame_support/weights/constants/struct.ExtrinsicBaseWeight.html){target=\_blank} is automatically added to the declared weight to account for the costs of simply including an empty extrinsic into a block. - -### Weights and Database Read/Write Operations - -To make weight annotations independent of the deployed database backend, they are defined as a constant and then used in the annotations when expressing database accesses performed by the dispatchable: - -```rust -#[pallet::weight(T::DbWeight::get().reads_writes(1, 2) + 20_000)] -fn my_dispatchable() { - // ... -} -``` - -This dispatchable allows one database to read and two to write, in addition to other things that add the additional 20,000. Database access is generally every time a value declared inside the [`#[pallet::storage]`](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/attr.storage.html){target=\_blank} block is accessed. However, unique accesses are counted because after a value is accessed, it is cached, and reaccessing it does not result in a database operation. That is: - -- Multiple reads of the exact value count as one read. -- Multiple writes of the exact value count as one write. -- Multiple reads of the same value, followed by a write to that value, count as one read and one write. -- A write followed by a read-only counts as one write. - -### Dispatch Classes - -Dispatches are broken into three classes: - -- Normal -- Operational -- Mandatory - -If a dispatch is not defined as `Operational` or `Mandatory` in the weight annotation, the dispatch is identified as `Normal` by default. You can specify that the dispatchable uses another class like this: - -```rust -#[pallet::dispatch((DispatchClass::Operational))] -fn my_dispatchable() { - // ... -} -``` - -This tuple notation also allows you to specify a final argument determining whether the user is charged based on the annotated weight. If you don't specify otherwise, `Pays::Yes` is assumed: - -```rust -#[pallet::dispatch(DispatchClass::Normal, Pays::No)] -fn my_dispatchable() { - // ... -} -``` - -#### Normal Dispatches - -Dispatches in this class represent normal user-triggered transactions. These types of dispatches only consume a portion of a block's total weight limit. For information about the maximum portion of a block that can be consumed for normal dispatches, see [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Normal dispatches are sent to the transaction pool. - -#### Operational Dispatches - -Unlike normal dispatches, which represent the usage of network capabilities, operational dispatches are those that provide network capabilities. Operational dispatches can consume the entire weight limit of a block. They are not bound by the [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Dispatches in this class are given maximum priority and are exempt from paying the [`length_fee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/){target=\_blank}. - -#### Mandatory Dispatches - -Mandatory dispatches are included in a block even if they cause the block to surpass its weight limit. You can only use the mandatory dispatch class for inherent transactions that the block author submits. This dispatch class is intended to represent functions in the block validation process. Because these dispatches are always included in a block regardless of the function weight, the validation process must prevent malicious nodes from abusing the function to craft valid but impossibly heavy blocks. You can typically accomplish this by ensuring that: - -- The operation performed is always light. -- The operation can only be included in a block once. - -To make it more difficult for malicious nodes to abuse mandatory dispatches, they cannot be included in blocks that return errors. This dispatch class serves the assumption that it is better to allow an overweight block to be created than not to allow any block to be created at all. - -### Dynamic Weights - -In addition to purely fixed weights and constants, the weight calculation can consider the input arguments of a dispatchable. The weight should be trivially computable from the input arguments with some basic arithmetic: - -```rust -use frame_support:: { - dispatch:: { - DispatchClass::Normal, - Pays::Yes, - }, - weights::Weight, -}; - -#[pallet::weight(FunctionOf( - |args: (&Vec,)| args.0.len().saturating_mul(10_000), - ) -] -fn handle_users(origin, calls: Vec) { - // Do something per user -} -``` - -## Post Dispatch Weight Correction - -Depending on the execution logic, a dispatchable function might consume less weight than was prescribed pre-dispatch. To correct weight, the function declares a different return type and returns its actual weight: - -```rust -#[pallet::weight(10_000 + 500_000_000)] -fn expensive_or_cheap(input: u64) -> DispatchResultWithPostInfo { - let was_heavy = do_calculation(input); - - if (was_heavy) { - // None means "no correction" from the weight annotation. - Ok(None.into()) - } else { - // Return the actual weight consumed. - Ok(Some(10_000).into()) - } -} -``` - -## Custom Fees - -You can also define custom fee systems through custom weight functions or inclusion fee functions. - -### Custom Weights - -Instead of using the default weight annotations, you can create a custom weight calculation type using the weights module. The custom weight calculation type must implement the following traits: - -- [`WeighData`](https://crates.parity.io/frame_support/weights/trait.WeighData.html){target=\_blank} to determine the weight of the dispatch. -- [`ClassifyDispatch`](https://crates.parity.io/frame_support/weights/trait.ClassifyDispatch.html){target=\_blank} to determine the class of the dispatch. -- [`PaysFee`](https://crates.parity.io/frame_support/weights/trait.PaysFee.html){target=\_blank} to determine whether the sender of the dispatch pays fees. - -The Polkadot SDK then bundles the output information of the three traits into the [`DispatchInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_support/dispatch/struct.DispatchInfo.html){target=\_blank} struct and provides it by implementing the [`GetDispatchInfo`](https://docs.rs/frame-support/latest/frame_support/dispatch/trait.GetDispatchInfo.html){target=\_blank} for all `Call` variants and opaque extrinsic types. This is used internally by the System and Executive modules. - -`ClassifyDispatch`, `WeighData`, and `PaysFee` are generic over T, which gets resolved into the tuple of all dispatch arguments except for the origin. The following example illustrates a struct that calculates the weight as `m * len(args)`, where `m` is a given multiplier and args is the concatenated tuple of all dispatch arguments. In this example, the dispatch class is `Operational` if the transaction has more than 100 bytes of length in arguments and will pay fees if the encoded length exceeds 10 bytes. - -```rust -struct LenWeight(u32); -impl WeighData for LenWeight { - fn weigh_data(&self, target: T) -> Weight { - let multiplier = self.0; - let encoded_len = target.encode().len() as u32; - multiplier * encoded_len - } -} - -impl ClassifyDispatch for LenWeight { - fn classify_dispatch(&self, target: T) -> DispatchClass { - let encoded_len = target.encode().len() as u32; - if encoded_len > 100 { - DispatchClass::Operational - } else { - DispatchClass::Normal - } - } -} - -impl PaysFee { - fn pays_fee(&self, target: T) -> Pays { - let encoded_len = target.encode().len() as u32; - if encoded_len > 10 { - Pays::Yes - } else { - Pays::No - } - } -} -``` - -A weight calculator function can also be coerced to the final type of the argument instead of defining it as a vague type that can be encoded. The code would roughly look like this: - -```rust -struct CustomWeight; -impl WeighData<(&u32, &u64)> for CustomWeight { - fn weigh_data(&self, target: (&u32, &u64)) -> Weight { - ... - } -} - -// given a dispatch: -#[pallet::call] -impl, I: 'static> Pallet { - #[pallet::weight(CustomWeight)] - fn foo(a: u32, b: u64) { ... } -} -``` - -In this example, the `CustomWeight` can only be used in conjunction with a dispatch with a particular signature `(u32, u64)`, as opposed to `LenWeight`, which can be used with anything because there aren't any assumptions about ``. - -#### Custom Inclusion Fee - -The following example illustrates how to customize your inclusion fee. You must configure the appropriate associated types in the respective module. - -```rust -// Assume this is the balance type -type Balance = u64; - -// Assume we want all the weights to have a `100 + 2 * w` conversion to fees -struct CustomWeightToFee; -impl WeightToFee for CustomWeightToFee { - fn convert(w: Weight) -> Balance { - let a = Balance::from(100); - let b = Balance::from(2); - let w = Balance::from(w); - a + b * w - } -} - -parameter_types! { - pub const ExtrinsicBaseWeight: Weight = 10_000_000; -} - -impl frame_system::Config for Runtime { - type ExtrinsicBaseWeight = ExtrinsicBaseWeight; -} - -parameter_types! { - pub const TransactionByteFee: Balance = 10; -} - -impl transaction_payment::Config { - type TransactionByteFee = TransactionByteFee; - type WeightToFee = CustomWeightToFee; - type FeeMultiplierUpdate = TargetedFeeAdjustment; -} - -struct TargetedFeeAdjustment(sp_std::marker::PhantomData); -impl> WeightToFee for TargetedFeeAdjustment { - fn convert(multiplier: Fixed128) -> Fixed128 { - // Don't change anything. Put any fee update info here. - multiplier - } -} -``` - -## Additional Resources - -You now know the weight system, how it affects transaction fee computation, and how to specify weights for your dispatchable calls. The next step is determining the correct weight for your dispatchable operations. You can use Substrate benchmarking functions and frame-benchmarking calls to test your functions with different parameters and empirically determine the proper weight in their worst-case scenarios. - -- [Benchmark](/parachains/customize-runtime/pallet-development/benchmark-pallet/) -- [`SignedExtension`](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} -- [Custom weights for the Example pallet](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/substrate/frame/examples/basic/src/weights.rs){target=\_blank} -- [Web3 Foundation Research](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank} - - ---- - -Page Title: XCM Tools - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-xcm-tools.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/xcm-tools/ -- Summary: Explore essential XCM tools across Polkadot, crafted to enhance cross-chain functionality and integration within the ecosystem. - -# XCM Tools - -## Introduction - -As described in the [Interoperability](/develop/interoperability){target=\_blank} section, XCM (Cross-Consensus Messaging) is a protocol used in the Polkadot and Kusama ecosystems to enable communication and interaction between chains. It facilitates cross-chain communication, allowing assets, data, and messages to flow seamlessly across the ecosystem. - -As XCM is central to enabling communication between blockchains, developers need robust tools to help interact with, build, and test XCM messages. Several XCM tools simplify working with the protocol by providing libraries, frameworks, and utilities that enhance the development process, ensuring that applications built within the Polkadot ecosystem can efficiently use cross-chain functionalities. - -## Popular XCM Tools - -### Moonsong Labs XCM Tools - -[Moonsong Labs XCM Tools](https://github.com/Moonsong-Labs/xcm-tools){target=\_blank} provides a collection of scripts for managing and testing XCM operations between Polkadot SDK-based runtimes. These tools allow performing tasks like asset registration, channel setup, and XCM initialization. Key features include: - -- **Asset registration**: Registers assets, setting units per second (up-front fees), and configuring error (revert) codes. -- **XCM initializer**: Initializes XCM, sets default XCM versions, and configures revert codes for XCM-related precompiles. -- **HRMP manipulator**: Manages HRMP channel actions, including opening, accepting, or closing channels. -- **XCM-Transactor-Info-Setter**: Configures transactor information, including extra weight and fee settings. -- **Decode XCM**: Decodes XCM messages on the relay chain or parachains to help interpret cross-chain communication. - -To get started, clone the repository and install the required dependencies: - -```bash -git clone https://github.com/Moonsong-Labs/xcm-tools && -cd xcm-tools && -yarn install -``` - -For a full overview of each script, visit the [scripts](https://github.com/Moonsong-Labs/xcm-tools/tree/main/scripts){target=\_blank} directory or refer to the [official documentation](https://github.com/Moonsong-Labs/xcm-tools/blob/main/README.md){target=\_blank} on GitHub. - -### ParaSpell - -[ParaSpell](/reference/tools/paraspell/){target=\_blank} is a collection of open-source XCM tools that streamline cross-chain asset transfers and interactions across the Polkadot and Kusama ecosystems. It provides developers with an intuitive interface to build, test, and deploy interoperable dApps, featuring message composition, decoding, and practical utilities for parachain interactions that simplify debugging and cross-chain communication optimization. - -### Astar XCM Tools - -The [Astar parachain](https://github.com/AstarNetwork/Astar/tree/master){target=\_blank} offers a crate with a set of utilities for interacting with the XCM protocol. The [xcm-tools](https://github.com/AstarNetwork/Astar/tree/master/bin/xcm-tools){target=\_blank} crate provides a straightforward method for users to locate a sovereign account or calculate an XC20 asset ID. Some commands included by the xcm-tools crate allow users to perform the following tasks: - -- **Sovereign accounts**: Obtain the sovereign account address for any parachain, either on the Relay Chain or for sibling parachains, using a simple command. -- **XC20 EVM addresses**: Generate XC20-compatible Ethereum addresses for assets by entering the asset ID, making it easy to integrate assets across Ethereum-compatible environments. -- **Remote accounts**: Retrieve remote account addresses needed for multi-location compatibility, using flexible options to specify account types and parachain IDs. - -To start using these tools, clone the [Astar repository](https://github.com/AstarNetwork/Astar){target=\_blank} and compile the xcm-tools package: - -```bash -git clone https://github.com/AstarNetwork/Astar && -cd Astar && -cargo build --release -p xcm-tools -``` - -After compiling, verify the setup with the following command: - -```bash -./target/release/xcm-tools --help -``` -For more details on using Astar xcm-tools, consult the [official documentation](https://docs.astar.network/docs/learn/interoperability/xcm/integration/tools/){target=\_blank}. - -### Chopsticks - -The Chopsticks library provides XCM functionality for testing XCM messages across networks, enabling you to fork multiple parachains along with a relay chain. For further details, see the [Chopsticks documentation](/tutorials/polkadot-sdk/testing/fork-live-chains/){target=\_blank} about XCM. - -### Moonbeam XCM SDK - -The [Moonbeam XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk){target=\_blank} enables developers to easily transfer assets between chains, either between parachains or between a parachain and the relay chain, within the Polkadot/Kusama ecosystem. With the SDK, you don't need to worry about determining the [Multilocation](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#7-universal-consensus-location-identifiers){target=\_blank} of the origin or destination assets or which extrinsics are used on which networks. - -The SDK consists of two main packages: - -- **[XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/sdk){target=\_blank}**: Core SDK for executing XCM transfers between chains in the Polkadot/Kusama ecosystem. -- **[MRL SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/mrl){target=\_blank}**: Extension of the XCM SDK for transferring liquidity into and across the Polkadot ecosystem from other ecosystems like Ethereum. - -Key features include: - -- **Simplified asset transfers**: Abstracts away complex multilocation determinations and extrinsic selection. -- **Cross-ecosystem support**: Enables transfers between Polkadot/Kusama chains and external ecosystems. -- **Developer-friendly API**: Provides intuitive interfaces for cross-chain functionality. -- **Comprehensive documentation**: Includes usage guides and API references for both packages. - -For detailed usage examples and API documentation, visit the [official Moonbeam XCM SDK documentation](https://moonbeam-foundation.github.io/xcm-sdk/latest/){target=\_blank}. diff --git a/.ai/categories/reference.md b/.ai/categories/reference.md index db1273b99..825037625 100644 --- a/.ai/categories/reference.md +++ b/.ai/categories/reference.md @@ -1,374 +1,6 @@ Begin New Bundle: Reference ---- - -Page Title: Glossary - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-glossary.md -- Canonical (HTML): https://docs.polkadot.com/reference/glossary/ -- Summary: Glossary of terms used within the Polkadot ecosystem, Polkadot SDK, its subsequent libraries, and other relevant Web3 terminology. - -# Glossary - -Key definitions, concepts, and terminology specific to the Polkadot ecosystem are included here. - -Additional glossaries from around the ecosystem you might find helpful: - -- [Polkadot Wiki Glossary](https://wiki.polkadot.com/general/glossary){target=\_blank} -- [Polkadot SDK Glossary](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/glossary/index.html){target=\_blank} - -## Authority - -The role in a blockchain that can participate in consensus mechanisms. - -- **[GRANDPA](#grandpa)**: The authorities vote on chains they consider final. -- **[Blind Assignment of Blockchain Extension](#blind-assignment-of-blockchain-extension-babe) (BABE)**: The authorities are also [block authors](#block-author). - -Authority sets can be used as a basis for consensus mechanisms such as the [Nominated Proof of Stake (NPoS)](#nominated-proof-of-stake-npos) protocol. - -## Authority Round (Aura) - -A deterministic [consensus](#consensus) protocol where block production is limited to a rotating list of [authorities](#authority) that take turns creating blocks. In authority round (Aura) consensus, most online authorities are assumed to be honest. It is often used in combination with [GRANDPA](#grandpa) as a [hybrid consensus](#hybrid-consensus) protocol. - -Learn more by reading the official [Aura consensus algorithm](https://openethereum.github.io/Aura){target=\_blank} wiki article. - -## Blind Assignment of Blockchain Extension (BABE) - -A [block authoring](#block-author) protocol similar to [Aura](#authority-round-aura), except [authorities](#authority) win [slots](#slot) based on a Verifiable Random Function (VRF) instead of the round-robin selection method. The winning authority can select a chain and submit a new block. - -Learn more by reading the official Web3 Foundation [BABE research document](https://research.web3.foundation/Polkadot/protocols/block-production/Babe){target=\_blank}. - -## Block Author - -The node responsible for the creation of a block, also called _block producers_. In a Proof of Work (PoW) blockchain, these nodes are called _miners_. - -## Byzantine Fault Tolerance (BFT) - -The ability of a distributed computer network to remain operational if a certain proportion of its nodes or [authorities](#authority) are defective or behaving maliciously. A distributed network is typically considered Byzantine fault tolerant if it can remain functional, with up to one-third of nodes assumed to be defective, offline, actively malicious, and part of a coordinated attack. - -### Byzantine Failure - -The loss of a network service due to node failures that exceed the proportion of nodes required to reach consensus. - -### Practical Byzantine Fault Tolerance (pBFT) - -An early approach to Byzantine fault tolerance (BFT), practical Byzantine fault tolerance (pBFT) systems tolerate Byzantine behavior from up to one-third of participants. - -The communication overhead for such systems is `O(n²)`, where `n` is the number of nodes (participants) in the system. - -### Preimage - -A preimage is the data that is input into a hash function to calculate a hash. Since a hash function is a [one-way function](https://en.wikipedia.org/wiki/One-way_function){target=\_blank}, the output, the hash, cannot be used to reveal the input, the preimage. - -## Call - -In the context of pallets containing functions to be dispatched to the runtime, `Call` is an enumeration data type that describes the functions that can be dispatched with one variant per pallet. A `Call` represents a [dispatch](#dispatchable) data structure object. - -## Chain Specification - -A chain specification file defines the properties required to run a node in an active or new Polkadot SDK-built network. It often contains the initial genesis runtime code, network properties (such as the network's name), the initial state for some pallets, and the boot node list. The chain specification file makes it easy to use a single Polkadot SDK codebase as the foundation for multiple independently configured chains. - -## Collator - -An [author](#block-author) of a [parachain](#parachain) network. -They aren't [authorities](#authority) in themselves, as they require a [relay chain](#relay-chain) to coordinate [consensus](#consensus). - -More details are found on the [Polkadot Collator Wiki](https://wiki.polkadot.com/learn/learn-collator/){target=\_blank}. - -## Collective - -Most often used to refer to an instance of the Collective pallet on Polkadot SDK-based networks such as [Kusama](#kusama) or [Polkadot](#polkadot) if the Collective pallet is part of the FRAME-based runtime for the network. - -## Consensus - -Consensus is the process blockchain nodes use to agree on a chain's canonical fork. It is composed of [authorship](#block-author), finality, and [fork-choice rule](#fork-choice-rulestrategy). In the Polkadot ecosystem, these three components are usually separate and the term consensus often refers specifically to authorship. - -See also [hybrid consensus](#hybrid-consensus). - -## Consensus Algorithm - -Ensures a set of [actors](#authority)—who don't necessarily trust each other—can reach an agreement about the state as the result of some computation. Most consensus algorithms assume that up to one-third of the actors or nodes can be [Byzantine fault tolerant](#byzantine-fault-tolerance-bft). - -Consensus algorithms are generally concerned with ensuring two properties: - -- **Safety**: Indicating that all honest nodes eventually agreed on the state of the chain. -- **Liveness**: Indicating the ability of the chain to keep progressing. - -## Consensus Engine - -The node subsystem responsible for consensus tasks. - -For detailed information about the consensus strategies of the [Polkadot](#polkadot) network, see the [Polkadot Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} blog series. - -See also [hybrid consensus](#hybrid-consensus). - -## Coretime - -The time allocated for utilizing a core, measured in relay chain blocks. There are two types of coretime: *on-demand* and *bulk*. - -On-demand coretime refers to coretime acquired through bidding in near real-time for the validation of a single parachain block on one of the cores reserved specifically for on-demand orders. They are available as an on-demand coretime pool. Set of cores that are available on-demand. Cores reserved through bulk coretime could also be made available in the on-demand coretime pool, in parts or in entirety. - -Bulk coretime is a fixed duration of continuous coretime represented by an NFT that can be split, shared, or resold. It is managed by the [Broker pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_broker/index.html){target=\_blank}. - -## Development Phrase - -A [mnemonic phrase](https://en.wikipedia.org/wiki/Mnemonic#For_numerical_sequences_and_mathematical_operations){target=\_blank} that is intentionally made public. - -Well-known development accounts, such as Alice, Bob, Charlie, Dave, Eve, and Ferdie, are generated from the same secret phrase: - -``` -bottom drive obey lake curtain smoke basket hold race lonely fit walk -``` - -Many tools in the Polkadot SDK ecosystem, such as [`subkey`](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/bin/utils/subkey){target=\_blank}, allow you to implicitly specify an account using a derivation path such as `//Alice`. - -## Digest - -An extensible field of the [block header](#header) that encodes information needed by several actors in a blockchain network, including: - -- [Light clients](#light-client) for chain synchronization. -- Consensus engines for block verification. -- The runtime itself, in the case of pre-runtime digests. - -## Dispatchable - -Function objects that act as the entry points in FRAME [pallets](#pallet). Internal or external entities can call them to interact with the blockchain’s state. They are a core aspect of the runtime logic, handling [transactions](#transaction) and other state-changing operations. - -## Events - -A means of recording that some particular [state](#state) transition happened. - -In the context of [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities), events are composable data types that each [pallet](#pallet) can individually define. Events in FRAME are implemented as a set of transient storage items inspected immediately after a block has been executed and reset during block initialization. - -## Executor - -A means of executing a function call in a given [runtime](#runtime) with a set of dependencies. -There are two orchestration engines in Polkadot SDK, _WebAssembly_ and _native_. - -- The _native executor_ uses a natively compiled runtime embedded in the node to execute calls. This is a performance optimization available to up-to-date nodes. - -- The _WebAssembly executor_ uses a [Wasm](#webassembly-wasm) binary and a Wasm interpreter to execute calls. The binary is guaranteed to be up-to-date regardless of the version of the blockchain node because it is persisted in the [state](#state) of the Polkadot SDK-based chain. - -## Existential Deposit - -The minimum balance an account is allowed to have in the [Balances pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/index.html){target=\_blank}. Accounts cannot be created with a balance less than the existential deposit amount. - -If an account balance drops below this amount, the Balances pallet uses [a FRAME System API](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.dec_ref){target=\_blank} to drop its references to that account. - -If the Balances pallet reference to an account is dropped, the account can be [reaped](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.allow_death){target=\_blank}. - -## Extrinsic - -A general term for data that originates outside the runtime, is included in a block, and leads to some action. This includes user-initiated transactions and inherent transactions placed into the block by the block builder. - -It is a SCALE-encoded array typically consisting of a version number, signature, and varying data types indicating the resulting runtime function to be called. Extrinsics can take two forms: [inherents](#inherent-transactions) and [transactions](#transaction). - -For more technical details, see the [Polkadot spec](https://spec.polkadot.network/id-extrinsics){target=\_blank}. - -## Fork Choice Rule/Strategy - -A fork choice rule or strategy helps determine which chain is valid when reconciling several network forks. A common fork choice rule is the [longest chain](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/struct.LongestChain.html){target=\_blank}, in which the chain with the most blocks is selected. - -## FRAME (Framework for Runtime Aggregation of Modularized Entities) - -Enables developers to create blockchain [runtime](#runtime) environments from a modular set of components called [pallets](#pallet). It utilizes a set of procedural macros to construct runtimes. - -[Visit the Polkadot SDK docs for more details on FRAME.](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank} - -## Full Node - -A node that prunes historical states, keeping only recently finalized block states to reduce storage needs. Full nodes provide current chain state access and allow direct submission and validation of [extrinsics](#extrinsic), maintaining network decentralization. - -## Genesis Configuration - -A mechanism for specifying the initial state of a blockchain. By convention, this initial state or first block is commonly referred to as the genesis state or genesis block. The genesis configuration for Polkadot SDK-based chains is accomplished by way of a [chain specification](#chain-specification) file. - -## GRANDPA - -A deterministic finality mechanism for blockchains that is implemented in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. - -The [formal specification](https://github.com/w3f/consensus/blob/master/pdf/grandpa-old.pdf){target=\_blank} is maintained by the [Web3 Foundation](https://web3.foundation/){target=\_blank}. - -## Header - -A structure that aggregates the information used to summarize a block. Primarily, it consists of cryptographic information used by [light clients](#light-client) to get minimally secure but very efficient chain synchronization. - -## Hybrid Consensus - -A blockchain consensus protocol that consists of independent or loosely coupled mechanisms for [block production](#block-author) and finality. - -Hybrid consensus allows the chain to grow as fast as probabilistic consensus protocols, such as [Aura](#authority-round-aura), while maintaining the same level of security as deterministic finality consensus protocols, such as [GRANDPA](#grandpa). - -## Inherent Transactions - -A special type of unsigned transaction, referred to as _inherents_, that enables a block authoring node to insert information that doesn't require validation directly into a block. - -Only the block-authoring node that calls the inherent transaction function can insert data into its block. In general, validators assume the data inserted using an inherent transaction is valid and reasonable even if it can't be deterministically verified. - -## JSON-RPC - -A stateless, lightweight remote procedure call protocol encoded in JavaScript Object Notation (JSON). JSON-RPC provides a standard way to call functions on a remote system by using JSON. - -For Polkadot SDK, this protocol is implemented through the [Parity JSON-RPC](https://github.com/paritytech/jsonrpc){target=\_blank} crate. - -## Keystore - -A subsystem for managing keys for the purpose of producing new blocks. - -## Kusama - -[Kusama](https://kusama.network/){target=\_blank} is a Polkadot SDK-based blockchain that implements a design similar to the [Polkadot](#polkadot) network. - -Kusama is a [canary](https://en.wiktionary.org/wiki/canary_in_a_coal_mine){target=\_blank} network and is referred to as [Polkadot's "wild cousin."](https://wiki.polkadot.com/learn/learn-comparisons-kusama/){target=\_blank}. - -As a canary network, Kusama is expected to be more stable than a test network like [Westend](#westend) but less stable than a production network like [Polkadot](#polkadot). Kusama is controlled by its network participants and is intended to be stable enough to encourage meaningful experimentation. - -## libp2p - -A peer-to-peer networking stack that allows the use of many transport mechanisms, including WebSockets (usable in a web browser). - -Polkadot SDK uses the [Rust implementation](https://github.com/libp2p/rust-libp2p){target=\_blank} of the `libp2p` networking stack. - -## Light Client - -A type of blockchain node that doesn't store the [chain state](#state) or produce blocks. - -A light client can verify cryptographic primitives and provides a [remote procedure call (RPC)](https://en.wikipedia.org/wiki/Remote_procedure_call){target=\_blank} server, enabling blockchain users to interact with the network. - -## Metadata - -Data that provides information about one or more aspects of a system. -The metadata that exposes information about a Polkadot SDK blockchain enables you to interact with that system. - -## Nominated Proof of Stake (NPoS) - -A method for determining [validators](#validator) or _[authorities](#authority)_ based on a willingness to commit their stake to the proper functioning of one or more block-producing nodes. - -## Oracle - -An entity that connects a blockchain to a non-blockchain data source. Oracles enable the blockchain to access and act upon information from existing data sources and incorporate data from non-blockchain systems and services. - -## Origin - -A [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitive that identifies the source of a [dispatched](#dispatchable) function call into the [runtime](#runtime). The FRAME System pallet defines three built-in [origins](#origin). As a [pallet](#pallet) developer, you can also define custom origins, such as those defined by the [Collective pallet](https://paritytech.github.io/substrate/master/pallet_collective/enum.RawOrigin.html){target=\_blank}. - -## Pallet - -A module that can be used to extend the capabilities of a [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities)-based [runtime](#runtime). -Pallets bundle domain-specific logic with runtime primitives like [events](#events) and [storage items](#storage-item). - -## Parachain - -A parachain is a blockchain that derives shared infrastructure and security from a _[relay chain](#relay-chain)_. -You can learn more about parachains on the [Polkadot Wiki](https://wiki.polkadot.com/learn/learn-parachains/){target=\_blank}. - -## Paseo - -Paseo TestNet provisions testing on Polkadot's "production" runtime, which means less chance of feature or code mismatch when developing parachain apps. Specifically, after the [Polkadot Technical fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} proposes a runtime upgrade for Polkadot, this TestNet is updated, giving a period where the TestNet will be ahead of Polkadot to allow for testing. - -## Polkadot - -The [Polkadot network](https://polkadot.com/){target=\_blank} is a blockchain that serves as the central hub of a heterogeneous blockchain network. It serves the role of the [relay chain](#relay-chain) and provides shared infrastructure and security to support [parachains](#parachain). - -## Polkadot Cloud - -Polkadot Cloud is a platform for deploying resilient, customizable and scalable Web3 applications through Polkadot's functionality. It encompasses the wider Polkadot network infrastructure and security layer where parachains operate. The platform enables users to launch Ethereum-compatible chains, build specialized blockchains, and flexibly manage computing resources through on-demand or bulk coretime purchases. Initially launched with basic parachain functionality, Polkadot Cloud has evolved to offer enhanced flexibility with features like coretime, elastic scaling, and async backing for improved performance. - -## Polkadot Hub - -Polkadot Hub is a Layer 1 platform that serves as the primary entry point to the Polkadot ecosystem, providing essential functionality without requiring parachain deployment. It offers core services including smart contracts, identity management, staking, governance, and interoperability with other ecosystems, making it simple and fast for both builders and users to get started in Web3. - -## PolkaVM - -PolkaVM is a custom virtual machine optimized for performance, leveraging a RISC-V-based architecture to support Solidity and any language that compiles to RISC-V. It is specifically designed for the Polkadot ecosystem, enabling smart contract deployment and execution. - -## Relay Chain - -Relay chains are blockchains that provide shared infrastructure and security to the [parachains](#parachain) in the network. In addition to providing [consensus](#consensus) capabilities, relay chains allow parachains to communicate and exchange digital assets without needing to trust one another. - -## Rococo - -A [parachain](#parachain) test network for the Polkadot network. The [Rococo](#rococo) network is a Polkadot SDK-based blockchain with an October 14, 2024 deprecation date. Development teams are encouraged to use the Paseo TestNet instead. - -## Runtime - -The runtime represents the [state transition function](#state-transition-function-stf) for a blockchain. In Polkadot SDK, the runtime is stored as a [Wasm](#webassembly-wasm) binary in the chain state. The Runtime is stored under a unique state key and can be modified during the execution of the state transition function. - -## Slot - -A fixed, equal interval of time used by consensus engines such as [Aura](#authority-round-aura) and [BABE](#blind-assignment-of-blockchain-extension-babe). In each slot, a subset of [authorities](#authority) is permitted, or obliged, to [author](#block-author) a block. - -## Sovereign Account - -The unique account identifier for each chain in the relay chain ecosystem. It is often used in cross-consensus (XCM) interactions to sign XCM messages sent to the relay chain or other chains in the ecosystem. - -The sovereign account for each chain is a root-level account that can only be accessed using the Sudo pallet or through governance. The account identifier is calculated by concatenating the Blake2 hash of a specific text string and the registered parachain identifier. - -## SS58 Address Format - -A public key address based on the Bitcoin [`Base-58-check`](https://en.bitcoin.it/wiki/Base58Check_encoding){target=\_blank} encoding. Each Polkadot SDK SS58 address uses a `base-58` encoded value to identify a specific account on a specific Polkadot SDK-based chain - -The [canonical `ss58-registry`](https://github.com/paritytech/ss58-registry){target=\_blank} provides additional details about the address format used by different Polkadot SDK-based chains, including the network prefix and website used for different networks - -## State Transition Function (STF) - -The logic of a blockchain that determines how the state changes when a block is processed. In Polkadot SDK, the state transition function is effectively equivalent to the [runtime](#runtime). - -## Storage Item - -[FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitives that provide type-safe data persistence capabilities to the [runtime](#runtime). -Learn more in the [storage items](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/index.html){target=\_blank} reference document in the Polkadot SDK. - -## Substrate - -A flexible framework for building modular, efficient, and upgradeable blockchains. Substrate is written in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language and is maintained by [Parity Technologies](https://www.parity.io/){target=\_blank}. - -## Transaction - -An [extrinsic](#extrinsic) that includes a signature that can be used to verify the account authorizing it inherently or via [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}. - -## Transaction Era - -A definable period expressed as a range of block numbers during which a transaction can be included in a block. -Transaction eras are used to protect against transaction replay attacks if an account is reaped and its replay-protecting nonce is reset to zero. - -## Trie (Patricia Merkle Tree) - -A data structure used to represent sets of key-value pairs and enables the items in the data set to be stored and retrieved using a cryptographic hash. Because incremental changes to the data set result in a new hash, retrieving data is efficient even if the data set is very large. With this data structure, you can also prove whether the data set includes any particular key-value pair without access to the entire data set. - -In Polkadot SDK-based blockchains, state is stored in a trie data structure that supports the efficient creation of incremental digests. This trie is exposed to the [runtime](#runtime) as [a simple key/value map](#storage-item) where both keys and values can be arbitrary byte arrays. - -## Validator - -A validator is a node that participates in the consensus mechanism of the network. Its roles include block production, transaction validation, network integrity, and security maintenance. - -## WebAssembly (Wasm) - -An execution architecture that allows for the efficient, platform-neutral expression of -deterministic, machine-executable logic. - -[Wasm](https://webassembly.org/){target=\_blank} can be compiled from many languages, including -the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. Polkadot SDK-based chains use a Wasm binary to provide portable [runtimes](#runtime) that can be included as part of the chain's state. - -## Weight - -A convention used in Polkadot SDK-based blockchains to measure and manage the time it takes to validate a block. -Polkadot SDK defines one unit of weight as one picosecond of execution time on reference hardware. - -The maximum block weight should be equivalent to one-third of the target block time with an allocation of one-third each for: - -- Block construction -- Network propagation -- Import and verification - -By defining weights, you can trade-off the number of transactions per second and the hardware required to maintain the target block time appropriate for your use case. Weights are defined in the runtime, meaning you can tune them using runtime updates to keep up with hardware and software improvements. - -## Westend - -Westend is a Parity-maintained, Polkadot SDK-based blockchain that serves as a test network for the [Polkadot](#polkadot) network. - - --- Page Title: JSON-RPC APIs @@ -1238,128 +870,3 @@ If an error occurs, the response will include an error object: } } ``` - - ---- - -Page Title: Technical Reference Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference.md -- Canonical (HTML): https://docs.polkadot.com/reference/ -- Summary: Learn about Polkadot's technical architecture, governance framework, parachain ecosystem, and the tools you need to build and interact with the network. - -## Introduction - -The Technical Reference section provides comprehensive documentation of Polkadot's architecture, core concepts, and development tooling. Whether you're exploring how Polkadot's relay chain coordinates parachains, understanding governance mechanisms, or building applications on the network, this reference covers the technical foundations you need. - -Polkadot is a multi-chain network that enables diverse, interconnected blockchains to share security and communicate seamlessly. Understanding how these components interact from the [relay chain](/polkadot-protocol/glossary#relay-chain){target=\_blank} that validates [parachains](/polkadot-protocol/glossary#parachain){target=\_blank} to the [governance](/reference/glossary#governance){target=\_blank} mechanisms that evolve the protocol is essential for developers, validators, and network participants. - -This guide organizes technical documentation across five core areas: Polkadot Hub, Parachains, On-Chain Governance, Glossary, and Tools, each providing detailed information on different aspects of the Polkadot ecosystem. - -## Polkadot Hub - -[Polkadot Hub](/reference/polkadot-hub/){target=\_blank} is the entry point to Polkadot for all users and application developers. It provides access to essential Web3 services, including smart contracts, staking, governance, identity management, and cross-ecosystem interoperability—without requiring you to deploy or manage a parachain. - -The Hub encompasses a set of core functionality that enables developers and users to build and interact with applications on Polkadot. Key capabilities include: - -- **Smart contracts**: Deploy Ethereum-compatible smart contracts and build decentralized applications. -- **Assets and tokens**: Create, manage, and transfer fungible tokens and NFTs across the ecosystem. -- **Staking**: Participate in network security and earn rewards by staking DOT. -- **Governance**: Vote on proposals and participate in Polkadot's decentralized decision-making through OpenGov. -- **Identity services**: Register and manage on-chain identities, enabling access to governance roles and network opportunities. -- **Cross-chain interoperability**: Leverage XCM messaging to interact securely with other chains in the Polkadot ecosystem. -- **Collectives and DAOs**: Participate in governance collectives and decentralized autonomous organizations. - -## Parachains - -[Parachains](/reference/parachains/){target=\_blank} are specialized blockchains that connect to the Polkadot relay chain, inheriting its security while maintaining their own application-specific logic. The parachains documentation covers: - -- **Accounts**: Deep dive into account types, storage, and management on parachains. -- **Blocks, transactions and fees**: Understand block production, transaction inclusion, and fee mechanisms. -- **Consensus**: Learn how parachain blocks are validated and finalized through the relay chain's consensus. -- **Chain data**: Explore data structures, storage layouts, and state management. -- **Cryptography**: Study cryptographic primitives used in Polkadot SDK-based chains. -- **Data encoding**: Understand how data is encoded and decoded for blockchain compatibility. -- **Networks**: Learn about networking protocols and peer-to-peer communication. -- **Interoperability**: Discover [Cross-Consensus Messaging (XCM)](/parachains/interoperability/get-started/){target=\_blank}, the standard for cross-chain communication. -- **Randomness**: Understand how randomness is generated and used in Polkadot chains. -- **Node and runtime**: Learn about parachain nodes, runtime environments, and the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}. - -## On-Chain Governance - -[On-Chain governance](/reference/governance/){target=\_blank} is the decentralized decision-making mechanism for the Polkadot network. It manages the evolution and modification of the network's runtime logic, enabling community oversight and approval for proposed changes. The governance documentation details: - -- **OpenGov framework**: Understand Polkadot's next-generation governance system with enhanced delegation, flexible tracks, and simultaneous referendums. -- **Origins and tracks**: Learn how governance proposals are categorized, prioritized, and executed based on their privilege level and complexity. -- **Voting and delegation**: Explore conviction voting, vote delegation, and how token holders participate in governance. -- **Governance evolution**: See how Polkadot's governance has evolved from Governance V1 to the current OpenGov system. - -## Glossary - -The [Glossary](/reference/glossary/){target=\_blank} provides quick-reference definitions for Polkadot-specific terminology. Essential terms include: - -- Blockchain concepts (blocks, transactions, state) -- Consensus mechanisms (validators, collators, finality) -- Polkadot-specific terms (relay chain, parachain, XCM, FRAME) -- Network components (nodes, runtimes, storage) -- Governance terminology (origins, tracks, referendums) - -## Tools - -The [Tools](/reference/tools/){target=\_blank} section documents essential development and interaction tools for the Polkadot ecosystem: - -- **Light clients**: Lightweight solutions for interacting with the network without running full nodes. -- **JavaScript/TypeScript tools**: Libraries like [Polkadot.js API](/reference/tools/polkadot-js-api/){target=\_blank} and [PAPI](/reference/tools/papi/){target=\_blank} for building applications. -- **Rust tools**: [Polkadart](/reference/tools/polkadart/){target=\_blank} and other Rust-based libraries for SDK development. -- **Python tools**: [py-substrate-interface](/reference/tools/py-substrate-interface/){target=\_blank} for Python developers. -- **Testing and development**: Tools like [Moonwall](/reference/tools/moonwall/){target=\_blank}, [Chopsticks](/reference/tools/chopsticks/){target=\_blank}, and [Omninode](/reference/tools/omninode/){target=\_blank} for smart contract and parachain testing. -- **Indexing and monitoring**: [Sidecar](/reference/tools/sidecar/){target=\_blank} for data indexing and [Dedot](/reference/tools/dedot/){target=\_blank} for substrate interaction. -- **Cross-chain tools**: [ParaSpell](/reference/tools/paraspell/){target=\_blank} for XCM integration and asset transfers. - -## Where to Go Next - -For detailed exploration of specific areas, proceed to any of the main sections: - -
- -- Learn **Polkadot Hub** - - --- - - Understand the relay chain's role in coordinating parachains, providing shared security, and enabling governance. - - [:octicons-arrow-right-24: Reference](/reference/polkadot-hub/) - -- Learn **Parachains** - - --- - - Deep dive into parachain architecture, consensus, data structures, and building application-specific blockchains. - - [:octicons-arrow-right-24: Reference](/reference/parachains/) - -- Learn **On-Chain Governance** - - --- - - Explore Polkadot's decentralized governance framework and how to participate in network decision-making. - - [:octicons-arrow-right-24: Reference](/reference/governance/) - -- Guide **Glossary** - - --- - - Quick reference for Polkadot-specific terminology and concepts used throughout the documentation. - - [:octicons-arrow-right-24: Reference](/reference/glossary/) - -- Guide **Tools** - - --- - - Discover development tools, libraries, and frameworks for building and interacting with Polkadot. - - [:octicons-arrow-right-24: Reference](/reference/tools/) - -
diff --git a/.ai/categories/smart-contracts.md b/.ai/categories/smart-contracts.md index 51b361f54..b5f0bfcb7 100644 --- a/.ai/categories/smart-contracts.md +++ b/.ai/categories/smart-contracts.md @@ -516,440 +516,6 @@ BlockScout is an open-source explorer platform with a user-friendly interface ad ![](/images/smart-contracts/explorers/block-explorers-2.webp) ---- - -Page Title: Blocks - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-blocks.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/blocks/ -- Summary: Understand how blocks are produced, validated, and imported in Polkadot SDK-based blockchains, covering initialization, finalization, and authoring processes. - -# Blocks - -## Introduction - -In the Polkadot SDK, blocks are fundamental to the functioning of the blockchain, serving as containers for [transactions](/reference/parachains/blocks-transactions-fees/transactions/){target=\_blank} and changes to the chain's state. Blocks consist of headers and an array of transactions, ensuring the integrity and validity of operations on the network. This guide explores the essential components of a block, the process of block production, and how blocks are validated and imported across the network. By understanding these concepts, developers can better grasp how blockchains maintain security, consistency, and performance within the Polkadot ecosystem. - -## What is a Block? - -In the Polkadot SDK, a block is a fundamental unit that encapsulates both the header and an array of transactions. The block header includes critical metadata to ensure the integrity and sequence of the blockchain. Here's a breakdown of its components: - -- **Block height**: Indicates the number of blocks created in the chain so far. -- **Parent hash**: The hash of the previous block, providing a link to maintain the blockchain's immutability. -- **Transaction root**: Cryptographic digest summarizing all transactions in the block. -- **State root**: A cryptographic digest representing the post-execution state. -- **Digest**: Additional information that can be attached to a block, such as consensus-related messages. - -Each transaction is part of a series that is executed according to the runtime's rules. The transaction root is a cryptographic digest of this series, which prevents alterations and enables succinct verification by light clients. This verification process allows light clients to confirm whether a transaction exists in a block with only the block header, avoiding downloading the entire block. - -## Block Production - -When an authoring node is authorized to create a new block, it selects transactions from the transaction queue based on priority. This step, known as block production, relies heavily on the executive module to manage the initialization and finalization of blocks. The process is summarized as follows: - -### Initialize Block - -The block initialization process begins with a series of function calls that prepare the block for transaction execution: - -1. **Call `on_initialize`**: The executive module calls the [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} hook from the system pallet and other runtime pallets to prepare for the block's transactions. -2. **Coordinate runtime calls**: Coordinates function calls in the order defined by the transaction queue. -3. **Verify information**: Once [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} functions are executed, the executive module checks the parent hash in the block header and the trie root to verify information is consistent. - -### Finalize Block - -Once transactions are processed, the block must be finalized before being broadcast to the network. The finalization steps are as follows: - -1. **Call `on_finalize`**: The executive module calls the [`on_finalize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_finalize){target=\_blank} hooks in each pallet to ensure any remaining state updates or checks are completed before the block is sealed and published. -2. **Verify information**: The block's digest and storage root in the header are checked against the initialized block to ensure consistency. -3. **Call `on_idle`**: The [`on_idle`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_idle){target=\_blank} hook is triggered to process any remaining tasks using the leftover weight from the block. - -## Block Authoring and Import - -Once the block is finalized, it is gossiped to other nodes in the network. Nodes follow this procedure: - -1. **Receive transactions**: The authoring node collects transactions from the network. -2. **Validate**: Transactions are checked for validity. -3. **Queue**: Valid transactions are placed in the transaction pool for execution. -4. **Execute**: State changes are made as the transactions are executed. -5. **Publish**: The finalized block is broadcast to the network. - -### Block Import Queue - -After a block is published, other nodes on the network can import it into their chain state. The block import queue is part of the outer node in every Polkadot SDK-based node and ensures incoming blocks are valid before adding them to the node's state. - -In most cases, you don't need to know details about how transactions are gossiped or how other nodes on the network import blocks. The following traits are relevant, however, if you plan to write any custom consensus logic or want a deeper dive into the block import queue: - -- **[`ImportQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.ImportQueue.html){target=\_blank}**: The trait that defines the block import queue. -- **[`Link`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Link.html){target=\_blank}**: The trait that defines the link between the block import queue and the network. -- **[`BasicQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/struct.BasicQueue.html){target=\_blank}**: A basic implementation of the block import queue. -- **[`Verifier`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Verifier.html){target=\_blank}**: The trait that defines the block verifier. -- **[`BlockImport`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/block_import/trait.BlockImport.html){target=\_blank}**: The trait that defines the block import process. - -These traits govern how blocks are validated and imported across the network, ensuring consistency and security. - -## Additional Resources - -To learn more about the block structure in the Polkadot SDK runtime, see the [`Block` reference](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.Block.html){target=\_blank} entry in the Rust Docs. - - ---- - -Page Title: Chain Data - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-chain-data.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/chain-data/ -- Summary: Learn how to expose and utilize chain data for blockchain applications. Discover runtime metadata, RPC APIs, and tools for efficient development. - -# Chain Data - -## Introduction - -Understanding and leveraging on-chain data is a fundamental aspect of blockchain development. Whether you're building frontend applications or backend systems, accessing and decoding runtime metadata is vital to interacting with the blockchain. This guide introduces you to the tools and processes for generating and retrieving metadata, explains its role in application development, and outlines the additional APIs available for interacting with a Polkadot node. By mastering these components, you can ensure seamless communication between your applications and the blockchain. - -## Application Development - -You might not be directly involved in building frontend applications as a blockchain developer. However, most applications that run on a blockchain require some form of frontend or user-facing client to enable users or other programs to access and modify the data that the blockchain stores. For example, you might develop a browser-based, mobile, or desktop application that allows users to submit transactions, post articles, view their assets, or track previous activity. The backend for that application is configured in the runtime logic for your blockchain, but the frontend client makes the runtime features accessible to your users. - -For your custom chain to be useful to others, you'll need to provide a client application that allows users to view, interact with, or update information that the blockchain keeps track of. In this article, you'll learn how to expose information about your runtime so that client applications can use it, see examples of the information exposed, and explore tools and libraries that use it. - -## Understand Metadata - -Polkadot SDK-based blockchain networks are designed to expose their runtime information, allowing developers to learn granular details regarding pallets, RPC calls, and runtime APIs. The metadata also exposes their related documentation. The chain's metadata is [SCALE-encoded](/reference/parachains/data-encoding/){target=\_blank}, allowing for the development of browser-based, mobile, or desktop applications to support the chain's runtime upgrades seamlessly. It is also possible to develop applications compatible with multiple Polkadot SDK-based chains simultaneously. - -## Expose Runtime Information as Metadata - -To interact with a node or the state of the blockchain, you need to know how to connect to the chain and access the exposed runtime features. This interaction involves a Remote Procedure Call (RPC) through a node endpoint address, commonly through a secure web socket connection. - -An application developer typically needs to know the contents of the runtime logic, including the following details: - -- Version of the runtime the application is connecting to. -- Supported APIs. -- Implemented pallets. -- Defined functions and corresponding type signatures. -- Defined custom types. -- Exposed parameters users can set. - -As the Polkadot SDK is modular and provides a composable framework for building blockchains, there are limitless opportunities to customize the schema of properties. Each runtime can be configured with its properties, including function calls and types, which can be changed over time with runtime upgrades. - -The Polkadot SDK enables you to generate the runtime metadata schema to capture information unique to a runtime. The metadata for a runtime describes the pallets in use and types defined for a specific runtime version. The metadata includes information about each pallet's storage items, functions, events, errors, and constants. The metadata also provides type definitions for any custom types included in the runtime. - -Metadata provides a complete inventory of a chain's runtime. It is key to enabling client applications to interact with the node, parse responses, and correctly format message payloads sent back to that chain. - -## Generate Metadata - -To efficiently use the blockchain's networking resources and minimize the data transmitted over the network, the metadata schema is encoded using the [Parity SCALE Codec](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank}. This encoding is done automatically through the [`scale-info`](https://docs.rs/scale-info/latest/scale_info/){target=\_blank}crate. - -At a high level, generating the metadata involves the following steps: - -1. The pallets in the runtime logic expose callable functions, types, parameters, and documentation that need to be encoded in the metadata. -2. The `scale-info` crate collects type information for the pallets in the runtime, builds a registry of the pallets that exist in a particular runtime, and the relevant types for each pallet in the registry. The type information is detailed enough to enable encoding and decoding for every type. -3. The [`frame-metadata`](https://github.com/paritytech/frame-metadata){target=\_blank} crate describes the structure of the runtime based on the registry provided by the `scale-info` crate. -4. Nodes provide the RPC method `state_getMetadata` to return a complete description of all the types in the current runtime as a hex-encoded vector of SCALE-encoded bytes. - -## Retrieve Runtime Metadata - -The type information provided by the metadata enables applications to communicate with nodes using different runtime versions and across chains that expose different calls, events, types, and storage items. The metadata also allows libraries to generate a substantial portion of the code needed to communicate with a given node, enabling libraries like [`subxt`](https://github.com/paritytech/subxt){target=\_blank} to generate frontend interfaces that are specific to a target chain. - -### Use Polkadot.js - -Visit the [Polkadot.js Portal](https://polkadot.js.org/apps/#/rpc){target=\_blank} and select the **Developer** dropdown in the top banner. Select **RPC Calls** to make the call to request metadata. Follow these steps to make the RPC call: - -1. Select **state** as the endpoint to call. -2. Select **`getMetadata(at)`** as the method to call. -3. Click **Submit RPC call** to submit the call and return the metadata in JSON format. - -### Use Curl - -You can fetch the metadata for the network by calling the node's RPC endpoint. This request returns the metadata in bytes rather than human-readable JSON: - -```sh -curl -H "Content-Type: application/json" \ --d '{"id":1, "jsonrpc":"2.0", "method": "state_getMetadata"}' \ -https://rpc.polkadot.io - -``` - -### Use Subxt - -[`subxt`](https://github.com/paritytech/subxt){target=\_blank} may also be used to fetch the metadata of any data in a human-readable JSON format: - -```sh -subxt metadata --url wss://rpc.polkadot.io --format json > spec.json -``` - -Another option is to use the [`subxt` explorer web UI](https://paritytech.github.io/subxt-explorer/#/){target=\_blank}. - -## Client Applications and Metadata - -The metadata exposes the expected way to decode each type, meaning applications can send, retrieve, and process application information without manual encoding and decoding. Client applications must use the [SCALE codec library](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank} to encode and decode RPC payloads to use the metadata. Client applications use the metadata to interact with the node, parse responses, and format message payloads sent to the node. - -## Metadata Format - -Although the SCALE-encoded bytes can be decoded using the `frame-metadata` and [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} libraries, there are other tools, such as `subxt` and the Polkadot-JS API, that can convert the raw data to human-readable JSON format. - -The types and type definitions included in the metadata returned by the `state_getMetadata` RPC call depend on the runtime's metadata version. - -In general, the metadata includes the following information: - -- A constant identifying the file as containing metadata. -- The version of the metadata format used in the runtime. -- Type definitions for all types used in the runtime and generated by the `scale-info` crate. -- Pallet information for the pallets included in the runtime in the order that they are defined in the `construct_runtime` macro. - -!!!tip - Depending on the frontend library used (such as the [Polkadot API](https://papi.how/){target=\_blank}), they may format the metadata differently than the raw format shown. - -The following example illustrates a condensed and annotated section of metadata decoded and converted to JSON: - -```json -[ - 1635018093, - { - "V14": { - "types": { - "types": [{}] - }, - "pallets": [{}], - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [{}] - }, - "ty": 141 - } - } -] - -``` - -The constant `1635018093` is a magic number that identifies the file as a metadata file. The rest of the metadata is divided into the `types`, `pallets`, and `extrinsic` sections: - -- The `types` section contains an index of the types and information about each type's type signature. -- The `pallets` section contains information about each pallet in the runtime. -- The `extrinsic` section describes the type identifier and transaction format version that the runtime uses. - -Different extrinsic versions can have varying formats, especially when considering [signed transactions](/reference/parachains/blocks-transactions-fees/transactions/#signed-transactions){target=\_blank}. - -### Pallets - -The following is a condensed and annotated example of metadata for a single element in the `pallets` array (the [`sudo`](https://paritytech.github.io/polkadot-sdk/master/pallet_sudo/index.html){target=\_blank} pallet): - -```json -{ - "name": "Sudo", - "storage": { - "prefix": "Sudo", - "entries": [ - { - "name": "Key", - "modifier": "Optional", - "ty": { - "Plain": 0 - }, - "default": [0], - "docs": ["The `AccountId` of the sudo key."] - } - ] - }, - "calls": { - "ty": 117 - }, - "event": { - "ty": 42 - }, - "constants": [], - "error": { - "ty": 124 - }, - "index": 8 -} - -``` - -Every element metadata contains the name of the pallet it represents and information about its storage, calls, events, and errors. You can look up details about the definition of the calls, events, and errors by viewing the type index identifier. The type index identifier is the `u32` integer used to access the type information for that item. For example, the type index identifier for calls in the Sudo pallet is 117. If you view information for that type identifier in the `types` section of the metadata, it provides information about the available calls, including the documentation for each call. - -For example, the following is a condensed excerpt of the calls for the Sudo pallet: - -```json -{ - "id": 117, - "type": { - "path": ["pallet_sudo", "pallet", "Call"], - "params": [ - { - "name": "T", - "type": null - } - ], - "def": { - "variant": { - "variants": [ - { - "name": "sudo", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 0, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "sudo_unchecked_weight", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - }, - { - "name": "weight", - "type": 8, - "typeName": "Weight" - } - ], - "index": 1, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "set_key", - "fields": [ - { - "name": "new", - "type": 103, - "typeName": "AccountIdLookupOf" - } - ], - "index": 2, - "docs": [ - "Authenticates current sudo key, sets the given AccountId (`new`) as the new sudo" - ] - }, - { - "name": "sudo_as", - "fields": [ - { - "name": "who", - "type": 103, - "typeName": "AccountIdLookupOf" - }, - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 3, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Signed` origin from a given account" - ] - } - ] - } - } - } -} - -``` - -For each field, you can access type information and metadata for the following: - -- **Storage metadata**: Provides the information required to enable applications to get information for specific storage items. -- **Call metadata**: Includes information about the runtime calls defined by the `#[pallet]` macro including call names, arguments and documentation. -- **Event metadata**: Provides the metadata generated by the `#[pallet::event]` macro, including the name, arguments, and documentation for each pallet event. -- **Constants metadata**: Provides metadata generated by the `#[pallet::constant]` macro, including the name, type, and hex-encoded value of the constant. -- **Error metadata**: Provides metadata generated by the `#[pallet::error]` macro, including the name and documentation for each pallet error. - -!!!tip - Type identifiers change from time to time, so you should avoid relying on specific type identifiers in your applications. - -### Extrinsic - -The runtime generates extrinsic metadata and provides useful information about transaction format. When decoded, the metadata contains the transaction version and the list of signed extensions. - -For example: - -```json -{ - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [ - { - "identifier": "CheckNonZeroSender", - "ty": 132, - "additional_signed": 41 - }, - { - "identifier": "CheckSpecVersion", - "ty": 133, - "additional_signed": 4 - }, - { - "identifier": "CheckTxVersion", - "ty": 134, - "additional_signed": 4 - }, - { - "identifier": "CheckGenesis", - "ty": 135, - "additional_signed": 11 - }, - { - "identifier": "CheckMortality", - "ty": 136, - "additional_signed": 11 - }, - { - "identifier": "CheckNonce", - "ty": 138, - "additional_signed": 41 - }, - { - "identifier": "CheckWeight", - "ty": 139, - "additional_signed": 41 - }, - { - "identifier": "ChargeTransactionPayment", - "ty": 140, - "additional_signed": 41 - } - ] - }, - "ty": 141 -} - -``` - -The type system is [composite](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/frame_runtime_types/index.html){target=\_blank}, meaning each type identifier contains a reference to a specific type or to another type identifier that provides information about the associated primitive types. - -For example, you can encode the `BitVec` type, but to decode it properly, you must know the types used for the `Order` and `Store` types. To find type information for `Order` and `Store`, you can use the path in the decoded JSON to locate their type identifiers. - -## Included RPC APIs - -A standard node comes with the following APIs to interact with a node: - -- **[`AuthorApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/author/trait.AuthorApiServer.html){target=\_blank}**: Make calls into a full node, including authoring extrinsics and verifying session keys. -- **[`ChainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/chain/trait.ChainApiServer.html){target=\_blank}**: Retrieve block header and finality information. -- **[`OffchainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/offchain/trait.OffchainApiServer.html){target=\_blank}**: Make RPC calls for off-chain workers. -- **[`StateApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/state/trait.StateApiServer.html){target=\_blank}**: Query information about on-chain state such as runtime version, storage items, and proofs. -- **[`SystemApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/system/trait.SystemApiServer.html){target=\_blank}**: Retrieve information about network state, such as connected peers and node roles. - -## Additional Resources - -The following tools can help you locate and decode metadata: - -- [Subxt Explorer](https://paritytech.github.io/subxt-explorer/#/){target=\_blank} -- [Metadata Portal 🌗](https://github.com/paritytech/metadata-portal){target=\_blank} -- [De[code] Sub[strate]](https://github.com/paritytech/desub){target=\_blank} - - --- Page Title: Connect to Polkadot @@ -1170,413 +736,139 @@ Both backends support contract deployment effectively, with REVM offering drop-i --- -Page Title: Cryptography +Page Title: Deploy a Basic Contract to Polkadot Hub -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-cryptography.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/cryptography/ -- Summary: A concise guide to cryptography in blockchain, covering hash functions, encryption types, digital signatures, and elliptic curve applications. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-.deploy-basic-pvm.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/.deploy-basic-pvm/ +- Summary: Learn how to deploy a basic smart contract to Polkadot Hub using the PolkaVM. -# Cryptography +# Deploy a Basic Contract ## Introduction -Cryptography forms the backbone of blockchain technology, providing the mathematical verifiability crucial for consensus systems, data integrity, and user security. While a deep understanding of the underlying mathematical processes isn't necessary for most blockchain developers, grasping the fundamental applications of cryptography is essential. This page comprehensively overviews cryptographic implementations used across Polkadot SDK-based chains and the broader blockchain ecosystem. - -## Hash Functions - -Hash functions are fundamental to blockchain technology, creating a unique digital fingerprint for any piece of data, including simple text, images, or any other form of file. They map input data of any size to a fixed-size output (typically 32 bytes) using complex mathematical operations. Hashing is used to verify data integrity, create digital signatures, and provide a secure way to store passwords. This form of mapping is known as the ["pigeonhole principle,"](https://en.wikipedia.org/wiki/Pigeonhole_principle){target=\_blank} it is primarily implemented to efficiently and verifiably identify data from large sets. - -### Key Properties of Hash Functions - -- **Deterministic**: The same input always produces the same output. -- **Quick computation**: It's easy to calculate the hash value for any given input. -- **Pre-image resistance**: It's infeasible to generate the input data from its hash. -- **Small changes in input yield large changes in output**: Known as the ["avalanche effect"](https://en.wikipedia.org/wiki/Avalanche_effect){target=\_blank}. -- **Collision resistance**: The probabilities are extremely low to find two different inputs with the same hash. - -### Blake2 - -The Polkadot SDK utilizes Blake2, a state-of-the-art hashing method that offers: - -- Equal or greater security compared to [SHA-2](https://en.wikipedia.org/wiki/SHA-2){target=\_blank}. -- Significantly faster performance than other algorithms. - -These properties make Blake2 ideal for blockchain systems, reducing sync times for new nodes and lowering the resources required for validation. For detailed technical specifications about Blake2, see the [official Blake2 paper](https://www.blake2.net/blake2.pdf){target=\_blank}. +Deploying smart contracts to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank} can be accomplished through various tools and environments, each suited to different development workflows. This guide demonstrates how to deploy a basic PolkaVM (PVM) smart contract using four popular approaches: JavaScript with [Ethers.js](https://docs.ethers.org/v6/){target=\_blank}, [Remix IDE](https://remix.live/){target=\_blank}, [Hardhat](https://hardhat.org/){target=\_blank}, and [Foundry](https://getfoundry.sh/){target=\_blank}. -## Types of Cryptography +All these tools leverage the `revive` compiler to transform Solidity smart contracts into PolkaVM bytecode, making them compatible with Polkadot Hub's native smart contract environment. Whether you prefer working with lightweight JavaScript libraries, visual browser-based IDEs, comprehensive development frameworks, or fast command-line toolkits, this guide covers the deployment process for each approach. -There are two different ways that cryptographic algorithms are implemented: symmetric cryptography and asymmetric cryptography. +**Prerequisites:** -### Symmetric Cryptography +- Basic understanding of Solidity programming. +- [Node.js](https://nodejs.org/en/download){target=\_blank} v22.13.1 or later (for JavaScript/Hardhat approaches). +- Test tokens for gas fees (available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}). +- A wallet with a private key for signing transactions. -Symmetric encryption is a branch of cryptography that isn't based on one-way functions, unlike asymmetric cryptography. It uses the same cryptographic key to encrypt plain text and decrypt the resulting ciphertext. +## JavaScript with Ethers.js -Symmetric cryptography is a type of encryption that has been used throughout history, such as the Enigma Cipher and the Caesar Cipher. It is still widely used today and can be found in Web2 and Web3 applications alike. There is only one single key, and a recipient must also have access to it to access the contained information. +Ethers.js provides a lightweight approach for deploying contracts using pure JavaScript. This method is ideal for developers who want programmatic control over the deployment process or need to integrate contract deployment into existing applications. -#### Advantages {: #symmetric-advantages } +### Setup -- Fast and efficient for large amounts of data. -- Requires less computational power. +First, initialize your project and install dependencies: -#### Disadvantages {: #symmetric-disadvantages } +```bash +mkdir ethers-deployment +cd ethers-deployment +npm init -y +npm install ethers @parity/resolc +``` -- Key distribution can be challenging. -- Scalability issues in systems with many users. +### Create and Compile Your Contract -### Asymmetric Cryptography +Create a simple storage contract in `contracts/Storage.sol`: -Asymmetric encryption is a type of cryptography that uses two different keys, known as a keypair: a public key, used to encrypt plain text, and a private counterpart, used to decrypt the ciphertext. +```solidity title="contracts/Storage.sol" +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.9; -The public key encrypts a fixed-length message that can only be decrypted with the recipient's private key and, sometimes, a set password. The public key can be used to cryptographically verify that the corresponding private key was used to create a piece of data without compromising the private key, such as with digital signatures. This has obvious implications for identity, ownership, and properties and is used in many different protocols across Web2 and Web3. +contract Storage { + uint256 private storedNumber; -#### Advantages {: #asymmetric-advantages } + function store(uint256 num) public { + storedNumber = num; + } -- Solves the key distribution problem. -- Enables digital signatures and secure key exchange. + function retrieve() public view returns (uint256) { + return storedNumber; + } +} +``` -#### Disadvantages {: #asymmetric-disadvantages } +Create a compilation script `compile.js`: -- Slower than symmetric encryption. -- Requires more computational resources. +```javascript title="compile.js" +const { compile } = require('@parity/resolc'); +const { readFileSync, writeFileSync } = require('fs'); +const { basename, join } = require('path'); -### Trade-offs and Compromises +const compileContract = async (solidityFilePath, outputDir) => { + try { + // Read the Solidity file + const source = readFileSync(solidityFilePath, 'utf8'); -Symmetric cryptography is faster and requires fewer bits in the key to achieve the same level of security that asymmetric cryptography provides. However, it requires a shared secret before communication can occur, which poses issues to its integrity and a potential compromise point. On the other hand, asymmetric cryptography doesn't require the secret to be shared ahead of time, allowing for far better end-user security. + // Construct the input object for the compiler + const input = { + [basename(solidityFilePath)]: { content: source }, + }; -Hybrid symmetric and asymmetric cryptography is often used to overcome the engineering issues of asymmetric cryptography, as it is slower and requires more bits in the key to achieve the same level of security. It encrypts a key and then uses the comparatively lightweight symmetric cipher to do the "heavy lifting" with the message. + console.log(`Compiling contract: ${basename(solidityFilePath)}...`); -## Digital Signatures + // Compile the contract + const out = await compile(input); -Digital signatures are a way of verifying the authenticity of a document or message using asymmetric keypairs. They are used to ensure that a sender or signer's document or message hasn't been tampered with in transit, and for recipients to verify that the data is accurate and from the expected sender. + for (const contracts of Object.values(out.contracts)) { + for (const [name, contract] of Object.entries(contracts)) { + console.log(`Compiled contract: ${name}`); -Signing digital signatures only requires a low-level understanding of mathematics and cryptography. For a conceptual example -- when signing a check, it is expected that it cannot be cashed multiple times. This isn't a feature of the signature system but rather the check serialization system. The bank will check that the serial number on the check hasn't already been used. Digital signatures essentially combine these two concepts, allowing the signature to provide the serialization via a unique cryptographic fingerprint that cannot be reproduced. + // Write the ABI + const abiPath = join(outputDir, `${name}.json`); + writeFileSync(abiPath, JSON.stringify(contract.abi, null, 2)); + console.log(`ABI saved to ${abiPath}`); -Unlike pen-and-paper signatures, knowledge of a digital signature cannot be used to create other signatures. Digital signatures are often used in bureaucratic processes, as they are more secure than simply scanning in a signature and pasting it onto a document. + // Write the bytecode + const bytecodePath = join(outputDir, `${name}.polkavm`); + writeFileSync( + bytecodePath, + Buffer.from(contract.evm.bytecode.object, 'hex'), + ); + console.log(`Bytecode saved to ${bytecodePath}`); + } + } + } catch (error) { + console.error('Error compiling contracts:', error); + } +}; -Polkadot SDK provides multiple different cryptographic schemes and is generic so that it can support anything that implements the [`Pair` trait](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Pair.html){target=\_blank}. +const solidityFilePath = join(__dirname, 'contracts/Storage.sol'); +const outputDir = join(__dirname, 'contracts'); -### Example of Creating a Digital Signature +compileContract(solidityFilePath, outputDir); +``` -The process of creating and verifying a digital signature involves several steps: +Run the compilation: -1. The sender creates a hash of the message. -2. The hash is encrypted using the sender's private key, creating the signature. -3. The message and signature are sent to the recipient. -4. The recipient decrypts the signature using the sender's public key. -5. The recipient hashes the received message and compares it to the decrypted hash. +```bash +node compile.js +``` -If the hashes match, the signature is valid, confirming the message's integrity and the sender's identity. +### Deploy the Contract -## Elliptic Curve +Create a deployment script `deploy.js`: -Blockchain technology requires the ability to have multiple keys creating a signature for block proposal and validation. To this end, Elliptic Curve Digital Signature Algorithm (ECDSA) and Schnorr signatures are two of the most commonly used methods. While ECDSA is a far simpler implementation, Schnorr signatures are more efficient when it comes to multi-signatures. +```javascript title="deploy.js" +const { writeFileSync, existsSync, readFileSync } = require('fs'); +const { join } = require('path'); +const { ethers, JsonRpcProvider } = require('ethers'); -Schnorr signatures bring some noticeable features over the ECDSA/EdDSA schemes: +const codegenDir = join(__dirname); -- It is better for hierarchical deterministic key derivations. -- It allows for native multi-signature through [signature aggregation](https://bitcoincore.org/en/2017/03/23/schnorr-signature-aggregation/){target=\_blank}. -- It is generally more resistant to misuse. - -One sacrifice that is made when using Schnorr signatures over ECDSA is that both require 64 bytes, but only ECDSA signatures communicate their public key. - -### Various Implementations - -- **[ECDSA](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm){target=\_blank}**: Polkadot SDK provides an ECDSA signature scheme using the [secp256k1](https://en.bitcoin.it/wiki/Secp256k1){target=\_blank} curve. This is the same cryptographic algorithm used to secure [Bitcoin](https://en.wikipedia.org/wiki/Bitcoin){target=\_blank} and [Ethereum](https://en.wikipedia.org/wiki/Ethereum){target=\_blank}. - -- **[Ed25519](https://en.wikipedia.org/wiki/EdDSA#Ed25519){target=\_blank}**: An EdDSA signature scheme using [Curve25519](https://en.wikipedia.org/wiki/Curve25519){target=\_blank}. It is carefully engineered at several levels of design and implementation to achieve very high speeds without compromising security. - -- **[SR25519](https://research.web3.foundation/Polkadot/security/keys/accounts-more){target=\_blank}**: Based on the same underlying curve as Ed25519. However, it uses Schnorr signatures instead of the EdDSA scheme. - - ---- - -Page Title: Data Encoding - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-data-encoding.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/data-encoding/ -- Summary: SCALE codec enables fast, efficient data encoding, ideal for resource-constrained environments like Wasm, supporting custom types and compact encoding. - -# Data Encoding - -## Introduction - -The Polkadot SDK uses a lightweight and efficient encoding/decoding mechanism to optimize data transmission across the network. This mechanism, known as the _SCALE_ codec, is used for serializing and deserializing data. - -The SCALE codec enables communication between the runtime and the outer node. This mechanism is designed for high-performance, copy-free data encoding and decoding in resource-constrained environments like the Polkadot SDK [Wasm runtime](/develop/parachains/deployment/build-deterministic-runtime/#introduction){target=\_blank}. - -It is not self-describing, meaning the decoding context must fully know the encoded data types. - -Parity's libraries utilize the [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} crate (a Rust implementation of the SCALE codec) to handle encoding and decoding for interactions between RPCs and the runtime. - -The `codec` mechanism is ideal for Polkadot SDK-based chains because: - -- It is lightweight compared to generic serialization frameworks like [`serde`](https://serde.rs/){target=\_blank}, which add unnecessary bulk to binaries. -- It doesn’t rely on Rust’s `libstd`, making it compatible with `no_std` environments like Wasm runtime. -- It integrates seamlessly with Rust, allowing easy derivation of encoding and decoding logic for new types using `#[derive(Encode, Decode)]`. - -Defining a custom encoding scheme in the Polkadot SDK-based chains, rather than using an existing Rust codec library, is crucial for enabling cross-platform and multi-language support. - -## SCALE Codec - -The codec is implemented using the following traits: - -- [`Encode`](#encode) -- [`Decode`](#decode) -- [`CompactAs`](#compactas) -- [`HasCompact`](#hascompact) -- [`EncodeLike`](#encodelike) - -### Encode - -The [`Encode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Encode.html){target=\_blank} trait handles data encoding into SCALE format and includes the following key functions: - -- **`size_hint(&self) -> usize`**: Estimates the number of bytes required for encoding to prevent multiple memory allocations. This should be inexpensive and avoid complex operations. Optional if the size isn’t known. -- **`encode_to(&self, dest: &mut T)`**: Encodes the data, appending it to a destination buffer. -- **`encode(&self) -> Vec`**: Encodes the data and returns it as a byte vector. -- **`using_encoded R>(&self, f: F) -> R`**: Encodes the data and passes it to a closure, returning the result. -- **`encoded_size(&self) -> usize`**: Calculates the encoded size. Should be used when the encoded data isn’t required. - -!!!tip - For best performance, value types should override `using_encoded`, and allocating types should override `encode_to`. It's recommended to implement `size_hint` for all types where possible. - -### Decode - -The [`Decode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Decode.html){target=\_blank} trait handles decoding SCALE-encoded data back into the appropriate types: - -- **`fn decode(value: &mut I) -> Result`**: Decodes data from the SCALE format, returning an error if decoding fails. - -### CompactAs - -The [`CompactAs`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.CompactAs.html){target=\_blank} trait wraps custom types for compact encoding: - -- **`encode_as(&self) -> &Self::As`**: Encodes the type as a compact type. -- **`decode_from(_: Self::As) -> Result`**: decodes from a compact encoded type. - -### HasCompact - -The [`HasCompact`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.HasCompact.html){target=\_blank} trait indicates a type supports compact encoding. - -### EncodeLike - -The [`EncodeLike`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.EncodeLike.html){target=\_blank} trait is used to ensure multiple types that encode similarly are accepted by the same function. When using `derive`, it is automatically implemented. - -### Data Types - -The table below outlines how the Rust implementation of the Parity SCALE codec encodes different data types. - -| Type | Description | Example SCALE Decoded Value | SCALE Encoded Value | -|-------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------| -| Boolean | Boolean values are encoded using the least significant bit of a single byte. | `false` / `true` | `0x00` / `0x01` | -| Compact/general integers | A "compact" or general integer encoding is sufficient for encoding large integers (up to 2^536) and is more efficient at encoding most values than the fixed-width version. | `unsigned integer 0` / `unsigned integer 1` / `unsigned integer 42` / `unsigned integer 69` / `unsigned integer 65535` / `BigInt(100000000000000)` | `0x00` / `0x04` / `0xa8` / `0x1501` / `0xfeff0300` / `0x0b00407a10f35a` | -| Enumerations (tagged-unions) | A fixed number of variants, each mutually exclusive and potentially implying a further value or series of values. Encoded as the first byte identifying the index of the variant that the value is. Any further bytes are used to encode any data that the variant implies. Thus, no more than 256 variants are supported. | `Int(42)` and `Bool(true)` where `enum IntOrBool { Int(u8), Bool(bool) }` | `0x002a` and `0x0101` | -| Fixed-width integers | Basic integers are encoded using a fixed-width little-endian (LE) format. | `signed 8-bit integer 69` / `unsigned 16-bit integer 42` / `unsigned 32-bit integer 16777215` | `0x45` / `0x2a00` / `0xffffff00` | -| Options | One or zero values of a particular type. | `Some` / `None` | `0x01` followed by the encoded value / `0x00` | -| Results | Results are commonly used enumerations which indicate whether certain operations were successful or unsuccessful. | `Ok(42)` / `Err(false)` | `0x002a` / `0x0100` | -| Strings | Strings are Vectors of bytes (Vec) containing a valid UTF8 sequence. | | | -| Structs | For structures, the values are named, but that is irrelevant for the encoding (names are ignored - only order matters). | `SortedVecAsc::from([3, 5, 2, 8])` | `[3, 2, 5, 8] ` | -| Tuples | A fixed-size series of values, each with a possibly different but predetermined and fixed type. This is simply the concatenation of each encoded value. | Tuple of compact unsigned integer and boolean: `(3, false)` | `0x0c00` | -| Vectors (lists, series, sets) | A collection of same-typed values is encoded, prefixed with a compact encoding of the number of items, followed by each item's encoding concatenated in turn. | Vector of unsigned `16`-bit integers: `[4, 8, 15, 16, 23, 42]` | `0x18040008000f00100017002a00` | - -## Encode and Decode Rust Trait Implementations - -Here's how the `Encode` and `Decode` traits are implemented: - - -```rust -use parity_scale_codec::{Encode, Decode}; - -[derive(Debug, PartialEq, Encode, Decode)] -enum EnumType { - #[codec(index = 15)] - A, - B(u32, u64), - C { - a: u32, - b: u64, - }, -} - -let a = EnumType::A; -let b = EnumType::B(1, 2); -let c = EnumType::C { a: 1, b: 2 }; - -a.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x0f"); -}); - -b.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); - -c.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); - -let mut da: &[u8] = b"\x0f"; -assert_eq!(EnumType::decode(&mut da).ok(), Some(a)); - -let mut db: &[u8] = b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut db).ok(), Some(b)); - -let mut dc: &[u8] = b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut dc).ok(), Some(c)); - -let mut dz: &[u8] = &[0]; -assert_eq!(EnumType::decode(&mut dz).ok(), None); -``` - -## SCALE Codec Libraries - -Several SCALE codec implementations are available in various languages. Here's a list of them: - -- **AssemblyScript**: [`LimeChain/as-scale-codec`](https://github.com/LimeChain/as-scale-codec){target=\_blank} -- **C**: [`MatthewDarnell/cScale`](https://github.com/MatthewDarnell/cScale){target=\_blank} -- **C++**: [`qdrvm/scale-codec-cpp`](https://github.com/qdrvm/scale-codec-cpp){target=\_blank} -- **JavaScript**: [`polkadot-js/api`](https://github.com/polkadot-js/api){target=\_blank} -- **Dart**: [`leonardocustodio/polkadart`](https://github.com/leonardocustodio/polkadart){target=\_blank} -- **Haskell**: [`airalab/hs-web3`](https://github.com/airalab/hs-web3/tree/master/packages/scale){target=\_blank} -- **Golang**: [`itering/scale.go`](https://github.com/itering/scale.go){target=\_blank} -- **Java**: [`splix/polkaj`](https://github.com/splix/polkaj){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **Ruby**: [` wuminzhe/scale_rb`](https://github.com/wuminzhe/scale_rb){target=\_blank} -- **TypeScript**: [`parity-scale-codec-ts`](https://github.com/tjjfvi/subshape){target=\_blank}, [`scale-ts`](https://github.com/unstoppablejs/unstoppablejs/tree/main/packages/scale-ts#scale-ts){target=\_blank}, [`soramitsu/scale-codec-js-library`](https://github.com/soramitsu/scale-codec-js-library){target=\_blank}, [`subsquid/scale-codec`](https://github.com/subsquid/squid-sdk/tree/master/substrate/scale-codec){target=\_blank} - - ---- - -Page Title: Deploy a Basic Contract to Polkadot Hub - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-.deploy-basic-pvm.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/.deploy-basic-pvm/ -- Summary: Learn how to deploy a basic smart contract to Polkadot Hub using the PolkaVM. - -# Deploy a Basic Contract - -## Introduction - -Deploying smart contracts to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank} can be accomplished through various tools and environments, each suited to different development workflows. This guide demonstrates how to deploy a basic PolkaVM (PVM) smart contract using four popular approaches: JavaScript with [Ethers.js](https://docs.ethers.org/v6/){target=\_blank}, [Remix IDE](https://remix.live/){target=\_blank}, [Hardhat](https://hardhat.org/){target=\_blank}, and [Foundry](https://getfoundry.sh/){target=\_blank}. - -All these tools leverage the `revive` compiler to transform Solidity smart contracts into PolkaVM bytecode, making them compatible with Polkadot Hub's native smart contract environment. Whether you prefer working with lightweight JavaScript libraries, visual browser-based IDEs, comprehensive development frameworks, or fast command-line toolkits, this guide covers the deployment process for each approach. - -**Prerequisites:** - -- Basic understanding of Solidity programming. -- [Node.js](https://nodejs.org/en/download){target=\_blank} v22.13.1 or later (for JavaScript/Hardhat approaches). -- Test tokens for gas fees (available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}). -- A wallet with a private key for signing transactions. - -## JavaScript with Ethers.js - -Ethers.js provides a lightweight approach for deploying contracts using pure JavaScript. This method is ideal for developers who want programmatic control over the deployment process or need to integrate contract deployment into existing applications. - -### Setup - -First, initialize your project and install dependencies: - -```bash -mkdir ethers-deployment -cd ethers-deployment -npm init -y -npm install ethers @parity/resolc -``` - -### Create and Compile Your Contract - -Create a simple storage contract in `contracts/Storage.sol`: - -```solidity title="contracts/Storage.sol" -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.9; - -contract Storage { - uint256 private storedNumber; - - function store(uint256 num) public { - storedNumber = num; - } - - function retrieve() public view returns (uint256) { - return storedNumber; - } -} -``` - -Create a compilation script `compile.js`: - -```javascript title="compile.js" -const { compile } = require('@parity/resolc'); -const { readFileSync, writeFileSync } = require('fs'); -const { basename, join } = require('path'); - -const compileContract = async (solidityFilePath, outputDir) => { - try { - // Read the Solidity file - const source = readFileSync(solidityFilePath, 'utf8'); - - // Construct the input object for the compiler - const input = { - [basename(solidityFilePath)]: { content: source }, - }; - - console.log(`Compiling contract: ${basename(solidityFilePath)}...`); - - // Compile the contract - const out = await compile(input); - - for (const contracts of Object.values(out.contracts)) { - for (const [name, contract] of Object.entries(contracts)) { - console.log(`Compiled contract: ${name}`); - - // Write the ABI - const abiPath = join(outputDir, `${name}.json`); - writeFileSync(abiPath, JSON.stringify(contract.abi, null, 2)); - console.log(`ABI saved to ${abiPath}`); - - // Write the bytecode - const bytecodePath = join(outputDir, `${name}.polkavm`); - writeFileSync( - bytecodePath, - Buffer.from(contract.evm.bytecode.object, 'hex'), - ); - console.log(`Bytecode saved to ${bytecodePath}`); - } - } - } catch (error) { - console.error('Error compiling contracts:', error); - } -}; - -const solidityFilePath = join(__dirname, 'contracts/Storage.sol'); -const outputDir = join(__dirname, 'contracts'); - -compileContract(solidityFilePath, outputDir); -``` - -Run the compilation: - -```bash -node compile.js -``` - -### Deploy the Contract - -Create a deployment script `deploy.js`: - -```javascript title="deploy.js" -const { writeFileSync, existsSync, readFileSync } = require('fs'); -const { join } = require('path'); -const { ethers, JsonRpcProvider } = require('ethers'); - -const codegenDir = join(__dirname); - -// Creates a provider with specified RPC URL and chain details -const createProvider = (rpcUrl, chainId, chainName) => { - const provider = new JsonRpcProvider(rpcUrl, { - chainId: chainId, - name: chainName, - }); - return provider; -}; +// Creates a provider with specified RPC URL and chain details +const createProvider = (rpcUrl, chainId, chainName) => { + const provider = new JsonRpcProvider(rpcUrl, { + chainId: chainId, + name: chainName, + }); + return provider; +}; // Reads and parses the ABI file for a given contract const getAbi = (contractName) => { @@ -3912,49 +3204,6 @@ Revive implements the standard set of Ethereum precompiles: Ethereum-native precompiles provide a powerful foundation for smart contract development on Polkadot Hub, offering high-performance implementations of essential cryptographic and utility functions. By maintaining compatibility with standard Ethereum precompile addresses and interfaces, Revive ensures that developers can leverage existing knowledge and tools while benefiting from the enhanced performance of native execution. ---- - -Page Title: Faucet - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-faucet.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/faucet/ -- Summary: Learn how to obtain test tokens from Polkadot faucets for development and testing purposes across different networks. - -# Faucet - -Test tokens allow you to experiment with smart contracts, test transactions, and validate your dApp functionality without using real cryptocurrency. - -Polkadot has a faucet that distributes free TestNet tokens to developers for testing purposes: - -- Execute transactions on TestNet networks. -- Pay for gas fees when deploying smart contracts. -- Test dApp functionality before MainNet deployment. -- Experiment with blockchain interactions without financial risk. - - -## Get Test Tokens - -For Polkadot Hub TestNet, you can use the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank} to obtain test tokens. Here's how to do it: - -1. Navigate to the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. If the desired network is not already selected, choose it from the **Network** drop-down. This example uses the Polkadot Hub TestNet. -2. Copy your address linked to the TestNet and paste it into the designated field. -3. Click the **Get Some PASs** button to request free test PAS tokens. These tokens will be sent to your wallet shortly. - -![Polkadot Faucet](/images/smart-contracts/faucet/faucet-1.gif) - -## Things to Consider - -!!! info "Rate Limiting" - Faucets typically implement rate limiting to prevent abuse. You may need to wait between requests if you've recently obtained tokens from the same faucet. - -!!! warning "Network Compatibility" - Ensure your wallet is connected to the correct network (Polkadot Hub TestNet) before requesting tokens. Tokens sent to addresses on different networks will not be accessible. - -## Using Your Test Tokens - -Getting started with test tokens is the first step in your Polkadot development journey. These free resources enable you to build, experiment with, and refine your applications without financial constraints, ensuring your projects are robust and ready for deployment on MainNet. - - --- Page Title: Get Started with Parachain Development @@ -4159,370 +3408,173 @@ From here, follow the quick starts to get connected, iterate locally with your p --- -Page Title: Glossary - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-glossary.md -- Canonical (HTML): https://docs.polkadot.com/reference/glossary/ -- Summary: Glossary of terms used within the Polkadot ecosystem, Polkadot SDK, its subsequent libraries, and other relevant Web3 terminology. - -# Glossary +Page Title: Get Started with XCM -Key definitions, concepts, and terminology specific to the Polkadot ecosystem are included here. - -Additional glossaries from around the ecosystem you might find helpful: +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md +- Canonical (HTML): https://docs.polkadot.com/parachains/interoperability/get-started/ +- Summary: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. -- [Polkadot Wiki Glossary](https://wiki.polkadot.com/general/glossary){target=\_blank} -- [Polkadot SDK Glossary](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/glossary/index.html){target=\_blank} +# Get Started with XCM -## Authority +## Introduction -The role in a blockchain that can participate in consensus mechanisms. +Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems. -- **[GRANDPA](#grandpa)**: The authorities vote on chains they consider final. -- **[Blind Assignment of Blockchain Extension](#blind-assignment-of-blockchain-extension-babe) (BABE)**: The authorities are also [block authors](#block-author). +With XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation. -Authority sets can be used as a basis for consensus mechanisms such as the [Nominated Proof of Stake (NPoS)](#nominated-proof-of-stake-npos) protocol. +## Messaging Format -## Authority Round (Aura) +XCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics. -A deterministic [consensus](#consensus) protocol where block production is limited to a rotating list of [authorities](#authority) that take turns creating blocks. In authority round (Aura) consensus, most online authorities are assumed to be honest. It is often used in combination with [GRANDPA](#grandpa) as a [hybrid consensus](#hybrid-consensus) protocol. +XCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing. -Learn more by reading the official [Aura consensus algorithm](https://openethereum.github.io/Aura){target=\_blank} wiki article. +## The Four Principles of XCM -## Blind Assignment of Blockchain Extension (BABE) +XCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems: -A [block authoring](#block-author) protocol similar to [Aura](#authority-round-aura), except [authorities](#authority) win [slots](#slot) based on a Verifiable Random Function (VRF) instead of the round-robin selection method. The winning authority can select a chain and submit a new block. - -Learn more by reading the official Web3 Foundation [BABE research document](https://research.web3.foundation/Polkadot/protocols/block-production/Babe){target=\_blank}. - -## Block Author - -The node responsible for the creation of a block, also called _block producers_. In a Proof of Work (PoW) blockchain, these nodes are called _miners_. - -## Byzantine Fault Tolerance (BFT) - -The ability of a distributed computer network to remain operational if a certain proportion of its nodes or [authorities](#authority) are defective or behaving maliciously. A distributed network is typically considered Byzantine fault tolerant if it can remain functional, with up to one-third of nodes assumed to be defective, offline, actively malicious, and part of a coordinated attack. - -### Byzantine Failure - -The loss of a network service due to node failures that exceed the proportion of nodes required to reach consensus. - -### Practical Byzantine Fault Tolerance (pBFT) - -An early approach to Byzantine fault tolerance (BFT), practical Byzantine fault tolerance (pBFT) systems tolerate Byzantine behavior from up to one-third of participants. - -The communication overhead for such systems is `O(n²)`, where `n` is the number of nodes (participants) in the system. - -### Preimage - -A preimage is the data that is input into a hash function to calculate a hash. Since a hash function is a [one-way function](https://en.wikipedia.org/wiki/One-way_function){target=\_blank}, the output, the hash, cannot be used to reveal the input, the preimage. - -## Call - -In the context of pallets containing functions to be dispatched to the runtime, `Call` is an enumeration data type that describes the functions that can be dispatched with one variant per pallet. A `Call` represents a [dispatch](#dispatchable) data structure object. - -## Chain Specification - -A chain specification file defines the properties required to run a node in an active or new Polkadot SDK-built network. It often contains the initial genesis runtime code, network properties (such as the network's name), the initial state for some pallets, and the boot node list. The chain specification file makes it easy to use a single Polkadot SDK codebase as the foundation for multiple independently configured chains. - -## Collator - -An [author](#block-author) of a [parachain](#parachain) network. -They aren't [authorities](#authority) in themselves, as they require a [relay chain](#relay-chain) to coordinate [consensus](#consensus). - -More details are found on the [Polkadot Collator Wiki](https://wiki.polkadot.com/learn/learn-collator/){target=\_blank}. - -## Collective - -Most often used to refer to an instance of the Collective pallet on Polkadot SDK-based networks such as [Kusama](#kusama) or [Polkadot](#polkadot) if the Collective pallet is part of the FRAME-based runtime for the network. - -## Consensus - -Consensus is the process blockchain nodes use to agree on a chain's canonical fork. It is composed of [authorship](#block-author), finality, and [fork-choice rule](#fork-choice-rulestrategy). In the Polkadot ecosystem, these three components are usually separate and the term consensus often refers specifically to authorship. - -See also [hybrid consensus](#hybrid-consensus). - -## Consensus Algorithm - -Ensures a set of [actors](#authority)—who don't necessarily trust each other—can reach an agreement about the state as the result of some computation. Most consensus algorithms assume that up to one-third of the actors or nodes can be [Byzantine fault tolerant](#byzantine-fault-tolerance-bft). - -Consensus algorithms are generally concerned with ensuring two properties: - -- **Safety**: Indicating that all honest nodes eventually agreed on the state of the chain. -- **Liveness**: Indicating the ability of the chain to keep progressing. - -## Consensus Engine +- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes. +- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended. +- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin. +- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems. -The node subsystem responsible for consensus tasks. +These principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments. -For detailed information about the consensus strategies of the [Polkadot](#polkadot) network, see the [Polkadot Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} blog series. +## The XCM Tech Stack -See also [hybrid consensus](#hybrid-consensus). +![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp) -## Coretime +The XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels. -The time allocated for utilizing a core, measured in relay chain blocks. There are two types of coretime: *on-demand* and *bulk*. +## Core Functionalities of XCM -On-demand coretime refers to coretime acquired through bidding in near real-time for the validation of a single parachain block on one of the cores reserved specifically for on-demand orders. They are available as an on-demand coretime pool. Set of cores that are available on-demand. Cores reserved through bulk coretime could also be made available in the on-demand coretime pool, in parts or in entirety. +XCM enhances cross-consensus communication by introducing several powerful features: -Bulk coretime is a fixed duration of continuous coretime represented by an NFT that can be split, shared, or resold. It is managed by the [Broker pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_broker/index.html){target=\_blank}. +- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management. +- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification. +- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location. -## Development Phrase +The standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications. -A [mnemonic phrase](https://en.wikipedia.org/wiki/Mnemonic#For_numerical_sequences_and_mathematical_operations){target=\_blank} that is intentionally made public. +## XCM Example -Well-known development accounts, such as Alice, Bob, Charlie, Dave, Eve, and Ferdie, are generated from the same secret phrase: +The following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA). +```rust +let message = Xcm(vec![ + WithdrawAsset((Here, amount).into()), + BuyExecution { + fees: (Here, amount).into(), + weight_limit: WeightLimit::Unlimited + }, + DepositAsset { + assets: All.into(), + beneficiary: MultiLocation { + parents: 0, + interior: Junction::AccountId32 { + network: None, + id: BOB.clone().into() + }.into(), + }.into() + } +]); ``` -bottom drive obey lake curtain smoke basket hold race lonely fit walk -``` - -Many tools in the Polkadot SDK ecosystem, such as [`subkey`](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/bin/utils/subkey){target=\_blank}, allow you to implicitly specify an account using a derivation path such as `//Alice`. - -## Digest - -An extensible field of the [block header](#header) that encodes information needed by several actors in a blockchain network, including: - -- [Light clients](#light-client) for chain synchronization. -- Consensus engines for block verification. -- The runtime itself, in the case of pre-runtime digests. - -## Dispatchable - -Function objects that act as the entry points in FRAME [pallets](#pallet). Internal or external entities can call them to interact with the blockchain’s state. They are a core aspect of the runtime logic, handling [transactions](#transaction) and other state-changing operations. - -## Events - -A means of recording that some particular [state](#state) transition happened. - -In the context of [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities), events are composable data types that each [pallet](#pallet) can individually define. Events in FRAME are implemented as a set of transient storage items inspected immediately after a block has been executed and reset during block initialization. - -## Executor - -A means of executing a function call in a given [runtime](#runtime) with a set of dependencies. -There are two orchestration engines in Polkadot SDK, _WebAssembly_ and _native_. - -- The _native executor_ uses a natively compiled runtime embedded in the node to execute calls. This is a performance optimization available to up-to-date nodes. - -- The _WebAssembly executor_ uses a [Wasm](#webassembly-wasm) binary and a Wasm interpreter to execute calls. The binary is guaranteed to be up-to-date regardless of the version of the blockchain node because it is persisted in the [state](#state) of the Polkadot SDK-based chain. - -## Existential Deposit - -The minimum balance an account is allowed to have in the [Balances pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/index.html){target=\_blank}. Accounts cannot be created with a balance less than the existential deposit amount. - -If an account balance drops below this amount, the Balances pallet uses [a FRAME System API](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.dec_ref){target=\_blank} to drop its references to that account. - -If the Balances pallet reference to an account is dropped, the account can be [reaped](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.allow_death){target=\_blank}. - -## Extrinsic - -A general term for data that originates outside the runtime, is included in a block, and leads to some action. This includes user-initiated transactions and inherent transactions placed into the block by the block builder. - -It is a SCALE-encoded array typically consisting of a version number, signature, and varying data types indicating the resulting runtime function to be called. Extrinsics can take two forms: [inherents](#inherent-transactions) and [transactions](#transaction). - -For more technical details, see the [Polkadot spec](https://spec.polkadot.network/id-extrinsics){target=\_blank}. - -## Fork Choice Rule/Strategy - -A fork choice rule or strategy helps determine which chain is valid when reconciling several network forks. A common fork choice rule is the [longest chain](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/struct.LongestChain.html){target=\_blank}, in which the chain with the most blocks is selected. - -## FRAME (Framework for Runtime Aggregation of Modularized Entities) - -Enables developers to create blockchain [runtime](#runtime) environments from a modular set of components called [pallets](#pallet). It utilizes a set of procedural macros to construct runtimes. - -[Visit the Polkadot SDK docs for more details on FRAME.](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank} - -## Full Node - -A node that prunes historical states, keeping only recently finalized block states to reduce storage needs. Full nodes provide current chain state access and allow direct submission and validation of [extrinsics](#extrinsic), maintaining network decentralization. - -## Genesis Configuration - -A mechanism for specifying the initial state of a blockchain. By convention, this initial state or first block is commonly referred to as the genesis state or genesis block. The genesis configuration for Polkadot SDK-based chains is accomplished by way of a [chain specification](#chain-specification) file. - -## GRANDPA - -A deterministic finality mechanism for blockchains that is implemented in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. - -The [formal specification](https://github.com/w3f/consensus/blob/master/pdf/grandpa-old.pdf){target=\_blank} is maintained by the [Web3 Foundation](https://web3.foundation/){target=\_blank}. - -## Header - -A structure that aggregates the information used to summarize a block. Primarily, it consists of cryptographic information used by [light clients](#light-client) to get minimally secure but very efficient chain synchronization. - -## Hybrid Consensus - -A blockchain consensus protocol that consists of independent or loosely coupled mechanisms for [block production](#block-author) and finality. - -Hybrid consensus allows the chain to grow as fast as probabilistic consensus protocols, such as [Aura](#authority-round-aura), while maintaining the same level of security as deterministic finality consensus protocols, such as [GRANDPA](#grandpa). - -## Inherent Transactions - -A special type of unsigned transaction, referred to as _inherents_, that enables a block authoring node to insert information that doesn't require validation directly into a block. - -Only the block-authoring node that calls the inherent transaction function can insert data into its block. In general, validators assume the data inserted using an inherent transaction is valid and reasonable even if it can't be deterministically verified. - -## JSON-RPC - -A stateless, lightweight remote procedure call protocol encoded in JavaScript Object Notation (JSON). JSON-RPC provides a standard way to call functions on a remote system by using JSON. - -For Polkadot SDK, this protocol is implemented through the [Parity JSON-RPC](https://github.com/paritytech/jsonrpc){target=\_blank} crate. - -## Keystore - -A subsystem for managing keys for the purpose of producing new blocks. - -## Kusama - -[Kusama](https://kusama.network/){target=\_blank} is a Polkadot SDK-based blockchain that implements a design similar to the [Polkadot](#polkadot) network. - -Kusama is a [canary](https://en.wiktionary.org/wiki/canary_in_a_coal_mine){target=\_blank} network and is referred to as [Polkadot's "wild cousin."](https://wiki.polkadot.com/learn/learn-comparisons-kusama/){target=\_blank}. - -As a canary network, Kusama is expected to be more stable than a test network like [Westend](#westend) but less stable than a production network like [Polkadot](#polkadot). Kusama is controlled by its network participants and is intended to be stable enough to encourage meaningful experimentation. - -## libp2p - -A peer-to-peer networking stack that allows the use of many transport mechanisms, including WebSockets (usable in a web browser). - -Polkadot SDK uses the [Rust implementation](https://github.com/libp2p/rust-libp2p){target=\_blank} of the `libp2p` networking stack. - -## Light Client - -A type of blockchain node that doesn't store the [chain state](#state) or produce blocks. - -A light client can verify cryptographic primitives and provides a [remote procedure call (RPC)](https://en.wikipedia.org/wiki/Remote_procedure_call){target=\_blank} server, enabling blockchain users to interact with the network. - -## Metadata - -Data that provides information about one or more aspects of a system. -The metadata that exposes information about a Polkadot SDK blockchain enables you to interact with that system. - -## Nominated Proof of Stake (NPoS) - -A method for determining [validators](#validator) or _[authorities](#authority)_ based on a willingness to commit their stake to the proper functioning of one or more block-producing nodes. - -## Oracle - -An entity that connects a blockchain to a non-blockchain data source. Oracles enable the blockchain to access and act upon information from existing data sources and incorporate data from non-blockchain systems and services. - -## Origin - -A [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitive that identifies the source of a [dispatched](#dispatchable) function call into the [runtime](#runtime). The FRAME System pallet defines three built-in [origins](#origin). As a [pallet](#pallet) developer, you can also define custom origins, such as those defined by the [Collective pallet](https://paritytech.github.io/substrate/master/pallet_collective/enum.RawOrigin.html){target=\_blank}. -## Pallet - -A module that can be used to extend the capabilities of a [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities)-based [runtime](#runtime). -Pallets bundle domain-specific logic with runtime primitives like [events](#events) and [storage items](#storage-item). - -## Parachain - -A parachain is a blockchain that derives shared infrastructure and security from a _[relay chain](#relay-chain)_. -You can learn more about parachains on the [Polkadot Wiki](https://wiki.polkadot.com/learn/learn-parachains/){target=\_blank}. - -## Paseo - -Paseo TestNet provisions testing on Polkadot's "production" runtime, which means less chance of feature or code mismatch when developing parachain apps. Specifically, after the [Polkadot Technical fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} proposes a runtime upgrade for Polkadot, this TestNet is updated, giving a period where the TestNet will be ahead of Polkadot to allow for testing. - -## Polkadot - -The [Polkadot network](https://polkadot.com/){target=\_blank} is a blockchain that serves as the central hub of a heterogeneous blockchain network. It serves the role of the [relay chain](#relay-chain) and provides shared infrastructure and security to support [parachains](#parachain). - -## Polkadot Cloud - -Polkadot Cloud is a platform for deploying resilient, customizable and scalable Web3 applications through Polkadot's functionality. It encompasses the wider Polkadot network infrastructure and security layer where parachains operate. The platform enables users to launch Ethereum-compatible chains, build specialized blockchains, and flexibly manage computing resources through on-demand or bulk coretime purchases. Initially launched with basic parachain functionality, Polkadot Cloud has evolved to offer enhanced flexibility with features like coretime, elastic scaling, and async backing for improved performance. - -## Polkadot Hub - -Polkadot Hub is a Layer 1 platform that serves as the primary entry point to the Polkadot ecosystem, providing essential functionality without requiring parachain deployment. It offers core services including smart contracts, identity management, staking, governance, and interoperability with other ecosystems, making it simple and fast for both builders and users to get started in Web3. - -## PolkaVM - -PolkaVM is a custom virtual machine optimized for performance, leveraging a RISC-V-based architecture to support Solidity and any language that compiles to RISC-V. It is specifically designed for the Polkadot ecosystem, enabling smart contract deployment and execution. - -## Relay Chain - -Relay chains are blockchains that provide shared infrastructure and security to the [parachains](#parachain) in the network. In addition to providing [consensus](#consensus) capabilities, relay chains allow parachains to communicate and exchange digital assets without needing to trust one another. - -## Rococo - -A [parachain](#parachain) test network for the Polkadot network. The [Rococo](#rococo) network is a Polkadot SDK-based blockchain with an October 14, 2024 deprecation date. Development teams are encouraged to use the Paseo TestNet instead. - -## Runtime - -The runtime represents the [state transition function](#state-transition-function-stf) for a blockchain. In Polkadot SDK, the runtime is stored as a [Wasm](#webassembly-wasm) binary in the chain state. The Runtime is stored under a unique state key and can be modified during the execution of the state transition function. - -## Slot +The message consists of three instructions described as follows: -A fixed, equal interval of time used by consensus engines such as [Aura](#authority-round-aura) and [BABE](#blind-assignment-of-blockchain-extension-babe). In each slot, a subset of [authorities](#authority) is permitted, or obliged, to [author](#block-author) a block. +- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register. -## Sovereign Account + ```rust + WithdrawAsset((Here, amount).into()), + ``` -The unique account identifier for each chain in the relay chain ecosystem. It is often used in cross-consensus (XCM) interactions to sign XCM messages sent to the relay chain or other chains in the ecosystem. + - **`Here`**: The native parachain token. + - **`amount`**: The number of tokens that are transferred. -The sovereign account for each chain is a root-level account that can only be accessed using the Sudo pallet or through governance. The account identifier is calculated by concatenating the Blake2 hash of a specific text string and the registered parachain identifier. + The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register. -## SS58 Address Format +- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\_blank} of the XCM instructions. -A public key address based on the Bitcoin [`Base-58-check`](https://en.bitcoin.it/wiki/Base58Check_encoding){target=\_blank} encoding. Each Polkadot SDK SS58 address uses a `base-58` encoded value to identify a specific account on a specific Polkadot SDK-based chain + ```rust + BuyExecution { + fees: (Here, amount).into(), + weight_limit: WeightLimit::Unlimited + }, + ``` -The [canonical `ss58-registry`](https://github.com/paritytech/ss58-registry){target=\_blank} provides additional details about the address format used by different Polkadot SDK-based chains, including the network prefix and website used for different networks + - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight. + - **`weight_limit`**: Defines the maximum fees that can be used to buy weight. -## State Transition Function (STF) +- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\_blank}**: Moves the remaining tokens from the holding register to Bob’s account. -The logic of a blockchain that determines how the state changes when a block is processed. In Polkadot SDK, the state transition function is effectively equivalent to the [runtime](#runtime). + ```rust + DepositAsset { + assets: All.into(), + beneficiary: MultiLocation { + parents: 0, + interior: Junction::AccountId32 { + network: None, + id: BOB.clone().into() + }.into(), + }.into() + } + ``` -## Storage Item + - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited. + +This step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. -[FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitives that provide type-safe data persistence capabilities to the [runtime](#runtime). -Learn more in the [storage items](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/index.html){target=\_blank} reference document in the Polkadot SDK. +## Overview -## Substrate +XCM revolutionizes cross-chain communication by enabling use cases such as: -A flexible framework for building modular, efficient, and upgradeable blockchains. Substrate is written in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language and is maintained by [Parity Technologies](https://www.parity.io/){target=\_blank}. +- Token transfers between blockchains. +- Asset locking for cross-chain smart contract interactions. +- Remote execution of functions on other blockchains. -## Transaction +These functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. -An [extrinsic](#extrinsic) that includes a signature that can be used to verify the account authorizing it inherently or via [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}. -## Transaction Era +--- -A definable period expressed as a range of block numbers during which a transaction can be included in a block. -Transaction eras are used to protect against transaction replay attacks if an account is reaped and its replay-protecting nonce is reset to zero. +Page Title: Get Tokens from the Official Faucet -## Trie (Patricia Merkle Tree) +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-faucet.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/faucet/ +- Summary: Learn how to obtain test tokens from Polkadot faucets for development and testing purposes across different networks. -A data structure used to represent sets of key-value pairs and enables the items in the data set to be stored and retrieved using a cryptographic hash. Because incremental changes to the data set result in a new hash, retrieving data is efficient even if the data set is very large. With this data structure, you can also prove whether the data set includes any particular key-value pair without access to the entire data set. +# Faucet -In Polkadot SDK-based blockchains, state is stored in a trie data structure that supports the efficient creation of incremental digests. This trie is exposed to the [runtime](#runtime) as [a simple key/value map](#storage-item) where both keys and values can be arbitrary byte arrays. +Test tokens allow you to experiment with smart contracts, test transactions, and validate your dApp functionality without using real cryptocurrency. -## Validator +Polkadot has a faucet that distributes free TestNet tokens to developers for testing purposes: -A validator is a node that participates in the consensus mechanism of the network. Its roles include block production, transaction validation, network integrity, and security maintenance. +- Execute transactions on TestNet networks. +- Pay for gas fees when deploying smart contracts. +- Test dApp functionality before MainNet deployment. +- Experiment with blockchain interactions without financial risk. -## WebAssembly (Wasm) -An execution architecture that allows for the efficient, platform-neutral expression of -deterministic, machine-executable logic. +## Get Test Tokens -[Wasm](https://webassembly.org/){target=\_blank} can be compiled from many languages, including -the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. Polkadot SDK-based chains use a Wasm binary to provide portable [runtimes](#runtime) that can be included as part of the chain's state. +For Polkadot Hub TestNet, you can use the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank} to obtain test tokens. Here's how to do it: -## Weight +1. Navigate to the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. If the desired network is not already selected, choose it from the **Network** drop-down. This example uses the Polkadot Hub TestNet. +2. Copy your address linked to the TestNet and paste it into the designated field. +3. Click the **Get Some PASs** button to request free test PAS tokens. These tokens will be sent to your wallet shortly. -A convention used in Polkadot SDK-based blockchains to measure and manage the time it takes to validate a block. -Polkadot SDK defines one unit of weight as one picosecond of execution time on reference hardware. +![Polkadot Faucet](/images/smart-contracts/faucet/faucet-1.gif) -The maximum block weight should be equivalent to one-third of the target block time with an allocation of one-third each for: +## Things to Consider -- Block construction -- Network propagation -- Import and verification +!!! info "Rate Limiting" + Faucets typically implement rate limiting to prevent abuse. You may need to wait between requests if you've recently obtained tokens from the same faucet. -By defining weights, you can trade-off the number of transactions per second and the hardware required to maintain the target block time appropriate for your use case. Weights are defined in the runtime, meaning you can tune them using runtime updates to keep up with hardware and software improvements. +!!! warning "Network Compatibility" + Ensure your wallet is connected to the correct network (Polkadot Hub TestNet) before requesting tokens. Tokens sent to addresses on different networks will not be accessible. -## Westend +## Using Your Test Tokens -Westend is a Parity-maintained, Polkadot SDK-based blockchain that serves as a test network for the [Polkadot](#polkadot) network. +Getting started with test tokens is the first step in your Polkadot development journey. These free resources enable you to build, experiment with, and refine your applications without financial constraints, ensuring your projects are robust and ready for deployment on MainNet. --- @@ -5138,271 +4190,73 @@ You can use PAPI to build XCM programs and test them with Chopsticks. --- -Page Title: Interoperability +Page Title: JSON-RPC APIs -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-interoperability.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/interoperability/ -- Summary: Explore the importance of interoperability in the Polkadot ecosystem, covering XCM, bridges, and cross-chain communication. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-json-rpc-apis.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/json-rpc-apis/ +- Summary: JSON-RPC APIs guide for Polkadot Hub, covering supported methods, parameters, and examples for interacting with the chain. -# Interoperability +# JSON-RPC APIs +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. ## Introduction -Interoperability lies at the heart of the Polkadot ecosystem, enabling communication and collaboration across a diverse range of blockchains. By bridging the gaps between parachains, relay chains, and even external networks, Polkadot unlocks the potential for truly decentralized applications, efficient resource sharing, and scalable solutions. +Polkadot Hub provides Ethereum compatibility through its JSON-RPC interface, allowing developers to interact with the chain using familiar Ethereum tooling and methods. This document outlines the supported [Ethereum JSON-RPC methods](https://ethereum.org/developers/docs/apis/json-rpc/#json-rpc-methods){target=\_blank} and provides examples of how to use them. -Polkadot’s design ensures that blockchains can transcend their individual limitations by working together as part of a unified system. This cooperative architecture is what sets Polkadot apart in the blockchain landscape. +This guide uses the Polkadot Hub TestNet endpoint: -## Why Interoperability Matters +```text +https://testnet-passet-hub-eth-rpc.polkadot.io +``` -The blockchain ecosystem is inherently fragmented. Different blockchains excel in specialized domains such as finance, gaming, or supply chain management, but these chains function in isolation without interoperability. This lack of connectivity stifles the broader utility of blockchain technology. +## Available Methods -Interoperability solves this problem by enabling blockchains to: +### eth_accounts -- **Collaborate across networks**: Chains can interact to share assets, functionality, and data, creating synergies that amplify their individual strengths. -- **Achieve greater scalability**: Specialized chains can offload tasks to others, optimizing performance and resource utilization. -- **Expand use-case potential**: Cross-chain applications can leverage features from multiple blockchains, unlocking novel user experiences and solutions. +Returns a list of addresses owned by the client. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_accounts){target=\_blank}. -In the Polkadot ecosystem, interoperability transforms a collection of isolated chains into a cohesive, efficient network, pushing the boundaries of what blockchains can achieve together. +**Parameters**: -## Key Mechanisms for Interoperability +None. -At the core of Polkadot's cross-chain collaboration are foundational technologies designed to break down barriers between networks. These mechanisms empower blockchains to communicate, share resources, and operate as a cohesive ecosystem. +**Example**: -### Cross-Consensus Messaging (XCM): The Backbone of Communication +```bash title="eth_accounts" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_accounts", + "params":[], + "id":1 +}' +``` -Polkadot's Cross-Consensus Messaging (XCM) is the standard framework for interaction between parachains, relay chains, and, eventually, external blockchains. XCM provides a trustless, secure messaging format for exchanging assets, sharing data, and executing cross-chain operations. +--- -Through XCM, decentralized applications can: +### eth_blockNumber -- Transfer tokens and other assets across chains. -- Coordinate complex workflows that span multiple blockchains. -- Enable seamless user experiences where underlying blockchain differences are invisible. -- XCM exemplifies Polkadot’s commitment to creating a robust and interoperable ecosystem. +Returns the number of the most recent block. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_blocknumber){target=\_blank}. -For further information about XCM, check the [Introduction to XCM](/parachains/interoperability/get-started/){target=\_blank} article. +**Parameters**: -### Bridges: Connecting External Networks +None. -While XCM enables interoperability within the Polkadot ecosystem, bridges extend this functionality to external blockchains such as Ethereum and Bitcoin. By connecting these networks, bridges allow Polkadot-based chains to access external liquidity, additional functionalities, and broader user bases. +**Example**: -With bridges, developers and users gain the ability to: +```bash title="eth_blockNumber" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_blockNumber", + "params":[], + "id":1 +}' +``` -- Integrate external assets into Polkadot-based applications. -- Combine the strengths of Polkadot’s scalability with the liquidity of other networks. -- Facilitate accurate multi-chain applications that transcend ecosystem boundaries. - -For more information about bridges in the Polkadot ecosystem, see the [Bridge Hub](/reference/polkadot-hub/bridging/){target=\_blank} guide. - -## The Polkadot Advantage - -Polkadot was purpose-built for interoperability. Unlike networks that add interoperability as an afterthought, Polkadot integrates it as a fundamental design principle. This approach offers several distinct advantages: - -- **Developer empowerment**: Polkadot’s interoperability tools allow developers to build applications that leverage multiple chains’ capabilities without added complexity. -- **Enhanced ecosystem collaboration**: Chains in Polkadot can focus on their unique strengths while contributing to the ecosystem’s overall growth. -- **Future-proofing blockchain**: By enabling seamless communication, Polkadot ensures its ecosystem can adapt to evolving demands and technologies. - -## Looking Ahead - -Polkadot’s vision of interoperability extends beyond technical functionality, representing a shift towards a more collaborative blockchain landscape. By enabling chains to work together, Polkadot fosters innovation, efficiency, and accessibility, paving the way for a decentralized future where blockchains are not isolated competitors but interconnected collaborators. - - ---- - -Page Title: Introduction to XCM - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md -- Canonical (HTML): https://docs.polkadot.com/parachains/interoperability/get-started/ -- Summary: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. - -# Introduction to XCM - -## Introduction - -Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems. - -With XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation. - -## Messaging Format - -XCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics. - -XCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing. - -## The Four Principles of XCM - -XCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems: - -- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes. -- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended. -- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin. -- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems. - -These principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments. - -## The XCM Tech Stack - -![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp) - -The XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels. - -## Core Functionalities of XCM - -XCM enhances cross-consensus communication by introducing several powerful features: - -- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management. -- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification. -- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location. - -The standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications. - -## XCM Example - -The following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA). - -```rust -let message = Xcm(vec![ - WithdrawAsset((Here, amount).into()), - BuyExecution { - fees: (Here, amount).into(), - weight_limit: WeightLimit::Unlimited - }, - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: Junction::AccountId32 { - network: None, - id: BOB.clone().into() - }.into(), - }.into() - } -]); -``` - -The message consists of three instructions described as follows: - -- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register. - - ```rust - WithdrawAsset((Here, amount).into()), - ``` - - - **`Here`**: The native parachain token. - - **`amount`**: The number of tokens that are transferred. - - The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register. - -- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\_blank} of the XCM instructions. - - ```rust - BuyExecution { - fees: (Here, amount).into(), - weight_limit: WeightLimit::Unlimited - }, - ``` - - - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight. - - **`weight_limit`**: Defines the maximum fees that can be used to buy weight. - -- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\_blank}**: Moves the remaining tokens from the holding register to Bob’s account. - - ```rust - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: Junction::AccountId32 { - network: None, - id: BOB.clone().into() - }.into(), - }.into() - } - ``` - - - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited. - -This step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - -## Overview - -XCM revolutionizes cross-chain communication by enabling use cases such as: - -- Token transfers between blockchains. -- Asset locking for cross-chain smart contract interactions. -- Remote execution of functions on other blockchains. - -These functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - - ---- - -Page Title: JSON-RPC APIs - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-json-rpc-apis.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/json-rpc-apis/ -- Summary: JSON-RPC APIs guide for Polkadot Hub, covering supported methods, parameters, and examples for interacting with the chain. - -# JSON-RPC APIs - -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction - -Polkadot Hub provides Ethereum compatibility through its JSON-RPC interface, allowing developers to interact with the chain using familiar Ethereum tooling and methods. This document outlines the supported [Ethereum JSON-RPC methods](https://ethereum.org/developers/docs/apis/json-rpc/#json-rpc-methods){target=\_blank} and provides examples of how to use them. - -This guide uses the Polkadot Hub TestNet endpoint: - -```text -https://testnet-passet-hub-eth-rpc.polkadot.io -``` - -## Available Methods - -### eth_accounts - -Returns a list of addresses owned by the client. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_accounts){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_accounts" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_accounts", - "params":[], - "id":1 -}' -``` - ---- - -### eth_blockNumber - -Returns the number of the most recent block. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_blocknumber){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_blockNumber" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_blockNumber", - "params":[], - "id":1 -}' -``` - ---- +--- ### eth_call @@ -6496,376 +5350,84 @@ Your existing Solidity knowledge and tooling transfer directly to Polkadot Hub, --- -Page Title: Networks +Page Title: Overview of FRAME -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-networks.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/networks/ -- Summary: Explore Polkadot's testing and production networks, including Westend, Kusama, and Paseo, for efficient development, deployment, and testing. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime.md +- Canonical (HTML): https://docs.polkadot.com/parachains/customize-runtime/ +- Summary: Learn how Polkadot SDK’s FRAME framework simplifies blockchain development with modular pallets and support libraries for efficient runtime design. -# Networks +# Customize Your Runtime ## Introduction -The Polkadot ecosystem is built on a robust set of networks designed to enable secure and scalable development. Whether you are testing new features or deploying to live production, Polkadot offers several layers of networks tailored for each stage of the development process. From local environments to experimental networks like Kusama and community-run TestNets such as Paseo, developers can thoroughly test, iterate, and validate their applications. This guide will introduce you to Polkadot's various networks and explain how they fit into the development workflow. - -## Network Overview +A blockchain runtime is more than just a fixed set of rules—it's a dynamic foundation that you can shape to match your specific needs. With Polkadot SDK's [FRAME (Framework for Runtime Aggregation of Modularized Entities)](/reference/glossary/#frame-framework-for-runtime-aggregation-of-modularized-entities){target=\_blank}, customizing your runtime is straightforward and modular. Instead of building everything from scratch, you combine pre-built pallets with your own custom logic to create a runtime suited to your blockchain's purpose. -Polkadot's development process is structured to ensure new features and upgrades are rigorously tested before being deployed on live production networks. The progression follows a well-defined path, starting from local environments and advancing through TestNets, ultimately reaching the Polkadot MainNet. The diagram below outlines the typical progression of the Polkadot development cycle: +This overview explains how runtime customization works, introduces the building blocks you'll use, and guides you through the key patterns for extending your runtime. -``` mermaid -flowchart LR - id1[Local] --> id2[Westend] --> id4[Kusama] --> id5[Polkadot] - id1[Local] --> id3[Paseo] --> id5[Polkadot] -``` +## Understanding Your Runtime -This flow ensures developers can thoroughly test and iterate without risking real tokens or affecting production networks. Testing tools like [Chopsticks](#chopsticks) and various TestNets make it easier to experiment safely before releasing to production. +The runtime is the core logic of your blockchain—it processes transactions, manages state, and enforces the rules that govern your network. When a transaction arrives at your blockchain, the [`frame_executive`](https://paritytech.github.io/polkadot-sdk/master/frame_executive/index.html){target=\_blank} pallet receives it and routes it to the appropriate pallet for execution. -A typical journey through the Polkadot core protocol development process might look like this: +Think of your runtime as a collection of specialized modules, each handling a different aspect of your blockchain. Need token balances? Use the Balances pallet. Want governance? Add the Governance pallets. Need something custom? Create your own pallet. By mixing and matching these modules, you build a runtime that's efficient, secure, and tailored to your use case. -1. **Local development node**: Development starts in a local environment, where developers can create, test, and iterate on upgrades or new features using a local development node. This stage allows rapid experimentation in an isolated setup without any external dependencies. +## Runtime Architecture -2. **Westend**: After testing locally, upgrades are deployed to [Westend](#westend), Polkadot's primary TestNet. Westend simulates real-world conditions without using real tokens, making it the ideal place for rigorous feature testing before moving on to production networks. +The following diagram shows how FRAME components work together to form your runtime: -3. **Kusama**: Once features have passed extensive testing on Westend, they move to Kusama, Polkadot's experimental and fast-moving "canary" network. Kusama operates as a high-fidelity testing ground with actual economic incentives, giving developers insights into how their features will perform in a real-world environment. +![](/images/parachains/customize-runtime/index/frame-overview-01.webp) -4. **Polkadot**: After passing tests on Westend and Kusama, features are considered ready for deployment to Polkadot, the live production network. +The main components are: - In addition, parachain developers can leverage local TestNets like [Zombienet](#zombienet) and deploy upgrades on parachain TestNets. +- **`frame_executive`**: Routes all incoming transactions to the correct pallet for execution. +- **Pallets**: Domain-specific modules that implement your blockchain's features and business logic. +- **`frame_system`**: Provides core runtime primitives and storage. +- **`frame_support`**: Utilities and macros that simplify pallet development. -5. **Paseo**: For parachain and dApp developers, Paseo serves as a community-run TestNet that mirrors Polkadot's runtime. Like Westend for core protocol development, Paseo provides a testing ground for parachain development without affecting live networks. +## Building Blocks: Pallets -!!!note - The Rococo TestNet deprecation date was October 14, 2024. Teams should use Westend for Polkadot protocol and feature testing and Paseo for chain development-related testing. +[Pallets](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/pallet/index.html){target=\_blank} are the fundamental units of runtime customization. Each pallet encapsulates specific functionality and can be independently developed, tested, and integrated. -## Polkadot Development Networks +A pallet can implement virtually any blockchain feature you need: -Development and testing are crucial to building robust dApps and parachains and performing network upgrades within the Polkadot ecosystem. To achieve this, developers can leverage various networks and tools that provide a risk-free environment for experimentation and validation before deploying features to live networks. These networks help avoid the costs and risks associated with real tokens, enabling testing for functionalities like governance, cross-chain messaging, and runtime upgrades. +- Expose new transactions that users can submit. +- Store data on-chain. +- Enforce business rules and validation logic. +- Emit events to notify users of state changes. +- Handle errors gracefully. -## Kusama Network +### Pre-Built Pallets vs. Custom Pallets -Kusama is the experimental version of Polkadot, designed for developers who want to move quickly and test their applications in a real-world environment with economic incentives. Kusama serves as a production-grade testing ground where developers can deploy features and upgrades with the pressure of game theory and economics in mind. It mirrors Polkadot but operates as a more flexible space for innovation. +FRAME provides a comprehensive library of [pre-built pallets](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame){target=\_blank} for common blockchain features, including consensus, staking, balances, governance, and more. These pallets are battle-tested, optimized, and ready to use. -The native token for Kusama is KSM. For more information about KSM, visit the [Native Assets](https://wiki.polkadot.com/kusama/kusama-getting-started/){target=\_blank} page. +However, you're not limited to pre-built functionality. When pre-built pallets don't meet your needs, you can create custom pallets with entirely custom logic. The real power of FRAME is the flexibility to use pre-built modules for standard features while building your own for unique requirements. -## Test Networks +### Pallet Structure -The following test networks provide controlled environments for testing upgrades and new features. TestNet tokens are available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}. +FRAME uses Rust macros extensively, allowing you to focus on your pallet's logic while the framework handles boilerplate and integration code. -### Westend +A typical pallet looks like this: -Westend is Polkadot's primary permanent TestNet. Unlike temporary test networks, Westend is not reset to the genesis block, making it an ongoing environment for testing Polkadot core features. Managed by Parity Technologies, Westend ensures that developers can test features in a real-world simulation without using actual tokens. +```rust +pub use pallet::*; -The native token for Westend is WND. More details about WND can be found on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_2){target=\_blank} page. +#[frame_support::pallet] +pub mod pallet { + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; -### Paseo + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(_); -[Paseo](https://github.com/paseo-network){target=\_blank} is a community-managed TestNet designed for parachain and dApp developers. It mirrors Polkadot's runtime and is maintained by Polkadot community members. Paseo provides a dedicated space for parachain developers to test their applications in a Polkadot-like environment without the risks associated with live networks. + #[pallet::config] // snip + #[pallet::event] // snip + #[pallet::error] // snip + #[pallet::storage] // snip + #[pallet::call] // snip +} +``` -The native token for Paseo is PAS. Additional information on PAS is available on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_1){target=\_blank} page. - -## Local Test Networks - -Local test networks are an essential part of the development cycle for blockchain developers using the Polkadot SDK. They allow for fast, iterative testing in controlled, private environments without connecting to public TestNets. Developers can quickly spin up local instances to experiment, debug, and validate their code before deploying to larger TestNets like Westend or Paseo. Two key tools for local network testing are Zombienet and Chopsticks. - -### Zombienet - -[Zombienet](https://github.com/paritytech/zombienet){target=\_blank} is a flexible testing framework for Polkadot SDK-based blockchains. It enables developers to create and manage ephemeral, short-lived networks. This feature makes Zombienet particularly useful for quick iterations, as it allows you to run multiple local networks concurrently, mimicking different runtime conditions. Whether you're developing a parachain or testing your custom blockchain logic, Zombienet gives you the tools to automate local testing. - -Key features of Zombienet include: - -- Creating dynamic, local networks with different configurations. -- Running parachains and relay chains in a simulated environment. -- Efficient testing of network components like cross-chain messaging and governance. - -Zombienet is ideal for developers looking to test quickly and thoroughly before moving to more resource-intensive public TestNets. - -### Chopsticks - -[Chopsticks](https://github.com/AcalaNetwork/chopsticks){target=\_blank} is a tool designed to create forks of Polkadot SDK-based blockchains, allowing developers to interact with network forks as part of their testing process. This capability makes Chopsticks a powerful option for testing upgrades, runtime changes, or cross-chain applications in a forked network environment. - -Key features of Chopsticks include: - -- Forking live Polkadot SDK-based blockchains for isolated testing. -- Simulating cross-chain messages in a private, controlled setup. -- Debugging network behavior by interacting with the fork in real-time. - -Chopsticks provides a controlled environment for developers to safely explore the effects of runtime changes. It ensures that network behavior is tested and verified before upgrades are deployed to live networks. - - ---- - -Page Title: Node and Runtime - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-node-and-runtime.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/node-and-runtime/ -- Summary: Learn how Polkadot SDK-based nodes function, how the client and runtime are separated, and how they communicate using SCALE-encoded data. - -# Node and Runtime - -## Introduction - -Every blockchain platform relies on a decentralized network of computers, called nodes, that communicate with each other about transactions and blocks. In this context, a node refers to the software running on the connected devices rather than the physical or virtual machines in the network. - -Polkadot SDK-based nodes consist of two main components, each with distinct responsibilities: the client (also called node) and the runtime. - -If the system were a monolithic protocol, any modification would require updating the entire system. Instead, Polkadot achieves true upgradeability by defining an immutable meta-protocol (the client) and a protocol (the runtime) that can be upgraded independently. - -This separation gives the [Polkadot Relay Chain](/polkadot-protocol/architecture/polkadot-chain){target=\_blank} and all connected [parachains](/polkadot-protocol/architecture/parachains){target=\_blank} an evolutionary advantage over other blockchain platforms. - -## Architectural Principles - -The Polkadot SDK-based blockchain architecture is fundamentally built on two distinct yet interconnected components: - -- Client (Meta-protocol): - - Handles the foundational infrastructure of the blockchain. - - Manages runtime execution, networking, consensus, and other off-chain components. - - Provides an immutable base layer that ensures network stability. - - Upgradable only through hard forks. - -- Runtime (Protocol): - - Defines the blockchain's state transition logic. - - Determines the specific rules and behaviors of the blockchain. - - Compiled to WebAssembly (Wasm) for platform-independent execution. - - Capable of being upgraded without network-wide forking. - -### Advantages of this Architecture - -- **Forkless upgrades**: Runtime can be updated without disrupting the entire network. -- **Modularity**: Clear separation allows independent development of client and runtime. -- **Flexibility**: Enables rapid iteration and evolution of blockchain logic. -- **Performance**: WebAssembly compilation provides efficient, cross-platform execution. - -## Node (Client) - -The node, also known as the client, is the core component responsible for executing the Wasm runtime and orchestrating various essential blockchain components. It ensures the correct execution of the state transition function and manages multiple critical subsystems, including: - -- **Wasm execution**: Runs the blockchain runtime, which defines the state transition rules. -- **Database management**: Stores blockchain data. -- **Networking**: Facilitates peer-to-peer communication, block propagation, and transaction gossiping. -- **Transaction pool (Mempool)**: Manages pending transactions before they are included in a block. -- **Consensus mechanism**: Ensures agreement on the blockchain state across nodes. -- **RPC services**: Provides external interfaces for applications and users to interact with the node. - -## Runtime - -The runtime is more than just a set of rules. It's the fundamental logic engine that defines a blockchain's entire behavior. In Polkadot SDK-based blockchains, the runtime represents a complete, self-contained description of the blockchain's state transition function. - -### Characteristics - -The runtime is distinguished by three key characteristics: - -- **Business logic**: Defines the complete application-specific blockchain behavior. -- **WebAssembly compilation**: Ensures platform-independent, secure execution. -- **On-chain storage**: Stored within the blockchain's state, allowing dynamic updates. - -### Key Functions - -The runtime performs several critical functions, such as: - -- Define state transition rules. -- Implement blockchain-specific logic. -- Manage account interactions. -- Control transaction processing. -- Define governance mechanisms. -- Handle custom pallets and modules. - -## Communication Between Node and Runtime - -The client and runtime communicate exclusively using [SCALE-encoded](/polkadot-protocol/parachain-basics/data-encoding){target=\_blank} communication. This ensures efficient and compact data exchange between the two components. - -### Runtime APIs - -The Runtime API consists of well-defined functions and constants a client assumes are implemented in the Runtime Wasm blob. These APIs enable the client to interact with the runtime to execute blockchain operations and retrieve information. The client invokes these APIs to: - -- Build, execute, and finalize blocks. -- Access metadata. -- Access consensus related information. -- Handle transaction execution. - -### Host Functions - -During execution, the runtime can access certain external client functionalities via host functions. The specific functions the client exposes allow the runtime to perform operations outside the WebAssembly domain. Host functions enable the runtime to: - -- Perform cryptographic operations. -- Access the current blockchain state. -- Handle storage modifications. -- Allocate memory. - - ---- - -Page Title: On-Chain Governance Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-governance.md -- Canonical (HTML): https://docs.polkadot.com/reference/governance/ -- Summary: Discover Polkadot’s cutting-edge OpenGov system, enabling transparent, decentralized decision-making through direct democracy and flexible governance tracks. - -# On-Chain Governance - -## Introduction - -Polkadot’s governance system exemplifies decentralized decision-making, empowering its community of stakeholders to shape the network’s future through active participation. The latest evolution, OpenGov, builds on Polkadot’s foundation by providing a more inclusive and efficient governance model. - -This guide will explain the principles and structure of OpenGov and walk you through its key components, such as Origins, Tracks, and Delegation. You will learn about improvements over earlier governance systems, including streamlined voting processes and enhanced stakeholder participation. - -With OpenGov, Polkadot achieves a flexible, scalable, and democratic governance framework that allows multiple proposals to proceed simultaneously, ensuring the network evolves in alignment with its community's needs. - -## Governance Evolution - -Polkadot’s governance journey began with [Governance V1](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#governance-summary){target=\_blank}, a system that proved effective in managing treasury funds and protocol upgrades. However, it faced limitations, such as: - -- Slow voting cycles, causing delays in decision-making. -- Inflexibility in handling multiple referendums, restricting scalability. - -To address these challenges, Polkadot introduced OpenGov, a governance model designed for greater inclusivity, efficiency, and scalability. OpenGov replaces the centralized structures of Governance V1, such as the Council and Technical Committee, with a fully decentralized and dynamic framework. - -For a full comparison of the historic and current governance models, visit the [Gov1 vs. Polkadot OpenGov](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#gov1-vs-polkadot-opengov){target=\_blank} section of the Polkadot Wiki. - -## OpenGov Key Features - -OpenGov transforms Polkadot’s governance into a decentralized, stakeholder-driven model, eliminating centralized decision-making bodies like the Council. Key enhancements include: - -- **Decentralization**: Shifts all decision-making power to the public, ensuring a more democratic process. -- **Enhanced delegation**: Allows users to delegate their votes to trusted experts across specific governance tracks. -- **Simultaneous referendums**: Multiple proposals can progress at once, enabling faster decision-making. -- **Polkadot Technical Fellowship**: A broad, community-driven group replacing the centralized Technical Committee. - -This new system ensures Polkadot governance remains agile and inclusive, even as the ecosystem grows. - -## Origins and Tracks - -In OpenGov, origins and tracks are central to managing proposals and votes. - -- **Origin**: Determines the authority level of a proposal (e.g., Treasury, Root) which decides the track of all referendums from that origin. -- **Track**: Define the procedural flow of a proposal, such as voting duration, approval thresholds, and enactment timelines. - -Developers must be aware that referendums from different origins and tracks will take varying amounts of time to reach approval and enactment. The [Polkadot Technical Fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} has the option to shorten this timeline by whitelisting a proposal and allowing it to be enacted through the [Whitelist Caller](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#whitelisted-caller){target=\_blank} origin. - -Visit [Origins and Tracks Info](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#origins-and-tracks){target=\_blank} for details on current origins and tracks, associated terminology, and parameters. - -## Referendums - -In OpenGov, anyone can submit a referendum, fostering an open and participatory system. The timeline for a referendum depends on the privilege level of the origin with more significant changes offering more time for community voting and participation before enactment. - -The timeline for an individual referendum includes four distinct periods: - -- **Lead-in**: A minimum amount of time to allow for community participation, available room in the origin, and payment of the decision deposit. Voting is open during this period. -- **Decision**: Voting continues. -- **Confirmation**: Referendum must meet [approval and support](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#approval-and-support){target=\_blank} criteria during entire period to avoid rejection. -- **Enactment**: Changes approved by the referendum are executed. - -### Vote on Referendums - -Voters can vote with their tokens on each referendum. Polkadot uses a voluntary token locking mechanism, called conviction voting, as a way for voters to increase their voting power. A token holder signals they have a stronger preference for approving a proposal based upon their willingness to lock up tokens. Longer voluntary token locks are seen as a signal of continual approval and translate to increased voting weight. - -See [Voting on a Referendum](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank} for a deeper look at conviction voting and related token locks. - -### Delegate Voting Power - -The OpenGov system also supports multi-role delegations, allowing token holders to assign their voting power on different tracks to entities with expertise in those areas. - -For example, if a token holder lacks the technical knowledge to evaluate proposals on the [Root track](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#root){target=\_blank}, they can delegate their voting power for that track to an expert they trust to vote in the best interest of the network. This ensures informed decision-making across tracks while maintaining flexibility for token holders. - -Visit [Multirole Delegation](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#multirole-delegation){target=\_blank} for more details on delegating voting power. - -### Cancel a Referendum - -Polkadot OpenGov has two origins for rejecting ongoing referendums: - -- [**Referendum Canceller**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-canceller){target=\_blank}: Cancels an active referendum when non-malicious errors occur and refunds the deposits to the originators. -- [**Referendum Killer**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-killer){target=\_blank}: Used for urgent, malicious cases this origin instantly terminates an active referendum and slashes deposits. - -See [Cancelling, Killing, and Blacklisting](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#cancelling-killing--blacklisting){target=\_blank} for additional information on rejecting referendums. - -## Additional Resources - -- **[Democracy pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/democracy/src){target=\_blank}**: Handles administration of general stakeholder voting. -- **[Gov2: Polkadot’s Next Generation of Decentralised Governance](https://medium.com/polkadot-network/gov2-polkadots-next-generation-of-decentralised-governance-4d9ef657d11b){target=\_blank}**: Medium article by Gavin Wood. -- **[Polkadot Direction](https://matrix.to/#/#Polkadot-Direction:parity.io){target=\_blank}**: Matrix Element client. -- **[Polkassembly](https://polkadot.polkassembly.io/){target=\_blank}**: OpenGov dashboard and UI. -- **[Polkadot.js Apps Governance](https://polkadot.js.org/apps/#/referenda){target=\_blank}**: Overview of active referendums. - - ---- - -Page Title: Overview of FRAME - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime.md -- Canonical (HTML): https://docs.polkadot.com/parachains/customize-runtime/ -- Summary: Learn how Polkadot SDK’s FRAME framework simplifies blockchain development with modular pallets and support libraries for efficient runtime design. - -# Customize Your Runtime - -## Introduction - -A blockchain runtime is more than just a fixed set of rules—it's a dynamic foundation that you can shape to match your specific needs. With Polkadot SDK's [FRAME (Framework for Runtime Aggregation of Modularized Entities)](/reference/glossary/#frame-framework-for-runtime-aggregation-of-modularized-entities){target=\_blank}, customizing your runtime is straightforward and modular. Instead of building everything from scratch, you combine pre-built pallets with your own custom logic to create a runtime suited to your blockchain's purpose. - -This overview explains how runtime customization works, introduces the building blocks you'll use, and guides you through the key patterns for extending your runtime. - -## Understanding Your Runtime - -The runtime is the core logic of your blockchain—it processes transactions, manages state, and enforces the rules that govern your network. When a transaction arrives at your blockchain, the [`frame_executive`](https://paritytech.github.io/polkadot-sdk/master/frame_executive/index.html){target=\_blank} pallet receives it and routes it to the appropriate pallet for execution. - -Think of your runtime as a collection of specialized modules, each handling a different aspect of your blockchain. Need token balances? Use the Balances pallet. Want governance? Add the Governance pallets. Need something custom? Create your own pallet. By mixing and matching these modules, you build a runtime that's efficient, secure, and tailored to your use case. - -## Runtime Architecture - -The following diagram shows how FRAME components work together to form your runtime: - -![](/images/parachains/customize-runtime/index/frame-overview-01.webp) - -The main components are: - -- **`frame_executive`**: Routes all incoming transactions to the correct pallet for execution. -- **Pallets**: Domain-specific modules that implement your blockchain's features and business logic. -- **`frame_system`**: Provides core runtime primitives and storage. -- **`frame_support`**: Utilities and macros that simplify pallet development. - -## Building Blocks: Pallets - -[Pallets](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/pallet/index.html){target=\_blank} are the fundamental units of runtime customization. Each pallet encapsulates specific functionality and can be independently developed, tested, and integrated. - -A pallet can implement virtually any blockchain feature you need: - -- Expose new transactions that users can submit. -- Store data on-chain. -- Enforce business rules and validation logic. -- Emit events to notify users of state changes. -- Handle errors gracefully. - -### Pre-Built Pallets vs. Custom Pallets - -FRAME provides a comprehensive library of [pre-built pallets](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame){target=\_blank} for common blockchain features, including consensus, staking, balances, governance, and more. These pallets are battle-tested, optimized, and ready to use. - -However, you're not limited to pre-built functionality. When pre-built pallets don't meet your needs, you can create custom pallets with entirely custom logic. The real power of FRAME is the flexibility to use pre-built modules for standard features while building your own for unique requirements. - -### Pallet Structure - -FRAME uses Rust macros extensively, allowing you to focus on your pallet's logic while the framework handles boilerplate and integration code. - -A typical pallet looks like this: - -```rust -pub use pallet::*; - -#[frame_support::pallet] -pub mod pallet { - use frame_support::pallet_prelude::*; - use frame_system::pallet_prelude::*; - - #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] - pub struct Pallet(_); - - #[pallet::config] // snip - #[pallet::event] // snip - #[pallet::error] // snip - #[pallet::storage] // snip - #[pallet::call] // snip -} -``` - -Every pallet can implement these core macros: +Every pallet can implement these core macros: - **`#[frame_support::pallet]`**: Marks your module as a FRAME pallet. - **`#[pallet::pallet]`**: Designates the struct that holds pallet metadata. @@ -6879,967 +5441,45 @@ For a comprehensive reference, see the [`pallet_macros` documentation](https://p ## How Runtime Customization Works -Customizing your runtime typically follows these patterns: - -**Adding Pre-Built Pallets**: Select pallets from the FRAME library and integrate them into your runtime configuration. This is the fastest way to add functionality. - -**Creating Custom Pallets**: Write custom pallets for features that don't exist in the pre-built library. Custom pallets follow the same structure as pre-built ones and integrate seamlessly. - -**Combining Multiple Pallets**: Layer multiple pallets together to create complex behaviors. Pallets can call each other and share storage when needed. - -**Configuring Pallet Parameters**: Most pallets are configurable—you can adjust their behavior through configuration traits without modifying their code. - -The following diagram illustrates how pallets combine to form a complete runtime: - -![](/images/parachains/customize-runtime/index/frame-overview-02.webp) - -## Starting Templates - -The easiest way to begin customizing your runtime is with a starter template. These templates provide a pre-configured foundation so you can focus on customization rather than setup. - -- **[Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank}**: The recommended choice for most developers, it includes pre-configured pallets for common features (balances, block production, governance), a complete runtime setup, and built-in parachain consensus support. This template offers the best balance of features and learning opportunities. - -- **[Polkadot SDK Minimal Template](https://github.com/paritytech/polkadot-sdk-minimal-template){target=\_blank}**: Provides a bare-bones runtime with only essential components. Choose this if you want maximum flexibility and prefer building from a clean slate. - -- **[Polkadot SDK Solochain Template](https://github.com/paritytech/polkadot-sdk/tree/master/templates/solochain){target=\_blank}**: Designed for building standalone blockchains with moderate features, simple consensus, and several core pallets. Use this if you want a sovereign blockchain independent of a relay chain. - -- **[OpenZeppelin Runtime Templates](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\_blank}**: Provides security-focused configurations following industry best practices. The [generic-template](https://github.com/OpenZeppelin/polkadot-runtime-templates/tree/main/generic-template){target=\_blank} includes curated pallet selections and production-ready defaults—ideal if security is your top priority. - -## Key Customization Scenarios - -This section covers the most common customization patterns you'll encounter: - -- **[Add Existing Pallets to Your Runtime](/parachains/customize-runtime/add-existing-pallets/)**: Integrate pre-built pallets from the FRAME library with minimal configuration. - -- **[Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/)**: Run multiple instances of the same pallet with different configurations—useful for multi-token systems or parallel features. - -- **[Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/)**: Enable smart contract execution on your parachain using Contracts pallets. - -- **[Create Custom Pallets](/parachains/customize-runtime/pallet-development/create-a-pallet/)**: Build entirely custom pallets for features unique to your blockchain. - -- **[Test Your Runtime](/parachains/customize-runtime/pallet-development/pallet-testing/)**: Unit test pallets and mock complete runtimes to ensure everything works correctly. - - ---- - -Page Title: Overview of the Polkadot Relay Chain - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-relay-chain.md -- Canonical (HTML): https://docs.polkadot.com/reference/polkadot-hub/consensus-and-security/relay-chain/ -- Summary: Explore Polkadot's core architecture, including its multi-chain vision, shared security, and the DOT token's governance and staking roles. - -# Overview - -## Introduction - -Polkadot is a next-generation blockchain protocol designed to support a multi-chain future by enabling secure communication and interoperability between different blockchains. Built as a Layer-0 protocol, Polkadot introduces innovations like application-specific Layer-1 chains ([parachains](/polkadot-protocol/architecture/parachains/){targe=\_blank}), shared security through [Nominated Proof of Stake (NPoS)](/reference/glossary/#nominated-proof-of-stake-npos){target=\_blank}, and cross-chain interactions via its native [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank}. - -This guide covers key aspects of Polkadot’s architecture, including its high-level protocol structure, blockspace commoditization, and the role of its native token, DOT, in governance, staking, and resource allocation. - -## Polkadot 1.0 - -Polkadot 1.0 represents the state of Polkadot as of 2023, coinciding with the release of [Polkadot runtime v1.0.0](https://github.com/paritytech/polkadot/releases/tag/v1.0.0){target=\_blank}. This section will focus on Polkadot 1.0, along with philosophical insights into network resilience and blockspace. - -As a Layer-0 blockchain, Polkadot contributes to the multi-chain vision through several key innovations and initiatives, including: - -- **Application-specific Layer-1 blockchains (parachains)**: Polkadot's sharded network allows for parallel transaction processing, with shards that can have unique state transition functions, enabling custom-built L1 chains optimized for specific applications. - -- **Shared security and scalability**: L1 chains connected to Polkadot benefit from its [Nominated Proof of Stake (NPoS)](/reference/polkadot-hub/consensus-and-security/pos-consensus/#nominated-proof-of-stake){target=\_blank} system, providing security out-of-the-box without the need to bootstrap their own. - -- **Secure interoperability**: Polkadot's native interoperability enables seamless data and value exchange between parachains. This interoperability can also be used outside of the ecosystem for bridging with external networks. - -- **Resilient infrastructure**: Decentralized and scalable, Polkadot ensures ongoing support for development and community initiatives via its on-chain [treasury](https://wiki.polkadot.com/learn/learn-polkadot-opengov-treasury/){target=\_blank} and governance. - -- **Rapid L1 development**: The [Polkadot SDK](/reference/parachains/){target=\_blank} allows fast, flexible creation and deployment of Layer-1 chains. - -- **Cultivating the next generation of Web3 developers**: Polkadot supports the growth of Web3 core developers through initiatives such as. - - - [Polkadot Blockchain Academy](https://polkadot.com/blockchain-academy){target=\_blank} - - [EdX courses](https://www.edx.org/school/web3x){target=\_blank} - - Rust and Substrate courses (coming soon) - -### High-Level Architecture - -Polkadot features a chain that serves as the central component of the system. This chain is depicted as a ring encircled by several parachains that are connected to it. - -According to Polkadot's design, any blockchain that can compile to WebAssembly (Wasm) and adheres to the Parachains Protocol becomes a parachain on the Polkadot network. - -Here’s a high-level overview of the Polkadot protocol architecture: - -![](/images/reference/polkadot-hub/consensus-and-security/relay-chain/relay-chain-01.webp){ style="background:white" } - -Parachains propose blocks to Polkadot validators, who check for availability and validity before finalizing them. With the relay chain providing security, collators—full nodes of parachains—can focus on their tasks without needing strong incentives. - -The [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank} allows parachains to exchange messages freely, leveraging the chain's security for trust-free communication. - -In order to interact with chains that want to use their own finalization process (e.g., Bitcoin), Polkadot has [bridges](/reference/parachains/interoperability/#bridges-connecting-external-networks){target=\_blank} that offer two-way compatibility, meaning that transactions can be made between different parachains. - -### Polkadot's Additional Functionalities - -Historically, obtaining core slots on Polkadot chain relied upon crowdloans and auctions. Chain cores were leased through auctions for three-month periods, up to a maximum of two years. Crowdloans enabled users to securely lend funds to teams for lease deposits in exchange for pre-sale tokens, which is the only way to access slots on Polkadot 1.0. Auctions are now deprecated in favor of [coretime](/polkadot-protocol/architecture/system-chains/coretime/){target=\_blank}. - -Additionally, the chain handles [staking](https://wiki.polkadot.com/learn/learn-staking/){target=\_blank}, [accounts](/reference/parachains/accounts/){target=\_blank}, balances, and [governance](/reference/governance/){target=\_blank}. - -#### Agile Coretime - -The new and more efficient way of obtaining core on Polkadot is to go through the process of purchasing coretime. - -[Agile coretime](/reference/polkadot-hub/consensus-and-security/agile-coretime/){target=\_blank} improves the efficient use of Polkadot's network resources and offers economic flexibility for developers, extending Polkadot's capabilities far beyond the original vision outlined in the [whitepaper](https://polkadot.com/papers/Polkadot-whitepaper.pdf){target=\_blank}. - -It enables parachains to purchase monthly "bulk" allocations of coretime (the time allocated for utilizing a core, measured in Polkadot relay chain blocks), ensuring heavy-duty parachains that can author a block every six seconds with [Asynchronous Backing](https://wiki.polkadot.com/learn/learn-async-backing/#asynchronous-backing){target=\_blank} can reliably renew their coretime each month. Although six-second block times are now the default, parachains have the option of producing blocks less frequently. - -Renewal orders are prioritized over new orders, offering stability against price fluctuations and helping parachains budget more effectively for project costs. - -### Polkadot's Resilience - -Decentralization is a vital component of blockchain networks, but it comes with trade-offs: - -- An overly decentralized network may face challenges in reaching consensus and require significant energy to operate. -- Also, a network that achieves consensus quickly risks centralization, making it easier to manipulate or attack. - -A network should be decentralized enough to prevent manipulative or malicious influence. In this sense, decentralization is a tool for achieving resilience. - -Polkadot 1.0 currently achieves resilience through several strategies: - -- **Nominated Proof of Stake (NPoS)**: Ensures that the stake per validator is maximized and evenly distributed among validators. - -- **Decentralized nodes**: Designed to encourage operators to join the network. This program aims to expand and diversify the validators in the ecosystem who aim to become independent of the program during their term. Feel free to explore more about the program on the official [Decentralized Nodes](https://nodes.web3.foundation/){target=\_blank} page. - -- **On-chain treasury and governance**: Known as [OpenGov](/reference/governance/){target=\_blank}, this system allows every decision to be made through public referenda, enabling any token holder to cast a vote. - -### Polkadot's Blockspace - -Polkadot 1.0’s design allows for the commoditization of blockspace. - -Blockspace is a blockchain's capacity to finalize and commit operations, encompassing its security, computing, and storage capabilities. Its characteristics can vary across different blockchains, affecting security, flexibility, and availability. - -- **Security**: Measures the robustness of blockspace in Proof of Stake (PoS) networks linked to the stake locked on validator nodes, the variance in stake among validators, and the total number of validators. It also considers social centralization (how many validators are owned by single operators) and physical centralization (how many validators run on the same service provider). - -- **Flexibility**: Reflects the functionalities and types of data that can be stored, with high-quality data essential to avoid bottlenecks in critical processes. - -- **Availability**: Indicates how easily users can access blockspace. It should be easily accessible, allowing diverse business models to thrive, ideally regulated by a marketplace based on demand and supplemented by options for "second-hand" blockspace. - -Polkadot is built on core blockspace principles, but there's room for improvement. Tasks like balance transfers, staking, and governance are managed on the relay chain. - -Delegating these responsibilities to [system chains](/polkadot-protocol/architecture/system-chains/){target=\_blank} could enhance flexibility and allow the relay chain to concentrate on providing shared security and interoperability. - -For more information about blockspace, watch [Robert Habermeier’s interview](https://www.youtube.com/watch?v=e1vISppPwe4){target=\_blank} or read his [technical blog post](https://www.rob.tech/blog/polkadot-blockspace-over-blockchains/){target=\_blank}. - -## DOT Token - -DOT is the native token of the Polkadot network, much like BTC for Bitcoin and Ether for the Ethereum blockchain. DOT has 10 decimals, uses the Planck base unit, and has a balance type of `u128`. The same is true for Kusama's KSM token with the exception of having 12 decimals. - -### Redenomination of DOT - -Polkadot conducted a community poll, which ended on 27 July 2020 at block 888,888, to decide whether to redenominate the DOT token. The stakeholders chose to redenominate the token, changing the value of 1 DOT from 1e12 plancks to 1e10 plancks. - -Importantly, this did not affect the network's total number of base units (plancks); it only affects how a single DOT is represented. The redenomination became effective 72 hours after transfers were enabled, occurring at block 1,248,328 on 21 August 2020 around 16:50 UTC. - -### The Planck Unit - -The smallest unit of account balance on Polkadot SDK-based blockchains (such as Polkadot and Kusama) is called _Planck_, named after the Planck length, the smallest measurable distance in the physical universe. - -Similar to how BTC's smallest unit is the Satoshi and ETH's is the Wei, Polkadot's native token DOT equals 1e10 Planck, while Kusama's native token KSM equals 1e12 Planck. - -### Uses for DOT - -DOT serves three primary functions within the Polkadot network: - -- **Governance**: It is used to participate in the governance of the network. -- **Staking**: DOT is staked to support the network's operation and security. -- **Buying coretime**: Used to purchase coretime in-bulk or on-demand and access the chain to benefit from Polkadot's security and interoperability. - -Additionally, DOT can serve as a transferable token. For example, DOT, held in the treasury, can be allocated to teams developing projects that benefit the Polkadot ecosystem. - -## JAM and the Road Ahead - -The Join-Accumulate Machine (JAM) represents a transformative redesign of Polkadot's core architecture, envisioned as the successor to the current relay chain. Unlike traditional blockchain architectures, JAM introduces a unique computational model that processes work through two primary functions: - -- **Join**: Handles data integration. -- **Accumulate**: Folds computations into the chain's state. - -JAM removes many of the opinions and constraints of the current relay chain while maintaining its core security properties. Expected improvements include: - -- **Permissionless code execution**: JAM is designed to be more generic and flexible, allowing for permissionless code execution through services that can be deployed without governance approval. -- **More effective block time utilization**: JAM's efficient pipeline processing model places the prior state root in block headers instead of the posterior state root, enabling more effective utilization of block time for computations. - -This architectural evolution promises to enhance Polkadot's scalability and flexibility while maintaining robust security guarantees. JAM is planned to be rolled out to Polkadot as a single, complete upgrade rather than a stream of smaller updates. This approach seeks to minimize the developer overhead required to address any breaking changes. - - ---- - -Page Title: Parachains Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/ -- Summary: Learn about parachains, specialized blockchains on Polkadot that gain shared security and interoperability. Discover how they work and the tools to build them. - -# Parachains Overview - -## Introduction - -A parachain is a specialized blockchain that connects to the Polkadot relay chain, benefiting from shared security, interoperability, and scalability. Parachains are built using the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}, a powerful toolkit written in Rust that provides everything needed to create custom blockchain logic while integrating seamlessly with the Polkadot network. - -Unlike standalone blockchains that must bootstrap their own validator sets and security, parachains leverage Polkadot's pooled security model. This allows parachain developers to focus on their application-specific functionality rather than consensus and security infrastructure. Parachains can communicate with each other through Cross-Consensus Messaging (XCM), enabling seamless interoperability across the Polkadot ecosystem. - -Key capabilities that parachains provide include: - -- **Shared security**: Inherit security from Polkadot's validator set without maintaining your own. -- **Interoperability**: Communicate trustlessly with other parachains via XCM. -- **Scalability**: Process transactions in parallel with other parachains. -- **Customization**: Build application-specific logic tailored to your use case. -- **Upgradeability**: Upgrade runtime logic without hard forks. - -## Polkadot SDK: Parachain Architecture - -Building a parachain involves understanding and utilizing several key components of the Polkadot SDK: - -![](/images/reference/parachains/index/overview-01.webp) - -- **[Substrate](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/substrate/index.html){target=\_blank}**: The foundation providing core blockchain primitives and libraries. -- **[FRAME](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank}**: A modular framework for building your parachain's runtime logic. -- **[Cumulus](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/cumulus/index.html){target=\_blank}**: Essential libraries and pallets that enable parachain functionality. -- **[XCM (Cross Consensus Messaging)](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/xcm/index.html){target=\_blank}**: The messaging format for communicating with other parachains and the relay chain. -- **[Polkadot](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/polkadot/index.html){target=\_blank}**: The relay chain that provides security and coordination. - -### Substrate: The Foundation - -Substrate provides the core infrastructure that every parachain is built upon. It handles the low-level blockchain functionality, allowing you to focus on your application's unique features. Substrate includes implementations for networking, database management, consensus participation, and the execution environment for your runtime. - -Every Polkadot SDK node consists of two main components: - -- **Client (Host)**: Handles infrastructure services. - - - Native binary that runs on validator and collator nodes. - - Executes the Wasm-compiled runtime. - - Manages networking, database, mempool, and block production. - - Interfaces with the relay chain for validation. - -- **Runtime (State Transition Function)**: Contains your business logic. - - - Defines how your Polkadot SDK node processes transactions. - - Compiled to [Wasm](https://webassembly.org/){target=\_blank} for deterministic execution. - - Stored on-chain and upgradeable via governance. - -```mermaid -%%{init: {'flowchart': {'padding': 5, 'nodeSpacing': 50, 'rankSpacing': 10}}}%% -graph TB - classDef title font-size:20px,font-weight:bold,stroke-width:0px - classDef clientStyle font-size:16px,font-weight:bold - classDef clientSubNodeStyle margin-top:10px - classDef runtimeCallExecutorStyle padding-top:10px - - subgraph sg1[Parachain
Node] - direction TB - - I[RuntimeCall Executor] - B[Wasm Runtime - STF] - - subgraph sg2[Client] - direction TB - C[Network and Blockchain
Infrastructure Services
+ Relay Chain Interface] - end - - I --> B - end - - class sg1 title - class sg2 clientStyle - class C clientSubNodeStyle - class I runtimeCallExecutorStyle - -``` - -### FRAME: Building Blocks for Your Runtime - -FRAME provides modular components called [pallets](/reference/glossary#pallet){target=\_blank} that you can compose to build your parachain's runtime. Each pallet provides specific functionality that you can customize and configure for your needs. This modular approach allows you to quickly assemble complex functionality without writing everything from scratch. - -```mermaid -graph LR - subgraph SP["Parachain Runtime"] - direction LR - Timestamp ~~~ Aura ~~~ ParachainSystem - Balances ~~~ TransactionPayment ~~~ Sudo - subgraph Timestamp["Timestamp"] - SS1[Custom Config] - end - subgraph Aura["Aura"] - SS2[Custom Config] - end - subgraph ParachainSystem["Parachain System"] - SS3[Custom Config] - end - subgraph Balances["Balances"] - SS4[Custom Config] - end - subgraph TransactionPayment["Transaction Payment"] - SS5[Custom Config] - end - subgraph Sudo["Sudo"] - SS6[Custom Config] - end - style Timestamp stroke:#FF69B4 - style Aura stroke:#FF69B4 - style ParachainSystem stroke:#FF69B4 - style Balances stroke:#FF69B4 - style TransactionPayment stroke:#FF69B4 - style Sudo stroke:#FF69B4 - style SS1 stroke-dasharray: 5 - style SS2 stroke-dasharray: 5 - style SS3 stroke-dasharray: 5 - style SS4 stroke-dasharray: 5 - style SS5 stroke-dasharray: 5 - style SS6 stroke-dasharray: 5 - - end - subgraph AP["Available FRAME Pallets"] - direction LR - A1[Aura]~~~A2[Parachain
System]~~~A3[Transaction
Payment]~~~A4[Sudo] - B1[Identity]~~~B2[Balances]~~~B3[Assets]~~~B4[EVM] - C1[Timestamp]~~~C2[Staking]~~~C3[Contracts]~~~C4[and more...] - end - AP --> SP -``` - -### Cumulus: Parachain-Specific Functionality - -Cumulus is what transforms a Polkadot SDK-based runtime into a parachain-capable runtime. It provides the essential components for communicating with the relay chain, participating in Polkadot's consensus, and handling parachain-specific operations like block validation and collation. - -Key Cumulus components include: - -- **Parachain system pallet**: Core parachain functionality and relay chain communication. -- **Collator consensus**: Block production logic for parachain collators. -- **Relay chain interface**: APIs for interacting with the Polkadot relay chain. -- **Validation data**: Handling proof-of-validity data required by relay chain validators. - -## Where to Go Next - -Building a parachain requires understanding the relationship between your chain and the Polkadot relay chain. The Polkadot SDK provides all the tools needed to design custom runtime logic, enable cross-chain communication, and deploy your parachain to production. - -The following sections provide detailed guidance on each aspect of parachain development, from initial design through deployment and ongoing maintenance. - -
- -- Guide __Launch a Simple Parachain__ - - --- - - Walk through the complete parachain launch flow: from setup and deployment to obtaining coretime. - - [:octicons-arrow-right-24: Deploy](/parachains/launch-a-parachain/set-up-the-parachain-template/) - - -- Guide __Customize Your Runtime__ - - --- - - Design your parachain's runtime logic and choose appropriate pallets for your use case. - - [:octicons-arrow-right-24: Get Started](/parachains/customize-runtime/) - -- Guide __Interoperability__ - - --- - - Implement XCM for trustless cross-chain communication with other parachains. - - [:octicons-arrow-right-24: Learn More](/parachains/interoperability/get-started/) - -- Guide __Runtime Upgrades__ - - --- - - Upgrade your parachain's runtime without hard forks using forkless upgrade mechanisms. - - [:octicons-arrow-right-24: Maintain](/parachains/runtime-maintenance/runtime-upgrades/) - -
- - ---- - -Page Title: Polkadot SDK Accounts - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-accounts.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/accounts/ -- Summary: Learn about account structures, balances, and address formats in the Polkadot SDK, including how to manage lifecycle, references, and balances. - -# Accounts - -## Introduction - -Accounts are essential for managing identity, transactions, and governance on the network in the Polkadot SDK. Understanding these components is critical for seamless development and operation on the network, whether you're building or interacting with Polkadot-based chains. - -This page will guide you through the essential aspects of accounts, including their data structure, balance types, reference counters, and address formats. You’ll learn how accounts are managed within the runtime, how balances are categorized, and how addresses are encoded and validated. - -## Account Data Structure - -Accounts are foundational to any blockchain, and the Polkadot SDK provides a flexible management system. This section explains how the Polkadot SDK defines accounts and manages their lifecycle through data structures within the runtime. - -### Account - -The [`Account` data type](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/type.Account.html){target=\_blank} is a storage map within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank} that links an account ID to its corresponding data. This structure is fundamental for mapping account-related information within the chain. - -The code snippet below shows how accounts are defined: - -```rs - /// The full account information for a particular account ID. - #[pallet::storage] - #[pallet::getter(fn account)] - pub type Account = StorageMap< - _, - Blake2_128Concat, - T::AccountId, - AccountInfo, - ValueQuery, - >; -``` - -The preceding code block defines a storage map named `Account`. The `StorageMap` is a type of on-chain storage that maps keys to values. In the `Account` map, the key is an account ID, and the value is the account's information. Here, `T` represents the generic parameter for the runtime configuration, which is defined by the pallet's configuration trait (`Config`). - -The `StorageMap` consists of the following parameters: - -- **`_`**: Used in macro expansion and acts as a placeholder for the storage prefix type. Tells the macro to insert the default prefix during expansion. -- **`Blake2_128Concat`**: The hashing function applied to keys in the storage map. -- **`T: :AccountId`**: Represents the key type, which corresponds to the account’s unique ID. -- **`AccountInfo`**: The value type stored in the map. For each account ID, the map stores an `AccountInfo` struct containing: - - - **`T::Nonce`**: A nonce for the account, which is incremented with each transaction to ensure transaction uniqueness. - - **`T: :AccountData`**: Custom account data defined by the runtime configuration, which could include balances, locked funds, or other relevant information. - -- **`ValueQuery`**: Defines how queries to the storage map behave when no value is found; returns a default value instead of `None`. - -For a detailed explanation of storage maps, see the [`StorageMap`](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/struct.StorageMap.html){target=\_blank} entry in the Rust docs. - -### Account Info - -The `AccountInfo` structure is another key element within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank}, providing more granular details about each account's state. This structure tracks vital data, such as the number of transactions and the account’s relationships with other modules. - -```rs -/// Information of an account. -#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)] -pub struct AccountInfo { - /// The number of transactions this account has sent. - pub nonce: Nonce, - /// The number of other modules that currently depend on this account's existence. The account - /// cannot be reaped until this is zero. - pub consumers: RefCount, - /// The number of other modules that allow this account to exist. The account may not be reaped - /// until this and `sufficients` are both zero. - pub providers: RefCount, - /// The number of modules that allow this account to exist for their own purposes only. The - /// account may not be reaped until this and `providers` are both zero. - pub sufficients: RefCount, - /// The additional data that belongs to this account. Used to store the balance(s) in a lot of - /// chains. - pub data: AccountData, -} -``` - -The `AccountInfo` structure includes the following components: - -- **`nonce`**: Tracks the number of transactions initiated by the account, which ensures transaction uniqueness and prevents replay attacks. -- **`consumers`**: Counts how many other modules or pallets rely on this account’s existence. The account cannot be removed from the chain (reaped) until this count reaches zero. -- **`providers`**: Tracks how many modules permit this account’s existence. An account can only be reaped once both `providers` and `sufficients` are zero. -- **`sufficients`**: Represents the number of modules that allow the account to exist for internal purposes, independent of any other modules. -- **`AccountData`**: A flexible data structure that can be customized in the runtime configuration, usually containing balances or other user-specific data. - -This structure helps manage an account's state and prevents its premature removal while it is still referenced by other on-chain data or modules. The [`AccountInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.AccountInfo.html){target=\_blank} structure can vary as long as it satisfies the trait bounds defined by the `AccountData` associated type in the [`frame-system::pallet::Config`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/trait.Config.html){target=\_blank} trait. - -### Account Reference Counters - -Polkadot SDK uses reference counters to track an account’s dependencies across different runtime modules. These counters ensure that accounts remain active while data is associated with them. - -The reference counters include: - -- **`consumers`**: Prevents account removal while other pallets still rely on the account. -- **`providers`**: Ensures an account is active before other pallets store data related to it. -- **`sufficients`**: Indicates the account’s independence, ensuring it can exist even without a native token balance, such as when holding sufficient alternative assets. - -#### Providers Reference Counters - -The `providers` counter ensures that an account is ready to be depended upon by other runtime modules. For example, it is incremented when an account has a balance above the existential deposit, which marks the account as active. - -The system requires this reference counter to be greater than zero for the `consumers` counter to be incremented, ensuring the account is stable before any dependencies are added. - -#### Consumers Reference Counters - -The `consumers` counter ensures that the account cannot be reaped until all references to it across the runtime have been removed. This check prevents the accidental deletion of accounts that still have active on-chain data. - -It is the user’s responsibility to clear out any data from other runtime modules if they wish to remove their account and reclaim their existential deposit. - -#### Sufficients Reference Counter - -The `sufficients` counter tracks accounts that can exist independently without relying on a native account balance. This is useful for accounts holding other types of assets, like tokens, without needing a minimum balance in the native token. - -For instance, the [Assets pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_assets/index.html){target=\_blank}, may increment this counter for an account holding sufficient tokens. - -#### Account Deactivation - -In Polkadot SDK-based chains, an account is deactivated when its reference counters (such as `providers`, `consumers`, and `sufficient`) reach zero. These counters ensure the account remains active as long as other runtime modules or pallets reference it. - -When all dependencies are cleared and the counters drop to zero, the account becomes deactivated and may be removed from the chain (reaped). This is particularly important in Polkadot SDK-based blockchains, where accounts with balances below the existential deposit threshold are pruned from storage to conserve state resources. - -Each pallet that references an account has cleanup functions that decrement these counters when the pallet no longer depends on the account. Once these counters reach zero, the account is marked for deactivation. - -#### Updating Counters - -The Polkadot SDK provides runtime developers with various methods to manage account lifecycle events, such as deactivation or incrementing reference counters. These methods ensure that accounts cannot be reaped while still in use. - -The following helper functions manage these counters: - -- **`inc_consumers()`**: Increments the `consumer` reference counter for an account, signaling that another pallet depends on it. -- **`dec_consumers()`**: Decrements the `consumer` reference counter, signaling that a pallet no longer relies on the account. -- **`inc_providers()`**: Increments the `provider` reference counter, ensuring the account remains active. -- **`dec_providers()`**: Decrements the `provider` reference counter, allowing for account deactivation when no longer in use. -- **`inc_sufficients()`**: Increments the `sufficient` reference counter for accounts that hold sufficient assets. -- **`dec_sufficients()`**: Decrements the `sufficient` reference counter. - -To ensure proper account cleanup and lifecycle management, a corresponding decrement should be made for each increment action. - -The `System` pallet offers three query functions to assist developers in tracking account states: - -- **[`can_inc_consumer()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_inc_consumer){target=\_blank}**: Checks if the account can safely increment the consumer reference. -- **[`can_dec_provider()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_dec_provider){target=\_blank}**: Ensures that no consumers exist before allowing the decrement of the provider counter. -- **[`is_provider_required()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.is_provider_required){target=\_blank}**: Verifies whether the account still has any active consumer references. - -This modular and flexible system of reference counters tightly controls the lifecycle of accounts in Polkadot SDK-based blockchains, preventing the accidental removal or retention of unneeded accounts. You can refer to the [System pallet Rust docs](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html){target=\_blank} for more details. - - -## Account Balance Types - -In the Polkadot ecosystem, account balances are categorized into different types based on how the funds are utilized and their availability. These balance types determine the actions that can be performed, such as transferring tokens, paying transaction fees, or participating in governance activities. Understanding these balance types helps developers manage user accounts and implement balance-dependent logic. - -!!! note "A more efficient distribution of account balance types is in development" - Soon, pallets in the Polkadot SDK will implement the [`Fungible` trait](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} (see the [tracking issue](https://github.com/paritytech/polkadot-sdk/issues/226){target=\_blank} for more details). For example, the [`transaction-storage`](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_storage/index.html){target=\_blank} pallet changed the implementation of the [`Currency`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/currency/index.html){target=\_blank} trait (see the [Refactor transaction storage pallet to use fungible traits](https://github.com/paritytech/polkadot-sdk/pull/1800){target=\_blank} PR for further details): - - ```rust - type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; - ``` - - To the [`Fungible`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} trait: - - ```rust - type BalanceOf = <::Currency as FnInspect<::AccountId>>::Balance; - ``` - - This update will enable more efficient use of account balances, allowing the free balance to be utilized for on-chain activities such as setting proxies and managing identities. - -### Balance Types - -The five main balance types are: - -- **Free balance**: Represents the total tokens available to the account for any on-chain activity, including staking, governance, and voting. However, it may not be fully spendable or transferrable if portions of it are locked or reserved. -- **Locked balance**: Portions of the free balance that cannot be spent or transferred because they are tied up in specific activities like [staking](https://wiki.polkadot.com/learn/learn-staking/#nominating-validators){target=\_blank}, [vesting](https://wiki.polkadot.com/learn/learn-guides-transfers/#vested-transfers-with-the-polkadot-js-ui){target=\_blank}, or participating in [governance](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank}. While the tokens remain part of the free balance, they are non-transferable for the duration of the lock. -- **Reserved balance**: Funds locked by specific system actions, such as setting up an [identity](https://wiki.polkadot.com/learn/learn-identity/){target=\_blank}, creating [proxies](https://wiki.polkadot.com/learn/learn-proxies/){target=\_blank}, or submitting [deposits for governance proposals](https://wiki.polkadot.com/learn/learn-guides-polkadot-opengov/#claiming-opengov-deposits){target=\_blank}. These tokens are not part of the free balance and cannot be spent unless they are unreserved. -- **Spendable balance**: The portion of the free balance that is available for immediate spending or transfers. It is calculated by subtracting the maximum of locked or reserved amounts from the free balance, ensuring that existential deposit limits are met. -- **Untouchable balance**: Funds that cannot be directly spent or transferred but may still be utilized for on-chain activities, such as governance participation or staking. These tokens are typically tied to certain actions or locked for a specific period. - -The spendable balance is calculated as follows: - -```text -spendable = free - max(locked - reserved, ED) -``` - -Here, `free`, `locked`, and `reserved` are defined above. The `ED` represents the [existential deposit](https://wiki.polkadot.com/learn/learn-accounts/#existential-deposit-and-reaping){target=\_blank}, the minimum balance required to keep an account active and prevent it from being reaped. You may find you can't see all balance types when looking at your account via a wallet. Wallet providers often display only spendable, locked, and reserved balances. - -### Locks - -Locks are applied to an account's free balance, preventing that portion from being spent or transferred. Locks are automatically placed when an account participates in specific on-chain activities, such as staking or governance. Although multiple locks may be applied simultaneously, they do not stack. Instead, the largest lock determines the total amount of locked tokens. - -Locks follow these basic rules: - -- If different locks apply to varying amounts, the largest lock amount takes precedence. -- If multiple locks apply to the same amount, the lock with the longest duration governs when the balance can be unlocked. - -#### Locks Example - -Consider an example where an account has 80 DOT locked for both staking and governance purposes like so: - -- 80 DOT is staked with a 28-day lock period. -- 24 DOT is locked for governance with a 1x conviction and a 7-day lock period. -- 4 DOT is locked for governance with a 6x conviction and a 224-day lock period. - -In this case, the total locked amount is 80 DOT because only the largest lock (80 DOT from staking) governs the locked balance. These 80 DOT will be released at different times based on the lock durations. In this example, the 24 DOT locked for governance will be released first since the shortest lock period is seven days. The 80 DOT stake with a 28-day lock period is released next. Now, all that remains locked is the 4 DOT for governance. After 224 days, all 80 DOT (minus the existential deposit) will be free and transferable. - -![Illustration of Lock Example](/images/reference/parachains/accounts/accounts-01.webp) - -#### Edge Cases for Locks - -In scenarios where multiple convictions and lock periods are active, the lock duration and amount are determined by the longest period and largest amount. For example, if you delegate with different convictions and attempt to undelegate during an active lock period, the lock may be extended for the full amount of tokens. For a detailed discussion on edge case lock behavior, see this [Stack Exchange post](https://substrate.stackexchange.com/questions/5067/delegating-and-undelegating-during-the-lock-period-extends-it-for-the-initial-am){target=\_blank}. - -### Balance Types on Polkadot.js - -Polkadot.js provides a user-friendly interface for managing and visualizing various account balances on Polkadot and Kusama networks. When interacting with Polkadot.js, you will encounter multiple balance types that are critical for understanding how your funds are distributed and restricted. This section explains how different balances are displayed in the Polkadot.js UI and what each type represents. - -![](/images/reference/parachains/accounts/accounts-02.webp) - -The most common balance types displayed on Polkadot.js are: - -- **Total balance**: The total number of tokens available in the account. This includes all tokens, whether they are transferable, locked, reserved, or vested. However, the total balance does not always reflect what can be spent immediately. In this example, the total balance is 0.6274 KSM. - -- **Transferable balance**: Shows how many tokens are immediately available for transfer. It is calculated by subtracting the locked and reserved balances from the total balance. For example, if an account has a total balance of 0.6274 KSM and a transferable balance of 0.0106 KSM, only the latter amount can be sent or spent freely. - -- **Vested balance**: Tokens that allocated to the account but released according to a specific schedule. Vested tokens remain locked and cannot be transferred until fully vested. For example, an account with a vested balance of 0.2500 KSM means that this amount is owned but not yet transferable. - -- **Locked balance**: Tokens that are temporarily restricted from being transferred or spent. These locks typically result from participating in staking, governance, or vested transfers. In Polkadot.js, locked balances do not stack—only the largest lock is applied. For instance, if an account has 0.5500 KSM locked for governance and staking, the locked balance would display 0.5500 KSM, not the sum of all locked amounts. - -- **Reserved balance**: Refers to tokens locked for specific on-chain actions, such as setting an identity, creating a proxy, or making governance deposits. Reserved tokens are not part of the free balance, but can be freed by performing certain actions. For example, removing an identity would unreserve those funds. - -- **Bonded balance**: The tokens locked for staking purposes. Bonded tokens are not transferable until they are unbonded after the unbonding period. - -- **Redeemable balance**: The number of tokens that have completed the unbonding period and are ready to be unlocked and transferred again. For example, if an account has a redeemable balance of 0.1000 KSM, those tokens are now available for spending. - -- **Democracy balance**: Reflects the number of tokens locked for governance activities, such as voting on referenda. These tokens are locked for the duration of the governance action and are only released after the lock period ends. - -By understanding these balance types and their implications, developers and users can better manage their funds and engage with on-chain activities more effectively. - -## Address Formats - -The SS58 address format is a core component of the Polkadot SDK that enables accounts to be uniquely identified across Polkadot-based networks. This format is a modified version of Bitcoin's Base58Check encoding, specifically designed to accommodate the multi-chain nature of the Polkadot ecosystem. SS58 encoding allows each chain to define its own set of addresses while maintaining compatibility and checksum validation for security. - -### Basic Format - -SS58 addresses consist of three main components: - -```text -base58encode(concat(,
, )) -``` - -- **Address type**: A byte or set of bytes that define the network (or chain) for which the address is intended. This ensures that addresses are unique across different Polkadot SDK-based chains. -- **Address**: The public key of the account encoded as bytes. -- **Checksum**: A hash-based checksum which ensures that addresses are valid and unaltered. The checksum is derived from the concatenated address type and address components, ensuring integrity. - -The encoding process transforms the concatenated components into a Base58 string, providing a compact and human-readable format that avoids easily confused characters (e.g., zero '0', capital 'O', lowercase 'l'). This encoding function ([`encode`](https://docs.rs/bs58/latest/bs58/fn.encode.html){target=\_blank}) is implemented exactly as defined in Bitcoin and IPFS specifications, using the same alphabet as both implementations. - -For more details about the SS58 address format implementation, see the [`Ss58Codec`](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Ss58Codec.html){target=\_blank} trait in the Rust Docs. - -### Address Type - -The address type defines how an address is interpreted and to which network it belongs. Polkadot SDK uses different prefixes to distinguish between various chains and address formats: - -- **Address types `0-63`**: Simple addresses, commonly used for network identifiers. -- **Address types `64-127`**: Full addresses that support a wider range of network identifiers. -- **Address types `128-255`**: Reserved for future address format extensions. - -For example, Polkadot’s main network uses an address type of 0, while Kusama uses 2. This ensures that addresses can be used without confusion between networks. - -The address type is always encoded as part of the SS58 address, making it easy to quickly identify the network. Refer to the [SS58 registry](https://github.com/paritytech/ss58-registry){target=\_blank} for the canonical listing of all address type identifiers and how they map to Polkadot SDK-based networks. - -### Address Length - -SS58 addresses can have different lengths depending on the specific format. Address lengths range from as short as 3 to 35 bytes, depending on the complexity of the address and network requirements. This flexibility allows SS58 addresses to adapt to different chains while providing a secure encoding mechanism. - -| Total | Type | Raw account | Checksum | -|-------|------|-------------|----------| -| 3 | 1 | 1 | 1 | -| 4 | 1 | 2 | 1 | -| 5 | 1 | 2 | 2 | -| 6 | 1 | 4 | 1 | -| 7 | 1 | 4 | 2 | -| 8 | 1 | 4 | 3 | -| 9 | 1 | 4 | 4 | -| 10 | 1 | 8 | 1 | -| 11 | 1 | 8 | 2 | -| 12 | 1 | 8 | 3 | -| 13 | 1 | 8 | 4 | -| 14 | 1 | 8 | 5 | -| 15 | 1 | 8 | 6 | -| 16 | 1 | 8 | 7 | -| 17 | 1 | 8 | 8 | -| 35 | 1 | 32 | 2 | - -SS58 addresses also support different payload sizes, allowing a flexible range of account identifiers. - -### Checksum Types - -A checksum is applied to validate SS58 addresses. Polkadot SDK uses a Blake2b-512 hash function to calculate the checksum, which is appended to the address before encoding. The checksum length can vary depending on the address format (e.g., 1-byte, 2-byte, or longer), providing varying levels of validation strength. - -The checksum ensures that an address is not modified or corrupted, adding an extra layer of security for account management. - -### Validating Addresses - -SS58 addresses can be validated using the subkey command-line interface or the Polkadot.js API. These tools help ensure an address is correctly formatted and valid for the intended network. The following sections will provide an overview of how validation works with these tools. - -#### Using Subkey - -[Subkey](https://paritytech.github.io/polkadot-sdk/master/subkey/index.html){target=\_blank} is a CLI tool provided by Polkadot SDK for generating and managing keys. It can inspect and validate SS58 addresses. - -The `inspect` command gets a public key and an SS58 address from the provided secret URI. The basic syntax for the `subkey inspect` command is: - -```bash -subkey inspect [flags] [options] uri -``` - -For the `uri` command-line argument, you can specify the secret seed phrase, a hex-encoded private key, or an SS58 address. If the input is a valid address, the `subkey` program displays the corresponding hex-encoded public key, account identifier, and SS58 addresses. - -For example, to inspect the public keys derived from a secret seed phrase, you can run a command similar to the following: - -```bash -subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" -``` - -The command displays output similar to the following: - -
- subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" - Secret phrase `caution juice atom organ advance problem want pledge someone senior holiday very` is account: - Secret seed: 0xc8fa03532fb22ee1f7f6908b9c02b4e72483f0dbd66e4cd456b8f34c6230b849 - Public key (hex): 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - Public key (SS58): 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR - Account ID: 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - SS58 Address: 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR -
- -The `subkey` program assumes an address is based on a public/private key pair. If you inspect an address, the command returns the 32-byte account identifier. - -However, not all addresses in Polkadot SDK-based networks are based on keys. - -Depending on the command-line options you specify and the input you provided, the command output might also display the network for which the address has been encoded. For example: - -```bash -subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" -``` - -The command displays output similar to the following: - -
- subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" - Public Key URI `12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU` is account: - Network ID/Version: polkadot - Public key (hex): 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Account ID: 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Public key (SS58): 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU - SS58 Address: 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU -
- -#### Using Polkadot.js API - -To verify an address in JavaScript or TypeScript projects, you can use the functions built into the [Polkadot.js API](https://polkadot.js.org/docs/){target=\_blank}. For example: - -```js -// Import Polkadot.js API dependencies -const { decodeAddress, encodeAddress } = require('@polkadot/keyring'); -const { hexToU8a, isHex } = require('@polkadot/util'); - -// Specify an address to test. -const address = 'INSERT_ADDRESS_TO_TEST'; - -// Check address -const isValidSubstrateAddress = () => { - try { - encodeAddress(isHex(address) ? hexToU8a(address) : decodeAddress(address)); - - return true; - } catch (error) { - return false; - } -}; - -// Query result -const isValid = isValidSubstrateAddress(); -console.log(isValid); - -``` - -If the function returns `true`, the specified address is a valid address. - -#### Other SS58 Implementations - -Support for encoding and decoding Polkadot SDK SS58 addresses has been implemented in several other languages and libraries. - -- **Crystal**: [`wyhaines/base58.cr`](https://github.com/wyhaines/base58.cr){target=\_blank} -- **Go**: [`itering/subscan-plugin`](https://github.com/itering/subscan-plugin){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **TypeScript**: [`subsquid/squid-sdk`](https://github.com/subsquid/squid-sdk){target=\_blank} - - ---- - -Page Title: Randomness - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-randomness.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/randomness/ -- Summary: Explore the importance of randomness in PoS blockchains, focusing on Polkadot’s VRF-based approach to ensure fairness and security in validator selection. - -# Randomness - -## Introduction - -Randomness is crucial in Proof of Stake (PoS) blockchains to ensure a fair and unpredictable distribution of validator duties. However, computers are inherently deterministic, meaning the same input always produces the same output. What we typically refer to as "random" numbers on a computer are actually pseudo-random. These numbers rely on an initial "seed," which can come from external sources like [atmospheric noise](https://www.random.org/randomness/){target=\_blank}, [heart rates](https://mdpi.altmetric.com/details/47574324){target=\_blank}, or even [lava lamps](https://en.wikipedia.org/wiki/Lavarand){target=\_blank}. While this may seem random, given the same "seed," the same sequence of numbers will always be generated. - -In a global blockchain network, relying on real-world entropy for randomness isn’t feasible because these inputs vary by time and location. If nodes use different inputs, blockchains can fork. Hence, real-world randomness isn't suitable for use as a seed in blockchain systems. - -Currently, two primary methods for generating randomness in blockchains are used: [`RANDAO`](#randao) and [`VRF`](#vrf) (Verifiable Random Function). Polkadot adopts the `VRF` approach for its randomness. - -## VRF - -A Verifiable Random Function (VRF) is a cryptographic function that generates a random number and proof that ensures the submitter produced the number. This proof allows anyone to verify the validity of the random number. - -Polkadot's VRF is similar to the one used in [**Ouroboros Praos**](https://eprint.iacr.org/2017/573.pdf){target=\_blank}, which secures randomness for block production in systems like [BABE](/reference/polkadot-hub/consensus-and-security/pos-consensus/#block-production-babe){target=\_blank} (Polkadot’s block production mechanism). - -The key difference is that Polkadot's VRF doesn’t rely on a central clock—avoiding the issue of whose clock to trust. Instead, it uses its own past results and slot numbers to simulate time and determine future outcomes. - -### How VRF Works - -Slots on Polkadot are discrete units of time, each lasting six seconds, and can potentially hold a block. Multiple slots form an epoch, with 2400 slots making up one four-hour epoch. - -In each slot, validators execute a "die roll" using a VRF. The VRF uses three inputs: - -1. A "secret key," unique to each validator, is used for the die roll. -2. An epoch randomness value, derived from the hash of VRF outputs from blocks two epochs ago (N-2), so past randomness influences the current epoch (N). -3. The current slot number. - -This process helps maintain fair randomness across the network. - -Here is a graphical representation: - -![](/images/reference/parachains/randomness/randomness-01.webp) - -The VRF produces two outputs: a result (the random number) and a proof (verifying that the number was generated correctly). - -The result is checked by the validator against a protocol threshold. If it's below the threshold, the validator becomes a candidate for block production in that slot. - -The validator then attempts to create a block, submitting it along with the `PROOF` and `RESULT`. - -So, VRF can be expressed like: - -`(RESULT, PROOF) = VRF(SECRET, EPOCH_RANDOMNESS_VALUE, CURRENT_SLOT_NUMBER)` - -Put simply, performing a "VRF roll" generates a random number along with proof that the number was genuinely produced and not arbitrarily chosen. - -After executing the VRF, the `RESULT` is compared to a protocol-defined `THRESHOLD`. If the `RESULT` is below the `THRESHOLD`, the validator becomes a valid candidate to propose a block for that slot. Otherwise, the validator skips the slot. - -As a result, there may be multiple validators eligible to propose a block for a slot. In this case, the block accepted by other nodes will prevail, provided it is on the chain with the latest finalized block as determined by the GRANDPA finality gadget. It's also possible for no block producers to be available for a slot, in which case the AURA consensus takes over. AURA is a fallback mechanism that randomly selects a validator to produce a block, running in parallel with BABE and only stepping in when no block producers exist for a slot. Otherwise, it remains inactive. - -Because validators roll independently, no block candidates may appear in some slots if all roll numbers are above the threshold. - -To verify resolution of this issue and that Polkadot block times remain near constant-time, see the [PoS Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} page of this documentation. - -## RANDAO - -An alternative on-chain randomness method is Ethereum's RANDAO, where validators perform thousands of hashes on a seed and publish the final hash during a round. The collective input from all validators forms the random number, and as long as one honest validator participates, the randomness is secure. - -To enhance security, RANDAO can optionally be combined with a Verifiable Delay Function (VDF), ensuring that randomness can't be predicted or manipulated during computation. - -For more information about RANDAO, see the [Randomness - RANDAO](https://eth2book.info/capella/part2/building_blocks/randomness/){target=\_blank} section of the Upgrading Ethereum documentation. - -## VDFs - -Verifiable Delay Functions (VDFs) are time-bound computations that, even on parallel computers, take a set amount of time to complete. - -They produce a unique result that can be quickly verified publicly. When combined with RANDAO, feeding RANDAO's output into a VDF introduces a delay that nullifies an attacker's chance to influence the randomness. - -However, VDF likely requires specialized ASIC devices to run separately from standard nodes. - -!!!warning - While only one is needed to secure the system, and they will be open-source and inexpensive, running VDF devices involves significant costs without direct incentives, adding friction for blockchain users. - -## Additional Resources - -For more information about the reasoning for choices made along with proofs, see Polkadot's research on blockchain randomness and sortition in the [Block production](https://research.web3.foundation/Polkadot/protocols/block-production){target=\_blank} entry of the Polkadot Wiki. - -For a discussion with Web3 Foundation researchers about when and under what conditions Polkadot's randomness can be utilized, see the [Discussion on Randomness used in Polkadot](https://github.com/use-ink/ink/issues/57){target=\_blank} issue on GitHub. - - ---- - -Page Title: Register a Local Asset - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-token-operations-register-local-asset.md -- Canonical (HTML): https://docs.polkadot.com/chain-interactions/token-operations/register-local-asset/ -- Summary: Comprehensive guide to registering a local asset on the Asset Hub system parachain, including step-by-step instructions. - -# Register a Local Asset on Asset Hub - -## Introduction - -As detailed in the [Asset Hub Overview](/polkadot-protocol/architecture/system-chains/asset-hub){target=\_blank} page, Asset Hub accommodates two types of assets: local and foreign. Local assets are those that were created in Asset Hub and are identifiable by an integer ID. On the other hand, foreign assets originate from a sibling parachain and are identified by a Multilocation. - -This guide will take you through the steps of registering a local asset on the Asset Hub parachain. - -## Prerequisites - -Before you begin, ensure you have access to the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and a funded wallet with DOT or KSM. - -- For Polkadot Asset Hub, you would need a deposit of 10 DOT and around 0.201 DOT for the metadata. -- For Kusama Asset Hub, the deposit is 0.1 KSM and around 0.000669 KSM for the metadata. - -You need to ensure that your Asset Hub account balance is a bit more than the sum of those two deposits, which should seamlessly account for the required deposits and transaction fees. - -## Steps to Register a Local Asset - -To register a local asset on the Asset Hub parachain, follow these steps: - -1. Open the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and connect to the Asset Hub parachain using the network selector in the top left corner. - - - You may prefer to test local asset registration on TestNet before registering the asset on a MainNet hub. If you still need to set up a local testing environment, review the [Environment setup](#test-setup-environment) section for instructions. Once the local environment is set up, connect to the Local Node (Chopsticks) available on `ws://127.0.0.1:8000`. - - For the live network, connect to the **Asset Hub** parachain. Either Polkadot or Kusama Asset Hub can be selected from the dropdown list, choosing the desired RPC provider. - -2. Click on the **Network** tab on the top navigation bar and select **Assets** from the dropdown list. - - ![Access to Asset Hub through Polkadot.JS](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-01.webp) - -3. Now, you need to examine all the registered asset IDs. This step is crucial to ensure that the asset ID you are about to register is unique. Asset IDs are displayed in the **assets** column. - - ![Asset IDs on Asset Hub](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-02.webp) - -4. Once you have confirmed that the asset ID is unique, click on the **Create** button on the top right corner of the page. - - ![Create a new asset](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-03.webp) +Customizing your runtime typically follows these patterns: -5. Fill in the required fields in the **Create Asset** form: +**Adding Pre-Built Pallets**: Select pallets from the FRAME library and integrate them into your runtime configuration. This is the fastest way to add functionality. - 1. **creator account**: The account to be used for creating this asset and setting up the initial metadata. - 2. **asset name**: The descriptive name of the asset you are registering. - 3. **asset symbol**: The symbol that will be used to represent the asset. - 4. **asset decimals**: The number of decimal places for this token, with a maximum of 20 allowed through the user interface. - 5. **minimum balance**: The minimum balance for the asset. This is specified in the units and decimals as requested. - 6. **asset ID**: The selected id for the asset. This should not match an already-existing asset id. - 7. Click on the **Next** button. - - ![Create Asset Form](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-04.webp) +**Creating Custom Pallets**: Write custom pallets for features that don't exist in the pre-built library. Custom pallets follow the same structure as pre-built ones and integrate seamlessly. -6. Choose the accounts for the roles listed below: +**Combining Multiple Pallets**: Layer multiple pallets together to create complex behaviors. Pallets can call each other and share storage when needed. - 1. **admin account**: The account designated for continuous administration of the token. - 2. **issuer account**: The account that will be used for issuing this token. - 3. **freezer account**: The account that will be used for performing token freezing operations. - 4. Click on the **Create** button. +**Configuring Pallet Parameters**: Most pallets are configurable—you can adjust their behavior through configuration traits without modifying their code. - ![Admin, Issuer, Freezer accounts](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-05.webp) +The following diagram illustrates how pallets combine to form a complete runtime: -7. Click on the **Sign and Submit** button to complete the asset registration process. +![](/images/parachains/customize-runtime/index/frame-overview-02.webp) - ![Sign and Submit](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-06.webp) +## Starting Templates -## Verify Asset Registration +The easiest way to begin customizing your runtime is with a starter template. These templates provide a pre-configured foundation so you can focus on customization rather than setup. -After completing these steps, the asset will be successfully registered. You can now view your asset listed on the [**Assets**](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fasset-hub-polkadot-rpc.dwellir.com#/assets){target=\_blank} section of the Polkadot.js Apps interface. +- **[Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank}**: The recommended choice for most developers, it includes pre-configured pallets for common features (balances, block production, governance), a complete runtime setup, and built-in parachain consensus support. This template offers the best balance of features and learning opportunities. -![Asset listed on Polkadot.js Apps](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-07.webp) +- **[Polkadot SDK Minimal Template](https://github.com/paritytech/polkadot-sdk-minimal-template){target=\_blank}**: Provides a bare-bones runtime with only essential components. Choose this if you want maximum flexibility and prefer building from a clean slate. -!!! tip - Take into consideration that the **Assets** section’s link may differ depending on the network you are using. For the local environment, enter `ws://127.0.0.1:8000` into the **Custom Endpoint** field. +- **[Polkadot SDK Solochain Template](https://github.com/paritytech/polkadot-sdk/tree/master/templates/solochain){target=\_blank}**: Designed for building standalone blockchains with moderate features, simple consensus, and several core pallets. Use this if you want a sovereign blockchain independent of a relay chain. -In this way, you have successfully registered a local asset on the Asset Hub parachain. +- **[OpenZeppelin Runtime Templates](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\_blank}**: Provides security-focused configurations following industry best practices. The [generic-template](https://github.com/OpenZeppelin/polkadot-runtime-templates/tree/main/generic-template){target=\_blank} includes curated pallet selections and production-ready defaults—ideal if security is your top priority. -For an in-depth explanation about Asset Hub and its features, see the [Asset Hub](/chain-interactions/token-operations/convert-assets/){target=\_blank} entry in the Polkadot Wiki. +## Key Customization Scenarios -## Test Setup Environment +This section covers the most common customization patterns you'll encounter: -You can set up a local parachain environment to test the asset registration process before deploying it on the live network. This guide uses Chopsticks to simulate that process. For further information on chopsticks usage, refer to the [Chopsticks](/develop/toolkit/parachains/fork-chains/chopsticks/get-started){target=\_blank} documentation. +- **[Add Existing Pallets to Your Runtime](/parachains/customize-runtime/add-existing-pallets/)**: Integrate pre-built pallets from the FRAME library with minimal configuration. -To set up a test environment, execute the following command: +- **[Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/)**: Run multiple instances of the same pallet with different configurations—useful for multi-token systems or parallel features. -```bash -npx @acala-network/chopsticks \ ---config=https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/polkadot-asset-hub.yml -``` +- **[Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/)**: Enable smart contract execution on your parachain using Contracts pallets. -The above command will spawn a lazy fork of Polkadot Asset Hub with the latest block data from the network. If you need to test Kusama Asset Hub, replace `polkadot-asset-hub.yml` with `kusama-asset-hub.yml` in the command. +- **[Create Custom Pallets](/parachains/customize-runtime/pallet-development/create-a-pallet/)**: Build entirely custom pallets for features unique to your blockchain. -An Asset Hub instance is now running locally, and you can proceed with the asset registration process. Note that the local registration process does not differ from the live network process. Once you have a successful TestNet transaction, you can use the same steps to register the asset on MainNet. +- **[Test Your Runtime](/parachains/customize-runtime/pallet-development/pallet-testing/)**: Unit test pallets and mock complete runtimes to ensure everything works correctly. --- @@ -8102,503 +5742,111 @@ This page contains a list of all relevant tutorials and guides to help you get s ## Port Ethereum DApps -| Title | Difficulty | Tools | Description | -|-------------------------------------------------------------------------------------|:---------------:|---------|----------------------------------------------------------------------------------------------------------------------------------| -| [Deploying Uniswap V2 on Polkadot](/smart-contracts/cookbook/eth-dapps/uniswap-v2/) | 🟡 Intermediate | Hardhat | Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. | - - ---- - -Page Title: Smart Contracts Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-overview.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/overview/ -- Summary: Learn about smart contract development capabilities in the Polkadot ecosystem, either by leveraging Polkadot Hub or other alternatives. - -# Smart Contracts on Polkadot - -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction - -Polkadot offers developers multiple approaches to building and deploying smart contracts within its ecosystem. As a multi-chain network designed for interoperability, Polkadot provides various environments optimized for different developer preferences and application requirements. From native smart contract support on Polkadot Hub to specialized parachain environments, developers can choose the platform that best suits their technical needs while benefiting from Polkadot's shared security model and cross-chain messaging capabilities. - -Whether you're looking for Ethereum compatibility through EVM-based parachains like [Moonbeam](https://docs.moonbeam.network/){target=\_blank}, [Astar](https://docs.astar.network/){target=\_blank}, and [Acala](https://evmdocs.acala.network/){target=\_blank} or prefer PolkaVM-based development with [ink!](https://use.ink/docs/v6/){target=\_blank}, the Polkadot ecosystem accommodates a range of diverse developers. - -These guides explore the diverse smart contract options available in the Polkadot ecosystem, helping developers understand the unique advantages of each approach and make informed decisions about where to deploy their decentralized applications. - -## Native Smart Contracts - -### Introduction - -Polkadot Hub enables smart contract deployment and execution through PolkaVM, a cutting-edge virtual machine designed specifically for the Polkadot ecosystem. This native integration allows developers to deploy smart contracts directly on Polkadot's system chain while maintaining compatibility with Ethereum development tools and workflows. - -### Smart Contract Development - -The smart contract platform on Polkadot Hub combines _Polkadot's robust security and scalability_ with the extensive Ethereum development ecosystem. Developers can utilize familiar Ethereum libraries for contract interactions and leverage industry-standard development environments for writing and testing smart contracts. - -Polkadot Hub provides _full Ethereum JSON-RPC API compatibility_, ensuring seamless integration with existing development tools and services. This compatibility enables developers to maintain their preferred workflows while building on Polkadot's native infrastructure. - -### Technical Architecture - -PolkaVM, the underlying virtual machine, utilizes a RISC-V-based register architecture _optimized for the Polkadot ecosystem_. This design choice offers several advantages: - -- Enhanced performance for smart contract execution. -- Improved gas efficiency for complex operations. -- Native compatibility with Polkadot's runtime environment. -- Optimized storage and state management. - -### Development Tools and Resources - -Polkadot Hub supports a comprehensive suite of development tools familiar to Ethereum developers. The platform integrates with popular development frameworks, testing environments, and deployment tools. Key features include: - -- Contract development in Solidity or Rust. -- Support for standard Ethereum development libraries. -- Integration with widely used development environments. -- Access to blockchain explorers and indexing solutions. -- Compatibility with contract monitoring and management tools. - -### Cross-Chain Capabilities - -Smart contracts deployed on Polkadot Hub can leverage Polkadot's [cross-consensus messaging (XCM) protocol](/parachains/interoperability/get-started/){target=\_blank} protocol to seamlessly _transfer tokens and call functions on other blockchain networks_ within the Polkadot ecosystem, all without complex bridging infrastructure or third-party solutions. For further references, check the [Interoperability](/develop/interoperability/){target=\_blank} section. - -### Use Cases - -Polkadot Hub's smart contract platform is suitable for a wide range of applications: - -- DeFi protocols leveraging _cross-chain capabilities_. -- NFT platforms utilizing Polkadot's native token standards. -- Governance systems integrated with Polkadot's democracy mechanisms. -- Cross-chain bridges and asset management solutions. - -## Other Smart Contract Environments - -Beyond Polkadot Hub's native PolkaVM support, the ecosystem offers two main alternatives for smart contract development: - -- **EVM-compatible parachains**: Provide access to Ethereum's extensive developer ecosystem, smart contract portability, and established tooling like Hardhat, Remix, Foundry, and OpenZeppelin. The main options include Moonbeam (the first full Ethereum-compatible parachain serving as an interoperability hub), Astar (featuring dual VM support for both EVM and WebAssembly contracts), and Acala (DeFi-focused with enhanced Acala EVM+ offering advanced DeFi primitives). - -- **Rust (ink!)**: ink! is a Rust-based framework that can compile to PolkaVM. It uses [`#[ink(...)]`](https://use.ink/docs/v6/macros-attributes/){target=\_blank} attribute macros to create Polkadot SDK-compatible PolkaVM bytecode, offering strong memory safety from Rust, an advanced type system, high-performance PolkaVM execution, and platform independence with sandboxed security. - - -Each environment provides unique advantages based on developer preferences and application requirements. - -## Where to Go Next - -Developers can use their existing Ethereum development tools and connect to Polkadot Hub's RPC endpoints. The platform's Ethereum compatibility layer ensures a smooth transition for teams already building on Ethereum-compatible chains. - -Subsequent sections of this guide provide detailed information about specific development tools, advanced features, and best practices for building on Polkadot Hub. - -
- -- Guide __Libraries__ - - --- - - Explore essential libraries to optimize smart contract development and interaction. - - [:octicons-arrow-right-24: Reference](/smart-contracts/libraries/ethers-js/) - -- Guide __Dev Environments__ - - --- - - Set up your development environment for seamless contract deployment and testing. - - [:octicons-arrow-right-24: Reference](/smart-contracts/dev-environments/local-dev-node/) - -
- - ---- - -Page Title: Technical Reference Overview - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference.md -- Canonical (HTML): https://docs.polkadot.com/reference/ -- Summary: Learn about Polkadot's technical architecture, governance framework, parachain ecosystem, and the tools you need to build and interact with the network. - -## Introduction - -The Technical Reference section provides comprehensive documentation of Polkadot's architecture, core concepts, and development tooling. Whether you're exploring how Polkadot's relay chain coordinates parachains, understanding governance mechanisms, or building applications on the network, this reference covers the technical foundations you need. - -Polkadot is a multi-chain network that enables diverse, interconnected blockchains to share security and communicate seamlessly. Understanding how these components interact from the [relay chain](/polkadot-protocol/glossary#relay-chain){target=\_blank} that validates [parachains](/polkadot-protocol/glossary#parachain){target=\_blank} to the [governance](/reference/glossary#governance){target=\_blank} mechanisms that evolve the protocol is essential for developers, validators, and network participants. - -This guide organizes technical documentation across five core areas: Polkadot Hub, Parachains, On-Chain Governance, Glossary, and Tools, each providing detailed information on different aspects of the Polkadot ecosystem. - -## Polkadot Hub - -[Polkadot Hub](/reference/polkadot-hub/){target=\_blank} is the entry point to Polkadot for all users and application developers. It provides access to essential Web3 services, including smart contracts, staking, governance, identity management, and cross-ecosystem interoperability—without requiring you to deploy or manage a parachain. - -The Hub encompasses a set of core functionality that enables developers and users to build and interact with applications on Polkadot. Key capabilities include: - -- **Smart contracts**: Deploy Ethereum-compatible smart contracts and build decentralized applications. -- **Assets and tokens**: Create, manage, and transfer fungible tokens and NFTs across the ecosystem. -- **Staking**: Participate in network security and earn rewards by staking DOT. -- **Governance**: Vote on proposals and participate in Polkadot's decentralized decision-making through OpenGov. -- **Identity services**: Register and manage on-chain identities, enabling access to governance roles and network opportunities. -- **Cross-chain interoperability**: Leverage XCM messaging to interact securely with other chains in the Polkadot ecosystem. -- **Collectives and DAOs**: Participate in governance collectives and decentralized autonomous organizations. - -## Parachains - -[Parachains](/reference/parachains/){target=\_blank} are specialized blockchains that connect to the Polkadot relay chain, inheriting its security while maintaining their own application-specific logic. The parachains documentation covers: - -- **Accounts**: Deep dive into account types, storage, and management on parachains. -- **Blocks, transactions and fees**: Understand block production, transaction inclusion, and fee mechanisms. -- **Consensus**: Learn how parachain blocks are validated and finalized through the relay chain's consensus. -- **Chain data**: Explore data structures, storage layouts, and state management. -- **Cryptography**: Study cryptographic primitives used in Polkadot SDK-based chains. -- **Data encoding**: Understand how data is encoded and decoded for blockchain compatibility. -- **Networks**: Learn about networking protocols and peer-to-peer communication. -- **Interoperability**: Discover [Cross-Consensus Messaging (XCM)](/parachains/interoperability/get-started/){target=\_blank}, the standard for cross-chain communication. -- **Randomness**: Understand how randomness is generated and used in Polkadot chains. -- **Node and runtime**: Learn about parachain nodes, runtime environments, and the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}. - -## On-Chain Governance - -[On-Chain governance](/reference/governance/){target=\_blank} is the decentralized decision-making mechanism for the Polkadot network. It manages the evolution and modification of the network's runtime logic, enabling community oversight and approval for proposed changes. The governance documentation details: - -- **OpenGov framework**: Understand Polkadot's next-generation governance system with enhanced delegation, flexible tracks, and simultaneous referendums. -- **Origins and tracks**: Learn how governance proposals are categorized, prioritized, and executed based on their privilege level and complexity. -- **Voting and delegation**: Explore conviction voting, vote delegation, and how token holders participate in governance. -- **Governance evolution**: See how Polkadot's governance has evolved from Governance V1 to the current OpenGov system. - -## Glossary - -The [Glossary](/reference/glossary/){target=\_blank} provides quick-reference definitions for Polkadot-specific terminology. Essential terms include: - -- Blockchain concepts (blocks, transactions, state) -- Consensus mechanisms (validators, collators, finality) -- Polkadot-specific terms (relay chain, parachain, XCM, FRAME) -- Network components (nodes, runtimes, storage) -- Governance terminology (origins, tracks, referendums) - -## Tools - -The [Tools](/reference/tools/){target=\_blank} section documents essential development and interaction tools for the Polkadot ecosystem: - -- **Light clients**: Lightweight solutions for interacting with the network without running full nodes. -- **JavaScript/TypeScript tools**: Libraries like [Polkadot.js API](/reference/tools/polkadot-js-api/){target=\_blank} and [PAPI](/reference/tools/papi/){target=\_blank} for building applications. -- **Rust tools**: [Polkadart](/reference/tools/polkadart/){target=\_blank} and other Rust-based libraries for SDK development. -- **Python tools**: [py-substrate-interface](/reference/tools/py-substrate-interface/){target=\_blank} for Python developers. -- **Testing and development**: Tools like [Moonwall](/reference/tools/moonwall/){target=\_blank}, [Chopsticks](/reference/tools/chopsticks/){target=\_blank}, and [Omninode](/reference/tools/omninode/){target=\_blank} for smart contract and parachain testing. -- **Indexing and monitoring**: [Sidecar](/reference/tools/sidecar/){target=\_blank} for data indexing and [Dedot](/reference/tools/dedot/){target=\_blank} for substrate interaction. -- **Cross-chain tools**: [ParaSpell](/reference/tools/paraspell/){target=\_blank} for XCM integration and asset transfers. - -## Where to Go Next - -For detailed exploration of specific areas, proceed to any of the main sections: - -
- -- Learn **Polkadot Hub** - - --- - - Understand the relay chain's role in coordinating parachains, providing shared security, and enabling governance. - - [:octicons-arrow-right-24: Reference](/reference/polkadot-hub/) - -- Learn **Parachains** - - --- - - Deep dive into parachain architecture, consensus, data structures, and building application-specific blockchains. - - [:octicons-arrow-right-24: Reference](/reference/parachains/) - -- Learn **On-Chain Governance** - - --- - - Explore Polkadot's decentralized governance framework and how to participate in network decision-making. - - [:octicons-arrow-right-24: Reference](/reference/governance/) - -- Guide **Glossary** - - --- - - Quick reference for Polkadot-specific terminology and concepts used throughout the documentation. - - [:octicons-arrow-right-24: Reference](/reference/glossary/) - -- Guide **Tools** - - --- - - Discover development tools, libraries, and frameworks for building and interacting with Polkadot. - - [:octicons-arrow-right-24: Reference](/reference/tools/) - -
- - ---- - -Page Title: Transactions - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-transactions.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/transactions/ -- Summary: Learn how to construct, submit, and validate transactions in the Polkadot SDK, covering signed, unsigned, and inherent types of transactions. - -# Transactions - -## Introduction - -Transactions are essential components of blockchain networks, enabling state changes and the execution of key operations. In the Polkadot SDK, transactions, often called extrinsics, come in multiple forms, including signed, unsigned, and inherent transactions. - -This guide walks you through the different transaction types and how they're formatted, validated, and processed within the Polkadot ecosystem. You'll also learn how to customize transaction formats and construct transactions for FRAME-based runtimes, ensuring a complete understanding of how transactions are built and executed in Polkadot SDK-based chains. - -## What Is a Transaction? - -In the Polkadot SDK, transactions represent operations that modify the chain's state, bundled into blocks for execution. The term extrinsic is often used to refer to any data that originates outside the runtime and is included in the chain. While other blockchain systems typically refer to these operations as "transactions," the Polkadot SDK adopts the broader term "extrinsic" to capture the wide variety of data types that can be added to a block. - -There are three primary types of transactions (extrinsics) in the Polkadot SDK: - -- **Signed transactions**: Signed by the submitting account, often carrying transaction fees. -- **Unsigned transactions**: Submitted without a signature, often requiring custom validation logic. -- **Inherent transactions**: Typically inserted directly into blocks by block authoring nodes, without gossiping between peers. - -Each type serves a distinct purpose, and understanding when and how to use each is key to efficiently working with the Polkadot SDK. - -### Signed Transactions - -Signed transactions require an account's signature and typically involve submitting a request to execute a runtime call. The signature serves as a form of cryptographic proof that the sender has authorized the action, using their private key. These transactions often involve a transaction fee to cover the cost of execution and incentivize block producers. - -Signed transactions are the most common type of transaction and are integral to user-driven actions, such as token transfers. For instance, when you transfer tokens from one account to another, the sending account must sign the transaction to authorize the operation. - -For example, the [`pallet_balances::Call::transfer_allow_death`](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/pallet/struct.Pallet.html#method.transfer_allow_death){target=\_blank} extrinsic in the Balances pallet allows you to transfer tokens. Since your account initiates this transaction, your account key is used to sign it. You'll also be responsible for paying the associated transaction fee, with the option to include an additional tip to incentivize faster inclusion in the block. - -### Unsigned Transactions - -Unsigned transactions do not require a signature or account-specific data from the sender. Unlike signed transactions, they do not come with any form of economic deterrent, such as fees, which makes them susceptible to spam or replay attacks. Custom validation logic must be implemented to mitigate these risks and ensure these transactions are secure. - -Unsigned transactions typically involve scenarios where including a fee or signature is unnecessary or counterproductive. However, due to the absence of fees, they require careful validation to protect the network. For example, [`pallet_im_online::Call::heartbeat`](https://paritytech.github.io/polkadot-sdk/master/pallet_im_online/pallet/struct.Pallet.html#method.heartbeat){target=\_blank} extrinsic allows validators to send a heartbeat signal, indicating they are active. Since only validators can make this call, the logic embedded in the transaction ensures that the sender is a validator, making the need for a signature or fee redundant. - -Unsigned transactions are more resource-intensive than signed ones because custom validation is required, but they play a crucial role in certain operational scenarios, especially when regular user accounts aren't involved. - -### Inherent Transactions - -Inherent transactions are a specialized type of unsigned transaction that is used primarily for block authoring. Unlike signed or other unsigned transactions, inherent transactions are added directly by block producers and are not broadcasted to the network or stored in the transaction queue. They don't require signatures or the usual validation steps and are generally used to insert system-critical data directly into blocks. - -A key example of an inherent transaction is inserting a timestamp into each block. The [`pallet_timestamp::Call::now`](https://paritytech.github.io/polkadot-sdk/master/pallet_timestamp/pallet/struct.Pallet.html#method.now-1){target=\_blank} extrinsic allows block authors to include the current time in the block they are producing. Since the block producer adds this information, there is no need for transaction validation, like signature verification. The validation in this case is done indirectly by the validators, who check whether the timestamp is within an acceptable range before finalizing the block. - -Another example is the [`paras_inherent::Call::enter`](https://paritytech.github.io/polkadot-sdk/master/polkadot_runtime_parachains/paras_inherent/pallet/struct.Pallet.html#method.enter){target=\_blank} extrinsic, which enables parachain collator nodes to send validation data to the relay chain. This inherent transaction ensures that the necessary parachain data is included in each block without the overhead of gossiped transactions. - -Inherent transactions serve a critical role in block authoring by allowing important operational data to be added directly to the chain without needing the validation processes required for standard transactions. - -## Transaction Formats - -Understanding the structure of signed and unsigned transactions is crucial for developers building on Polkadot SDK-based chains. Whether you're optimizing transaction processing, customizing formats, or interacting with the transaction pool, knowing the format of extrinsics, Polkadot's term for transactions, is essential. - -### Types of Transaction Formats - -In Polkadot SDK-based chains, extrinsics can fall into three main categories: - -- **Unchecked extrinsics**: Typically used for signed transactions that require validation. They contain a signature and additional data, such as a nonce and information for fee calculation. Unchecked extrinsics are named as such because they require validation checks before being accepted into the transaction pool. -- **Checked extrinsics**: Typically used for inherent extrinsics (unsigned transactions); these don't require signature verification. Instead, they carry information such as where the extrinsic originates and any additional data required for the block authoring process. -- **Opaque extrinsics**: Used when the format of an extrinsic is not yet fully committed or finalized. They are still decodable, but their structure can be flexible depending on the context. - -### Signed Transaction Data Structure - -A signed transaction typically includes the following components: - -- **Signature**: Verifies the authenticity of the transaction sender. -- **Call**: The actual function or method call the transaction is requesting (for example, transferring funds). -- **Nonce**: Tracks the number of prior transactions sent from the account, helping to prevent replay attacks. -- **Tip**: An optional incentive to prioritize the transaction in block inclusion. -- **Additional data**: Includes details such as spec version, block hash, and genesis hash to ensure the transaction is valid within the correct runtime and chain context. - -Here's a simplified breakdown of how signed transactions are typically constructed in a Polkadot SDK runtime: - -``` code - + + -``` - -Each part of the signed transaction has a purpose, ensuring the transaction's authenticity and context within the blockchain. - -### Signed Extensions - -Polkadot SDK also provides the concept of [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}, which allow developers to extend extrinsics with additional data or validation logic before they are included in a block. The [`SignedExtension`](https://paritytech.github.io/try-runtime-cli/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} set helps enforce custom rules or protections, such as ensuring the transaction's validity or calculating priority. - -The transaction queue regularly calls signed extensions to verify a transaction's validity before placing it in the ready queue. This safeguard ensures transactions won't fail in a block. Signed extensions are commonly used to enforce validation logic and protect the transaction pool from spam and replay attacks. - -In FRAME, a signed extension can hold any of the following types by default: - -- **[`AccountId`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/runtime/types_common/type.AccountId.html){target=\_blank}**: To encode the sender's identity. -- **[`Call`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Call){target=\_blank}**: To encode the pallet call to be dispatched. This data is used to calculate transaction fees. -- **[`AdditionalSigned`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.AdditionalSigned){target=\_blank}**: To handle any additional data to go into the signed payload allowing you to attach any custom logic prior to dispatching a transaction. -- **[`Pre`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Pre){target=\_blank}**: To encode the information that can be passed from before a call is dispatched to after it gets dispatched. - -Signed extensions can enforce checks like: - -- **[`CheckSpecVersion`](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/extensions/check_spec_version.rs.html){target=\_blank}**: Ensures the transaction is compatible with the runtime's current version. -- **[`CheckWeight`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.CheckWeight.html){target=\_blank}**: Calculates the weight (or computational cost) of the transaction, ensuring the block doesn't exceed the maximum allowed weight. - -These extensions are critical in the transaction lifecycle, ensuring that only valid and prioritized transactions are processed. - -## Transaction Construction - -Building transactions in the Polkadot SDK involves constructing a payload that can be verified, signed, and submitted for inclusion in a block. Each runtime in the Polkadot SDK has its own rules for validating and executing transactions, but there are common patterns for constructing a signed transaction. - -### Construct a Signed Transaction - -A signed transaction in the Polkadot SDK includes various pieces of data to ensure security, prevent replay attacks, and prioritize processing. Here's an overview of how to construct one: - -1. **Construct the unsigned payload**: Gather the necessary information for the call, including: - - - **Pallet index**: Identifies the pallet where the runtime function resides. - - **Function index**: Specifies the particular function to call in the pallet. - - **Parameters**: Any additional arguments required by the function call. - -2. **Create a signing payload**: Once the unsigned payload is ready, additional data must be included: - - - **Transaction nonce**: Unique identifier to prevent replay attacks. - - **Era information**: Defines how long the transaction is valid before it's dropped from the pool. - - **Block hash**: Ensures the transaction doesn't execute on the wrong chain or fork. - -3. **Sign the payload**: Using the sender's private key, sign the payload to ensure that the transaction can only be executed by the account holder. -4. **Serialize the signed payload**: Once signed, the transaction must be serialized into a binary format, ensuring the data is compact and easy to transmit over the network. -5. **Submit the serialized transaction**: Finally, submit the serialized transaction to the network, where it will enter the transaction pool and wait for processing by an authoring node. - -The following is an example of how a signed transaction might look: - -``` rust -node_runtime::UncheckedExtrinsic::new_signed( - function.clone(), // some call - sp_runtime::AccountId32::from(sender.public()).into(), // some sending account - node_runtime::Signature::Sr25519(signature.clone()), // the account's signature - extra.clone(), // the signed extensions -) -``` - -### Transaction Encoding - -Before a transaction is sent to the network, it is serialized and encoded using a structured encoding process that ensures consistency and prevents tampering: - -- **`[1]`**: Compact encoded length in bytes of the entire transaction. -- **`[2]`**: A u8 containing 1 byte to indicate whether the transaction is signed or unsigned (1 bit) and the encoded transaction version ID (7 bits). -- **`[3]`**: If signed, this field contains an account ID, an SR25519 signature, and some extra data. -- **`[4]`**: Encoded call data, including pallet and function indices and any required arguments. - -This encoded format ensures consistency and efficiency in processing transactions across the network. By adhering to this format, applications can construct valid transactions and pass them to the network for execution. - -To learn more about how compact encoding works using SCALE, see the [SCALE Codec](https://github.com/paritytech/parity-scale-codec){target=\_blank} README on GitHub. - -### Customize Transaction Construction - -Although the basic steps for constructing transactions are consistent across Polkadot SDK-based chains, developers can customize transaction formats and validation rules. For example: - -- **Custom pallets**: You can define new pallets with custom function calls, each with its own parameters and validation logic. -- **Signed extensions**: Developers can implement custom extensions that modify how transactions are prioritized, validated, or included in blocks. - -By leveraging Polkadot SDK's modular design, developers can create highly specialized transaction logic tailored to their chain's needs. +| Title | Difficulty | Tools | Description | +|-------------------------------------------------------------------------------------|:---------------:|---------|----------------------------------------------------------------------------------------------------------------------------------| +| [Deploying Uniswap V2 on Polkadot](/smart-contracts/cookbook/eth-dapps/uniswap-v2/) | 🟡 Intermediate | Hardhat | Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. | -## Lifecycle of a Transaction -In the Polkadot SDK, transactions are often referred to as extrinsics because the data in transactions originates outside of the runtime. These transactions contain data that initiates changes to the chain state. The most common type of extrinsic is a signed transaction, which is cryptographically verified and typically incurs a fee. This section focuses on how signed transactions are processed, validated, and ultimately included in a block. +--- -### Define Transaction Properties +Page Title: Smart Contracts Overview -The Polkadot SDK runtime defines key transaction properties, such as: +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-overview.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/overview/ +- Summary: Learn about smart contract development capabilities in the Polkadot ecosystem, either by leveraging Polkadot Hub or other alternatives. -- **Transaction validity**: Ensures the transaction meets all runtime requirements. -- **Signed or unsigned**: Identifies whether a transaction needs to be signed by an account. -- **State changes**: Determines how the transaction modifies the state of the chain. +# Smart Contracts on Polkadot -Pallets, which compose the runtime's logic, define the specific transactions that your chain supports. When a user submits a transaction, such as a token transfer, it becomes a signed transaction, verified by the user's account signature. If the account has enough funds to cover fees, the transaction is executed, and the chain's state is updated accordingly. +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. +## Introduction -### Process on a Block Authoring Node +Polkadot offers developers multiple approaches to building and deploying smart contracts within its ecosystem. As a multi-chain network designed for interoperability, Polkadot provides various environments optimized for different developer preferences and application requirements. From native smart contract support on Polkadot Hub to specialized parachain environments, developers can choose the platform that best suits their technical needs while benefiting from Polkadot's shared security model and cross-chain messaging capabilities. -In Polkadot SDK-based networks, some nodes are authorized to author blocks. These nodes validate and process transactions. When a transaction is sent to a node that can produce blocks, it undergoes a lifecycle that involves several stages, including validation and execution. Non-authoring nodes gossip the transaction across the network until an authoring node receives it. The following diagram illustrates the lifecycle of a transaction that's submitted to a network and processed by an authoring node. +Whether you're looking for Ethereum compatibility through EVM-based parachains like [Moonbeam](https://docs.moonbeam.network/){target=\_blank}, [Astar](https://docs.astar.network/){target=\_blank}, and [Acala](https://evmdocs.acala.network/){target=\_blank} or prefer PolkaVM-based development with [ink!](https://use.ink/docs/v6/){target=\_blank}, the Polkadot ecosystem accommodates a range of diverse developers. -![Transaction lifecycle diagram](/images/reference/parachains/blocks-transactions-fees/transactions/transactions-01.webp){ style="background:white" } +These guides explore the diverse smart contract options available in the Polkadot ecosystem, helping developers understand the unique advantages of each approach and make informed decisions about where to deploy their decentralized applications. -### Validate and Queue +## Native Smart Contracts -Once a transaction reaches an authoring node, it undergoes an initial validation process to ensure it meets specific conditions defined in the runtime. This validation includes checks for: +### Introduction -- **Correct nonce**: Ensures the transaction is sequentially valid for the account. -- **Sufficient funds**: Confirms the account can cover any associated transaction fees. -- **Signature validity**: Verifies that the sender's signature matches the transaction data. +Polkadot Hub enables smart contract deployment and execution through PolkaVM, a cutting-edge virtual machine designed specifically for the Polkadot ecosystem. This native integration allows developers to deploy smart contracts directly on Polkadot's system chain while maintaining compatibility with Ethereum development tools and workflows. -After these checks, valid transactions are placed in the transaction pool, where they are queued for inclusion in a block. The transaction pool regularly re-validates queued transactions to ensure they remain valid before being processed. To reach consensus, two-thirds of the nodes must agree on the order of the transactions executed and the resulting state change. Transactions are validated and queued on the local node in a transaction pool to prepare for consensus. +### Smart Contract Development -#### Transaction Pool +The smart contract platform on Polkadot Hub combines _Polkadot's robust security and scalability_ with the extensive Ethereum development ecosystem. Developers can utilize familiar Ethereum libraries for contract interactions and leverage industry-standard development environments for writing and testing smart contracts. -The transaction pool is responsible for managing valid transactions. It ensures that only transactions that pass initial validity checks are queued. Transactions that fail validation, expire, or become invalid for other reasons are removed from the pool. +Polkadot Hub provides _full Ethereum JSON-RPC API compatibility_, ensuring seamless integration with existing development tools and services. This compatibility enables developers to maintain their preferred workflows while building on Polkadot's native infrastructure. -The transaction pool organizes transactions into two queues: +### Technical Architecture -- **Ready queue**: Transactions that are valid and ready to be included in a block. -- **Future queue**: Transactions that are not yet valid but could be in the future, such as transactions with a nonce too high for the current state. +PolkaVM, the underlying virtual machine, utilizes a RISC-V-based register architecture _optimized for the Polkadot ecosystem_. This design choice offers several advantages: -Details on how the transaction pool validates transactions, including fee and signature handling, can be found in the [`validate_transaction`](https://paritytech.github.io/polkadot-sdk/master/sp_transaction_pool/runtime_api/trait.TaggedTransactionQueue.html#method.validate_transaction){target=\_blank} method. +- Enhanced performance for smart contract execution. +- Improved gas efficiency for complex operations. +- Native compatibility with Polkadot's runtime environment. +- Optimized storage and state management. -#### Invalid Transactions +### Development Tools and Resources -If a transaction is invalid, for example, due to an invalid signature or insufficient funds, it is rejected and won't be added to the block. Invalid transactions might be rejected for reasons such as: +Polkadot Hub supports a comprehensive suite of development tools familiar to Ethereum developers. The platform integrates with popular development frameworks, testing environments, and deployment tools. Key features include: -- The transaction has already been included in a block. -- The transaction's signature does not match the sender. -- The transaction is too large to fit in the current block. +- Contract development in Solidity or Rust. +- Support for standard Ethereum development libraries. +- Integration with widely used development environments. +- Access to blockchain explorers and indexing solutions. +- Compatibility with contract monitoring and management tools. -### Transaction Ordering and Priority +### Cross-Chain Capabilities -When a node is selected as the next block author, it prioritizes transactions based on weight, length, and tip amount. The goal is to fill the block with high-priority transactions without exceeding its maximum size or computational limits. Transactions are ordered as follows: +Smart contracts deployed on Polkadot Hub can leverage Polkadot's [cross-consensus messaging (XCM) protocol](/parachains/interoperability/get-started/){target=\_blank} protocol to seamlessly _transfer tokens and call functions on other blockchain networks_ within the Polkadot ecosystem, all without complex bridging infrastructure or third-party solutions. For further references, check the [Interoperability](/develop/interoperability/){target=\_blank} section. -- **Inherents first**: Inherent transactions, such as block timestamp updates, are always placed first. -- **Nonce-based ordering**: Transactions from the same account are ordered by their nonce. -- **Fee-based ordering**: Among transactions with the same nonce or priority level, those with higher fees are prioritized. +### Use Cases -### Transaction Execution +Polkadot Hub's smart contract platform is suitable for a wide range of applications: -Once a block author selects transactions from the pool, the transactions are executed in priority order. As each transaction is processed, the state changes are written directly to the chain's storage. It's important to note that these changes are not cached, meaning a failed transaction won't revert earlier state changes, which could leave the block in an inconsistent state. +- DeFi protocols leveraging _cross-chain capabilities_. +- NFT platforms utilizing Polkadot's native token standards. +- Governance systems integrated with Polkadot's democracy mechanisms. +- Cross-chain bridges and asset management solutions. -Events are also written to storage. Runtime logic should not emit an event before performing the associated actions. If the associated transaction fails after the event was emitted, the event will not revert. +## Other Smart Contract Environments -## Transaction Mortality +Beyond Polkadot Hub's native PolkaVM support, the ecosystem offers two main alternatives for smart contract development: -Transactions in the network can be configured as either mortal (with expiration) or immortal (without expiration). Every transaction payload contains a block checkpoint (reference block number and hash) and an era/validity period that determines how many blocks after the checkpoint the transaction remains valid. +- **EVM-compatible parachains**: Provide access to Ethereum's extensive developer ecosystem, smart contract portability, and established tooling like Hardhat, Remix, Foundry, and OpenZeppelin. The main options include Moonbeam (the first full Ethereum-compatible parachain serving as an interoperability hub), Astar (featuring dual VM support for both EVM and WebAssembly contracts), and Acala (DeFi-focused with enhanced Acala EVM+ offering advanced DeFi primitives). -When a transaction is submitted, the network validates it against these parameters. If the transaction is not included in a block within the specified validity window, it is automatically removed from the transaction queue. +- **Rust (ink!)**: ink! is a Rust-based framework that can compile to PolkaVM. It uses [`#[ink(...)]`](https://use.ink/docs/v6/macros-attributes/){target=\_blank} attribute macros to create Polkadot SDK-compatible PolkaVM bytecode, offering strong memory safety from Rust, an advanced type system, high-performance PolkaVM execution, and platform independence with sandboxed security. -- **Mortal transactions**: Have a finite lifespan and will expire after a specified number of blocks. For example, a transaction with a block checkpoint of 1000 and a validity period of 64 blocks will be valid from blocks 1000 to 1064. -- **Immortal transactions**: Never expire and remain valid indefinitely. To create an immortal transaction, set the block checkpoint to 0 (genesis block), use the genesis hash as a reference, and set the validity period to 0. +Each environment provides unique advantages based on developer preferences and application requirements. -However, immortal transactions pose significant security risks through replay attacks. If an account is reaped (balance drops to zero, account removed) and later re-funded, malicious actors can replay old immortal transactions. +## Where to Go Next -The blockchain maintains only a limited number of prior block hashes for reference validation, called `BlockHashCount`. If your validity period exceeds `BlockHashCount`, the effective validity period becomes the minimum of your specified period and the block hash count. +Developers can use their existing Ethereum development tools and connect to Polkadot Hub's RPC endpoints. The platform's Ethereum compatibility layer ensures a smooth transition for teams already building on Ethereum-compatible chains. -## Unique Identifiers for Extrinsics +Subsequent sections of this guide provide detailed information about specific development tools, advanced features, and best practices for building on Polkadot Hub. -Transaction hashes are **not unique identifiers** in Polkadot SDK-based chains. +
-Key differences from traditional blockchains: +- Guide __Libraries__ -- Transaction hashes serve only as fingerprints of transaction information. -- Multiple valid transactions can share the same hash. -- Hash uniqueness assumptions lead to serious issues. + --- -For example, when an account is reaped (removed due to insufficient balance) and later recreated, it resets to nonce 0, allowing identical transactions to be valid at different points: + Explore essential libraries to optimize smart contract development and interaction. -| Block | Extrinsic Index | Hash | Origin | Nonce | Call | Result | -|-------|----------------|------|-----------|-------|---------------------|-------------------------------| -| 100 | 0 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Account A reaped | -| 150 | 5 | 0x02 | Account B | 4 | Transfer 7 DOT to A | Account A created (nonce = 0) | -| 200 | 2 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Successful transaction | + [:octicons-arrow-right-24: Reference](/smart-contracts/libraries/ethers-js/) -Notice that blocks 100 and 200 contain transactions with identical hashes (0x01) but are completely different, valid operations occurring at different times. +- Guide __Dev Environments__ -Additional complexity comes from Polkadot SDK's origin abstraction. Origins can represent collectives, governance bodies, or other non-account entities that don't maintain nonces like regular accounts and might dispatch identical calls multiple times with the same hash values. Each execution occurs in different chain states with different results. + --- -The correct way to uniquely identify an extrinsic on a Polkadot SDK-based chain is to use the block ID (height or hash) and the extrinsic index. Since the Polkadot SDK defines blocks as headers plus ordered arrays of extrinsics, the index position within a canonical block provides guaranteed uniqueness. + Set up your development environment for seamless contract deployment and testing. -## Additional Resources + [:octicons-arrow-right-24: Reference](/smart-contracts/dev-environments/local-dev-node/) -For a video overview of the lifecycle of transactions and the types of transactions that exist, see the [Transaction lifecycle](https://www.youtube.com/watch?v=3pfM0GOp02c){target=\_blank} seminar from Parity Tech. +
--- @@ -8708,351 +5956,6 @@ The system maintains precise conversion mechanisms between: This ensures accurate fee calculation while maintaining compatibility with existing Ethereum tools and workflows. ---- - -Page Title: Transactions Weights and Fees - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-fees.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/fees/ -- Summary: Overview of transaction weights and fees in Polkadot SDK chains, detailing how fees are calculated using a defined formula and runtime specifics. - -# Transactions Weights and Fees - -## Introductions - -When transactions are executed, or data is stored on-chain, the activity changes the chain's state and consumes blockchain resources. Because the resources available to a blockchain are limited, managing how operations on-chain consume them is important. In addition to being limited in practical terms, such as storage capacity, blockchain resources represent a potential attack vector for malicious users. For example, a malicious user might attempt to overload the network with messages to stop the network from producing new blocks. To protect blockchain resources from being drained or overloaded, you need to manage how they are made available and how they are consumed. The resources to be aware of include: - -- Memory usage -- Storage input and output -- Computation -- Transaction and block size -- State database size - -The Polkadot SDK provides block authors with several ways to manage access to resources and to prevent individual components of the chain from consuming too much of any single resource. Two of the most important mechanisms available to block authors are weights and transaction fees. - -[Weights](/reference/glossary/#weight){target=\_blank} manage the time it takes to validate a block and characterize the time it takes to execute the calls in the block's body. By controlling the execution time a block can consume, weights set limits on storage input, output, and computation. - -Some of the weight allowed for a block is consumed as part of the block's initialization and finalization. The weight might also be used to execute mandatory inherent extrinsic calls. To help ensure blocks don’t consume too much execution time and prevent malicious users from overloading the system with unnecessary calls, weights are combined with transaction fees. - -[Transaction fees](/reference/parachains/blocks-transactions-fees/transactions/#transaction-fees){target=\_blank} provide an economic incentive to limit execution time, computation, and the number of calls required to perform operations. Transaction fees are also used to make the blockchain economically sustainable because they are typically applied to transactions initiated by users and deducted before a transaction request is executed. - -## How Fees are Calculated - -The final fee for a transaction is calculated using the following parameters: - -- **`base fee`**: This is the minimum amount a user pays for a transaction. It is declared a base weight in the runtime and converted to a fee using the [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} conversion. -- **`weight fee`**: A fee proportional to the execution time (input and output and computation) that a transaction consumes. -- **`length fee`**: A fee proportional to the encoded length of the transaction. -- **`tip`**: An optional tip to increase the transaction’s priority, giving it a higher chance to be included in the transaction queue. - -The base fee and proportional weight and length fees constitute the inclusion fee. The inclusion fee is the minimum fee that must be available for a transaction to be included in a block. - -```text -inclusion fee = base fee + weight fee + length fee -``` - -Transaction fees are withdrawn before the transaction is executed. After the transaction is executed, the weight can be adjusted to reflect the resources used. If a transaction uses fewer resources than expected, the transaction fee is corrected, and the adjusted transaction fee is deposited. - -## Using the Transaction Payment Pallet - -The [Transaction Payment pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/transaction-payment){target=\_blank} provides the basic logic for calculating the inclusion fee. You can also use the Transaction Payment pallet to: - -- Convert a weight value into a deductible fee based on a currency type using [`Config::WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank}. -- Update the fee for the next block by defining a multiplier based on the chain’s final state at the end of the previous block using [`Config::FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank}. -- Manage the withdrawal, refund, and deposit of transaction fees using [`Config::OnChargeTransaction`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.OnChargeTransaction){target=\_blank}. - -You can learn more about these configuration traits in the [Transaction Payment documentation](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_payment/index.html){target=\_blank}. - -### Understanding the Inclusion Fee - -The formula for calculating the inclusion fee is as follows: - -```text -inclusion_fee = base_fee + length_fee + [targeted_fee_adjustment * weight_fee] -``` - -And then, for calculating the final fee: - -```text -final_fee = inclusion_fee + tip -``` - -In the first formula, the `targeted_fee_adjustment` is a multiplier that can tune the final fee based on the network’s congestion. - -- The `base_fee` derived from the base weight covers inclusion overhead like signature verification. -- The `length_fee` is a per-byte fee that is multiplied by the length of the encoded extrinsic. -- The `weight_fee` fee is calculated using two parameters: - - The `ExtrinsicBaseWeight` that is declared in the runtime and applies to all extrinsics. - - The `#[pallet::weight]` annotation that accounts for an extrinsic's complexity. - -To convert the weight to `Currency`, the runtime must define a `WeightToFee` struct that implements a conversion function, [`Convert`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/struct.Pallet.html#method.weight_to_fee){target=\_blank}. - -Note that the extrinsic sender is charged the inclusion fee before the extrinsic is invoked. The fee is deducted from the sender's balance even if the transaction fails upon execution. - -### Accounts with an Insufficient Balance - -If an account does not have a sufficient balance to pay the inclusion fee and remain alive—that is, enough to pay the inclusion fee and maintain the minimum existential deposit—then you should ensure the transaction is canceled so that no fee is deducted and the transaction does not begin execution. - -The Polkadot SDK doesn't enforce this rollback behavior. However, this scenario would be rare because the transaction queue and block-making logic perform checks to prevent it before adding an extrinsic to a block. - -### Fee Multipliers - -The inclusion fee formula always results in the same fee for the same input. However, weight can be dynamic and—based on how [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} is defined—the final fee can include some degree of variability. -The Transaction Payment pallet provides the [`FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank} configurable parameter to account for this variability. - -The Polkadot network inspires the default update function and implements a targeted adjustment in which a target saturation level of block weight is defined. If the previous block is more saturated, the fees increase slightly. Similarly, if the last block has fewer transactions than the target, fees are decreased by a small amount. For more information about fee multiplier adjustments, see the [Web3 Research Page](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank}. - -## Transactions with Special Requirements - -Inclusion fees must be computable before execution and can only represent fixed logic. Some transactions warrant limiting resources with other strategies. For example: - -- Bonds are a type of fee that might be returned or slashed after some on-chain event. For example, you might want to require users to place a bond to participate in a vote. The bond might then be returned at the end of the referendum or slashed if the voter attempted malicious behavior. -- Deposits are fees that might be returned later. For example, you might require users to pay a deposit to execute an operation that uses storage. The user’s deposit could be returned if a subsequent operation frees up storage. -- Burn operations are used to pay for a transaction based on its internal logic. For example, a transaction might burn funds from the sender if the transaction creates new storage items to pay for the increased state size. -- Limits enable you to enforce constant or configurable limits on specific operations. For example, the default [Staking pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/staking){target=\_blank} only allows nominators to nominate 16 validators to limit the complexity of the validator election process. - -It is important to note that if you query the chain for a transaction fee, it only returns the inclusion fee. - -## Default Weight Annotations - -All dispatchable functions in the Polkadot SDK must specify a weight. The way of doing that is using the annotation-based system that lets you combine fixed values for database read/write weight and/or fixed values based on benchmarks. The most basic example would look like this: - -```rust -#[pallet::weight(100_000)] -fn my_dispatchable() { - // ... -} -``` - -Note that the [`ExtrinsicBaseWeight`](https://crates.parity.io/frame_support/weights/constants/struct.ExtrinsicBaseWeight.html){target=\_blank} is automatically added to the declared weight to account for the costs of simply including an empty extrinsic into a block. - -### Weights and Database Read/Write Operations - -To make weight annotations independent of the deployed database backend, they are defined as a constant and then used in the annotations when expressing database accesses performed by the dispatchable: - -```rust -#[pallet::weight(T::DbWeight::get().reads_writes(1, 2) + 20_000)] -fn my_dispatchable() { - // ... -} -``` - -This dispatchable allows one database to read and two to write, in addition to other things that add the additional 20,000. Database access is generally every time a value declared inside the [`#[pallet::storage]`](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/attr.storage.html){target=\_blank} block is accessed. However, unique accesses are counted because after a value is accessed, it is cached, and reaccessing it does not result in a database operation. That is: - -- Multiple reads of the exact value count as one read. -- Multiple writes of the exact value count as one write. -- Multiple reads of the same value, followed by a write to that value, count as one read and one write. -- A write followed by a read-only counts as one write. - -### Dispatch Classes - -Dispatches are broken into three classes: - -- Normal -- Operational -- Mandatory - -If a dispatch is not defined as `Operational` or `Mandatory` in the weight annotation, the dispatch is identified as `Normal` by default. You can specify that the dispatchable uses another class like this: - -```rust -#[pallet::dispatch((DispatchClass::Operational))] -fn my_dispatchable() { - // ... -} -``` - -This tuple notation also allows you to specify a final argument determining whether the user is charged based on the annotated weight. If you don't specify otherwise, `Pays::Yes` is assumed: - -```rust -#[pallet::dispatch(DispatchClass::Normal, Pays::No)] -fn my_dispatchable() { - // ... -} -``` - -#### Normal Dispatches - -Dispatches in this class represent normal user-triggered transactions. These types of dispatches only consume a portion of a block's total weight limit. For information about the maximum portion of a block that can be consumed for normal dispatches, see [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Normal dispatches are sent to the transaction pool. - -#### Operational Dispatches - -Unlike normal dispatches, which represent the usage of network capabilities, operational dispatches are those that provide network capabilities. Operational dispatches can consume the entire weight limit of a block. They are not bound by the [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Dispatches in this class are given maximum priority and are exempt from paying the [`length_fee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/){target=\_blank}. - -#### Mandatory Dispatches - -Mandatory dispatches are included in a block even if they cause the block to surpass its weight limit. You can only use the mandatory dispatch class for inherent transactions that the block author submits. This dispatch class is intended to represent functions in the block validation process. Because these dispatches are always included in a block regardless of the function weight, the validation process must prevent malicious nodes from abusing the function to craft valid but impossibly heavy blocks. You can typically accomplish this by ensuring that: - -- The operation performed is always light. -- The operation can only be included in a block once. - -To make it more difficult for malicious nodes to abuse mandatory dispatches, they cannot be included in blocks that return errors. This dispatch class serves the assumption that it is better to allow an overweight block to be created than not to allow any block to be created at all. - -### Dynamic Weights - -In addition to purely fixed weights and constants, the weight calculation can consider the input arguments of a dispatchable. The weight should be trivially computable from the input arguments with some basic arithmetic: - -```rust -use frame_support:: { - dispatch:: { - DispatchClass::Normal, - Pays::Yes, - }, - weights::Weight, -}; - -#[pallet::weight(FunctionOf( - |args: (&Vec,)| args.0.len().saturating_mul(10_000), - ) -] -fn handle_users(origin, calls: Vec) { - // Do something per user -} -``` - -## Post Dispatch Weight Correction - -Depending on the execution logic, a dispatchable function might consume less weight than was prescribed pre-dispatch. To correct weight, the function declares a different return type and returns its actual weight: - -```rust -#[pallet::weight(10_000 + 500_000_000)] -fn expensive_or_cheap(input: u64) -> DispatchResultWithPostInfo { - let was_heavy = do_calculation(input); - - if (was_heavy) { - // None means "no correction" from the weight annotation. - Ok(None.into()) - } else { - // Return the actual weight consumed. - Ok(Some(10_000).into()) - } -} -``` - -## Custom Fees - -You can also define custom fee systems through custom weight functions or inclusion fee functions. - -### Custom Weights - -Instead of using the default weight annotations, you can create a custom weight calculation type using the weights module. The custom weight calculation type must implement the following traits: - -- [`WeighData`](https://crates.parity.io/frame_support/weights/trait.WeighData.html){target=\_blank} to determine the weight of the dispatch. -- [`ClassifyDispatch`](https://crates.parity.io/frame_support/weights/trait.ClassifyDispatch.html){target=\_blank} to determine the class of the dispatch. -- [`PaysFee`](https://crates.parity.io/frame_support/weights/trait.PaysFee.html){target=\_blank} to determine whether the sender of the dispatch pays fees. - -The Polkadot SDK then bundles the output information of the three traits into the [`DispatchInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_support/dispatch/struct.DispatchInfo.html){target=\_blank} struct and provides it by implementing the [`GetDispatchInfo`](https://docs.rs/frame-support/latest/frame_support/dispatch/trait.GetDispatchInfo.html){target=\_blank} for all `Call` variants and opaque extrinsic types. This is used internally by the System and Executive modules. - -`ClassifyDispatch`, `WeighData`, and `PaysFee` are generic over T, which gets resolved into the tuple of all dispatch arguments except for the origin. The following example illustrates a struct that calculates the weight as `m * len(args)`, where `m` is a given multiplier and args is the concatenated tuple of all dispatch arguments. In this example, the dispatch class is `Operational` if the transaction has more than 100 bytes of length in arguments and will pay fees if the encoded length exceeds 10 bytes. - -```rust -struct LenWeight(u32); -impl WeighData for LenWeight { - fn weigh_data(&self, target: T) -> Weight { - let multiplier = self.0; - let encoded_len = target.encode().len() as u32; - multiplier * encoded_len - } -} - -impl ClassifyDispatch for LenWeight { - fn classify_dispatch(&self, target: T) -> DispatchClass { - let encoded_len = target.encode().len() as u32; - if encoded_len > 100 { - DispatchClass::Operational - } else { - DispatchClass::Normal - } - } -} - -impl PaysFee { - fn pays_fee(&self, target: T) -> Pays { - let encoded_len = target.encode().len() as u32; - if encoded_len > 10 { - Pays::Yes - } else { - Pays::No - } - } -} -``` - -A weight calculator function can also be coerced to the final type of the argument instead of defining it as a vague type that can be encoded. The code would roughly look like this: - -```rust -struct CustomWeight; -impl WeighData<(&u32, &u64)> for CustomWeight { - fn weigh_data(&self, target: (&u32, &u64)) -> Weight { - ... - } -} - -// given a dispatch: -#[pallet::call] -impl, I: 'static> Pallet { - #[pallet::weight(CustomWeight)] - fn foo(a: u32, b: u64) { ... } -} -``` - -In this example, the `CustomWeight` can only be used in conjunction with a dispatch with a particular signature `(u32, u64)`, as opposed to `LenWeight`, which can be used with anything because there aren't any assumptions about ``. - -#### Custom Inclusion Fee - -The following example illustrates how to customize your inclusion fee. You must configure the appropriate associated types in the respective module. - -```rust -// Assume this is the balance type -type Balance = u64; - -// Assume we want all the weights to have a `100 + 2 * w` conversion to fees -struct CustomWeightToFee; -impl WeightToFee for CustomWeightToFee { - fn convert(w: Weight) -> Balance { - let a = Balance::from(100); - let b = Balance::from(2); - let w = Balance::from(w); - a + b * w - } -} - -parameter_types! { - pub const ExtrinsicBaseWeight: Weight = 10_000_000; -} - -impl frame_system::Config for Runtime { - type ExtrinsicBaseWeight = ExtrinsicBaseWeight; -} - -parameter_types! { - pub const TransactionByteFee: Balance = 10; -} - -impl transaction_payment::Config { - type TransactionByteFee = TransactionByteFee; - type WeightToFee = CustomWeightToFee; - type FeeMultiplierUpdate = TargetedFeeAdjustment; -} - -struct TargetedFeeAdjustment(sp_std::marker::PhantomData); -impl> WeightToFee for TargetedFeeAdjustment { - fn convert(multiplier: Fixed128) -> Fixed128 { - // Don't change anything. Put any fee update info here. - multiplier - } -} -``` - -## Additional Resources - -You now know the weight system, how it affects transaction fee computation, and how to specify weights for your dispatchable calls. The next step is determining the correct weight for your dispatchable operations. You can use Substrate benchmarking functions and frame-benchmarking calls to test your functions with different parameters and empirically determine the proper weight in their worst-case scenarios. - -- [Benchmark](/parachains/customize-runtime/pallet-development/benchmark-pallet/) -- [`SignedExtension`](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} -- [Custom weights for the Example pallet](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/substrate/frame/examples/basic/src/weights.rs){target=\_blank} -- [Web3 Foundation Research](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank} - - --- Page Title: Troubleshooting Remix IDE @@ -11332,91 +8235,3 @@ Now that you have the foundation for using Web3.py with Polkadot Hub, consider e
- - ---- - -Page Title: XCM Tools - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-xcm-tools.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/xcm-tools/ -- Summary: Explore essential XCM tools across Polkadot, crafted to enhance cross-chain functionality and integration within the ecosystem. - -# XCM Tools - -## Introduction - -As described in the [Interoperability](/develop/interoperability){target=\_blank} section, XCM (Cross-Consensus Messaging) is a protocol used in the Polkadot and Kusama ecosystems to enable communication and interaction between chains. It facilitates cross-chain communication, allowing assets, data, and messages to flow seamlessly across the ecosystem. - -As XCM is central to enabling communication between blockchains, developers need robust tools to help interact with, build, and test XCM messages. Several XCM tools simplify working with the protocol by providing libraries, frameworks, and utilities that enhance the development process, ensuring that applications built within the Polkadot ecosystem can efficiently use cross-chain functionalities. - -## Popular XCM Tools - -### Moonsong Labs XCM Tools - -[Moonsong Labs XCM Tools](https://github.com/Moonsong-Labs/xcm-tools){target=\_blank} provides a collection of scripts for managing and testing XCM operations between Polkadot SDK-based runtimes. These tools allow performing tasks like asset registration, channel setup, and XCM initialization. Key features include: - -- **Asset registration**: Registers assets, setting units per second (up-front fees), and configuring error (revert) codes. -- **XCM initializer**: Initializes XCM, sets default XCM versions, and configures revert codes for XCM-related precompiles. -- **HRMP manipulator**: Manages HRMP channel actions, including opening, accepting, or closing channels. -- **XCM-Transactor-Info-Setter**: Configures transactor information, including extra weight and fee settings. -- **Decode XCM**: Decodes XCM messages on the relay chain or parachains to help interpret cross-chain communication. - -To get started, clone the repository and install the required dependencies: - -```bash -git clone https://github.com/Moonsong-Labs/xcm-tools && -cd xcm-tools && -yarn install -``` - -For a full overview of each script, visit the [scripts](https://github.com/Moonsong-Labs/xcm-tools/tree/main/scripts){target=\_blank} directory or refer to the [official documentation](https://github.com/Moonsong-Labs/xcm-tools/blob/main/README.md){target=\_blank} on GitHub. - -### ParaSpell - -[ParaSpell](/reference/tools/paraspell/){target=\_blank} is a collection of open-source XCM tools that streamline cross-chain asset transfers and interactions across the Polkadot and Kusama ecosystems. It provides developers with an intuitive interface to build, test, and deploy interoperable dApps, featuring message composition, decoding, and practical utilities for parachain interactions that simplify debugging and cross-chain communication optimization. - -### Astar XCM Tools - -The [Astar parachain](https://github.com/AstarNetwork/Astar/tree/master){target=\_blank} offers a crate with a set of utilities for interacting with the XCM protocol. The [xcm-tools](https://github.com/AstarNetwork/Astar/tree/master/bin/xcm-tools){target=\_blank} crate provides a straightforward method for users to locate a sovereign account or calculate an XC20 asset ID. Some commands included by the xcm-tools crate allow users to perform the following tasks: - -- **Sovereign accounts**: Obtain the sovereign account address for any parachain, either on the Relay Chain or for sibling parachains, using a simple command. -- **XC20 EVM addresses**: Generate XC20-compatible Ethereum addresses for assets by entering the asset ID, making it easy to integrate assets across Ethereum-compatible environments. -- **Remote accounts**: Retrieve remote account addresses needed for multi-location compatibility, using flexible options to specify account types and parachain IDs. - -To start using these tools, clone the [Astar repository](https://github.com/AstarNetwork/Astar){target=\_blank} and compile the xcm-tools package: - -```bash -git clone https://github.com/AstarNetwork/Astar && -cd Astar && -cargo build --release -p xcm-tools -``` - -After compiling, verify the setup with the following command: - -```bash -./target/release/xcm-tools --help -``` -For more details on using Astar xcm-tools, consult the [official documentation](https://docs.astar.network/docs/learn/interoperability/xcm/integration/tools/){target=\_blank}. - -### Chopsticks - -The Chopsticks library provides XCM functionality for testing XCM messages across networks, enabling you to fork multiple parachains along with a relay chain. For further details, see the [Chopsticks documentation](/tutorials/polkadot-sdk/testing/fork-live-chains/){target=\_blank} about XCM. - -### Moonbeam XCM SDK - -The [Moonbeam XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk){target=\_blank} enables developers to easily transfer assets between chains, either between parachains or between a parachain and the relay chain, within the Polkadot/Kusama ecosystem. With the SDK, you don't need to worry about determining the [Multilocation](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#7-universal-consensus-location-identifiers){target=\_blank} of the origin or destination assets or which extrinsics are used on which networks. - -The SDK consists of two main packages: - -- **[XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/sdk){target=\_blank}**: Core SDK for executing XCM transfers between chains in the Polkadot/Kusama ecosystem. -- **[MRL SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/mrl){target=\_blank}**: Extension of the XCM SDK for transferring liquidity into and across the Polkadot ecosystem from other ecosystems like Ethereum. - -Key features include: - -- **Simplified asset transfers**: Abstracts away complex multilocation determinations and extrinsic selection. -- **Cross-ecosystem support**: Enables transfers between Polkadot/Kusama chains and external ecosystems. -- **Developer-friendly API**: Provides intuitive interfaces for cross-chain functionality. -- **Comprehensive documentation**: Includes usage guides and API references for both packages. - -For detailed usage examples and API documentation, visit the [official Moonbeam XCM SDK documentation](https://moonbeam-foundation.github.io/xcm-sdk/latest/){target=\_blank}. diff --git a/.ai/categories/tooling.md b/.ai/categories/tooling.md index f4dd788b0..f9c835d10 100644 --- a/.ai/categories/tooling.md +++ b/.ai/categories/tooling.md @@ -516,440 +516,6 @@ BlockScout is an open-source explorer platform with a user-friendly interface ad ![](/images/smart-contracts/explorers/block-explorers-2.webp) ---- - -Page Title: Blocks - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-blocks.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/blocks/ -- Summary: Understand how blocks are produced, validated, and imported in Polkadot SDK-based blockchains, covering initialization, finalization, and authoring processes. - -# Blocks - -## Introduction - -In the Polkadot SDK, blocks are fundamental to the functioning of the blockchain, serving as containers for [transactions](/reference/parachains/blocks-transactions-fees/transactions/){target=\_blank} and changes to the chain's state. Blocks consist of headers and an array of transactions, ensuring the integrity and validity of operations on the network. This guide explores the essential components of a block, the process of block production, and how blocks are validated and imported across the network. By understanding these concepts, developers can better grasp how blockchains maintain security, consistency, and performance within the Polkadot ecosystem. - -## What is a Block? - -In the Polkadot SDK, a block is a fundamental unit that encapsulates both the header and an array of transactions. The block header includes critical metadata to ensure the integrity and sequence of the blockchain. Here's a breakdown of its components: - -- **Block height**: Indicates the number of blocks created in the chain so far. -- **Parent hash**: The hash of the previous block, providing a link to maintain the blockchain's immutability. -- **Transaction root**: Cryptographic digest summarizing all transactions in the block. -- **State root**: A cryptographic digest representing the post-execution state. -- **Digest**: Additional information that can be attached to a block, such as consensus-related messages. - -Each transaction is part of a series that is executed according to the runtime's rules. The transaction root is a cryptographic digest of this series, which prevents alterations and enables succinct verification by light clients. This verification process allows light clients to confirm whether a transaction exists in a block with only the block header, avoiding downloading the entire block. - -## Block Production - -When an authoring node is authorized to create a new block, it selects transactions from the transaction queue based on priority. This step, known as block production, relies heavily on the executive module to manage the initialization and finalization of blocks. The process is summarized as follows: - -### Initialize Block - -The block initialization process begins with a series of function calls that prepare the block for transaction execution: - -1. **Call `on_initialize`**: The executive module calls the [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} hook from the system pallet and other runtime pallets to prepare for the block's transactions. -2. **Coordinate runtime calls**: Coordinates function calls in the order defined by the transaction queue. -3. **Verify information**: Once [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} functions are executed, the executive module checks the parent hash in the block header and the trie root to verify information is consistent. - -### Finalize Block - -Once transactions are processed, the block must be finalized before being broadcast to the network. The finalization steps are as follows: - -1. **Call `on_finalize`**: The executive module calls the [`on_finalize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_finalize){target=\_blank} hooks in each pallet to ensure any remaining state updates or checks are completed before the block is sealed and published. -2. **Verify information**: The block's digest and storage root in the header are checked against the initialized block to ensure consistency. -3. **Call `on_idle`**: The [`on_idle`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_idle){target=\_blank} hook is triggered to process any remaining tasks using the leftover weight from the block. - -## Block Authoring and Import - -Once the block is finalized, it is gossiped to other nodes in the network. Nodes follow this procedure: - -1. **Receive transactions**: The authoring node collects transactions from the network. -2. **Validate**: Transactions are checked for validity. -3. **Queue**: Valid transactions are placed in the transaction pool for execution. -4. **Execute**: State changes are made as the transactions are executed. -5. **Publish**: The finalized block is broadcast to the network. - -### Block Import Queue - -After a block is published, other nodes on the network can import it into their chain state. The block import queue is part of the outer node in every Polkadot SDK-based node and ensures incoming blocks are valid before adding them to the node's state. - -In most cases, you don't need to know details about how transactions are gossiped or how other nodes on the network import blocks. The following traits are relevant, however, if you plan to write any custom consensus logic or want a deeper dive into the block import queue: - -- **[`ImportQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.ImportQueue.html){target=\_blank}**: The trait that defines the block import queue. -- **[`Link`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Link.html){target=\_blank}**: The trait that defines the link between the block import queue and the network. -- **[`BasicQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/struct.BasicQueue.html){target=\_blank}**: A basic implementation of the block import queue. -- **[`Verifier`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Verifier.html){target=\_blank}**: The trait that defines the block verifier. -- **[`BlockImport`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/block_import/trait.BlockImport.html){target=\_blank}**: The trait that defines the block import process. - -These traits govern how blocks are validated and imported across the network, ensuring consistency and security. - -## Additional Resources - -To learn more about the block structure in the Polkadot SDK runtime, see the [`Block` reference](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.Block.html){target=\_blank} entry in the Rust Docs. - - ---- - -Page Title: Chain Data - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-chain-data.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/chain-data/ -- Summary: Learn how to expose and utilize chain data for blockchain applications. Discover runtime metadata, RPC APIs, and tools for efficient development. - -# Chain Data - -## Introduction - -Understanding and leveraging on-chain data is a fundamental aspect of blockchain development. Whether you're building frontend applications or backend systems, accessing and decoding runtime metadata is vital to interacting with the blockchain. This guide introduces you to the tools and processes for generating and retrieving metadata, explains its role in application development, and outlines the additional APIs available for interacting with a Polkadot node. By mastering these components, you can ensure seamless communication between your applications and the blockchain. - -## Application Development - -You might not be directly involved in building frontend applications as a blockchain developer. However, most applications that run on a blockchain require some form of frontend or user-facing client to enable users or other programs to access and modify the data that the blockchain stores. For example, you might develop a browser-based, mobile, or desktop application that allows users to submit transactions, post articles, view their assets, or track previous activity. The backend for that application is configured in the runtime logic for your blockchain, but the frontend client makes the runtime features accessible to your users. - -For your custom chain to be useful to others, you'll need to provide a client application that allows users to view, interact with, or update information that the blockchain keeps track of. In this article, you'll learn how to expose information about your runtime so that client applications can use it, see examples of the information exposed, and explore tools and libraries that use it. - -## Understand Metadata - -Polkadot SDK-based blockchain networks are designed to expose their runtime information, allowing developers to learn granular details regarding pallets, RPC calls, and runtime APIs. The metadata also exposes their related documentation. The chain's metadata is [SCALE-encoded](/reference/parachains/data-encoding/){target=\_blank}, allowing for the development of browser-based, mobile, or desktop applications to support the chain's runtime upgrades seamlessly. It is also possible to develop applications compatible with multiple Polkadot SDK-based chains simultaneously. - -## Expose Runtime Information as Metadata - -To interact with a node or the state of the blockchain, you need to know how to connect to the chain and access the exposed runtime features. This interaction involves a Remote Procedure Call (RPC) through a node endpoint address, commonly through a secure web socket connection. - -An application developer typically needs to know the contents of the runtime logic, including the following details: - -- Version of the runtime the application is connecting to. -- Supported APIs. -- Implemented pallets. -- Defined functions and corresponding type signatures. -- Defined custom types. -- Exposed parameters users can set. - -As the Polkadot SDK is modular and provides a composable framework for building blockchains, there are limitless opportunities to customize the schema of properties. Each runtime can be configured with its properties, including function calls and types, which can be changed over time with runtime upgrades. - -The Polkadot SDK enables you to generate the runtime metadata schema to capture information unique to a runtime. The metadata for a runtime describes the pallets in use and types defined for a specific runtime version. The metadata includes information about each pallet's storage items, functions, events, errors, and constants. The metadata also provides type definitions for any custom types included in the runtime. - -Metadata provides a complete inventory of a chain's runtime. It is key to enabling client applications to interact with the node, parse responses, and correctly format message payloads sent back to that chain. - -## Generate Metadata - -To efficiently use the blockchain's networking resources and minimize the data transmitted over the network, the metadata schema is encoded using the [Parity SCALE Codec](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank}. This encoding is done automatically through the [`scale-info`](https://docs.rs/scale-info/latest/scale_info/){target=\_blank}crate. - -At a high level, generating the metadata involves the following steps: - -1. The pallets in the runtime logic expose callable functions, types, parameters, and documentation that need to be encoded in the metadata. -2. The `scale-info` crate collects type information for the pallets in the runtime, builds a registry of the pallets that exist in a particular runtime, and the relevant types for each pallet in the registry. The type information is detailed enough to enable encoding and decoding for every type. -3. The [`frame-metadata`](https://github.com/paritytech/frame-metadata){target=\_blank} crate describes the structure of the runtime based on the registry provided by the `scale-info` crate. -4. Nodes provide the RPC method `state_getMetadata` to return a complete description of all the types in the current runtime as a hex-encoded vector of SCALE-encoded bytes. - -## Retrieve Runtime Metadata - -The type information provided by the metadata enables applications to communicate with nodes using different runtime versions and across chains that expose different calls, events, types, and storage items. The metadata also allows libraries to generate a substantial portion of the code needed to communicate with a given node, enabling libraries like [`subxt`](https://github.com/paritytech/subxt){target=\_blank} to generate frontend interfaces that are specific to a target chain. - -### Use Polkadot.js - -Visit the [Polkadot.js Portal](https://polkadot.js.org/apps/#/rpc){target=\_blank} and select the **Developer** dropdown in the top banner. Select **RPC Calls** to make the call to request metadata. Follow these steps to make the RPC call: - -1. Select **state** as the endpoint to call. -2. Select **`getMetadata(at)`** as the method to call. -3. Click **Submit RPC call** to submit the call and return the metadata in JSON format. - -### Use Curl - -You can fetch the metadata for the network by calling the node's RPC endpoint. This request returns the metadata in bytes rather than human-readable JSON: - -```sh -curl -H "Content-Type: application/json" \ --d '{"id":1, "jsonrpc":"2.0", "method": "state_getMetadata"}' \ -https://rpc.polkadot.io - -``` - -### Use Subxt - -[`subxt`](https://github.com/paritytech/subxt){target=\_blank} may also be used to fetch the metadata of any data in a human-readable JSON format: - -```sh -subxt metadata --url wss://rpc.polkadot.io --format json > spec.json -``` - -Another option is to use the [`subxt` explorer web UI](https://paritytech.github.io/subxt-explorer/#/){target=\_blank}. - -## Client Applications and Metadata - -The metadata exposes the expected way to decode each type, meaning applications can send, retrieve, and process application information without manual encoding and decoding. Client applications must use the [SCALE codec library](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank} to encode and decode RPC payloads to use the metadata. Client applications use the metadata to interact with the node, parse responses, and format message payloads sent to the node. - -## Metadata Format - -Although the SCALE-encoded bytes can be decoded using the `frame-metadata` and [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} libraries, there are other tools, such as `subxt` and the Polkadot-JS API, that can convert the raw data to human-readable JSON format. - -The types and type definitions included in the metadata returned by the `state_getMetadata` RPC call depend on the runtime's metadata version. - -In general, the metadata includes the following information: - -- A constant identifying the file as containing metadata. -- The version of the metadata format used in the runtime. -- Type definitions for all types used in the runtime and generated by the `scale-info` crate. -- Pallet information for the pallets included in the runtime in the order that they are defined in the `construct_runtime` macro. - -!!!tip - Depending on the frontend library used (such as the [Polkadot API](https://papi.how/){target=\_blank}), they may format the metadata differently than the raw format shown. - -The following example illustrates a condensed and annotated section of metadata decoded and converted to JSON: - -```json -[ - 1635018093, - { - "V14": { - "types": { - "types": [{}] - }, - "pallets": [{}], - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [{}] - }, - "ty": 141 - } - } -] - -``` - -The constant `1635018093` is a magic number that identifies the file as a metadata file. The rest of the metadata is divided into the `types`, `pallets`, and `extrinsic` sections: - -- The `types` section contains an index of the types and information about each type's type signature. -- The `pallets` section contains information about each pallet in the runtime. -- The `extrinsic` section describes the type identifier and transaction format version that the runtime uses. - -Different extrinsic versions can have varying formats, especially when considering [signed transactions](/reference/parachains/blocks-transactions-fees/transactions/#signed-transactions){target=\_blank}. - -### Pallets - -The following is a condensed and annotated example of metadata for a single element in the `pallets` array (the [`sudo`](https://paritytech.github.io/polkadot-sdk/master/pallet_sudo/index.html){target=\_blank} pallet): - -```json -{ - "name": "Sudo", - "storage": { - "prefix": "Sudo", - "entries": [ - { - "name": "Key", - "modifier": "Optional", - "ty": { - "Plain": 0 - }, - "default": [0], - "docs": ["The `AccountId` of the sudo key."] - } - ] - }, - "calls": { - "ty": 117 - }, - "event": { - "ty": 42 - }, - "constants": [], - "error": { - "ty": 124 - }, - "index": 8 -} - -``` - -Every element metadata contains the name of the pallet it represents and information about its storage, calls, events, and errors. You can look up details about the definition of the calls, events, and errors by viewing the type index identifier. The type index identifier is the `u32` integer used to access the type information for that item. For example, the type index identifier for calls in the Sudo pallet is 117. If you view information for that type identifier in the `types` section of the metadata, it provides information about the available calls, including the documentation for each call. - -For example, the following is a condensed excerpt of the calls for the Sudo pallet: - -```json -{ - "id": 117, - "type": { - "path": ["pallet_sudo", "pallet", "Call"], - "params": [ - { - "name": "T", - "type": null - } - ], - "def": { - "variant": { - "variants": [ - { - "name": "sudo", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 0, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "sudo_unchecked_weight", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - }, - { - "name": "weight", - "type": 8, - "typeName": "Weight" - } - ], - "index": 1, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "set_key", - "fields": [ - { - "name": "new", - "type": 103, - "typeName": "AccountIdLookupOf" - } - ], - "index": 2, - "docs": [ - "Authenticates current sudo key, sets the given AccountId (`new`) as the new sudo" - ] - }, - { - "name": "sudo_as", - "fields": [ - { - "name": "who", - "type": 103, - "typeName": "AccountIdLookupOf" - }, - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 3, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Signed` origin from a given account" - ] - } - ] - } - } - } -} - -``` - -For each field, you can access type information and metadata for the following: - -- **Storage metadata**: Provides the information required to enable applications to get information for specific storage items. -- **Call metadata**: Includes information about the runtime calls defined by the `#[pallet]` macro including call names, arguments and documentation. -- **Event metadata**: Provides the metadata generated by the `#[pallet::event]` macro, including the name, arguments, and documentation for each pallet event. -- **Constants metadata**: Provides metadata generated by the `#[pallet::constant]` macro, including the name, type, and hex-encoded value of the constant. -- **Error metadata**: Provides metadata generated by the `#[pallet::error]` macro, including the name and documentation for each pallet error. - -!!!tip - Type identifiers change from time to time, so you should avoid relying on specific type identifiers in your applications. - -### Extrinsic - -The runtime generates extrinsic metadata and provides useful information about transaction format. When decoded, the metadata contains the transaction version and the list of signed extensions. - -For example: - -```json -{ - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [ - { - "identifier": "CheckNonZeroSender", - "ty": 132, - "additional_signed": 41 - }, - { - "identifier": "CheckSpecVersion", - "ty": 133, - "additional_signed": 4 - }, - { - "identifier": "CheckTxVersion", - "ty": 134, - "additional_signed": 4 - }, - { - "identifier": "CheckGenesis", - "ty": 135, - "additional_signed": 11 - }, - { - "identifier": "CheckMortality", - "ty": 136, - "additional_signed": 11 - }, - { - "identifier": "CheckNonce", - "ty": 138, - "additional_signed": 41 - }, - { - "identifier": "CheckWeight", - "ty": 139, - "additional_signed": 41 - }, - { - "identifier": "ChargeTransactionPayment", - "ty": 140, - "additional_signed": 41 - } - ] - }, - "ty": 141 -} - -``` - -The type system is [composite](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/frame_runtime_types/index.html){target=\_blank}, meaning each type identifier contains a reference to a specific type or to another type identifier that provides information about the associated primitive types. - -For example, you can encode the `BitVec` type, but to decode it properly, you must know the types used for the `Order` and `Store` types. To find type information for `Order` and `Store`, you can use the path in the decoded JSON to locate their type identifiers. - -## Included RPC APIs - -A standard node comes with the following APIs to interact with a node: - -- **[`AuthorApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/author/trait.AuthorApiServer.html){target=\_blank}**: Make calls into a full node, including authoring extrinsics and verifying session keys. -- **[`ChainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/chain/trait.ChainApiServer.html){target=\_blank}**: Retrieve block header and finality information. -- **[`OffchainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/offchain/trait.OffchainApiServer.html){target=\_blank}**: Make RPC calls for off-chain workers. -- **[`StateApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/state/trait.StateApiServer.html){target=\_blank}**: Query information about on-chain state such as runtime version, storage items, and proofs. -- **[`SystemApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/system/trait.SystemApiServer.html){target=\_blank}**: Retrieve information about network state, such as connected peers and node roles. - -## Additional Resources - -The following tools can help you locate and decode metadata: - -- [Subxt Explorer](https://paritytech.github.io/subxt-explorer/#/){target=\_blank} -- [Metadata Portal 🌗](https://github.com/paritytech/metadata-portal){target=\_blank} -- [De[code] Sub[strate]](https://github.com/paritytech/desub){target=\_blank} - - --- Page Title: Contract Deployment @@ -1063,9552 +629,5345 @@ Both backends support contract deployment effectively, with REVM offering drop-i --- -Page Title: Cryptography +Page Title: Deploy an ERC-20 to Polkadot Hub -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-cryptography.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/cryptography/ -- Summary: A concise guide to cryptography in blockchain, covering hash functions, encryption types, digital signatures, and elliptic curve applications. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-erc20-erc20-hardhat.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-hardhat/ +- Summary: Deploy an ERC-20 token on Polkadot Hub using PolkaVM. This guide covers contract creation, compilation, deployment, and interaction via Hardhat. -# Cryptography +# Deploy an ERC-20 to Polkadot Hub ## Introduction -Cryptography forms the backbone of blockchain technology, providing the mathematical verifiability crucial for consensus systems, data integrity, and user security. While a deep understanding of the underlying mathematical processes isn't necessary for most blockchain developers, grasping the fundamental applications of cryptography is essential. This page comprehensively overviews cryptographic implementations used across Polkadot SDK-based chains and the broader blockchain ecosystem. - -## Hash Functions - -Hash functions are fundamental to blockchain technology, creating a unique digital fingerprint for any piece of data, including simple text, images, or any other form of file. They map input data of any size to a fixed-size output (typically 32 bytes) using complex mathematical operations. Hashing is used to verify data integrity, create digital signatures, and provide a secure way to store passwords. This form of mapping is known as the ["pigeonhole principle,"](https://en.wikipedia.org/wiki/Pigeonhole_principle){target=\_blank} it is primarily implemented to efficiently and verifiably identify data from large sets. - -### Key Properties of Hash Functions - -- **Deterministic**: The same input always produces the same output. -- **Quick computation**: It's easy to calculate the hash value for any given input. -- **Pre-image resistance**: It's infeasible to generate the input data from its hash. -- **Small changes in input yield large changes in output**: Known as the ["avalanche effect"](https://en.wikipedia.org/wiki/Avalanche_effect){target=\_blank}. -- **Collision resistance**: The probabilities are extremely low to find two different inputs with the same hash. - -### Blake2 - -The Polkadot SDK utilizes Blake2, a state-of-the-art hashing method that offers: - -- Equal or greater security compared to [SHA-2](https://en.wikipedia.org/wiki/SHA-2){target=\_blank}. -- Significantly faster performance than other algorithms. - -These properties make Blake2 ideal for blockchain systems, reducing sync times for new nodes and lowering the resources required for validation. For detailed technical specifications about Blake2, see the [official Blake2 paper](https://www.blake2.net/blake2.pdf){target=\_blank}. - -## Types of Cryptography - -There are two different ways that cryptographic algorithms are implemented: symmetric cryptography and asymmetric cryptography. - -### Symmetric Cryptography - -Symmetric encryption is a branch of cryptography that isn't based on one-way functions, unlike asymmetric cryptography. It uses the same cryptographic key to encrypt plain text and decrypt the resulting ciphertext. - -Symmetric cryptography is a type of encryption that has been used throughout history, such as the Enigma Cipher and the Caesar Cipher. It is still widely used today and can be found in Web2 and Web3 applications alike. There is only one single key, and a recipient must also have access to it to access the contained information. +[ERC-20](https://eips.ethereum.org/EIPS/eip-20){target=\_blank} tokens are fungible tokens commonly used for creating cryptocurrencies, governance tokens, and staking mechanisms. Polkadot Hub enables easy token deployment with Ethereum-compatible smart contracts and tools via the EVM backend. -#### Advantages {: #symmetric-advantages } +This tutorial covers deploying an ERC-20 contract on the Polkadot Hub TestNet using [Hardhat](https://hardhat.org/){target=\_blank}, an Ethereum development environment. The ERC-20 contract can be retrieved from OpenZeppelin's [GitHub repository](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20){target=\_blank} or their [Contract Wizard](https://wizard.openzeppelin.com/){target=\_blank}. -- Fast and efficient for large amounts of data. -- Requires less computational power. +## Prerequisites -#### Disadvantages {: #symmetric-disadvantages } +Before starting, make sure you have: -- Key distribution can be challenging. -- Scalability issues in systems with many users. +- Basic understanding of Solidity programming and fungible tokens. +- Node.js v22.13.1 or later. +- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. -### Asymmetric Cryptography +## Set Up Your Project -Asymmetric encryption is a type of cryptography that uses two different keys, known as a keypair: a public key, used to encrypt plain text, and a private counterpart, used to decrypt the ciphertext. +This tutorial uses a [Hardhat ERC-20 template](https://github.com/polkadot-developers/revm-hardhat-examples/tree/master/erc20-hardhat){target=\_blank} that contains all the necessary files. To get started, take the following steps: -The public key encrypts a fixed-length message that can only be decrypted with the recipient's private key and, sometimes, a set password. The public key can be used to cryptographically verify that the corresponding private key was used to create a piece of data without compromising the private key, such as with digital signatures. This has obvious implications for identity, ownership, and properties and is used in many different protocols across Web2 and Web3. +1. Clone the GitHub repository locally: -#### Advantages {: #asymmetric-advantages } + ```bash + git clone https://github.com/polkadot-developers/revm-hardhat-examples/ + cd revm-hardhat-examples/erc20-hardhat + ``` -- Solves the key distribution problem. -- Enables digital signatures and secure key exchange. +2. Install the dependencies: -#### Disadvantages {: #asymmetric-disadvantages } + ```bash + npm i + ``` -- Slower than symmetric encryption. -- Requires more computational resources. +This will fetch all the necessary packages to help you deploy an ERC-20 with Hardhat to Polkadot. -### Trade-offs and Compromises +## Configure Hardhat -Symmetric cryptography is faster and requires fewer bits in the key to achieve the same level of security that asymmetric cryptography provides. However, it requires a shared secret before communication can occur, which poses issues to its integrity and a potential compromise point. On the other hand, asymmetric cryptography doesn't require the secret to be shared ahead of time, allowing for far better end-user security. +Once you've [setup your project](#set-up-your-project), you can configure the `hardhat.config.ts` to your needs. This tutorial has the file prepared to deploy to the Polkadot TestNet. -Hybrid symmetric and asymmetric cryptography is often used to overcome the engineering issues of asymmetric cryptography, as it is slower and requires more bits in the key to achieve the same level of security. It encrypts a key and then uses the comparatively lightweight symmetric cipher to do the "heavy lifting" with the message. +To store and use private keys or network URLs, you can use Hardhat's configuration variables. This can be set via tasks in the **vars** scope. For example, to store the private key to deploy to the Polkadot TestNet, run the following command: -## Digital Signatures +```bash +npx hardhat vars set TESTNET_PRIVATE_KEY +``` -Digital signatures are a way of verifying the authenticity of a document or message using asymmetric keypairs. They are used to ensure that a sender or signer's document or message hasn't been tampered with in transit, and for recipients to verify that the data is accurate and from the expected sender. +The command will initiate a wizard in which you'll have to enter the value to be stored: -Signing digital signatures only requires a low-level understanding of mathematics and cryptography. For a conceptual example -- when signing a check, it is expected that it cannot be cashed multiple times. This isn't a feature of the signature system but rather the check serialization system. The bank will check that the serial number on the check hasn't already been used. Digital signatures essentially combine these two concepts, allowing the signature to provide the serialization via a unique cryptographic fingerprint that cannot be reproduced. +
+ npx hardhat vars set TESTNET_PRIVATE_KEY + ✔ Enter value: · ••••••••• + The configuration variable has been stored in /Users/albertoviera/Library/Preferences/hardhat-nodejs/vars.json +
-Unlike pen-and-paper signatures, knowledge of a digital signature cannot be used to create other signatures. Digital signatures are often used in bureaucratic processes, as they are more secure than simply scanning in a signature and pasting it onto a document. +??? warning "Key Encryption" + This solution just prevents variables to be included in the code repository. You should find a solution that encrypts private keys and access them securely. -Polkadot SDK provides multiple different cryptographic schemes and is generic so that it can support anything that implements the [`Pair` trait](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Pair.html){target=\_blank}. +You can now use the account related to this private key by importing it into the Hardhat configuration file: -### Example of Creating a Digital Signature +```ts title="hardhat.config.ts" hl_lines="1 17" -The process of creating and verifying a digital signature involves several steps: +const config: HardhatUserConfig = { + solidity: { + version: "0.8.28", + settings: { + optimizer: { + enabled: true, + runs: 200, + }, + }, + }, + networks: { + polkadotTestnet: { + url: vars.get("TESTNET_URL", "http://127.0.0.1:8545"), + accounts: vars.has("TESTNET_PRIVATE_KEY") ? [vars.get("TESTNET_PRIVATE_KEY")] : [], + }, + }, + mocha: { + timeout: 40000, + }, +}; -1. The sender creates a hash of the message. -2. The hash is encrypted using the sender's private key, creating the signature. -3. The message and signature are sent to the recipient. -4. The recipient decrypts the signature using the sender's public key. -5. The recipient hashes the received message and compares it to the decrypted hash. +export default config; +``` -If the hashes match, the signature is valid, confirming the message's integrity and the sender's identity. +## Compile your Contract -## Elliptic Curve +Once you've configured Hardhat, you can compile the contract. -Blockchain technology requires the ability to have multiple keys creating a signature for block proposal and validation. To this end, Elliptic Curve Digital Signature Algorithm (ECDSA) and Schnorr signatures are two of the most commonly used methods. While ECDSA is a far simpler implementation, Schnorr signatures are more efficient when it comes to multi-signatures. +In this tutorial, a simple ERC-20 is provided. Therefore, to compile the contract you can run the following command: -Schnorr signatures bring some noticeable features over the ECDSA/EdDSA schemes: +```bash +npx hardhat compile +``` -- It is better for hierarchical deterministic key derivations. -- It allows for native multi-signature through [signature aggregation](https://bitcoincore.org/en/2017/03/23/schnorr-signature-aggregation/){target=\_blank}. -- It is generally more resistant to misuse. +If everything compiles successfully, you should see the following output: -One sacrifice that is made when using Schnorr signatures over ECDSA is that both require 64 bytes, but only ECDSA signatures communicate their public key. +
+ npx hardhat compile + Generating typings for: 23 artifacts in dir: typechain-types for target: ethers-v6 + Successfully generated 62 typings! + Compiled 21 Solidity files successfully (evm target: paris). +
-### Various Implementations +## Test your Contract -- **[ECDSA](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm){target=\_blank}**: Polkadot SDK provides an ECDSA signature scheme using the [secp256k1](https://en.bitcoin.it/wiki/Secp256k1){target=\_blank} curve. This is the same cryptographic algorithm used to secure [Bitcoin](https://en.wikipedia.org/wiki/Bitcoin){target=\_blank} and [Ethereum](https://en.wikipedia.org/wiki/Ethereum){target=\_blank}. +Hardhat has a native feature to test contracts. You can run tests against the local Hardhat development node, but it could have some technical differences to Polkadot. Therefore, in this tutorial, you'll be testing against the Polkadot TestNet -- **[Ed25519](https://en.wikipedia.org/wiki/EdDSA#Ed25519){target=\_blank}**: An EdDSA signature scheme using [Curve25519](https://en.wikipedia.org/wiki/Curve25519){target=\_blank}. It is carefully engineered at several levels of design and implementation to achieve very high speeds without compromising security. +This example has a predefined test file located in [`test/Token.test.js`](https://github.com/polkadot-developers/revm-hardhat-examples/blob/master/erc20-hardhat/test/MyToken.test.ts){target=\_blank}, that runs the following tests: -- **[SR25519](https://research.web3.foundation/Polkadot/security/keys/accounts-more){target=\_blank}**: Based on the same underlying curve as Ed25519. However, it uses Schnorr signatures instead of the EdDSA scheme. +1. The token was deployed by verifying its **name** and **symbol**. +2. The token has the right owner configured. +3. The token has an initial supply of zero. +4. The owner can mint tokens. +5. The total supply is increased after a mint. +6. Perform multiple mints to different addresses and checks the balance of each address and the new total supply. +To run the test, you can execute the following command: ---- +```bash +npx hardhat test --network polkadotTestnet +``` -Page Title: Data Encoding +If tests are successful, you should see the following logs: -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-data-encoding.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/data-encoding/ -- Summary: SCALE codec enables fast, efficient data encoding, ideal for resource-constrained environments like Wasm, supporting custom types and compact encoding. - -# Data Encoding +
+ npx hardhat test --network polkadotTestnet + +   MyToken +     Deployment +       ✔ Should have correct name and symbol +       ✔ Should set the right owner +       ✔ Should have zero initial supply +     Minting +       ✔ Should allow owner to mint tokens +       ✔ Should increase total supply on mint +     Multiple mints +       ✔ Should correctly track balance after multiple mints + +   6 passing (369ms) +
-## Introduction +## Deploy your Contract -The Polkadot SDK uses a lightweight and efficient encoding/decoding mechanism to optimize data transmission across the network. This mechanism, known as the _SCALE_ codec, is used for serializing and deserializing data. +With the Hardhat configuration file ready, the private key stored as a variable under **vars**, and the contract compiled, you can proceed to deploy the contract to a given network. In this tutorial, you are deploying it to the Polkadot TestNet. -The SCALE codec enables communication between the runtime and the outer node. This mechanism is designed for high-performance, copy-free data encoding and decoding in resource-constrained environments like the Polkadot SDK [Wasm runtime](/develop/parachains/deployment/build-deterministic-runtime/#introduction){target=\_blank}. +To deploy the contract, run the following command: -It is not self-describing, meaning the decoding context must fully know the encoded data types. +```bash +npx hardhat ignition deploy ./ignition/modules/MyToken.ts --network polkadotTestnet +``` -Parity's libraries utilize the [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} crate (a Rust implementation of the SCALE codec) to handle encoding and decoding for interactions between RPCs and the runtime. +You'll need to confirm the target network (by chain ID): -The `codec` mechanism is ideal for Polkadot SDK-based chains because: +
+ npx hardhat ignition deploy ./ignition/modules/MyToken.ts --network polkadotTestnet + ✔ Confirm deploy to network polkadotTestnet (420420420)? … yes +   + Hardhat Ignition 🚀 +   + Deploying [ TokenModule ] +   + Batch #1 + Executed TokenModule#MyToken +   + Batch #2 + Executed TokenModule#MyToken.mint +   + [ TokenModule ] successfully deployed 🚀 +   + Deployed Addresses +   + TokenModule#MyToken - 0xc01Ee7f10EA4aF4673cFff62710E1D7792aBa8f3 +
-- It is lightweight compared to generic serialization frameworks like [`serde`](https://serde.rs/){target=\_blank}, which add unnecessary bulk to binaries. -- It doesn’t rely on Rust’s `libstd`, making it compatible with `no_std` environments like Wasm runtime. -- It integrates seamlessly with Rust, allowing easy derivation of encoding and decoding logic for new types using `#[derive(Encode, Decode)]`. +And that is it! You've successfully deployed an ERC-20 token contract to the Polkadot TestNet using Hardhat. -Defining a custom encoding scheme in the Polkadot SDK-based chains, rather than using an existing Rust codec library, is crucial for enabling cross-platform and multi-language support. +## Where to Go Next -## SCALE Codec +
-The codec is implemented using the following traits: +- Guide __Deploy an NFT with Remix__ -- [`Encode`](#encode) -- [`Decode`](#decode) -- [`CompactAs`](#compactas) -- [`HasCompact`](#hascompact) -- [`EncodeLike`](#encodelike) + --- -### Encode + Walk through deploying an ERC-721 Non-Fungible Token (NFT) using OpenZeppelin's battle-tested NFT implementation and Remix. -The [`Encode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Encode.html){target=\_blank} trait handles data encoding into SCALE format and includes the following key functions: + [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) -- **`size_hint(&self) -> usize`**: Estimates the number of bytes required for encoding to prevent multiple memory allocations. This should be inexpensive and avoid complex operations. Optional if the size isn’t known. -- **`encode_to(&self, dest: &mut T)`**: Encodes the data, appending it to a destination buffer. -- **`encode(&self) -> Vec`**: Encodes the data and returns it as a byte vector. -- **`using_encoded R>(&self, f: F) -> R`**: Encodes the data and passes it to a closure, returning the result. -- **`encoded_size(&self) -> usize`**: Calculates the encoded size. Should be used when the encoded data isn’t required. +
-!!!tip - For best performance, value types should override `using_encoded`, and allocating types should override `encode_to`. It's recommended to implement `size_hint` for all types where possible. -### Decode +--- -The [`Decode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Decode.html){target=\_blank} trait handles decoding SCALE-encoded data back into the appropriate types: +Page Title: Deploy an ERC-20 to Polkadot Hub -- **`fn decode(value: &mut I) -> Result`**: Decodes data from the SCALE format, returning an error if decoding fails. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-erc20-erc20-remix.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix/ +- Summary: Deploy an ERC-20 token contract on Polkadot Hub. This guide covers contract creation, compilation, deployment, and interaction via the Remix IDE. -### CompactAs +# Deploy an ERC-20 to Polkadot Hub -The [`CompactAs`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.CompactAs.html){target=\_blank} trait wraps custom types for compact encoding: +## Introduction -- **`encode_as(&self) -> &Self::As`**: Encodes the type as a compact type. -- **`decode_from(_: Self::As) -> Result`**: decodes from a compact encoded type. +[ERC-20](https://eips.ethereum.org/EIPS/eip-20){target=\_blank} tokens are fungible tokens commonly used for creating cryptocurrencies, governance tokens, and staking mechanisms. Polkadot Hub enables easy token deployment with Ethereum-compatible smart contracts and tools via the EVM backend. -### HasCompact +This tutorial covers deploying an ERC-20 contract on the Polkadot Hub TestNet using [Remix IDE](https://remix.ethereum.org/){target=\_blank}, a web-based development tool. The ERC-20 contract can be retrieved from OpenZeppelin's [GitHub repository](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20){target=\_blank} or their [Contract Wizard](https://wizard.openzeppelin.com/){target=\_blank}. -The [`HasCompact`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.HasCompact.html){target=\_blank} trait indicates a type supports compact encoding. +## Prerequisites -### EncodeLike +Before starting, make sure you have: -The [`EncodeLike`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.EncodeLike.html){target=\_blank} trait is used to ensure multiple types that encode similarly are accepted by the same function. When using `derive`, it is automatically implemented. +- Basic understanding of Solidity programming and fungible tokens. +- An EVM-compatible wallet [connected to Polkadot Hub](/smart-contracts/integrations/wallets){target=\_blank}. This example utilizes [MetaMask](https://metamask.io/){target=\_blank}. +- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. -### Data Types +## Create Your Contract -The table below outlines how the Rust implementation of the Parity SCALE codec encodes different data types. +To create the ERC-20 contract, you can follow the steps below: -| Type | Description | Example SCALE Decoded Value | SCALE Encoded Value | -|-------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------| -| Boolean | Boolean values are encoded using the least significant bit of a single byte. | `false` / `true` | `0x00` / `0x01` | -| Compact/general integers | A "compact" or general integer encoding is sufficient for encoding large integers (up to 2^536) and is more efficient at encoding most values than the fixed-width version. | `unsigned integer 0` / `unsigned integer 1` / `unsigned integer 42` / `unsigned integer 69` / `unsigned integer 65535` / `BigInt(100000000000000)` | `0x00` / `0x04` / `0xa8` / `0x1501` / `0xfeff0300` / `0x0b00407a10f35a` | -| Enumerations (tagged-unions) | A fixed number of variants, each mutually exclusive and potentially implying a further value or series of values. Encoded as the first byte identifying the index of the variant that the value is. Any further bytes are used to encode any data that the variant implies. Thus, no more than 256 variants are supported. | `Int(42)` and `Bool(true)` where `enum IntOrBool { Int(u8), Bool(bool) }` | `0x002a` and `0x0101` | -| Fixed-width integers | Basic integers are encoded using a fixed-width little-endian (LE) format. | `signed 8-bit integer 69` / `unsigned 16-bit integer 42` / `unsigned 32-bit integer 16777215` | `0x45` / `0x2a00` / `0xffffff00` | -| Options | One or zero values of a particular type. | `Some` / `None` | `0x01` followed by the encoded value / `0x00` | -| Results | Results are commonly used enumerations which indicate whether certain operations were successful or unsuccessful. | `Ok(42)` / `Err(false)` | `0x002a` / `0x0100` | -| Strings | Strings are Vectors of bytes (Vec) containing a valid UTF8 sequence. | | | -| Structs | For structures, the values are named, but that is irrelevant for the encoding (names are ignored - only order matters). | `SortedVecAsc::from([3, 5, 2, 8])` | `[3, 2, 5, 8] ` | -| Tuples | A fixed-size series of values, each with a possibly different but predetermined and fixed type. This is simply the concatenation of each encoded value. | Tuple of compact unsigned integer and boolean: `(3, false)` | `0x0c00` | -| Vectors (lists, series, sets) | A collection of same-typed values is encoded, prefixed with a compact encoding of the number of items, followed by each item's encoding concatenated in turn. | Vector of unsigned `16`-bit integers: `[4, 8, 15, 16, 23, 42]` | `0x18040008000f00100017002a00` | +1. Navigate to the [Polkadot Remix IDE](https://remix.polkadot.io){target=\_blank}. +2. Click in the **Create new file** button under the **contracts** folder, and name your contract as `MyToken.sol`. -## Encode and Decode Rust Trait Implementations + ![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-1.webp) -Here's how the `Encode` and `Decode` traits are implemented: +3. Now, paste the following ERC-20 contract code into the editor: + ```solidity title="MyToken.sol" + // SPDX-License-Identifier: MIT + // Compatible with OpenZeppelin Contracts ^5.4.0 + pragma solidity ^0.8.27; -```rust -use parity_scale_codec::{Encode, Decode}; - -[derive(Debug, PartialEq, Encode, Decode)] -enum EnumType { - #[codec(index = 15)] - A, - B(u32, u64), - C { - a: u32, - b: u64, - }, -} + import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; + import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol"; + import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; -let a = EnumType::A; -let b = EnumType::B(1, 2); -let c = EnumType::C { a: 1, b: 2 }; + contract MyToken is ERC20, Ownable, ERC20Permit { + constructor(address initialOwner) + ERC20("MyToken", "MTK") + Ownable(initialOwner) + ERC20Permit("MyToken") + {} -a.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x0f"); -}); + function mint(address to, uint256 amount) public onlyOwner { + _mint(to, amount); + } + } + ``` -b.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); + The key components of the code above are: -c.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); + - Contract imports: -let mut da: &[u8] = b"\x0f"; -assert_eq!(EnumType::decode(&mut da).ok(), Some(a)); + - **[`ERC20.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20/ERC20.sol){target=\_blank}**: The base contract for fungible tokens, implementing core functionality like transfers, approvals, and balance tracking. + - **[`ERC20Permit.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20/extensions/ERC20Permit.sol){target=\_blank}**: [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612){target=\_blank} extension for ERC-20 that adds the [permit function](https://docs.openzeppelin.com/contracts/5.x/api/token/erc20#ERC20Permit-permit-address-address-uint256-uint256-uint8-bytes32-bytes32-){target=\_blank}, allowing approvals via off-chain signatures (no on-chain tx from the holder). Manages nonces and EIP-712 domain separator and updates allowances when a valid signature is presented. + - **[`Ownable.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/access/Ownable.sol){target=\_blank}**: Provides basic authorization control, ensuring only the contract owner can mint new tokens. + + - Constructor parameters: -let mut db: &[u8] = b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut db).ok(), Some(b)); + - **`initialOwner`**: Sets the address that will have administrative rights over the contract. + - **`"MyToken"`**: The full name of your token. + - **`"MTK"`**: The symbol representing your token in wallets and exchanges. -let mut dc: &[u8] = b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut dc).ok(), Some(c)); + - Key functions: -let mut dz: &[u8] = &[0]; -assert_eq!(EnumType::decode(&mut dz).ok(), None); -``` + - **`mint(address to, uint256 amount)`**: Allows the contract owner to create new tokens for any address. The amount should include 18 decimals (e.g., 1 token = 1000000000000000000). + - Inherited [Standard ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/){target=\_blank} functions: + - **`transfer(address recipient, uint256 amount)`**: Sends a specified amount of tokens to another address. + - **`approve(address spender, uint256 amount)`**: Grants permission for another address to spend a specific number of tokens on behalf of the token owner. + - **`transferFrom(address sender, address recipient, uint256 amount)`**: Transfers tokens from one address to another, if previously approved. + - **`balanceOf(address account)`**: Returns the token balance of a specific address. + - **`allowance(address owner, address spender)`**: Checks how many tokens an address is allowed to spend on behalf of another address. -## SCALE Codec Libraries + !!! tip + Use the [OpenZeppelin Contracts Wizard](https://wizard.openzeppelin.com/){target=\_blank} to generate customized smart contracts quickly. Simply configure your contract, copy the generated code, and paste it into the Remix IDE for deployment. Below is an example of an ERC-20 token contract created with it: -Several SCALE codec implementations are available in various languages. Here's a list of them: + ![Screenshot of the OpenZeppelin Contracts Wizard showing an ERC-20 contract configuration.](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-2.webp) + -- **AssemblyScript**: [`LimeChain/as-scale-codec`](https://github.com/LimeChain/as-scale-codec){target=\_blank} -- **C**: [`MatthewDarnell/cScale`](https://github.com/MatthewDarnell/cScale){target=\_blank} -- **C++**: [`qdrvm/scale-codec-cpp`](https://github.com/qdrvm/scale-codec-cpp){target=\_blank} -- **JavaScript**: [`polkadot-js/api`](https://github.com/polkadot-js/api){target=\_blank} -- **Dart**: [`leonardocustodio/polkadart`](https://github.com/leonardocustodio/polkadart){target=\_blank} -- **Haskell**: [`airalab/hs-web3`](https://github.com/airalab/hs-web3/tree/master/packages/scale){target=\_blank} -- **Golang**: [`itering/scale.go`](https://github.com/itering/scale.go){target=\_blank} -- **Java**: [`splix/polkaj`](https://github.com/splix/polkaj){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **Ruby**: [` wuminzhe/scale_rb`](https://github.com/wuminzhe/scale_rb){target=\_blank} -- **TypeScript**: [`parity-scale-codec-ts`](https://github.com/tjjfvi/subshape){target=\_blank}, [`scale-ts`](https://github.com/unstoppablejs/unstoppablejs/tree/main/packages/scale-ts#scale-ts){target=\_blank}, [`soramitsu/scale-codec-js-library`](https://github.com/soramitsu/scale-codec-js-library){target=\_blank}, [`subsquid/scale-codec`](https://github.com/subsquid/squid-sdk/tree/master/substrate/scale-codec){target=\_blank} +## Compile +The compilation transforms your Solidity source code into bytecode that can be deployed on the blockchain. During this process, the compiler checks your contract for syntax errors, ensures type safety, and generates the machine-readable instructions needed for blockchain execution. ---- +To compile your contract, ensure you have it opened in the Remix IDE Editor, and follow the instructions below: -Page Title: Dedot +1. Select the **Solidity Compiler** plugin from the left panel. +2. Click the **Compile MyToken.sol** button. +3. If the compilation succeeded, you'll see a green checkmark indicating success in the **Solidity Compiler** icon. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-dedot.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/dedot/ -- Summary: Dedot is a next-gen JavaScript client for Polkadot and Polkadot SDK-based blockchains, offering lightweight, tree-shakable APIs with strong TypeScript support. +![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-3.gif) -# Dedot +## Deploy -## Introduction +Deployment is the process of publishing your compiled smart contract to the blockchain, making it permanently available for interaction. During deployment, you'll create a new instance of your contract on the blockchain, which involves: -[Dedot](https://github.com/dedotdev/dedot){target=\_blank} is a next-generation JavaScript client for Polkadot and Polkadot SDK-based blockchains. Designed to elevate the dApp development experience, Dedot is built and optimized to be lightweight and tree-shakable, offering precise types and APIs suggestions for individual Polkadot SDK-based blockchains and [ink! smart contracts](https://use.ink/){target=\_blank}. +1. Select the **Deploy & Run Transactions** plugin from the left panel. +2. Configure the deployment settings: + 1. From the **ENVIRONMENT** dropdown, select **Injected Provider - MetaMask** (check the [Deploying Contracts](/smart-contracts/dev-environments/remix/deploy-a-contract/){target=\_blank} section of the Remix IDE guide for more details). + 2. (Optional) From the **ACCOUNT** dropdown, select the acccount you want to use for the deploy. -### Key Features +3. Configure the contract parameters: + 1. Enter the address that will own the deployed token contract. + 2. Click the **Deploy** button to initiate the deployment. -- **Lightweight and tree-shakable**: No more bn.js or WebAssembly blobs, optimized for dapps bundle size. -- **Fully typed API**: Comprehensive TypeScript support for seamless on-chain interaction and ink! smart contract integration. -- **Multi-version JSON-RPC support**: Compatible with both [legacy](https://github.com/w3f/PSPs/blob/master/PSPs/drafts/psp-6.md){target=\_blank} and [new](https://paritytech.github.io/json-rpc-interface-spec/introduction.html){target=\_blank} JSON-RPC APIs for broad ecosystem interoperability. -- **Light client support**: Designed to work with light clients such as [Smoldot](https://github.com/smol-dot/smoldot){target=\_blank}. -- **Native TypeScript for scale codec**: Implements scale codec parsing directly in TypeScript without relying on custom wrappers. -- **Wallet integration**: Works out-of-the-box with [@polkadot/extension-based](https://github.com/polkadot-js/extension?tab=readme-ov-file#api-interface){target=\_blank} wallets. -- **Familiar API design**: Similar API style to Polkadot.js for easy and fast migration. +4. **MetaMask will pop up**: Review the transaction details. Click **Confirm** to deploy your contract. +5. If the deployment process succeeded, you will see the transaction details in the terminal, including the contract address and deployment transaction hash. -## Installation +![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-4.gif) -To add Dedot to your project, use the following command: +## Interact with Your Contract -=== "npm" +Once deployed, you can interact with your contract through Remix. Find your contract under **Deployed/Unpinned Contracts**, and click it to expand the available methods. In this example, you'll mint some tokens to a given address: - ```bash - npm i dedot - ``` +1. Expand the **mint** function: + 1. Enter the recipient address and the amount (remember to add 18 zeros for 1 whole token). + 2. Click **transact**. -=== "pnpm" +2. Click **Approve** to confirm the transaction in the MetaMask popup. - ```bash - pnpm add dedot - ``` +3. If the transaction succeeds, you will see a green check mark in the terminal. -=== "yarn" +4. You can also call the **balanceOf** function by passing the address of the **mint** call to confirm the new balance. - ```bash - yarn add dedot - ``` +![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-5.gif) -To enable auto-completion/IntelliSense for individual chains, install the [`@dedot/chaintypes`](https://www.npmjs.com/package/@dedot/chaintypes){target=\_blank} package as a development dependency: -=== "npm" +Other standard functions you can use: - ```bash - npm i -D @dedot/chaintypes - ``` +- **`transfer(address to, uint256 amount)`**: Send tokens to another address. +- **`approve(address spender, uint256 amount)`**: Allow another address to spend your tokens. -=== "pnpm" +Feel free to explore and interact with the contract's other functions using the same approach: select the method, provide any required parameters, and confirm the transaction in MetaMask when needed. - ```bash - pnpm add -D @dedot/chaintypes - ``` +## Where to Go Next -=== "yarn" +
- ```bash - yarn add -D @dedot/chaintypes - ``` +- Guide __Deploy an NFT with Remix__ -## Get Started + --- -### Initialize a Client Instance + Walk through deploying an ERC-721 Non-Fungible Token (NFT) using OpenZeppelin's battle-tested NFT implementation and Remix. -To connect to and interact with different networks, Dedot provides two client options depending on your needs: + [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) -- **[`DedotClient`](https://docs.dedot.dev/clients-and-providers/clients#dedotclient){target=\_blank}**: Interacts with chains via the [new JSON-RPC APIs](https://paritytech.github.io/json-rpc-interface-spec/introduction.html){target=\_blank}. -- **[`LegacyClient`](https://docs.dedot.dev/clients-and-providers/clients#legacyclient){target=\_blank}**: Interacts with chains via the [legacy JSON-RPC APIs](https://github.com/w3f/PSPs/blob/master/PSPs/drafts/psp-6.md){target=\_blank}. +
-Use the following snippets to connect to Polkadot using `DedotClient`: -=== "WebSocket" +--- - ```typescript - import { DedotClient, WsProvider } from 'dedot'; - import type { PolkadotApi } from '@dedot/chaintypes'; +Page Title: Deploy an NFT to Polkadot Hub with Foundry - // Initialize providers & clients - const provider = new WsProvider('wss://rpc.polkadot.io'); - const client = await DedotClient.new(provider); +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-.foundry.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/.foundry/ +- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub using Foundry, a Rust toolkit with high-performance compilation. - ``` +# Deploy an NFT with Foundry -=== "Light Client (Smoldot)" +## Introduction - ```typescript - import { DedotClient, SmoldotProvider } from 'dedot'; - import type { PolkadotApi } from '@dedot/chaintypes'; - import * as smoldot from 'smoldot'; +Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. - // import `polkadot` chain spec to connect to Polkadot - import { polkadot } from '@substrate/connect-known-chains'; +This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. It showcases a secure approach using [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and the [Foundry](https://getfoundry.sh/){target=\_blank} toolchain. Foundry, a fast, Rust-written toolkit, ensures high-performance compilation and is fully compatible with the Hub’s EVM environment via standard Solidity compilation. - // Start smoldot instance & initialize a chain - const client = smoldot.start(); - const chain = await client.addChain({ chainSpec: polkadot }); +## Prerequisites - // Initialize providers & clients - const provider = new SmoldotProvider(chain); - const client = await DedotClient.new(provider); +- Basic understanding of Solidity programming and NFT standards. +- Test tokens for gas fees (available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}). See the [step-by-step instructions](/smart-contracts/faucet/#get-test-tokens){target=\_blank}. +- A wallet with a private key for signing transactions. - ``` +## Set Up Your Project -If the node doesn't support new JSON-RPC APIs yet, you can connect to the network using the `LegacyClient`, which is built on top of the legacy JSON-RPC APIs. +To get started, take the following steps: -```typescript -import { LegacyClient, WsProvider } from 'dedot'; -import type { PolkadotApi } from '@dedot/chaintypes'; +1. Install Foundry: -const provider = new WsProvider('wss://rpc.polkadot.io'); -const client = await LegacyClient.new(provider); + ```bash + curl -L https://foundry.paradigm.xyz | bash + foundryup + ``` -``` +2. Initialize your project: -### Enable Type and API Suggestions + ```bash + forge init foundry-nft-deployment + cd foundry-nft-deployment + ``` -It is recommended to specify the `ChainApi` interface (e.g., `PolkadotApi` in the example in the previous section) of the chain you want to interact with. This enables type and API suggestions/autocompletion for that particular chain (via IntelliSense). If you don't specify a `ChainApi` interface, a default `SubstrateApi` interface will be used. +3. Install OpenZeppelin contracts: -```typescript -import { DedotClient, WsProvider } from 'dedot'; -import type { PolkadotApi, KusamaApi } from '@dedot/chaintypes'; + ```bash + forge install OpenZeppelin/openzeppelin-contracts + ``` -const polkadotClient = await DedotClient.new( - new WsProvider('wss://rpc.polkadot.io') -); -const kusamaClient = await DedotClient.new( - new WsProvider('wss://kusama-rpc.polkadot.io') -); -const genericClient = await DedotClient.new( - new WsProvider('ws://localhost:9944') -); +## Configure Foundry -``` +Edit `foundry.toml`: -If you don't find the `ChainApi` for the network you're working with in [the list](https://github.com/dedotdev/chaintypes?tab=readme-ov-file#supported-networks){target=\_blank}, you can generate the `ChainApi` (types and APIs) using the built-in [`dedot` cli](https://docs.dedot.dev/cli){target=\_blank}. +```toml title="foundry.toml" +[profile.default] +src = "src" +out = "out" +libs = ["lib"] +remappings = ['@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/'] -```bash -# Generate ChainApi interface for Polkadot network via rpc endpoint: wss://rpc.polkadot.io -npx dedot chaintypes -w wss://rpc.polkadot.io +[rpc_endpoints] +polkadot_hub_testnet = "https://testnet-passet-hub-eth-rpc.polkadot.io" ``` -Or open a pull request to add your favorite network to the [`@dedot/chaintypes`](https://github.com/dedotdev/chaintypes){target=\_blank} repo. - -### Read On-Chain Data +## Create Your Contract -Dedot provides several ways to read data from the chain: +Create `src/MyNFT.sol`: -- **Access runtime constants**: Use the syntax `client.consts..` to inspect runtime constants (parameter types). +```solidity title="src/MyNFT.sol" +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; - ```typescript - const ss58Prefix = client.consts.system.ss58Prefix; - console.log('Polkadot ss58Prefix:', ss58Prefix); +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/access/Ownable.sol"; - ``` +contract MyNFT is ERC721, Ownable { + uint256 private _nextTokenId; -- **Storage queries**: Use the syntax `client.query..` to query on-chain storage. + constructor(address initialOwner) + ERC721("MyToken", "MTK") + Ownable(initialOwner) + {} - ```typescript - const balance = await client.query.system.account('INSERT_ADDRESS'); - console.log('Balance:', balance.data.free); + function safeMint(address to) public onlyOwner { + uint256 tokenId = _nextTokenId++; + _safeMint(to, tokenId); + } +} +``` - ``` +## Compile -- **Subscribe to storage changes**: +```bash +forge build +``` - ```typescript - const unsub = await client.query.system.number((blockNumber) => { - console.log(`Current block number: ${blockNumber}`); - }); +Verify the compilation by inspecting the bytecode: - ``` +```bash +forge inspect MyNFT bytecode +``` -- **Call Runtime APIs**: Use the syntax `client.call..` to execute Runtime APIs. +## Deploy - ```typescript - const metadata = await client.call.metadata.metadataAtVersion(15); - console.log('Metadata V15', metadata); +Deploy to Polkadot Hub TestNet: - ``` +```bash +forge create MyNFT \ + --rpc-url polkadot_hub_testnet \ + --private-key YOUR_PRIVATE_KEY \ + --constructor-args YOUR_OWNER_ADDRESS \ + --broadcast +``` -- **Watch on-chain events**: Use the syntax `client.events..` to access pallet events. - - ```typescript - const unsub = await client.events.system.NewAccount.watch((events) => { - console.log('New Account Created', events); - }); +Replace `YOUR_PRIVATE_KEY` with your private key and `YOUR_OWNER_ADDRESS` with the address that will own the NFT contract. - ``` +## Where to Go Next -### Sign and Send Transactions - -Sign the transaction using `IKeyringPair` from Keyring ([`@polkadot/keyring`](https://polkadot.js.org/docs/keyring/start/sign-verify/){target=\_blank}) and send the transaction. - -```typescript -import { cryptoWaitReady } from '@polkadot/util-crypto'; -import { Keyring } from '@polkadot/keyring'; -// Setup keyring -await cryptoWaitReady(); -const keyring = new Keyring({ type: 'sr25519' }); -const alice = keyring.addFromUri('//Alice'); -// Send transaction -const unsub = await client.tx.balances - .transferKeepAlive('INSERT_DEST_ADDRESS', 2_000_000_000_000n) - .signAndSend(alice, async ({ status }) => { - console.log('Transaction status', status.type); - if (status.type === 'BestChainBlockIncluded') { - console.log(`Transaction is included in best block`); - } - if (status.type === 'Finalized') { - console.log( - `Transaction completed at block hash ${status.value.blockHash}` - ); - await unsub(); - } - }); +
-``` +- Guide __Verify Your Contract__ -You can also use `Signer` from wallet extensions: + --- -```typescript -const injected = await window.injectedWeb3['polkadot-js'].enable('My dApp'); -const account = (await injected.accounts.get())[0]; -const signer = injected.signer; -const unsub = await client.tx.balances - .transferKeepAlive('INSERT_DEST_ADDRESS', 2_000_000_000_000n) - .signAndSend(account.address, { signer }, async ({ status }) => { - console.log('Transaction status', status.type); - if (status.type === 'BestChainBlockIncluded') { - console.log(`Transaction is included in best block`); - } - if (status.type === 'Finalized') { - console.log( - `Transaction completed at block hash ${status.value.blockHash}` - ); - await unsub(); - } - }); + Now that you've deployed an NFT contract, learn how to verify it with Foundry. -``` + [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/foundry/verify-a-contract/) -## Where to Go Next +- Guide __Deploy an ERC-20__ + + --- + + Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Foundry. + + [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/foundry/) -For more detailed information about Dedot, check the [official documentation](https://dedot.dev/){target=\_blank}. +
--- -Page Title: Deploy an ERC-20 to Polkadot Hub +Page Title: Deploy an NFT to Polkadot Hub with Hardhat -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-erc20-erc20-hardhat.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-hardhat/ -- Summary: Deploy an ERC-20 token on Polkadot Hub using PolkaVM. This guide covers contract creation, compilation, deployment, and interaction via Hardhat. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-hardhat.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/hardhat/ +- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub with Hardhat, a comprehenive development environment with built-in deployment capabilities. -# Deploy an ERC-20 to Polkadot Hub +# Deploy an NFT with Hardhat ## Introduction -[ERC-20](https://eips.ethereum.org/EIPS/eip-20){target=\_blank} tokens are fungible tokens commonly used for creating cryptocurrencies, governance tokens, and staking mechanisms. Polkadot Hub enables easy token deployment with Ethereum-compatible smart contracts and tools via the EVM backend. +Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. -This tutorial covers deploying an ERC-20 contract on the Polkadot Hub TestNet using [Hardhat](https://hardhat.org/){target=\_blank}, an Ethereum development environment. The ERC-20 contract can be retrieved from OpenZeppelin's [GitHub repository](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20){target=\_blank} or their [Contract Wizard](https://wizard.openzeppelin.com/){target=\_blank}. +This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. You'll use [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and [Hardhat](https://hardhat.org/docs/getting-started){target=\_blank}, a comprehensive development environment with built-in testing, debugging, and deployment capabilities. Hardhat uses standard Solidity compilation to generate EVM bytecode, making it fully compatible with Polkadot Hub's EVM environment. ## Prerequisites -Before starting, make sure you have: - -- Basic understanding of Solidity programming and fungible tokens. +- Basic understanding of Solidity programming and NFT standards. - Node.js v22.13.1 or later. - A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. +- A wallet with a private key for signing transactions. ## Set Up Your Project -This tutorial uses a [Hardhat ERC-20 template](https://github.com/polkadot-developers/revm-hardhat-examples/tree/master/erc20-hardhat){target=\_blank} that contains all the necessary files. To get started, take the following steps: +Take the following steps to get started: -1. Clone the GitHub repository locally: +1. Initialize your Hardhat project: ```bash - git clone https://github.com/polkadot-developers/revm-hardhat-examples/ - cd revm-hardhat-examples/erc20-hardhat + mkdir hardhat-nft-deployment + cd hardhat-nft-deployment + npx hardhat --init ``` -2. Install the dependencies: +2. Install OpenZeppelin contracts: ```bash - npm i + npm install @openzeppelin/contracts ``` -This will fetch all the necessary packages to help you deploy an ERC-20 with Hardhat to Polkadot. - ## Configure Hardhat -Once you've [setup your project](#set-up-your-project), you can configure the `hardhat.config.ts` to your needs. This tutorial has the file prepared to deploy to the Polkadot TestNet. - -To store and use private keys or network URLs, you can use Hardhat's configuration variables. This can be set via tasks in the **vars** scope. For example, to store the private key to deploy to the Polkadot TestNet, run the following command: - -```bash -npx hardhat vars set TESTNET_PRIVATE_KEY -``` - -The command will initiate a wizard in which you'll have to enter the value to be stored: - -
- npx hardhat vars set TESTNET_PRIVATE_KEY - ✔ Enter value: · ••••••••• - The configuration variable has been stored in /Users/albertoviera/Library/Preferences/hardhat-nodejs/vars.json -
- -??? warning "Key Encryption" - This solution just prevents variables to be included in the code repository. You should find a solution that encrypts private keys and access them securely. +Edit `hardhat.config.ts`: -You can now use the account related to this private key by importing it into the Hardhat configuration file: +```typescript title="hardhat.config.ts" +import type { HardhatUserConfig } from 'hardhat/config'; -```ts title="hardhat.config.ts" hl_lines="1 17" +import hardhatToolboxViemPlugin from '@nomicfoundation/hardhat-toolbox-viem'; +import { configVariable } from 'hardhat/config'; const config: HardhatUserConfig = { + plugins: [hardhatToolboxViemPlugin], solidity: { - version: "0.8.28", - settings: { - optimizer: { - enabled: true, - runs: 200, + profiles: { + default: { + version: '0.8.28', + }, + production: { + version: '0.8.28', + settings: { + optimizer: { + enabled: true, + runs: 200, + }, + }, }, }, }, networks: { - polkadotTestnet: { - url: vars.get("TESTNET_URL", "http://127.0.0.1:8545"), - accounts: vars.has("TESTNET_PRIVATE_KEY") ? [vars.get("TESTNET_PRIVATE_KEY")] : [], + hardhatMainnet: { + type: 'edr-simulated', + chainType: 'l1', + }, + hardhatOp: { + type: 'edr-simulated', + chainType: 'op', + }, + sepolia: { + type: 'http', + chainType: 'l1', + url: configVariable('SEPOLIA_RPC_URL'), + accounts: [configVariable('SEPOLIA_PRIVATE_KEY')], + }, + polkadotHubTestnet: { + type: 'http', + url: 'https://testnet-passet-hub-eth-rpc.polkadot.io', + chainId: 420420422, + accounts: [configVariable('PRIVATE_KEY')], }, - }, - mocha: { - timeout: 40000, }, }; export default config; ``` -## Compile your Contract - -Once you've configured Hardhat, you can compile the contract. - -In this tutorial, a simple ERC-20 is provided. Therefore, to compile the contract you can run the following command: +!!! tip + Learn how to use Hardhat's [Config Variables](https://hardhat.org/docs/learn-more/configuration-variables){target=\_blank} to handle your private keys in a secure way. -```bash -npx hardhat compile -``` +## Create Your Contract -If everything compiles successfully, you should see the following output: +Create `contracts/MyNFT.sol`: -
- npx hardhat compile - Generating typings for: 23 artifacts in dir: typechain-types for target: ethers-v6 - Successfully generated 62 typings! - Compiled 21 Solidity files successfully (evm target: paris). -
+```solidity title="contracts/MyNFT.sol" +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.20; -## Test your Contract +import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; +import "@openzeppelin/contracts/access/Ownable.sol"; -Hardhat has a native feature to test contracts. You can run tests against the local Hardhat development node, but it could have some technical differences to Polkadot. Therefore, in this tutorial, you'll be testing against the Polkadot TestNet +contract MyNFT is ERC721, Ownable { + uint256 private _nextTokenId; -This example has a predefined test file located in [`test/Token.test.js`](https://github.com/polkadot-developers/revm-hardhat-examples/blob/master/erc20-hardhat/test/MyToken.test.ts){target=\_blank}, that runs the following tests: + constructor(address initialOwner) + ERC721("MyToken", "MTK") + Ownable(initialOwner) + {} -1. The token was deployed by verifying its **name** and **symbol**. -2. The token has the right owner configured. -3. The token has an initial supply of zero. -4. The owner can mint tokens. -5. The total supply is increased after a mint. -6. Perform multiple mints to different addresses and checks the balance of each address and the new total supply. + function safeMint(address to) public onlyOwner { + uint256 tokenId = _nextTokenId++; + _safeMint(to, tokenId); + } +} +``` -To run the test, you can execute the following command: +## Compile ```bash -npx hardhat test --network polkadotTestnet +npx hardhat compile ``` -If tests are successful, you should see the following logs: - -
- npx hardhat test --network polkadotTestnet - -   MyToken -     Deployment -       ✔ Should have correct name and symbol -       ✔ Should set the right owner -       ✔ Should have zero initial supply -     Minting -       ✔ Should allow owner to mint tokens -       ✔ Should increase total supply on mint -     Multiple mints -       ✔ Should correctly track balance after multiple mints - -   6 passing (369ms) -
- -## Deploy your Contract +## Set Up Deployment -With the Hardhat configuration file ready, the private key stored as a variable under **vars**, and the contract compiled, you can proceed to deploy the contract to a given network. In this tutorial, you are deploying it to the Polkadot TestNet. +Create a deployment module in `ignition/modules/MyNFT.ts`: -To deploy the contract, run the following command: +```typescript title="ignition/modules/MyNFT.ts" +import { buildModule } from '@nomicfoundation/hardhat-ignition/modules'; -```bash -npx hardhat ignition deploy ./ignition/modules/MyToken.ts --network polkadotTestnet +export default buildModule('MyNFTModule', (m) => { + const initialOwner = m.getParameter('initialOwner', 'INSERT_OWNER_ADDRESS'); + const myNFT = m.contract('MyNFT', [initialOwner]); + return { myNFT }; +}); ``` -You'll need to confirm the target network (by chain ID): +Replace `INSERT_OWNER_ADDRESS` with your desired owner address. -
- npx hardhat ignition deploy ./ignition/modules/MyToken.ts --network polkadotTestnet - ✔ Confirm deploy to network polkadotTestnet (420420420)? … yes -   - Hardhat Ignition 🚀 -   - Deploying [ TokenModule ] -   - Batch #1 - Executed TokenModule#MyToken -   - Batch #2 - Executed TokenModule#MyToken.mint -   - [ TokenModule ] successfully deployed 🚀 -   - Deployed Addresses -   - TokenModule#MyToken - 0xc01Ee7f10EA4aF4673cFff62710E1D7792aBa8f3 -
+## Deploy -And that is it! You've successfully deployed an ERC-20 token contract to the Polkadot TestNet using Hardhat. +Deploy to Polkadot Hub TestNet: + +```bash +npx hardhat ignition deploy ignition/modules/MyNFT.ts --network polkadotHubTestnet +``` ## Where to Go Next
-- Guide __Deploy an NFT with Remix__ +- Guide __Verify Your Contract__ --- - Walk through deploying an ERC-721 Non-Fungible Token (NFT) using OpenZeppelin's battle-tested NFT implementation and Remix. + Now that you've deployed an NFT contract, learn how to verify it with Hardhat. - [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) + [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/hardhat/verify-a-contract/) -
+ +- Guide __Deploy an ERC-20__ + + --- + + Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Hardhat. + + [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/hardhat/) + + --- -Page Title: Deploy an ERC-20 to Polkadot Hub +Page Title: Deploy an NFT to Polkadot Hub with Remix -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-erc20-erc20-remix.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix/ -- Summary: Deploy an ERC-20 token contract on Polkadot Hub. This guide covers contract creation, compilation, deployment, and interaction via the Remix IDE. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-remix.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/ +- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub using Remix, a browser-based IDE for quick prototyping and learning. -# Deploy an ERC-20 to Polkadot Hub +# Deploy an NFT with Remix ## Introduction -[ERC-20](https://eips.ethereum.org/EIPS/eip-20){target=\_blank} tokens are fungible tokens commonly used for creating cryptocurrencies, governance tokens, and staking mechanisms. Polkadot Hub enables easy token deployment with Ethereum-compatible smart contracts and tools via the EVM backend. +Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. -This tutorial covers deploying an ERC-20 contract on the Polkadot Hub TestNet using [Remix IDE](https://remix.ethereum.org/){target=\_blank}, a web-based development tool. The ERC-20 contract can be retrieved from OpenZeppelin's [GitHub repository](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20){target=\_blank} or their [Contract Wizard](https://wizard.openzeppelin.com/){target=\_blank}. +This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. You'll use [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and [Remix](https://remix.ethereum.org/){target=\_blank}, a visual, browser-based environment perfect for rapid prototyping and learning. It requires no local installation and provides an intuitive interface for contract development. ## Prerequisites -Before starting, make sure you have: - -- Basic understanding of Solidity programming and fungible tokens. -- An EVM-compatible wallet [connected to Polkadot Hub](/smart-contracts/integrations/wallets){target=\_blank}. This example utilizes [MetaMask](https://metamask.io/){target=\_blank}. -- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. +- Basic understanding of Solidity programming and NFT standards. +- Test tokens for gas fees (available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}). See the [step-by-step instructions](/smart-contracts/faucet/#get-test-tokens){target=\_blank} +- A wallet with a private key for signing transactions. -## Create Your Contract +## Access Remix -To create the ERC-20 contract, you can follow the steps below: +Navigate to [Remix](https://remix.ethereum.org/){target=\_blank} in your web browser. -1. Navigate to the [Polkadot Remix IDE](https://remix.polkadot.io){target=\_blank}. -2. Click in the **Create new file** button under the **contracts** folder, and name your contract as `MyToken.sol`. +The interface will load with a default workspace containing sample contracts. In this interface, you can access a file explorer, edit your code, interact with various plugins for development, and use a terminal. - ![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-1.webp) +## Create Your Contract -3. Now, paste the following ERC-20 contract code into the editor: +1. Create a new file `contracts/MyNFT.sol`. +2. Paste the following code: - ```solidity title="MyToken.sol" + ```solidity title="contracts/MyNFT.sol" // SPDX-License-Identifier: MIT - // Compatible with OpenZeppelin Contracts ^5.4.0 - pragma solidity ^0.8.27; + pragma solidity ^0.8.20; - import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; - import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol"; - import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; + import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; + import "@openzeppelin/contracts/access/Ownable.sol"; + + contract MyNFT is ERC721, Ownable { + uint256 private _nextTokenId; - contract MyToken is ERC20, Ownable, ERC20Permit { constructor(address initialOwner) - ERC20("MyToken", "MTK") + ERC721("MyToken", "MTK") Ownable(initialOwner) - ERC20Permit("MyToken") {} - function mint(address to, uint256 amount) public onlyOwner { - _mint(to, amount); + function safeMint(address to) public onlyOwner { + uint256 tokenId = _nextTokenId++; + _safeMint(to, tokenId); } } ``` - The key components of the code above are: +![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-01.webp) - - Contract imports: +## Compile - - **[`ERC20.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20/ERC20.sol){target=\_blank}**: The base contract for fungible tokens, implementing core functionality like transfers, approvals, and balance tracking. - - **[`ERC20Permit.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/token/ERC20/extensions/ERC20Permit.sol){target=\_blank}**: [EIP-2612](https://eips.ethereum.org/EIPS/eip-2612){target=\_blank} extension for ERC-20 that adds the [permit function](https://docs.openzeppelin.com/contracts/5.x/api/token/erc20#ERC20Permit-permit-address-address-uint256-uint256-uint8-bytes32-bytes32-){target=\_blank}, allowing approvals via off-chain signatures (no on-chain tx from the holder). Manages nonces and EIP-712 domain separator and updates allowances when a valid signature is presented. - - **[`Ownable.sol`](https://github.com/OpenZeppelin/openzeppelin-contracts/tree/v5.4.0/contracts/access/Ownable.sol){target=\_blank}**: Provides basic authorization control, ensuring only the contract owner can mint new tokens. - - - Constructor parameters: +1. Navigate to the **Solidity Compiler** tab (third icon in the left sidebar). +2. Click **Compile MyNFT.sol** or press `Ctrl+S`. - - **`initialOwner`**: Sets the address that will have administrative rights over the contract. - - **`"MyToken"`**: The full name of your token. - - **`"MTK"`**: The symbol representing your token in wallets and exchanges. +![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-02.webp) - - Key functions: +Compilation errors and warnings appear in the terminal panel at the bottom of the screen. - - **`mint(address to, uint256 amount)`**: Allows the contract owner to create new tokens for any address. The amount should include 18 decimals (e.g., 1 token = 1000000000000000000). - - Inherited [Standard ERC-20](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/){target=\_blank} functions: - - **`transfer(address recipient, uint256 amount)`**: Sends a specified amount of tokens to another address. - - **`approve(address spender, uint256 amount)`**: Grants permission for another address to spend a specific number of tokens on behalf of the token owner. - - **`transferFrom(address sender, address recipient, uint256 amount)`**: Transfers tokens from one address to another, if previously approved. - - **`balanceOf(address account)`**: Returns the token balance of a specific address. - - **`allowance(address owner, address spender)`**: Checks how many tokens an address is allowed to spend on behalf of another address. +## Deploy - !!! tip - Use the [OpenZeppelin Contracts Wizard](https://wizard.openzeppelin.com/){target=\_blank} to generate customized smart contracts quickly. Simply configure your contract, copy the generated code, and paste it into the Remix IDE for deployment. Below is an example of an ERC-20 token contract created with it: +1. Navigate to the **Deploy & Run Transactions** tab. +2. Click the **Environment** dropdown, select **Browser Extension**, and click on **Injected Provider - MetaMask**. - ![Screenshot of the OpenZeppelin Contracts Wizard showing an ERC-20 contract configuration.](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-2.webp) - + ![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-03.webp) -## Compile +3. In the deploy section, enter the initial owner address in the constructor parameter field. +4. Click **Deploy**. -The compilation transforms your Solidity source code into bytecode that can be deployed on the blockchain. During this process, the compiler checks your contract for syntax errors, ensures type safety, and generates the machine-readable instructions needed for blockchain execution. + ![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-04.webp) -To compile your contract, ensure you have it opened in the Remix IDE Editor, and follow the instructions below: +5. Approve the transaction in your MetaMask wallet. -1. Select the **Solidity Compiler** plugin from the left panel. -2. Click the **Compile MyToken.sol** button. -3. If the compilation succeeded, you'll see a green checkmark indicating success in the **Solidity Compiler** icon. +Your deployed contract will appear in the **Deployed Contracts** section, ready for interaction. -![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-3.gif) +## Where to Go Next -## Deploy +
-Deployment is the process of publishing your compiled smart contract to the blockchain, making it permanently available for interaction. During deployment, you'll create a new instance of your contract on the blockchain, which involves: +- Guide __Verify Your Contract__ -1. Select the **Deploy & Run Transactions** plugin from the left panel. -2. Configure the deployment settings: - 1. From the **ENVIRONMENT** dropdown, select **Injected Provider - MetaMask** (check the [Deploying Contracts](/smart-contracts/dev-environments/remix/deploy-a-contract/){target=\_blank} section of the Remix IDE guide for more details). - 2. (Optional) From the **ACCOUNT** dropdown, select the acccount you want to use for the deploy. + --- -3. Configure the contract parameters: - 1. Enter the address that will own the deployed token contract. - 2. Click the **Deploy** button to initiate the deployment. + Now that you've deployed an NFT contract, learn how to verify it with Remix. -4. **MetaMask will pop up**: Review the transaction details. Click **Confirm** to deploy your contract. -5. If the deployment process succeeded, you will see the transaction details in the terminal, including the contract address and deployment transaction hash. + [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/remix/verify-a-contract/) -![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-4.gif) +- Guide __Deploy an ERC-20__ -## Interact with Your Contract + --- -Once deployed, you can interact with your contract through Remix. Find your contract under **Deployed/Unpinned Contracts**, and click it to expand the available methods. In this example, you'll mint some tokens to a given address: + Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Remix. -1. Expand the **mint** function: - 1. Enter the recipient address and the amount (remember to add 18 zeros for 1 whole token). - 2. Click **transact**. + [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/) -2. Click **Approve** to confirm the transaction in the MetaMask popup. +
-3. If the transaction succeeds, you will see a green check mark in the terminal. -4. You can also call the **balanceOf** function by passing the address of the **mint** call to confirm the new balance. +--- -![](/images/smart-contracts/cookbook/smart-contracts/deploy-erc20/erc20-remix-5.gif) +Page Title: Deploy Contracts to Polkadot Hub with Ethers.js +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-libraries-ethers-js.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/libraries/ethers-js/ +- Summary: Learn how to interact with Polkadot Hub using Ethers.js, from compiling and deploying Solidity contracts to interacting with deployed smart contracts. -Other standard functions you can use: +# Ethers.js -- **`transfer(address to, uint256 amount)`**: Send tokens to another address. -- **`approve(address spender, uint256 amount)`**: Allow another address to spend your tokens. +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. +## Introduction -Feel free to explore and interact with the contract's other functions using the same approach: select the method, provide any required parameters, and confirm the transaction in MetaMask when needed. +[Ethers.js](https://docs.ethers.org/v6/){target=\_blank} is a lightweight library that enables interaction with Ethereum Virtual Machine (EVM)-compatible blockchains through JavaScript. Ethers is widely used as a toolkit to establish connections and read and write blockchain data. This article demonstrates using Ethers.js to interact and deploy smart contracts to Polkadot Hub. -## Where to Go Next +This guide is intended for developers who are familiar with JavaScript and want to interact with Polkadot Hub using Ethers.js. -
+## Prerequisites -- Guide __Deploy an NFT with Remix__ +Before getting started, ensure you have the following installed: - --- +- **Node.js**: v22.13.1 or later, check the [Node.js installation guide](https://nodejs.org/en/download/current/){target=\_blank}. +- **npm**: v6.13.4 or later (comes bundled with Node.js). +- **Solidity**: This guide uses Solidity `^0.8.9` for smart contract development. - Walk through deploying an ERC-721 Non-Fungible Token (NFT) using OpenZeppelin's battle-tested NFT implementation and Remix. +## Project Structure - [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) +This project organizes contracts, scripts, and compiled artifacts for easy development and deployment. -
+```text title="Ethers.js Polkadot Hub" +ethers-project +├── contracts +│ ├── Storage.sol +├── scripts +│ ├── connectToProvider.js +│ ├── fetchLastBlock.js +│ ├── compile.js +│ ├── deploy.js +│ ├── checkStorage.js +├── abis +│ ├── Storage.json +├── artifacts +│ ├── Storage.polkavm +├── contract-address.json +├── node_modules/ +├── package.json +├── package-lock.json +└── README.md +``` + +## Set Up the Project +To start working with Ethers.js, create a new folder and initialize your project by running the following commands in your terminal: ---- +```bash +mkdir ethers-project +cd ethers-project +npm init -y +``` -Page Title: Deploy an NFT to Polkadot Hub with Foundry +## Install Dependencies -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-.foundry.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/.foundry/ -- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub using Foundry, a Rust toolkit with high-performance compilation. +Next, run the following command to install the Ethers.js library: -# Deploy an NFT with Foundry +```bash +npm install ethers +``` -## Introduction +## Set Up the Ethers.js Provider -Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. +A [`Provider`](https://docs.ethers.org/v6/api/providers/#Provider){target=\_blank} is an abstraction of a connection to the Ethereum network, allowing you to query blockchain data and send transactions. It serves as a bridge between your application and the blockchain. -This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. It showcases a secure approach using [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and the [Foundry](https://getfoundry.sh/){target=\_blank} toolchain. Foundry, a fast, Rust-written toolkit, ensures high-performance compilation and is fully compatible with the Hub’s EVM environment via standard Solidity compilation. +To interact with Polkadot Hub, you must set up an Ethers.js provider. This provider connects to a blockchain node, allowing you to query blockchain data and interact with smart contracts. In the root of your project, create a file named `connectToProvider.js` and add the following code: -## Prerequisites +```js title="scripts/connectToProvider.js" +const { JsonRpcProvider } = require('ethers'); -- Basic understanding of Solidity programming and NFT standards. -- Test tokens for gas fees (available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}). See the [step-by-step instructions](/smart-contracts/faucet/#get-test-tokens){target=\_blank}. -- A wallet with a private key for signing transactions. +const createProvider = (rpcUrl, chainId, chainName) => { + const provider = new JsonRpcProvider(rpcUrl, { + chainId: chainId, + name: chainName, + }); -## Set Up Your Project + return provider; +}; -To get started, take the following steps: +const PROVIDER_RPC = { + rpc: 'INSERT_RPC_URL', + chainId: 'INSERT_CHAIN_ID', + name: 'INSERT_CHAIN_NAME', +}; -1. Install Foundry: +createProvider(PROVIDER_RPC.rpc, PROVIDER_RPC.chainId, PROVIDER_RPC.name); - ```bash - curl -L https://foundry.paradigm.xyz | bash - foundryup - ``` +``` -2. Initialize your project: +!!! note + Replace `INSERT_RPC_URL`, `INSERT_CHAIN_ID`, and `INSERT_CHAIN_NAME` with the appropriate values. For example, to connect to Polkadot Hub TestNet's Ethereum RPC instance, you can use the following parameters: - ```bash - forge init foundry-nft-deployment - cd foundry-nft-deployment + ```js + const PROVIDER_RPC = { + rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', + chainId: 420420422, + name: 'polkadot-hub-testnet' + }; ``` -3. Install OpenZeppelin contracts: +To connect to the provider, execute: - ```bash - forge install OpenZeppelin/openzeppelin-contracts - ``` +```bash +node connectToProvider +``` -## Configure Foundry +With the provider set up, you can start querying the blockchain. For instance, to fetch the latest block number: -Edit `foundry.toml`: +??? code "Fetch Last Block code" -```toml title="foundry.toml" -[profile.default] -src = "src" -out = "out" -libs = ["lib"] -remappings = ['@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/'] + ```js title="scripts/fetchLastBlock.js" + const { JsonRpcProvider } = require('ethers'); -[rpc_endpoints] -polkadot_hub_testnet = "https://testnet-passet-hub-eth-rpc.polkadot.io" -``` + const createProvider = (rpcUrl, chainId, chainName) => { + const provider = new JsonRpcProvider(rpcUrl, { + chainId: chainId, + name: chainName, + }); -## Create Your Contract + return provider; + }; -Create `src/MyNFT.sol`: + const PROVIDER_RPC = { + rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', + chainId: 420420422, + name: 'polkadot-hub-testnet', + }; -```solidity title="src/MyNFT.sol" -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.20; + const main = async () => { + try { + const provider = createProvider( + PROVIDER_RPC.rpc, + PROVIDER_RPC.chainId, + PROVIDER_RPC.name, + ); + const latestBlock = await provider.getBlockNumber(); + console.log(`Latest block: ${latestBlock}`); + } catch (error) { + console.error('Error connecting to Polkadot Hub TestNet: ' + error.message); + } + }; -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "@openzeppelin/contracts/access/Ownable.sol"; + main(); -contract MyNFT is ERC721, Ownable { - uint256 private _nextTokenId; + ``` - constructor(address initialOwner) - ERC721("MyToken", "MTK") - Ownable(initialOwner) - {} +## Compile Contracts - function safeMint(address to) public onlyOwner { - uint256 tokenId = _nextTokenId++; - _safeMint(to, tokenId); - } -} -``` +!!! note "Contracts Code Blob Size Disclaimer" + The maximum contract code blob size on Polkadot Hub networks is _100 kilobytes_, significantly larger than Ethereum’s EVM limit of 24 kilobytes. -## Compile + For detailed comparisons and migration guidelines, see the [EVM vs. PolkaVM](/polkadot-protocol/smart-contract-basics/evm-vs-polkavm/#current-memory-limits){target=\_blank} documentation page. -```bash -forge build -``` +The `revive` compiler transforms Solidity smart contracts into [PolkaVM](/smart-contracts/overview/#native-smart-contracts){target=\_blank} bytecode for deployment on Polkadot Hub. Revive's Ethereum RPC interface allows you to use familiar tools like Ethers.js and MetaMask to interact with contracts. -Verify the compilation by inspecting the bytecode: +### Install the Revive Library + +The [`@parity/resolc`](https://www.npmjs.com/package/@parity/resolc){target=\_blank} library will compile your Solidity code for deployment on Polkadot Hub. Run the following command in your terminal to install the library: ```bash -forge inspect MyNFT bytecode +npm install --save-dev @parity/resolc ``` -## Deploy +This guide uses `@parity/resolc` version `0.2.0`. -Deploy to Polkadot Hub TestNet: +### Sample Storage Smart Contract -```bash -forge create MyNFT \ - --rpc-url polkadot_hub_testnet \ - --private-key YOUR_PRIVATE_KEY \ - --constructor-args YOUR_OWNER_ADDRESS \ - --broadcast -``` +This example demonstrates compiling a `Storage.sol` Solidity contract for deployment to Polkadot Hub. The contract's functionality stores a number and permits users to update it with a new value. -Replace `YOUR_PRIVATE_KEY` with your private key and `YOUR_OWNER_ADDRESS` with the address that will own the NFT contract. +```solidity title="contracts/Storage.sol" +//SPDX-License-Identifier: MIT -## Where to Go Next +// Solidity files have to start with this pragma. +// It will be used by the Solidity compiler to validate its version. +pragma solidity ^0.8.9; -
+contract Storage { + // Public state variable to store a number + uint256 public storedNumber; -- Guide __Verify Your Contract__ + /** + * Updates the stored number. + * + * The `public` modifier allows anyone to call this function. + * + * @param _newNumber - The new value to store. + */ + function setNumber(uint256 _newNumber) public { + storedNumber = _newNumber; + } +} +``` - --- +### Compile the Smart Contract - Now that you've deployed an NFT contract, learn how to verify it with Foundry. +To compile this contract, use the following script: - [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/foundry/verify-a-contract/) +```js title="scripts/compile.js" +const { compile } = require('@parity/resolc'); +const { readFileSync, writeFileSync } = require('fs'); +const { basename, join } = require('path'); -- Guide __Deploy an ERC-20__ +const compileContract = async (solidityFilePath, outputDir) => { + try { + // Read the Solidity file + const source = readFileSync(solidityFilePath, 'utf8'); - --- + // Construct the input object for the compiler + const input = { + [basename(solidityFilePath)]: { content: source }, + }; - Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Foundry. + console.log(`Compiling contract: ${basename(solidityFilePath)}...`); - [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/foundry/) + // Compile the contract + const out = await compile(input); -
+ for (const contracts of Object.values(out.contracts)) { + for (const [name, contract] of Object.entries(contracts)) { + console.log(`Compiled contract: ${name}`); + // Write the ABI + const abiPath = join(outputDir, `${name}.json`); + writeFileSync(abiPath, JSON.stringify(contract.abi, null, 2)); + console.log(`ABI saved to ${abiPath}`); ---- + // Write the bytecode + const bytecodePath = join(outputDir, `${name}.polkavm`); + writeFileSync( + bytecodePath, + Buffer.from(contract.evm.bytecode.object, 'hex'), + ); + console.log(`Bytecode saved to ${bytecodePath}`); + } + } + } catch (error) { + console.error('Error compiling contracts:', error); + } +}; -Page Title: Deploy an NFT to Polkadot Hub with Hardhat +const solidityFilePath = join(__dirname, '../contracts/Storage.sol'); +const outputDir = join(__dirname, '../contracts'); -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-hardhat.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/hardhat/ -- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub with Hardhat, a comprehenive development environment with built-in deployment capabilities. +compileContract(solidityFilePath, outputDir); -# Deploy an NFT with Hardhat +``` -## Introduction +!!! note + The script above is tailored to the `Storage.sol` contract. It can be adjusted for other contracts by changing the file name or modifying the ABI and bytecode paths. -Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. +The ABI (Application Binary Interface) is a JSON representation of your contract's functions, events, and their parameters. It serves as the interface between your JavaScript code and the deployed smart contract, allowing your application to know how to format function calls and interpret returned data. -This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. You'll use [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and [Hardhat](https://hardhat.org/docs/getting-started){target=\_blank}, a comprehensive development environment with built-in testing, debugging, and deployment capabilities. Hardhat uses standard Solidity compilation to generate EVM bytecode, making it fully compatible with Polkadot Hub's EVM environment. +Execute the script above by running: -## Prerequisites +```bash +node compile +``` -- Basic understanding of Solidity programming and NFT standards. -- Node.js v22.13.1 or later. -- A funded account with tokens for transaction fees. This example will deploy the contract to the Polkadot TestNet, so you'll [need some TestNet tokens](/smart-contracts/faucet/#get-test-tokens){target=\_blank} from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}. -- A wallet with a private key for signing transactions. +After executing the script, the Solidity contract will be compiled into the required PolkaVM bytecode format. The ABI and bytecode will be saved into files with `.json` and `.polkavm` extensions, respectively. You can now proceed with deploying the contract to Polkadot Hub, as outlined in the next section. -## Set Up Your Project +## Deploy the Compiled Contract -Take the following steps to get started: +To deploy your compiled contract to Polkadot Hub, you'll need a wallet with a private key to sign the deployment transaction. -1. Initialize your Hardhat project: +You can create a `deploy.js` script in the root of your project to achieve this. The deployment script can be divided into key components: - ```bash - mkdir hardhat-nft-deployment - cd hardhat-nft-deployment - npx hardhat --init - ``` +1. Set up the required imports and utilities: -2. Install OpenZeppelin contracts: + ```js title="scripts/deploy.js" + // Deploy an EVM-compatible smart contract using ethers.js + const { writeFileSync, existsSync, readFileSync } = require('fs'); + const { join } = require('path'); + const { ethers, JsonRpcProvider } = require('ethers'); - ```bash - npm install @openzeppelin/contracts + const codegenDir = join(__dirname); ``` -## Configure Hardhat +2. Create a provider to connect to Polkadot Hub: -Edit `hardhat.config.ts`: + ```js title="scripts/deploy.js" -```typescript title="hardhat.config.ts" -import type { HardhatUserConfig } from 'hardhat/config'; + // Creates an Ethereum provider with specified RPC URL and chain details + const createProvider = (rpcUrl, chainId, chainName) => { + const provider = new JsonRpcProvider(rpcUrl, { + chainId: chainId, + name: chainName, + }); + return provider; + }; + ``` + +3. Set up functions to read contract artifacts: -import hardhatToolboxViemPlugin from '@nomicfoundation/hardhat-toolbox-viem'; -import { configVariable } from 'hardhat/config'; + ```js title="scripts/deploy.js" + // Reads and parses the ABI file for a given contract + const getAbi = (contractName) => { + try { + return JSON.parse( + readFileSync(join(codegenDir, `${contractName}.json`), 'utf8'), + ); + } catch (error) { + console.error( + `Could not find ABI for contract ${contractName}:`, + error.message, + ); + throw error; + } + }; -const config: HardhatUserConfig = { - plugins: [hardhatToolboxViemPlugin], - solidity: { - profiles: { - default: { - version: '0.8.28', - }, - production: { - version: '0.8.28', - settings: { - optimizer: { - enabled: true, - runs: 200, - }, - }, - }, - }, - }, - networks: { - hardhatMainnet: { - type: 'edr-simulated', - chainType: 'l1', - }, - hardhatOp: { - type: 'edr-simulated', - chainType: 'op', - }, - sepolia: { - type: 'http', - chainType: 'l1', - url: configVariable('SEPOLIA_RPC_URL'), - accounts: [configVariable('SEPOLIA_PRIVATE_KEY')], - }, - polkadotHubTestnet: { - type: 'http', - url: 'https://testnet-passet-hub-eth-rpc.polkadot.io', - chainId: 420420422, - accounts: [configVariable('PRIVATE_KEY')], - }, - }, -}; - -export default config; -``` - -!!! tip - Learn how to use Hardhat's [Config Variables](https://hardhat.org/docs/learn-more/configuration-variables){target=\_blank} to handle your private keys in a secure way. - -## Create Your Contract - -Create `contracts/MyNFT.sol`: - -```solidity title="contracts/MyNFT.sol" -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.20; - -import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; -import "@openzeppelin/contracts/access/Ownable.sol"; - -contract MyNFT is ERC721, Ownable { - uint256 private _nextTokenId; - - constructor(address initialOwner) - ERC721("MyToken", "MTK") - Ownable(initialOwner) - {} - - function safeMint(address to) public onlyOwner { - uint256 tokenId = _nextTokenId++; - _safeMint(to, tokenId); - } -} -``` - -## Compile - -```bash -npx hardhat compile -``` - -## Set Up Deployment - -Create a deployment module in `ignition/modules/MyNFT.ts`: - -```typescript title="ignition/modules/MyNFT.ts" -import { buildModule } from '@nomicfoundation/hardhat-ignition/modules'; - -export default buildModule('MyNFTModule', (m) => { - const initialOwner = m.getParameter('initialOwner', 'INSERT_OWNER_ADDRESS'); - const myNFT = m.contract('MyNFT', [initialOwner]); - return { myNFT }; -}); -``` - -Replace `INSERT_OWNER_ADDRESS` with your desired owner address. - -## Deploy - -Deploy to Polkadot Hub TestNet: - -```bash -npx hardhat ignition deploy ignition/modules/MyNFT.ts --network polkadotHubTestnet -``` - -## Where to Go Next - -
- -- Guide __Verify Your Contract__ - - --- - - Now that you've deployed an NFT contract, learn how to verify it with Hardhat. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/hardhat/verify-a-contract/) - - -- Guide __Deploy an ERC-20__ - - --- - - Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Hardhat. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/hardhat/) - -
- - ---- - -Page Title: Deploy an NFT to Polkadot Hub with Remix - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-remix.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/ -- Summary: Learn how to deploy an ERC-721 NFT contract to Polkadot Hub using Remix, a browser-based IDE for quick prototyping and learning. - -# Deploy an NFT with Remix - -## Introduction - -Non-Fungible Tokens (NFTs) represent unique digital assets commonly used for digital art, collectibles, gaming, and identity verification. - -This guide demonstrates how to deploy an [ERC-721](https://eips.ethereum.org/EIPS/eip-721){target=\_blank} NFT contract to [Polkadot Hub](/smart-contracts/overview/#smart-contract-development){target=\_blank}. You'll use [OpenZeppelin's battle-tested NFT implementation](https://github.com/OpenZeppelin/openzeppelin-contracts){target=\_blank} and [Remix](https://remix.ethereum.org/){target=\_blank}, a visual, browser-based environment perfect for rapid prototyping and learning. It requires no local installation and provides an intuitive interface for contract development. - -## Prerequisites - -- Basic understanding of Solidity programming and NFT standards. -- Test tokens for gas fees (available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}). See the [step-by-step instructions](/smart-contracts/faucet/#get-test-tokens){target=\_blank} -- A wallet with a private key for signing transactions. - -## Access Remix - -Navigate to [Remix](https://remix.ethereum.org/){target=\_blank} in your web browser. - -The interface will load with a default workspace containing sample contracts. In this interface, you can access a file explorer, edit your code, interact with various plugins for development, and use a terminal. - -## Create Your Contract - -1. Create a new file `contracts/MyNFT.sol`. -2. Paste the following code: - - ```solidity title="contracts/MyNFT.sol" - // SPDX-License-Identifier: MIT - pragma solidity ^0.8.20; - - import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; - import "@openzeppelin/contracts/access/Ownable.sol"; - - contract MyNFT is ERC721, Ownable { - uint256 private _nextTokenId; - - constructor(address initialOwner) - ERC721("MyToken", "MTK") - Ownable(initialOwner) - {} - - function safeMint(address to) public onlyOwner { - uint256 tokenId = _nextTokenId++; - _safeMint(to, tokenId); - } - } + // Reads the compiled bytecode for a given contract + const getByteCode = (contractName) => { + try { + const bytecodePath = join( + codegenDir, + '../contracts', + `${contractName}.polkavm`, + ); + return `0x${readFileSync(bytecodePath).toString('hex')}`; + } catch (error) { + console.error( + `Could not find bytecode for contract ${contractName}:`, + error.message, + ); + throw error; + } + }; ``` -![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-01.webp) - -## Compile - -1. Navigate to the **Solidity Compiler** tab (third icon in the left sidebar). -2. Click **Compile MyNFT.sol** or press `Ctrl+S`. - -![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-02.webp) - -Compilation errors and warnings appear in the terminal panel at the bottom of the screen. - -## Deploy - -1. Navigate to the **Deploy & Run Transactions** tab. -2. Click the **Environment** dropdown, select **Browser Extension**, and click on **Injected Provider - MetaMask**. - - ![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-03.webp) - -3. In the deploy section, enter the initial owner address in the constructor parameter field. -4. Click **Deploy**. - - ![](/images/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/remix-04.webp) - -5. Approve the transaction in your MetaMask wallet. - -Your deployed contract will appear in the **Deployed Contracts** section, ready for interaction. - -## Where to Go Next +4. Create the main deployment function: -
+ ```js title="scripts/deploy.js" -- Guide __Verify Your Contract__ + const deployContract = async (contractName, mnemonic, providerConfig) => { + console.log(`Deploying ${contractName}...`); - --- + try { + // Step 1: Set up provider and wallet + const provider = createProvider( + providerConfig.rpc, + providerConfig.chainId, + providerConfig.name, + ); + const walletMnemonic = ethers.Wallet.fromPhrase(mnemonic); + const wallet = walletMnemonic.connect(provider); - Now that you've deployed an NFT contract, learn how to verify it with Remix. + // Step 2: Create and deploy the contract + const factory = new ethers.ContractFactory( + getAbi(contractName), + getByteCode(contractName), + wallet, + ); + const contract = await factory.deploy(); + await contract.waitForDeployment(); - [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/remix/verify-a-contract/) + // Step 3: Save deployment information + const address = await contract.getAddress(); + console.log(`Contract ${contractName} deployed at: ${address}`); -- Guide __Deploy an ERC-20__ + const addressesFile = join(codegenDir, 'contract-address.json'); + const addresses = existsSync(addressesFile) + ? JSON.parse(readFileSync(addressesFile, 'utf8')) + : {}; + addresses[contractName] = address; + writeFileSync(addressesFile, JSON.stringify(addresses, null, 2), 'utf8'); + } catch (error) { + console.error(`Failed to deploy contract ${contractName}:`, error); + } + }; + ``` - --- - - Walk through deploying a fully-functional ERC-20 to the Polkadot Hub using Remix. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/) - -
- - ---- - -Page Title: Deploy Contracts to Polkadot Hub with Ethers.js - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-libraries-ethers-js.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/libraries/ethers-js/ -- Summary: Learn how to interact with Polkadot Hub using Ethers.js, from compiling and deploying Solidity contracts to interacting with deployed smart contracts. - -# Ethers.js - -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction - -[Ethers.js](https://docs.ethers.org/v6/){target=\_blank} is a lightweight library that enables interaction with Ethereum Virtual Machine (EVM)-compatible blockchains through JavaScript. Ethers is widely used as a toolkit to establish connections and read and write blockchain data. This article demonstrates using Ethers.js to interact and deploy smart contracts to Polkadot Hub. - -This guide is intended for developers who are familiar with JavaScript and want to interact with Polkadot Hub using Ethers.js. - -## Prerequisites - -Before getting started, ensure you have the following installed: - -- **Node.js**: v22.13.1 or later, check the [Node.js installation guide](https://nodejs.org/en/download/current/){target=\_blank}. -- **npm**: v6.13.4 or later (comes bundled with Node.js). -- **Solidity**: This guide uses Solidity `^0.8.9` for smart contract development. - -## Project Structure - -This project organizes contracts, scripts, and compiled artifacts for easy development and deployment. - -```text title="Ethers.js Polkadot Hub" -ethers-project -├── contracts -│ ├── Storage.sol -├── scripts -│ ├── connectToProvider.js -│ ├── fetchLastBlock.js -│ ├── compile.js -│ ├── deploy.js -│ ├── checkStorage.js -├── abis -│ ├── Storage.json -├── artifacts -│ ├── Storage.polkavm -├── contract-address.json -├── node_modules/ -├── package.json -├── package-lock.json -└── README.md -``` - -## Set Up the Project - -To start working with Ethers.js, create a new folder and initialize your project by running the following commands in your terminal: - -```bash -mkdir ethers-project -cd ethers-project -npm init -y -``` - -## Install Dependencies - -Next, run the following command to install the Ethers.js library: - -```bash -npm install ethers -``` - -## Set Up the Ethers.js Provider - -A [`Provider`](https://docs.ethers.org/v6/api/providers/#Provider){target=\_blank} is an abstraction of a connection to the Ethereum network, allowing you to query blockchain data and send transactions. It serves as a bridge between your application and the blockchain. - -To interact with Polkadot Hub, you must set up an Ethers.js provider. This provider connects to a blockchain node, allowing you to query blockchain data and interact with smart contracts. In the root of your project, create a file named `connectToProvider.js` and add the following code: - -```js title="scripts/connectToProvider.js" -const { JsonRpcProvider } = require('ethers'); - -const createProvider = (rpcUrl, chainId, chainName) => { - const provider = new JsonRpcProvider(rpcUrl, { - chainId: chainId, - name: chainName, - }); - - return provider; -}; - -const PROVIDER_RPC = { - rpc: 'INSERT_RPC_URL', - chainId: 'INSERT_CHAIN_ID', - name: 'INSERT_CHAIN_NAME', -}; - -createProvider(PROVIDER_RPC.rpc, PROVIDER_RPC.chainId, PROVIDER_RPC.name); - -``` - -!!! note - Replace `INSERT_RPC_URL`, `INSERT_CHAIN_ID`, and `INSERT_CHAIN_NAME` with the appropriate values. For example, to connect to Polkadot Hub TestNet's Ethereum RPC instance, you can use the following parameters: - - ```js - const PROVIDER_RPC = { - rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', - chainId: 420420422, - name: 'polkadot-hub-testnet' - }; - ``` - -To connect to the provider, execute: - -```bash -node connectToProvider -``` - -With the provider set up, you can start querying the blockchain. For instance, to fetch the latest block number: - -??? code "Fetch Last Block code" - - ```js title="scripts/fetchLastBlock.js" - const { JsonRpcProvider } = require('ethers'); - - const createProvider = (rpcUrl, chainId, chainName) => { - const provider = new JsonRpcProvider(rpcUrl, { - chainId: chainId, - name: chainName, - }); - - return provider; - }; - - const PROVIDER_RPC = { - rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', - chainId: 420420422, - name: 'polkadot-hub-testnet', - }; - - const main = async () => { - try { - const provider = createProvider( - PROVIDER_RPC.rpc, - PROVIDER_RPC.chainId, - PROVIDER_RPC.name, - ); - const latestBlock = await provider.getBlockNumber(); - console.log(`Latest block: ${latestBlock}`); - } catch (error) { - console.error('Error connecting to Polkadot Hub TestNet: ' + error.message); - } - }; - - main(); - - ``` - -## Compile Contracts - -!!! note "Contracts Code Blob Size Disclaimer" - The maximum contract code blob size on Polkadot Hub networks is _100 kilobytes_, significantly larger than Ethereum’s EVM limit of 24 kilobytes. - - For detailed comparisons and migration guidelines, see the [EVM vs. PolkaVM](/polkadot-protocol/smart-contract-basics/evm-vs-polkavm/#current-memory-limits){target=\_blank} documentation page. - -The `revive` compiler transforms Solidity smart contracts into [PolkaVM](/smart-contracts/overview/#native-smart-contracts){target=\_blank} bytecode for deployment on Polkadot Hub. Revive's Ethereum RPC interface allows you to use familiar tools like Ethers.js and MetaMask to interact with contracts. - -### Install the Revive Library - -The [`@parity/resolc`](https://www.npmjs.com/package/@parity/resolc){target=\_blank} library will compile your Solidity code for deployment on Polkadot Hub. Run the following command in your terminal to install the library: - -```bash -npm install --save-dev @parity/resolc -``` - -This guide uses `@parity/resolc` version `0.2.0`. - -### Sample Storage Smart Contract - -This example demonstrates compiling a `Storage.sol` Solidity contract for deployment to Polkadot Hub. The contract's functionality stores a number and permits users to update it with a new value. - -```solidity title="contracts/Storage.sol" -//SPDX-License-Identifier: MIT - -// Solidity files have to start with this pragma. -// It will be used by the Solidity compiler to validate its version. -pragma solidity ^0.8.9; - -contract Storage { - // Public state variable to store a number - uint256 public storedNumber; - - /** - * Updates the stored number. - * - * The `public` modifier allows anyone to call this function. - * - * @param _newNumber - The new value to store. - */ - function setNumber(uint256 _newNumber) public { - storedNumber = _newNumber; - } -} -``` - -### Compile the Smart Contract - -To compile this contract, use the following script: - -```js title="scripts/compile.js" -const { compile } = require('@parity/resolc'); -const { readFileSync, writeFileSync } = require('fs'); -const { basename, join } = require('path'); - -const compileContract = async (solidityFilePath, outputDir) => { - try { - // Read the Solidity file - const source = readFileSync(solidityFilePath, 'utf8'); - - // Construct the input object for the compiler - const input = { - [basename(solidityFilePath)]: { content: source }, - }; - - console.log(`Compiling contract: ${basename(solidityFilePath)}...`); - - // Compile the contract - const out = await compile(input); - - for (const contracts of Object.values(out.contracts)) { - for (const [name, contract] of Object.entries(contracts)) { - console.log(`Compiled contract: ${name}`); - - // Write the ABI - const abiPath = join(outputDir, `${name}.json`); - writeFileSync(abiPath, JSON.stringify(contract.abi, null, 2)); - console.log(`ABI saved to ${abiPath}`); - - // Write the bytecode - const bytecodePath = join(outputDir, `${name}.polkavm`); - writeFileSync( - bytecodePath, - Buffer.from(contract.evm.bytecode.object, 'hex'), - ); - console.log(`Bytecode saved to ${bytecodePath}`); - } - } - } catch (error) { - console.error('Error compiling contracts:', error); - } -}; - -const solidityFilePath = join(__dirname, '../contracts/Storage.sol'); -const outputDir = join(__dirname, '../contracts'); - -compileContract(solidityFilePath, outputDir); - -``` - -!!! note - The script above is tailored to the `Storage.sol` contract. It can be adjusted for other contracts by changing the file name or modifying the ABI and bytecode paths. - -The ABI (Application Binary Interface) is a JSON representation of your contract's functions, events, and their parameters. It serves as the interface between your JavaScript code and the deployed smart contract, allowing your application to know how to format function calls and interpret returned data. - -Execute the script above by running: - -```bash -node compile -``` - -After executing the script, the Solidity contract will be compiled into the required PolkaVM bytecode format. The ABI and bytecode will be saved into files with `.json` and `.polkavm` extensions, respectively. You can now proceed with deploying the contract to Polkadot Hub, as outlined in the next section. - -## Deploy the Compiled Contract - -To deploy your compiled contract to Polkadot Hub, you'll need a wallet with a private key to sign the deployment transaction. - -You can create a `deploy.js` script in the root of your project to achieve this. The deployment script can be divided into key components: - -1. Set up the required imports and utilities: - - ```js title="scripts/deploy.js" - // Deploy an EVM-compatible smart contract using ethers.js - const { writeFileSync, existsSync, readFileSync } = require('fs'); - const { join } = require('path'); - const { ethers, JsonRpcProvider } = require('ethers'); - - const codegenDir = join(__dirname); - ``` - -2. Create a provider to connect to Polkadot Hub: - - ```js title="scripts/deploy.js" - - // Creates an Ethereum provider with specified RPC URL and chain details - const createProvider = (rpcUrl, chainId, chainName) => { - const provider = new JsonRpcProvider(rpcUrl, { - chainId: chainId, - name: chainName, - }); - return provider; - }; - ``` - -3. Set up functions to read contract artifacts: - - ```js title="scripts/deploy.js" - // Reads and parses the ABI file for a given contract - const getAbi = (contractName) => { - try { - return JSON.parse( - readFileSync(join(codegenDir, `${contractName}.json`), 'utf8'), - ); - } catch (error) { - console.error( - `Could not find ABI for contract ${contractName}:`, - error.message, - ); - throw error; - } - }; - - // Reads the compiled bytecode for a given contract - const getByteCode = (contractName) => { - try { - const bytecodePath = join( - codegenDir, - '../contracts', - `${contractName}.polkavm`, - ); - return `0x${readFileSync(bytecodePath).toString('hex')}`; - } catch (error) { - console.error( - `Could not find bytecode for contract ${contractName}:`, - error.message, - ); - throw error; - } - }; - ``` - -4. Create the main deployment function: - - ```js title="scripts/deploy.js" - - const deployContract = async (contractName, mnemonic, providerConfig) => { - console.log(`Deploying ${contractName}...`); - - try { - // Step 1: Set up provider and wallet - const provider = createProvider( - providerConfig.rpc, - providerConfig.chainId, - providerConfig.name, - ); - const walletMnemonic = ethers.Wallet.fromPhrase(mnemonic); - const wallet = walletMnemonic.connect(provider); - - // Step 2: Create and deploy the contract - const factory = new ethers.ContractFactory( - getAbi(contractName), - getByteCode(contractName), - wallet, - ); - const contract = await factory.deploy(); - await contract.waitForDeployment(); - - // Step 3: Save deployment information - const address = await contract.getAddress(); - console.log(`Contract ${contractName} deployed at: ${address}`); - - const addressesFile = join(codegenDir, 'contract-address.json'); - const addresses = existsSync(addressesFile) - ? JSON.parse(readFileSync(addressesFile, 'utf8')) - : {}; - addresses[contractName] = address; - writeFileSync(addressesFile, JSON.stringify(addresses, null, 2), 'utf8'); - } catch (error) { - console.error(`Failed to deploy contract ${contractName}:`, error); - } - }; - ``` - -5. Configure and execute the deployment: - - ```js title="scripts/deploy.js" - const providerConfig = { - rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', - chainId: 420420422, - name: 'polkadot-hub-testnet', - }; - - const mnemonic = 'INSERT_MNEMONIC'; - - deployContract('Storage', mnemonic, providerConfig); - ``` - - !!! note - A mnemonic (seed phrase) is a series of words that can generate multiple private keys and their corresponding addresses. It's used here to derive the wallet that will sign and pay for the deployment transaction. **Always keep your mnemonic secure and never share it publicly**. - - Ensure to replace the `INSERT_MNEMONIC` placeholder with your actual mnemonic. - -??? code "View complete script" - - ```js title="scripts/deploy.js" - // Deploy an EVM-compatible smart contract using ethers.js - const { writeFileSync, existsSync, readFileSync } = require('fs'); - const { join } = require('path'); - const { ethers, JsonRpcProvider } = require('ethers'); - - const codegenDir = join(__dirname); - - // Creates an Ethereum provider with specified RPC URL and chain details - const createProvider = (rpcUrl, chainId, chainName) => { - const provider = new JsonRpcProvider(rpcUrl, { - chainId: chainId, - name: chainName, - }); - return provider; - }; - - // Reads and parses the ABI file for a given contract - const getAbi = (contractName) => { - try { - return JSON.parse( - readFileSync(join(codegenDir, `${contractName}.json`), 'utf8'), - ); - } catch (error) { - console.error( - `Could not find ABI for contract ${contractName}:`, - error.message, - ); - throw error; - } - }; - - // Reads the compiled bytecode for a given contract - const getByteCode = (contractName) => { - try { - const bytecodePath = join( - codegenDir, - '../contracts', - `${contractName}.polkavm`, - ); - return `0x${readFileSync(bytecodePath).toString('hex')}`; - } catch (error) { - console.error( - `Could not find bytecode for contract ${contractName}:`, - error.message, - ); - throw error; - } - }; - - const deployContract = async (contractName, mnemonic, providerConfig) => { - console.log(`Deploying ${contractName}...`); - - try { - // Step 1: Set up provider and wallet - const provider = createProvider( - providerConfig.rpc, - providerConfig.chainId, - providerConfig.name, - ); - const walletMnemonic = ethers.Wallet.fromPhrase(mnemonic); - const wallet = walletMnemonic.connect(provider); - - // Step 2: Create and deploy the contract - const factory = new ethers.ContractFactory( - getAbi(contractName), - getByteCode(contractName), - wallet, - ); - const contract = await factory.deploy(); - await contract.waitForDeployment(); - - // Step 3: Save deployment information - const address = await contract.getAddress(); - console.log(`Contract ${contractName} deployed at: ${address}`); - - const addressesFile = join(codegenDir, 'contract-address.json'); - const addresses = existsSync(addressesFile) - ? JSON.parse(readFileSync(addressesFile, 'utf8')) - : {}; - addresses[contractName] = address; - writeFileSync(addressesFile, JSON.stringify(addresses, null, 2), 'utf8'); - } catch (error) { - console.error(`Failed to deploy contract ${contractName}:`, error); - } - }; - - const providerConfig = { - rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', - chainId: 420420422, - name: 'polkadot-hub-testnet', - }; - - const mnemonic = 'INSERT_MNEMONIC'; - - deployContract('Storage', mnemonic, providerConfig); - - ``` - -To run the script, execute the following command: - -```bash -node deploy -``` - -After running this script, your contract will be deployed to Polkadot Hub, and its address will be saved in `contract-address.json` within your project directory. You can use this address for future contract interactions. - -## Interact with the Contract - -Once the contract is deployed, you can interact with it by calling its functions. For example, to set a number, read it and then modify that number by its double, you can create a file named `checkStorage.js` in the root of your project and add the following code: - -```js title="scripts/checkStorage.js" -const { ethers } = require('ethers'); -const { readFileSync } = require('fs'); -const { join } = require('path'); - -const createProvider = (providerConfig) => { - return new ethers.JsonRpcProvider(providerConfig.rpc, { - chainId: providerConfig.chainId, - name: providerConfig.name, - }); -}; - -const createWallet = (mnemonic, provider) => { - return ethers.Wallet.fromPhrase(mnemonic).connect(provider); -}; - -const loadContractAbi = (contractName, directory = __dirname) => { - const contractPath = join(directory, `${contractName}.json`); - const contractJson = JSON.parse(readFileSync(contractPath, 'utf8')); - return contractJson.abi || contractJson; // Depending on JSON structure -}; - -const createContract = (contractAddress, abi, wallet) => { - return new ethers.Contract(contractAddress, abi, wallet); -}; - -const interactWithStorageContract = async ( - contractName, - contractAddress, - mnemonic, - providerConfig, - numberToSet, -) => { - try { - console.log(`Setting new number in Storage contract: ${numberToSet}`); - - // Create provider and wallet - const provider = createProvider(providerConfig); - const wallet = createWallet(mnemonic, provider); - - // Load the contract ABI and create the contract instance - const abi = loadContractAbi(contractName); - const contract = createContract(contractAddress, abi, wallet); - - // Send a transaction to set the stored number - const tx1 = await contract.setNumber(numberToSet); - await tx1.wait(); // Wait for the transaction to be mined - console.log(`Number successfully set to ${numberToSet}`); - - // Retrieve the updated number - const storedNumber = await contract.storedNumber(); - console.log(`Retrieved stored number:`, storedNumber.toString()); - - // Send a transaction to set the stored number - const tx2 = await contract.setNumber(numberToSet * 2); - await tx2.wait(); // Wait for the transaction to be mined - console.log(`Number successfully set to ${numberToSet * 2}`); - - // Retrieve the updated number - const updatedNumber = await contract.storedNumber(); - console.log(`Retrieved stored number:`, updatedNumber.toString()); - } catch (error) { - console.error('Error interacting with Storage contract:', error.message); - } -}; - -const providerConfig = { - name: 'asset-hub-smart-contracts', - rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', - chainId: 420420422, -}; - -const mnemonic = 'INSERT_MNEMONIC'; -const contractName = 'Storage'; -const contractAddress = 'INSERT_CONTRACT_ADDRESS'; -const newNumber = 42; - -interactWithStorageContract( - contractName, - contractAddress, - mnemonic, - providerConfig, - newNumber, -); - -``` - -Ensure you replace the `INSERT_MNEMONIC`, `INSERT_CONTRACT_ADDRESS`, and `INSERT_ADDRESS_TO_CHECK` placeholders with actual values. Also, ensure the contract ABI file (`Storage.json`) is correctly referenced. - -To interact with the contract, run: - -```bash -node checkStorage -``` - -## Where to Go Next - -Now that you have the foundational knowledge to use Ethers.js with Polkadot Hub, you can: - -- **Dive into Ethers.js utilities**: Discover additional Ethers.js features, such as wallet management, signing messages, etc. -- **Implement batch transactions**: Use Ethers.js to execute batch transactions for efficient multi-step contract interactions. -- **Build scalable applications**: Combine Ethers.js with frameworks like [`Next.js`](https://nextjs.org/docs){target=\_blank} or [`Node.js`](https://nodejs.org/en){target=\_blank} to create full-stack decentralized applications (dApps). - - ---- - -Page Title: Deploy Contracts Using Remix IDE - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-remix-deploy-a-contract.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/dev-environments/remix/deploy-a-contract/ -- Summary: Learn how to deploy smart contracts to the Polkadot Hub network and interact with them using the Remix IDE and wallet providers, covering deployment and state. - -# Deploy Smart Contracts Using Remix IDE - -## Overview - -After compiling your smart contract in Remix IDE, the next step is to deploy it to the Polkadot Hub network. This guide will walk you through the deployment process using a wallet provider and show you how to interact with your deployed contracts directly from the Remix interface. - -## Prerequisites - -Before deploying your contract, ensure you have: - -- Completed the [Remix IDE setup](/smart-contracts/dev-environments/remix/get-started/){target=\_blank} and have a compiled contract ready. -- A compatible wallet extension installed (e.g., [MetaMask](https://metamask.io/){target=\_blank} or [Talisman](https://www.talisman.xyz/){target=\_blank}). -- Your wallet connected to the Polkadot Hub network. Check the [Connect to Polkadot](/smart-contracts/connect/){target=\_blank} guide for more information. -- Test tokens in your wallet to cover deployment and transaction fees (available from the [Polkadot faucet](/smart-contracts/faucet/){target=\_blank}). - -## Deploy Contracts - -The steps to use Remix IDE to deploy a contract to Polkadot Hub are as follows: - -1. Navigate to [Remix](https://remix.ethereum.org/){target=\_blank} in your web browser. -2. Locate the **Deploy & Run Transactions** tab. -3. Select the **Environment** dropdown. -4. Select **Browser Extension**. -5. Select the **Injected Provider - MetaMask** option. -6. Click the **Deploy** button and then click **Confirm** in the wallet popup. - -Once your contract is deployed successfully, you will see the deployment confirmation in the Remix terminal. - -![](/images/smart-contracts/dev-environments/remix/deploy-a-contract/remix-1.gif) - -## Interact with Contracts - -Deployed contracts appear in the **Deployed/Unpinned Contracts** section. Follow these steps to interact with the deployed contract: - -1. Expand the contract to view available methods. - - !!! tip - Pin your frequently used contracts to the **Pinned Contracts** section for easy access. - -2. Select any of the exposed methods to interact with the contract. - - You can use these methods to interact with your deployed contract by reading or writing to its state. Remix IDE uses a color-coding scheme for method buttons to help differentiate between types of available methods as follows: - - - **Blue buttons**: indicate `view` or `pure` functions which read state only. Interactions do not create a new transaction and do not incur gas fees. - - **Orange buttons**: label `non-payable` functions which change contract state but don't accept any value (ETH or other tokens) being sent with the transaction. - - **Red buttons**: designate `payable` functions which create a transaction and can accept a value (ETH or other tokens) to send with the transaction. - -If you deployed the `Counter.sol` contract from [Remix IDE setup](/smart-contracts/dev-environments/remix/get-started/){target=\_blank}, you can try interacting with the exposed methods as follows: - -1. Select the **GetCount** button to read the current count value. - -2. Select the **Increment** button to increment the count value. - -3. Submit the transaction and click the **Confirm** button in the wallet pop-up. - -Once the transaction is confirmed, you will see the updated count value in the Remix terminal. - -![](/images/smart-contracts/dev-environments/remix/deploy-a-contract/remix-2.gif) - -## Where to Go Next - -You've successfully deployed and interacted with your smart contract on Polkadot Hub using Remix IDE. Continue enhancing your development workflow with these resources: - -
- - - -- Guide __Troubleshooting__ - - --- - - Find solutions to common issues when working with Remix IDE. - - [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/remix/troubleshooting-faq/) - -
- - ---- - -Page Title: Deploying Uniswap V2 on Polkadot - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-eth-dapps-uniswap-v2.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/eth-dapps/uniswap-v2/ -- Summary: Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. - -# Deploy Uniswap V2 - -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction - -Decentralized exchanges (DEXs) are a cornerstone of the DeFi ecosystem, allowing for permissionless token swaps without intermediaries. [Uniswap V2](https://docs.uniswap.org/contracts/v2/overview){target=\_blank}, with its Automated Market Maker (AMM) model, revolutionized DEXs by enabling liquidity provision for any ERC-20 token pair. - -This tutorial will guide you through how Uniswap V2 works so you can take advantage of it in your projects deployed to Polkadot Hub. By understanding these contracts, you'll gain hands-on experience with one of the most influential DeFi protocols and understand how it functions across blockchain ecosystems. - -## Prerequisites - -Before starting, make sure you have: - -- Node.js (v16.0.0 or later) and npm installed. -- Basic understanding of Solidity and JavaScript. -- Familiarity with [`hardhat-polkadot`](/smart-contracts/dev-environments/hardhat/get-started/){target=\_blank} development environment. -- Some PAS test tokens to cover transaction fees (obtained from the [Polkadot faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}). -- Basic understanding of how AMMs and liquidity pools work. - -## Set Up the Project - -Let's start by cloning the Uniswap V2 project: - -1. Clone the Uniswap V2 repository: - - ``` - git clone https://github.com/polkadot-developers/polkavm-hardhat-examples.git -b v0.0.6 - cd polkavm-hardhat-examples/uniswap-v2-polkadot/ - ``` - -2. Install the required dependencies: - - ```bash - npm install - ``` - -3. Update the `hardhat.config.js` file so the paths for the Substrate node and the ETH-RPC adapter match with the paths on your machine. For more info, check the [Testing your Contract](/smart-contracts/dev-environments/hardhat/compile-and-test/){target=\_blank} section in the Hardhat guide. - - ```js title="hardhat.config.js" - hardhat: { - polkavm: true, - nodeConfig: { - nodeBinaryPath: '../bin/substrate-node', - rpcPort: 8000, - dev: true, - }, - adapterConfig: { - adapterBinaryPath: '../bin/eth-rpc', - dev: true, - }, - }, - ``` - -4. Create a `.env` file in your project root to store your private keys (you can use as an example the `env.example` file): - - ```text title=".env" - LOCAL_PRIV_KEY="INSERT_LOCAL_PRIVATE_KEY" - AH_PRIV_KEY="INSERT_AH_PRIVATE_KEY" - ``` - - Ensure to replace `"INSERT_LOCAL_PRIVATE_KEY"` with a private key available in the local environment (you can get them from this [file](https://github.com/paritytech/hardhat-polkadot/blob/main/packages/hardhat-polkadot-node/src/constants.ts#L22){target=\_blank}). And `"INSERT_AH_PRIVATE_KEY"` with the account's private key you want to use to deploy the contracts. You can get this by exporting the private key from your wallet (e.g., MetaMask). - - !!!warning - Keep your private key safe, and never share it with anyone. If it is compromised, your funds can be stolen. - -5. Compile the contracts: - - ```bash - npx hardhat compile - ``` - -If the compilation is successful, you should see the following output: - -
- npx hardhat compile - Compiling 12 Solidity files - Successfully compiled 12 Solidity files -
- -After running the above command, you should see the compiled contracts in the `artifacts-pvm` directory. This directory contains the ABI and bytecode of your contracts. - -## Understanding Uniswap V2 Architecture - -Before interacting with the contracts, it's essential to understand the core architecture that powers Uniswap V2. This model forms the basis of nearly every modern DEX implementation and operates under automated market making, token pair liquidity pools, and deterministic pricing principles. - -At the heart of Uniswap V2 lies a simple but powerful system composed of two major smart contracts: - -- **Factory contract**: The factory acts as a registry and creator of new trading pairs. When two ERC-20 tokens are to be traded, the Factory contract is responsible for generating a new Pair contract that will manage that specific token pair’s liquidity pool. It keeps track of all deployed pairs and ensures uniqueness—no duplicate pools can exist for the same token combination. -- **Pair contract**: Each pair contract is a decentralized liquidity pool that holds reserves of two ERC-20 tokens. These contracts implement the core logic of the AMM, maintaining a constant product invariant (x \* y = k) to facilitate swaps and price determination. Users can contribute tokens to these pools in return for LP (liquidity provider) tokens, which represent their proportional share of the reserves. - -This minimal architecture enables Uniswap to be highly modular, trustless, and extensible. By distributing responsibilities across these components, developers, and users can engage with the protocol in a composable and predictable manner, making it an ideal foundation for DEX functionality across ecosystems, including Polkadot Hub. - -The project scaffolding is as follows: - -```bash -uniswap-V2-polkadot -├── bin/ -├── contracts/ -│ ├── interfaces/ -│ │ ├── IERC20.sol -│ │ ├── IUniswapV2Callee.sol -│ │ ├── IUniswapV2ERC20.sol -│ │ ├── IUniswapV2Factory.sol -│ │ └── IUniswapV2Pair.sol -│ ├── libraries/ -│ │ ├── Math.sol -│ │ ├── SafeMath.sol -│ │ └── UQ112x112.sol -│ ├── test/ -│ │ └── ERC20.sol -│ ├── UniswapV2ERC20.sol -│ ├── UniswapV2Factory.sol -│ └── UniswapV2Pair.sol -├── ignition/ -├── scripts/ -│ └── deploy.js -├── node_modules/ -├── test/ -│ ├── shared/ -│ │ ├── fixtures.js -│ │ └── utilities.js -│ ├── UniswapV2ERC20.js -│ ├── UniswapV2Factory.js -│ └── UniswapV2Pair.js -├── .env.example -├── .gitignore -├── hardhat.config.js -├── package.json -└── README.md -``` - -## Test the Contracts - -You can run the provided test suite to ensure the contracts are working as expected. The tests cover various scenarios, including creating pairs, adding liquidity, and executing swaps. - -To test it locally, you can run the following commands: - -1. Spawn a local node for testing: - - ```bash - npx hardhat node - ``` - - This command will spawn a local Substrate node along with the ETH-RPC adapter. The node will be available at `ws://127.0.0.1:8000` and the ETH-RPC adapter at `http://localhost:8545`. - -2. In a new terminal, run the tests: - - ```bash - npx hardhat test --network localNode - ``` - -The result should look like this: - -
- npx hardhat test --network localNode - Compiling 12 Solidity files - Successfully compiled 12 Solidity files - - UniswapV2ERC20 - ✔ name, symbol, decimals, totalSupply, balanceOf, DOMAIN_SEPARATOR, PERMIT_TYPEHASH (44ms) - ✔ approve (5128ms) - ✔ transfer (5133ms) - ✔ transfer:fail - ✔ transferFrom (6270ms) - ✔ transferFrom:max (6306ms) - - UniswapV2Factory - ✔ feeTo, feeToSetter, allPairsLength - ✔ createPair (176ms) - ✔ createPair:reverse (1224ms) - ✔ setFeeTo (1138ms) - ✔ setFeeToSetter (1125ms) - - UniswapV2Pair - ✔ mint (11425ms) - ✔ getInputPrice:0 (12590ms) - ✔ getInputPrice:1 (17600ms) - ✔ getInputPrice:2 (17618ms) - ✔ getInputPrice:3 (17704ms) - ✔ getInputPrice:4 (17649ms) - ✔ getInputPrice:5 (17594ms) - ✔ getInputPrice:6 (13643ms) - ✔ optimistic:0 (17647ms) - ✔ optimistic:1 (17946ms) - ✔ optimistic:2 (17657ms) - ✔ optimistic:3 (21625ms) - ✔ swap:token0 (12665ms) - ✔ swap:token1 (17631ms) - ✔ burn (17690ms) - ✔ feeTo:off (23900ms) - ✔ feeTo:on (24991ms) - - 28 passing (12m) -
- -## Deploy the Contracts - -After successfully testing the contracts, you can deploy them to the local node or Polkadot Hub. The deployment script is located in the `scripts` directory and is named `deploy.js`. This script deploys the `Factory` and `Pair` contracts to the network. - -To deploy the contracts, run the following command: - -```bash -npx hardhat run scripts/deploy.js --network localNode -``` - -This command deploys the contracts to your local blockchain for development and testing. If you want to deploy to Polkadot Hub, you can use the following command: - -```bash -npx hardhat run scripts/deploy.js --network passetHub -``` - -The command above deploys to the actual Polkadot TestNet. It requires PAS test tokens, persists on the network, and operates under real network conditions. - -The deployment script will output the addresses of the deployed contracts. Save these addresses, as you will need them to interact with the contracts. For example, the output should look like this: - -
- npx hardhat run scripts/deploy.js --network localNode - Successfully compiled 12 Solidity files - Deploying contracts using 0xf24FF3a9CF04c71Dbc94D0b566f7A27B94566cac - Deploying UniswapV2ERC20... - ETH deployed to : 0x7acc1aC65892CF3547b1b0590066FB93199b430D - Deploying UniswapV2Factory... - Factory deployed to : 0x85b108660f47caDfAB9e0503104C08C1c96e0DA9 - Deploying UniswapV2Pair with JsonRpcProvider workaround... - Pair deployed to : 0xF0e46847c8bFD122C4b5EEE1D4494FF7C5FC5104 -
- -## Conclusion - -This tutorial guided you through deploying Uniswap V2 contracts to Polkadot Hub. This implementation brings the powerful AMM architecture to the Polkadot ecosystem, laying the foundation for the decentralized trading of ERC-20 token pairs. - -By following this guide, you've gained practical experience with: - -- Setting up a Hardhat project for deploying to Polkadot Hub. -- Understanding the Uniswap V2 architecture. -- Testing Uniswap V2 contracts in a local environment. -- Deploying contracts to both local and testnet environments. - -To build on this foundation, you could extend this project by implementing functionality to create liquidity pools, execute token swaps, and build a user interface for interacting with your deployment. - -This knowledge can be leveraged to build more complex DeFi applications or to integrate Uniswap V2 functionality into your existing projects on Polkadot. - - ---- - -Page Title: Dual Virtual Machine Stack - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-dual-vm-stack.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/dual-vm-stack/ -- Summary: Compare Polkadot’s dual smart contract VMs—REVM for EVM compatibility and PolkaVM for RISC-V performance, flexibility, and efficiency. - -# Dual Virtual Machine Stack - -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction - -Polkadot's smart contract platform supports two distinct virtual machine (VM) architectures, providing developers with flexibility in selecting the optimal execution backend for their specific needs. This approach strikes a balance between immediate Ethereum compatibility and long-term innovation, enabling developers to deploy either unmodified (Ethereum Virtual Machine) EVM contracts using Rust Ethereum Virtual Machine (REVM) or optimize for higher performance using PolkaVM (PVM). - -Both VM options share common infrastructure, including RPC interfaces, tooling support, and precompiles. The following sections compare architectures and guide you in selecting the best VM for your project's needs. - -## Migrate from EVM - -The [REVM backend](https://github.com/bluealloy/revm){target=\_blank} integrates a complete Rust implementation of the EVM, enabling Solidity contracts to run unchanged on Polkadot's smart contract platform. - -REVM allows developers to use their existing Ethereum tooling and infrastructure to build on Polkadot. Choose REVM to: - -- Migrate existing Ethereum contracts without modifications. -- Retain exact EVM behavior for audit tools. -- Use developer tools that rely upon inspecting EVM bytecode. -- Prioritize rapid deployment over optimization. -- Work with established Ethereum infrastructure and tooling to build on Polkadot. - -REVM enables Ethereum developers to seamlessly migrate to Polkadot, achieving performance and fee improvements without modifying their existing contracts or developer tooling stack. - -## Upgrade to PolkaVM - -[**PolkaVM**](https://github.com/paritytech/polkavm){target=\_blank} is a custom virtual machine optimized for performance with [RISC-V-based](https://en.wikipedia.org/wiki/RISC-V){target=\_blank} architecture, supporting Solidity and additional high-performance languages. It serves as the core execution environment, integrated directly within the runtime. Choose the PolkaVM for: - -- An efficient interpreter for immediate code execution. -- A planned [Just In Time (JIT)](https://en.wikipedia.org/wiki/Just-in-time_compilation){target=\_blank} compiler for optimized performance. -- Dual-mode execution capability, allowing selection of the most appropriate backend for specific workloads. -- Optimized performance for short-running contract calls through the interpreter. - -The interpreter remains particularly beneficial for contracts with minimal code execution, as it enables immediate code execution through lazy interpretation. - -## Architecture - -The following key components of PolkaVM work together to enable Ethereum compatibility on Polkadot-based chains. - -### Revive Pallet - -[**`pallet_revive`**](https://paritytech.github.io/polkadot-sdk/master/pallet_revive/index.html){target=\_blank} is a runtime module that executes smart contracts by adding extrinsics, runtime APIs, and logic to convert Ethereum-style transactions into formats compatible with Polkadot SDK-based blockchains. It processes Ethereum-style transactions through the following workflow: - -```mermaid -sequenceDiagram - participant User as User/dApp - participant Proxy as Ethereum JSON RPC Proxy - participant Chain as Blockchain Node - participant Pallet as pallet_revive - - User->>Proxy: Submit Ethereum Transaction - Proxy->>Chain: Repackage as Polkadot Compatible Transaction - Chain->>Pallet: Process Transaction - Pallet->>Pallet: Decode Ethereum Transaction - Pallet->>Pallet: Execute Contract via PolkaVM - Pallet->>Chain: Return Results - Chain->>Proxy: Forward Results - Proxy->>User: Return Ethereum-compatible Response -``` - -This proxy-based approach eliminates the need for node binary modifications, maintaining compatibility across different client implementations. Preserving the original Ethereum transaction payload simplifies the adaptation of existing tools, which can continue processing familiar transaction formats. - -### PolkaVM Design Fundamentals - -PolkaVM differs from the EVM in two key ways that make it faster, more hardware-efficient, and easier to extend: - -- **Register-based design**: Instead of a stack machine, PolkaVM uses a RISC-V–style register model. This design: - - - Uses a fixed set of registers to pass arguments, not an infinite stack. - - Maps cleanly to real hardware like x86-64. - - Simplifies compilation and boosts runtime efficiency. - - Enables tighter control over register allocation and performance tuning. - -- **64-bit word size**: PolkaVM runs on a native 64-bit word size, aligning directly with modern CPUs. This design: - - - Executes arithmetic operations with direct hardware support. - - Maintains compatibility with Solidity’s 256-bit types via YUL translation. - - Accelerates computation-heavy workloads through native word alignment. - - Integrates easily with low-level, performance-focused components. - -## Where To Go Next - -
- -- Learn __Contract Deployment__ - - --- - - Learn how REVM and PVM compare for compiling and deploying smart contracts. - - [:octicons-arrow-right-24: Reference](/smart-contracts/for-eth-devs/contract-deployment/) - -
- - ---- - -Page Title: E2E Testing with Moonwall - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-moonwall.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/moonwall/ -- Summary: Enhance blockchain end-to-end testing with Moonwall's standardized environment setup, comprehensive configuration management, and simple network interactions. - -# E2E Testing with Moonwall - -## Introduction - -Moonwall is an end-to-end testing framework designed explicitly for Polkadot SDK-based blockchain networks. It addresses one of the most significant challenges in blockchain development: managing complex test environments and network configurations. - -Moonwall consolidates this complexity by providing the following: - -- A centralized configuration management system that explicitly defines all network parameters. -- A standardized approach to environment setup across different Substrate-based chains. -- Built-in utilities for common testing scenarios and network interactions. - -Developers can focus on writing meaningful tests rather than managing infrastructure complexities or searching through documentation for configuration options. - -## Prerequisites - -Before you begin, ensure you have the following installed: - -- [Node.js](https://nodejs.org/en/){target=\_blank} (version 20.10 or higher). -- A package manager such as [npm](https://www.npmjs.com/){target=\_blank}, [yarn](https://yarnpkg.com/){target=\_blank}, or [pnpm](https://pnpm.io/){target=\_blank}. - -## Install Moonwall - -Moonwall can be installed globally for system-wide access or locally within specific projects. This section covers both installation methods. - -!!! tip - This documentation corresponds to Moonwall version `5.15.0`. To avoid compatibility issues with the documented features, ensure you're using the matching version. - -### Global Installation - -Global installation provides system-wide access to the Moonwall CLI, making it ideal for developers working across multiple blockchain projects. Install it by running one of the following commands: - -=== "npm" - - ```bash - npm install -g @moonwall/cli@5.15.0 - ``` - -=== "pnpm" - - ```bash - pnpm -g install @moonwall/cli@5.15.0 - ``` - -=== "yarn" - - ```bash - yarn global add @moonwall/cli@5.15.0 - ``` - -Now, you can run the `moonwall` command from your terminal. - -### Local Installation - -Local installation is recommended for better dependency management and version control within a specific project. First, initialize your project: - -```bash -mkdir my-moonwall-project -cd my-moonwall-project -npm init -y -``` - -Then, install it as a local dependency: - -=== "npm" - - ```bash - npm install @moonwall/cli@5.15.0 - ``` - -=== "pnpm" - - ```bash - pnpm install @moonwall/cli@5.15.0 - ``` - -=== "yarn" - - ```bash - yarn add @moonwall/cli@5.15.0 - ``` - -## Initialize Moonwall - -The `moonwall init` command launches an interactive wizard to create your configuration file: - -```bash -moonwall init -``` - -During setup, you will see prompts for the following parameters: - -- **`label`**: Identifies your test configuration. -- **`global timeout`**: Maximum time (ms) for test execution. -- **`environment name`**: Name for your testing environment. -- **`network foundation`**: Type of blockchain environment to use. -- **`tests directory`**: Location of your test files. - -Select `Enter` to accept defaults or input custom values. You should see something like this: - -
- moonwall init - ✔ Provide a label for the config file moonwall_config - ✔ Provide a global timeout value 30000 - ✔ Provide a name for this environment default_env - ✔ What type of network foundation is this? dev - ✔ Provide the path for where tests for this environment are kept tests/ - ? Would you like to generate this config? (no to restart from beginning) (Y/n) -
- -The wizard generates a `moonwall.config` file: - -```json -{ - "label": "moonwall_config", - "defaultTestTimeout": 30000, - "environments": [ - { - "name": "default_env", - "testFileDir": ["tests/"], - "foundation": { - "type": "dev" - } - } - ] -} - -``` - -The default configuration requires specific details about your blockchain node and test requirements: - -- The `foundation` object defines how your test blockchain node will be launched and managed. The dev foundation, which runs a local node binary, is used for local development. - - For more information about available options, check the [Foundations](https://moonsong-labs.github.io/moonwall/guide/intro/foundations.html){target=\_blank} section. - -- The `connections` array specifies how your tests will interact with the blockchain node. This typically includes provider configuration and endpoint details. - - A provider is a tool that allows you or your application to connect to a blockchain network and simplifies the low-level details of the process. A provider handles submitting transactions, reading state, and more. For more information on available providers, check the [Providers supported](https://moonsong-labs.github.io/moonwall/guide/intro/providers.html#providers-supported){target=\_blank} page in the Moonwall documentation. - -Here's a complete configuration example for testing a local node using Polkadot.js as a provider: - -```json -{ - "label": "moonwall_config", - "defaultTestTimeout": 30000, - "environments": [ - { - "name": "default_env", - "testFileDir": ["tests/"], - "foundation": { - "launchSpec": [ - { - "binPath": "./node-template", - "newRpcBehaviour": true, - "ports": { "rpcPort": 9944 } - } - ], - "type": "dev" - }, - "connections": [ - { - "name": "myconnection", - "type": "polkadotJs", - "endpoints": ["ws://127.0.0.1:9944"] - } - ] - } - ] -} - -``` - -## Writing Tests - -Moonwall uses the [`describeSuite`](https://github.com/Moonsong-Labs/moonwall/blob/7568048c52e9f7844f38fb4796ae9e1b9205fdaa/packages/cli/src/lib/runnerContext.ts#L65){target=\_blank} function to define test suites, like using [Mocha](https://mochajs.org/){target=\_blank}. Each test suite requires the following: - -- **`id`**: Unique identifier for the suite. -- **`title`**: Descriptive name for the suite. -- **`foundationMethods`**: Specifies the testing environment (e.g., `dev` for local node testing). -- **`testCases`**: A callback function that houses the individual test cases of this suite. - -The following example shows how to test a balance transfer between two accounts: - -```ts -import '@polkadot/api-augment'; -import { describeSuite, expect } from '@moonwall/cli'; -import { Keyring } from '@polkadot/api'; - -describeSuite({ - id: 'D1', - title: 'Demo suite', - foundationMethods: 'dev', - testCases: ({ it, context, log }) => { - it({ - id: 'T1', - title: 'Test Case', - test: async () => { - // Set up polkadot.js API and testing accounts - let api = context.polkadotJs(); - let alice = new Keyring({ type: 'sr25519' }).addFromUri('//Alice'); - let charlie = new Keyring({ type: 'sr25519' }).addFromUri('//Charlie'); - - // Query Charlie's account balance before transfer - const balanceBefore = (await api.query.system.account(charlie.address)) - .data.free; - - // Before transfer, Charlie's account balance should be 0 - expect(balanceBefore.toString()).toEqual('0'); - log('Balance before: ' + balanceBefore.toString()); - - // Transfer from Alice to Charlie - const amount = 1000000000000000; - await api.tx.balances - .transferAllowDeath(charlie.address, amount) - .signAndSend(alice); - - // Wait for the transaction to be included in a block. - // This is necessary because the balance is not updated immediately. - // Block time is 6 seconds. - await new Promise((resolve) => setTimeout(resolve, 6000)); - - // Query Charlie's account balance after transfer - const balanceAfter = (await api.query.system.account(charlie.address)) - .data.free; - - // After transfer, Charlie's account balance should be 1000000000000000 - expect(balanceAfter.toString()).toEqual(amount.toString()); - log('Balance after: ' + balanceAfter.toString()); - }, - }); - }, -}); - -``` - -This test demonstrates several key concepts: - -- Initializing the Polkadot.js API through Moonwall's context and setting up test accounts. -- Querying on-chain state. -- Executing transactions. -- Waiting for block inclusion. -- Verifying results using assertions. - -## Running the Tests - -Execute your tests using the `test` Moonwall CLI command. For the default environment setup run: - -```bash -moonwall test default_env -c moonwall.config -``` - -The test runner will output detailed results showing: - -- Test suite execution status. -- Individual test case results. -- Execution time. -- Detailed logs and error messages (if any). - -Example output: -
- moonwall test default_env -c moonwall.config - stdout | tests/test1.ts > 🗃️ D1 Demo suite > 📁 D1T1 Test Case - 2025-01-21T19:27:55.624Z test:default_env Balance before: 0 - - stdout | tests/test1.ts > 🗃️ D1 Demo suite > 📁 D1T1 Test Case - 2025-01-21T19:28:01.637Z test:default_env Balance after: 1000000000000000 - - ✓ default_env tests/test1.ts (1 test) 6443ms - ✓ 🗃️ D1 Demo suite > 📁 D1T1 Test Case 6028ms - - Test Files 1 passed (1) - Tests 1 passed (1) - Start at 16:27:53 - Duration 7.95s (transform 72ms, setup 0ms, collect 1.31s, tests 6.44s, environment 0ms, prepare 46ms) - - ✅ All tests passed -
- -## Where to Go Next - -For a comprehensive guide to Moonwall's full capabilities, available configurations, and advanced usage, see the official [Moonwall](https://moonsong-labs.github.io/moonwall/){target=\_blank} documentation. - - ---- - -Page Title: Get Started - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-fork-a-parachain.md -- Canonical (HTML): https://docs.polkadot.com/parachains/testing/fork-a-parachain/ -- Summary: Simplify Polkadot SDK development with Chopsticks. Learn essential features, how to install Chopsticks, and how to configure local blockchain forks. - -# Get Started - -## Introduction - -[Chopsticks](https://github.com/AcalaNetwork/chopsticks/){target=\_blank}, developed by the [Acala Foundation](https://github.com/AcalaNetwork){target=\_blank}, is a versatile tool tailored for developers working on Polkadot SDK-based blockchains. With Chopsticks, you can fork live chains locally, replay blocks to analyze extrinsics, and simulate complex scenarios like XCM interactions all without deploying to a live network. - -This guide walks you through installing Chopsticks and provides information on configuring a local blockchain fork. By streamlining testing and experimentation, Chopsticks empowers developers to innovate and accelerate their blockchain projects within the Polkadot ecosystem. - -For additional support and information, please reach out through [GitHub Issues](https://github.com/AcalaNetwork/chopsticks/issues){target=_blank}. - -!!! warning - Chopsticks uses [Smoldot](https://github.com/smol-dot/smoldot){target=_blank} light client, which only supports the native Polkadot SDK API. Consequently, a Chopsticks-based fork doesn't support Ethereum JSON-RPC calls, meaning you cannot use it to fork your chain and connect Metamask. - -## Prerequisites - -Before you begin, ensure you have the following installed: - -- [Node.js](https://nodejs.org/en/){target=\_blank}. -- A package manager such as [npm](https://www.npmjs.com/){target=\_blank}, which should be installed with Node.js by default, or [Yarn](https://yarnpkg.com/){target=\_blank}. - -## Install Chopsticks - -You can install Chopsticks globally or locally in your project. Choose the option that best fits your development workflow. This documentation explains the features of Chopsticks version `1.2.2`. Make sure you're using the correct version to match these instructions. - -### Global Installation - -To install Chopsticks globally, allowing you to use it across multiple projects, run: - -```bash -npm i -g @acala-network/chopsticks@1.2.2 -``` - -Now, you should be able to run the `chopsticks` command from your terminal. - -### Local Installation - -To use Chopsticks in a specific project, first create a new directory and initialize a Node.js project: - -```bash -mkdir my-chopsticks-project -cd my-chopsticks-project -npm init -y -``` - -Then, install Chopsticks as a local dependency: - -```bash -npm i @acala-network/chopsticks@1.2.2 -``` - -Finally, you can run Chopsticks using the `npx` command. To see all available options and commands, run it with the `--help` flag: - -```bash -npx @acala-network/chopsticks --help -``` - -## Configure Chopsticks - -To run Chopsticks, you need to configure some parameters. This can be set either through using a configuration file or the command line interface (CLI). The parameters that can be configured are as follows: - -- **`genesis`**: The link to a parachain's raw genesis file to build the fork from, instead of an endpoint. -- **`timestamp`**: Timestamp of the block to fork from. -- **`endpoint`**: The endpoint of the parachain to fork. -- **`block`**: Use to specify at which block hash or number to replay the fork. -- **`wasm-override`**: Path of the Wasm to use as the parachain runtime, instead of an endpoint's runtime. -- **`db`**: Path to the name of the file that stores or will store the parachain's database. -- **`config`**: Path or URL of the config file. -- **`port`**: The port to expose an endpoint on. -- **`build-block-mode`**: How blocks should be built in the fork: batch, manual, instant. -- **`import-storage`**: A pre-defined JSON/YAML storage path to override in the parachain's storage. -- **`allow-unresolved-imports`**: Whether to allow Wasm unresolved imports when using a Wasm to build the parachain. -- **`html`**: Include to generate storage diff preview between blocks. -- **`mock-signature-host`**: Mock signature host so that any signature starts with `0xdeadbeef` and filled by `0xcd` is considered valid. - -### Configuration File - -The Chopsticks source repository includes a collection of [YAML](https://yaml.org/){target=\_blank} files that can be used to set up various Polkadot SDK chains locally. You can download these configuration files from the [repository's `configs` folder](https://github.com/AcalaNetwork/chopsticks/tree/master/configs){target=\_blank}. - -An example of a configuration file for Polkadot is as follows: - -{% raw %} -```yaml -endpoint: - - wss://rpc.ibp.network/polkadot - - wss://polkadot-rpc.dwellir.com -mock-signature-host: true -block: ${env.POLKADOT_BLOCK_NUMBER} -db: ./db.sqlite -runtime-log-level: 5 - -import-storage: - System: - Account: - - - - 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY - - providers: 1 - data: - free: '10000000000000000000' - ParasDisputes: - $removePrefix: ['disputes'] # those can makes block building super slow - -``` -{% endraw %} - -The configuration file allows you to modify the storage of the forked network by rewriting the pallet, state component and value that you want to change. For example, Polkadot's file rewrites Alice's `system.Account` storage so that the free balance is set to `10000000000000000000`. - -### CLI Flags - -Alternatively, all settings (except for genesis and timestamp) can be configured via command-line flags, providing a comprehensive method to set up the environment. - -## WebSocket Commands - -Chopstick's internal WebSocket server has special endpoints that allow the manipulation of the local Polkadot SDK chain. - -These are the methods that can be invoked and their parameters: - -- **dev_newBlock** (newBlockParams): Generates one or more new blocks. - - === "Parameters" - - - **`newBlockParams` ++"NewBlockParams"++**: The parameters to build the new block with. Where the `NewBlockParams` interface includes the following properties. - - - **`count` ++"number"++**: The number of blocks to build. - - **`dmp` ++"{ msg: string, sentAt: number }[]"++**: The downward messages to include in the block. - - **`hrmp` ++"Record"++**: The horizontal messages to include in the block. - - **`to` ++"number"++**: The block number to build to. - - **`transactions` ++"string[]"++**: The transactions to include in the block. - - **`ump` ++"Record"++**: The upward messages to include in the block. - - **`unsafeBlockHeight` ++"number"++**: Build block using a specific block height (unsafe). - - === "Example" - - ```js - import { ApiPromise, WsProvider } from '@polkadot/api'; - - async function main() { - const wsProvider = new WsProvider('ws://localhost:8000'); - const api = await ApiPromise.create({ provider: wsProvider }); - await api.isReady; - await api.rpc('dev_newBlock', { count: 1 }); - } - - main(); - - ``` - -- **dev_setBlockBuildMode** (buildBlockMode): Sets block build mode. - - === "Parameter" - - - **`buildBlockMode` ++"BuildBlockMode"++**: The build mode. Can be any of the following modes: - - ```ts - export enum BuildBlockMode { - Batch = 'Batch', /** One block per batch (default) */ - Instant = 'Instant', /** One block per transaction */ - Manual = 'Manual', /** Only build when triggered */ - } - ``` - - === "Example" - - ```js - import { ApiPromise, WsProvider } from '@polkadot/api'; - - async function main() { - const wsProvider = new WsProvider('ws://localhost:8000'); - const api = await ApiPromise.create({ provider: wsProvider }); - await api.isReady; - await api.rpc('dev_setBlockBuildMode', 'Instant'); - } - - main(); - - ``` - -- **dev_setHead** (hashOrNumber): Sets the head of the blockchain to a specific hash or number. - - === "Parameter" - - - **`hashOrNumber` ++"string | number"++**: The block hash or number to set as head. - - === "Example" - - ```js - import { ApiPromise, WsProvider } from '@polkadot/api'; - - async function main() { - const wsProvider = new WsProvider('ws://localhost:8000'); - const api = await ApiPromise.create({ provider: wsProvider }); - await api.isReady; - await api.rpc('dev_setHead', 500); - } - - main(); - - ``` - -- **dev_setRuntimeLogLevel** (runtimeLogLevel): Sets the runtime log level. - - === "Parameter" - - - **`runtimeLogLevel` ++"number"++**: The runtime log level to set. - - === "Example" - - ```js - import { ApiPromise, WsProvider } from '@polkadot/api'; - - async function main() { - const wsProvider = new WsProvider('ws://localhost:8000'); - const api = await ApiPromise.create({ provider: wsProvider }); - await api.isReady; - await api.rpc('dev_setRuntimeLogLevel', 1); - } - - main(); - - ``` - -- **dev_setStorage** (values, blockHash): Creates or overwrites the value of any storage. - - === "Parameters" - - - **`values` ++"object"++**: JSON object resembling the path to a storage value. - - **`blockHash` ++"string"++**: The block hash to set the storage value. - - === "Example" - - ```js - import { ApiPromise, WsProvider } from '@polkadot/api'; - - import { Keyring } from '@polkadot/keyring'; - async function main() { - const wsProvider = new WsProvider('ws://localhost:8000'); - const api = await ApiPromise.create({ provider: wsProvider }); - await api.isReady; - const keyring = new Keyring({ type: 'ed25519' }); - const bob = keyring.addFromUri('//Bob'); - const storage = { - System: { - Account: [[[bob.address], { data: { free: 100000 }, nonce: 1 }]], - }, - }; - await api.rpc('dev_setStorage', storage); - } - - main(); - - ``` - -- **dev_timeTravel** (date): Sets the timestamp of the block to a specific date". - - === "Parameter" - - - **`date` ++"string"++**: Timestamp or date string to set. All future blocks will be sequentially created after this point in time. - - === "Example" - - ```js - import { ApiPromise, WsProvider } from '@polkadot/api'; - - async function main() { - const wsProvider = new WsProvider('ws://localhost:8000'); - const api = await ApiPromise.create({ provider: wsProvider }); - await api.isReady; - await api.rpc('dev_timeTravel', '2030-08-15T00:00:00'); - } - - main(); - - ``` - -## Where to Go Next - -
- -- Tutorial __Fork a Chain with Chopsticks__ - - --- - - Visit this guide for step-by-step instructions for configuring and interacting with your forked chain. - - [:octicons-arrow-right-24: Reference](/tutorials/polkadot-sdk/testing/fork-live-chains/) - -
- - ---- - -Page Title: Get Started - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-run-a-parachain-network.md -- Canonical (HTML): https://docs.polkadot.com/parachains/testing/run-a-parachain-network/ -- Summary: Quickly install and configure Zombienet to deploy and test Polkadot-based blockchain networks with this comprehensive getting-started guide. - -# Get Started - -## Introduction - -Zombienet is a robust testing framework designed for Polkadot SDK-based blockchain networks. It enables developers to efficiently deploy and test ephemeral blockchain environments on platforms like Kubernetes, Podman, and native setups. With its simple and versatile CLI, Zombienet provides an all-in-one solution for spawning networks, running tests, and validating performance. - -This guide will outline the different installation methods for Zombienet, provide step-by-step instructions for setting up on various platforms, and highlight essential provider-specific features and requirements. - -By following this guide, Zombienet will be up and running quickly, ready to streamline your blockchain testing and development workflows. - -## Install Zombienet - -Zombienet releases are available on the [Zombienet repository](https://github.com/paritytech/zombienet){target=\_blank}. - -Multiple options are available for installing Zombienet, depending on the user's preferences and the environment where it will be used. The following section will guide you through the installation process for each option. - -=== "Use the executable" - - Install Zombienet using executables by visiting the [latest release](https://github.com/paritytech/zombienet/releases){target=\_blank} page and selecting the appropriate asset for your operating system. You can download the executable and move it to a directory in your PATH. - - Each release includes executables for Linux and macOS. Executables are generated using [pkg](https://github.com/vercel/pkg){target=\_blank}, which allows the Zombienet CLI to operate without requiring Node.js to be installed. - - Then, ensure the downloaded file is executable: - - ```bash - chmod +x zombienet-macos-arm64 - ``` - - Finally, you can run the following command to check if the installation was successful. If so, it will display the version of the installed Zombienet: - - ```bash - ./zombienet-macos-arm64 version - ``` - - If you want to add the `zombienet` executable to your PATH, you can move it to a directory in your PATH, such as `/usr/local/bin`: - - ```bash - mv zombienet-macos-arm64 /usr/local/bin/zombienet - ``` - - Now you can refer to the `zombienet` executable directly. - - ```bash - zombienet version - ``` - -=== "Use Nix" - - For Nix users, the Zombienet repository provides a [`flake.nix`](https://github.com/paritytech/zombienet/blob/main/flake.nix){target=\_blank} file to install Zombienet making it easy to incorporate Zombienet into Nix-based projects. - - To install Zombienet utilizing Nix, users can run the following command, triggering the fetching of the flake and subsequently installing the Zombienet package: - - ```bash - nix run github:paritytech/zombienet/INSERT_ZOMBIENET_VERSION -- \ - spawn INSERT_ZOMBIENET_CONFIG_FILE_NAME.toml - ``` - - Replace the `INSERT_ZOMBIENET_VERSION` with the desired version of Zombienet and the `INSERT_ZOMBIENET_CONFIG_FILE_NAME` with the name of the configuration file you want to use. - - To run the command above, you need to have [Flakes](https://nixos.wiki/wiki/Flakes#Enable_flakes){target=\_blank} enabled. - - Alternatively, you can also include the Zombienet binary in the PATH for the current shell using the following command: - - ```bash - nix shell github:paritytech/zombienet/INSERT_ZOMBIENET_VERSION - ``` - -=== "Use Docker" - - Zombienet can also be run using Docker. The Zombienet repository provides a Docker image that can be used to run the Zombienet CLI. To run Zombienet using Docker, you can use the following command: - - ```bash - docker run -it --rm \ - -v $(pwd):/home/nonroot/zombie-net/host-current-files \ - paritytech/zombienet - ``` - - The command above will run the Zombienet CLI inside a Docker container and mount the current directory to the `/home/nonroot/zombie-net/host-current-files` directory. This allows Zombienet to access the configuration file and other files in the current directory. If you want to mount a different directory, replace `$(pwd)` with the desired directory path. - - Inside the Docker container, you can run the Zombienet CLI commands. First, you need to set up Zombienet to download the necessary binaries: - - ```bash - npm run zombie -- setup polkadot polkadot-parachain - ``` - - After that, you need to add those binaries to the PATH: - - ```bash - export PATH=/home/nonroot/zombie-net:$PATH - ``` - - Finally, you can run the Zombienet CLI commands. For example, to spawn a network using a specific configuration file, you can run the following command: - - ```bash - npm run zombie -- -p native spawn host-current-files/minimal.toml - ``` - - The command above mounts the current directory to the `/workspace` directory inside the Docker container, allowing Zombienet to access the configuration file and other files in the current directory. If you want to mount a different directory, replace `$(pwd)` with the desired directory path. - -## Providers - -Zombienet supports different backend providers for running the nodes. At this moment, [Kubernetes](https://kubernetes.io/){target=\_blank}, [Podman](https://podman.io/){target=\_blank}, and local providers are supported, which can be declared as `kubernetes`, `podman`, or `native`, respectively. - -To use a particular provider, you can specify it in the network file or use the `--provider` flag in the CLI: - -```bash -zombienet spawn network.toml --provider INSERT_PROVIDER -``` - -Alternatively, you can set the provider in the network file: - -```toml -[settings] -provider = "INSERT_PROVIDER" -... -``` - -It's important to note that each provider has specific requirements and associated features. The following sections cover each provider's requirements and added features. - -### Kubernetes - -Kubernetes is a portable, extensible, open-source platform for managing containerized workloads and services. Zombienet is designed to be compatible with a variety of Kubernetes clusters, including: - -- [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine){target=\_blank} -- [Docker Desktop](https://docs.docker.com/desktop/features/kubernetes/){target=\_blank} -- [kind](https://kind.sigs.k8s.io/){target=\_blank} - -#### Requirements - -To effectively interact with your cluster, you'll need to ensure that [`kubectl`](https://kubernetes.io/docs/reference/kubectl/){target=\_blank} is installed on your system. This Kubernetes command-line tool allows you to run commands against Kubernetes clusters. If you don't have `kubectl` installed, you can follow the instructions provided in the [Kubernetes documentation](https://kubernetes.io/docs/tasks/tools/#kubectl){target=\_blank}. - -To create resources such as namespaces, pods, and CronJobs within the target cluster, you must grant your user or service account the appropriate permissions. These permissions are essential for managing and deploying applications effectively within Kubernetes. - -#### Features - -If available, Zombienet uses the Prometheus operator to oversee monitoring and visibility. This configuration ensures that only essential networking-related pods are deployed. Using the Prometheus operator, Zombienet improves its ability to monitor and manage network activities within the Kubernetes cluster efficiently. - -### Podman - -Podman is a daemonless container engine for developing, managing, and running Open Container Initiative (OCI) containers and container images on Linux-based systems. Zombienet supports Podman rootless as a provider on Linux machines. Although Podman has support for macOS through an internal virtual machine (VM), the Zombienet provider code requires Podman to run natively on Linux. - -#### Requirements - -To use Podman as a provider, you need to have Podman installed on your system. You can install Podman by following the instructions provided on the [Podman website](https://podman.io/getting-started/installation){target=\_blank}. - -#### Features - -Using Podman, Zombienet deploys additional pods to enhance the monitoring and visibility of the active network. Specifically, pods for [Prometheus](https://prometheus.io/){target=\_blank}, [Tempo](https://grafana.com/docs/tempo/latest/operations/monitor/){target=\_blank}, and [Grafana](https://grafana.com/){target=\_blank} are included in the deployment. Grafana is configured with Prometheus and Tempo as data sources. - -Upon launching Zombienet, access to these monitoring services is facilitated through specific URLs provided in the output: - -- **Prometheus**: `http://127.0.0.1:34123` -- **Tempo**: `http://127.0.0.1:34125` -- **Grafana**: `http://127.0.0.1:41461` - -It's important to note that Grafana is deployed with default administrator access. - -When network operations cease, either from halting a running spawn with the `Ctrl+C` command or test completion, Zombienet automatically removes all associated pods. - -### Local Provider - -The Zombienet local provider, also called native, enables you to run nodes as local processes in your environment. - -#### Requirements - -You must have the necessary binaries for your network (such as `polkadot` and `polkadot-parachain`). These binaries should be available in your PATH, allowing Zombienet to spawn the nodes as local processes. - -To install the necessary binaries, you can use the Zombienet CLI command: - -```bash -zombienet setup polkadot polkadot-parachain -``` - -This command will download and prepare the necessary binaries for Zombienet's use. - -If you need to use a custom binary, ensure the binary is available in your PATH. You can also specify the binary path in the network configuration file. The following example uses the custom [OpenZeppelin template](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\_blank}: - -First, clone the OpenZeppelin template repository using the following command: - -```bash -git clone https://github.com/OpenZeppelin/polkadot-runtime-templates \ -&& cd polkadot-runtime-templates/generic-template -``` - -Next, run the command to build the custom binary: - -```bash -cargo build --release -``` - -Finally, add the custom binary to your PATH as follows: - -```bash -export PATH=$PATH:INSERT_PATH_TO_RUNTIME_TEMPLATES/parachain-template-node/target/release -``` - -Alternatively, you can specify the binary path in the network configuration file. The local provider exclusively utilizes the command configuration for nodes, which supports both relative and absolute paths. You can employ the `default_command` configuration to specify the binary for spawning all nodes in the relay chain. - -```toml -[relaychain] -chain = "rococo-local" -default_command = "./bin-v1.6.0/polkadot" - -[parachain] -id = 1000 - - [parachain.collators] - name = "collator01" - command = "./target/release/parachain-template-node" -``` - -#### Features - -The local provider does not offer any additional features. - -## Configure Zombienet - -Effective network configuration is crucial for deploying and managing blockchain systems. Zombienet simplifies this process by offering versatile configuration options in both JSON and TOML formats. Whether setting up a simple test network or a complex multi-node system, Zombienet's tools provide the flexibility to customize every aspect of your network's setup. - -The following sections will explore the structure and usage of Zombienet configuration files, explain key settings for network customization, and walk through CLI commands and flags to optimize your development workflow. - -### Configuration Files - -The network configuration file can be either JSON or TOML format. The Zombienet repository also provides a collection of [example configuration files](https://github.com/paritytech/zombienet/tree/main/examples){target=\_blank} that can be used as a reference. - -Each section may include provider-specific keys that aren't recognized by other providers. For example, if you use the local provider, any references to images for nodes will be disregarded. - -### CLI Usage - -Zombienet provides a CLI that allows interaction with the tool. The CLI can receive commands and flags to perform different kinds of operations. These operations use the following syntax: - -```bash -zombienet -``` - -The following sections will guide you through the primary usage of the Zombienet CLI and the available commands and flags. - -#### CLI Commands - -- **`spawn `**: Spawn the network defined in the [configuration file](#configuration-files). -- **`test `**: Run tests on the spawned network using the assertions and tests defined in the [test file](/develop/toolkit/parachains/spawn-chains/zombienet/write-tests/#the-test-file){target=\_blank}. -- **`setup `**: Set up the Zombienet development environment to download and use the `polkadot` or `polkadot-parachain` executable. -- **`convert `**: Transforms a [polkadot-launch](https://github.com/paritytech/polkadot-launch){target=\_blank} configuration file with a `.js` or `.json` extension into a Zombienet configuration file. -- **`version`**: Prints Zombienet version. -- **`help`**: Prints help information. - -#### CLI Flags - -You can use the following flags to customize the behavior of the CLI: - -- **`-p`, `--provider`**: Override the [provider](#providers) to use. -- **`-d`, `--dir`**: Specify a directory path for placing the network files instead of using the default temporary path. -- **`-f`, `--force`**: Force override all prompt commands. -- **`-l`, `--logType`**: Type of logging on the console. Defaults to `table`. -- **`-m`, `--monitor`**: Start as monitor and don't auto clean up network. -- **`-c`, `--spawn-concurrency`**: Number of concurrent spawning processes to launch. Defaults to `1`. -- **`-h`, `--help`**: Display help for command. - -### Settings - -Through the keyword `settings`, it's possible to define the general settings for the network. The available keys are: - -- **`global_volumes?`** ++"GlobalVolume[]"++: A list of global volumes to use. - - ??? child "`GlobalVolume` interface definition" - ```js - export interface GlobalVolume { - name: string; - fs_type: string; - mount_path: string; - } - ``` - -- **`bootnode`** ++"boolean"++: Add bootnode to network. Defaults to `true`. -- **`bootnode_domain?`** ++"string"++: Domain to use for bootnode. -- **`timeout`** ++"number"++: Global timeout to use for spawning the whole network. -- **`node_spawn_timeout?`** ++"number"++: Timeout to spawn pod/process. -- **`grafana?`** ++"boolean"++: Deploy an instance of Grafana. -- **`prometheus?`** ++"boolean"++: Deploy an instance of Prometheus. -- **`telemetry?`** ++"boolean"++: Enable telemetry for the network. -- **`jaeger_agent?`** ++"string"++: The Jaeger agent endpoint passed to the nodes. Only available on Kubernetes. -- **`tracing_collator_url?`** ++"string"++: The URL of the tracing collator used to query by the tracing assertion. Should be tempo query compatible. -- **`tracing_collator_service_name?`** ++"string"++: Service name for tempo query frontend. Only available on Kubernetes. Defaults to `tempo-tempo-distributed-query-frontend`. -- **`tracing_collator_service_namespace?`** ++"string"++: Namespace where tempo is running. Only available on Kubernetes. Defaults to `tempo`. -- **`tracing_collator_service_port?`** ++"number"++: Port of the query instance of tempo. Only available on Kubernetes. Defaults to `3100`. -- **`enable_tracing?`** ++"boolean"++: Enable the tracing system. Only available on Kubernetes. Defaults to `true`. -- **`provider`** ++"string"++: Provider to use. Default is `kubernetes`". -- **`polkadot_introspector?`** ++"boolean"++: Deploy an instance of polkadot-introspector. Only available on Podman and Kubernetes. Defaults to `false`. -- **`backchannel?`** ++"boolean"++: Deploy an instance of backchannel server. Only available on Kubernetes. Defaults to `false`. -- **`image_pull_policy?`** ++"string"++: Image pull policy to use in the network. Possible values are `Always`, `IfNotPresent`, and `Never`. -- **`local_ip?`** ++"string"++: IP used for exposing local services (rpc/metrics/monitors). Defaults to `"127.0.0.1"`. -- **`global_delay_network_global_settings?`** ++"number"++: Delay in seconds to apply to the network. -- **`node_verifier?`** ++"string"++: Specify how to verify node readiness or deactivate by using `None`. Possible values are `None` and `Metric`. Defaults to `Metric`. - -For example, the following configuration file defines a minimal example for the settings: - -=== "TOML" - - ```toml title="base-example.toml" - [settings] - timeout = 1000 - bootnode = false - provider = "kubernetes" - backchannel = false - # ... - - ``` - -=== "JSON" - - ```json title="base-example.json" - { - "settings": { - "timeout": 1000, - "bootnode": false, - "provider": "kubernetes", - "backchannel": false, - "...": {} - }, - "...": {} - } - - ``` - -### Relay Chain Configuration - -You can use the `relaychain` keyword to define further parameters for the relay chain at start-up. The available keys are: - -- **`default_command?`** ++"string"++: The default command to run. Defaults to `polkadot`. -- **`default_image?`** ++"string"++: The default Docker image to use. -- **`default_resources?`** ++"Resources"++: Represents the resource limits/reservations the nodes need by default. Only available on Kubernetes. - - ??? child "`Resources` interface definition" - ```js - export interface Resources { - resources: { - requests?: { - memory?: string; - cpu?: string; - }; - limits?: { - memory?: string; - cpu?: string; - }; - }; - } - ``` - -- **`default_db_snapshot?`** ++"string"++: The default database snapshot to use. -- **`default_prometheus_prefix`** ++"string"++: A parameter for customizing the metric's prefix. Defaults to `substrate`. -- **`default_substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version. - - ??? child "`SubstrateCliArgsVersion` enum definition" - ```js - export enum SubstrateCliArgsVersion { - V0 = 0, - V1 = 1, - V2 = 2, - V3 = 3, - } - ``` - -- **`default_keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. -- **`chain`** ++"string"++: The chain name. -- **`chain_spec_path?`** ++"string"++: Path to the chain spec file. Should be the plain version to allow customizations. -- **`chain_spec_command?`** ++"string"++: Command to generate the chain spec. It can't be used in combination with `chain_spec_path`. -- **`default_args?`** ++"string[]"++: An array of arguments to use as default to pass to the command. -- **`default_overrides?`** ++"Override[]"++: An array of overrides to upload to the node. - - ??? child "`Override` interface definition" - ```js - export interface Override { - local_path: string; - remote_name: string; - } - ``` - -- **`random_nominators_count?`** ++"number"++: If set and the stacking pallet is enabled, Zombienet will generate the input quantity of nominators and inject them into the genesis. -- **`max_nominations`** ++"number"++: The max number of nominations allowed by a nominator. Should match the value set in the runtime. Defaults to `24`. -- **`nodes?`** ++"Node[]"++: An array of nodes to spawn. It is further defined in the [Node Configuration](#node-configuration) section. -- **`node_groups?`** ++"NodeGroup[]"++: An array of node groups to spawn. It is further defined in the [Node Group Configuration](#node-group-configuration) section. -- **`total_node_in_group?`** ++"number"++: The total number of nodes in the group. Defaults to `1`. -- **`genesis`** ++"JSON"++: The genesis configuration. -- **`default_delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. - - ??? child "`DelayNetworkSettings` interface definition" - ```js - export interface DelayNetworkSettings { - latency: string; - correlation?: string; // should be parsable as float by k8s - jitter?: string; - } - ``` - -#### Node Configuration - -One specific key capable of receiving more subkeys is the `nodes` key. This key is used to define further parameters for the nodes. The available keys: - -- **`name`** ++"string"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`). -- **`image?`** ++"string"++: Override default Docker image to use for this node. -- **`command?`** ++"string"++: Override default command to run. -- **`command_with_args?`** ++"string"++: Override default command and arguments. -- **`args?`** ++"string[]"++: Arguments to be passed to the command. -- **`env?`** ++"envVars[]"++: Environment variables to set in the container. - - ??? child "`envVars` interface definition" - ```js - export interface EnvVars { - name: string; - value: string; - } - ``` - -- **`prometheus_prefix?`** ++"string"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`. -- **`db_snapshot?`** ++"string"++: Database snapshot to use. -- **`substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead. - - ??? child "`SubstrateCliArgsVersion` enum definition" - ```js - export enum SubstrateCliArgsVersion { - V0 = 0, - V1 = 1, - V2 = 2, - V3 = 3, - } - ``` - -- **`resources?`** ++"Resources"++: Represent the resources limits/reservations needed by the node. - - ??? child "`Resources` interface definition" - ```js - export interface Resources { - resources: { - requests?: { - memory?: string; - cpu?: string; - }; - limits?: { - memory?: string; - cpu?: string; - }; - }; - } - ``` - -- **`keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. -- **`validator`** ++"boolean"++: Pass the `--validator` flag to the command. Defaults to `true`. -- **`invulnerable`** ++"boolean"++: If true, add the node to invulnerables in the chain spec. Defaults to `false`. -- **`balance`** ++"number"++: Balance to set in balances for node's account. Defaults to `2000000000000`. -- **`bootnodes?`** ++"string[]"++: Array of bootnodes to use. -- **`add_to_bootnodes?`** ++"boolean"++: Add this node to the bootnode list. Defaults to `false`. -- **`ws_port?`** ++"number"++: WS port to use. -- **`rpc_port?`** ++"number"++: RPC port to use. -- **`prometheus_port?`** ++"number"++: Prometheus port to use. -- **`p2p_cert_hash?`** ++"string"++: Libp2p certhash to use with webRTC transport. -- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. - - ??? child "`DelayNetworkSettings` interface definition" - ```js - export interface DelayNetworkSettings { - latency: string; - correlation?: string; // should be parsable as float by k8s - jitter?: string; - } - ``` - -The following configuration file defines a minimal example for the relay chain, including the `nodes` key: - -=== "TOML" - - ```toml title="relaychain-example-nodes.toml" - [relaychain] - default_command = "polkadot" - default_image = "polkadot-debug:master" - chain = "rococo-local" - chain_spec_path = "INSERT_PATH_TO_CHAIN_SPEC" - default_args = ["--chain", "rococo-local"] - - [[relaychain.nodes]] - name = "alice" - validator = true - balance = 1000000000000 - - [[relaychain.nodes]] - name = "bob" - validator = true - balance = 1000000000000 - # ... - - ``` - -=== "JSON" - - ```json title="relaychain-example-nodes.json" - { - "relaychain": { - "default_command": "polkadot", - "default_image": "polkadot-debug:master", - "chain": "rococo-local", - "chain_spec_path": "INSERT_PATH_TO_CHAIN-SPEC.JSON", - "default_args": ["--chain", "rococo-local"], - "nodes": [ - { - "name": "alice", - "validator": true, - "balance": 1000000000000 - }, - { - "name": "bob", - "validator": true, - "balance": 1000000000000 - } - ] - } - } - - ``` - -#### Node Group Configuration - -The `node_groups` key defines further parameters for the node groups. The available keys are: - -- **`name`** ++"string"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`). -- **`image?`** ++"string"++: Override default Docker image to use for this node. -- **`command?`** ++"string"++: Override default command to run. -- **`args?`** ++"string[]"++: Arguments to be passed to the command. -- **`env?`** ++"envVars[]"++: Environment variables to set in the container. - - ??? child "`envVars` interface definition" - ```js - export interface EnvVars { - name: string; - value: string; - } - ``` - -- **`overrides?`** ++"Override[]"++: Array of overrides definitions. - - ??? child "`Override` interface definition" - ```js - export interface Override { - local_path: string; - remote_name: string; - } - ``` - -- **`prometheus_prefix?`** ++"string"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`. -- **`db_snapshot?`** ++"string"++: Database snapshot to use. -- **`substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead. - - ??? child "`SubstrateCliArgsVersion` enum definition" - ```js - export enum SubstrateCliArgsVersion { - V0 = 0, - V1 = 1, - V2 = 2, - V3 = 3, - } - ``` - -- **`resources?`** ++"Resources"++: Represent the resources limits/reservations needed by the node. - - ??? child "`Resources` interface definition" - ```js - export interface Resources { - resources: { - requests?: { - memory?: string; - cpu?: string; - }; - limits?: { - memory?: string; - cpu?: string; - }; - }; - } - ``` - -- **`keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. -- **`count`** ++"number | string"++: Number of nodes to launch for this group. -- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. - - ??? child "`DelayNetworkSettings` interface definition" - ```js - export interface DelayNetworkSettings { - latency: string; - correlation?: string; // should be parsable as float by k8s - jitter?: string; - } - ``` - -The following configuration file defines a minimal example for the relay chain, including the `node_groups` key: - -=== "TOML" - - ```toml title="relaychain-example-node-groups.toml" - [relaychain] - default_command = "polkadot" - default_image = "polkadot-debug:master" - chain = "rococo-local" - chain_spec_path = "INSERT_PATH_TO_CHAIN_SPEC" - default_args = ["--chain", "rococo-local"] - - [[relaychain.node_groups]] - name = "group-1" - count = 2 - image = "polkadot-debug:master" - command = "polkadot" - args = ["--chain", "rococo-local"] - # ... - - ``` - -=== "JSON" - - ```json title="relaychain-example-node-groups.json" - { - "relaychain": { - "default_command": "polkadot", - "default_image": "polkadot-debug:master", - "chain": "rococo-local", - "chain_spec_path": "INSERT_PATH_TO_CHAIN-SPEC.JSON", - "default_args": ["--chain", "rococo-local"], - "node_groups": [ - { - "name": "group-1", - "count": 2, - "image": "polkadot-debug:master", - "command": "polkadot", - "args": ["--chain", "rococo-local"] - } - ], - "...": {} - }, - "...": {} - } - - ``` - -### Parachain Configuration - -The `parachain` keyword defines further parameters for the parachain. The available keys are: - -- **`id`** ++"number"++: The id to assign to this parachain. Must be unique. -- **`chain?`** ++"string"++: The chain name. -- **`force_decorator?`** ++"string"++: Force the use of a specific decorator. -- **`genesis?`** ++"JSON"++: The genesis configuration. -- **`balance?`** ++"number"++: Balance to set in balances for parachain's account. -- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. - - ??? child "`DelayNetworkSettings` interface definition" - ```js - export interface DelayNetworkSettings { - latency: string; - correlation?: string; // should be parsable as float by k8s - jitter?: string; - } - ``` - -- **`add_to_genesis?`** ++"boolean"++: Flag to add parachain to genesis or register in runtime. Defaults to `true`. -- **`register_para?`** ++"boolean"++: Flag to specify whether the para should be registered. The `add_to_genesis` flag must be set to false for this flag to have any effect. Defaults to `true`. -- **`onboard_as_parachain?`** ++"boolean"++: Flag to specify whether the para should be onboarded as a parachain, rather than remaining a parathread. Defaults to `true`. -- **`genesis_wasm_path?`** ++"string"++: Path to the Wasm file to use. -- **`genesis_wasm_generator?`** ++"string"++: Command to generate the Wasm file. -- **`genesis_state_path?`** ++"string"++: Path to the state file to use. -- **`genesis_state_generator?`** ++"string"++: Command to generate the state file. -- **`chain_spec_path?`** ++"string"++: Path to the chain spec file. -- **`chain_spec_command?`** ++"string"++: Command to generate the chain spec. -- **`cumulus_based?`** ++"boolean"++: Flag to use cumulus command generation. Defaults to `true`. -- **`bootnodes?`** ++"string[]"++: Array of bootnodes to use. -- **`prometheus_prefix?`** ++"string"++: Parameter for customizing the metric's prefix for all parachain nodes/collators. Defaults to `substrate`. -- **`collator?`** ++"Collator"++: Further defined in the [Collator Configuration](#collator-configuration) section. -- **`collator_groups?`** ++"CollatorGroup[]"++: An array of collator groups to spawn. It is further defined in the [Collator Groups Configuration](#collator-groups-configuration) section. - -For example, the following configuration file defines a minimal example for the parachain: - -=== "TOML" - - ```toml title="parachain-example.toml" - [parachain] - id = 100 - add_to_genesis = true - cumulus_based = true - genesis_wasm_path = "INSERT_PATH_TO_WASM" - genesis_state_path = "INSERT_PATH_TO_STATE" - # ... - - ``` - -=== "JSON" - - ```json title="parachain-example.json" - { - "parachain": { - "id": 100, - "add_to_genesis": true, - "cumulus_based": true, - "genesis_wasm_path": "INSERT_PATH_TO_WASM", - "genesis_state_path": "INSERT_PATH_TO_STATE", - "...": {} - }, - "...": {} - } - - ``` - -#### Collator Configuration - -One specific key capable of receiving more subkeys is the `collator` key. This key defines further parameters for the nodes. The available keys are: - -- **`name`** ++"string"++: Name of the collator. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`). -- **`image?`** ++"string"++: Image to use for the collator. -- **`command_with_args?`** ++"string"++: Overrides both command and arguments for the collator. -- **`validator`** ++"boolean"++: Pass the `--validator` flag to the command. Defaults to `true`. -- **`invulnerable`** ++"boolean"++: If true, add the collator to invulnerables in the chain spec. Defaults to `false`. -- **`balance`** ++"number"++: Balance to set in balances for collator's account. Defaults to `2000000000000`. -- **`bootnodes?`** ++"string[]"++: Array of bootnodes to use. -- **`add_to_bootnodes?`** ++"boolean"++: Add this collator to the bootnode list. Defaults to `false`. -- **`ws_port?`** ++"number"++: WS port to use. -- **`rpc_port?`** ++"number"++: RPC port to use. -- **`prometheus_port?`** ++"number"++: Prometheus port to use. -- **`p2p_port?`** ++"number"++: P2P port to use. -- **`p2p_cert_hash?`** ++"string"++: Libp2p certhash to use with webRTC transport. -- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. - - ??? child "`DelayNetworkSettings` interface definition" - ```js - export interface DelayNetworkSettings { - latency: string; - correlation?: string; // should be parsable as float by k8s - jitter?: string; - } - ``` - -- **`command?`** ++"string"++: Override default command to run. -- **`args?`** ++"string[]"++: Arguments to be passed to the command. -- **`env?`** ++"envVars[]"++: Environment variables to set in the container. - - ??? child "`envVars` interface definition" - ```js - export interface EnvVars { - name: string; - value: string; - } - ``` - -- **`overrides?`** ++"Override[]"++: Array of overrides definitions. - - ??? child "`Override` interface definition" - ```js - export interface Override { - local_path: string; - remote_name: string; - } - ``` - -- **`prometheus_prefix?`** ++"string"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`. -- **`db_snapshot?`** ++"string"++: Database snapshot to use. -- **`substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead. - - ??? child "`SubstrateCliArgsVersion` enum definition" - ```js - export enum SubstrateCliArgsVersion { - V0 = 0, - V1 = 1, - V2 = 2, - V3 = 3, - } - ``` - -- **`resources?`** ++"Resources"++: Represent the resources limits/reservations needed by the node. - - ??? child "`Resources` interface definition" - ```js - export interface Resources { - resources: { - requests?: { - memory?: string; - cpu?: string; - }; - limits?: { - memory?: string; - cpu?: string; - }; - }; - } - ``` - -- **`keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. - -The configuration file below defines a minimal example for the collator: - -=== "TOML" - - ```toml title="collator-example.toml" - [parachain] - id = 100 - add_to_genesis = true - cumulus_based = true - genesis_wasm_path = "INSERT_PATH_TO_WASM" - genesis_state_path = "INSERT_PATH_TO_STATE" - - [[parachain.collators]] - name = "alice" - image = "polkadot-parachain" - command = "polkadot-parachain" - # ... - - ``` - -=== "JSON" - - ```json title="collator-example.json" - { - "parachain": { - "id": 100, - "add_to_genesis": true, - "cumulus_based": true, - "genesis_wasm_path": "INSERT_PATH_TO_WASM", - "genesis_state_path": "INSERT_PATH_TO_STATE", - "collators": [ - { - "name": "alice", - "image": "polkadot-parachain", - "command": "polkadot-parachain", - "...": {} - } - ] - }, - "...": {} - } - - ``` - -#### Collator Groups Configuration - -The `collator_groups` key defines further parameters for the collator groups. The available keys are: - -- **`name`** ++"string"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`). -- **`image?`** ++"string"++: Override default Docker image to use for this node. -- **`command?`** ++"string"++: Override default command to run. -- **`args?`** ++"string[]"++: Arguments to be passed to the command. -- **`env?`** ++"envVars[]"++: Environment variables to set in the container. - - ??? child "`envVars` interface definition" - ```js - export interface EnvVars { - name: string; - value: string; - } - ``` - -- **`overrides?`** ++"Override[]"++: Array of overrides definitions. - - ??? child "`Override` interface definition" - ```js - export interface Override { - local_path: string; - remote_name: string; - } - ``` - -- **`prometheus_prefix?`** ++"string"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`. -- **`db_snapshot?`** ++"string"++: Database snapshot to use. -- **`substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead. - - ??? child "`SubstrateCliArgsVersion` enum definition" - ```js - export enum SubstrateCliArgsVersion { - V0 = 0, - V1 = 1, - V2 = 2, - V3 = 3, - } - ``` - -- **`resources?`** ++"Resources"++: Represent the resources limits/reservations needed by the node. - - ??? child "`Resources` interface definition" - ```js - export interface Resources { - resources: { - requests?: { - memory?: string; - cpu?: string; - }; - limits?: { - memory?: string; - cpu?: string; - }; - }; - } - ``` - -- **`keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. -- **`count`** ++"number | string"++: Number of nodes to launch for this group. -- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. - - ??? child "`DelayNetworkSettings` interface definition" - ```js - export interface DelayNetworkSettings { - latency: string; - correlation?: string; // should be parsable as float by k8s - jitter?: string; - } - ``` - -For instance, the configuration file below defines a minimal example for the collator groups: - -=== "TOML" - - ```toml title="collator-groups-example.toml" - [parachain] - id = 100 - add_to_genesis = true - cumulus_based = true - genesis_wasm_path = "INSERT_PATH_TO_WASM" - genesis_state_path = "INSERT_PATH_TO_STATE" - - [[parachain.collator_groups]] - name = "group-1" - count = 2 - image = "polkadot-parachain" - command = "polkadot-parachain" - # ... - - ``` - -=== "JSON" - - ```json title="collator-groups-example.json" - { - "parachain": { - "id": 100, - "add_to_genesis": true, - "cumulus_based": true, - "genesis_wasm_path": "INSERT_PATH_TO_WASM", - "genesis_state_path": "INSERT_PATH_TO_STATE", - "collator_groups": [ - { - "name": "group-1", - "count": 2, - "image": "polkadot-parachain", - "command": "polkadot-parachain", - "...": {} - } - ] - }, - "...": {} - } - - ``` - -### XCM Configuration - -You can use the `hrmp_channels` keyword to define further parameters for the XCM channels at start-up. The available keys are: - -- **`hrmp_channels`** ++"HrmpChannelsConfig[]"++: Array of Horizontal Relay-routed Message Passing (HRMP) channel configurations. - - ??? child "`HrmpChannelsConfig` interface definition" - ```js - export interface HrmpChannelsConfig { - sender: number; - recipient: number; - max_capacity: number; - max_message_size: number; - } - ``` - Each of the `HrmpChannelsConfig` keys are defined as follows: - - - **`sender` ++"number"++**: Parachain ID of the sender. - - **`recipient` ++"number"++**: Parachain ID of the recipient. - - **`max_capacity` ++"number"++**: Maximum capacity of the HRMP channel. - - **`max_message_size` ++"number"++**: Maximum message size allowed in the HRMP channel. - -## Where to Go Next - -
- -- External __Zombienet Support__ - - --- - - [Parity Technologies](https://www.parity.io/){target=\_blank} has designed and developed this framework, now maintained by the Zombienet team. - - For further support and information, refer to the following contact points: - - [:octicons-arrow-right-24: Zombienet repository](https://github.com/paritytech/zombienet){target=\_blank} - - [:octicons-arrow-right-24: Element public channel](https://matrix.to/#/!FWyuEyNvIFygLnWNMh:parity.io?via=parity.io&via=matrix.org&via=web3.foundation){target=\_blank} - - -- Tutorial __Spawn a Basic Chain with Zombienet__ - - --- - - Learn to spawn, connect to and monitor a basic blockchain network with Zombienet, using customizable configurations for streamlined development and debugging. - - [:octicons-arrow-right-24: Reference](/tutorials/polkadot-sdk/testing/spawn-basic-chain/) - -
- - ---- - -Page Title: Get Started with Parachain Development - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-get-started.md -- Canonical (HTML): https://docs.polkadot.com/parachains/get-started/ -- Summary: Practical examples and tutorials for building and deploying Polkadot parachains, covering everything from launch to customization and cross-chain messaging. - -# Get Started - -The following sections provide practical recipes for building parachains on Polkadot—each focused on specific development scenarios with step-by-step, hands-on examples. - -## Quick Start Guides - -Quick start guides help developers set up and interact with the Polkadot parachain ecosystem using various tools and frameworks. - -| Tutorial | Tools | Description | -| :--------------------------------------------------------------------------------------------: | :----------------------------: | :---------------------------------------------------------------------: | -| [Set Up the Parachain Template](/parachains/launch-a-parachain/set-up-the-parachain-template/) | Polkadot SDK | Learn how to set up and run the Polkadot SDK Parachain Template locally | -| [Launch a Local Parachain](/parachains/testing/run-a-parachain-network/) | Zombienet, Chopsticks | Set up a local development environment for testing | -| [Connect to Polkadot](/chain-interactions/query-on-chain-data/query-sdks/) | Polkadot.js, Substrate Connect | Connect your application to Polkadot networks | -| [Fork an Existing Parachain](/parachains/testing/fork-a-parachain/) | Chopsticks | Create a local fork of a live parachain for testing | - -## Launch a Simple Parachain - -Learn the fundamentals of launching and deploying a parachain to the Polkadot network. - -| Tutorial | Description | -| :--------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------: | -| [Set Up the Parachain Template](/parachains/launch-a-parachain/set-up-the-parachain-template/) | Polkadot SDK | -| [Deploy to Polkadot](/parachains/launch-a-parachain/deploy-to-polkadot/) | Step-by-step tutorial to deploying your parachain to Polkadot | -| [Obtain Coretime](/parachains/launch-a-parachain/obtain-coretime/) | Learn how to acquire blockspace using Polkadot's coretime model (RegionX) | - -## Customize Your Runtime - -Build custom functionality for your parachain by composing and creating pallets. - -| Tutorial | Description | -| :-------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------: | -| [Add Existing Pallets to the Runtime](/parachains/customize-runtime/add-existing-pallets/) | Integrate pre-built pallets from the FRAME ecosystem | -| [Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/) | Configure and use multiple instances of the same pallet | -| [Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/) | Enable smart contract capabilities using Contracts or EVM pallets | - -### Pallet Development - -Deep dive into creating and managing custom pallets for your parachain. - -| Tutorial | Description | -| :--------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------: | -| [Create a Custom Pallet](/parachains/customize-runtime/pallet-development/create-a-pallet/) | Build a pallet from scratch with custom logic | -| [Mock Your Runtime](/parachains/customize-runtime/pallet-development/mock-runtime/) | Set up a mock runtime environment for testing | -| [Pallet Unit Testing](/parachains/customize-runtime/pallet-development/pallet-testing/) | Write comprehensive tests for your pallet logic | -| [Add Your Custom Pallet to the Runtime](/parachains/customize-runtime/pallet-development/add-pallet-to-runtime/) | Integrate your custom pallet into your parachain runtime | -| [Benchmark the Custom Pallet](/parachains/customize-runtime/pallet-development/benchmark-pallet/) | Measure and optimize pallet performance with benchmarking | - -## Testing - -Test your parachain in various environments before production deployment. - -| Tutorial | Description | -| :---------------------------------------------------------------------: | :-----------------------------------------------------: | -| [Fork a Parachain](/parachains/testing/fork-a-parachain/) | Use Chopsticks to create a local fork for testing | -| [Run a Parachain Network](/parachains/testing/run-a-parachain-network/) | Launch a complete parachain test network with Zombienet | - -## Runtime Upgrades and Maintenance - -Manage your parachain's lifecycle with forkless upgrades and maintenance operations. - -| Tutorial | Description | -| :-----------------------------------------------------------------------: | :--------------------------------------------------: | -| [Runtime Upgrades](/parachains/runtime-maintenance/runtime-upgrades/) | Perform forkless runtime upgrades via governance | -| [Storage Migrations](/parachains/runtime-maintenance/storage-migrations/) | Safely migrate storage when updating runtime logic | -| [Unlock Parachains](/parachains/runtime-maintenance/unlock-parachains/) | Understand parachain lifecycle and unlock mechanisms | - -## Interoperability - -Configure your parachain for cross-chain communication using XCM (Cross-Consensus Messaging). - -| Tutorial | Description | -| :--------------------------------------------------------------------------------------------------------: | :----------------------------------------------------: | -| [Open HRMP Channels Between Parachains](/parachains/interoperability/channels-between-parachains/) | Establish communication channels with other parachains | -| [Open HRMP Channels with System Parachains](/parachains/interoperability/channels-with-system-parachains/) | Connect with Asset Hub and other system parachains | - -## Integrations - -Integrate your parachain with essential ecosystem tools and services. - -| Tutorial | Description | -| :--------------------------------------------: | :----------------------------------------------------: | -| [Wallets](/parachains/integrations/wallets/) | Integrate wallet support for user interactions | -| [Indexers](/parachains/integrations/indexers/) | Set up indexing solutions for querying blockchain data | -| [Oracles](/parachains/integrations/oracles/) | Connect your parachain to off-chain data sources | - -## Additional Resources - -- [Polkadot SDK Documentation](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/index.html) -- [Polkadot Wiki - Parachains](https://wiki.polkadot.network/docs/learn-parachains/) - - ---- - -Page Title: Get Started with Smart Contracts - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-get-started.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/get-started/ -- Summary: Practical examples for building and deploying smart contracts on Polkadot Hub, from connecting and tooling to deployment, integrations, and precompiles. - -# Get Started - -This resource provides quick-starts for building smart contracts on Polkadot Hub. Use the tables below to jump directly to the tools and workflows you need. - -## Quick Starts - -Kick off development fast with curated links for connecting, funding, exploring, and deploying your first contract. - -| Quick Start | Tools | Description | -|:---------------------------------------------------------------------------------------------------:|:---------------------:|:---------------------------------------------------------------:| -| [Connect to Polkadot](/smart-contracts/connect/){target=\_blank} | Polkadot.js, MetaMask | Add the network, configure RPC, verify activity in the explorer | -| [Get Test Tokens](/smart-contracts/faucets/){target=\_blank} | - | Request test funds to deploy and interact with contracts | -| [Explore Transactions](/smart-contracts/explorers/){target=\_blank} | Subscan | Inspect transactions, logs, token transfers, and contract state | -| [Deploy with Remix](/smart-contracts/dev-environments/remix/deploy-a-contract/){target=\_blank} | Remix | One‑click browser deployment to Polkadot Hub | -| [Deploy with Foundry](/smart-contracts/dev-environments/foundry/deploy-a-contract/){target=\_blank} | Foundry | Scripted deployments and testing from the CLI | -| [Deploy with Hardhat](/smart-contracts/dev-environments/hardhat/deploy-a-contract/){target=\_blank} | Hardhat | Project scaffolding, testing, and deployments | - -## Build and Test Locally - -Set up local environments and CI-friendly workflows to iterate quickly and validate changes before deploying. - -| Build and Test Locally | Tools | Description | -|:------------------------------------------------------------------------------------------------------------:|:-----------------:|:----------------------------------------------------:| -| [Run a Local Dev Node](/smart-contracts/dev-environments/local-dev-node/){target=\_blank} | Polkadot SDK node | Spin up a local node for iterative development | -| [Remix: Get Started](/smart-contracts/dev-environments/remix/get-started/){target=\_blank} | Remix | Connect Remix to Polkadot Hub and configure accounts | -| [Remix: Verify a Contract](/smart-contracts/dev-environments/remix/verify-a-contract/){target=\_blank} | Remix | Publish verified source on explorers | -| [Foundry: Install and Config](/smart-contracts/dev-environments/foundry/install-and-config/){target=\_blank} | Foundry | Install toolchain and configure networks | -| [Foundry: Compile and Test](/smart-contracts/dev-environments/foundry/compile-and-test/){target=\_blank} | Foundry | Write and run Solidity tests locally | -| [Foundry: Verify a Contract](/smart-contracts/dev-environments/foundry/verify-a-contract/){target=\_blank} | Foundry | Verify deployed bytecode and metadata | -| [Hardhat: Install and Config](/smart-contracts/dev-environments/hardhat/install-and-config/){target=\_blank} | Hardhat | Initialize a project and configure networks | -| [Hardhat: Compile and Test](/smart-contracts/dev-environments/hardhat/compile-and-test/){target=\_blank} | Hardhat | Unit test contracts and run scripts | -| [Hardhat: Verify a Contract](/smart-contracts/dev-environments/hardhat/verify-a-contract/){target=\_blank} | Hardhat | Verify deployments on explorers | - -## Ethereum Developer Resources - -Bridge your Ethereum knowledge with Polkadot Hub specifics: account mapping, fees, JSON‑RPC, and deployment. - -| Ethereum Developer Guides | Description | -|:---------------------------------------------------------------------------------------------------------:|:---------------------------------------------------------------:| -| [Accounts](/smart-contracts/for-eth-devs/accounts/){target=\_blank} | How 20‑byte Ethereum addresses map to 32‑byte Polkadot accounts | -| [Blocks, Transactions, and Fees](/smart-contracts/for-eth-devs/blocks-transactions-fees/){target=\_blank} | Transaction types, fees, and multi‑dimensional metering | -| [Gas Model](/smart-contracts/for-eth-devs/gas-model/){target=\_blank} | Gas vs. weight, proof size, and storage deposits | -| [Contract Deployment](/smart-contracts/for-eth-devs/contract-deployment/){target=\_blank} | Deployment patterns and best practices on Polkadot Hub | -| [JSON‑RPC APIs](/smart-contracts/for-eth-devs/json-rpc-apis/){target=\_blank} | Supported Ethereum JSON‑RPC methods and examples | -| [Migration](/smart-contracts/for-eth-devs/migration/){target=\_blank} | Port existing apps and tooling to Polkadot Hub | -| [Dual VM Stack](/smart-contracts/for-eth-devs/dual-vm-stack/){target=\_blank} | Overview of EVM and native execution on the Hub | - -## Cookbook: Hands‑on Tutorials - -Follow step‑by‑step guides that walk through common tasks and complete dApp examples. - -| Tutorial | Tools | Description | -|:--------------------------------------------------------------------------------------------------------:|:-------------------:|:-----------------------------------------:| -| [Deploy a Basic Contract](/smart-contracts/cookbook/smart-contracts/deploy-basic/remix/){target=\_blank} | Remix | Minimal deployment walkthrough | -| [Deploy an ERC‑20](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/){target=\_blank} | Remix, OpenZeppelin | Create, deploy, and mint a fungible token | -| [Deploy an NFT (ERC‑721)](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/){target=\_blank} | Remix, OpenZeppelin | Build and deploy an NFT collection | -| [Uniswap V2](/smart-contracts/cookbook/eth-dapps/uniswap-v2/){target=\_blank} | Hardhat | Full dApp project: compile, test, deploy | -| [Zero‑to‑Hero dApp](/smart-contracts/cookbook/dapps/zero-to-hero/){target=\_blank} | Multiple | End‑to‑end dApp patterns and practices | - -## Libraries - -Choose the client libraries that fit your stack for connecting wallets and calling contracts. - -| Library | Description | -|:------------------------------------------------------------------:|:-------------------------------------------------------:| -| [Ethers.js](/smart-contracts/libraries/ethers-js/){target=\_blank} | Connect, sign, and interact with contracts using Ethers | -| [viem](/smart-contracts/libraries/viem/){target=\_blank} | Type‑safe EVM interactions and utilities | -| [Wagmi](/smart-contracts/libraries/wagmi/){target=\_blank} | React hooks for wallet connections and contract calls | -| [Web3.js](/smart-contracts/libraries/web3-js/){target=\_blank} | Web3 provider and contract APIs | -| [Web3.py](/smart-contracts/libraries/web3-py/){target=\_blank} | Python toolkit for on‑chain interactions and scripts | - -## Integrations - -Integrate essential services like wallets, indexers, and oracles to round out your dApp. - -| Integration | Description | -|:-------------------------------------------------------------------:|:-----------------------------------------:| -| [Wallets](/smart-contracts/integrations/wallets/){target=\_blank} | Supported wallets and configuration notes | -| [Indexers](/smart-contracts/integrations/indexers/){target=\_blank} | Index and query blockchain data | -| [Oracles](/smart-contracts/integrations/oracles/){target=\_blank} | Bring external data on‑chain | - -## Precompiles - -Discover precompiled system contracts available on the Hub and how to use them. - -| Topic | Description | -|:------------------------------------------------------------------------:|:---------------------------------------------------:| -| [Overview of Precompiles](/smart-contracts/precompiles/){target=\_blank} | What precompiles are available on the Hub | -| [ETH Native](/smart-contracts/precompiles/eth-native/){target=\_blank} | EVM precompiles and interfaces | -| [Staking](/smart-contracts/precompiles/staking/){target=\_blank} | Interact with staking functionality via precompiles | -| [XCM](/smart-contracts/precompiles/xcm/){target=\_blank} | Cross‑chain messaging helpers for contracts | - -From here, follow the quick starts to get connected, iterate locally with your preferred tools, and use the guides, libraries, integrations, and precompiles as you grow into production‑ready dApps. If you get stuck, [open an issue](https://github.com/polkadot-developers/polkadot-docs/issues/new?template=docs-issue.yml){target=\_blank} or reach out in the community channels. - - ---- - -Page Title: Glossary - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-glossary.md -- Canonical (HTML): https://docs.polkadot.com/reference/glossary/ -- Summary: Glossary of terms used within the Polkadot ecosystem, Polkadot SDK, its subsequent libraries, and other relevant Web3 terminology. - -# Glossary - -Key definitions, concepts, and terminology specific to the Polkadot ecosystem are included here. - -Additional glossaries from around the ecosystem you might find helpful: - -- [Polkadot Wiki Glossary](https://wiki.polkadot.com/general/glossary){target=\_blank} -- [Polkadot SDK Glossary](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/glossary/index.html){target=\_blank} - -## Authority - -The role in a blockchain that can participate in consensus mechanisms. - -- **[GRANDPA](#grandpa)**: The authorities vote on chains they consider final. -- **[Blind Assignment of Blockchain Extension](#blind-assignment-of-blockchain-extension-babe) (BABE)**: The authorities are also [block authors](#block-author). - -Authority sets can be used as a basis for consensus mechanisms such as the [Nominated Proof of Stake (NPoS)](#nominated-proof-of-stake-npos) protocol. - -## Authority Round (Aura) - -A deterministic [consensus](#consensus) protocol where block production is limited to a rotating list of [authorities](#authority) that take turns creating blocks. In authority round (Aura) consensus, most online authorities are assumed to be honest. It is often used in combination with [GRANDPA](#grandpa) as a [hybrid consensus](#hybrid-consensus) protocol. - -Learn more by reading the official [Aura consensus algorithm](https://openethereum.github.io/Aura){target=\_blank} wiki article. - -## Blind Assignment of Blockchain Extension (BABE) - -A [block authoring](#block-author) protocol similar to [Aura](#authority-round-aura), except [authorities](#authority) win [slots](#slot) based on a Verifiable Random Function (VRF) instead of the round-robin selection method. The winning authority can select a chain and submit a new block. - -Learn more by reading the official Web3 Foundation [BABE research document](https://research.web3.foundation/Polkadot/protocols/block-production/Babe){target=\_blank}. - -## Block Author - -The node responsible for the creation of a block, also called _block producers_. In a Proof of Work (PoW) blockchain, these nodes are called _miners_. - -## Byzantine Fault Tolerance (BFT) - -The ability of a distributed computer network to remain operational if a certain proportion of its nodes or [authorities](#authority) are defective or behaving maliciously. A distributed network is typically considered Byzantine fault tolerant if it can remain functional, with up to one-third of nodes assumed to be defective, offline, actively malicious, and part of a coordinated attack. - -### Byzantine Failure - -The loss of a network service due to node failures that exceed the proportion of nodes required to reach consensus. - -### Practical Byzantine Fault Tolerance (pBFT) - -An early approach to Byzantine fault tolerance (BFT), practical Byzantine fault tolerance (pBFT) systems tolerate Byzantine behavior from up to one-third of participants. - -The communication overhead for such systems is `O(n²)`, where `n` is the number of nodes (participants) in the system. - -### Preimage - -A preimage is the data that is input into a hash function to calculate a hash. Since a hash function is a [one-way function](https://en.wikipedia.org/wiki/One-way_function){target=\_blank}, the output, the hash, cannot be used to reveal the input, the preimage. - -## Call - -In the context of pallets containing functions to be dispatched to the runtime, `Call` is an enumeration data type that describes the functions that can be dispatched with one variant per pallet. A `Call` represents a [dispatch](#dispatchable) data structure object. - -## Chain Specification - -A chain specification file defines the properties required to run a node in an active or new Polkadot SDK-built network. It often contains the initial genesis runtime code, network properties (such as the network's name), the initial state for some pallets, and the boot node list. The chain specification file makes it easy to use a single Polkadot SDK codebase as the foundation for multiple independently configured chains. - -## Collator - -An [author](#block-author) of a [parachain](#parachain) network. -They aren't [authorities](#authority) in themselves, as they require a [relay chain](#relay-chain) to coordinate [consensus](#consensus). - -More details are found on the [Polkadot Collator Wiki](https://wiki.polkadot.com/learn/learn-collator/){target=\_blank}. - -## Collective - -Most often used to refer to an instance of the Collective pallet on Polkadot SDK-based networks such as [Kusama](#kusama) or [Polkadot](#polkadot) if the Collective pallet is part of the FRAME-based runtime for the network. - -## Consensus - -Consensus is the process blockchain nodes use to agree on a chain's canonical fork. It is composed of [authorship](#block-author), finality, and [fork-choice rule](#fork-choice-rulestrategy). In the Polkadot ecosystem, these three components are usually separate and the term consensus often refers specifically to authorship. - -See also [hybrid consensus](#hybrid-consensus). - -## Consensus Algorithm - -Ensures a set of [actors](#authority)—who don't necessarily trust each other—can reach an agreement about the state as the result of some computation. Most consensus algorithms assume that up to one-third of the actors or nodes can be [Byzantine fault tolerant](#byzantine-fault-tolerance-bft). - -Consensus algorithms are generally concerned with ensuring two properties: - -- **Safety**: Indicating that all honest nodes eventually agreed on the state of the chain. -- **Liveness**: Indicating the ability of the chain to keep progressing. - -## Consensus Engine - -The node subsystem responsible for consensus tasks. - -For detailed information about the consensus strategies of the [Polkadot](#polkadot) network, see the [Polkadot Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} blog series. - -See also [hybrid consensus](#hybrid-consensus). - -## Coretime - -The time allocated for utilizing a core, measured in relay chain blocks. There are two types of coretime: *on-demand* and *bulk*. - -On-demand coretime refers to coretime acquired through bidding in near real-time for the validation of a single parachain block on one of the cores reserved specifically for on-demand orders. They are available as an on-demand coretime pool. Set of cores that are available on-demand. Cores reserved through bulk coretime could also be made available in the on-demand coretime pool, in parts or in entirety. - -Bulk coretime is a fixed duration of continuous coretime represented by an NFT that can be split, shared, or resold. It is managed by the [Broker pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_broker/index.html){target=\_blank}. - -## Development Phrase - -A [mnemonic phrase](https://en.wikipedia.org/wiki/Mnemonic#For_numerical_sequences_and_mathematical_operations){target=\_blank} that is intentionally made public. - -Well-known development accounts, such as Alice, Bob, Charlie, Dave, Eve, and Ferdie, are generated from the same secret phrase: - -``` -bottom drive obey lake curtain smoke basket hold race lonely fit walk -``` - -Many tools in the Polkadot SDK ecosystem, such as [`subkey`](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/bin/utils/subkey){target=\_blank}, allow you to implicitly specify an account using a derivation path such as `//Alice`. - -## Digest - -An extensible field of the [block header](#header) that encodes information needed by several actors in a blockchain network, including: - -- [Light clients](#light-client) for chain synchronization. -- Consensus engines for block verification. -- The runtime itself, in the case of pre-runtime digests. - -## Dispatchable - -Function objects that act as the entry points in FRAME [pallets](#pallet). Internal or external entities can call them to interact with the blockchain’s state. They are a core aspect of the runtime logic, handling [transactions](#transaction) and other state-changing operations. - -## Events - -A means of recording that some particular [state](#state) transition happened. - -In the context of [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities), events are composable data types that each [pallet](#pallet) can individually define. Events in FRAME are implemented as a set of transient storage items inspected immediately after a block has been executed and reset during block initialization. - -## Executor - -A means of executing a function call in a given [runtime](#runtime) with a set of dependencies. -There are two orchestration engines in Polkadot SDK, _WebAssembly_ and _native_. - -- The _native executor_ uses a natively compiled runtime embedded in the node to execute calls. This is a performance optimization available to up-to-date nodes. - -- The _WebAssembly executor_ uses a [Wasm](#webassembly-wasm) binary and a Wasm interpreter to execute calls. The binary is guaranteed to be up-to-date regardless of the version of the blockchain node because it is persisted in the [state](#state) of the Polkadot SDK-based chain. - -## Existential Deposit - -The minimum balance an account is allowed to have in the [Balances pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/index.html){target=\_blank}. Accounts cannot be created with a balance less than the existential deposit amount. - -If an account balance drops below this amount, the Balances pallet uses [a FRAME System API](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.dec_ref){target=\_blank} to drop its references to that account. - -If the Balances pallet reference to an account is dropped, the account can be [reaped](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.allow_death){target=\_blank}. - -## Extrinsic - -A general term for data that originates outside the runtime, is included in a block, and leads to some action. This includes user-initiated transactions and inherent transactions placed into the block by the block builder. - -It is a SCALE-encoded array typically consisting of a version number, signature, and varying data types indicating the resulting runtime function to be called. Extrinsics can take two forms: [inherents](#inherent-transactions) and [transactions](#transaction). - -For more technical details, see the [Polkadot spec](https://spec.polkadot.network/id-extrinsics){target=\_blank}. - -## Fork Choice Rule/Strategy - -A fork choice rule or strategy helps determine which chain is valid when reconciling several network forks. A common fork choice rule is the [longest chain](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/struct.LongestChain.html){target=\_blank}, in which the chain with the most blocks is selected. - -## FRAME (Framework for Runtime Aggregation of Modularized Entities) - -Enables developers to create blockchain [runtime](#runtime) environments from a modular set of components called [pallets](#pallet). It utilizes a set of procedural macros to construct runtimes. - -[Visit the Polkadot SDK docs for more details on FRAME.](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank} - -## Full Node - -A node that prunes historical states, keeping only recently finalized block states to reduce storage needs. Full nodes provide current chain state access and allow direct submission and validation of [extrinsics](#extrinsic), maintaining network decentralization. - -## Genesis Configuration - -A mechanism for specifying the initial state of a blockchain. By convention, this initial state or first block is commonly referred to as the genesis state or genesis block. The genesis configuration for Polkadot SDK-based chains is accomplished by way of a [chain specification](#chain-specification) file. - -## GRANDPA - -A deterministic finality mechanism for blockchains that is implemented in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. - -The [formal specification](https://github.com/w3f/consensus/blob/master/pdf/grandpa-old.pdf){target=\_blank} is maintained by the [Web3 Foundation](https://web3.foundation/){target=\_blank}. - -## Header - -A structure that aggregates the information used to summarize a block. Primarily, it consists of cryptographic information used by [light clients](#light-client) to get minimally secure but very efficient chain synchronization. - -## Hybrid Consensus - -A blockchain consensus protocol that consists of independent or loosely coupled mechanisms for [block production](#block-author) and finality. - -Hybrid consensus allows the chain to grow as fast as probabilistic consensus protocols, such as [Aura](#authority-round-aura), while maintaining the same level of security as deterministic finality consensus protocols, such as [GRANDPA](#grandpa). - -## Inherent Transactions - -A special type of unsigned transaction, referred to as _inherents_, that enables a block authoring node to insert information that doesn't require validation directly into a block. - -Only the block-authoring node that calls the inherent transaction function can insert data into its block. In general, validators assume the data inserted using an inherent transaction is valid and reasonable even if it can't be deterministically verified. - -## JSON-RPC - -A stateless, lightweight remote procedure call protocol encoded in JavaScript Object Notation (JSON). JSON-RPC provides a standard way to call functions on a remote system by using JSON. - -For Polkadot SDK, this protocol is implemented through the [Parity JSON-RPC](https://github.com/paritytech/jsonrpc){target=\_blank} crate. - -## Keystore - -A subsystem for managing keys for the purpose of producing new blocks. - -## Kusama - -[Kusama](https://kusama.network/){target=\_blank} is a Polkadot SDK-based blockchain that implements a design similar to the [Polkadot](#polkadot) network. - -Kusama is a [canary](https://en.wiktionary.org/wiki/canary_in_a_coal_mine){target=\_blank} network and is referred to as [Polkadot's "wild cousin."](https://wiki.polkadot.com/learn/learn-comparisons-kusama/){target=\_blank}. - -As a canary network, Kusama is expected to be more stable than a test network like [Westend](#westend) but less stable than a production network like [Polkadot](#polkadot). Kusama is controlled by its network participants and is intended to be stable enough to encourage meaningful experimentation. - -## libp2p - -A peer-to-peer networking stack that allows the use of many transport mechanisms, including WebSockets (usable in a web browser). - -Polkadot SDK uses the [Rust implementation](https://github.com/libp2p/rust-libp2p){target=\_blank} of the `libp2p` networking stack. - -## Light Client - -A type of blockchain node that doesn't store the [chain state](#state) or produce blocks. - -A light client can verify cryptographic primitives and provides a [remote procedure call (RPC)](https://en.wikipedia.org/wiki/Remote_procedure_call){target=\_blank} server, enabling blockchain users to interact with the network. - -## Metadata - -Data that provides information about one or more aspects of a system. -The metadata that exposes information about a Polkadot SDK blockchain enables you to interact with that system. - -## Nominated Proof of Stake (NPoS) - -A method for determining [validators](#validator) or _[authorities](#authority)_ based on a willingness to commit their stake to the proper functioning of one or more block-producing nodes. - -## Oracle - -An entity that connects a blockchain to a non-blockchain data source. Oracles enable the blockchain to access and act upon information from existing data sources and incorporate data from non-blockchain systems and services. - -## Origin - -A [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitive that identifies the source of a [dispatched](#dispatchable) function call into the [runtime](#runtime). The FRAME System pallet defines three built-in [origins](#origin). As a [pallet](#pallet) developer, you can also define custom origins, such as those defined by the [Collective pallet](https://paritytech.github.io/substrate/master/pallet_collective/enum.RawOrigin.html){target=\_blank}. - -## Pallet - -A module that can be used to extend the capabilities of a [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities)-based [runtime](#runtime). -Pallets bundle domain-specific logic with runtime primitives like [events](#events) and [storage items](#storage-item). - -## Parachain - -A parachain is a blockchain that derives shared infrastructure and security from a _[relay chain](#relay-chain)_. -You can learn more about parachains on the [Polkadot Wiki](https://wiki.polkadot.com/learn/learn-parachains/){target=\_blank}. - -## Paseo - -Paseo TestNet provisions testing on Polkadot's "production" runtime, which means less chance of feature or code mismatch when developing parachain apps. Specifically, after the [Polkadot Technical fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} proposes a runtime upgrade for Polkadot, this TestNet is updated, giving a period where the TestNet will be ahead of Polkadot to allow for testing. - -## Polkadot - -The [Polkadot network](https://polkadot.com/){target=\_blank} is a blockchain that serves as the central hub of a heterogeneous blockchain network. It serves the role of the [relay chain](#relay-chain) and provides shared infrastructure and security to support [parachains](#parachain). - -## Polkadot Cloud - -Polkadot Cloud is a platform for deploying resilient, customizable and scalable Web3 applications through Polkadot's functionality. It encompasses the wider Polkadot network infrastructure and security layer where parachains operate. The platform enables users to launch Ethereum-compatible chains, build specialized blockchains, and flexibly manage computing resources through on-demand or bulk coretime purchases. Initially launched with basic parachain functionality, Polkadot Cloud has evolved to offer enhanced flexibility with features like coretime, elastic scaling, and async backing for improved performance. - -## Polkadot Hub - -Polkadot Hub is a Layer 1 platform that serves as the primary entry point to the Polkadot ecosystem, providing essential functionality without requiring parachain deployment. It offers core services including smart contracts, identity management, staking, governance, and interoperability with other ecosystems, making it simple and fast for both builders and users to get started in Web3. - -## PolkaVM - -PolkaVM is a custom virtual machine optimized for performance, leveraging a RISC-V-based architecture to support Solidity and any language that compiles to RISC-V. It is specifically designed for the Polkadot ecosystem, enabling smart contract deployment and execution. - -## Relay Chain - -Relay chains are blockchains that provide shared infrastructure and security to the [parachains](#parachain) in the network. In addition to providing [consensus](#consensus) capabilities, relay chains allow parachains to communicate and exchange digital assets without needing to trust one another. - -## Rococo - -A [parachain](#parachain) test network for the Polkadot network. The [Rococo](#rococo) network is a Polkadot SDK-based blockchain with an October 14, 2024 deprecation date. Development teams are encouraged to use the Paseo TestNet instead. - -## Runtime - -The runtime represents the [state transition function](#state-transition-function-stf) for a blockchain. In Polkadot SDK, the runtime is stored as a [Wasm](#webassembly-wasm) binary in the chain state. The Runtime is stored under a unique state key and can be modified during the execution of the state transition function. - -## Slot - -A fixed, equal interval of time used by consensus engines such as [Aura](#authority-round-aura) and [BABE](#blind-assignment-of-blockchain-extension-babe). In each slot, a subset of [authorities](#authority) is permitted, or obliged, to [author](#block-author) a block. - -## Sovereign Account - -The unique account identifier for each chain in the relay chain ecosystem. It is often used in cross-consensus (XCM) interactions to sign XCM messages sent to the relay chain or other chains in the ecosystem. - -The sovereign account for each chain is a root-level account that can only be accessed using the Sudo pallet or through governance. The account identifier is calculated by concatenating the Blake2 hash of a specific text string and the registered parachain identifier. - -## SS58 Address Format - -A public key address based on the Bitcoin [`Base-58-check`](https://en.bitcoin.it/wiki/Base58Check_encoding){target=\_blank} encoding. Each Polkadot SDK SS58 address uses a `base-58` encoded value to identify a specific account on a specific Polkadot SDK-based chain - -The [canonical `ss58-registry`](https://github.com/paritytech/ss58-registry){target=\_blank} provides additional details about the address format used by different Polkadot SDK-based chains, including the network prefix and website used for different networks - -## State Transition Function (STF) - -The logic of a blockchain that determines how the state changes when a block is processed. In Polkadot SDK, the state transition function is effectively equivalent to the [runtime](#runtime). - -## Storage Item - -[FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitives that provide type-safe data persistence capabilities to the [runtime](#runtime). -Learn more in the [storage items](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/index.html){target=\_blank} reference document in the Polkadot SDK. - -## Substrate - -A flexible framework for building modular, efficient, and upgradeable blockchains. Substrate is written in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language and is maintained by [Parity Technologies](https://www.parity.io/){target=\_blank}. - -## Transaction - -An [extrinsic](#extrinsic) that includes a signature that can be used to verify the account authorizing it inherently or via [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}. - -## Transaction Era - -A definable period expressed as a range of block numbers during which a transaction can be included in a block. -Transaction eras are used to protect against transaction replay attacks if an account is reaped and its replay-protecting nonce is reset to zero. - -## Trie (Patricia Merkle Tree) - -A data structure used to represent sets of key-value pairs and enables the items in the data set to be stored and retrieved using a cryptographic hash. Because incremental changes to the data set result in a new hash, retrieving data is efficient even if the data set is very large. With this data structure, you can also prove whether the data set includes any particular key-value pair without access to the entire data set. - -In Polkadot SDK-based blockchains, state is stored in a trie data structure that supports the efficient creation of incremental digests. This trie is exposed to the [runtime](#runtime) as [a simple key/value map](#storage-item) where both keys and values can be arbitrary byte arrays. - -## Validator - -A validator is a node that participates in the consensus mechanism of the network. Its roles include block production, transaction validation, network integrity, and security maintenance. - -## WebAssembly (Wasm) - -An execution architecture that allows for the efficient, platform-neutral expression of -deterministic, machine-executable logic. - -[Wasm](https://webassembly.org/){target=\_blank} can be compiled from many languages, including -the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. Polkadot SDK-based chains use a Wasm binary to provide portable [runtimes](#runtime) that can be included as part of the chain's state. - -## Weight - -A convention used in Polkadot SDK-based blockchains to measure and manage the time it takes to validate a block. -Polkadot SDK defines one unit of weight as one picosecond of execution time on reference hardware. - -The maximum block weight should be equivalent to one-third of the target block time with an allocation of one-third each for: - -- Block construction -- Network propagation -- Import and verification - -By defining weights, you can trade-off the number of transactions per second and the hardware required to maintain the target block time appropriate for your use case. Weights are defined in the runtime, meaning you can tune them using runtime updates to keep up with hardware and software improvements. - -## Westend - -Westend is a Parity-maintained, Polkadot SDK-based blockchain that serves as a test network for the [Polkadot](#polkadot) network. - - ---- - -Page Title: Indexers - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-indexers.md -- Canonical (HTML): https://docs.polkadot.com/parachains/integrations/indexers/ -- Summary: Discover blockchain indexers. Enhance data access, enable fast and complex queries, and optimize blockchain data for seamless app performance. - -# Indexers - -## The Challenge of Blockchain Data Access - -Blockchain data is inherently sequential and distributed, with information stored chronologically across numerous blocks. While retrieving data from a single block through JSON-RPC API calls is straightforward, more complex queries that span multiple blocks present significant challenges: - -- Data is scattered and unorganized across the blockchain. -- Retrieving large datasets can take days or weeks to sync. -- Complex operations (like aggregations, averages, or cross-chain queries) require additional processing. -- Direct blockchain queries can impact dApp performance and responsiveness. - -## What is a Blockchain Indexer? - -A blockchain indexer is a specialized infrastructure tool that processes, organizes, and stores blockchain data in an optimized format for efficient querying. Think of it as a search engine for blockchain data that: - -- Continuously monitors the blockchain for new blocks and transactions. -- Processes and categorizes this data according to predefined schemas. -- Stores the processed data in an easily queryable database. -- Provides efficient APIs (typically [GraphQL](https://graphql.org/){target=\_blank}) for data retrieval. - -## Indexer Implementations - -
- -- __Subsquid__ - - --- - - Subsquid is a data network that allows rapid and cost-efficient retrieval of blockchain data from 100+ chains using Subsquid's decentralized data lake and open-source SDK. In simple terms, Subsquid can be considered an ETL (extract, transform, and load) tool with a GraphQL server included. It enables comprehensive filtering, pagination, and even full-text search capabilities. Subsquid has native and full support for EVM and Substrate data, even within the same project. - - [:octicons-arrow-right-24: Reference](https://www.sqd.ai/){target=\_blank} - -- __Subquery__ - - --- - - SubQuery is a fast, flexible, and reliable open-source data decentralised infrastructure network that provides both RPC and indexed data to consumers worldwide. - It provides custom APIs for your web3 project across multiple supported chains. - - [:octicons-arrow-right-24: Reference](https://subquery.network/){target=\_blank} - -
- - ---- - -Page Title: Install Polkadot SDK - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-install-polkadot-sdk.md -- Canonical (HTML): https://docs.polkadot.com/parachains/install-polkadot-sdk/ -- Summary: Install all required Polkadot SDK dependencies, set up the SDK itself, and verify that it runs correctly on your machine. - -# Install Polkadot SDK - -This guide provides step-by-step instructions for installing the Polkadot SDK on macOS, Linux, and Windows. The installation process consists of two main parts: - -- **Installing dependencies**: Setting up Rust, required system packages, and development tools. -- **Building the Polkadot SDK**: Cloning and compiling the Polkadot SDK repository. - -Follow the appropriate section for your operating system to ensure all necessary tools are installed and configured properly. - -## Install Dependencies: macOS - -You can install Rust and set up a Substrate development environment on Apple macOS computers with Intel or Apple M1 processors. - -### Before You Begin {: #before-you-begin-mac-os } - -Before you install Rust and set up your development environment on macOS, verify that your computer meets the following basic requirements: - -- Operating system version is 10.7 Lion or later. -- Processor speed of at least 2 GHz. Note that 3 GHz is recommended. -- Memory of at least 8 GB RAM. Note that 16 GB is recommended. -- Storage of at least 10 GB of available space. -- Broadband Internet connection. - -### Install Homebrew - -In most cases, you should use Homebrew to install and manage packages on macOS computers. If you don't already have Homebrew installed on your local computer, you should download and install it before continuing. - -To install Homebrew: - -1. Open the Terminal application. -2. Download and install Homebrew by running the following command: - - ```bash - /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" - ``` - -3. Verify Homebrew has been successfully installed by running the following command: - - ```bash - brew --version - ``` - - The command displays output similar to the following: - -
- brew --version - Homebrew 4.3.15 -
- -### Support for Apple Silicon - -Protobuf must be installed before the build process can begin. To install it, run the following command: - -```bash -brew install protobuf -``` - -### Install Required Packages and Rust {: #install-required-packages-and-rust-mac-os } - -Because the blockchain requires standard cryptography to support the generation of public/private key pairs and the validation of transaction signatures, you must also have a package that provides cryptography, such as `openssl`. - -To install `openssl` and the Rust toolchain on macOS: - -1. Open the Terminal application. -2. Ensure you have an updated version of Homebrew by running the following command: - - ```bash - brew update - ``` - -3. Install the `openssl` package by running the following command: - - ```bash - brew install openssl - ``` - -4. Download the `rustup` installation program and use it to install Rust by running the following command: - - ```bash - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh - ``` - -5. Follow the prompts displayed to proceed with a default installation. -6. Update your current shell to include Cargo by running the following command: - - ```bash - source ~/.cargo/env - ``` - -7. Configure the Rust toolchain to default to the latest stable version by running the following commands: - - ```bash - rustup default stable - rustup update - rustup target add wasm32-unknown-unknown - rustup component add rust-src - ``` - -8. Install `cmake` using the following command: - - ```bash - brew install cmake - ``` - -9. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). - -## Install Dependencies: Linux - -Rust supports most Linux distributions. Depending on the specific distribution and version of the operating system you use, you might need to add some software dependencies to your environment. In general, your development environment should include a linker or a C-compatible compiler, such as `clang`, and an appropriate integrated development environment (IDE). - -### Before You Begin {: #before-you-begin-linux } - -Check the documentation for your operating system for information about the installed packages and how to download and install any additional packages you might need. For example, if you use Ubuntu, you can use the Ubuntu Advanced Packaging Tool (`apt`) to install the `build-essential` package: - -```bash -sudo apt install build-essential -``` - -At a minimum, you need the following packages before you install Rust: - -```text -clang curl git make -``` - -Because the blockchain requires standard cryptography to support the generation of public/private key pairs and the validation of transaction signatures, you must also have a package that provides cryptography, such as `libssl-dev` or `openssl-devel`. - -### Install Required Packages and Rust {: #install-required-packages-and-rust-linux } - -To install the Rust toolchain on Linux: - -1. Open a terminal shell. -2. Check the packages installed on the local computer by running the appropriate package management command for your Linux distribution. -3. Add any package dependencies you are missing to your local development environment by running the appropriate package management command for your Linux distribution: - - === "Ubuntu" - - ```bash - sudo apt install --assume-yes git clang curl libssl-dev protobuf-compiler - ``` - - === "Debian" - - ```sh - sudo apt install --assume-yes git clang curl libssl-dev llvm libudev-dev make protobuf-compiler - ``` - - === "Arch" - - ```sh - pacman -Syu --needed --noconfirm curl git clang make protobuf - ``` - - === "Fedora" - - ```sh - sudo dnf update - sudo dnf install clang curl git openssl-devel make protobuf-compiler - ``` - - === "OpenSUSE" - - ```sh - sudo zypper install clang curl git openssl-devel llvm-devel libudev-devel make protobuf - ``` - - Remember that different distributions might use different package managers and bundle packages in different ways. For example, depending on your installation selections, Ubuntu Desktop and Ubuntu Server might have different packages and different requirements. However, the packages listed in the command-line examples are applicable to many common Linux distributions, including Debian, Linux Mint, MX Linux, and Elementary OS. - -4. Download the `rustup` installation program and use it to install Rust by running the following command: - - ```bash - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh - ``` - -5. Follow the prompts displayed to proceed with a default installation. -6. Update your current shell to include Cargo by running the following command: - - ```bash - source $HOME/.cargo/env - ``` - -7. Verify your installation by running the following command: - - ```bash - rustc --version - ``` - -8. Configure the Rust toolchain to default to the latest stable version by running the following commands: - - ```bash - rustup default stable - rustup update - rustup target add wasm32-unknown-unknown - rustup component add rust-src - ``` - -9. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). - -## Install Dependencies: Windows (WSL) - -In general, UNIX-based operating systems—like macOS or Linux—provide a better development environment for building Substrate-based blockchains. - -However, suppose your local computer uses Microsoft Windows instead of a UNIX-based operating system. In that case, you can configure it with additional software to make it a suitable development environment for building Substrate-based blockchains. To prepare a development environment on a Microsoft Windows computer, you can use Windows Subsystem for Linux (WSL) to emulate a UNIX operating environment. - -### Before You Begin {: #before-you-begin-windows-wls } - -Before installing on Microsoft Windows, verify the following basic requirements: - -- You have a computer running a supported Microsoft Windows operating system: - - **For Windows desktop**: You must be running Microsoft Windows 10, version 2004 or later, or Microsoft Windows 11 to install WSL. - - **For Windows server**: You must be running Microsoft Windows Server 2019, or later, to install WSL on a server operating system. -- You have a good internet connection and access to a shell terminal on your local computer. - -### Set Up Windows Subsystem for Linux - -WSL enables you to emulate a Linux environment on a computer that uses the Windows operating system. The primary advantage of this approach for Substrate development is that you can use all of the code and command-line examples as described in the Substrate documentation. For example, you can run common commands—such as `ls` and `ps`—unmodified. By using WSL, you can avoid configuring a virtual machine image or a dual-boot operating system. - -To prepare a development environment using WSL: - -1. Check your Windows version and build number to see if WSL is enabled by default. - - If you have Microsoft Windows 10, version 2004 (Build 19041 and higher), or Microsoft Windows 11, WSL is available by default and you can continue to the next step. - - If you have an older version of Microsoft Windows installed, see the [WSL manual installation steps for older versions](https://learn.microsoft.com/en-us/windows/wsl/install-manual){target=\_blank}. If you are installing on an older version of Microsoft Windows, you can download and install WLS 2 if your computer has Windows 10, version 1903 or higher. - -2. Select **Windows PowerShell** or **Command Prompt** from the **Start** menu, right-click, then **Run as administrator**. - -3. In the PowerShell or Command Prompt terminal, run the following command: - - ```bash - wsl --install - ``` - - This command enables the required WSL 2 components that are part of the Windows operating system, downloads the latest Linux kernel, and installs the Ubuntu Linux distribution by default. - - If you want to review the other Linux distributions available, run the following command: - - ```bash - wsl --list --online - ``` - -4. After the distribution is downloaded, close the terminal. - -5. Click the **Start** menu, select **Shut down or sign out**, then click **Restart** to restart the computer. - - Restarting the computer is required to start the installation of the Linux distribution. It can take a few minutes for the installation to complete after you restart. - - For more information about setting up WSL as a development environment, see the [Set up a WSL development environment](https://learn.microsoft.com/en-us/windows/wsl/setup/environment){target=\_blank} docs. - -### Install Required Packages and Rust {: #install-required-packages-and-rust-windows-wls } - -To install the Rust toolchain on WSL: - -1. Click the **Start** menu, then select **Ubuntu**. -2. Type a UNIX user name to create a user account. -3. Type a password for your UNIX user, then retype the password to confirm it. -4. Download the latest updates for the Ubuntu distribution using the Ubuntu Advanced Packaging Tool (`apt`) by running the following command: - - ```bash - sudo apt update - ``` - -5. Add the required packages for the Ubuntu distribution by running the following command: - - ```bash - sudo apt install --assume-yes git clang curl libssl-dev llvm libudev-dev make protobuf-compiler - ``` - -6. Download the `rustup` installation program and use it to install Rust for the Ubuntu distribution by running the following command: - - ```bash - curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh - ``` - -7. Follow the prompts displayed to proceed with a default installation. - -8. Update your current shell to include Cargo by running the following command: - - ```bash - source ~/.cargo/env - ``` - -9. Verify your installation by running the following command: - - ```bash - rustc --version - ``` - -10. Configure the Rust toolchain to use the latest stable version as the default toolchain by running the following commands: - - ```bash - rustup default stable - rustup update - rustup target add wasm32-unknown-unknown - rustup component add rust-src - ``` - -11. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). - -## Build the Polkadot SDK - -After installing all dependencies, you can now clone and compile the Polkadot SDK repository to verify your setup. - -### Clone the Polkadot SDK - -1. Clone the Polkadot SDK repository: - - ```bash - git clone https://github.com/paritytech/polkadot-sdk.git - ``` - -2. Navigate into the project directory: - - ```bash - cd polkadot-sdk - ``` - -### Compile the Polkadot SDK - -Compile the entire Polkadot SDK repository to ensure your environment is properly configured: - -```bash -cargo build --release --locked -``` - -!!!note - This initial compilation will take significant time, depending on your machine specifications. It compiles all components of the Polkadot SDK to verify your toolchain is correctly configured. - -### Verify the Build - -Once the build completes successfully, verify the installation by checking the compiled binaries: - -```bash -ls target/release -``` - -You should see several binaries, including: - -- `polkadot`: The Polkadot relay chain node. -- `polkadot-parachain`: The parachain collator node. -- `polkadot-omni-node`:The omni node for running parachains. -- `substrate-node`: The kitchensink node with many pre-configured pallets. - -Verify the Polkadot binary works by checking its version: - -```bash -./target/release/polkadot --version -``` - -This should display version information similar to: - -```bash -polkadot 1.16.0-1234abcd567 -``` - -If you see the version output without errors, your development environment is correctly configured and ready for Polkadot SDK development! - -## Optional: Run the Kitchensink Node - -The Polkadot SDK includes a feature-rich node called "kitchensink" located at `substrate/bin/node`. This node comes pre-configured with many pallets and features from the Polkadot SDK, making it an excellent reference for exploring capabilities and understanding how different components work together. - -!!!note - If you've already compiled the Polkadot SDK in the previous step, the `substrate-node` binary is already built and ready to use. You can skip directly to running the node. - -### Run the Kitchensink Node in Development Mode - -From the `polkadot-sdk` root directory, start the kitchensink node in development mode: - -```bash -./target/release/substrate-node --dev -``` - -The `--dev` flag enables development mode, which: - -- Runs a single-node development chain. -- Produces and finalizes blocks automatically. -- Uses pre-configured development accounts (Alice, Bob, etc.). -- Deletes all data when stopped, ensuring a clean state on restart. - - -You should see log output indicating the node is running and producing blocks, with increasing block numbers after `finalized`. - -### Interact with the Kitchensink Node - -The kitchensink node is accessible at `ws://localhost:9944`. Open [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} in your browser to explore its features and connect to the local node. - -1. Click the network icon in the top left corner. -2. Scroll to **Development** and select **Local Node**. -3. Click **Switch** to connect to your local node. - -![](/images/parachains/install-polkadot-sdk/install-polkadot-sdk-1.webp) - -Once connected, the interface updates its color scheme to indicate a successful connection to the local node. - -![](/images/parachains/install-polkadot-sdk/install-polkadot-sdk-2.webp) - -You can now explore the various pallets and features included in the kitchensink node, making it a valuable reference as you develop your own blockchain applications. - -To stop the node, press `Control-C` in the terminal. - -## Where to Go Next - -
- -- __Get Started with Parachain Development__ - - --- - - Practical examples and tutorials for building and deploying Polkadot parachains, covering everything from launch to customization and cross-chain messaging. - - [:octicons-arrow-right-24: Get Started](/parachains/get-started/) - -
- - ---- - -Page Title: Interoperability - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-interoperability.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/interoperability/ -- Summary: Explore the importance of interoperability in the Polkadot ecosystem, covering XCM, bridges, and cross-chain communication. - -# Interoperability - -## Introduction - -Interoperability lies at the heart of the Polkadot ecosystem, enabling communication and collaboration across a diverse range of blockchains. By bridging the gaps between parachains, relay chains, and even external networks, Polkadot unlocks the potential for truly decentralized applications, efficient resource sharing, and scalable solutions. - -Polkadot’s design ensures that blockchains can transcend their individual limitations by working together as part of a unified system. This cooperative architecture is what sets Polkadot apart in the blockchain landscape. - -## Why Interoperability Matters - -The blockchain ecosystem is inherently fragmented. Different blockchains excel in specialized domains such as finance, gaming, or supply chain management, but these chains function in isolation without interoperability. This lack of connectivity stifles the broader utility of blockchain technology. - -Interoperability solves this problem by enabling blockchains to: - -- **Collaborate across networks**: Chains can interact to share assets, functionality, and data, creating synergies that amplify their individual strengths. -- **Achieve greater scalability**: Specialized chains can offload tasks to others, optimizing performance and resource utilization. -- **Expand use-case potential**: Cross-chain applications can leverage features from multiple blockchains, unlocking novel user experiences and solutions. - -In the Polkadot ecosystem, interoperability transforms a collection of isolated chains into a cohesive, efficient network, pushing the boundaries of what blockchains can achieve together. - -## Key Mechanisms for Interoperability - -At the core of Polkadot's cross-chain collaboration are foundational technologies designed to break down barriers between networks. These mechanisms empower blockchains to communicate, share resources, and operate as a cohesive ecosystem. - -### Cross-Consensus Messaging (XCM): The Backbone of Communication - -Polkadot's Cross-Consensus Messaging (XCM) is the standard framework for interaction between parachains, relay chains, and, eventually, external blockchains. XCM provides a trustless, secure messaging format for exchanging assets, sharing data, and executing cross-chain operations. - -Through XCM, decentralized applications can: - -- Transfer tokens and other assets across chains. -- Coordinate complex workflows that span multiple blockchains. -- Enable seamless user experiences where underlying blockchain differences are invisible. -- XCM exemplifies Polkadot’s commitment to creating a robust and interoperable ecosystem. - -For further information about XCM, check the [Introduction to XCM](/parachains/interoperability/get-started/){target=\_blank} article. - -### Bridges: Connecting External Networks - -While XCM enables interoperability within the Polkadot ecosystem, bridges extend this functionality to external blockchains such as Ethereum and Bitcoin. By connecting these networks, bridges allow Polkadot-based chains to access external liquidity, additional functionalities, and broader user bases. - -With bridges, developers and users gain the ability to: - -- Integrate external assets into Polkadot-based applications. -- Combine the strengths of Polkadot’s scalability with the liquidity of other networks. -- Facilitate accurate multi-chain applications that transcend ecosystem boundaries. - -For more information about bridges in the Polkadot ecosystem, see the [Bridge Hub](/reference/polkadot-hub/bridging/){target=\_blank} guide. - -## The Polkadot Advantage - -Polkadot was purpose-built for interoperability. Unlike networks that add interoperability as an afterthought, Polkadot integrates it as a fundamental design principle. This approach offers several distinct advantages: - -- **Developer empowerment**: Polkadot’s interoperability tools allow developers to build applications that leverage multiple chains’ capabilities without added complexity. -- **Enhanced ecosystem collaboration**: Chains in Polkadot can focus on their unique strengths while contributing to the ecosystem’s overall growth. -- **Future-proofing blockchain**: By enabling seamless communication, Polkadot ensures its ecosystem can adapt to evolving demands and technologies. - -## Looking Ahead - -Polkadot’s vision of interoperability extends beyond technical functionality, representing a shift towards a more collaborative blockchain landscape. By enabling chains to work together, Polkadot fosters innovation, efficiency, and accessibility, paving the way for a decentralized future where blockchains are not isolated competitors but interconnected collaborators. - - ---- - -Page Title: Introduction to XCM - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md -- Canonical (HTML): https://docs.polkadot.com/parachains/interoperability/get-started/ -- Summary: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. - -# Introduction to XCM - -## Introduction - -Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems. - -With XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation. - -## Messaging Format - -XCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics. - -XCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing. - -## The Four Principles of XCM - -XCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems: - -- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes. -- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended. -- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin. -- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems. - -These principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments. - -## The XCM Tech Stack - -![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp) - -The XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels. - -## Core Functionalities of XCM - -XCM enhances cross-consensus communication by introducing several powerful features: - -- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management. -- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification. -- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location. - -The standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications. - -## XCM Example - -The following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA). - -```rust -let message = Xcm(vec![ - WithdrawAsset((Here, amount).into()), - BuyExecution { - fees: (Here, amount).into(), - weight_limit: WeightLimit::Unlimited - }, - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: Junction::AccountId32 { - network: None, - id: BOB.clone().into() - }.into(), - }.into() - } -]); -``` - -The message consists of three instructions described as follows: - -- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register. - - ```rust - WithdrawAsset((Here, amount).into()), - ``` - - - **`Here`**: The native parachain token. - - **`amount`**: The number of tokens that are transferred. - - The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register. - -- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\_blank} of the XCM instructions. - - ```rust - BuyExecution { - fees: (Here, amount).into(), - weight_limit: WeightLimit::Unlimited - }, - ``` - - - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight. - - **`weight_limit`**: Defines the maximum fees that can be used to buy weight. - -- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\_blank}**: Moves the remaining tokens from the holding register to Bob’s account. - - ```rust - DepositAsset { - assets: All.into(), - beneficiary: MultiLocation { - parents: 0, - interior: Junction::AccountId32 { - network: None, - id: BOB.clone().into() - }.into(), - }.into() - } - ``` - - - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited. - -This step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - -## Overview - -XCM revolutionizes cross-chain communication by enabling use cases such as: - -- Token transfers between blockchains. -- Asset locking for cross-chain smart contract interactions. -- Remote execution of functions on other blockchains. - -These functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - - ---- - -Page Title: JSON-RPC APIs - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-json-rpc-apis.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/json-rpc-apis/ -- Summary: JSON-RPC APIs guide for Polkadot Hub, covering supported methods, parameters, and examples for interacting with the chain. - -# JSON-RPC APIs - -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction - -Polkadot Hub provides Ethereum compatibility through its JSON-RPC interface, allowing developers to interact with the chain using familiar Ethereum tooling and methods. This document outlines the supported [Ethereum JSON-RPC methods](https://ethereum.org/developers/docs/apis/json-rpc/#json-rpc-methods){target=\_blank} and provides examples of how to use them. - -This guide uses the Polkadot Hub TestNet endpoint: - -```text -https://testnet-passet-hub-eth-rpc.polkadot.io -``` - -## Available Methods - -### eth_accounts - -Returns a list of addresses owned by the client. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_accounts){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_accounts" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_accounts", - "params":[], - "id":1 -}' -``` - ---- - -### eth_blockNumber - -Returns the number of the most recent block. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_blocknumber){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_blockNumber" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_blockNumber", - "params":[], - "id":1 -}' -``` - ---- - -### eth_call - -Executes a new message call immediately without creating a transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_call){target=\_blank}. - -**Parameters**: - -- **`transaction` ++"object"++**: The transaction call object. - - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - -**Example**: - -```bash title="eth_call" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_call", - "params":[{ - "to": "INSERT_RECIPIENT_ADDRESS", - "data": "INSERT_ENCODED_CALL" - }, "INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_RECIPIENT_ADDRESS`, `INSERT_ENCODED_CALL`, and `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_chainId - -Returns the chain ID used for signing transactions. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_chainid){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_chainId" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_chainId", - "params":[], - "id":1 -}' -``` - ---- - -### eth_estimateGas - -Estimates gas required for a transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_estimategas){target=\_blank}. - -**Parameters**: - -- **`transaction` ++"object"++**: The transaction call object. - - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - -**Example**: - -```bash title="eth_estimateGas" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_estimateGas", - "params":[{ - "to": "INSERT_RECIPIENT_ADDRESS", - "data": "INSERT_ENCODED_FUNCTION_CALL" - }], - "id":1 -}' -``` - -Ensure to replace the `INSERT_RECIPIENT_ADDRESS` and `INSERT_ENCODED_CALL` with the proper values. - ---- - -### eth_gasPrice - -Returns the current gas price in Wei. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gasprice){target=\_blank}. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_gasPrice" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_gasPrice", - "params":[], - "id":1 -}' -``` - ---- - -### eth_getBalance - -Returns the balance of a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getbalance){target=\_blank}. - -**Parameters**: - -- **`address` ++"string"++**: Address to query balance. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - -**Example**: - -```bash title="eth_getBalance" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getBalance", - "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_getBlockByHash - -Returns information about a block by its hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblockbyhash){target=\_blank}. - -**Parameters**: - -- **`blockHash` ++"string"++**: The hash of the block to retrieve. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`fullTransactions` ++"boolean"++**: If `true`, returns full transaction details; if `false`, returns only transaction hashes. - -**Example**: - -```bash title="eth_getBlockByHash" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getBlockByHash", - "params":["INSERT_BLOCK_HASH", INSERT_BOOLEAN], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_HASH` and `INSERT_BOOLEAN` with the proper values. - ---- - -### eth_getBlockByNumber - -Returns information about a block by its number. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblockbynumber){target=\_blank}. - -**Parameters**: - -- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -- **`fullTransactions` ++"boolean"++**: If `true`, returns full transaction details; if `false`, returns only transaction hashes. - -**Example**: - -```bash title="eth_getBlockByNumber" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getBlockByNumber", - "params":["INSERT_BLOCK_VALUE", INSERT_BOOLEAN], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_VALUE` and `INSERT_BOOLEAN` with the proper values. - ---- - -### eth_getBlockTransactionCountByNumber - -Returns the number of transactions in a block from a block number. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber){target=\_blank}. - -**Parameters**: - -- **`blockValue` ++"string"++**: The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - -**Example**: - -```bash title="eth_getBlockTransactionCountByNumber" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getBlockTransactionCountByNumber", - "params":["INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_getBlockTransactionCountByHash - -Returns the number of transactions in a block from a block hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash){target=\_blank}. - -**Parameters**: - -- **`blockHash` ++"string"++**: The hash of the block to retrieve. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getBlockTransactionCountByHash" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getBlockTransactionCountByHash", - "params":["INSERT_BLOCK_HASH"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_HASH` with the proper values. - ---- - -### eth_getCode - -Returns the code at a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getcode){target=\_blank}. - -**Parameters**: - -- **`address` ++"string"++**: Contract or account address to query code. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). - -**Example**: - -```bash title="eth_getCode" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getCode", - "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_getLogs - -Returns an array of all logs matching a given filter object. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getlogs){target=\_blank}. - -**Parameters**: - -- **`filter` ++"object"++**: The filter object. - - **`fromBlock` ++"string"++**: (Optional) Block number or tag to start from. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - - **`toBlock` ++"string"++**: (Optional) Block number or tag to end at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. - - **`address` ++"string" or "array of strings"++**: (Optional) Contract address or a list of addresses from which to get logs. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`topics` ++"array of strings"++**: (Optional) Array of topics for filtering logs. Each topic can be a single [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string or an array of such strings (meaning OR). - - **`blockhash` ++"string"++**: (Optional) Hash of a specific block. Cannot be used with `fromBlock` or `toBlock`. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getLogs" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getLogs", - "params":[{ - "fromBlock": "latest", - "toBlock": "latest" - }], - "id":1 -}' -``` - ---- - -### eth_getStorageAt - -Returns the value from a storage position at a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getstorageat){target=\_blank}. - -**Parameters**: - -- **`address` ++"string"++**: Contract or account address to query code. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`storageKey` ++"string"++**: Position in storage to retrieve data from. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). - -**Example**: - -```bash title="eth_getStorageAt" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getStorageAt", - "params":["INSERT_ADDRESS", "INSERT_STORAGE_KEY", "INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_ADDRESS`, `INSERT_STORAGE_KEY`, and `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_getTransactionCount - -Returns the number of transactions sent from an address (nonce). [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactioncount){target=\_blank}. - -**Parameters**: - -- **`address` ++"string"++**: Address to query balance. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). - -**Example**: - -```bash title="eth_getTransactionCount" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getTransactionCount", - "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. - ---- - -### eth_getTransactionByHash - -Returns information about a transaction by its hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyhash){target=\_blank}. - -**Parameters**: - -- **`transactionHash` ++"string"++**: The hash of the transaction. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getTransactionByHash" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getTransactionByHash", - "params":["INSERT_TRANSACTION_HASH"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper values. - ---- - -### eth_getTransactionByBlockNumberAndIndex - -Returns information about a transaction by block number and transaction index. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyblocknumberandindex){target=\_blank}. - -**Parameters**: - -- **`blockValue` ++"string"++**: The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -- **`transactionIndex` ++"string"++**: The index of the transaction in the block. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getTransactionByBlockNumberAndIndex" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getTransactionByBlockNumberAndIndex", - "params":["INSERT_BLOCK_VALUE", "INSERT_TRANSACTION_INDEX"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_VALUE` and `INSERT_TRANSACTION_INDEX` with the proper values. - ---- - -### eth_getTransactionByBlockHashAndIndex - -Returns information about a transaction by block hash and transaction index. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyblockhashandindex){target=\_blank}. - -**Parameters**: - -- **`blockHash` ++"string"++**: The hash of the block. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`transactionIndex` ++"string"++**: The index of the transaction in the block. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getTransactionByBlockHashAndIndex" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getTransactionByBlockHashAndIndex", - "params":["INSERT_BLOCK_HASH", "INSERT_TRANSACTION_INDEX"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_BLOCK_HASH` and `INSERT_TRANSACTION_INDEX` with the proper values. - ---- - -### eth_getTransactionReceipt - -Returns the receipt of a transaction by transaction hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionreceipt){target=\_blank}. - -**Parameters**: - -- **`transactionHash` ++"string"++**: The hash of the transaction. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_getTransactionReceipt" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_getTransactionReceipt", - "params":["INSERT_TRANSACTION_HASH"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper values. - ---- - -### eth_maxPriorityFeePerGas - -Returns an estimate of the current priority fee per gas, in Wei, to be included in a block. - -**Parameters**: - -None. - -**Example**: - -```bash title="eth_maxPriorityFeePerGas" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_maxPriorityFeePerGas", - "params":[], - "id":1 -}' -``` - ---- - -### eth_sendRawTransaction - -Submits a raw transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_sendrawtransaction){target=\_blank}. - -**Parameters**: - -- **`callData` ++"string"++**: Signed transaction data. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_sendRawTransaction" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_sendRawTransaction", - "params":["INSERT_CALL_DATA"], - "id":1 -}' -``` - -Ensure to replace the `INSERT_CALL_DATA` with the proper values. - ---- - -### eth_sendTransaction - -Creates and sends a new transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_sendtransaction){target=\_blank}. - -**Parameters**: - -- **`transaction` ++"object"++**: The transaction object. - - **`from` ++"string"++**: Address sending the transaction. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`to` ++"string"++**: (Optional) Recipient address. No need to provide this value when deploying a contract. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`gas` ++"string"++**: (optional, default: `90000`) gas limit for execution. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`gasPrice` ++"string"++**: (Optional) Gas price per unit. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`value` ++"string"++**: (Optional) Amount of Ether to send. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`data` ++"string"++**: (Optional) Contract bytecode or encoded method call. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`nonce` ++"string"++**: (Optional) Transaction nonce. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - -**Example**: - -```bash title="eth_sendTransaction" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_sendTransaction", - "params":[{ - "from": "INSERT_SENDER_ADDRESS", - "to": "INSERT_RECIPIENT_ADDRESS", - "gas": "INSERT_GAS_LIMIT", - "gasPrice": "INSERT_GAS_PRICE", - "value": "INSERT_VALUE", - "input": "INSERT_INPUT_DATA", - "nonce": "INSERT_NONCE" - }], - "id":1 -}' -``` +5. Configure and execute the deployment: -Ensure to replace the `INSERT_SENDER_ADDRESS`, `INSERT_RECIPIENT_ADDRESS`, `INSERT_GAS_LIMIT`, `INSERT_GAS_PRICE`, `INSERT_VALUE`, `INSERT_INPUT_DATA`, and `INSERT_NONCE` with the proper values. + ```js title="scripts/deploy.js" + const providerConfig = { + rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', + chainId: 420420422, + name: 'polkadot-hub-testnet', + }; ---- + const mnemonic = 'INSERT_MNEMONIC'; -### eth_syncing + deployContract('Storage', mnemonic, providerConfig); + ``` -Returns an object with syncing data or `false` if not syncing. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_syncing){target=\_blank}. + !!! note + A mnemonic (seed phrase) is a series of words that can generate multiple private keys and their corresponding addresses. It's used here to derive the wallet that will sign and pay for the deployment transaction. **Always keep your mnemonic secure and never share it publicly**. -**Parameters**: + Ensure to replace the `INSERT_MNEMONIC` placeholder with your actual mnemonic. -None. +??? code "View complete script" -**Example**: + ```js title="scripts/deploy.js" + // Deploy an EVM-compatible smart contract using ethers.js + const { writeFileSync, existsSync, readFileSync } = require('fs'); + const { join } = require('path'); + const { ethers, JsonRpcProvider } = require('ethers'); -```bash title="eth_syncing" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"eth_syncing", - "params":[], - "id":1 -}' -``` + const codegenDir = join(__dirname); ---- + // Creates an Ethereum provider with specified RPC URL and chain details + const createProvider = (rpcUrl, chainId, chainName) => { + const provider = new JsonRpcProvider(rpcUrl, { + chainId: chainId, + name: chainName, + }); + return provider; + }; -### net_listening + // Reads and parses the ABI file for a given contract + const getAbi = (contractName) => { + try { + return JSON.parse( + readFileSync(join(codegenDir, `${contractName}.json`), 'utf8'), + ); + } catch (error) { + console.error( + `Could not find ABI for contract ${contractName}:`, + error.message, + ); + throw error; + } + }; -Returns `true` if the client is currently listening for network connections, otherwise `false`. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#net_listening){target=\_blank}. + // Reads the compiled bytecode for a given contract + const getByteCode = (contractName) => { + try { + const bytecodePath = join( + codegenDir, + '../contracts', + `${contractName}.polkavm`, + ); + return `0x${readFileSync(bytecodePath).toString('hex')}`; + } catch (error) { + console.error( + `Could not find bytecode for contract ${contractName}:`, + error.message, + ); + throw error; + } + }; -**Parameters**: + const deployContract = async (contractName, mnemonic, providerConfig) => { + console.log(`Deploying ${contractName}...`); -None. + try { + // Step 1: Set up provider and wallet + const provider = createProvider( + providerConfig.rpc, + providerConfig.chainId, + providerConfig.name, + ); + const walletMnemonic = ethers.Wallet.fromPhrase(mnemonic); + const wallet = walletMnemonic.connect(provider); -**Example**: + // Step 2: Create and deploy the contract + const factory = new ethers.ContractFactory( + getAbi(contractName), + getByteCode(contractName), + wallet, + ); + const contract = await factory.deploy(); + await contract.waitForDeployment(); -```bash title="net_listening" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"net_listening", - "params":[], - "id":1 -}' -``` + // Step 3: Save deployment information + const address = await contract.getAddress(); + console.log(`Contract ${contractName} deployed at: ${address}`); ---- + const addressesFile = join(codegenDir, 'contract-address.json'); + const addresses = existsSync(addressesFile) + ? JSON.parse(readFileSync(addressesFile, 'utf8')) + : {}; + addresses[contractName] = address; + writeFileSync(addressesFile, JSON.stringify(addresses, null, 2), 'utf8'); + } catch (error) { + console.error(`Failed to deploy contract ${contractName}:`, error); + } + }; -### net_peerCount + const providerConfig = { + rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', + chainId: 420420422, + name: 'polkadot-hub-testnet', + }; -Returns the number of peers currently connected to the client. + const mnemonic = 'INSERT_MNEMONIC'; -**Parameters**: + deployContract('Storage', mnemonic, providerConfig); -None. + ``` -**Example**: +To run the script, execute the following command: -```bash title="net_peerCount" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"net_peerCount", - "params":[], - "id":1 -}' +```bash +node deploy ``` ---- +After running this script, your contract will be deployed to Polkadot Hub, and its address will be saved in `contract-address.json` within your project directory. You can use this address for future contract interactions. -### net_version +## Interact with the Contract -Returns the current network ID as a string. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#net_version){target=\_blank}. +Once the contract is deployed, you can interact with it by calling its functions. For example, to set a number, read it and then modify that number by its double, you can create a file named `checkStorage.js` in the root of your project and add the following code: -**Parameters**: +```js title="scripts/checkStorage.js" +const { ethers } = require('ethers'); +const { readFileSync } = require('fs'); +const { join } = require('path'); -None. +const createProvider = (providerConfig) => { + return new ethers.JsonRpcProvider(providerConfig.rpc, { + chainId: providerConfig.chainId, + name: providerConfig.name, + }); +}; -**Example**: +const createWallet = (mnemonic, provider) => { + return ethers.Wallet.fromPhrase(mnemonic).connect(provider); +}; -```bash title="net_version" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"net_version", - "params":[], - "id":1 -}' -``` +const loadContractAbi = (contractName, directory = __dirname) => { + const contractPath = join(directory, `${contractName}.json`); + const contractJson = JSON.parse(readFileSync(contractPath, 'utf8')); + return contractJson.abi || contractJson; // Depending on JSON structure +}; ---- +const createContract = (contractAddress, abi, wallet) => { + return new ethers.Contract(contractAddress, abi, wallet); +}; -### system_health +const interactWithStorageContract = async ( + contractName, + contractAddress, + mnemonic, + providerConfig, + numberToSet, +) => { + try { + console.log(`Setting new number in Storage contract: ${numberToSet}`); -Returns information about the health of the system. + // Create provider and wallet + const provider = createProvider(providerConfig); + const wallet = createWallet(mnemonic, provider); -**Parameters**: + // Load the contract ABI and create the contract instance + const abi = loadContractAbi(contractName); + const contract = createContract(contractAddress, abi, wallet); -None. + // Send a transaction to set the stored number + const tx1 = await contract.setNumber(numberToSet); + await tx1.wait(); // Wait for the transaction to be mined + console.log(`Number successfully set to ${numberToSet}`); -**Example**: + // Retrieve the updated number + const storedNumber = await contract.storedNumber(); + console.log(`Retrieved stored number:`, storedNumber.toString()); + + // Send a transaction to set the stored number + const tx2 = await contract.setNumber(numberToSet * 2); + await tx2.wait(); // Wait for the transaction to be mined + console.log(`Number successfully set to ${numberToSet * 2}`); + + // Retrieve the updated number + const updatedNumber = await contract.storedNumber(); + console.log(`Retrieved stored number:`, updatedNumber.toString()); + } catch (error) { + console.error('Error interacting with Storage contract:', error.message); + } +}; + +const providerConfig = { + name: 'asset-hub-smart-contracts', + rpc: 'https://testnet-passet-hub-eth-rpc.polkadot.io', + chainId: 420420422, +}; + +const mnemonic = 'INSERT_MNEMONIC'; +const contractName = 'Storage'; +const contractAddress = 'INSERT_CONTRACT_ADDRESS'; +const newNumber = 42; + +interactWithStorageContract( + contractName, + contractAddress, + mnemonic, + providerConfig, + newNumber, +); -```bash title="system_health" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"system_health", - "params":[], - "id":1 -}' ``` ---- +Ensure you replace the `INSERT_MNEMONIC`, `INSERT_CONTRACT_ADDRESS`, and `INSERT_ADDRESS_TO_CHECK` placeholders with actual values. Also, ensure the contract ABI file (`Storage.json`) is correctly referenced. -### web3_clientVersion +To interact with the contract, run: -Returns the current client version. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#web3_clientversion){target=\_blank}. +```bash +node checkStorage +``` -**Parameters**: +## Where to Go Next -None. +Now that you have the foundational knowledge to use Ethers.js with Polkadot Hub, you can: -**Example**: +- **Dive into Ethers.js utilities**: Discover additional Ethers.js features, such as wallet management, signing messages, etc. +- **Implement batch transactions**: Use Ethers.js to execute batch transactions for efficient multi-step contract interactions. +- **Build scalable applications**: Combine Ethers.js with frameworks like [`Next.js`](https://nextjs.org/docs){target=\_blank} or [`Node.js`](https://nodejs.org/en){target=\_blank} to create full-stack decentralized applications (dApps). -```bash title="web3_clientVersion" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"web3_clientVersion", - "params":[], - "id":1 -}' -``` --- -### debug_traceBlockByNumber - -Traces a block's execution by its number and returns a detailed execution trace for each transaction. +Page Title: Deploy Contracts Using Remix IDE -**Parameters**: +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-remix-deploy-a-contract.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/dev-environments/remix/deploy-a-contract/ +- Summary: Learn how to deploy smart contracts to the Polkadot Hub network and interact with them using the Remix IDE and wallet providers, covering deployment and state. -- **`blockValue` ++"string"++**: The block number or tag to trace. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -- **`options` ++"object"++**: (Optional) An object containing tracer options. - - **`tracer` ++"string"++**: The name of the tracer to use (e.g., `"callTracer"`, `"opTracer"`). - - Other tracer-specific options may be supported. +# Deploy Smart Contracts Using Remix IDE -**Example**: +## Overview -```bash title="debug_traceBlockByNumber" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"debug_traceBlockByNumber", - "params":["INSERT_BLOCK_VALUE", {"tracer": "callTracer"}], - "id":1 -}' -``` +After compiling your smart contract in Remix IDE, the next step is to deploy it to the Polkadot Hub network. This guide will walk you through the deployment process using a wallet provider and show you how to interact with your deployed contracts directly from the Remix interface. -Ensure to replace `INSERT_BLOCK_VALUE` with a proper block number if needed. +## Prerequisites ---- +Before deploying your contract, ensure you have: -### debug_traceTransaction +- Completed the [Remix IDE setup](/smart-contracts/dev-environments/remix/get-started/){target=\_blank} and have a compiled contract ready. +- A compatible wallet extension installed (e.g., [MetaMask](https://metamask.io/){target=\_blank} or [Talisman](https://www.talisman.xyz/){target=\_blank}). +- Your wallet connected to the Polkadot Hub network. Check the [Connect to Polkadot](/smart-contracts/connect/){target=\_blank} guide for more information. +- Test tokens in your wallet to cover deployment and transaction fees (available from the [Polkadot faucet](/smart-contracts/faucet/){target=\_blank}). -Traces the execution of a single transaction by its hash and returns a detailed execution trace. +## Deploy Contracts -**Parameters**: +The steps to use Remix IDE to deploy a contract to Polkadot Hub are as follows: -- **`transactionHash` ++"string"++**: The hash of the transaction to trace. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- **`options` ++"object"++**: (Optional) An object containing tracer options (e.g., `tracer: "callTracer"`). +1. Navigate to [Remix](https://remix.ethereum.org/){target=\_blank} in your web browser. +2. Locate the **Deploy & Run Transactions** tab. +3. Select the **Environment** dropdown. +4. Select **Browser Extension**. +5. Select the **Injected Provider - MetaMask** option. +6. Click the **Deploy** button and then click **Confirm** in the wallet popup. -**Example**: +Once your contract is deployed successfully, you will see the deployment confirmation in the Remix terminal. -```bash title="debug_traceTransaction" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"debug_traceTransaction", - "params":["INSERT_TRANSACTION_HASH", {"tracer": "callTracer"}], - "id":1 -}' -``` +![](/images/smart-contracts/dev-environments/remix/deploy-a-contract/remix-1.gif) -Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper value. +## Interact with Contracts ---- +Deployed contracts appear in the **Deployed/Unpinned Contracts** section. Follow these steps to interact with the deployed contract: -### debug_traceCall +1. Expand the contract to view available methods. -Executes a new message call and returns a detailed execution trace without creating a transaction on the blockchain. + !!! tip + Pin your frequently used contracts to the **Pinned Contracts** section for easy access. -**Parameters**: +2. Select any of the exposed methods to interact with the contract. -- **`transaction` ++"object"++**: The transaction call object, similar to `eth_call` parameters. - - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -- **`options` ++"object"++**: (Optional) An object containing tracer options (e.g., `tracer: "callTracer"`). + You can use these methods to interact with your deployed contract by reading or writing to its state. Remix IDE uses a color-coding scheme for method buttons to help differentiate between types of available methods as follows: -**Example**: + - **Blue buttons**: indicate `view` or `pure` functions which read state only. Interactions do not create a new transaction and do not incur gas fees. + - **Orange buttons**: label `non-payable` functions which change contract state but don't accept any value (ETH or other tokens) being sent with the transaction. + - **Red buttons**: designate `payable` functions which create a transaction and can accept a value (ETH or other tokens) to send with the transaction. -```bash title="debug_traceCall" -curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ --H "Content-Type: application/json" \ ---data '{ - "jsonrpc":"2.0", - "method":"debug_traceCall", - "params":[{ - "from": "INSERT_SENDER_ADDRESS", - "to": "INSERT_RECIPIENT_ADDRESS", - "data": "INSERT_ENCODED_CALL" - }, "INSERT_BLOCK_VALUE", {"tracer": "callTracer"}], - "id":1 -}' -``` +If you deployed the `Counter.sol` contract from [Remix IDE setup](/smart-contracts/dev-environments/remix/get-started/){target=\_blank}, you can try interacting with the exposed methods as follows: -Ensure to replace the `INSERT_SENDER_ADDRESS`, `INSERT_RECIPIENT_ADDRESS`, `INSERT_ENCODED_CALL`, and `INSERT_BLOCK_VALUE` with the proper value. +1. Select the **GetCount** button to read the current count value. ---- +2. Select the **Increment** button to increment the count value. -## Response Format +3. Submit the transaction and click the **Confirm** button in the wallet pop-up. -All responses follow the standard JSON-RPC 2.0 format: +Once the transaction is confirmed, you will see the updated count value in the Remix terminal. -```json -{ - "jsonrpc": "2.0", - "id": 1, - "result": ... // The return value varies by method -} -``` +![](/images/smart-contracts/dev-environments/remix/deploy-a-contract/remix-2.gif) -## Error Handling +## Where to Go Next -If an error occurs, the response will include an error object: +You've successfully deployed and interacted with your smart contract on Polkadot Hub using Remix IDE. Continue enhancing your development workflow with these resources: -```json -{ - "jsonrpc": "2.0", - "id": 1, - "error": { - "code": -32000, - "message": "Error message here" - } -} -``` +
---- -Page Title: Light Clients +- Guide __Troubleshooting__ -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-light-clients.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/light-clients/ -- Summary: Light clients enable secure and efficient blockchain interaction without running a full node. Learn everything you need to know about light clients on Polkadot. + --- -# Light Clients + Find solutions to common issues when working with Remix IDE. -## Introduction + [:octicons-arrow-right-24: Get Started](/smart-contracts/dev-environments/remix/troubleshooting-faq/) -Light clients enable secure and efficient blockchain interaction without running a full node. They provide a trust-minimized alternative to JSON-RPC by verifying data through cryptographic proofs rather than blindly trusting remote nodes. +
-This guide covers: -- What light clients are and how they work. -- Their advantages compared to full nodes and JSON-RPC. -- Available implementations in the Polkadot ecosystem. -- How to use light clients in your applications. +--- -Light clients are particularly valuable for resource-constrained environments and applications requiring secure, decentralized blockchain access without the overhead of maintaining full nodes. +Page Title: Deploying Uniswap V2 on Polkadot -!!!note "Light node or light client?" - The terms _light node_ and _light client_ are interchangeable. Both refer to a blockchain client that syncs without downloading the entire blockchain state. All nodes in a blockchain network are fundamentally clients, engaging in peer-to-peer communication. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-eth-dapps-uniswap-v2.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/eth-dapps/uniswap-v2/ +- Summary: Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. -## Light Clients Workflow +# Deploy Uniswap V2 -Unlike JSON-RPC interfaces, where an application must maintain a list of providers or rely on a single node, light clients are not limited to or dependent on a single node. They use cryptographic proofs to verify the blockchain's state, ensuring it is up-to-date and accurate. By verifying only block headers, light clients avoid syncing the entire state, making them ideal for resource-constrained environments. +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. +## Introduction -```mermaid -flowchart LR -DAPP([dApp])-- Query Account Info -->LC([Light Client]) -LC -- Request --> FN(((Full Node))) -LC -- Response --> DAPP -FN -- Response (validated via Merkle proof) --> LC -``` +Decentralized exchanges (DEXs) are a cornerstone of the DeFi ecosystem, allowing for permissionless token swaps without intermediaries. [Uniswap V2](https://docs.uniswap.org/contracts/v2/overview){target=\_blank}, with its Automated Market Maker (AMM) model, revolutionized DEXs by enabling liquidity provision for any ERC-20 token pair. -In the diagram above, the decentralized application queries on-chain account information through the light client. The light client runs as part of the application and requires minimal memory and computational resources. It uses Merkle proofs to verify the state retrieved from a full node in a trust-minimized manner. Polkadot-compatible light clients utilize [warp syncing](https://spec.polkadot.network/sect-lightclient#sect-sync-warp-lightclient){target=\_blank}, which downloads only block headers. +This tutorial will guide you through how Uniswap V2 works so you can take advantage of it in your projects deployed to Polkadot Hub. By understanding these contracts, you'll gain hands-on experience with one of the most influential DeFi protocols and understand how it functions across blockchain ecosystems. -Light clients can quickly verify the blockchain's state, including [GRANDPA finality](/polkadot-protocol/glossary#grandpa){target=\_blank} justifications. +## Prerequisites -!!!note "What does it mean to be trust-minimized?" - _Trust-minimized_ means that the light client does not need to fully trust the full node from which it retrieves the state. This is achieved through the use of Merkle proofs, which allow the light client to verify the correctness of the state by checking the Merkle tree root. +Before starting, make sure you have: -## JSON-RPC and Light Client Comparison +- Node.js (v16.0.0 or later) and npm installed. +- Basic understanding of Solidity and JavaScript. +- Familiarity with [`hardhat-polkadot`](/smart-contracts/dev-environments/hardhat/get-started/){target=\_blank} development environment. +- Some PAS test tokens to cover transaction fees (obtained from the [Polkadot faucet](https://faucet.polkadot.io/?parachain=1111){target=\_blank}). +- Basic understanding of how AMMs and liquidity pools work. -Another common method of communication between a user interface (UI) and a node is through the JSON-RPC protocol. Generally, the UI retrieves information from the node, fetches network or [pallet](/polkadot-protocol/glossary#pallet){target=\_blank} data, and interacts with the blockchain. This is typically done in one of two ways: +## Set Up the Project -- **User-controlled nodes**: The UI connects to a node client installed on the user's machine. - - These nodes are secure, but installation and maintenance can be inconvenient. -- **Publicly accessible nodes**: The UI connects to a third-party-owned publicly accessible node client. - - These nodes are convenient but centralized and less secure. Applications must maintain a list of backup nodes in case the primary node becomes unavailable. +Let's start by cloning the Uniswap V2 project: -While light clients still communicate with [full nodes](/polkadot-protocol/glossary#full-node), they offer significant advantages for applications requiring a secure alternative to running a full node: +1. Clone the Uniswap V2 repository: -| Full Node | Light Client | -| :---------------------------------------------------------------------------------------------: | :------------------------------------------------------------: | -| Fully verifies all blocks of the chain | Verifies only the authenticity of blocks | -| Stores previous block data and the chain's storage in a database | Does not require a database | -| Installation, maintenance, and execution are resource-intensive and require technical expertise | No installation is typically included as part of the application | + ``` + git clone https://github.com/polkadot-developers/polkavm-hardhat-examples.git -b v0.0.6 + cd polkavm-hardhat-examples/uniswap-v2-polkadot/ + ``` -## Using Light Clients +2. Install the required dependencies: -The [`smoldot`](https://github.com/smol-dot/smoldot){target=\_blank} client is the cornerstone of light client implementation for Polkadot SDK-based chains. It provides the primitives needed to build light clients and is also integrated into libraries such as [PAPI](#papi-light-client-support). + ```bash + npm install + ``` -### PAPI Light Client Support +3. Update the `hardhat.config.js` file so the paths for the Substrate node and the ETH-RPC adapter match with the paths on your machine. For more info, check the [Testing your Contract](/smart-contracts/dev-environments/hardhat/compile-and-test/){target=\_blank} section in the Hardhat guide. -The [Polkadot API (PAPI)](/develop/toolkit/api-libraries/papi){target=\_blank} library natively supports light client configurations powered by [`smoldot`](https://github.com/smol-dot/smoldot){target=\_blank}. This allows developers to connect to multiple chains simultaneously using a light client. + ```js title="hardhat.config.js" + hardhat: { + polkavm: true, + nodeConfig: { + nodeBinaryPath: '../bin/substrate-node', + rpcPort: 8000, + dev: true, + }, + adapterConfig: { + adapterBinaryPath: '../bin/eth-rpc', + dev: true, + }, + }, + ``` -### Substrate Connect - Browser Extension +4. Create a `.env` file in your project root to store your private keys (you can use as an example the `env.example` file): -The [Substrate Connect browser extension](https://www.npmjs.com/package/@substrate/connect-extension-protocol){target=\_blank} enables end-users to interact with applications connected to multiple blockchains or to connect their own blockchains to supported applications. + ```text title=".env" + LOCAL_PRIV_KEY="INSERT_LOCAL_PRIVATE_KEY" + AH_PRIV_KEY="INSERT_AH_PRIVATE_KEY" + ``` -Establishing a sufficient number of peers can be challenging due to browser limitations on WebSocket connections from HTTPS pages, as many nodes require TLS. The Substrate Connect browser extension addresses this limitation by keeping chains synced in the background, enabling faster application performance. + Ensure to replace `"INSERT_LOCAL_PRIVATE_KEY"` with a private key available in the local environment (you can get them from this [file](https://github.com/paritytech/hardhat-polkadot/blob/main/packages/hardhat-polkadot-node/src/constants.ts#L22){target=\_blank}). And `"INSERT_AH_PRIVATE_KEY"` with the account's private key you want to use to deploy the contracts. You can get this by exporting the private key from your wallet (e.g., MetaMask). -Substrate Connect automatically detects whether the user has the extension installed. If not, an in-page Wasm light client is created for them. + !!!warning + Keep your private key safe, and never share it with anyone. If it is compromised, your funds can be stolen. -## Resources +5. Compile the contracts: -- [What is a light client and why you should care?](https://medium.com/paritytech/what-is-a-light-client-and-why-you-should-care-75f813ae2670){target=\_blank} -- [Introducing Substrate Connect: Browser-Based Light Clients for Connecting to Substrate Chains](https://www.parity.io/blog/introducing-substrate-connect){target=\_blank} -- [Substrate Connect GitHub Repository](https://github.com/paritytech/substrate-connect/tree/master/projects/extension){target=\_blank} -- [Light Clients - Polkadot Specification](https://spec.polkadot.network/sect-lightclient){target=\_blank} + ```bash + npx hardhat compile + ``` +If the compilation is successful, you should see the following output: ---- +
+ npx hardhat compile + Compiling 12 Solidity files + Successfully compiled 12 Solidity files +
-Page Title: Networks +After running the above command, you should see the compiled contracts in the `artifacts-pvm` directory. This directory contains the ABI and bytecode of your contracts. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-networks.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/networks/ -- Summary: Explore Polkadot's testing and production networks, including Westend, Kusama, and Paseo, for efficient development, deployment, and testing. +## Understanding Uniswap V2 Architecture -# Networks +Before interacting with the contracts, it's essential to understand the core architecture that powers Uniswap V2. This model forms the basis of nearly every modern DEX implementation and operates under automated market making, token pair liquidity pools, and deterministic pricing principles. -## Introduction +At the heart of Uniswap V2 lies a simple but powerful system composed of two major smart contracts: -The Polkadot ecosystem is built on a robust set of networks designed to enable secure and scalable development. Whether you are testing new features or deploying to live production, Polkadot offers several layers of networks tailored for each stage of the development process. From local environments to experimental networks like Kusama and community-run TestNets such as Paseo, developers can thoroughly test, iterate, and validate their applications. This guide will introduce you to Polkadot's various networks and explain how they fit into the development workflow. +- **Factory contract**: The factory acts as a registry and creator of new trading pairs. When two ERC-20 tokens are to be traded, the Factory contract is responsible for generating a new Pair contract that will manage that specific token pair’s liquidity pool. It keeps track of all deployed pairs and ensures uniqueness—no duplicate pools can exist for the same token combination. +- **Pair contract**: Each pair contract is a decentralized liquidity pool that holds reserves of two ERC-20 tokens. These contracts implement the core logic of the AMM, maintaining a constant product invariant (x \* y = k) to facilitate swaps and price determination. Users can contribute tokens to these pools in return for LP (liquidity provider) tokens, which represent their proportional share of the reserves. -## Network Overview +This minimal architecture enables Uniswap to be highly modular, trustless, and extensible. By distributing responsibilities across these components, developers, and users can engage with the protocol in a composable and predictable manner, making it an ideal foundation for DEX functionality across ecosystems, including Polkadot Hub. -Polkadot's development process is structured to ensure new features and upgrades are rigorously tested before being deployed on live production networks. The progression follows a well-defined path, starting from local environments and advancing through TestNets, ultimately reaching the Polkadot MainNet. The diagram below outlines the typical progression of the Polkadot development cycle: +The project scaffolding is as follows: -``` mermaid -flowchart LR - id1[Local] --> id2[Westend] --> id4[Kusama] --> id5[Polkadot] - id1[Local] --> id3[Paseo] --> id5[Polkadot] +```bash +uniswap-V2-polkadot +├── bin/ +├── contracts/ +│ ├── interfaces/ +│ │ ├── IERC20.sol +│ │ ├── IUniswapV2Callee.sol +│ │ ├── IUniswapV2ERC20.sol +│ │ ├── IUniswapV2Factory.sol +│ │ └── IUniswapV2Pair.sol +│ ├── libraries/ +│ │ ├── Math.sol +│ │ ├── SafeMath.sol +│ │ └── UQ112x112.sol +│ ├── test/ +│ │ └── ERC20.sol +│ ├── UniswapV2ERC20.sol +│ ├── UniswapV2Factory.sol +│ └── UniswapV2Pair.sol +├── ignition/ +├── scripts/ +│ └── deploy.js +├── node_modules/ +├── test/ +│ ├── shared/ +│ │ ├── fixtures.js +│ │ └── utilities.js +│ ├── UniswapV2ERC20.js +│ ├── UniswapV2Factory.js +│ └── UniswapV2Pair.js +├── .env.example +├── .gitignore +├── hardhat.config.js +├── package.json +└── README.md ``` -This flow ensures developers can thoroughly test and iterate without risking real tokens or affecting production networks. Testing tools like [Chopsticks](#chopsticks) and various TestNets make it easier to experiment safely before releasing to production. - -A typical journey through the Polkadot core protocol development process might look like this: - -1. **Local development node**: Development starts in a local environment, where developers can create, test, and iterate on upgrades or new features using a local development node. This stage allows rapid experimentation in an isolated setup without any external dependencies. - -2. **Westend**: After testing locally, upgrades are deployed to [Westend](#westend), Polkadot's primary TestNet. Westend simulates real-world conditions without using real tokens, making it the ideal place for rigorous feature testing before moving on to production networks. - -3. **Kusama**: Once features have passed extensive testing on Westend, they move to Kusama, Polkadot's experimental and fast-moving "canary" network. Kusama operates as a high-fidelity testing ground with actual economic incentives, giving developers insights into how their features will perform in a real-world environment. - -4. **Polkadot**: After passing tests on Westend and Kusama, features are considered ready for deployment to Polkadot, the live production network. - - In addition, parachain developers can leverage local TestNets like [Zombienet](#zombienet) and deploy upgrades on parachain TestNets. - -5. **Paseo**: For parachain and dApp developers, Paseo serves as a community-run TestNet that mirrors Polkadot's runtime. Like Westend for core protocol development, Paseo provides a testing ground for parachain development without affecting live networks. - -!!!note - The Rococo TestNet deprecation date was October 14, 2024. Teams should use Westend for Polkadot protocol and feature testing and Paseo for chain development-related testing. - -## Polkadot Development Networks +## Test the Contracts -Development and testing are crucial to building robust dApps and parachains and performing network upgrades within the Polkadot ecosystem. To achieve this, developers can leverage various networks and tools that provide a risk-free environment for experimentation and validation before deploying features to live networks. These networks help avoid the costs and risks associated with real tokens, enabling testing for functionalities like governance, cross-chain messaging, and runtime upgrades. +You can run the provided test suite to ensure the contracts are working as expected. The tests cover various scenarios, including creating pairs, adding liquidity, and executing swaps. -## Kusama Network +To test it locally, you can run the following commands: -Kusama is the experimental version of Polkadot, designed for developers who want to move quickly and test their applications in a real-world environment with economic incentives. Kusama serves as a production-grade testing ground where developers can deploy features and upgrades with the pressure of game theory and economics in mind. It mirrors Polkadot but operates as a more flexible space for innovation. +1. Spawn a local node for testing: -The native token for Kusama is KSM. For more information about KSM, visit the [Native Assets](https://wiki.polkadot.com/kusama/kusama-getting-started/){target=\_blank} page. + ```bash + npx hardhat node + ``` -## Test Networks + This command will spawn a local Substrate node along with the ETH-RPC adapter. The node will be available at `ws://127.0.0.1:8000` and the ETH-RPC adapter at `http://localhost:8545`. -The following test networks provide controlled environments for testing upgrades and new features. TestNet tokens are available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}. +2. In a new terminal, run the tests: -### Westend + ```bash + npx hardhat test --network localNode + ``` -Westend is Polkadot's primary permanent TestNet. Unlike temporary test networks, Westend is not reset to the genesis block, making it an ongoing environment for testing Polkadot core features. Managed by Parity Technologies, Westend ensures that developers can test features in a real-world simulation without using actual tokens. +The result should look like this: -The native token for Westend is WND. More details about WND can be found on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_2){target=\_blank} page. +
+ npx hardhat test --network localNode + Compiling 12 Solidity files + Successfully compiled 12 Solidity files + + UniswapV2ERC20 + ✔ name, symbol, decimals, totalSupply, balanceOf, DOMAIN_SEPARATOR, PERMIT_TYPEHASH (44ms) + ✔ approve (5128ms) + ✔ transfer (5133ms) + ✔ transfer:fail + ✔ transferFrom (6270ms) + ✔ transferFrom:max (6306ms) + + UniswapV2Factory + ✔ feeTo, feeToSetter, allPairsLength + ✔ createPair (176ms) + ✔ createPair:reverse (1224ms) + ✔ setFeeTo (1138ms) + ✔ setFeeToSetter (1125ms) + + UniswapV2Pair + ✔ mint (11425ms) + ✔ getInputPrice:0 (12590ms) + ✔ getInputPrice:1 (17600ms) + ✔ getInputPrice:2 (17618ms) + ✔ getInputPrice:3 (17704ms) + ✔ getInputPrice:4 (17649ms) + ✔ getInputPrice:5 (17594ms) + ✔ getInputPrice:6 (13643ms) + ✔ optimistic:0 (17647ms) + ✔ optimistic:1 (17946ms) + ✔ optimistic:2 (17657ms) + ✔ optimistic:3 (21625ms) + ✔ swap:token0 (12665ms) + ✔ swap:token1 (17631ms) + ✔ burn (17690ms) + ✔ feeTo:off (23900ms) + ✔ feeTo:on (24991ms) + + 28 passing (12m) +
-### Paseo +## Deploy the Contracts -[Paseo](https://github.com/paseo-network){target=\_blank} is a community-managed TestNet designed for parachain and dApp developers. It mirrors Polkadot's runtime and is maintained by Polkadot community members. Paseo provides a dedicated space for parachain developers to test their applications in a Polkadot-like environment without the risks associated with live networks. +After successfully testing the contracts, you can deploy them to the local node or Polkadot Hub. The deployment script is located in the `scripts` directory and is named `deploy.js`. This script deploys the `Factory` and `Pair` contracts to the network. -The native token for Paseo is PAS. Additional information on PAS is available on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_1){target=\_blank} page. +To deploy the contracts, run the following command: -## Local Test Networks +```bash +npx hardhat run scripts/deploy.js --network localNode +``` -Local test networks are an essential part of the development cycle for blockchain developers using the Polkadot SDK. They allow for fast, iterative testing in controlled, private environments without connecting to public TestNets. Developers can quickly spin up local instances to experiment, debug, and validate their code before deploying to larger TestNets like Westend or Paseo. Two key tools for local network testing are Zombienet and Chopsticks. +This command deploys the contracts to your local blockchain for development and testing. If you want to deploy to Polkadot Hub, you can use the following command: -### Zombienet +```bash +npx hardhat run scripts/deploy.js --network passetHub +``` -[Zombienet](https://github.com/paritytech/zombienet){target=\_blank} is a flexible testing framework for Polkadot SDK-based blockchains. It enables developers to create and manage ephemeral, short-lived networks. This feature makes Zombienet particularly useful for quick iterations, as it allows you to run multiple local networks concurrently, mimicking different runtime conditions. Whether you're developing a parachain or testing your custom blockchain logic, Zombienet gives you the tools to automate local testing. +The command above deploys to the actual Polkadot TestNet. It requires PAS test tokens, persists on the network, and operates under real network conditions. -Key features of Zombienet include: +The deployment script will output the addresses of the deployed contracts. Save these addresses, as you will need them to interact with the contracts. For example, the output should look like this: -- Creating dynamic, local networks with different configurations. -- Running parachains and relay chains in a simulated environment. -- Efficient testing of network components like cross-chain messaging and governance. +
+ npx hardhat run scripts/deploy.js --network localNode + Successfully compiled 12 Solidity files + Deploying contracts using 0xf24FF3a9CF04c71Dbc94D0b566f7A27B94566cac + Deploying UniswapV2ERC20... + ETH deployed to : 0x7acc1aC65892CF3547b1b0590066FB93199b430D + Deploying UniswapV2Factory... + Factory deployed to : 0x85b108660f47caDfAB9e0503104C08C1c96e0DA9 + Deploying UniswapV2Pair with JsonRpcProvider workaround... + Pair deployed to : 0xF0e46847c8bFD122C4b5EEE1D4494FF7C5FC5104 +
-Zombienet is ideal for developers looking to test quickly and thoroughly before moving to more resource-intensive public TestNets. +## Conclusion -### Chopsticks +This tutorial guided you through deploying Uniswap V2 contracts to Polkadot Hub. This implementation brings the powerful AMM architecture to the Polkadot ecosystem, laying the foundation for the decentralized trading of ERC-20 token pairs. -[Chopsticks](https://github.com/AcalaNetwork/chopsticks){target=\_blank} is a tool designed to create forks of Polkadot SDK-based blockchains, allowing developers to interact with network forks as part of their testing process. This capability makes Chopsticks a powerful option for testing upgrades, runtime changes, or cross-chain applications in a forked network environment. +By following this guide, you've gained practical experience with: -Key features of Chopsticks include: +- Setting up a Hardhat project for deploying to Polkadot Hub. +- Understanding the Uniswap V2 architecture. +- Testing Uniswap V2 contracts in a local environment. +- Deploying contracts to both local and testnet environments. -- Forking live Polkadot SDK-based blockchains for isolated testing. -- Simulating cross-chain messages in a private, controlled setup. -- Debugging network behavior by interacting with the fork in real-time. +To build on this foundation, you could extend this project by implementing functionality to create liquidity pools, execute token swaps, and build a user interface for interacting with your deployment. -Chopsticks provides a controlled environment for developers to safely explore the effects of runtime changes. It ensures that network behavior is tested and verified before upgrades are deployed to live networks. +This knowledge can be leveraged to build more complex DeFi applications or to integrate Uniswap V2 functionality into your existing projects on Polkadot. --- -Page Title: Node and Runtime +Page Title: Dual Virtual Machine Stack -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-node-and-runtime.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/node-and-runtime/ -- Summary: Learn how Polkadot SDK-based nodes function, how the client and runtime are separated, and how they communicate using SCALE-encoded data. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-dual-vm-stack.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/dual-vm-stack/ +- Summary: Compare Polkadot’s dual smart contract VMs—REVM for EVM compatibility and PolkaVM for RISC-V performance, flexibility, and efficiency. -# Node and Runtime +# Dual Virtual Machine Stack +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. ## Introduction -Every blockchain platform relies on a decentralized network of computers, called nodes, that communicate with each other about transactions and blocks. In this context, a node refers to the software running on the connected devices rather than the physical or virtual machines in the network. +Polkadot's smart contract platform supports two distinct virtual machine (VM) architectures, providing developers with flexibility in selecting the optimal execution backend for their specific needs. This approach strikes a balance between immediate Ethereum compatibility and long-term innovation, enabling developers to deploy either unmodified (Ethereum Virtual Machine) EVM contracts using Rust Ethereum Virtual Machine (REVM) or optimize for higher performance using PolkaVM (PVM). + +Both VM options share common infrastructure, including RPC interfaces, tooling support, and precompiles. The following sections compare architectures and guide you in selecting the best VM for your project's needs. -Polkadot SDK-based nodes consist of two main components, each with distinct responsibilities: the client (also called node) and the runtime. +## Migrate from EVM -If the system were a monolithic protocol, any modification would require updating the entire system. Instead, Polkadot achieves true upgradeability by defining an immutable meta-protocol (the client) and a protocol (the runtime) that can be upgraded independently. +The [REVM backend](https://github.com/bluealloy/revm){target=\_blank} integrates a complete Rust implementation of the EVM, enabling Solidity contracts to run unchanged on Polkadot's smart contract platform. -This separation gives the [Polkadot Relay Chain](/polkadot-protocol/architecture/polkadot-chain){target=\_blank} and all connected [parachains](/polkadot-protocol/architecture/parachains){target=\_blank} an evolutionary advantage over other blockchain platforms. +REVM allows developers to use their existing Ethereum tooling and infrastructure to build on Polkadot. Choose REVM to: -## Architectural Principles +- Migrate existing Ethereum contracts without modifications. +- Retain exact EVM behavior for audit tools. +- Use developer tools that rely upon inspecting EVM bytecode. +- Prioritize rapid deployment over optimization. +- Work with established Ethereum infrastructure and tooling to build on Polkadot. -The Polkadot SDK-based blockchain architecture is fundamentally built on two distinct yet interconnected components: +REVM enables Ethereum developers to seamlessly migrate to Polkadot, achieving performance and fee improvements without modifying their existing contracts or developer tooling stack. -- Client (Meta-protocol): - - Handles the foundational infrastructure of the blockchain. - - Manages runtime execution, networking, consensus, and other off-chain components. - - Provides an immutable base layer that ensures network stability. - - Upgradable only through hard forks. +## Upgrade to PolkaVM -- Runtime (Protocol): - - Defines the blockchain's state transition logic. - - Determines the specific rules and behaviors of the blockchain. - - Compiled to WebAssembly (Wasm) for platform-independent execution. - - Capable of being upgraded without network-wide forking. +[**PolkaVM**](https://github.com/paritytech/polkavm){target=\_blank} is a custom virtual machine optimized for performance with [RISC-V-based](https://en.wikipedia.org/wiki/RISC-V){target=\_blank} architecture, supporting Solidity and additional high-performance languages. It serves as the core execution environment, integrated directly within the runtime. Choose the PolkaVM for: -### Advantages of this Architecture +- An efficient interpreter for immediate code execution. +- A planned [Just In Time (JIT)](https://en.wikipedia.org/wiki/Just-in-time_compilation){target=\_blank} compiler for optimized performance. +- Dual-mode execution capability, allowing selection of the most appropriate backend for specific workloads. +- Optimized performance for short-running contract calls through the interpreter. -- **Forkless upgrades**: Runtime can be updated without disrupting the entire network. -- **Modularity**: Clear separation allows independent development of client and runtime. -- **Flexibility**: Enables rapid iteration and evolution of blockchain logic. -- **Performance**: WebAssembly compilation provides efficient, cross-platform execution. +The interpreter remains particularly beneficial for contracts with minimal code execution, as it enables immediate code execution through lazy interpretation. -## Node (Client) +## Architecture -The node, also known as the client, is the core component responsible for executing the Wasm runtime and orchestrating various essential blockchain components. It ensures the correct execution of the state transition function and manages multiple critical subsystems, including: +The following key components of PolkaVM work together to enable Ethereum compatibility on Polkadot-based chains. -- **Wasm execution**: Runs the blockchain runtime, which defines the state transition rules. -- **Database management**: Stores blockchain data. -- **Networking**: Facilitates peer-to-peer communication, block propagation, and transaction gossiping. -- **Transaction pool (Mempool)**: Manages pending transactions before they are included in a block. -- **Consensus mechanism**: Ensures agreement on the blockchain state across nodes. -- **RPC services**: Provides external interfaces for applications and users to interact with the node. +### Revive Pallet -## Runtime +[**`pallet_revive`**](https://paritytech.github.io/polkadot-sdk/master/pallet_revive/index.html){target=\_blank} is a runtime module that executes smart contracts by adding extrinsics, runtime APIs, and logic to convert Ethereum-style transactions into formats compatible with Polkadot SDK-based blockchains. It processes Ethereum-style transactions through the following workflow: -The runtime is more than just a set of rules. It's the fundamental logic engine that defines a blockchain's entire behavior. In Polkadot SDK-based blockchains, the runtime represents a complete, self-contained description of the blockchain's state transition function. +```mermaid +sequenceDiagram + participant User as User/dApp + participant Proxy as Ethereum JSON RPC Proxy + participant Chain as Blockchain Node + participant Pallet as pallet_revive + + User->>Proxy: Submit Ethereum Transaction + Proxy->>Chain: Repackage as Polkadot Compatible Transaction + Chain->>Pallet: Process Transaction + Pallet->>Pallet: Decode Ethereum Transaction + Pallet->>Pallet: Execute Contract via PolkaVM + Pallet->>Chain: Return Results + Chain->>Proxy: Forward Results + Proxy->>User: Return Ethereum-compatible Response +``` -### Characteristics +This proxy-based approach eliminates the need for node binary modifications, maintaining compatibility across different client implementations. Preserving the original Ethereum transaction payload simplifies the adaptation of existing tools, which can continue processing familiar transaction formats. -The runtime is distinguished by three key characteristics: +### PolkaVM Design Fundamentals -- **Business logic**: Defines the complete application-specific blockchain behavior. -- **WebAssembly compilation**: Ensures platform-independent, secure execution. -- **On-chain storage**: Stored within the blockchain's state, allowing dynamic updates. +PolkaVM differs from the EVM in two key ways that make it faster, more hardware-efficient, and easier to extend: -### Key Functions +- **Register-based design**: Instead of a stack machine, PolkaVM uses a RISC-V–style register model. This design: -The runtime performs several critical functions, such as: + - Uses a fixed set of registers to pass arguments, not an infinite stack. + - Maps cleanly to real hardware like x86-64. + - Simplifies compilation and boosts runtime efficiency. + - Enables tighter control over register allocation and performance tuning. -- Define state transition rules. -- Implement blockchain-specific logic. -- Manage account interactions. -- Control transaction processing. -- Define governance mechanisms. -- Handle custom pallets and modules. +- **64-bit word size**: PolkaVM runs on a native 64-bit word size, aligning directly with modern CPUs. This design: -## Communication Between Node and Runtime + - Executes arithmetic operations with direct hardware support. + - Maintains compatibility with Solidity’s 256-bit types via YUL translation. + - Accelerates computation-heavy workloads through native word alignment. + - Integrates easily with low-level, performance-focused components. -The client and runtime communicate exclusively using [SCALE-encoded](/polkadot-protocol/parachain-basics/data-encoding){target=\_blank} communication. This ensures efficient and compact data exchange between the two components. +## Where To Go Next -### Runtime APIs +
-The Runtime API consists of well-defined functions and constants a client assumes are implemented in the Runtime Wasm blob. These APIs enable the client to interact with the runtime to execute blockchain operations and retrieve information. The client invokes these APIs to: +- Learn __Contract Deployment__ -- Build, execute, and finalize blocks. -- Access metadata. -- Access consensus related information. -- Handle transaction execution. + --- -### Host Functions + Learn how REVM and PVM compare for compiling and deploying smart contracts. -During execution, the runtime can access certain external client functionalities via host functions. The specific functions the client exposes allow the runtime to perform operations outside the WebAssembly domain. Host functions enable the runtime to: + [:octicons-arrow-right-24: Reference](/smart-contracts/for-eth-devs/contract-deployment/) -- Perform cryptographic operations. -- Access the current blockchain state. -- Handle storage modifications. -- Allocate memory. +
--- -Page Title: On-Chain Governance Overview +Page Title: Fork a Parachain Using Chopsticks -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-governance.md -- Canonical (HTML): https://docs.polkadot.com/reference/governance/ -- Summary: Discover Polkadot’s cutting-edge OpenGov system, enabling transparent, decentralized decision-making through direct democracy and flexible governance tracks. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-fork-a-parachain.md +- Canonical (HTML): https://docs.polkadot.com/parachains/testing/fork-a-parachain/ +- Summary: Simplify Polkadot SDK development with Chopsticks. Learn essential features, how to install Chopsticks, and how to configure local blockchain forks. -# On-Chain Governance +# Fork a Parachain Using Chopsticks ## Introduction -Polkadot’s governance system exemplifies decentralized decision-making, empowering its community of stakeholders to shape the network’s future through active participation. The latest evolution, OpenGov, builds on Polkadot’s foundation by providing a more inclusive and efficient governance model. - -This guide will explain the principles and structure of OpenGov and walk you through its key components, such as Origins, Tracks, and Delegation. You will learn about improvements over earlier governance systems, including streamlined voting processes and enhanced stakeholder participation. - -With OpenGov, Polkadot achieves a flexible, scalable, and democratic governance framework that allows multiple proposals to proceed simultaneously, ensuring the network evolves in alignment with its community's needs. - -## Governance Evolution +[Chopsticks](https://github.com/AcalaNetwork/chopsticks/){target=\_blank}, developed by the [Acala Foundation](https://github.com/AcalaNetwork){target=\_blank}, is a versatile tool tailored for developers working on Polkadot SDK-based blockchains. With Chopsticks, you can fork live chains locally, replay blocks to analyze extrinsics, and simulate complex scenarios like XCM interactions all without deploying to a live network. -Polkadot’s governance journey began with [Governance V1](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#governance-summary){target=\_blank}, a system that proved effective in managing treasury funds and protocol upgrades. However, it faced limitations, such as: +This guide walks you through installing Chopsticks and provides information on configuring a local blockchain fork. By streamlining testing and experimentation, Chopsticks empowers developers to innovate and accelerate their blockchain projects within the Polkadot ecosystem. -- Slow voting cycles, causing delays in decision-making. -- Inflexibility in handling multiple referendums, restricting scalability. +For additional support and information, please reach out through [GitHub Issues](https://github.com/AcalaNetwork/chopsticks/issues){target=_blank}. -To address these challenges, Polkadot introduced OpenGov, a governance model designed for greater inclusivity, efficiency, and scalability. OpenGov replaces the centralized structures of Governance V1, such as the Council and Technical Committee, with a fully decentralized and dynamic framework. +!!! warning + Chopsticks uses [Smoldot](https://github.com/smol-dot/smoldot){target=_blank} light client, which only supports the native Polkadot SDK API. Consequently, a Chopsticks-based fork doesn't support Ethereum JSON-RPC calls, meaning you cannot use it to fork your chain and connect Metamask. -For a full comparison of the historic and current governance models, visit the [Gov1 vs. Polkadot OpenGov](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#gov1-vs-polkadot-opengov){target=\_blank} section of the Polkadot Wiki. +## Prerequisites -## OpenGov Key Features +Before you begin, ensure you have the following installed: -OpenGov transforms Polkadot’s governance into a decentralized, stakeholder-driven model, eliminating centralized decision-making bodies like the Council. Key enhancements include: +- [Node.js](https://nodejs.org/en/){target=\_blank}. +- A package manager such as [npm](https://www.npmjs.com/){target=\_blank}, which should be installed with Node.js by default, or [Yarn](https://yarnpkg.com/){target=\_blank}. -- **Decentralization**: Shifts all decision-making power to the public, ensuring a more democratic process. -- **Enhanced delegation**: Allows users to delegate their votes to trusted experts across specific governance tracks. -- **Simultaneous referendums**: Multiple proposals can progress at once, enabling faster decision-making. -- **Polkadot Technical Fellowship**: A broad, community-driven group replacing the centralized Technical Committee. +## Install Chopsticks -This new system ensures Polkadot governance remains agile and inclusive, even as the ecosystem grows. +You can install Chopsticks globally or locally in your project. Choose the option that best fits your development workflow. This documentation explains the features of Chopsticks version `1.2.2`. Make sure you're using the correct version to match these instructions. -## Origins and Tracks +### Global Installation -In OpenGov, origins and tracks are central to managing proposals and votes. +To install Chopsticks globally, allowing you to use it across multiple projects, run: -- **Origin**: Determines the authority level of a proposal (e.g., Treasury, Root) which decides the track of all referendums from that origin. -- **Track**: Define the procedural flow of a proposal, such as voting duration, approval thresholds, and enactment timelines. +```bash +npm i -g @acala-network/chopsticks@1.2.2 +``` -Developers must be aware that referendums from different origins and tracks will take varying amounts of time to reach approval and enactment. The [Polkadot Technical Fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} has the option to shorten this timeline by whitelisting a proposal and allowing it to be enacted through the [Whitelist Caller](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#whitelisted-caller){target=\_blank} origin. +Now, you should be able to run the `chopsticks` command from your terminal. -Visit [Origins and Tracks Info](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#origins-and-tracks){target=\_blank} for details on current origins and tracks, associated terminology, and parameters. +### Local Installation -## Referendums +To use Chopsticks in a specific project, first create a new directory and initialize a Node.js project: -In OpenGov, anyone can submit a referendum, fostering an open and participatory system. The timeline for a referendum depends on the privilege level of the origin with more significant changes offering more time for community voting and participation before enactment. +```bash +mkdir my-chopsticks-project +cd my-chopsticks-project +npm init -y +``` -The timeline for an individual referendum includes four distinct periods: +Then, install Chopsticks as a local dependency: -- **Lead-in**: A minimum amount of time to allow for community participation, available room in the origin, and payment of the decision deposit. Voting is open during this period. -- **Decision**: Voting continues. -- **Confirmation**: Referendum must meet [approval and support](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#approval-and-support){target=\_blank} criteria during entire period to avoid rejection. -- **Enactment**: Changes approved by the referendum are executed. +```bash +npm i @acala-network/chopsticks@1.2.2 +``` -### Vote on Referendums +Finally, you can run Chopsticks using the `npx` command. To see all available options and commands, run it with the `--help` flag: -Voters can vote with their tokens on each referendum. Polkadot uses a voluntary token locking mechanism, called conviction voting, as a way for voters to increase their voting power. A token holder signals they have a stronger preference for approving a proposal based upon their willingness to lock up tokens. Longer voluntary token locks are seen as a signal of continual approval and translate to increased voting weight. +```bash +npx @acala-network/chopsticks --help +``` -See [Voting on a Referendum](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank} for a deeper look at conviction voting and related token locks. +## Configure Chopsticks -### Delegate Voting Power +To run Chopsticks, you need to configure some parameters. This can be set either through using a configuration file or the command line interface (CLI). The parameters that can be configured are as follows: -The OpenGov system also supports multi-role delegations, allowing token holders to assign their voting power on different tracks to entities with expertise in those areas. +- **`genesis`**: The link to a parachain's raw genesis file to build the fork from, instead of an endpoint. +- **`timestamp`**: Timestamp of the block to fork from. +- **`endpoint`**: The endpoint of the parachain to fork. +- **`block`**: Use to specify at which block hash or number to replay the fork. +- **`wasm-override`**: Path of the Wasm to use as the parachain runtime, instead of an endpoint's runtime. +- **`db`**: Path to the name of the file that stores or will store the parachain's database. +- **`config`**: Path or URL of the config file. +- **`port`**: The port to expose an endpoint on. +- **`build-block-mode`**: How blocks should be built in the fork: batch, manual, instant. +- **`import-storage`**: A pre-defined JSON/YAML storage path to override in the parachain's storage. +- **`allow-unresolved-imports`**: Whether to allow Wasm unresolved imports when using a Wasm to build the parachain. +- **`html`**: Include to generate storage diff preview between blocks. +- **`mock-signature-host`**: Mock signature host so that any signature starts with `0xdeadbeef` and filled by `0xcd` is considered valid. -For example, if a token holder lacks the technical knowledge to evaluate proposals on the [Root track](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#root){target=\_blank}, they can delegate their voting power for that track to an expert they trust to vote in the best interest of the network. This ensures informed decision-making across tracks while maintaining flexibility for token holders. +### Configuration File -Visit [Multirole Delegation](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#multirole-delegation){target=\_blank} for more details on delegating voting power. +The Chopsticks source repository includes a collection of [YAML](https://yaml.org/){target=\_blank} files that can be used to set up various Polkadot SDK chains locally. You can download these configuration files from the [repository's `configs` folder](https://github.com/AcalaNetwork/chopsticks/tree/master/configs){target=\_blank}. -### Cancel a Referendum +An example of a configuration file for Polkadot is as follows: -Polkadot OpenGov has two origins for rejecting ongoing referendums: +{% raw %} +```yaml +endpoint: + - wss://rpc.ibp.network/polkadot + - wss://polkadot-rpc.dwellir.com +mock-signature-host: true +block: ${env.POLKADOT_BLOCK_NUMBER} +db: ./db.sqlite +runtime-log-level: 5 -- [**Referendum Canceller**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-canceller){target=\_blank}: Cancels an active referendum when non-malicious errors occur and refunds the deposits to the originators. -- [**Referendum Killer**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-killer){target=\_blank}: Used for urgent, malicious cases this origin instantly terminates an active referendum and slashes deposits. +import-storage: + System: + Account: + - - - 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY + - providers: 1 + data: + free: '10000000000000000000' + ParasDisputes: + $removePrefix: ['disputes'] # those can makes block building super slow -See [Cancelling, Killing, and Blacklisting](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#cancelling-killing--blacklisting){target=\_blank} for additional information on rejecting referendums. +``` +{% endraw %} -## Additional Resources +The configuration file allows you to modify the storage of the forked network by rewriting the pallet, state component and value that you want to change. For example, Polkadot's file rewrites Alice's `system.Account` storage so that the free balance is set to `10000000000000000000`. -- **[Democracy pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/democracy/src){target=\_blank}**: Handles administration of general stakeholder voting. -- **[Gov2: Polkadot’s Next Generation of Decentralised Governance](https://medium.com/polkadot-network/gov2-polkadots-next-generation-of-decentralised-governance-4d9ef657d11b){target=\_blank}**: Medium article by Gavin Wood. -- **[Polkadot Direction](https://matrix.to/#/#Polkadot-Direction:parity.io){target=\_blank}**: Matrix Element client. -- **[Polkassembly](https://polkadot.polkassembly.io/){target=\_blank}**: OpenGov dashboard and UI. -- **[Polkadot.js Apps Governance](https://polkadot.js.org/apps/#/referenda){target=\_blank}**: Overview of active referendums. +### CLI Flags +Alternatively, all settings (except for genesis and timestamp) can be configured via command-line flags, providing a comprehensive method to set up the environment. ---- +## WebSocket Commands -Page Title: Oracles +Chopstick's internal WebSocket server has special endpoints that allow the manipulation of the local Polkadot SDK chain. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-oracles.md -- Canonical (HTML): https://docs.polkadot.com/parachains/integrations/oracles/ -- Summary: Learn about blockchain oracles, the essential bridges connecting blockchains with real-world data for decentralized applications in the Polkadot ecosystem. +These are the methods that can be invoked and their parameters: -# Oracles +- **dev_newBlock** (newBlockParams): Generates one or more new blocks. -## What is a Blockchain Oracle? + === "Parameters" -Oracles enable blockchains to access external data sources. Since blockchains operate as isolated networks, they cannot natively interact with external systems - this limitation is known as the "blockchain oracle problem." Oracles solves this by extracting data from external sources (like APIs, IoT devices, or other blockchains), validating it, and submitting it on-chain. + - **`newBlockParams` ++"NewBlockParams"++**: The parameters to build the new block with. Where the `NewBlockParams` interface includes the following properties. -While simple oracle implementations may rely on a single trusted provider, more sophisticated solutions use decentralized networks where multiple providers stake assets and reach consensus on data validity. Typical applications include DeFi price feeds, weather data for insurance contracts, and cross-chain asset verification. + - **`count` ++"number"++**: The number of blocks to build. + - **`dmp` ++"{ msg: string, sentAt: number }[]"++**: The downward messages to include in the block. + - **`hrmp` ++"Record"++**: The horizontal messages to include in the block. + - **`to` ++"number"++**: The block number to build to. + - **`transactions` ++"string[]"++**: The transactions to include in the block. + - **`ump` ++"Record"++**: The upward messages to include in the block. + - **`unsafeBlockHeight` ++"number"++**: Build block using a specific block height (unsafe). -## Oracle Implementations + === "Example" -
+ ```js + import { ApiPromise, WsProvider } from '@polkadot/api'; -- __Acurast__ + async function main() { + const wsProvider = new WsProvider('ws://localhost:8000'); + const api = await ApiPromise.create({ provider: wsProvider }); + await api.isReady; + await api.rpc('dev_newBlock', { count: 1 }); + } - --- + main(); - Acurast is a decentralized, serverless cloud platform that uses a distributed network of mobile devices for oracle services, addressing centralized trust and data ownership issues. In the Polkadot ecosystem, it allows developers to define off-chain data and computation needs, which are processed by these devices acting as decentralized oracle nodes, delivering results to Substrate (Wasm) and EVM environments. + ``` - [:octicons-arrow-right-24: Reference](https://acurast.com/){target=\_blank} +- **dev_setBlockBuildMode** (buildBlockMode): Sets block build mode. -
+ === "Parameter" + + - **`buildBlockMode` ++"BuildBlockMode"++**: The build mode. Can be any of the following modes: + ```ts + export enum BuildBlockMode { + Batch = 'Batch', /** One block per batch (default) */ + Instant = 'Instant', /** One block per transaction */ + Manual = 'Manual', /** Only build when triggered */ + } + ``` + + === "Example" ---- + ```js + import { ApiPromise, WsProvider } from '@polkadot/api'; -Page Title: Overview of FRAME + async function main() { + const wsProvider = new WsProvider('ws://localhost:8000'); + const api = await ApiPromise.create({ provider: wsProvider }); + await api.isReady; + await api.rpc('dev_setBlockBuildMode', 'Instant'); + } -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime.md -- Canonical (HTML): https://docs.polkadot.com/parachains/customize-runtime/ -- Summary: Learn how Polkadot SDK’s FRAME framework simplifies blockchain development with modular pallets and support libraries for efficient runtime design. + main(); -# Customize Your Runtime + ``` -## Introduction +- **dev_setHead** (hashOrNumber): Sets the head of the blockchain to a specific hash or number. -A blockchain runtime is more than just a fixed set of rules—it's a dynamic foundation that you can shape to match your specific needs. With Polkadot SDK's [FRAME (Framework for Runtime Aggregation of Modularized Entities)](/reference/glossary/#frame-framework-for-runtime-aggregation-of-modularized-entities){target=\_blank}, customizing your runtime is straightforward and modular. Instead of building everything from scratch, you combine pre-built pallets with your own custom logic to create a runtime suited to your blockchain's purpose. + === "Parameter" -This overview explains how runtime customization works, introduces the building blocks you'll use, and guides you through the key patterns for extending your runtime. + - **`hashOrNumber` ++"string | number"++**: The block hash or number to set as head. -## Understanding Your Runtime + === "Example" -The runtime is the core logic of your blockchain—it processes transactions, manages state, and enforces the rules that govern your network. When a transaction arrives at your blockchain, the [`frame_executive`](https://paritytech.github.io/polkadot-sdk/master/frame_executive/index.html){target=\_blank} pallet receives it and routes it to the appropriate pallet for execution. + ```js + import { ApiPromise, WsProvider } from '@polkadot/api'; -Think of your runtime as a collection of specialized modules, each handling a different aspect of your blockchain. Need token balances? Use the Balances pallet. Want governance? Add the Governance pallets. Need something custom? Create your own pallet. By mixing and matching these modules, you build a runtime that's efficient, secure, and tailored to your use case. + async function main() { + const wsProvider = new WsProvider('ws://localhost:8000'); + const api = await ApiPromise.create({ provider: wsProvider }); + await api.isReady; + await api.rpc('dev_setHead', 500); + } -## Runtime Architecture + main(); -The following diagram shows how FRAME components work together to form your runtime: + ``` -![](/images/parachains/customize-runtime/index/frame-overview-01.webp) +- **dev_setRuntimeLogLevel** (runtimeLogLevel): Sets the runtime log level. -The main components are: + === "Parameter" -- **`frame_executive`**: Routes all incoming transactions to the correct pallet for execution. -- **Pallets**: Domain-specific modules that implement your blockchain's features and business logic. -- **`frame_system`**: Provides core runtime primitives and storage. -- **`frame_support`**: Utilities and macros that simplify pallet development. + - **`runtimeLogLevel` ++"number"++**: The runtime log level to set. -## Building Blocks: Pallets + === "Example" -[Pallets](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/pallet/index.html){target=\_blank} are the fundamental units of runtime customization. Each pallet encapsulates specific functionality and can be independently developed, tested, and integrated. + ```js + import { ApiPromise, WsProvider } from '@polkadot/api'; -A pallet can implement virtually any blockchain feature you need: + async function main() { + const wsProvider = new WsProvider('ws://localhost:8000'); + const api = await ApiPromise.create({ provider: wsProvider }); + await api.isReady; + await api.rpc('dev_setRuntimeLogLevel', 1); + } -- Expose new transactions that users can submit. -- Store data on-chain. -- Enforce business rules and validation logic. -- Emit events to notify users of state changes. -- Handle errors gracefully. + main(); -### Pre-Built Pallets vs. Custom Pallets + ``` -FRAME provides a comprehensive library of [pre-built pallets](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame){target=\_blank} for common blockchain features, including consensus, staking, balances, governance, and more. These pallets are battle-tested, optimized, and ready to use. +- **dev_setStorage** (values, blockHash): Creates or overwrites the value of any storage. -However, you're not limited to pre-built functionality. When pre-built pallets don't meet your needs, you can create custom pallets with entirely custom logic. The real power of FRAME is the flexibility to use pre-built modules for standard features while building your own for unique requirements. + === "Parameters" -### Pallet Structure + - **`values` ++"object"++**: JSON object resembling the path to a storage value. + - **`blockHash` ++"string"++**: The block hash to set the storage value. -FRAME uses Rust macros extensively, allowing you to focus on your pallet's logic while the framework handles boilerplate and integration code. + === "Example" -A typical pallet looks like this: + ```js + import { ApiPromise, WsProvider } from '@polkadot/api'; -```rust -pub use pallet::*; + import { Keyring } from '@polkadot/keyring'; + async function main() { + const wsProvider = new WsProvider('ws://localhost:8000'); + const api = await ApiPromise.create({ provider: wsProvider }); + await api.isReady; + const keyring = new Keyring({ type: 'ed25519' }); + const bob = keyring.addFromUri('//Bob'); + const storage = { + System: { + Account: [[[bob.address], { data: { free: 100000 }, nonce: 1 }]], + }, + }; + await api.rpc('dev_setStorage', storage); + } -#[frame_support::pallet] -pub mod pallet { - use frame_support::pallet_prelude::*; - use frame_system::pallet_prelude::*; + main(); - #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] - pub struct Pallet(_); + ``` - #[pallet::config] // snip - #[pallet::event] // snip - #[pallet::error] // snip - #[pallet::storage] // snip - #[pallet::call] // snip -} -``` +- **dev_timeTravel** (date): Sets the timestamp of the block to a specific date". -Every pallet can implement these core macros: + === "Parameter" -- **`#[frame_support::pallet]`**: Marks your module as a FRAME pallet. -- **`#[pallet::pallet]`**: Designates the struct that holds pallet metadata. -- **`#[pallet::config]`**: Defines configuration and associated types. -- **`#[pallet::event]`**: Defines events emitted by your pallet. -- **`#[pallet::error]`**: Defines error types your pallet can return. -- **`#[pallet::storage]`**: Defines on-chain storage items. -- **`#[pallet::call]`**: Defines dispatchable functions (transactions). + - **`date` ++"string"++**: Timestamp or date string to set. All future blocks will be sequentially created after this point in time. -For a comprehensive reference, see the [`pallet_macros` documentation](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/index.html){target=\_blank}. + === "Example" -## How Runtime Customization Works + ```js + import { ApiPromise, WsProvider } from '@polkadot/api'; -Customizing your runtime typically follows these patterns: + async function main() { + const wsProvider = new WsProvider('ws://localhost:8000'); + const api = await ApiPromise.create({ provider: wsProvider }); + await api.isReady; + await api.rpc('dev_timeTravel', '2030-08-15T00:00:00'); + } -**Adding Pre-Built Pallets**: Select pallets from the FRAME library and integrate them into your runtime configuration. This is the fastest way to add functionality. + main(); -**Creating Custom Pallets**: Write custom pallets for features that don't exist in the pre-built library. Custom pallets follow the same structure as pre-built ones and integrate seamlessly. + ``` -**Combining Multiple Pallets**: Layer multiple pallets together to create complex behaviors. Pallets can call each other and share storage when needed. +## Where to Go Next -**Configuring Pallet Parameters**: Most pallets are configurable—you can adjust their behavior through configuration traits without modifying their code. +
-The following diagram illustrates how pallets combine to form a complete runtime: +- Tutorial __Fork a Chain with Chopsticks__ -![](/images/parachains/customize-runtime/index/frame-overview-02.webp) + --- -## Starting Templates + Visit this guide for step-by-step instructions for configuring and interacting with your forked chain. -The easiest way to begin customizing your runtime is with a starter template. These templates provide a pre-configured foundation so you can focus on customization rather than setup. + [:octicons-arrow-right-24: Reference](/tutorials/polkadot-sdk/testing/fork-live-chains/) -- **[Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank}**: The recommended choice for most developers, it includes pre-configured pallets for common features (balances, block production, governance), a complete runtime setup, and built-in parachain consensus support. This template offers the best balance of features and learning opportunities. +
-- **[Polkadot SDK Minimal Template](https://github.com/paritytech/polkadot-sdk-minimal-template){target=\_blank}**: Provides a bare-bones runtime with only essential components. Choose this if you want maximum flexibility and prefer building from a clean slate. -- **[Polkadot SDK Solochain Template](https://github.com/paritytech/polkadot-sdk/tree/master/templates/solochain){target=\_blank}**: Designed for building standalone blockchains with moderate features, simple consensus, and several core pallets. Use this if you want a sovereign blockchain independent of a relay chain. +--- -- **[OpenZeppelin Runtime Templates](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\_blank}**: Provides security-focused configurations following industry best practices. The [generic-template](https://github.com/OpenZeppelin/polkadot-runtime-templates/tree/main/generic-template){target=\_blank} includes curated pallet selections and production-ready defaults—ideal if security is your top priority. +Page Title: Get Started with Parachain Development -## Key Customization Scenarios +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-get-started.md +- Canonical (HTML): https://docs.polkadot.com/parachains/get-started/ +- Summary: Practical examples and tutorials for building and deploying Polkadot parachains, covering everything from launch to customization and cross-chain messaging. -This section covers the most common customization patterns you'll encounter: +# Get Started -- **[Add Existing Pallets to Your Runtime](/parachains/customize-runtime/add-existing-pallets/)**: Integrate pre-built pallets from the FRAME library with minimal configuration. +The following sections provide practical recipes for building parachains on Polkadot—each focused on specific development scenarios with step-by-step, hands-on examples. -- **[Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/)**: Run multiple instances of the same pallet with different configurations—useful for multi-token systems or parallel features. +## Quick Start Guides -- **[Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/)**: Enable smart contract execution on your parachain using Contracts pallets. +Quick start guides help developers set up and interact with the Polkadot parachain ecosystem using various tools and frameworks. -- **[Create Custom Pallets](/parachains/customize-runtime/pallet-development/create-a-pallet/)**: Build entirely custom pallets for features unique to your blockchain. +| Tutorial | Tools | Description | +| :--------------------------------------------------------------------------------------------: | :----------------------------: | :---------------------------------------------------------------------: | +| [Set Up the Parachain Template](/parachains/launch-a-parachain/set-up-the-parachain-template/) | Polkadot SDK | Learn how to set up and run the Polkadot SDK Parachain Template locally | +| [Launch a Local Parachain](/parachains/testing/run-a-parachain-network/) | Zombienet, Chopsticks | Set up a local development environment for testing | +| [Connect to Polkadot](/chain-interactions/query-on-chain-data/query-sdks/) | Polkadot.js, Substrate Connect | Connect your application to Polkadot networks | +| [Fork an Existing Parachain](/parachains/testing/fork-a-parachain/) | Chopsticks | Create a local fork of a live parachain for testing | -- **[Test Your Runtime](/parachains/customize-runtime/pallet-development/pallet-testing/)**: Unit test pallets and mock complete runtimes to ensure everything works correctly. +## Launch a Simple Parachain +Learn the fundamentals of launching and deploying a parachain to the Polkadot network. ---- +| Tutorial | Description | +| :--------------------------------------------------------------------------------------------: | :-----------------------------------------------------------------------: | +| [Set Up the Parachain Template](/parachains/launch-a-parachain/set-up-the-parachain-template/) | Polkadot SDK | +| [Deploy to Polkadot](/parachains/launch-a-parachain/deploy-to-polkadot/) | Step-by-step tutorial to deploying your parachain to Polkadot | +| [Obtain Coretime](/parachains/launch-a-parachain/obtain-coretime/) | Learn how to acquire blockspace using Polkadot's coretime model (RegionX) | -Page Title: Overview of the Polkadot Relay Chain +## Customize Your Runtime -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-relay-chain.md -- Canonical (HTML): https://docs.polkadot.com/reference/polkadot-hub/consensus-and-security/relay-chain/ -- Summary: Explore Polkadot's core architecture, including its multi-chain vision, shared security, and the DOT token's governance and staking roles. +Build custom functionality for your parachain by composing and creating pallets. -# Overview +| Tutorial | Description | +| :-------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------: | +| [Add Existing Pallets to the Runtime](/parachains/customize-runtime/add-existing-pallets/) | Integrate pre-built pallets from the FRAME ecosystem | +| [Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/) | Configure and use multiple instances of the same pallet | +| [Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/) | Enable smart contract capabilities using Contracts or EVM pallets | -## Introduction +### Pallet Development -Polkadot is a next-generation blockchain protocol designed to support a multi-chain future by enabling secure communication and interoperability between different blockchains. Built as a Layer-0 protocol, Polkadot introduces innovations like application-specific Layer-1 chains ([parachains](/polkadot-protocol/architecture/parachains/){targe=\_blank}), shared security through [Nominated Proof of Stake (NPoS)](/reference/glossary/#nominated-proof-of-stake-npos){target=\_blank}, and cross-chain interactions via its native [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank}. +Deep dive into creating and managing custom pallets for your parachain. -This guide covers key aspects of Polkadot’s architecture, including its high-level protocol structure, blockspace commoditization, and the role of its native token, DOT, in governance, staking, and resource allocation. +| Tutorial | Description | +| :--------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------: | +| [Create a Custom Pallet](/parachains/customize-runtime/pallet-development/create-a-pallet/) | Build a pallet from scratch with custom logic | +| [Mock Your Runtime](/parachains/customize-runtime/pallet-development/mock-runtime/) | Set up a mock runtime environment for testing | +| [Pallet Unit Testing](/parachains/customize-runtime/pallet-development/pallet-testing/) | Write comprehensive tests for your pallet logic | +| [Add Your Custom Pallet to the Runtime](/parachains/customize-runtime/pallet-development/add-pallet-to-runtime/) | Integrate your custom pallet into your parachain runtime | +| [Benchmark the Custom Pallet](/parachains/customize-runtime/pallet-development/benchmark-pallet/) | Measure and optimize pallet performance with benchmarking | -## Polkadot 1.0 +## Testing -Polkadot 1.0 represents the state of Polkadot as of 2023, coinciding with the release of [Polkadot runtime v1.0.0](https://github.com/paritytech/polkadot/releases/tag/v1.0.0){target=\_blank}. This section will focus on Polkadot 1.0, along with philosophical insights into network resilience and blockspace. +Test your parachain in various environments before production deployment. -As a Layer-0 blockchain, Polkadot contributes to the multi-chain vision through several key innovations and initiatives, including: +| Tutorial | Description | +| :---------------------------------------------------------------------: | :-----------------------------------------------------: | +| [Fork a Parachain](/parachains/testing/fork-a-parachain/) | Use Chopsticks to create a local fork for testing | +| [Run a Parachain Network](/parachains/testing/run-a-parachain-network/) | Launch a complete parachain test network with Zombienet | -- **Application-specific Layer-1 blockchains (parachains)**: Polkadot's sharded network allows for parallel transaction processing, with shards that can have unique state transition functions, enabling custom-built L1 chains optimized for specific applications. +## Runtime Upgrades and Maintenance -- **Shared security and scalability**: L1 chains connected to Polkadot benefit from its [Nominated Proof of Stake (NPoS)](/reference/polkadot-hub/consensus-and-security/pos-consensus/#nominated-proof-of-stake){target=\_blank} system, providing security out-of-the-box without the need to bootstrap their own. +Manage your parachain's lifecycle with forkless upgrades and maintenance operations. -- **Secure interoperability**: Polkadot's native interoperability enables seamless data and value exchange between parachains. This interoperability can also be used outside of the ecosystem for bridging with external networks. +| Tutorial | Description | +| :-----------------------------------------------------------------------: | :--------------------------------------------------: | +| [Runtime Upgrades](/parachains/runtime-maintenance/runtime-upgrades/) | Perform forkless runtime upgrades via governance | +| [Storage Migrations](/parachains/runtime-maintenance/storage-migrations/) | Safely migrate storage when updating runtime logic | +| [Unlock Parachains](/parachains/runtime-maintenance/unlock-parachains/) | Understand parachain lifecycle and unlock mechanisms | -- **Resilient infrastructure**: Decentralized and scalable, Polkadot ensures ongoing support for development and community initiatives via its on-chain [treasury](https://wiki.polkadot.com/learn/learn-polkadot-opengov-treasury/){target=\_blank} and governance. +## Interoperability -- **Rapid L1 development**: The [Polkadot SDK](/reference/parachains/){target=\_blank} allows fast, flexible creation and deployment of Layer-1 chains. +Configure your parachain for cross-chain communication using XCM (Cross-Consensus Messaging). -- **Cultivating the next generation of Web3 developers**: Polkadot supports the growth of Web3 core developers through initiatives such as. +| Tutorial | Description | +| :--------------------------------------------------------------------------------------------------------: | :----------------------------------------------------: | +| [Open HRMP Channels Between Parachains](/parachains/interoperability/channels-between-parachains/) | Establish communication channels with other parachains | +| [Open HRMP Channels with System Parachains](/parachains/interoperability/channels-with-system-parachains/) | Connect with Asset Hub and other system parachains | - - [Polkadot Blockchain Academy](https://polkadot.com/blockchain-academy){target=\_blank} - - [EdX courses](https://www.edx.org/school/web3x){target=\_blank} - - Rust and Substrate courses (coming soon) +## Integrations -### High-Level Architecture +Integrate your parachain with essential ecosystem tools and services. -Polkadot features a chain that serves as the central component of the system. This chain is depicted as a ring encircled by several parachains that are connected to it. +| Tutorial | Description | +| :--------------------------------------------: | :----------------------------------------------------: | +| [Wallets](/parachains/integrations/wallets/) | Integrate wallet support for user interactions | +| [Indexers](/parachains/integrations/indexers/) | Set up indexing solutions for querying blockchain data | +| [Oracles](/parachains/integrations/oracles/) | Connect your parachain to off-chain data sources | -According to Polkadot's design, any blockchain that can compile to WebAssembly (Wasm) and adheres to the Parachains Protocol becomes a parachain on the Polkadot network. +## Additional Resources -Here’s a high-level overview of the Polkadot protocol architecture: +- [Polkadot SDK Documentation](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/index.html) +- [Polkadot Wiki - Parachains](https://wiki.polkadot.network/docs/learn-parachains/) -![](/images/reference/polkadot-hub/consensus-and-security/relay-chain/relay-chain-01.webp){ style="background:white" } -Parachains propose blocks to Polkadot validators, who check for availability and validity before finalizing them. With the relay chain providing security, collators—full nodes of parachains—can focus on their tasks without needing strong incentives. +--- -The [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank} allows parachains to exchange messages freely, leveraging the chain's security for trust-free communication. +Page Title: Get Started with Smart Contracts -In order to interact with chains that want to use their own finalization process (e.g., Bitcoin), Polkadot has [bridges](/reference/parachains/interoperability/#bridges-connecting-external-networks){target=\_blank} that offer two-way compatibility, meaning that transactions can be made between different parachains. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-get-started.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/get-started/ +- Summary: Practical examples for building and deploying smart contracts on Polkadot Hub, from connecting and tooling to deployment, integrations, and precompiles. -### Polkadot's Additional Functionalities +# Get Started -Historically, obtaining core slots on Polkadot chain relied upon crowdloans and auctions. Chain cores were leased through auctions for three-month periods, up to a maximum of two years. Crowdloans enabled users to securely lend funds to teams for lease deposits in exchange for pre-sale tokens, which is the only way to access slots on Polkadot 1.0. Auctions are now deprecated in favor of [coretime](/polkadot-protocol/architecture/system-chains/coretime/){target=\_blank}. +This resource provides quick-starts for building smart contracts on Polkadot Hub. Use the tables below to jump directly to the tools and workflows you need. -Additionally, the chain handles [staking](https://wiki.polkadot.com/learn/learn-staking/){target=\_blank}, [accounts](/reference/parachains/accounts/){target=\_blank}, balances, and [governance](/reference/governance/){target=\_blank}. +## Quick Starts -#### Agile Coretime +Kick off development fast with curated links for connecting, funding, exploring, and deploying your first contract. -The new and more efficient way of obtaining core on Polkadot is to go through the process of purchasing coretime. +| Quick Start | Tools | Description | +|:---------------------------------------------------------------------------------------------------:|:---------------------:|:---------------------------------------------------------------:| +| [Connect to Polkadot](/smart-contracts/connect/){target=\_blank} | Polkadot.js, MetaMask | Add the network, configure RPC, verify activity in the explorer | +| [Get Test Tokens](/smart-contracts/faucets/){target=\_blank} | - | Request test funds to deploy and interact with contracts | +| [Explore Transactions](/smart-contracts/explorers/){target=\_blank} | Subscan | Inspect transactions, logs, token transfers, and contract state | +| [Deploy with Remix](/smart-contracts/dev-environments/remix/deploy-a-contract/){target=\_blank} | Remix | One‑click browser deployment to Polkadot Hub | +| [Deploy with Foundry](/smart-contracts/dev-environments/foundry/deploy-a-contract/){target=\_blank} | Foundry | Scripted deployments and testing from the CLI | +| [Deploy with Hardhat](/smart-contracts/dev-environments/hardhat/deploy-a-contract/){target=\_blank} | Hardhat | Project scaffolding, testing, and deployments | -[Agile coretime](/reference/polkadot-hub/consensus-and-security/agile-coretime/){target=\_blank} improves the efficient use of Polkadot's network resources and offers economic flexibility for developers, extending Polkadot's capabilities far beyond the original vision outlined in the [whitepaper](https://polkadot.com/papers/Polkadot-whitepaper.pdf){target=\_blank}. +## Build and Test Locally -It enables parachains to purchase monthly "bulk" allocations of coretime (the time allocated for utilizing a core, measured in Polkadot relay chain blocks), ensuring heavy-duty parachains that can author a block every six seconds with [Asynchronous Backing](https://wiki.polkadot.com/learn/learn-async-backing/#asynchronous-backing){target=\_blank} can reliably renew their coretime each month. Although six-second block times are now the default, parachains have the option of producing blocks less frequently. +Set up local environments and CI-friendly workflows to iterate quickly and validate changes before deploying. -Renewal orders are prioritized over new orders, offering stability against price fluctuations and helping parachains budget more effectively for project costs. +| Build and Test Locally | Tools | Description | +|:------------------------------------------------------------------------------------------------------------:|:-----------------:|:----------------------------------------------------:| +| [Run a Local Dev Node](/smart-contracts/dev-environments/local-dev-node/){target=\_blank} | Polkadot SDK node | Spin up a local node for iterative development | +| [Remix: Get Started](/smart-contracts/dev-environments/remix/get-started/){target=\_blank} | Remix | Connect Remix to Polkadot Hub and configure accounts | +| [Remix: Verify a Contract](/smart-contracts/dev-environments/remix/verify-a-contract/){target=\_blank} | Remix | Publish verified source on explorers | +| [Foundry: Install and Config](/smart-contracts/dev-environments/foundry/install-and-config/){target=\_blank} | Foundry | Install toolchain and configure networks | +| [Foundry: Compile and Test](/smart-contracts/dev-environments/foundry/compile-and-test/){target=\_blank} | Foundry | Write and run Solidity tests locally | +| [Foundry: Verify a Contract](/smart-contracts/dev-environments/foundry/verify-a-contract/){target=\_blank} | Foundry | Verify deployed bytecode and metadata | +| [Hardhat: Install and Config](/smart-contracts/dev-environments/hardhat/install-and-config/){target=\_blank} | Hardhat | Initialize a project and configure networks | +| [Hardhat: Compile and Test](/smart-contracts/dev-environments/hardhat/compile-and-test/){target=\_blank} | Hardhat | Unit test contracts and run scripts | +| [Hardhat: Verify a Contract](/smart-contracts/dev-environments/hardhat/verify-a-contract/){target=\_blank} | Hardhat | Verify deployments on explorers | -### Polkadot's Resilience +## Ethereum Developer Resources -Decentralization is a vital component of blockchain networks, but it comes with trade-offs: +Bridge your Ethereum knowledge with Polkadot Hub specifics: account mapping, fees, JSON‑RPC, and deployment. -- An overly decentralized network may face challenges in reaching consensus and require significant energy to operate. -- Also, a network that achieves consensus quickly risks centralization, making it easier to manipulate or attack. +| Ethereum Developer Guides | Description | +|:---------------------------------------------------------------------------------------------------------:|:---------------------------------------------------------------:| +| [Accounts](/smart-contracts/for-eth-devs/accounts/){target=\_blank} | How 20‑byte Ethereum addresses map to 32‑byte Polkadot accounts | +| [Blocks, Transactions, and Fees](/smart-contracts/for-eth-devs/blocks-transactions-fees/){target=\_blank} | Transaction types, fees, and multi‑dimensional metering | +| [Gas Model](/smart-contracts/for-eth-devs/gas-model/){target=\_blank} | Gas vs. weight, proof size, and storage deposits | +| [Contract Deployment](/smart-contracts/for-eth-devs/contract-deployment/){target=\_blank} | Deployment patterns and best practices on Polkadot Hub | +| [JSON‑RPC APIs](/smart-contracts/for-eth-devs/json-rpc-apis/){target=\_blank} | Supported Ethereum JSON‑RPC methods and examples | +| [Migration](/smart-contracts/for-eth-devs/migration/){target=\_blank} | Port existing apps and tooling to Polkadot Hub | +| [Dual VM Stack](/smart-contracts/for-eth-devs/dual-vm-stack/){target=\_blank} | Overview of EVM and native execution on the Hub | -A network should be decentralized enough to prevent manipulative or malicious influence. In this sense, decentralization is a tool for achieving resilience. +## Cookbook: Hands‑on Tutorials -Polkadot 1.0 currently achieves resilience through several strategies: +Follow step‑by‑step guides that walk through common tasks and complete dApp examples. -- **Nominated Proof of Stake (NPoS)**: Ensures that the stake per validator is maximized and evenly distributed among validators. +| Tutorial | Tools | Description | +|:--------------------------------------------------------------------------------------------------------:|:-------------------:|:-----------------------------------------:| +| [Deploy a Basic Contract](/smart-contracts/cookbook/smart-contracts/deploy-basic/remix/){target=\_blank} | Remix | Minimal deployment walkthrough | +| [Deploy an ERC‑20](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/){target=\_blank} | Remix, OpenZeppelin | Create, deploy, and mint a fungible token | +| [Deploy an NFT (ERC‑721)](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/){target=\_blank} | Remix, OpenZeppelin | Build and deploy an NFT collection | +| [Uniswap V2](/smart-contracts/cookbook/eth-dapps/uniswap-v2/){target=\_blank} | Hardhat | Full dApp project: compile, test, deploy | +| [Zero‑to‑Hero dApp](/smart-contracts/cookbook/dapps/zero-to-hero/){target=\_blank} | Multiple | End‑to‑end dApp patterns and practices | -- **Decentralized nodes**: Designed to encourage operators to join the network. This program aims to expand and diversify the validators in the ecosystem who aim to become independent of the program during their term. Feel free to explore more about the program on the official [Decentralized Nodes](https://nodes.web3.foundation/){target=\_blank} page. +## Libraries -- **On-chain treasury and governance**: Known as [OpenGov](/reference/governance/){target=\_blank}, this system allows every decision to be made through public referenda, enabling any token holder to cast a vote. +Choose the client libraries that fit your stack for connecting wallets and calling contracts. -### Polkadot's Blockspace +| Library | Description | +|:------------------------------------------------------------------:|:-------------------------------------------------------:| +| [Ethers.js](/smart-contracts/libraries/ethers-js/){target=\_blank} | Connect, sign, and interact with contracts using Ethers | +| [viem](/smart-contracts/libraries/viem/){target=\_blank} | Type‑safe EVM interactions and utilities | +| [Wagmi](/smart-contracts/libraries/wagmi/){target=\_blank} | React hooks for wallet connections and contract calls | +| [Web3.js](/smart-contracts/libraries/web3-js/){target=\_blank} | Web3 provider and contract APIs | +| [Web3.py](/smart-contracts/libraries/web3-py/){target=\_blank} | Python toolkit for on‑chain interactions and scripts | -Polkadot 1.0’s design allows for the commoditization of blockspace. +## Integrations -Blockspace is a blockchain's capacity to finalize and commit operations, encompassing its security, computing, and storage capabilities. Its characteristics can vary across different blockchains, affecting security, flexibility, and availability. +Integrate essential services like wallets, indexers, and oracles to round out your dApp. -- **Security**: Measures the robustness of blockspace in Proof of Stake (PoS) networks linked to the stake locked on validator nodes, the variance in stake among validators, and the total number of validators. It also considers social centralization (how many validators are owned by single operators) and physical centralization (how many validators run on the same service provider). +| Integration | Description | +|:-------------------------------------------------------------------:|:-----------------------------------------:| +| [Wallets](/smart-contracts/integrations/wallets/){target=\_blank} | Supported wallets and configuration notes | +| [Indexers](/smart-contracts/integrations/indexers/){target=\_blank} | Index and query blockchain data | +| [Oracles](/smart-contracts/integrations/oracles/){target=\_blank} | Bring external data on‑chain | -- **Flexibility**: Reflects the functionalities and types of data that can be stored, with high-quality data essential to avoid bottlenecks in critical processes. +## Precompiles -- **Availability**: Indicates how easily users can access blockspace. It should be easily accessible, allowing diverse business models to thrive, ideally regulated by a marketplace based on demand and supplemented by options for "second-hand" blockspace. +Discover precompiled system contracts available on the Hub and how to use them. -Polkadot is built on core blockspace principles, but there's room for improvement. Tasks like balance transfers, staking, and governance are managed on the relay chain. +| Topic | Description | +|:------------------------------------------------------------------------:|:---------------------------------------------------:| +| [Overview of Precompiles](/smart-contracts/precompiles/){target=\_blank} | What precompiles are available on the Hub | +| [ETH Native](/smart-contracts/precompiles/eth-native/){target=\_blank} | EVM precompiles and interfaces | +| [Staking](/smart-contracts/precompiles/staking/){target=\_blank} | Interact with staking functionality via precompiles | +| [XCM](/smart-contracts/precompiles/xcm/){target=\_blank} | Cross‑chain messaging helpers for contracts | -Delegating these responsibilities to [system chains](/polkadot-protocol/architecture/system-chains/){target=\_blank} could enhance flexibility and allow the relay chain to concentrate on providing shared security and interoperability. +From here, follow the quick starts to get connected, iterate locally with your preferred tools, and use the guides, libraries, integrations, and precompiles as you grow into production‑ready dApps. If you get stuck, [open an issue](https://github.com/polkadot-developers/polkadot-docs/issues/new?template=docs-issue.yml){target=\_blank} or reach out in the community channels. -For more information about blockspace, watch [Robert Habermeier’s interview](https://www.youtube.com/watch?v=e1vISppPwe4){target=\_blank} or read his [technical blog post](https://www.rob.tech/blog/polkadot-blockspace-over-blockchains/){target=\_blank}. -## DOT Token +--- -DOT is the native token of the Polkadot network, much like BTC for Bitcoin and Ether for the Ethereum blockchain. DOT has 10 decimals, uses the Planck base unit, and has a balance type of `u128`. The same is true for Kusama's KSM token with the exception of having 12 decimals. +Page Title: Get Started with XCM -### Redenomination of DOT - -Polkadot conducted a community poll, which ended on 27 July 2020 at block 888,888, to decide whether to redenominate the DOT token. The stakeholders chose to redenominate the token, changing the value of 1 DOT from 1e12 plancks to 1e10 plancks. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md +- Canonical (HTML): https://docs.polkadot.com/parachains/interoperability/get-started/ +- Summary: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. -Importantly, this did not affect the network's total number of base units (plancks); it only affects how a single DOT is represented. The redenomination became effective 72 hours after transfers were enabled, occurring at block 1,248,328 on 21 August 2020 around 16:50 UTC. +# Get Started with XCM -### The Planck Unit +## Introduction -The smallest unit of account balance on Polkadot SDK-based blockchains (such as Polkadot and Kusama) is called _Planck_, named after the Planck length, the smallest measurable distance in the physical universe. +Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems. -Similar to how BTC's smallest unit is the Satoshi and ETH's is the Wei, Polkadot's native token DOT equals 1e10 Planck, while Kusama's native token KSM equals 1e12 Planck. +With XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation. -### Uses for DOT +## Messaging Format -DOT serves three primary functions within the Polkadot network: +XCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics. -- **Governance**: It is used to participate in the governance of the network. -- **Staking**: DOT is staked to support the network's operation and security. -- **Buying coretime**: Used to purchase coretime in-bulk or on-demand and access the chain to benefit from Polkadot's security and interoperability. +XCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing. -Additionally, DOT can serve as a transferable token. For example, DOT, held in the treasury, can be allocated to teams developing projects that benefit the Polkadot ecosystem. +## The Four Principles of XCM -## JAM and the Road Ahead +XCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems: -The Join-Accumulate Machine (JAM) represents a transformative redesign of Polkadot's core architecture, envisioned as the successor to the current relay chain. Unlike traditional blockchain architectures, JAM introduces a unique computational model that processes work through two primary functions: +- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes. +- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended. +- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin. +- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems. -- **Join**: Handles data integration. -- **Accumulate**: Folds computations into the chain's state. +These principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments. -JAM removes many of the opinions and constraints of the current relay chain while maintaining its core security properties. Expected improvements include: +## The XCM Tech Stack -- **Permissionless code execution**: JAM is designed to be more generic and flexible, allowing for permissionless code execution through services that can be deployed without governance approval. -- **More effective block time utilization**: JAM's efficient pipeline processing model places the prior state root in block headers instead of the posterior state root, enabling more effective utilization of block time for computations. +![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp) -This architectural evolution promises to enhance Polkadot's scalability and flexibility while maintaining robust security guarantees. JAM is planned to be rolled out to Polkadot as a single, complete upgrade rather than a stream of smaller updates. This approach seeks to minimize the developer overhead required to address any breaking changes. +The XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels. +## Core Functionalities of XCM ---- +XCM enhances cross-consensus communication by introducing several powerful features: -Page Title: Parachains Overview +- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management. +- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification. +- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/ -- Summary: Learn about parachains, specialized blockchains on Polkadot that gain shared security and interoperability. Discover how they work and the tools to build them. +The standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications. -# Parachains Overview +## XCM Example -## Introduction +The following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA). -A parachain is a specialized blockchain that connects to the Polkadot relay chain, benefiting from shared security, interoperability, and scalability. Parachains are built using the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}, a powerful toolkit written in Rust that provides everything needed to create custom blockchain logic while integrating seamlessly with the Polkadot network. +```rust +let message = Xcm(vec![ + WithdrawAsset((Here, amount).into()), + BuyExecution { + fees: (Here, amount).into(), + weight_limit: WeightLimit::Unlimited + }, + DepositAsset { + assets: All.into(), + beneficiary: MultiLocation { + parents: 0, + interior: Junction::AccountId32 { + network: None, + id: BOB.clone().into() + }.into(), + }.into() + } +]); +``` -Unlike standalone blockchains that must bootstrap their own validator sets and security, parachains leverage Polkadot's pooled security model. This allows parachain developers to focus on their application-specific functionality rather than consensus and security infrastructure. Parachains can communicate with each other through Cross-Consensus Messaging (XCM), enabling seamless interoperability across the Polkadot ecosystem. +The message consists of three instructions described as follows: -Key capabilities that parachains provide include: +- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register. -- **Shared security**: Inherit security from Polkadot's validator set without maintaining your own. -- **Interoperability**: Communicate trustlessly with other parachains via XCM. -- **Scalability**: Process transactions in parallel with other parachains. -- **Customization**: Build application-specific logic tailored to your use case. -- **Upgradeability**: Upgrade runtime logic without hard forks. + ```rust + WithdrawAsset((Here, amount).into()), + ``` -## Polkadot SDK: Parachain Architecture + - **`Here`**: The native parachain token. + - **`amount`**: The number of tokens that are transferred. -Building a parachain involves understanding and utilizing several key components of the Polkadot SDK: + The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register. -![](/images/reference/parachains/index/overview-01.webp) +- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\_blank} of the XCM instructions. -- **[Substrate](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/substrate/index.html){target=\_blank}**: The foundation providing core blockchain primitives and libraries. -- **[FRAME](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank}**: A modular framework for building your parachain's runtime logic. -- **[Cumulus](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/cumulus/index.html){target=\_blank}**: Essential libraries and pallets that enable parachain functionality. -- **[XCM (Cross Consensus Messaging)](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/xcm/index.html){target=\_blank}**: The messaging format for communicating with other parachains and the relay chain. -- **[Polkadot](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/polkadot/index.html){target=\_blank}**: The relay chain that provides security and coordination. + ```rust + BuyExecution { + fees: (Here, amount).into(), + weight_limit: WeightLimit::Unlimited + }, + ``` -### Substrate: The Foundation + - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight. + - **`weight_limit`**: Defines the maximum fees that can be used to buy weight. -Substrate provides the core infrastructure that every parachain is built upon. It handles the low-level blockchain functionality, allowing you to focus on your application's unique features. Substrate includes implementations for networking, database management, consensus participation, and the execution environment for your runtime. +- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\_blank}**: Moves the remaining tokens from the holding register to Bob’s account. -Every Polkadot SDK node consists of two main components: + ```rust + DepositAsset { + assets: All.into(), + beneficiary: MultiLocation { + parents: 0, + interior: Junction::AccountId32 { + network: None, + id: BOB.clone().into() + }.into(), + }.into() + } + ``` -- **Client (Host)**: Handles infrastructure services. + - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited. + +This step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - - Native binary that runs on validator and collator nodes. - - Executes the Wasm-compiled runtime. - - Manages networking, database, mempool, and block production. - - Interfaces with the relay chain for validation. +## Overview -- **Runtime (State Transition Function)**: Contains your business logic. +XCM revolutionizes cross-chain communication by enabling use cases such as: - - Defines how your Polkadot SDK node processes transactions. - - Compiled to [Wasm](https://webassembly.org/){target=\_blank} for deterministic execution. - - Stored on-chain and upgradeable via governance. +- Token transfers between blockchains. +- Asset locking for cross-chain smart contract interactions. +- Remote execution of functions on other blockchains. -```mermaid -%%{init: {'flowchart': {'padding': 5, 'nodeSpacing': 50, 'rankSpacing': 10}}}%% -graph TB - classDef title font-size:20px,font-weight:bold,stroke-width:0px - classDef clientStyle font-size:16px,font-weight:bold - classDef clientSubNodeStyle margin-top:10px - classDef runtimeCallExecutorStyle padding-top:10px +These functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\_blank}. - subgraph sg1[Parachain
Node] - direction TB - I[RuntimeCall Executor] - B[Wasm Runtime - STF] +--- - subgraph sg2[Client] - direction TB - C[Network and Blockchain
Infrastructure Services
+ Relay Chain Interface] - end +Page Title: Indexers - I --> B - end +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-indexers.md +- Canonical (HTML): https://docs.polkadot.com/parachains/integrations/indexers/ +- Summary: Discover blockchain indexers. Enhance data access, enable fast and complex queries, and optimize blockchain data for seamless app performance. - class sg1 title - class sg2 clientStyle - class C clientSubNodeStyle - class I runtimeCallExecutorStyle +# Indexers -``` +## The Challenge of Blockchain Data Access -### FRAME: Building Blocks for Your Runtime +Blockchain data is inherently sequential and distributed, with information stored chronologically across numerous blocks. While retrieving data from a single block through JSON-RPC API calls is straightforward, more complex queries that span multiple blocks present significant challenges: -FRAME provides modular components called [pallets](/reference/glossary#pallet){target=\_blank} that you can compose to build your parachain's runtime. Each pallet provides specific functionality that you can customize and configure for your needs. This modular approach allows you to quickly assemble complex functionality without writing everything from scratch. +- Data is scattered and unorganized across the blockchain. +- Retrieving large datasets can take days or weeks to sync. +- Complex operations (like aggregations, averages, or cross-chain queries) require additional processing. +- Direct blockchain queries can impact dApp performance and responsiveness. -```mermaid -graph LR - subgraph SP["Parachain Runtime"] - direction LR - Timestamp ~~~ Aura ~~~ ParachainSystem - Balances ~~~ TransactionPayment ~~~ Sudo - subgraph Timestamp["Timestamp"] - SS1[Custom Config] - end - subgraph Aura["Aura"] - SS2[Custom Config] - end - subgraph ParachainSystem["Parachain System"] - SS3[Custom Config] - end - subgraph Balances["Balances"] - SS4[Custom Config] - end - subgraph TransactionPayment["Transaction Payment"] - SS5[Custom Config] - end - subgraph Sudo["Sudo"] - SS6[Custom Config] - end - style Timestamp stroke:#FF69B4 - style Aura stroke:#FF69B4 - style ParachainSystem stroke:#FF69B4 - style Balances stroke:#FF69B4 - style TransactionPayment stroke:#FF69B4 - style Sudo stroke:#FF69B4 - style SS1 stroke-dasharray: 5 - style SS2 stroke-dasharray: 5 - style SS3 stroke-dasharray: 5 - style SS4 stroke-dasharray: 5 - style SS5 stroke-dasharray: 5 - style SS6 stroke-dasharray: 5 - - end - subgraph AP["Available FRAME Pallets"] - direction LR - A1[Aura]~~~A2[Parachain
System]~~~A3[Transaction
Payment]~~~A4[Sudo] - B1[Identity]~~~B2[Balances]~~~B3[Assets]~~~B4[EVM] - C1[Timestamp]~~~C2[Staking]~~~C3[Contracts]~~~C4[and more...] - end - AP --> SP -``` - -### Cumulus: Parachain-Specific Functionality - -Cumulus is what transforms a Polkadot SDK-based runtime into a parachain-capable runtime. It provides the essential components for communicating with the relay chain, participating in Polkadot's consensus, and handling parachain-specific operations like block validation and collation. - -Key Cumulus components include: - -- **Parachain system pallet**: Core parachain functionality and relay chain communication. -- **Collator consensus**: Block production logic for parachain collators. -- **Relay chain interface**: APIs for interacting with the Polkadot relay chain. -- **Validation data**: Handling proof-of-validity data required by relay chain validators. +## What is a Blockchain Indexer? -## Where to Go Next +A blockchain indexer is a specialized infrastructure tool that processes, organizes, and stores blockchain data in an optimized format for efficient querying. Think of it as a search engine for blockchain data that: -Building a parachain requires understanding the relationship between your chain and the Polkadot relay chain. The Polkadot SDK provides all the tools needed to design custom runtime logic, enable cross-chain communication, and deploy your parachain to production. +- Continuously monitors the blockchain for new blocks and transactions. +- Processes and categorizes this data according to predefined schemas. +- Stores the processed data in an easily queryable database. +- Provides efficient APIs (typically [GraphQL](https://graphql.org/){target=\_blank}) for data retrieval. -The following sections provide detailed guidance on each aspect of parachain development, from initial design through deployment and ongoing maintenance. +## Indexer Implementations
-- Guide __Launch a Simple Parachain__ +- __Subsquid__ --- - Walk through the complete parachain launch flow: from setup and deployment to obtaining coretime. - - [:octicons-arrow-right-24: Deploy](/parachains/launch-a-parachain/set-up-the-parachain-template/) + Subsquid is a data network that allows rapid and cost-efficient retrieval of blockchain data from 100+ chains using Subsquid's decentralized data lake and open-source SDK. In simple terms, Subsquid can be considered an ETL (extract, transform, and load) tool with a GraphQL server included. It enables comprehensive filtering, pagination, and even full-text search capabilities. Subsquid has native and full support for EVM and Substrate data, even within the same project. + [:octicons-arrow-right-24: Reference](https://www.sqd.ai/){target=\_blank} -- Guide __Customize Your Runtime__ +- __Subquery__ --- - Design your parachain's runtime logic and choose appropriate pallets for your use case. - - [:octicons-arrow-right-24: Get Started](/parachains/customize-runtime/) + SubQuery is a fast, flexible, and reliable open-source data decentralised infrastructure network that provides both RPC and indexed data to consumers worldwide. + It provides custom APIs for your web3 project across multiple supported chains. -- Guide __Interoperability__ + [:octicons-arrow-right-24: Reference](https://subquery.network/){target=\_blank} - --- +
- Implement XCM for trustless cross-chain communication with other parachains. - [:octicons-arrow-right-24: Learn More](/parachains/interoperability/get-started/) +--- -- Guide __Runtime Upgrades__ +Page Title: Install Polkadot SDK - --- +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-install-polkadot-sdk.md +- Canonical (HTML): https://docs.polkadot.com/parachains/install-polkadot-sdk/ +- Summary: Install all required Polkadot SDK dependencies, set up the SDK itself, and verify that it runs correctly on your machine. - Upgrade your parachain's runtime without hard forks using forkless upgrade mechanisms. +# Install Polkadot SDK - [:octicons-arrow-right-24: Maintain](/parachains/runtime-maintenance/runtime-upgrades/) +This guide provides step-by-step instructions for installing the Polkadot SDK on macOS, Linux, and Windows. The installation process consists of two main parts: - +- **Installing dependencies**: Setting up Rust, required system packages, and development tools. +- **Building the Polkadot SDK**: Cloning and compiling the Polkadot SDK repository. +Follow the appropriate section for your operating system to ensure all necessary tools are installed and configured properly. ---- +## Install Dependencies: macOS -Page Title: Polkadart +You can install Rust and set up a Substrate development environment on Apple macOS computers with Intel or Apple M1 processors. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-polkadart.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/polkadart/ -- Summary: Polkadart is a type-safe, native Dart, SDK for Polkadot and any compatible Polkadot-SDK blockchain network. +### Before You Begin {: #before-you-begin-mac-os } -# Polkadart +Before you install Rust and set up your development environment on macOS, verify that your computer meets the following basic requirements: -Polkadart is the most comprehensive Dart/Flutter SDK for interacting with Polkadot, Substrate, and other compatible blockchain networks. Designed with a Dart-first approach and type-safe APIs, it provides everything developers need to build powerful decentralized applications. +- Operating system version is 10.7 Lion or later. +- Processor speed of at least 2 GHz. Note that 3 GHz is recommended. +- Memory of at least 8 GB RAM. Note that 16 GB is recommended. +- Storage of at least 10 GB of available space. +- Broadband Internet connection. -This page will outline some of the core components of Polkadart. For more details, refer to the [official documentation](https://polkadart.dev){target=\_blank}. +### Install Homebrew -## Installation +In most cases, you should use Homebrew to install and manage packages on macOS computers. If you don't already have Homebrew installed on your local computer, you should download and install it before continuing. -Add Polkadart to your `pubspec.yaml`: +To install Homebrew: -=== "All packages" +1. Open the Terminal application. +2. Download and install Homebrew by running the following command: ```bash - dart pub add polkadart polkadart_cli polkadart_keyring polkadart_scale_codec secp256k1_ecdsa sr25519 ss58 substrate_bip39 substrate_metadata + /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" ``` -=== "Core only" +3. Verify Homebrew has been successfully installed by running the following command: ```bash - dart pub add polkadart polkadart_cli polkadart_keyring + brew --version ``` -For type-safe API generation, add the following to your `pubspec.yaml`: - -{% raw %} -```yaml title="pubspec.yaml" -polkadart: - output_dir: lib/generated - chains: - polkadot: wss://rpc.polkadot.io - kusama: wss://kusama-rpc.polkadot.io - custom: wss://your-node.example.com -``` -{% endraw %} - -## Get Started + The command displays output similar to the following: -### Type Generation +
+ brew --version + Homebrew 4.3.15 +
-Polkadart provides a CLI tool to generate type definitions from any Polkadot-SDK compatible blockchain network. This allows you to build type-safe Dart applications without dealing with the low-level details of the blockchain. +### Support for Apple Silicon -### Run Generator +Protobuf must be installed before the build process can begin. To install it, run the following command: ```bash -dart run polkadart_cli:generate -v +brew install protobuf ``` -### Use Generated Types +### Install Required Packages and Rust {: #install-required-packages-and-rust-mac-os } -```dart -import 'package:your_app/generated/polkadot/polkadot.dart'; -import 'package:polkadart/polkadart.dart'; -import 'package:ss58/ss58.dart'; +Because the blockchain requires standard cryptography to support the generation of public/private key pairs and the validation of transaction signatures, you must also have a package that provides cryptography, such as `openssl`. -final provider = Provider.fromUri(Uri.parse('wss://rpc.polkadot.io')); -final polkadot = Polkadot(provider); - -// Account from SS58 address -final account = Address.decode('19t9Q2ay58hMDaeg6eeBhqmHsRnc2jDMV3cYYw9zbc59HLj'); +To install `openssl` and the Rust toolchain on macOS: -// Retrieve Account Balance -final accountInfo = await polkadot.query.system.account(account.pubkey); -print('Balance: ${accountInfo.data.free}') -``` +1. Open the Terminal application. +2. Ensure you have an updated version of Homebrew by running the following command: + + ```bash + brew update + ``` + +3. Install the `openssl` package by running the following command: -### Creating an API Instance + ```bash + brew install openssl + ``` -An API instance is required to interact with the blockchain. Polkadart provides a `Provider` class that allows you to connect to any network. +4. Download the `rustup` installation program and use it to install Rust by running the following command: -```dart -import 'package:demo/generated/polkadot/polkadot.dart'; -import 'package:polkadart/provider.dart'; + ```bash + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh + ``` -Future main(List arguments) async { - final provider = Provider.fromUri(Uri.parse('wss://rpc.polkadot.io')); - final polkadot = Polkadot(provider); -} -``` +5. Follow the prompts displayed to proceed with a default installation. +6. Update your current shell to include Cargo by running the following command: -### Reading Chain Data + ```bash + source ~/.cargo/env + ``` -Besides querying the data using the `query` from the generated API, you can also use the State API for querying storage data, metadata, runtime information, and other chain information. +7. Configure the Rust toolchain to default to the latest stable version by running the following commands: -```dart -final stateApi = StateApi(provider); + ```bash + rustup default stable + rustup update + rustup target add wasm32-unknown-unknown + rustup component add rust-src + ``` -// Get current runtime version -final runtimeVersion = await stateApi.getRuntimeVersion(); -print(runtimeVersion.toJson()); +8. Install `cmake` using the following command: -// Get metadata -final metadata = await stateApi.getMetadata(); -print('Metadata version: ${metadata.version}'); -``` + ```bash + brew install cmake + ``` -### Subscribe to New Blocks +9. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). -You can subscribe to new blocks on the blockchain using the `subscribe` method. +## Install Dependencies: Linux -```dart -final subscription = await provider.subscribe('chain_subscribeNewHeads', []); +Rust supports most Linux distributions. Depending on the specific distribution and version of the operating system you use, you might need to add some software dependencies to your environment. In general, your development environment should include a linker or a C-compatible compiler, such as `clang`, and an appropriate integrated development environment (IDE). -subscription.stream.forEach((response) { - print('New head: ${response.result}'); -}); +### Before You Begin {: #before-you-begin-linux } + +Check the documentation for your operating system for information about the installed packages and how to download and install any additional packages you might need. For example, if you use Ubuntu, you can use the Ubuntu Advanced Packaging Tool (`apt`) to install the `build-essential` package: + +```bash +sudo apt install build-essential ``` -### Send a Transaction - -Perhaps the most common operation done in any blockchain is transferring funds. Here you can see how that can be done using Polkadart: - -```dart -final wallet = await KeyPair.sr25519.fromUri("//Alice"); -print('Alice\' wallet: ${wallet.address}'); - -// Get information necessary to build a proper extrinsic -final runtimeVersion = await polkadot.rpc.state.getRuntimeVersion(); -final currentBlockNumber = (await polkadot.query.system.number()) - 1; -final currentBlockHash = await polkadot.query.system.blockHash(currentBlockNumber); -final genesisHash = await polkadot.query.system.blockHash(0); -final nonce = await polkadot.rpc.system.accountNextIndex(wallet.address); - -// Make the encoded call -final multiAddress = $MultiAddress().id(wallet.publicKey.bytes); -final transferCall = polkadot.tx.balances.transferKeepAlive(dest: multiAddress, value: BigInt.one).encode(); - -// Make the payload -final payload = SigningPayload( - method: transferCall, - specVersion: runtimeVersion.specVersion, - transactionVersion: runtimeVersion.transactionVersion, - genesisHash: encodeHex(genesisHash), - blockHash: encodeHex(currentBlockHash), - blockNumber: currentBlockNumber, - eraPeriod: 64, - nonce: nonce, - tip: 0, -).encode(polkadot.registry); - -// Sign the payload and build the final extrinsic -final signature = wallet.sign(payload); -final extrinsic = ExtrinsicPayload( - signer: wallet.bytes(), - method: transferCall, - signature: signature, - eraPeriod: 64, - blockNumber: currentBlockNumber, - nonce: nonce, - tip: 0, -).encode(polkadot.registry, SignatureType.sr25519); - -// Send the extrinsic to the blockchain -final author = AuthorApi(provider); -await author.submitAndWatchExtrinsic(extrinsic, (data) { - print(data); -}); +At a minimum, you need the following packages before you install Rust: + +```text +clang curl git make ``` -## Where to Go Next +Because the blockchain requires standard cryptography to support the generation of public/private key pairs and the validation of transaction signatures, you must also have a package that provides cryptography, such as `libssl-dev` or `openssl-devel`. -To dive deeper into Polkadart, refer to the [official Polkadart documentation](https://polkadart.dev/){target=\_blank}, where you can find comprehensive guides for common use cases and advanced usage. +### Install Required Packages and Rust {: #install-required-packages-and-rust-linux } +To install the Rust toolchain on Linux: ---- +1. Open a terminal shell. +2. Check the packages installed on the local computer by running the appropriate package management command for your Linux distribution. +3. Add any package dependencies you are missing to your local development environment by running the appropriate package management command for your Linux distribution: -Page Title: Polkadot Omni Node + === "Ubuntu" -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-omninode.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/omninode/ -- Summary: Run parachain nodes easily with the polkadot-omni-node, a white-labeled binary that can run parachain nodes using a single pre-built solution. + ```bash + sudo apt install --assume-yes git clang curl libssl-dev protobuf-compiler + ``` -# Polkadot Omni Node + === "Debian" -## Introduction + ```sh + sudo apt install --assume-yes git clang curl libssl-dev llvm libudev-dev make protobuf-compiler + ``` -The [`polkadot-omni-node`](https://crates.io/crates/polkadot-omni-node/0.7.0){target=\_blank} crate is a versatile, pre-built binary designed to simplify running parachains in the Polkadot ecosystem. Unlike traditional node binaries that are tightly coupled to specific runtime code, the `polkadot-omni-node` operates using an external [chain specification](/polkadot-protocol/glossary#chain-specification){target=\_blank} file, allowing it to adapt dynamically to different parachains. + === "Arch" -This approach enables it to act as a white-labeled node binary, capable of running most parachains that do not require custom node-level logic or extensions. Developers can leverage this flexibility to test, deploy, or operate parachain nodes without maintaining a dedicated codebase for each network. + ```sh + pacman -Syu --needed --noconfirm curl git clang make protobuf + ``` -This guide provides step-by-step instructions for installing the `polkadot-omni-node`, obtaining a chain specification, and spinning up a parachain node. + === "Fedora" -## Prerequisites + ```sh + sudo dnf update + sudo dnf install clang curl git openssl-devel make protobuf-compiler + ``` -Before getting started, ensure you have the following prerequisites: + === "OpenSUSE" -- **[Rust](https://rust-lang.org/tools/install/){target=\_blank}**: Required to build and install the `polkadot-omni-node` binary. + ```sh + sudo zypper install clang curl git openssl-devel llvm-devel libudev-devel make protobuf + ``` -Ensure Rust's `cargo` command is available in your terminal by running: + Remember that different distributions might use different package managers and bundle packages in different ways. For example, depending on your installation selections, Ubuntu Desktop and Ubuntu Server might have different packages and different requirements. However, the packages listed in the command-line examples are applicable to many common Linux distributions, including Debian, Linux Mint, MX Linux, and Elementary OS. -```bash -cargo --version -``` +4. Download the `rustup` installation program and use it to install Rust by running the following command: -## Install Polkadot Omni Node + ```bash + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh + ``` -To install `polkadot-omni-node` globally using `cargo`, run: +5. Follow the prompts displayed to proceed with a default installation. +6. Update your current shell to include Cargo by running the following command: -```bash -cargo install --locked polkadot-omni-node@0.7.0 -``` + ```bash + source $HOME/.cargo/env + ``` -This command downloads and installs version 0.7.0 of the binary, making it available system-wide. +7. Verify your installation by running the following command: -To confirm the installation, run: + ```bash + rustc --version + ``` -```bash -polkadot-omni-node --version -``` +8. Configure the Rust toolchain to default to the latest stable version by running the following commands: -You should see the installed version number printed to the terminal, confirming a successful installation. + ```bash + rustup default stable + rustup update + rustup target add wasm32-unknown-unknown + rustup component add rust-src + ``` -## Obtain Chain Specifications +9. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). -The `polkadot-omni-node` binary uses a chain specification file to configure and launch a parachain node. This file defines the parachain's genesis state and network settings. +## Install Dependencies: Windows (WSL) -The most common source for official chain specifications is the [`paritytech/chainspecs`](https://github.com/paritytech/chainspecs){target=\_blank} repository. These specifications are also browsable in a user-friendly format via the [Chainspec Collection](https://paritytech.github.io/chainspecs/){target=\_blank} website. +In general, UNIX-based operating systems—like macOS or Linux—provide a better development environment for building Substrate-based blockchains. -To obtain a chain specification: +However, suppose your local computer uses Microsoft Windows instead of a UNIX-based operating system. In that case, you can configure it with additional software to make it a suitable development environment for building Substrate-based blockchains. To prepare a development environment on a Microsoft Windows computer, you can use Windows Subsystem for Linux (WSL) to emulate a UNIX operating environment. -1. Visit the [Chainspec Collection](https://paritytech.github.io/chainspecs/){target=\_blank} website. -2. Find the parachain you want to run. -3. Click the chain spec to open it. -4. Copy the JSON content and save it locally as a `.json` file, e.g., `chain_spec.json`. +### Before You Begin {: #before-you-begin-windows-wls } -## Run a Parachain Full Node +Before installing on Microsoft Windows, verify the following basic requirements: -Once you've installed `polkadot-omni-node` and saved the appropriate chain specification file, you can start a full node for your chosen parachain. +- You have a computer running a supported Microsoft Windows operating system: + - **For Windows desktop**: You must be running Microsoft Windows 10, version 2004 or later, or Microsoft Windows 11 to install WSL. + - **For Windows server**: You must be running Microsoft Windows Server 2019, or later, to install WSL on a server operating system. +- You have a good internet connection and access to a shell terminal on your local computer. -To see all available flags and configuration options, run: +### Set Up Windows Subsystem for Linux -```bash -polkadot-omni-node --help -``` +WSL enables you to emulate a Linux environment on a computer that uses the Windows operating system. The primary advantage of this approach for Substrate development is that you can use all of the code and command-line examples as described in the Substrate documentation. For example, you can run common commands—such as `ls` and `ps`—unmodified. By using WSL, you can avoid configuring a virtual machine image or a dual-boot operating system. -To launch the node, run the following command, replacing `./INSERT_PARACHAIN_CHAIN_SPEC.json` with the actual path to your saved chain spec file. +To prepare a development environment using WSL: -This command will: +1. Check your Windows version and build number to see if WSL is enabled by default. -- Load the chain specification. -- Initialize the node using the provided network configuration. -- Begin syncing with the parachain network. + If you have Microsoft Windows 10, version 2004 (Build 19041 and higher), or Microsoft Windows 11, WSL is available by default and you can continue to the next step. -```bash -polkadot-omni-node --chain ./INSERT_PARACHAIN_CHAIN_SPEC.json --sync warp -``` + If you have an older version of Microsoft Windows installed, see the [WSL manual installation steps for older versions](https://learn.microsoft.com/en-us/windows/wsl/install-manual){target=\_blank}. If you are installing on an older version of Microsoft Windows, you can download and install WLS 2 if your computer has Windows 10, version 1903 or higher. -- The `--chain` flag tells the `polkadot-omni-node` which parachain to run by pointing to its chain specification file. -- The `--sync warp` flag enables warp sync, allowing the node to quickly catch up to the latest finalized state. Historical blocks are fetched in the background as the node continues operating. +2. Select **Windows PowerShell** or **Command Prompt** from the **Start** menu, right-click, then **Run as administrator**. -Once started, the node will begin connecting to peers and syncing with the network. You’ll see logs in your terminal reflecting its progress. +3. In the PowerShell or Command Prompt terminal, run the following command: -## Interact with the Node + ```bash + wsl --install + ``` -By default, `polkadot-omni-node` exposes a WebSocket endpoint at `ws://localhost:9944`, which you can use to interact with the running node. You can connect using: + This command enables the required WSL 2 components that are part of the Windows operating system, downloads the latest Linux kernel, and installs the Ubuntu Linux distribution by default. -- **[Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank}**: A web-based interface for exploring and interacting with Polkadot SDK-based chains. -- Custom scripts using compatible [libraries](/develop/toolkit/api-libraries/){target=\_blank}. + If you want to review the other Linux distributions available, run the following command: -Once connected, you can review blocks, call extrinsics, inspect storage, and interact with the runtime. + ```bash + wsl --list --online + ``` -## Parachain Compatibility +4. After the distribution is downloaded, close the terminal. -The `polkadot-omni-node` is designed to work with most parachains out of the box; however, your parachain's runtime must meet specific requirements and follow certain conventions to be compatible. This section outlines what your runtime needs to implement and configure to work seamlessly with the `polkadot-omni-node`: +5. Click the **Start** menu, select **Shut down or sign out**, then click **Restart** to restart the computer. -- Your runtime must implement the required runtime APIs (see below). -- Your runtime must include and configure the required pallets. + Restarting the computer is required to start the installation of the Linux distribution. It can take a few minutes for the installation to complete after you restart. -The [`parachain-template`](https://github.com/paritytech/polkadot-sdk-parachain-template/tree/v0.0.4){target=_blank} provides a complete reference implementation that is fully compatible with the `polkadot-omni-node`. You can use it as a starting point or reference for ensuring your runtime meets all compatibility requirements. + For more information about setting up WSL as a development environment, see the [Set up a WSL development environment](https://learn.microsoft.com/en-us/windows/wsl/setup/environment){target=\_blank} docs. -### Required Runtime APIs +### Install Required Packages and Rust {: #install-required-packages-and-rust-windows-wls } -Your parachain runtime must implement the following runtime APIs for the `polkadot-omni-node` to function properly: +To install the Rust toolchain on WSL: -- **GetParachainInfo Runtime API**: The omni-node requires the [`GetParachainInfo`](https://paritytech.github.io/polkadot-sdk/master/cumulus_primitives_core/trait.GetParachainInfo.html){target=\_blank} runtime API to identify and configure the parachain correctly. This API provides the parachain ID to the node. +1. Click the **Start** menu, then select **Ubuntu**. +2. Type a UNIX user name to create a user account. +3. Type a password for your UNIX user, then retype the password to confirm it. +4. Download the latest updates for the Ubuntu distribution using the Ubuntu Advanced Packaging Tool (`apt`) by running the following command: - ```rust title="runtime/src/apis.rs" - impl cumulus_primitives_core::GetParachainInfo for Runtime { - fn parachain_id() -> cumulus_primitives_core::ParaId { - // Return your parachain ID - ParachainInfo::parachain_id() - } - } + ```bash + sudo apt update ``` -- **Aura Runtime API**: For consensus, the `polkadot-omni-node` expects the [Aura runtime API](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/runtime/apis/trait.AuraApi.html){target=\_blank} to be implemented. - - ```rust title="runtime/src/apis.rs" - impl sp_consensus_aura::AuraApi for Runtime { - fn slot_duration() -> sp_consensus_aura::SlotDuration { - sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION) - } +5. Add the required packages for the Ubuntu distribution by running the following command: - fn authorities() -> Vec { - Aura::authorities().into_inner() - } - } + ```bash + sudo apt install --assume-yes git clang curl libssl-dev llvm libudev-dev make protobuf-compiler ``` -### Required Pallets +6. Download the `rustup` installation program and use it to install Rust for the Ubuntu distribution by running the following command: -Your runtime must include and properly configure the following pallets: + ```bash + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh + ``` -- **System Pallet**: The System pallet ([`frame-system`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/prelude/frame_system/index.html){target=\_blank}) is fundamental and must be configured with appropriate types. +7. Follow the prompts displayed to proceed with a default installation. - ```rust title="runtime/src/lib.rs" - #[frame_support::runtime] - impl frame_system::Config for Runtime { - type Block = Block; - type BlockNumber = BlockNumber; - // ... other configurations - } +8. Update your current shell to include Cargo by running the following command: - // Must be named "System" for omni-node compatibility - pub type System = frame_system::Pallet; + ```bash + source ~/.cargo/env ``` -- **ParachainSystem Pallet**: This pallet ([`cumulus-pallet-parachain-system`](https://paritytech.github.io/polkadot-sdk/master/cumulus_pallet_parachain_system/index.html){target=\_blank}) enables parachain functionality and handles low-level details of being a parachain. +9. Verify your installation by running the following command: - ```rust title="runtime/src/lib.rs" - impl cumulus_pallet_parachain_system::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type OnSystemEvent = (); - // ... other configurations - } + ```bash + rustc --version + ``` - // Must be named "ParachainSystem" for omni-node compatibility - pub type ParachainSystem = cumulus_pallet_parachain_system::Pallet; +10. Configure the Rust toolchain to use the latest stable version as the default toolchain by running the following commands: + + ```bash + rustup default stable + rustup update + rustup target add wasm32-unknown-unknown + rustup component add rust-src ``` -- **Aura Pallet**: For block authoring consensus ([`pallet-aura`](https://paritytech.github.io/polkadot-sdk/master/pallet_aura/index.html){target=\_blank}). +11. Proceed to [Build the Polkadot SDK](#build-the-polkadot-sdk). - ```rust title="runtime/src/lib.rs" - impl pallet_aura::Config for Runtime { - type AuthorityId = AuraId; - type DisabledValidators = (); - type MaxAuthorities = MaxAuthorities; - type AllowMultipleBlocksPerSlot = ConstBool; - } +## Build the Polkadot SDK - pub type Aura = pallet_aura::Pallet; - ``` +After installing all dependencies, you can now clone and compile the Polkadot SDK repository to verify your setup. -- **ParachainInfo Pallet**: Provides parachain metadata ([`parachain-info`](https://paritytech.github.io/polkadot-sdk/master/staging_parachain_info/index.html){target=\_blank}). +### Clone the Polkadot SDK - ```rust title="runtime/src/lib.rs" - impl parachain_info::Config for Runtime {} +1. Clone the Polkadot SDK repository: - pub type ParachainInfo = parachain_info::Pallet; + ```bash + git clone https://github.com/paritytech/polkadot-sdk.git ``` -If you're migrating an existing parachain to use the `polkadot-omni-node`, you may need to perform runtime upgrades to add the required runtime APIs and pallets. Follow the standard parachain [runtime upgrade](/parachains/runtime-maintenance/runtime-upgrades/){target=\_blank} procedures to implement these changes on your live network. +2. Navigate into the project directory: + ```bash + cd polkadot-sdk + ``` ---- +### Compile the Polkadot SDK -Page Title: Polkadot SDK Accounts +Compile the entire Polkadot SDK repository to ensure your environment is properly configured: -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-accounts.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/accounts/ -- Summary: Learn about account structures, balances, and address formats in the Polkadot SDK, including how to manage lifecycle, references, and balances. +```bash +cargo build --release --locked +``` -# Accounts +!!!note + This initial compilation will take significant time, depending on your machine specifications. It compiles all components of the Polkadot SDK to verify your toolchain is correctly configured. -## Introduction +### Verify the Build -Accounts are essential for managing identity, transactions, and governance on the network in the Polkadot SDK. Understanding these components is critical for seamless development and operation on the network, whether you're building or interacting with Polkadot-based chains. +Once the build completes successfully, verify the installation by checking the compiled binaries: -This page will guide you through the essential aspects of accounts, including their data structure, balance types, reference counters, and address formats. You’ll learn how accounts are managed within the runtime, how balances are categorized, and how addresses are encoded and validated. +```bash +ls target/release +``` -## Account Data Structure +You should see several binaries, including: -Accounts are foundational to any blockchain, and the Polkadot SDK provides a flexible management system. This section explains how the Polkadot SDK defines accounts and manages their lifecycle through data structures within the runtime. +- `polkadot`: The Polkadot relay chain node. +- `polkadot-parachain`: The parachain collator node. +- `polkadot-omni-node`:The omni node for running parachains. +- `substrate-node`: The kitchensink node with many pre-configured pallets. -### Account +Verify the Polkadot binary works by checking its version: -The [`Account` data type](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/type.Account.html){target=\_blank} is a storage map within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank} that links an account ID to its corresponding data. This structure is fundamental for mapping account-related information within the chain. +```bash +./target/release/polkadot --version +``` -The code snippet below shows how accounts are defined: +This should display version information similar to: -```rs - /// The full account information for a particular account ID. - #[pallet::storage] - #[pallet::getter(fn account)] - pub type Account = StorageMap< - _, - Blake2_128Concat, - T::AccountId, - AccountInfo, - ValueQuery, - >; +```bash +polkadot 1.16.0-1234abcd567 ``` -The preceding code block defines a storage map named `Account`. The `StorageMap` is a type of on-chain storage that maps keys to values. In the `Account` map, the key is an account ID, and the value is the account's information. Here, `T` represents the generic parameter for the runtime configuration, which is defined by the pallet's configuration trait (`Config`). - -The `StorageMap` consists of the following parameters: +If you see the version output without errors, your development environment is correctly configured and ready for Polkadot SDK development! -- **`_`**: Used in macro expansion and acts as a placeholder for the storage prefix type. Tells the macro to insert the default prefix during expansion. -- **`Blake2_128Concat`**: The hashing function applied to keys in the storage map. -- **`T: :AccountId`**: Represents the key type, which corresponds to the account’s unique ID. -- **`AccountInfo`**: The value type stored in the map. For each account ID, the map stores an `AccountInfo` struct containing: +## Optional: Run the Kitchensink Node - - **`T::Nonce`**: A nonce for the account, which is incremented with each transaction to ensure transaction uniqueness. - - **`T: :AccountData`**: Custom account data defined by the runtime configuration, which could include balances, locked funds, or other relevant information. - -- **`ValueQuery`**: Defines how queries to the storage map behave when no value is found; returns a default value instead of `None`. - -For a detailed explanation of storage maps, see the [`StorageMap`](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/struct.StorageMap.html){target=\_blank} entry in the Rust docs. - -### Account Info - -The `AccountInfo` structure is another key element within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank}, providing more granular details about each account's state. This structure tracks vital data, such as the number of transactions and the account’s relationships with other modules. - -```rs -/// Information of an account. -#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)] -pub struct AccountInfo { - /// The number of transactions this account has sent. - pub nonce: Nonce, - /// The number of other modules that currently depend on this account's existence. The account - /// cannot be reaped until this is zero. - pub consumers: RefCount, - /// The number of other modules that allow this account to exist. The account may not be reaped - /// until this and `sufficients` are both zero. - pub providers: RefCount, - /// The number of modules that allow this account to exist for their own purposes only. The - /// account may not be reaped until this and `providers` are both zero. - pub sufficients: RefCount, - /// The additional data that belongs to this account. Used to store the balance(s) in a lot of - /// chains. - pub data: AccountData, -} -``` +The Polkadot SDK includes a feature-rich node called "kitchensink" located at `substrate/bin/node`. This node comes pre-configured with many pallets and features from the Polkadot SDK, making it an excellent reference for exploring capabilities and understanding how different components work together. -The `AccountInfo` structure includes the following components: +!!!note + If you've already compiled the Polkadot SDK in the previous step, the `substrate-node` binary is already built and ready to use. You can skip directly to running the node. -- **`nonce`**: Tracks the number of transactions initiated by the account, which ensures transaction uniqueness and prevents replay attacks. -- **`consumers`**: Counts how many other modules or pallets rely on this account’s existence. The account cannot be removed from the chain (reaped) until this count reaches zero. -- **`providers`**: Tracks how many modules permit this account’s existence. An account can only be reaped once both `providers` and `sufficients` are zero. -- **`sufficients`**: Represents the number of modules that allow the account to exist for internal purposes, independent of any other modules. -- **`AccountData`**: A flexible data structure that can be customized in the runtime configuration, usually containing balances or other user-specific data. +### Run the Kitchensink Node in Development Mode -This structure helps manage an account's state and prevents its premature removal while it is still referenced by other on-chain data or modules. The [`AccountInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.AccountInfo.html){target=\_blank} structure can vary as long as it satisfies the trait bounds defined by the `AccountData` associated type in the [`frame-system::pallet::Config`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/trait.Config.html){target=\_blank} trait. +From the `polkadot-sdk` root directory, start the kitchensink node in development mode: -### Account Reference Counters +```bash +./target/release/substrate-node --dev +``` -Polkadot SDK uses reference counters to track an account’s dependencies across different runtime modules. These counters ensure that accounts remain active while data is associated with them. +The `--dev` flag enables development mode, which: -The reference counters include: +- Runs a single-node development chain. +- Produces and finalizes blocks automatically. +- Uses pre-configured development accounts (Alice, Bob, etc.). +- Deletes all data when stopped, ensuring a clean state on restart. -- **`consumers`**: Prevents account removal while other pallets still rely on the account. -- **`providers`**: Ensures an account is active before other pallets store data related to it. -- **`sufficients`**: Indicates the account’s independence, ensuring it can exist even without a native token balance, such as when holding sufficient alternative assets. -#### Providers Reference Counters +You should see log output indicating the node is running and producing blocks, with increasing block numbers after `finalized`. -The `providers` counter ensures that an account is ready to be depended upon by other runtime modules. For example, it is incremented when an account has a balance above the existential deposit, which marks the account as active. +### Interact with the Kitchensink Node -The system requires this reference counter to be greater than zero for the `consumers` counter to be incremented, ensuring the account is stable before any dependencies are added. +The kitchensink node is accessible at `ws://localhost:9944`. Open [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} in your browser to explore its features and connect to the local node. -#### Consumers Reference Counters +1. Click the network icon in the top left corner. +2. Scroll to **Development** and select **Local Node**. +3. Click **Switch** to connect to your local node. -The `consumers` counter ensures that the account cannot be reaped until all references to it across the runtime have been removed. This check prevents the accidental deletion of accounts that still have active on-chain data. +![](/images/parachains/install-polkadot-sdk/install-polkadot-sdk-1.webp) -It is the user’s responsibility to clear out any data from other runtime modules if they wish to remove their account and reclaim their existential deposit. +Once connected, the interface updates its color scheme to indicate a successful connection to the local node. -#### Sufficients Reference Counter +![](/images/parachains/install-polkadot-sdk/install-polkadot-sdk-2.webp) -The `sufficients` counter tracks accounts that can exist independently without relying on a native account balance. This is useful for accounts holding other types of assets, like tokens, without needing a minimum balance in the native token. +You can now explore the various pallets and features included in the kitchensink node, making it a valuable reference as you develop your own blockchain applications. -For instance, the [Assets pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_assets/index.html){target=\_blank}, may increment this counter for an account holding sufficient tokens. +To stop the node, press `Control-C` in the terminal. -#### Account Deactivation +## Where to Go Next -In Polkadot SDK-based chains, an account is deactivated when its reference counters (such as `providers`, `consumers`, and `sufficient`) reach zero. These counters ensure the account remains active as long as other runtime modules or pallets reference it. +
-When all dependencies are cleared and the counters drop to zero, the account becomes deactivated and may be removed from the chain (reaped). This is particularly important in Polkadot SDK-based blockchains, where accounts with balances below the existential deposit threshold are pruned from storage to conserve state resources. +- __Get Started with Parachain Development__ -Each pallet that references an account has cleanup functions that decrement these counters when the pallet no longer depends on the account. Once these counters reach zero, the account is marked for deactivation. + --- -#### Updating Counters + Practical examples and tutorials for building and deploying Polkadot parachains, covering everything from launch to customization and cross-chain messaging. -The Polkadot SDK provides runtime developers with various methods to manage account lifecycle events, such as deactivation or incrementing reference counters. These methods ensure that accounts cannot be reaped while still in use. + [:octicons-arrow-right-24: Get Started](/parachains/get-started/) + +
-The following helper functions manage these counters: -- **`inc_consumers()`**: Increments the `consumer` reference counter for an account, signaling that another pallet depends on it. -- **`dec_consumers()`**: Decrements the `consumer` reference counter, signaling that a pallet no longer relies on the account. -- **`inc_providers()`**: Increments the `provider` reference counter, ensuring the account remains active. -- **`dec_providers()`**: Decrements the `provider` reference counter, allowing for account deactivation when no longer in use. -- **`inc_sufficients()`**: Increments the `sufficient` reference counter for accounts that hold sufficient assets. -- **`dec_sufficients()`**: Decrements the `sufficient` reference counter. +--- -To ensure proper account cleanup and lifecycle management, a corresponding decrement should be made for each increment action. +Page Title: JSON-RPC APIs -The `System` pallet offers three query functions to assist developers in tracking account states: +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-json-rpc-apis.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/for-eth-devs/json-rpc-apis/ +- Summary: JSON-RPC APIs guide for Polkadot Hub, covering supported methods, parameters, and examples for interacting with the chain. -- **[`can_inc_consumer()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_inc_consumer){target=\_blank}**: Checks if the account can safely increment the consumer reference. -- **[`can_dec_provider()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_dec_provider){target=\_blank}**: Ensures that no consumers exist before allowing the decrement of the provider counter. -- **[`is_provider_required()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.is_provider_required){target=\_blank}**: Verifies whether the account still has any active consumer references. +# JSON-RPC APIs -This modular and flexible system of reference counters tightly controls the lifecycle of accounts in Polkadot SDK-based blockchains, preventing the accidental removal or retention of unneeded accounts. You can refer to the [System pallet Rust docs](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html){target=\_blank} for more details. - +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. +## Introduction -## Account Balance Types +Polkadot Hub provides Ethereum compatibility through its JSON-RPC interface, allowing developers to interact with the chain using familiar Ethereum tooling and methods. This document outlines the supported [Ethereum JSON-RPC methods](https://ethereum.org/developers/docs/apis/json-rpc/#json-rpc-methods){target=\_blank} and provides examples of how to use them. -In the Polkadot ecosystem, account balances are categorized into different types based on how the funds are utilized and their availability. These balance types determine the actions that can be performed, such as transferring tokens, paying transaction fees, or participating in governance activities. Understanding these balance types helps developers manage user accounts and implement balance-dependent logic. +This guide uses the Polkadot Hub TestNet endpoint: -!!! note "A more efficient distribution of account balance types is in development" - Soon, pallets in the Polkadot SDK will implement the [`Fungible` trait](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} (see the [tracking issue](https://github.com/paritytech/polkadot-sdk/issues/226){target=\_blank} for more details). For example, the [`transaction-storage`](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_storage/index.html){target=\_blank} pallet changed the implementation of the [`Currency`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/currency/index.html){target=\_blank} trait (see the [Refactor transaction storage pallet to use fungible traits](https://github.com/paritytech/polkadot-sdk/pull/1800){target=\_blank} PR for further details): +```text +https://testnet-passet-hub-eth-rpc.polkadot.io +``` - ```rust - type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; - ``` - - To the [`Fungible`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} trait: +## Available Methods - ```rust - type BalanceOf = <::Currency as FnInspect<::AccountId>>::Balance; - ``` - - This update will enable more efficient use of account balances, allowing the free balance to be utilized for on-chain activities such as setting proxies and managing identities. +### eth_accounts -### Balance Types +Returns a list of addresses owned by the client. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_accounts){target=\_blank}. -The five main balance types are: +**Parameters**: -- **Free balance**: Represents the total tokens available to the account for any on-chain activity, including staking, governance, and voting. However, it may not be fully spendable or transferrable if portions of it are locked or reserved. -- **Locked balance**: Portions of the free balance that cannot be spent or transferred because they are tied up in specific activities like [staking](https://wiki.polkadot.com/learn/learn-staking/#nominating-validators){target=\_blank}, [vesting](https://wiki.polkadot.com/learn/learn-guides-transfers/#vested-transfers-with-the-polkadot-js-ui){target=\_blank}, or participating in [governance](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank}. While the tokens remain part of the free balance, they are non-transferable for the duration of the lock. -- **Reserved balance**: Funds locked by specific system actions, such as setting up an [identity](https://wiki.polkadot.com/learn/learn-identity/){target=\_blank}, creating [proxies](https://wiki.polkadot.com/learn/learn-proxies/){target=\_blank}, or submitting [deposits for governance proposals](https://wiki.polkadot.com/learn/learn-guides-polkadot-opengov/#claiming-opengov-deposits){target=\_blank}. These tokens are not part of the free balance and cannot be spent unless they are unreserved. -- **Spendable balance**: The portion of the free balance that is available for immediate spending or transfers. It is calculated by subtracting the maximum of locked or reserved amounts from the free balance, ensuring that existential deposit limits are met. -- **Untouchable balance**: Funds that cannot be directly spent or transferred but may still be utilized for on-chain activities, such as governance participation or staking. These tokens are typically tied to certain actions or locked for a specific period. +None. -The spendable balance is calculated as follows: +**Example**: -```text -spendable = free - max(locked - reserved, ED) +```bash title="eth_accounts" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_accounts", + "params":[], + "id":1 +}' ``` -Here, `free`, `locked`, and `reserved` are defined above. The `ED` represents the [existential deposit](https://wiki.polkadot.com/learn/learn-accounts/#existential-deposit-and-reaping){target=\_blank}, the minimum balance required to keep an account active and prevent it from being reaped. You may find you can't see all balance types when looking at your account via a wallet. Wallet providers often display only spendable, locked, and reserved balances. - -### Locks +--- -Locks are applied to an account's free balance, preventing that portion from being spent or transferred. Locks are automatically placed when an account participates in specific on-chain activities, such as staking or governance. Although multiple locks may be applied simultaneously, they do not stack. Instead, the largest lock determines the total amount of locked tokens. +### eth_blockNumber -Locks follow these basic rules: +Returns the number of the most recent block. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_blocknumber){target=\_blank}. -- If different locks apply to varying amounts, the largest lock amount takes precedence. -- If multiple locks apply to the same amount, the lock with the longest duration governs when the balance can be unlocked. +**Parameters**: -#### Locks Example +None. -Consider an example where an account has 80 DOT locked for both staking and governance purposes like so: +**Example**: -- 80 DOT is staked with a 28-day lock period. -- 24 DOT is locked for governance with a 1x conviction and a 7-day lock period. -- 4 DOT is locked for governance with a 6x conviction and a 224-day lock period. +```bash title="eth_blockNumber" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_blockNumber", + "params":[], + "id":1 +}' +``` -In this case, the total locked amount is 80 DOT because only the largest lock (80 DOT from staking) governs the locked balance. These 80 DOT will be released at different times based on the lock durations. In this example, the 24 DOT locked for governance will be released first since the shortest lock period is seven days. The 80 DOT stake with a 28-day lock period is released next. Now, all that remains locked is the 4 DOT for governance. After 224 days, all 80 DOT (minus the existential deposit) will be free and transferable. +--- -![Illustration of Lock Example](/images/reference/parachains/accounts/accounts-01.webp) +### eth_call -#### Edge Cases for Locks +Executes a new message call immediately without creating a transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_call){target=\_blank}. -In scenarios where multiple convictions and lock periods are active, the lock duration and amount are determined by the longest period and largest amount. For example, if you delegate with different convictions and attempt to undelegate during an active lock period, the lock may be extended for the full amount of tokens. For a detailed discussion on edge case lock behavior, see this [Stack Exchange post](https://substrate.stackexchange.com/questions/5067/delegating-and-undelegating-during-the-lock-period-extends-it-for-the-initial-am){target=\_blank}. +**Parameters**: -### Balance Types on Polkadot.js +- **`transaction` ++"object"++**: The transaction call object. + - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -Polkadot.js provides a user-friendly interface for managing and visualizing various account balances on Polkadot and Kusama networks. When interacting with Polkadot.js, you will encounter multiple balance types that are critical for understanding how your funds are distributed and restricted. This section explains how different balances are displayed in the Polkadot.js UI and what each type represents. +**Example**: -![](/images/reference/parachains/accounts/accounts-02.webp) +```bash title="eth_call" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_call", + "params":[{ + "to": "INSERT_RECIPIENT_ADDRESS", + "data": "INSERT_ENCODED_CALL" + }, "INSERT_BLOCK_VALUE"], + "id":1 +}' +``` -The most common balance types displayed on Polkadot.js are: +Ensure to replace the `INSERT_RECIPIENT_ADDRESS`, `INSERT_ENCODED_CALL`, and `INSERT_BLOCK_VALUE` with the proper values. -- **Total balance**: The total number of tokens available in the account. This includes all tokens, whether they are transferable, locked, reserved, or vested. However, the total balance does not always reflect what can be spent immediately. In this example, the total balance is 0.6274 KSM. +--- -- **Transferable balance**: Shows how many tokens are immediately available for transfer. It is calculated by subtracting the locked and reserved balances from the total balance. For example, if an account has a total balance of 0.6274 KSM and a transferable balance of 0.0106 KSM, only the latter amount can be sent or spent freely. +### eth_chainId -- **Vested balance**: Tokens that allocated to the account but released according to a specific schedule. Vested tokens remain locked and cannot be transferred until fully vested. For example, an account with a vested balance of 0.2500 KSM means that this amount is owned but not yet transferable. +Returns the chain ID used for signing transactions. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_chainid){target=\_blank}. -- **Locked balance**: Tokens that are temporarily restricted from being transferred or spent. These locks typically result from participating in staking, governance, or vested transfers. In Polkadot.js, locked balances do not stack—only the largest lock is applied. For instance, if an account has 0.5500 KSM locked for governance and staking, the locked balance would display 0.5500 KSM, not the sum of all locked amounts. +**Parameters**: -- **Reserved balance**: Refers to tokens locked for specific on-chain actions, such as setting an identity, creating a proxy, or making governance deposits. Reserved tokens are not part of the free balance, but can be freed by performing certain actions. For example, removing an identity would unreserve those funds. +None. -- **Bonded balance**: The tokens locked for staking purposes. Bonded tokens are not transferable until they are unbonded after the unbonding period. +**Example**: -- **Redeemable balance**: The number of tokens that have completed the unbonding period and are ready to be unlocked and transferred again. For example, if an account has a redeemable balance of 0.1000 KSM, those tokens are now available for spending. +```bash title="eth_chainId" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_chainId", + "params":[], + "id":1 +}' +``` -- **Democracy balance**: Reflects the number of tokens locked for governance activities, such as voting on referenda. These tokens are locked for the duration of the governance action and are only released after the lock period ends. +--- -By understanding these balance types and their implications, developers and users can better manage their funds and engage with on-chain activities more effectively. +### eth_estimateGas -## Address Formats +Estimates gas required for a transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_estimategas){target=\_blank}. -The SS58 address format is a core component of the Polkadot SDK that enables accounts to be uniquely identified across Polkadot-based networks. This format is a modified version of Bitcoin's Base58Check encoding, specifically designed to accommodate the multi-chain nature of the Polkadot ecosystem. SS58 encoding allows each chain to define its own set of addresses while maintaining compatibility and checksum validation for security. +**Parameters**: -### Basic Format +- **`transaction` ++"object"++**: The transaction call object. + - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -SS58 addresses consist of three main components: +**Example**: -```text -base58encode(concat(,
, )) +```bash title="eth_estimateGas" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_estimateGas", + "params":[{ + "to": "INSERT_RECIPIENT_ADDRESS", + "data": "INSERT_ENCODED_FUNCTION_CALL" + }], + "id":1 +}' ``` -- **Address type**: A byte or set of bytes that define the network (or chain) for which the address is intended. This ensures that addresses are unique across different Polkadot SDK-based chains. -- **Address**: The public key of the account encoded as bytes. -- **Checksum**: A hash-based checksum which ensures that addresses are valid and unaltered. The checksum is derived from the concatenated address type and address components, ensuring integrity. - -The encoding process transforms the concatenated components into a Base58 string, providing a compact and human-readable format that avoids easily confused characters (e.g., zero '0', capital 'O', lowercase 'l'). This encoding function ([`encode`](https://docs.rs/bs58/latest/bs58/fn.encode.html){target=\_blank}) is implemented exactly as defined in Bitcoin and IPFS specifications, using the same alphabet as both implementations. +Ensure to replace the `INSERT_RECIPIENT_ADDRESS` and `INSERT_ENCODED_CALL` with the proper values. -For more details about the SS58 address format implementation, see the [`Ss58Codec`](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Ss58Codec.html){target=\_blank} trait in the Rust Docs. +--- -### Address Type +### eth_gasPrice -The address type defines how an address is interpreted and to which network it belongs. Polkadot SDK uses different prefixes to distinguish between various chains and address formats: +Returns the current gas price in Wei. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gasprice){target=\_blank}. -- **Address types `0-63`**: Simple addresses, commonly used for network identifiers. -- **Address types `64-127`**: Full addresses that support a wider range of network identifiers. -- **Address types `128-255`**: Reserved for future address format extensions. +**Parameters**: -For example, Polkadot’s main network uses an address type of 0, while Kusama uses 2. This ensures that addresses can be used without confusion between networks. +None. -The address type is always encoded as part of the SS58 address, making it easy to quickly identify the network. Refer to the [SS58 registry](https://github.com/paritytech/ss58-registry){target=\_blank} for the canonical listing of all address type identifiers and how they map to Polkadot SDK-based networks. +**Example**: -### Address Length +```bash title="eth_gasPrice" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_gasPrice", + "params":[], + "id":1 +}' +``` -SS58 addresses can have different lengths depending on the specific format. Address lengths range from as short as 3 to 35 bytes, depending on the complexity of the address and network requirements. This flexibility allows SS58 addresses to adapt to different chains while providing a secure encoding mechanism. +--- -| Total | Type | Raw account | Checksum | -|-------|------|-------------|----------| -| 3 | 1 | 1 | 1 | -| 4 | 1 | 2 | 1 | -| 5 | 1 | 2 | 2 | -| 6 | 1 | 4 | 1 | -| 7 | 1 | 4 | 2 | -| 8 | 1 | 4 | 3 | -| 9 | 1 | 4 | 4 | -| 10 | 1 | 8 | 1 | -| 11 | 1 | 8 | 2 | -| 12 | 1 | 8 | 3 | -| 13 | 1 | 8 | 4 | -| 14 | 1 | 8 | 5 | -| 15 | 1 | 8 | 6 | -| 16 | 1 | 8 | 7 | -| 17 | 1 | 8 | 8 | -| 35 | 1 | 32 | 2 | +### eth_getBalance -SS58 addresses also support different payload sizes, allowing a flexible range of account identifiers. +Returns the balance of a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getbalance){target=\_blank}. -### Checksum Types +**Parameters**: -A checksum is applied to validate SS58 addresses. Polkadot SDK uses a Blake2b-512 hash function to calculate the checksum, which is appended to the address before encoding. The checksum length can vary depending on the address format (e.g., 1-byte, 2-byte, or longer), providing varying levels of validation strength. +- **`address` ++"string"++**: Address to query balance. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -The checksum ensures that an address is not modified or corrupted, adding an extra layer of security for account management. +**Example**: -### Validating Addresses +```bash title="eth_getBalance" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getBalance", + "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], + "id":1 +}' +``` -SS58 addresses can be validated using the subkey command-line interface or the Polkadot.js API. These tools help ensure an address is correctly formatted and valid for the intended network. The following sections will provide an overview of how validation works with these tools. +Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. -#### Using Subkey +--- -[Subkey](https://paritytech.github.io/polkadot-sdk/master/subkey/index.html){target=\_blank} is a CLI tool provided by Polkadot SDK for generating and managing keys. It can inspect and validate SS58 addresses. +### eth_getBlockByHash -The `inspect` command gets a public key and an SS58 address from the provided secret URI. The basic syntax for the `subkey inspect` command is: +Returns information about a block by its hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblockbyhash){target=\_blank}. -```bash -subkey inspect [flags] [options] uri -``` +**Parameters**: -For the `uri` command-line argument, you can specify the secret seed phrase, a hex-encoded private key, or an SS58 address. If the input is a valid address, the `subkey` program displays the corresponding hex-encoded public key, account identifier, and SS58 addresses. +- **`blockHash` ++"string"++**: The hash of the block to retrieve. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`fullTransactions` ++"boolean"++**: If `true`, returns full transaction details; if `false`, returns only transaction hashes. -For example, to inspect the public keys derived from a secret seed phrase, you can run a command similar to the following: +**Example**: -```bash -subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" +```bash title="eth_getBlockByHash" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getBlockByHash", + "params":["INSERT_BLOCK_HASH", INSERT_BOOLEAN], + "id":1 +}' ``` -The command displays output similar to the following: +Ensure to replace the `INSERT_BLOCK_HASH` and `INSERT_BOOLEAN` with the proper values. -
- subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" - Secret phrase `caution juice atom organ advance problem want pledge someone senior holiday very` is account: - Secret seed: 0xc8fa03532fb22ee1f7f6908b9c02b4e72483f0dbd66e4cd456b8f34c6230b849 - Public key (hex): 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - Public key (SS58): 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR - Account ID: 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - SS58 Address: 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR -
+--- -The `subkey` program assumes an address is based on a public/private key pair. If you inspect an address, the command returns the 32-byte account identifier. +### eth_getBlockByNumber -However, not all addresses in Polkadot SDK-based networks are based on keys. +Returns information about a block by its number. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblockbynumber){target=\_blank}. -Depending on the command-line options you specify and the input you provided, the command output might also display the network for which the address has been encoded. For example: +**Parameters**: -```bash -subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" -``` +- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. +- **`fullTransactions` ++"boolean"++**: If `true`, returns full transaction details; if `false`, returns only transaction hashes. -The command displays output similar to the following: +**Example**: -
- subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" - Public Key URI `12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU` is account: - Network ID/Version: polkadot - Public key (hex): 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Account ID: 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Public key (SS58): 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU - SS58 Address: 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU -
+```bash title="eth_getBlockByNumber" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getBlockByNumber", + "params":["INSERT_BLOCK_VALUE", INSERT_BOOLEAN], + "id":1 +}' +``` -#### Using Polkadot.js API +Ensure to replace the `INSERT_BLOCK_VALUE` and `INSERT_BOOLEAN` with the proper values. -To verify an address in JavaScript or TypeScript projects, you can use the functions built into the [Polkadot.js API](https://polkadot.js.org/docs/){target=\_blank}. For example: +--- -```js -// Import Polkadot.js API dependencies -const { decodeAddress, encodeAddress } = require('@polkadot/keyring'); -const { hexToU8a, isHex } = require('@polkadot/util'); +### eth_getBlockTransactionCountByNumber -// Specify an address to test. -const address = 'INSERT_ADDRESS_TO_TEST'; +Returns the number of transactions in a block from a block number. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbynumber){target=\_blank}. -// Check address -const isValidSubstrateAddress = () => { - try { - encodeAddress(isHex(address) ? hexToU8a(address) : decodeAddress(address)); +**Parameters**: - return true; - } catch (error) { - return false; - } -}; +- **`blockValue` ++"string"++**: The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. -// Query result -const isValid = isValidSubstrateAddress(); -console.log(isValid); +**Example**: +```bash title="eth_getBlockTransactionCountByNumber" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getBlockTransactionCountByNumber", + "params":["INSERT_BLOCK_VALUE"], + "id":1 +}' ``` -If the function returns `true`, the specified address is a valid address. - -#### Other SS58 Implementations +Ensure to replace the `INSERT_BLOCK_VALUE` with the proper values. -Support for encoding and decoding Polkadot SDK SS58 addresses has been implemented in several other languages and libraries. +--- -- **Crystal**: [`wyhaines/base58.cr`](https://github.com/wyhaines/base58.cr){target=\_blank} -- **Go**: [`itering/subscan-plugin`](https://github.com/itering/subscan-plugin){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **TypeScript**: [`subsquid/squid-sdk`](https://github.com/subsquid/squid-sdk){target=\_blank} +### eth_getBlockTransactionCountByHash +Returns the number of transactions in a block from a block hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getblocktransactioncountbyhash){target=\_blank}. ---- +**Parameters**: -Page Title: Polkadot-API +- **`blockHash` ++"string"++**: The hash of the block to retrieve. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-papi.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/papi/ -- Summary: Polkadot-API (PAPI) is a modular, composable library set designed for efficient interaction with Polkadot chains, prioritizing a "light-client first" approach. +**Example**: -# Polkadot-API +```bash title="eth_getBlockTransactionCountByHash" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getBlockTransactionCountByHash", + "params":["INSERT_BLOCK_HASH"], + "id":1 +}' +``` -## Introduction +Ensure to replace the `INSERT_BLOCK_HASH` with the proper values. -[Polkadot-API](https://github.com/polkadot-api/polkadot-api){target=\_blank} (PAPI) is a set of libraries built to be modular, composable, and grounded in a “light-client first” approach. Its primary aim is to equip dApp developers with an extensive toolkit for building fully decentralized applications. +--- -PAPI is optimized for light-client functionality, using the new JSON-RPC spec to support decentralized interactions fully. It provides strong TypeScript support with types and documentation generated directly from on-chain metadata, and it offers seamless access to storage reads, constants, transactions, events, and runtime calls. Developers can connect to multiple chains simultaneously and prepare for runtime updates through multi-descriptor generation and compatibility checks. PAPI is lightweight and performant, leveraging native BigInt, dynamic imports, and modular subpaths to avoid bundling unnecessary assets. It supports promise-based and observable-based APIs, integrates easily with Polkadot.js extensions, and offers signing options through browser extensions or private keys. +### eth_getCode -## Get Started +Returns the code at a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getcode){target=\_blank}. -### API Instantiation +**Parameters**: -To instantiate the API, you can install the package by using the following command: +- **`address` ++"string"++**: Contract or account address to query code. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). -=== "npm" +**Example**: - ```bash - npm i polkadot-api@1.17.2 - ``` +```bash title="eth_getCode" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getCode", + "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], + "id":1 +}' +``` -=== "pnpm" +Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. - ```bash - pnpm add polkadot-api@1.17.2 - ``` +--- -=== "yarn" +### eth_getLogs - ```bash - yarn add polkadot-api@1.17.2 - ``` +Returns an array of all logs matching a given filter object. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getlogs){target=\_blank}. -Then, obtain the latest metadata from the target chain and generate the necessary types: +**Parameters**: -```bash -# Add the target chain -npx papi add dot -n polkadot -``` +- **`filter` ++"object"++**: The filter object. + - **`fromBlock` ++"string"++**: (Optional) Block number or tag to start from. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. + - **`toBlock` ++"string"++**: (Optional) Block number or tag to end at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. + - **`address` ++"string" or "array of strings"++**: (Optional) Contract address or a list of addresses from which to get logs. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`topics` ++"array of strings"++**: (Optional) Array of topics for filtering logs. Each topic can be a single [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string or an array of such strings (meaning OR). + - **`blockhash` ++"string"++**: (Optional) Hash of a specific block. Cannot be used with `fromBlock` or `toBlock`. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -The `papi add` command initializes the library by generating the corresponding types needed for the chain used. It assigns the chain a custom name and specifies downloading metadata from the Polkadot chain. You can replace `dot` with the name you prefer or with another chain if you want to add a different one. Once the latest metadata is downloaded, generate the required types: +**Example**: -```bash -# Generate the necessary types -npx papi +```bash title="eth_getLogs" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getLogs", + "params":[{ + "fromBlock": "latest", + "toBlock": "latest" + }], + "id":1 +}' ``` -You can now set up a [`PolkadotClient`](https://github.com/polkadot-api/polkadot-api/blob/main/packages/client/src/types.ts#L153){target=\_blank} with your chosen provider to begin interacting with the API. Choose from Smoldot via WebWorker, Node.js, or direct usage, or connect through the WSS provider. The examples below show how to configure each option for your setup. +--- -=== "Smoldot (WebWorker)" +### eth_getStorageAt - ```typescript - // `dot` is the identifier assigned during `npx papi add` - import { dot } from '@polkadot-api/descriptors'; - import { createClient } from 'polkadot-api'; - import { getSmProvider } from 'polkadot-api/sm-provider'; - import { chainSpec } from 'polkadot-api/chains/polkadot'; - import { startFromWorker } from 'polkadot-api/smoldot/from-worker'; - import SmWorker from 'polkadot-api/smoldot/worker?worker'; +Returns the value from a storage position at a given address. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_getstorageat){target=\_blank}. - const worker = new SmWorker(); - const smoldot = startFromWorker(worker); - const chain = await smoldot.addChain({ chainSpec }); +**Parameters**: - // Establish connection to the Polkadot relay chain - const client = createClient(getSmProvider(chain)); +- **`address` ++"string"++**: Contract or account address to query code. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`storageKey` ++"string"++**: Position in storage to retrieve data from. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). - // To interact with the chain, obtain the `TypedApi`, which provides - // the necessary types for every API call on this chain - const dotApi = client.getTypedApi(dot); +**Example**: - ``` +```bash title="eth_getStorageAt" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getStorageAt", + "params":["INSERT_ADDRESS", "INSERT_STORAGE_KEY", "INSERT_BLOCK_VALUE"], + "id":1 +}' +``` -=== "Smoldot (Node.js)" - - ```typescript - // `dot` is the alias assigned during `npx papi add` - import { dot } from '@polkadot-api/descriptors'; - import { createClient } from 'polkadot-api'; - import { getSmProvider } from 'polkadot-api/sm-provider'; - import { chainSpec } from 'polkadot-api/chains/polkadot'; - import { startFromWorker } from 'polkadot-api/smoldot/from-node-worker'; - import { fileURLToPath } from 'url'; - import { Worker } from 'worker_threads'; - - // Get the path for the worker file in ESM - const workerPath = fileURLToPath( - import.meta.resolve('polkadot-api/smoldot/node-worker'), - ); +Ensure to replace the `INSERT_ADDRESS`, `INSERT_STORAGE_KEY`, and `INSERT_BLOCK_VALUE` with the proper values. - const worker = new Worker(workerPath); - const smoldot = startFromWorker(worker); - const chain = await smoldot.addChain({ chainSpec }); +--- - // Set up a client to connect to the Polkadot relay chain - const client = createClient(getSmProvider(chain)); +### eth_getTransactionCount - // To interact with the chain's API, use `TypedApi` for access to - // all the necessary types and calls associated with this chain - const dotApi = client.getTypedApi(dot); +Returns the number of transactions sent from an address (nonce). [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactioncount){target=\_blank}. - ``` +**Parameters**: -=== "Smoldot" +- **`address` ++"string"++**: Address to query balance. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block). - ```typescript - // `dot` is the alias assigned when running `npx papi add` - import { dot } from '@polkadot-api/descriptors'; - import { createClient } from 'polkadot-api'; - import { getSmProvider } from 'polkadot-api/sm-provider'; - import { chainSpec } from 'polkadot-api/chains/polkadot'; - import { start } from 'polkadot-api/smoldot'; +**Example**: - // Initialize Smoldot client - const smoldot = start(); - const chain = await smoldot.addChain({ chainSpec }); +```bash title="eth_getTransactionCount" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getTransactionCount", + "params":["INSERT_ADDRESS", "INSERT_BLOCK_VALUE"], + "id":1 +}' +``` - // Set up a client to connect to the Polkadot relay chain - const client = createClient(getSmProvider(chain)); +Ensure to replace the `INSERT_ADDRESS` and `INSERT_BLOCK_VALUE` with the proper values. - // Access the `TypedApi` to interact with all available chain calls and types - const dotApi = client.getTypedApi(dot); +--- - ``` +### eth_getTransactionByHash -=== "WSS" - - ```typescript - // `dot` is the identifier assigned when executing `npx papi add` - import { dot } from '@polkadot-api/descriptors'; - import { createClient } from 'polkadot-api'; - // Use this import for Node.js environments - import { getWsProvider } from 'polkadot-api/ws-provider/web'; - import { withPolkadotSdkCompat } from 'polkadot-api/polkadot-sdk-compat'; - - // Establish a connection to the Polkadot relay chain - const client = createClient( - // The Polkadot SDK nodes may have compatibility issues; using this enhancer is recommended. - // Refer to the Requirements page for additional details - withPolkadotSdkCompat(getWsProvider('wss://dot-rpc.stakeworld.io')), - ); +Returns information about a transaction by its hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyhash){target=\_blank}. - // To interact with the chain, obtain the `TypedApi`, which provides - // the types for all available calls in that chain - const dotApi = client.getTypedApi(dot); +**Parameters**: - ``` +- **`transactionHash` ++"string"++**: The hash of the transaction. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -Now that you have set up the client, you can interact with the chain by reading and sending transactions. +**Example**: -### Reading Chain Data +```bash title="eth_getTransactionByHash" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getTransactionByHash", + "params":["INSERT_TRANSACTION_HASH"], + "id":1 +}' +``` -The `TypedApi` provides a streamlined way to read blockchain data through three main interfaces, each designed for specific data access patterns: +Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper values. -- **Constants**: Access fixed values or configurations on the blockchain using the `constants` interface. +--- - ```typescript - const version = await typedApi.constants.System.Version(); - ``` +### eth_getTransactionByBlockNumberAndIndex -- **Storage queries**: Retrieve stored values by querying the blockchain’s storage via the `query` interface. +Returns information about a transaction by block number and transaction index. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyblocknumberandindex){target=\_blank}. - ```typescript - const asset = await api.query.ForeignAssets.Asset.getValue( - token.location, - { at: 'best' }, - ); - ``` +**Parameters**: -- **Runtime APIs**: Interact directly with runtime APIs using the `apis` interface. +- **`blockValue` ++"string"++**: The block value to be fetched. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. +- **`transactionIndex` ++"string"++**: The index of the transaction in the block. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - ```typescript - const metadata = await typedApi.apis.Metadata.metadata(); - ``` +**Example**: -To learn more about the different actions you can perform with the `TypedApi`, refer to the [TypedApi reference](https://papi.how/typed){target=\_blank}. +```bash title="eth_getTransactionByBlockNumberAndIndex" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getTransactionByBlockNumberAndIndex", + "params":["INSERT_BLOCK_VALUE", "INSERT_TRANSACTION_INDEX"], + "id":1 +}' +``` -### Sending Transactions +Ensure to replace the `INSERT_BLOCK_VALUE` and `INSERT_TRANSACTION_INDEX` with the proper values. -In PAPI, the `TypedApi` provides the `tx` and `txFromCallData` methods to send transactions. +--- -- The `tx` method allows you to directly send a transaction with the specified parameters by using the `typedApi.tx.Pallet.Call` pattern: +### eth_getTransactionByBlockHashAndIndex - ```typescript - const tx: Transaction = typedApi.tx.Pallet.Call({arg1, arg2, arg3}); - ``` +Returns information about a transaction by block hash and transaction index. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionbyblockhashandindex){target=\_blank}. - For instance, to execute the `balances.transferKeepAlive` call, you can use the following snippet: +**Parameters**: - ```typescript - import { MultiAddress } from '@polkadot-api/descriptors'; +- **`blockHash` ++"string"++**: The hash of the block. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`transactionIndex` ++"string"++**: The index of the transaction in the block. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. - const tx: Transaction = typedApi.tx.Balances.transfer_keep_alive({ - dest: MultiAddress.Id('INSERT_DESTINATION_ADDRESS'), - value: BigInt(INSERT_VALUE), - }); +**Example**: - ``` +```bash title="eth_getTransactionByBlockHashAndIndex" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getTransactionByBlockHashAndIndex", + "params":["INSERT_BLOCK_HASH", "INSERT_TRANSACTION_INDEX"], + "id":1 +}' +``` - Ensure you replace `INSERT_DESTINATION_ADDRESS` and `INSERT_VALUE` with the actual destination address and value, respectively. +Ensure to replace the `INSERT_BLOCK_HASH` and `INSERT_TRANSACTION_INDEX` with the proper values. -- The `txFromCallData` method allows you to send a transaction using the call data. This option accepts binary call data and constructs the transaction from it. It validates the input upon creation and will throw an error if invalid data is provided. The pattern is as follows: +--- - ```typescript - const callData = Binary.fromHex('0x...'); - const tx: Transaction = typedApi.txFromCallData(callData); - ``` +### eth_getTransactionReceipt - For instance, to execute a transaction using the call data, you can use the following snippet: +Returns the receipt of a transaction by transaction hash. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_gettransactionreceipt){target=\_blank}. - ```typescript - const callData = Binary.fromHex('0x00002470617065726d6f6f6e'); - const tx: Transaction = typedApi.txFromCallData(callData); - ``` +**Parameters**: -For more information about sending transactions, refer to the [Transactions](https://papi.how/typed/tx#transactions){target=\_blank} page. +- **`transactionHash` ++"string"++**: The hash of the transaction. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. -## Where to Go Next +**Example**: -For an in-depth guide on how to use PAPI, refer to the official [PAPI](https://papi.how/){target=\_blank} documentation. +```bash title="eth_getTransactionReceipt" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_getTransactionReceipt", + "params":["INSERT_TRANSACTION_HASH"], + "id":1 +}' +``` +Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper values. --- -Page Title: Polkadot.js API - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-polkadot-js-api.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/polkadot-js-api/ -- Summary: Interact with Polkadot SDK-based chains easily using the Polkadot.js API. Query chain data, submit transactions, and more via JavaScript or Typescript. - -# Polkadot.js API - -!!! warning "Maintenance Mode Only" - The Polkadot.js API is now in maintenance mode and is no longer actively developed. New projects should use [Dedot](/develop/toolkit/api-libraries/dedot){target=\_blank} (TypeScript-first API) or [Polkadot API](/develop/toolkit/api-libraries/papi){target=\_blank} (modern, type-safe API) as actively maintained alternatives. +### eth_maxPriorityFeePerGas -## Introduction +Returns an estimate of the current priority fee per gas, in Wei, to be included in a block. -The [Polkadot.js API](https://github.com/polkadot-js/api){target=\_blank} uses JavaScript/TypeScript to interact with Polkadot SDK-based chains. It allows you to query nodes, read chain state, and submit transactions through a dynamic, auto-generated API interface. +**Parameters**: -### Dynamic API Generation +None. -Unlike traditional static APIs, the Polkadot.js API generates its interfaces automatically when connecting to a node. Here's what happens when you connect: +**Example**: -1. The API connects to your node. -2. It retrieves the chain's metadata. -3. Based on this metadata, it creates specific endpoints in this format: `api...
`. +```bash title="eth_maxPriorityFeePerGas" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_maxPriorityFeePerGas", + "params":[], + "id":1 +}' +``` -### Available API Categories +--- -You can access three main categories of chain interactions: +### eth_sendRawTransaction -- **[Runtime constants](https://polkadot.js.org/docs/api/start/api.consts){target=\_blank}** (`api.consts`): +Submits a raw transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_sendrawtransaction){target=\_blank}. - - Access runtime constants directly. - - Returns values immediately without function calls. - - **Example**: `api.consts.balances.existentialDeposit` +**Parameters**: -- **[State queries](https://polkadot.js.org/docs/api/start/api.query/){target=\_blank}** (`api.query`): +- **`callData` ++"string"++**: Signed transaction data. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. - - Read chain state. - - **Example**: `api.query.system.account(accountId)` +**Example**: -- **[Transactions](https://polkadot.js.org/docs/api/start/api.tx/){target=\_blank}** (`api.tx`): - - Submit extrinsics (transactions). - - **Example**: `api.tx.balances.transfer(accountId, value)` +```bash title="eth_sendRawTransaction" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_sendRawTransaction", + "params":["INSERT_CALL_DATA"], + "id":1 +}' +``` -The available methods and interfaces will automatically reflect what's possible on your connected chain. +Ensure to replace the `INSERT_CALL_DATA` with the proper values. -## Installation +--- -To add the Polkadot.js API to your project, use the following command to install the version `16.4.7` which supports any Polkadot SDK-based chain: +### eth_sendTransaction -=== "npm" - ```bash - npm i @polkadot/api@16.4.7 - ``` +Creates and sends a new transaction. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_sendtransaction){target=\_blank}. -=== "pnpm" - ```bash - pnpm add @polkadot/api@16.4.7 - ``` +**Parameters**: -=== "yarn" - ```bash - yarn add @polkadot/api@16.4.7 - ``` +- **`transaction` ++"object"++**: The transaction object. + - **`from` ++"string"++**: Address sending the transaction. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`to` ++"string"++**: (Optional) Recipient address. No need to provide this value when deploying a contract. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`gas` ++"string"++**: (optional, default: `90000`) gas limit for execution. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`gasPrice` ++"string"++**: (Optional) Gas price per unit. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`value` ++"string"++**: (Optional) Amount of Ether to send. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`data` ++"string"++**: (Optional) Contract bytecode or encoded method call. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`nonce` ++"string"++**: (Optional) Transaction nonce. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. -For more detailed information about installation, see the [Installation](https://polkadot.js.org/docs/api/start/install/){target=\_blank} section in the official Polkadot.js API documentation. +**Example**: -## Get Started +```bash title="eth_sendTransaction" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_sendTransaction", + "params":[{ + "from": "INSERT_SENDER_ADDRESS", + "to": "INSERT_RECIPIENT_ADDRESS", + "gas": "INSERT_GAS_LIMIT", + "gasPrice": "INSERT_GAS_PRICE", + "value": "INSERT_VALUE", + "input": "INSERT_INPUT_DATA", + "nonce": "INSERT_NONCE" + }], + "id":1 +}' +``` -### Creating an API Instance +Ensure to replace the `INSERT_SENDER_ADDRESS`, `INSERT_RECIPIENT_ADDRESS`, `INSERT_GAS_LIMIT`, `INSERT_GAS_PRICE`, `INSERT_VALUE`, `INSERT_INPUT_DATA`, and `INSERT_NONCE` with the proper values. -To interact with a Polkadot SDK-based chain, you must establish a connection through an API instance. The API provides methods for querying chain state, sending transactions, and subscribing to updates. +--- -To create an API connection: +### eth_syncing -```js -import { ApiPromise, WsProvider } from '@polkadot/api'; +Returns an object with syncing data or `false` if not syncing. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_syncing){target=\_blank}. -// Create a WebSocket provider -const wsProvider = new WsProvider('wss://rpc.polkadot.io'); +**Parameters**: -// Initialize the API -const api = await ApiPromise.create({ provider: wsProvider }); +None. -// Verify the connection by getting the chain's genesis hash -console.log('Genesis Hash:', api.genesisHash.toHex()); +**Example**: +```bash title="eth_syncing" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"eth_syncing", + "params":[], + "id":1 +}' ``` -!!!warning - All `await` operations must be wrapped in an async function or block since the API uses promises for asynchronous operations. - -### Reading Chain Data - -The API provides several ways to read data from the chain. You can access: - -- **Constants**: Values that are fixed in the runtime and don't change without a runtime upgrade. - - ```js - // Get the minimum balance required for a new account - const minBalance = api.consts.balances.existentialDeposit.toNumber(); - - ``` - -- **State**: Current chain state that updates with each block. +--- - ```js - // Example address - const address = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFabHE'; +### net_listening - // Get current timestamp - const timestamp = await api.query.timestamp.now(); +Returns `true` if the client is currently listening for network connections, otherwise `false`. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#net_listening){target=\_blank}. - // Get account information - const { nonce, data: balance } = await api.query.system.account(address); +**Parameters**: - console.log(` - Timestamp: ${timestamp} - Free Balance: ${balance.free} - Nonce: ${nonce} - `); +None. - ``` +**Example**: -### Sending Transactions +```bash title="net_listening" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"net_listening", + "params":[], + "id":1 +}' +``` -Transactions (also called extrinsics) modify the chain state. Before sending a transaction, you need: +--- -- A funded account with sufficient balance to pay transaction fees. -- The account's keypair for signing. +### net_peerCount -To make a transfer: +Returns the number of peers currently connected to the client. -```js -// Assuming you have an `alice` keypair from the Keyring -const recipient = 'INSERT_RECIPIENT_ADDRESS'; -const amount = 'INSERT_VALUE'; // Amount in the smallest unit (e.g., Planck for DOT) +**Parameters**: -// Sign and send a transfer -const txHash = await api.tx.balances - .transfer(recipient, amount) - .signAndSend(alice); +None. -console.log('Transaction Hash:', txHash); +**Example**: +```bash title="net_peerCount" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"net_peerCount", + "params":[], + "id":1 +}' ``` -The `alice` keypair in the example comes from a `Keyring` object. For more details about managing keypairs, see the [Keyring documentation](https://polkadot.js.org/docs/keyring){target=\_blank}. +--- -## Where to Go Next +### net_version -For more detailed information about the Polkadot.js API, check the [official documentation](https://polkadot.js.org/docs/){target=\_blank}. +Returns the current network ID as a string. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#net_version){target=\_blank}. +**Parameters**: ---- +None. -Page Title: Python Substrate Interface +**Example**: -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-py-substrate-interface.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/py-substrate-interface/ -- Summary: Learn how to connect to Polkadot SDK-based nodes, query data, submit transactions, and manage blockchain interactions using the Python Substrate Interface. +```bash title="net_version" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"net_version", + "params":[], + "id":1 +}' +``` -# Python Substrate Interface +--- -## Introduction +### system_health -The [Python Substrate Interface](https://github.com/polkascan/py-substrate-interface){target=\_blank} is a powerful library that enables interaction with Polkadot SDK-based chains. It provides essential functionality for: +Returns information about the health of the system. -- Querying on-chain storage. -- Composing and submitting extrinsics. -- SCALE encoding/decoding. -- Interacting with Substrate runtime metadata. -- Managing blockchain interactions through convenient utility methods. +**Parameters**: -## Installation +None. -Install the library using `pip`: +**Example**: -```py -pip install substrate-interface +```bash title="system_health" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"system_health", + "params":[], + "id":1 +}' ``` -For more installation details, see the [Installation](https://jamdottech.github.io/py-polkadot-sdk/getting-started/installation/){target=\_blank} section in the official Python Substrate Interface documentation. - -## Get Started - -This guide will walk you through the basic operations with the Python Substrate Interface: connecting to a node, reading chain state, and submitting transactions. +--- -### Establishing Connection +### web3_clientVersion -The first step is to establish a connection to a Polkadot SDK-based node. You can connect to either a local or remote node: +Returns the current client version. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#web3_clientversion){target=\_blank}. -```py -from substrateinterface import SubstrateInterface +**Parameters**: -# Connect to a node using websocket -substrate = SubstrateInterface( - # For local node: "ws://127.0.0.1:9944" - # For Polkadot: "wss://rpc.polkadot.io" - # For Kusama: "wss://kusama-rpc.polkadot.io" - url="INSERT_WS_URL" -) +None. -# Verify connection -print(f"Connected to chain: {substrate.chain}") +**Example**: +```bash title="web3_clientVersion" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"web3_clientVersion", + "params":[], + "id":1 +}' ``` -### Reading Chain State - -You can query various on-chain storage items. To retrieve data, you need to specify three key pieces of information: - -- **Pallet name**: Module or pallet that contains the storage item you want to access. -- **Storage item**: Specific storage entry you want to query within the pallet. -- **Required parameters**: Any parameters needed to retrieve the desired data. +--- -Here's an example of how to check an account's balance and other details: +### debug_traceBlockByNumber -```py -# ... +Traces a block's execution by its number and returns a detailed execution trace for each transaction. -# Query account balance and info -account_info = substrate.query( - module="System", # The pallet name - storage_function="Account", # The storage item - params=["INSERT_ADDRESS"], # Account address in SS58 format -) +**Parameters**: -# Access account details from the result -free_balance = account_info.value["data"]["free"] -reserved = account_info.value["data"]["reserved"] -nonce = account_info.value["nonce"] +- **`blockValue` ++"string"++**: The block number or tag to trace. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. +- **`options` ++"object"++**: (Optional) An object containing tracer options. + - **`tracer` ++"string"++**: The name of the tracer to use (e.g., `"callTracer"`, `"opTracer"`). + - Other tracer-specific options may be supported. -print( - f""" - Account Details: - - Free Balance: {free_balance} - - Reserved: {reserved} - - Nonce: {nonce} - """ -) +**Example**: +```bash title="debug_traceBlockByNumber" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"debug_traceBlockByNumber", + "params":["INSERT_BLOCK_VALUE", {"tracer": "callTracer"}], + "id":1 +}' ``` -### Submitting Transactions - -To modify the chain state, you need to submit transactions (extrinsics). Before proceeding, ensure you have: - -- A funded account with sufficient balance to pay transaction fees. -- Access to the account's keypair. +Ensure to replace `INSERT_BLOCK_VALUE` with a proper block number if needed. -Here's how to create and submit a balance transfer: +--- -```py -#... +### debug_traceTransaction -# Compose the transfer call -call = substrate.compose_call( - call_module="Balances", # The pallet name - call_function="transfer_keep_alive", # The extrinsic function - call_params={ - 'dest': 'INSERT_ADDRESS', # Recipient's address - 'value': 'INSERT_VALUE' # Amount in smallest unit (e.g., Planck for DOT) - } -) +Traces the execution of a single transaction by its hash and returns a detailed execution trace. -# Create a signed extrinsic -extrinsic = substrate.create_signed_extrinsic( - call=call, keypair=keypair # Your keypair for signing -) +**Parameters**: -# Submit and wait for inclusion -receipt = substrate.submit_extrinsic( - extrinsic, wait_for_inclusion=True # Wait until the transaction is in a block -) +- **`transactionHash` ++"string"++**: The hash of the transaction to trace. Must be a [32 byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. +- **`options` ++"object"++**: (Optional) An object containing tracer options (e.g., `tracer: "callTracer"`). -if receipt.is_success: - print( - f""" - Transaction successful: - - Extrinsic Hash: {receipt.extrinsic_hash} - - Block Hash: {receipt.block_hash} - """ - ) -else: - print(f"Transaction failed: {receipt.error_message}") +**Example**: +```bash title="debug_traceTransaction" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"debug_traceTransaction", + "params":["INSERT_TRANSACTION_HASH", {"tracer": "callTracer"}], + "id":1 +}' ``` -The `keypair` object is essential for signing transactions. See the [Keypair](https://jamdottech.github.io/py-polkadot-sdk/reference/keypair/){target=\_blank} documentation for more details. - -## Where to Go Next - -Now that you understand the basics, you can: - -- Explore more complex queries and transactions. -- Learn about batch transactions and utility functions. -- Discover how to work with custom pallets and types. +Ensure to replace the `INSERT_TRANSACTION_HASH` with the proper value. -For comprehensive reference materials and advanced features, see the [Python Substrate Interface](https://jamdottech.github.io/py-polkadot-sdk/){target=\_blank} documentation. +--- +### debug_traceCall ---- +Executes a new message call and returns a detailed execution trace without creating a transaction on the blockchain. -Page Title: Randomness +**Parameters**: -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-randomness.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/randomness/ -- Summary: Explore the importance of randomness in PoS blockchains, focusing on Polkadot’s VRF-based approach to ensure fairness and security in validator selection. +- **`transaction` ++"object"++**: The transaction call object, similar to `eth_call` parameters. + - **`to` ++"string"++**: Recipient address of the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`data` ++"string"++**: Hash of the method signature and encoded parameters. Must be a [data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`from` ++"string"++**: (Optional) Sender's address for the call. Must be a [20-byte data](https://ethereum.org/developers/docs/apis/json-rpc/#unformatted-data-encoding){target=\_blank} string. + - **`gas` ++"string"++**: (Optional) Gas limit to execute the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`gasPrice` ++"string"++**: (Optional) Gas price per unit of gas. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. + - **`value` ++"string"++**: (Optional) Value in wei to send with the call. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string. +- **`blockValue` ++"string"++**: (Optional) Block tag or block number to execute the call at. Must be a [quantity](https://ethereum.org/developers/docs/apis/json-rpc/#quantities-encoding){target=\_blank} string or a [default block parameter](https://ethereum.org/developers/docs/apis/json-rpc/#default-block){target=\_blank}. +- **`options` ++"object"++**: (Optional) An object containing tracer options (e.g., `tracer: "callTracer"`). -# Randomness +**Example**: -## Introduction +```bash title="debug_traceCall" +curl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \ +-H "Content-Type: application/json" \ +--data '{ + "jsonrpc":"2.0", + "method":"debug_traceCall", + "params":[{ + "from": "INSERT_SENDER_ADDRESS", + "to": "INSERT_RECIPIENT_ADDRESS", + "data": "INSERT_ENCODED_CALL" + }, "INSERT_BLOCK_VALUE", {"tracer": "callTracer"}], + "id":1 +}' +``` -Randomness is crucial in Proof of Stake (PoS) blockchains to ensure a fair and unpredictable distribution of validator duties. However, computers are inherently deterministic, meaning the same input always produces the same output. What we typically refer to as "random" numbers on a computer are actually pseudo-random. These numbers rely on an initial "seed," which can come from external sources like [atmospheric noise](https://www.random.org/randomness/){target=\_blank}, [heart rates](https://mdpi.altmetric.com/details/47574324){target=\_blank}, or even [lava lamps](https://en.wikipedia.org/wiki/Lavarand){target=\_blank}. While this may seem random, given the same "seed," the same sequence of numbers will always be generated. +Ensure to replace the `INSERT_SENDER_ADDRESS`, `INSERT_RECIPIENT_ADDRESS`, `INSERT_ENCODED_CALL`, and `INSERT_BLOCK_VALUE` with the proper value. -In a global blockchain network, relying on real-world entropy for randomness isn’t feasible because these inputs vary by time and location. If nodes use different inputs, blockchains can fork. Hence, real-world randomness isn't suitable for use as a seed in blockchain systems. +--- -Currently, two primary methods for generating randomness in blockchains are used: [`RANDAO`](#randao) and [`VRF`](#vrf) (Verifiable Random Function). Polkadot adopts the `VRF` approach for its randomness. +## Response Format -## VRF +All responses follow the standard JSON-RPC 2.0 format: -A Verifiable Random Function (VRF) is a cryptographic function that generates a random number and proof that ensures the submitter produced the number. This proof allows anyone to verify the validity of the random number. +```json +{ + "jsonrpc": "2.0", + "id": 1, + "result": ... // The return value varies by method +} +``` -Polkadot's VRF is similar to the one used in [**Ouroboros Praos**](https://eprint.iacr.org/2017/573.pdf){target=\_blank}, which secures randomness for block production in systems like [BABE](/reference/polkadot-hub/consensus-and-security/pos-consensus/#block-production-babe){target=\_blank} (Polkadot’s block production mechanism). +## Error Handling -The key difference is that Polkadot's VRF doesn’t rely on a central clock—avoiding the issue of whose clock to trust. Instead, it uses its own past results and slot numbers to simulate time and determine future outcomes. +If an error occurs, the response will include an error object: -### How VRF Works +```json +{ + "jsonrpc": "2.0", + "id": 1, + "error": { + "code": -32000, + "message": "Error message here" + } +} +``` -Slots on Polkadot are discrete units of time, each lasting six seconds, and can potentially hold a block. Multiple slots form an epoch, with 2400 slots making up one four-hour epoch. -In each slot, validators execute a "die roll" using a VRF. The VRF uses three inputs: +--- -1. A "secret key," unique to each validator, is used for the die roll. -2. An epoch randomness value, derived from the hash of VRF outputs from blocks two epochs ago (N-2), so past randomness influences the current epoch (N). -3. The current slot number. +Page Title: Oracles -This process helps maintain fair randomness across the network. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-oracles.md +- Canonical (HTML): https://docs.polkadot.com/parachains/integrations/oracles/ +- Summary: Learn about blockchain oracles, the essential bridges connecting blockchains with real-world data for decentralized applications in the Polkadot ecosystem. -Here is a graphical representation: +# Oracles -![](/images/reference/parachains/randomness/randomness-01.webp) +## What is a Blockchain Oracle? -The VRF produces two outputs: a result (the random number) and a proof (verifying that the number was generated correctly). +Oracles enable blockchains to access external data sources. Since blockchains operate as isolated networks, they cannot natively interact with external systems - this limitation is known as the "blockchain oracle problem." Oracles solves this by extracting data from external sources (like APIs, IoT devices, or other blockchains), validating it, and submitting it on-chain. -The result is checked by the validator against a protocol threshold. If it's below the threshold, the validator becomes a candidate for block production in that slot. +While simple oracle implementations may rely on a single trusted provider, more sophisticated solutions use decentralized networks where multiple providers stake assets and reach consensus on data validity. Typical applications include DeFi price feeds, weather data for insurance contracts, and cross-chain asset verification. -The validator then attempts to create a block, submitting it along with the `PROOF` and `RESULT`. +## Oracle Implementations -So, VRF can be expressed like: +
-`(RESULT, PROOF) = VRF(SECRET, EPOCH_RANDOMNESS_VALUE, CURRENT_SLOT_NUMBER)` +- __Acurast__ -Put simply, performing a "VRF roll" generates a random number along with proof that the number was genuinely produced and not arbitrarily chosen. + --- -After executing the VRF, the `RESULT` is compared to a protocol-defined `THRESHOLD`. If the `RESULT` is below the `THRESHOLD`, the validator becomes a valid candidate to propose a block for that slot. Otherwise, the validator skips the slot. + Acurast is a decentralized, serverless cloud platform that uses a distributed network of mobile devices for oracle services, addressing centralized trust and data ownership issues. In the Polkadot ecosystem, it allows developers to define off-chain data and computation needs, which are processed by these devices acting as decentralized oracle nodes, delivering results to Substrate (Wasm) and EVM environments. -As a result, there may be multiple validators eligible to propose a block for a slot. In this case, the block accepted by other nodes will prevail, provided it is on the chain with the latest finalized block as determined by the GRANDPA finality gadget. It's also possible for no block producers to be available for a slot, in which case the AURA consensus takes over. AURA is a fallback mechanism that randomly selects a validator to produce a block, running in parallel with BABE and only stepping in when no block producers exist for a slot. Otherwise, it remains inactive. + [:octicons-arrow-right-24: Reference](https://acurast.com/){target=\_blank} -Because validators roll independently, no block candidates may appear in some slots if all roll numbers are above the threshold. +
-To verify resolution of this issue and that Polkadot block times remain near constant-time, see the [PoS Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} page of this documentation. -## RANDAO +--- -An alternative on-chain randomness method is Ethereum's RANDAO, where validators perform thousands of hashes on a seed and publish the final hash during a round. The collective input from all validators forms the random number, and as long as one honest validator participates, the randomness is secure. +Page Title: Overview of FRAME -To enhance security, RANDAO can optionally be combined with a Verifiable Delay Function (VDF), ensuring that randomness can't be predicted or manipulated during computation. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime.md +- Canonical (HTML): https://docs.polkadot.com/parachains/customize-runtime/ +- Summary: Learn how Polkadot SDK’s FRAME framework simplifies blockchain development with modular pallets and support libraries for efficient runtime design. -For more information about RANDAO, see the [Randomness - RANDAO](https://eth2book.info/capella/part2/building_blocks/randomness/){target=\_blank} section of the Upgrading Ethereum documentation. +# Customize Your Runtime -## VDFs +## Introduction -Verifiable Delay Functions (VDFs) are time-bound computations that, even on parallel computers, take a set amount of time to complete. +A blockchain runtime is more than just a fixed set of rules—it's a dynamic foundation that you can shape to match your specific needs. With Polkadot SDK's [FRAME (Framework for Runtime Aggregation of Modularized Entities)](/reference/glossary/#frame-framework-for-runtime-aggregation-of-modularized-entities){target=\_blank}, customizing your runtime is straightforward and modular. Instead of building everything from scratch, you combine pre-built pallets with your own custom logic to create a runtime suited to your blockchain's purpose. -They produce a unique result that can be quickly verified publicly. When combined with RANDAO, feeding RANDAO's output into a VDF introduces a delay that nullifies an attacker's chance to influence the randomness. +This overview explains how runtime customization works, introduces the building blocks you'll use, and guides you through the key patterns for extending your runtime. -However, VDF likely requires specialized ASIC devices to run separately from standard nodes. +## Understanding Your Runtime -!!!warning - While only one is needed to secure the system, and they will be open-source and inexpensive, running VDF devices involves significant costs without direct incentives, adding friction for blockchain users. +The runtime is the core logic of your blockchain—it processes transactions, manages state, and enforces the rules that govern your network. When a transaction arrives at your blockchain, the [`frame_executive`](https://paritytech.github.io/polkadot-sdk/master/frame_executive/index.html){target=\_blank} pallet receives it and routes it to the appropriate pallet for execution. -## Additional Resources +Think of your runtime as a collection of specialized modules, each handling a different aspect of your blockchain. Need token balances? Use the Balances pallet. Want governance? Add the Governance pallets. Need something custom? Create your own pallet. By mixing and matching these modules, you build a runtime that's efficient, secure, and tailored to your use case. -For more information about the reasoning for choices made along with proofs, see Polkadot's research on blockchain randomness and sortition in the [Block production](https://research.web3.foundation/Polkadot/protocols/block-production){target=\_blank} entry of the Polkadot Wiki. +## Runtime Architecture -For a discussion with Web3 Foundation researchers about when and under what conditions Polkadot's randomness can be utilized, see the [Discussion on Randomness used in Polkadot](https://github.com/use-ink/ink/issues/57){target=\_blank} issue on GitHub. +The following diagram shows how FRAME components work together to form your runtime: +![](/images/parachains/customize-runtime/index/frame-overview-01.webp) ---- +The main components are: -Page Title: Register a Local Asset +- **`frame_executive`**: Routes all incoming transactions to the correct pallet for execution. +- **Pallets**: Domain-specific modules that implement your blockchain's features and business logic. +- **`frame_system`**: Provides core runtime primitives and storage. +- **`frame_support`**: Utilities and macros that simplify pallet development. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-token-operations-register-local-asset.md -- Canonical (HTML): https://docs.polkadot.com/chain-interactions/token-operations/register-local-asset/ -- Summary: Comprehensive guide to registering a local asset on the Asset Hub system parachain, including step-by-step instructions. +## Building Blocks: Pallets -# Register a Local Asset on Asset Hub +[Pallets](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/pallet/index.html){target=\_blank} are the fundamental units of runtime customization. Each pallet encapsulates specific functionality and can be independently developed, tested, and integrated. -## Introduction +A pallet can implement virtually any blockchain feature you need: -As detailed in the [Asset Hub Overview](/polkadot-protocol/architecture/system-chains/asset-hub){target=\_blank} page, Asset Hub accommodates two types of assets: local and foreign. Local assets are those that were created in Asset Hub and are identifiable by an integer ID. On the other hand, foreign assets originate from a sibling parachain and are identified by a Multilocation. +- Expose new transactions that users can submit. +- Store data on-chain. +- Enforce business rules and validation logic. +- Emit events to notify users of state changes. +- Handle errors gracefully. -This guide will take you through the steps of registering a local asset on the Asset Hub parachain. +### Pre-Built Pallets vs. Custom Pallets -## Prerequisites +FRAME provides a comprehensive library of [pre-built pallets](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame){target=\_blank} for common blockchain features, including consensus, staking, balances, governance, and more. These pallets are battle-tested, optimized, and ready to use. -Before you begin, ensure you have access to the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and a funded wallet with DOT or KSM. +However, you're not limited to pre-built functionality. When pre-built pallets don't meet your needs, you can create custom pallets with entirely custom logic. The real power of FRAME is the flexibility to use pre-built modules for standard features while building your own for unique requirements. -- For Polkadot Asset Hub, you would need a deposit of 10 DOT and around 0.201 DOT for the metadata. -- For Kusama Asset Hub, the deposit is 0.1 KSM and around 0.000669 KSM for the metadata. +### Pallet Structure -You need to ensure that your Asset Hub account balance is a bit more than the sum of those two deposits, which should seamlessly account for the required deposits and transaction fees. +FRAME uses Rust macros extensively, allowing you to focus on your pallet's logic while the framework handles boilerplate and integration code. -## Steps to Register a Local Asset +A typical pallet looks like this: -To register a local asset on the Asset Hub parachain, follow these steps: +```rust +pub use pallet::*; -1. Open the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and connect to the Asset Hub parachain using the network selector in the top left corner. +#[frame_support::pallet] +pub mod pallet { + use frame_support::pallet_prelude::*; + use frame_system::pallet_prelude::*; - - You may prefer to test local asset registration on TestNet before registering the asset on a MainNet hub. If you still need to set up a local testing environment, review the [Environment setup](#test-setup-environment) section for instructions. Once the local environment is set up, connect to the Local Node (Chopsticks) available on `ws://127.0.0.1:8000`. - - For the live network, connect to the **Asset Hub** parachain. Either Polkadot or Kusama Asset Hub can be selected from the dropdown list, choosing the desired RPC provider. + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + pub struct Pallet(_); -2. Click on the **Network** tab on the top navigation bar and select **Assets** from the dropdown list. + #[pallet::config] // snip + #[pallet::event] // snip + #[pallet::error] // snip + #[pallet::storage] // snip + #[pallet::call] // snip +} +``` - ![Access to Asset Hub through Polkadot.JS](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-01.webp) +Every pallet can implement these core macros: -3. Now, you need to examine all the registered asset IDs. This step is crucial to ensure that the asset ID you are about to register is unique. Asset IDs are displayed in the **assets** column. +- **`#[frame_support::pallet]`**: Marks your module as a FRAME pallet. +- **`#[pallet::pallet]`**: Designates the struct that holds pallet metadata. +- **`#[pallet::config]`**: Defines configuration and associated types. +- **`#[pallet::event]`**: Defines events emitted by your pallet. +- **`#[pallet::error]`**: Defines error types your pallet can return. +- **`#[pallet::storage]`**: Defines on-chain storage items. +- **`#[pallet::call]`**: Defines dispatchable functions (transactions). - ![Asset IDs on Asset Hub](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-02.webp) +For a comprehensive reference, see the [`pallet_macros` documentation](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/index.html){target=\_blank}. -4. Once you have confirmed that the asset ID is unique, click on the **Create** button on the top right corner of the page. +## How Runtime Customization Works - ![Create a new asset](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-03.webp) +Customizing your runtime typically follows these patterns: -5. Fill in the required fields in the **Create Asset** form: +**Adding Pre-Built Pallets**: Select pallets from the FRAME library and integrate them into your runtime configuration. This is the fastest way to add functionality. - 1. **creator account**: The account to be used for creating this asset and setting up the initial metadata. - 2. **asset name**: The descriptive name of the asset you are registering. - 3. **asset symbol**: The symbol that will be used to represent the asset. - 4. **asset decimals**: The number of decimal places for this token, with a maximum of 20 allowed through the user interface. - 5. **minimum balance**: The minimum balance for the asset. This is specified in the units and decimals as requested. - 6. **asset ID**: The selected id for the asset. This should not match an already-existing asset id. - 7. Click on the **Next** button. - - ![Create Asset Form](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-04.webp) +**Creating Custom Pallets**: Write custom pallets for features that don't exist in the pre-built library. Custom pallets follow the same structure as pre-built ones and integrate seamlessly. -6. Choose the accounts for the roles listed below: +**Combining Multiple Pallets**: Layer multiple pallets together to create complex behaviors. Pallets can call each other and share storage when needed. - 1. **admin account**: The account designated for continuous administration of the token. - 2. **issuer account**: The account that will be used for issuing this token. - 3. **freezer account**: The account that will be used for performing token freezing operations. - 4. Click on the **Create** button. +**Configuring Pallet Parameters**: Most pallets are configurable—you can adjust their behavior through configuration traits without modifying their code. - ![Admin, Issuer, Freezer accounts](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-05.webp) +The following diagram illustrates how pallets combine to form a complete runtime: -7. Click on the **Sign and Submit** button to complete the asset registration process. +![](/images/parachains/customize-runtime/index/frame-overview-02.webp) - ![Sign and Submit](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-06.webp) +## Starting Templates -## Verify Asset Registration +The easiest way to begin customizing your runtime is with a starter template. These templates provide a pre-configured foundation so you can focus on customization rather than setup. -After completing these steps, the asset will be successfully registered. You can now view your asset listed on the [**Assets**](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fasset-hub-polkadot-rpc.dwellir.com#/assets){target=\_blank} section of the Polkadot.js Apps interface. +- **[Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank}**: The recommended choice for most developers, it includes pre-configured pallets for common features (balances, block production, governance), a complete runtime setup, and built-in parachain consensus support. This template offers the best balance of features and learning opportunities. -![Asset listed on Polkadot.js Apps](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-07.webp) +- **[Polkadot SDK Minimal Template](https://github.com/paritytech/polkadot-sdk-minimal-template){target=\_blank}**: Provides a bare-bones runtime with only essential components. Choose this if you want maximum flexibility and prefer building from a clean slate. -!!! tip - Take into consideration that the **Assets** section’s link may differ depending on the network you are using. For the local environment, enter `ws://127.0.0.1:8000` into the **Custom Endpoint** field. +- **[Polkadot SDK Solochain Template](https://github.com/paritytech/polkadot-sdk/tree/master/templates/solochain){target=\_blank}**: Designed for building standalone blockchains with moderate features, simple consensus, and several core pallets. Use this if you want a sovereign blockchain independent of a relay chain. -In this way, you have successfully registered a local asset on the Asset Hub parachain. +- **[OpenZeppelin Runtime Templates](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\_blank}**: Provides security-focused configurations following industry best practices. The [generic-template](https://github.com/OpenZeppelin/polkadot-runtime-templates/tree/main/generic-template){target=\_blank} includes curated pallet selections and production-ready defaults—ideal if security is your top priority. -For an in-depth explanation about Asset Hub and its features, see the [Asset Hub](/chain-interactions/token-operations/convert-assets/){target=\_blank} entry in the Polkadot Wiki. +## Key Customization Scenarios -## Test Setup Environment +This section covers the most common customization patterns you'll encounter: -You can set up a local parachain environment to test the asset registration process before deploying it on the live network. This guide uses Chopsticks to simulate that process. For further information on chopsticks usage, refer to the [Chopsticks](/develop/toolkit/parachains/fork-chains/chopsticks/get-started){target=\_blank} documentation. +- **[Add Existing Pallets to Your Runtime](/parachains/customize-runtime/add-existing-pallets/)**: Integrate pre-built pallets from the FRAME library with minimal configuration. -To set up a test environment, execute the following command: +- **[Add Multiple Instances of a Pallet](/parachains/customize-runtime/add-pallet-instances/)**: Run multiple instances of the same pallet with different configurations—useful for multi-token systems or parallel features. -```bash -npx @acala-network/chopsticks \ ---config=https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/polkadot-asset-hub.yml -``` +- **[Add Smart Contract Functionality](/parachains/customize-runtime/add-smart-contract-functionality/)**: Enable smart contract execution on your parachain using Contracts pallets. -The above command will spawn a lazy fork of Polkadot Asset Hub with the latest block data from the network. If you need to test Kusama Asset Hub, replace `polkadot-asset-hub.yml` with `kusama-asset-hub.yml` in the command. +- **[Create Custom Pallets](/parachains/customize-runtime/pallet-development/create-a-pallet/)**: Build entirely custom pallets for features unique to your blockchain. -An Asset Hub instance is now running locally, and you can proceed with the asset registration process. Note that the local registration process does not differ from the live network process. Once you have a successful TestNet transaction, you can use the same steps to register the asset on MainNet. +- **[Test Your Runtime](/parachains/customize-runtime/pallet-development/pallet-testing/)**: Unit test pallets and mock complete runtimes to ensure everything works correctly. --- -Page Title: Set Up the Polkadot SDK Parachain Template +Page Title: Run a Parachain Network -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-launch-a-parachain-set-up-the-parachain-template.md -- Canonical (HTML): https://docs.polkadot.com/parachains/launch-a-parachain/set-up-the-parachain-template/ -- Summary: Learn how to set up and run the Polkadot SDK Parachain Template locally, creating a ready-to-customize foundation for your parachain. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-run-a-parachain-network.md +- Canonical (HTML): https://docs.polkadot.com/parachains/testing/run-a-parachain-network/ +- Summary: Quickly install and configure Zombienet to deploy and test Polkadot-based blockchain networks with this comprehensive getting-started guide. -# Set Up the Polkadot SDK Parachain Template +# Run a Parachain Network Using Zombienet ## Introduction -The [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank} includes several [templates](/parachains/customize-runtime/#starting-templates){target=\_blank} designed to help you quickly start building your own blockchain. Each template offers a different level of configuration, from minimal setups to feature-rich environments, allowing you to choose the foundation that best fits your project's needs. - -Among these, the [Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank} provides a preconfigured runtime with commonly used pallets, making it an ideal starting point for most parachain development projects. +Zombienet is a robust testing framework designed for Polkadot SDK-based blockchain networks. It enables developers to efficiently deploy and test ephemeral blockchain environments on platforms like Kubernetes, Podman, and native setups. With its simple and versatile CLI, Zombienet provides an all-in-one solution for spawning networks, running tests, and validating performance. -This guide walks you through the full process of working with this template. You will: +This guide will outline the different installation methods for Zombienet, provide step-by-step instructions for setting up on various platforms, and highlight essential provider-specific features and requirements. -- Set up the Polkadot SDK Parachain Template. -- Understand the project structure and key components. -- Verify your template is ready for development. -- Run the parachain template locally in development mode. +By following this guide, Zombienet will be up and running quickly, ready to streamline your blockchain testing and development workflows. -By the end of this guide, you'll have a working template ready to customize and deploy as a parachain. +## Install Zombienet -## Prerequisites +Zombienet releases are available on the [Zombienet repository](https://github.com/paritytech/zombienet){target=\_blank}. -Before getting started, ensure you have done the following: +Multiple options are available for installing Zombienet, depending on the user's preferences and the environment where it will be used. The following section will guide you through the installation process for each option. -- Completed the [Install Polkadot SDK](/parachains/install-polkadot-sdk/){target=\_blank} guide and successfully installed [Rust](https://www.rust-lang.org/){target=\_blank} and the required packages to set up your development environment. +=== "Use the executable" -For this tutorial series, you need to use Rust `1.86`. Newer versions of the compiler may not work with this parachain template version. + Install Zombienet using executables by visiting the [latest release](https://github.com/paritytech/zombienet/releases){target=\_blank} page and selecting the appropriate asset for your operating system. You can download the executable and move it to a directory in your PATH. -Run the following commands to set up the correct Rust version: + Each release includes executables for Linux and macOS. Executables are generated using [pkg](https://github.com/vercel/pkg){target=\_blank}, which allows the Zombienet CLI to operate without requiring Node.js to be installed. -=== "macOS" + Then, ensure the downloaded file is executable: ```bash - rustup install 1.86 - rustup default 1.86 - rustup target add wasm32-unknown-unknown --toolchain 1.86-aarch64-apple-darwin - rustup component add rust-src --toolchain 1.86-aarch64-apple-darwin + chmod +x zombienet-macos-arm64 ``` -=== "Ubuntu" + Finally, you can run the following command to check if the installation was successful. If so, it will display the version of the installed Zombienet: ```bash - rustup toolchain install 1.86.0 - rustup default 1.86.0 - rustup target add wasm32-unknown-unknown --toolchain 1.86.0 - rustup component add rust-src --toolchain 1.86.0 + ./zombienet-macos-arm64 version ``` -## Polkadot SDK Utility Tools - -This tutorial requires two essential tools: + If you want to add the `zombienet` executable to your PATH, you can move it to a directory in your PATH, such as `/usr/local/bin`: -- [**Chain spec builder**](https://crates.io/crates/staging-chain-spec-builder/10.0.0){target=\_blank}: A Polkadot SDK utility for generating chain specifications. Refer to the [Generate Chain Specs](/develop/parachains/deployment/generate-chain-specs/){target=\_blank} documentation for detailed usage. - - Install it by executing the following command: - ```bash - cargo install --locked staging-chain-spec-builder@10.0.0 + mv zombienet-macos-arm64 /usr/local/bin/zombienet ``` - This command installs the `chain-spec-builder` binary. - -- [**Polkadot Omni Node**](https://crates.io/crates/polkadot-omni-node/0.5.0){target=\_blank}: A white-labeled binary, released as a part of Polkadot SDK that can act as the collator of a parachain in production, with all the related auxiliary functionalities that a normal collator node has: RPC server, archiving state, etc. Moreover, it can also run the Wasm blob of the parachain locally for testing and development. - - To install it, run the following command: + Now you can refer to the `zombienet` executable directly. ```bash - cargo install --locked polkadot-omni-node@0.5.0 + zombienet version ``` - This command installs the `polkadot-omni-node` binary. - -## Clone the Template - -The [Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank} provides a ready-to-use development environment for building with the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}. Follow these steps to set up the template: +=== "Use Nix" -1. Clone the template repository: + For Nix users, the Zombienet repository provides a [`flake.nix`](https://github.com/paritytech/zombienet/blob/main/flake.nix){target=\_blank} file to install Zombienet making it easy to incorporate Zombienet into Nix-based projects. + + To install Zombienet utilizing Nix, users can run the following command, triggering the fetching of the flake and subsequently installing the Zombienet package: ```bash - git clone https://github.com/paritytech/polkadot-sdk-parachain-template.git parachain-template + nix run github:paritytech/zombienet/INSERT_ZOMBIENET_VERSION -- \ + spawn INSERT_ZOMBIENET_CONFIG_FILE_NAME.toml ``` -2. Navigate into the project directory: + Replace the `INSERT_ZOMBIENET_VERSION` with the desired version of Zombienet and the `INSERT_ZOMBIENET_CONFIG_FILE_NAME` with the name of the configuration file you want to use. + + To run the command above, you need to have [Flakes](https://nixos.wiki/wiki/Flakes#Enable_flakes){target=\_blank} enabled. + Alternatively, you can also include the Zombienet binary in the PATH for the current shell using the following command: + ```bash - cd parachain-template + nix shell github:paritytech/zombienet/INSERT_ZOMBIENET_VERSION ``` -## Explore the Project Structure - -Before building the template, take a moment to familiarize yourself with its structure. Understanding this organization will help you navigate the codebase as you develop your parachain. - -The template follows a standard Polkadot SDK project layout: - -```text -parachain-template/ -├── node/ # Node implementation and client -├── pallets/ # Custom pallets for your parachain -├── runtime/ # Runtime configuration and logic -├── Cargo.toml # Workspace configuration -└── README.md # Documentation -``` - -Key directories explained: - -- **runtime/**: Contains your parachain's state transition function and pallet configuration. This is where you'll define what your blockchain can do. -- **node/**: Houses the client implementation that runs your blockchain, handles networking, and manages the database. -- **pallets/**: Where you'll create custom business logic modules (pallets) for your specific use case. -- **Cargo.toml**: The workspace configuration that ties all components together. - -!!!note - The runtime is compiled to WebAssembly (Wasm), enabling forkless upgrades. The node binary remains constant while the runtime can be updated on-chain. - -## Compile the Runtime - -Now that you understand the template structure, let's compile the runtime to ensure everything is working correctly. +=== "Use Docker" -1. Compile the runtime: + Zombienet can also be run using Docker. The Zombienet repository provides a Docker image that can be used to run the Zombienet CLI. To run Zombienet using Docker, you can use the following command: ```bash - cargo build --release --locked + docker run -it --rm \ + -v $(pwd):/home/nonroot/zombie-net/host-current-files \ + paritytech/zombienet ``` - !!!tip - Initial compilation may take several minutes, depending on your machine specifications. Use the `--release` flag for improved runtime performance compared to the default `--debug` build. If you need to troubleshoot issues, the `--debug` build provides better diagnostics. - - For production deployments, consider using a dedicated `--profile production` flag - this can provide an additional 15-30% performance improvement over the standard `--release` profile. - -2. Upon successful compilation, you should see output indicating the build was successful. The compiled runtime will be located at: - - `./target/release/wbuild/parachain-template-runtime/parachain_template_runtime.compact.compressed.wasm` - -## Verify the Build - -After compilation completes, verify that the runtime was created successfully by checking for the Wasm blob: - -```bash -ls -la ./target/release/wbuild/parachain-template-runtime/ -``` - -You should see the `parachain_template_runtime.compact.compressed.wasm` file in the output, confirming the build was successful. - -## Run the Node Locally - -After successfully compiling your runtime, you can spin up a local chain and produce blocks. This process will start your local parachain using the Polkadot Omni Node and allow you to interact with it. You'll first need to generate a chain specification that defines your network's identity, initial connections, and genesis state, providing the foundational configuration for how your nodes connect and what initial state they agree upon. - -Follow these steps to launch your node in development mode: + The command above will run the Zombienet CLI inside a Docker container and mount the current directory to the `/home/nonroot/zombie-net/host-current-files` directory. This allows Zombienet to access the configuration file and other files in the current directory. If you want to mount a different directory, replace `$(pwd)` with the desired directory path. -1. Generate the chain specification file of your parachain: + Inside the Docker container, you can run the Zombienet CLI commands. First, you need to set up Zombienet to download the necessary binaries: ```bash - chain-spec-builder create -t development \ - --relay-chain paseo \ - --para-id 1000 \ - --runtime ./target/release/wbuild/parachain-template-runtime/parachain_template_runtime.compact.compressed.wasm \ - named-preset development + npm run zombie -- setup polkadot polkadot-parachain ``` -2. Start the Omni Node with the generated chain spec. You'll start it in development mode (without a relay chain config), producing and finalizing blocks: + After that, you need to add those binaries to the PATH: ```bash - polkadot-omni-node --chain ./chain_spec.json --dev + export PATH=/home/nonroot/zombie-net:$PATH ``` - The `--dev` option does the following: - - - Deletes all active data (keys, blockchain database, networking information) when stopped. - - Ensures a clean working state each time you restart the node. - -3. Verify that your node is running by reviewing the terminal output. You should see log messages indicating block production and finalization. - -4. Confirm that your blockchain is producing new blocks by checking if the number after `finalized` is increasing in the output. - -The details of the log output will be explored in a later tutorial. For now, knowing that your node is running and producing blocks is sufficient. - -## Interact with the Node - -When running the template node, it's accessible by default at `ws://localhost:9944`. To interact with your node using the [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} interface, follow these steps: - -1. Open [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} in your web browser and click the network icon (which should be the Polkadot logo) in the top left corner: - - ![](/images/parachains/launch-a-parachain/set-up-the-parachain-template/parachain-template-01.webp) - -2. Connect to your local node: + Finally, you can run the Zombienet CLI commands. For example, to spawn a network using a specific configuration file, you can run the following command: - 1. Scroll to the bottom and select **Development**. - 2. Choose **Custom**. - 3. Enter `ws://localhost:9944` in the **custom endpoint** input field. - 4. Click the **Switch** button. - - ![](/images/parachains/launch-a-parachain/set-up-the-parachain-template/parachain-template-02.webp) + ```bash + npm run zombie -- -p native spawn host-current-files/minimal.toml + ``` -3. Once connected, you should see **parachain-template-runtime** in the top left corner, with the interface displaying information about your local blockchain. - - ![](/images/parachains/launch-a-parachain/set-up-the-parachain-template/parachain-template-03.webp) + The command above mounts the current directory to the `/workspace` directory inside the Docker container, allowing Zombienet to access the configuration file and other files in the current directory. If you want to mount a different directory, replace `$(pwd)` with the desired directory path. -You are now connected to your local node and can interact with it through the Polkadot.js Apps interface. This tool enables you to explore blocks, execute transactions, and interact with your blockchain's features. For in-depth guidance on using the interface effectively, refer to the [Polkadot.js Guides](https://wiki.polkadot.com/general/polkadotjs/){target=\_blank} available on the Polkadot Wiki. +## Providers -## Stop the Node +Zombienet supports different backend providers for running the nodes. At this moment, [Kubernetes](https://kubernetes.io/){target=\_blank}, [Podman](https://podman.io/){target=\_blank}, and local providers are supported, which can be declared as `kubernetes`, `podman`, or `native`, respectively. -When you're done exploring your local node, you can stop it to remove any state changes you've made. Since you started the node with the `--dev` option, stopping the node will purge all persistent block data, allowing you to start fresh the next time. +To use a particular provider, you can specify it in the network file or use the `--provider` flag in the CLI: -To stop the local node: +```bash +zombienet spawn network.toml --provider INSERT_PROVIDER +``` -1. Return to the terminal window where the node output is displayed. -2. Press `Control-C` to stop the running process. -3. Verify that your terminal returns to the prompt in the `parachain-template` directory. +Alternatively, you can set the provider in the network file: -## Where to Go Next +```toml +[settings] +provider = "INSERT_PROVIDER" +... +``` -
+It's important to note that each provider has specific requirements and associated features. The following sections cover each provider's requirements and added features. -- Tutorial __Deploy to Polkadot__ +### Kubernetes - --- +Kubernetes is a portable, extensible, open-source platform for managing containerized workloads and services. Zombienet is designed to be compatible with a variety of Kubernetes clusters, including: - Learn how to deploy your parachain template to a relay chain testnet. Configure your chain specification, register as a parachain, and start producing blocks. +- [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine){target=\_blank} +- [Docker Desktop](https://docs.docker.com/desktop/features/kubernetes/){target=\_blank} +- [kind](https://kind.sigs.k8s.io/){target=\_blank} - [:octicons-arrow-right-24: Get Started](/parachains/launch-a-parachain/deploy-to-polkadot.md) +#### Requirements + +To effectively interact with your cluster, you'll need to ensure that [`kubectl`](https://kubernetes.io/docs/reference/kubectl/){target=\_blank} is installed on your system. This Kubernetes command-line tool allows you to run commands against Kubernetes clusters. If you don't have `kubectl` installed, you can follow the instructions provided in the [Kubernetes documentation](https://kubernetes.io/docs/tasks/tools/#kubectl){target=\_blank}. -
+To create resources such as namespaces, pods, and CronJobs within the target cluster, you must grant your user or service account the appropriate permissions. These permissions are essential for managing and deploying applications effectively within Kubernetes. +#### Features + +If available, Zombienet uses the Prometheus operator to oversee monitoring and visibility. This configuration ensures that only essential networking-related pods are deployed. Using the Prometheus operator, Zombienet improves its ability to monitor and manage network activities within the Kubernetes cluster efficiently. ---- +### Podman -Page Title: Sidecar REST API +Podman is a daemonless container engine for developing, managing, and running Open Container Initiative (OCI) containers and container images on Linux-based systems. Zombienet supports Podman rootless as a provider on Linux machines. Although Podman has support for macOS through an internal virtual machine (VM), the Zombienet provider code requires Podman to run natively on Linux. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-sidecar.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/sidecar/ -- Summary: Learn about Substrate API Sidecar, a REST service that provides endpoints for interacting with Polkadot SDK-based chains and simplifies blockchain interactions. +#### Requirements + +To use Podman as a provider, you need to have Podman installed on your system. You can install Podman by following the instructions provided on the [Podman website](https://podman.io/getting-started/installation){target=\_blank}. -# Sidecar API +#### Features + +Using Podman, Zombienet deploys additional pods to enhance the monitoring and visibility of the active network. Specifically, pods for [Prometheus](https://prometheus.io/){target=\_blank}, [Tempo](https://grafana.com/docs/tempo/latest/operations/monitor/){target=\_blank}, and [Grafana](https://grafana.com/){target=\_blank} are included in the deployment. Grafana is configured with Prometheus and Tempo as data sources. -## Introduction +Upon launching Zombienet, access to these monitoring services is facilitated through specific URLs provided in the output: -The [Sidecar REST API](https://github.com/paritytech/substrate-api-sidecar){target=\_blank} is a service that provides a REST interface for interacting with Polkadot SDK-based blockchains. With this API, developers can easily access a broad range of endpoints for nodes, accounts, transactions, parachains, and more. +- **Prometheus**: `http://127.0.0.1:34123` +- **Tempo**: `http://127.0.0.1:34125` +- **Grafana**: `http://127.0.0.1:41461` -Sidecar functions as a caching layer between your application and a Polkadot SDK-based node, offering standardized REST endpoints that simplify interactions without requiring complex, direct RPC calls. This approach is especially valuable for developers who prefer REST APIs or build applications in languages with limited WebSocket support. +It's important to note that Grafana is deployed with default administrator access. + +When network operations cease, either from halting a running spawn with the `Ctrl+C` command or test completion, Zombienet automatically removes all associated pods. -Some of the key features of the Sidecar API include: +### Local Provider -- **REST API interface**: Provides a familiar REST API interface for interacting with Polkadot SDK-based chains. -- **Standardized endpoints**: Offers consistent endpoint formats across different chain implementations. -- **Caching layer**: Acts as a caching layer to improve performance and reduce direct node requests. -- **Multiple chain support**: Works with any Polkadot SDK-based chain, including Polkadot, Kusama, and custom chains. +The Zombienet local provider, also called native, enables you to run nodes as local processes in your environment. -## Prerequisites +#### Requirements + +You must have the necessary binaries for your network (such as `polkadot` and `polkadot-parachain`). These binaries should be available in your PATH, allowing Zombienet to spawn the nodes as local processes. -Sidecar API requires Node.js version 18.14 LTS or higher. Verify your Node.js version: +To install the necessary binaries, you can use the Zombienet CLI command: ```bash -node --version +zombienet setup polkadot polkadot-parachain ``` -If you need to install or update Node.js, visit the [official Node.js website](https://nodejs.org/){target=\_blank} to download and install the latest LTS version. - -## Installation - -To install Substrate API Sidecar, use one of the following commands: - -=== "npm" +This command will download and prepare the necessary binaries for Zombienet's use. - ```bash - npm install -g @substrate/api-sidecar - ``` +If you need to use a custom binary, ensure the binary is available in your PATH. You can also specify the binary path in the network configuration file. The following example uses the custom [OpenZeppelin template](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\_blank}: -=== "pnpm" +First, clone the OpenZeppelin template repository using the following command: - ```bash - pnpm install -g @substrate/api-sidecar - ``` +```bash +git clone https://github.com/OpenZeppelin/polkadot-runtime-templates \ +&& cd polkadot-runtime-templates/generic-template +``` -=== "yarn" +Next, run the command to build the custom binary: - ```bash - yarn global add @substrate/api-sidecar - ``` +```bash +cargo build --release +``` -You can confirm the installation by running: +Finally, add the custom binary to your PATH as follows: ```bash -substrate-api-sidecar --version +export PATH=$PATH:INSERT_PATH_TO_RUNTIME_TEMPLATES/parachain-template-node/target/release ``` -For more information about the Sidecar API installation, see the [installation and usage](https://github.com/paritytech/substrate-api-sidecar?tab=readme-ov-file#npm-package-installation-and-usage){target=\_blank} section of the Sidecar API README. +Alternatively, you can specify the binary path in the network configuration file. The local provider exclusively utilizes the command configuration for nodes, which supports both relative and absolute paths. You can employ the `default_command` configuration to specify the binary for spawning all nodes in the relay chain. + +```toml +[relaychain] +chain = "rococo-local" +default_command = "./bin-v1.6.0/polkadot" -## Usage +[parachain] +id = 1000 -To use the Sidecar API, you have two options: + [parachain.collators] + name = "collator01" + command = "./target/release/parachain-template-node" +``` -- **Local node**: Run a node locally, which Sidecar will connect to by default, requiring no additional configuration. To start, run the following: +#### Features - ```bash - substrate-api-sidecar - ``` +The local provider does not offer any additional features. -- **Remote node**: Connect Sidecar to a remote node by specifying the RPC endpoint for that chain. For example, to gain access to the Polkadot Asset Hub associated endpoints. +## Configure Zombienet - ```bash - SAS_SUBSTRATE_URL=wss://polkadot-asset-hub-rpc.polkadot.io substrate-api-sidecar - ``` +Effective network configuration is crucial for deploying and managing blockchain systems. Zombienet simplifies this process by offering versatile configuration options in both JSON and TOML formats. Whether setting up a simple test network or a complex multi-node system, Zombienet's tools provide the flexibility to customize every aspect of your network's setup. - For more configuration details, see the [Configuration](https://github.com/paritytech/substrate-api-sidecar?tab=readme-ov-file#configuration){target=\_blank} section of the Sidecar API documentation. +The following sections will explore the structure and usage of Zombienet configuration files, explain key settings for network customization, and walk through CLI commands and flags to optimize your development workflow. -Once the Sidecar API is running, you’ll see output similar to this: +### Configuration Files -
- SAS_SUBSTRATE_URL=wss://polkadot-asset-hub-rpc.polkadot.io substrate-api-sidecar -
- SAS: - 📦 LOG: - ✅ LEVEL: "info" - ✅ JSON: false - ✅ FILTER_RPC: false - ✅ STRIP_ANSI: false - ✅ WRITE: false - ✅ WRITE_PATH: "/opt/homebrew/lib/node_modules/@substrate/api-sidecar/build/src/logs" - ✅ WRITE_MAX_FILE_SIZE: 5242880 - ✅ WRITE_MAX_FILES: 5 - 📦 SUBSTRATE: - ✅ URL: "wss://polkadot-asset-hub-rpc.polkadot.io" - ✅ TYPES_BUNDLE: undefined - ✅ TYPES_CHAIN: undefined - ✅ TYPES_SPEC: undefined - ✅ TYPES: undefined - ✅ CACHE_CAPACITY: undefined - 📦 EXPRESS: - ✅ BIND_HOST: "127.0.0.1" - ✅ PORT: 8080 - ✅ KEEP_ALIVE_TIMEOUT: 5000 - 📦 METRICS: - ✅ ENABLED: false - ✅ PROM_HOST: "127.0.0.1" - ✅ PROM_PORT: 9100 - ✅ LOKI_HOST: "127.0.0.1" - ✅ LOKI_PORT: 3100 - ✅ INCLUDE_QUERYPARAMS: false -
- 2024-11-06 08:06:01 info: Version: 19.3.0 - 2024-11-06 08:06:02 warn: API/INIT: RPC methods not decorated: chainHead_v1_body, chainHead_v1_call, chainHead_v1_continue, chainHead_v1_follow, chainHead_v1_header, chainHead_v1_stopOperation, chainHead_v1_storage, chainHead_v1_unfollow, chainHead_v1_unpin, chainSpec_v1_chainName, chainSpec_v1_genesisHash, chainSpec_v1_properties, transactionWatch_v1_submitAndWatch, transactionWatch_v1_unwatch, transaction_v1_broadcast, transaction_v1_stop - 2024-11-06 08:06:02 info: Connected to chain Polkadot Asset Hub on the statemint client at wss://polkadot-asset-hub-rpc.polkadot.io - 2024-11-06 08:06:02 info: Listening on http://127.0.0.1:8080/ - 2024-11-06 08:06:02 info: Check the root endpoint (http://127.0.0.1:8080/) to see the available endpoints for the current node -
-With Sidecar running, you can access the exposed endpoints via a browser, [`Postman`](https://www.postman.com/){target=\_blank}, [`curl`](https://curl.se/){target=\_blank}, or your preferred tool. +The network configuration file can be either JSON or TOML format. The Zombienet repository also provides a collection of [example configuration files](https://github.com/paritytech/zombienet/tree/main/examples){target=\_blank} that can be used as a reference. -### Endpoints +Each section may include provider-specific keys that aren't recognized by other providers. For example, if you use the local provider, any references to images for nodes will be disregarded. -Sidecar API provides a set of REST endpoints that allow you to query different aspects of the chain, including blocks, accounts, and transactions. Each endpoint offers specific insights into the chain’s state and activities. +### CLI Usage -For example, to retrieve the version of the node, use the `/node/version` endpoint: +Zombienet provides a CLI that allows interaction with the tool. The CLI can receive commands and flags to perform different kinds of operations. These operations use the following syntax: ```bash -curl -X 'GET' \ - 'http://127.0.0.1:8080/node/version' \ - -H 'accept: application/json' +zombienet ``` -Alternatively, you can access `http://127.0.0.1:8080/node/version` directly in a browser since it’s a `GET` request. +The following sections will guide you through the primary usage of the Zombienet CLI and the available commands and flags. + +#### CLI Commands -In response, you’ll see output similar to this (assuming you’re connected to Polkadot Asset Hub): +- **`spawn `**: Spawn the network defined in the [configuration file](#configuration-files). +- **`test `**: Run tests on the spawned network using the assertions and tests defined in the [test file](/develop/toolkit/parachains/spawn-chains/zombienet/write-tests/#the-test-file){target=\_blank}. +- **`setup `**: Set up the Zombienet development environment to download and use the `polkadot` or `polkadot-parachain` executable. +- **`convert `**: Transforms a [polkadot-launch](https://github.com/paritytech/polkadot-launch){target=\_blank} configuration file with a `.js` or `.json` extension into a Zombienet configuration file. +- **`version`**: Prints Zombienet version. +- **`help`**: Prints help information. -
- curl -X 'GET' 'http://127.0.0.1:8080/node/version' -H 'accept: application/json' -
- { - "clientVersion": "1.16.1-835e0767fe8", - "clientImplName": "statemint", - "chain": "Polkadot Asset Hub" - } -
-For a complete list of available endpoints and their documentation, visit the [Sidecar API list endpoints](https://paritytech.github.io/substrate-api-sidecar/dist/){target=\_blank}. You can learn about the endpoints and how to use them in your applications. +#### CLI Flags -## Where to Go Next +You can use the following flags to customize the behavior of the CLI: -To dive deeper, refer to the [official Sidecar documentation](https://github.com/paritytech/substrate-api-sidecar?tab=readme-ov-file#substrateapi-sidecar){target=\_blank}. This provides a comprehensive guide to the available configurations and advanced usage. +- **`-p`, `--provider`**: Override the [provider](#providers) to use. +- **`-d`, `--dir`**: Specify a directory path for placing the network files instead of using the default temporary path. +- **`-f`, `--force`**: Force override all prompt commands. +- **`-l`, `--logType`**: Type of logging on the console. Defaults to `table`. +- **`-m`, `--monitor`**: Start as monitor and don't auto clean up network. +- **`-c`, `--spawn-concurrency`**: Number of concurrent spawning processes to launch. Defaults to `1`. +- **`-h`, `--help`**: Display help for command. +### Settings ---- +Through the keyword `settings`, it's possible to define the general settings for the network. The available keys are: -Page Title: Smart Contracts Cookbook Index +- **`global_volumes?`** ++"GlobalVolume[]"++: A list of global volumes to use. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/ -- Summary: Explore our full collection of tutorials and guides to learn step-by-step how to build, deploy, and work with smart contracts on Polkadot. + ??? child "`GlobalVolume` interface definition" + ```js + export interface GlobalVolume { + name: string; + fs_type: string; + mount_path: string; + } + ``` -# Smart Contracts Cookbook +- **`bootnode`** ++"boolean"++: Add bootnode to network. Defaults to `true`. +- **`bootnode_domain?`** ++"string"++: Domain to use for bootnode. +- **`timeout`** ++"number"++: Global timeout to use for spawning the whole network. +- **`node_spawn_timeout?`** ++"number"++: Timeout to spawn pod/process. +- **`grafana?`** ++"boolean"++: Deploy an instance of Grafana. +- **`prometheus?`** ++"boolean"++: Deploy an instance of Prometheus. +- **`telemetry?`** ++"boolean"++: Enable telemetry for the network. +- **`jaeger_agent?`** ++"string"++: The Jaeger agent endpoint passed to the nodes. Only available on Kubernetes. +- **`tracing_collator_url?`** ++"string"++: The URL of the tracing collator used to query by the tracing assertion. Should be tempo query compatible. +- **`tracing_collator_service_name?`** ++"string"++: Service name for tempo query frontend. Only available on Kubernetes. Defaults to `tempo-tempo-distributed-query-frontend`. +- **`tracing_collator_service_namespace?`** ++"string"++: Namespace where tempo is running. Only available on Kubernetes. Defaults to `tempo`. +- **`tracing_collator_service_port?`** ++"number"++: Port of the query instance of tempo. Only available on Kubernetes. Defaults to `3100`. +- **`enable_tracing?`** ++"boolean"++: Enable the tracing system. Only available on Kubernetes. Defaults to `true`. +- **`provider`** ++"string"++: Provider to use. Default is `kubernetes`". +- **`polkadot_introspector?`** ++"boolean"++: Deploy an instance of polkadot-introspector. Only available on Podman and Kubernetes. Defaults to `false`. +- **`backchannel?`** ++"boolean"++: Deploy an instance of backchannel server. Only available on Kubernetes. Defaults to `false`. +- **`image_pull_policy?`** ++"string"++: Image pull policy to use in the network. Possible values are `Always`, `IfNotPresent`, and `Never`. +- **`local_ip?`** ++"string"++: IP used for exposing local services (rpc/metrics/monitors). Defaults to `"127.0.0.1"`. +- **`global_delay_network_global_settings?`** ++"number"++: Delay in seconds to apply to the network. +- **`node_verifier?`** ++"string"++: Specify how to verify node readiness or deactivate by using `None`. Possible values are `None` and `Metric`. Defaults to `Metric`. -Welcome to the Polkadot smart contracts cookbook index. +For example, the following configuration file defines a minimal example for the settings: -This page contains a list of all relevant tutorials and guides to help you get started coding smart contracts and dApps in Polkadot. +=== "TOML" + ```toml title="base-example.toml" + [settings] + timeout = 1000 + bootnode = false + provider = "kubernetes" + backchannel = false + # ... + ``` +=== "JSON" -## Get Tokens from the Faucet + ```json title="base-example.json" + { + "settings": { + "timeout": 1000, + "bootnode": false, + "provider": "kubernetes", + "backchannel": false, + "...": {} + }, + "...": {} + } -| Title | Difficulty | Tools | Description | -|------------------------------------|:-----------:|-------|-----------------------------------------------------------------------------------------------------------------------| -| [Faucet](/smart-contracts/faucet/) | 🟢 Beginner | N/A | Learn how to obtain test tokens from Polkadot faucets for development and testing purposes across different networks. | + ``` -## EVM/PVM Smart Contracts +### Relay Chain Configuration -| Title | Difficulty | Tools | Description | -|---------------------------------------------------------------------------------------------------|:-----------:|--------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------| -| [Deploy an ERC-20 to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/) | 🟢 Beginner | EVM Wallet, Polkadot Remix IDE | Deploy an ERC-20 token on Polkadot Hub using PolkaVM. This guide covers contract creation, compilation, deployment, and interaction via Polkadot Remix IDE. | -| [Deploy an NFT to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) | 🟢 Beginner | EVM Wallet, Polkadot Remix IDE | Deploy an NFT on Polkadot Hub using PolkaVM and OpenZeppelin. Learn how to compile, deploy, and interact with your contract using Polkadot Remix IDE. | +You can use the `relaychain` keyword to define further parameters for the relay chain at start-up. The available keys are: -## Port Ethereum DApps +- **`default_command?`** ++"string"++: The default command to run. Defaults to `polkadot`. +- **`default_image?`** ++"string"++: The default Docker image to use. +- **`default_resources?`** ++"Resources"++: Represents the resource limits/reservations the nodes need by default. Only available on Kubernetes. -| Title | Difficulty | Tools | Description | -|-------------------------------------------------------------------------------------|:---------------:|---------|----------------------------------------------------------------------------------------------------------------------------------| -| [Deploying Uniswap V2 on Polkadot](/smart-contracts/cookbook/eth-dapps/uniswap-v2/) | 🟡 Intermediate | Hardhat | Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. | + ??? child "`Resources` interface definition" + ```js + export interface Resources { + resources: { + requests?: { + memory?: string; + cpu?: string; + }; + limits?: { + memory?: string; + cpu?: string; + }; + }; + } + ``` +- **`default_db_snapshot?`** ++"string"++: The default database snapshot to use. +- **`default_prometheus_prefix`** ++"string"++: A parameter for customizing the metric's prefix. Defaults to `substrate`. +- **`default_substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version. ---- + ??? child "`SubstrateCliArgsVersion` enum definition" + ```js + export enum SubstrateCliArgsVersion { + V0 = 0, + V1 = 1, + V2 = 2, + V3 = 3, + } + ``` -Page Title: Smart Contracts Overview +- **`default_keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. +- **`chain`** ++"string"++: The chain name. +- **`chain_spec_path?`** ++"string"++: Path to the chain spec file. Should be the plain version to allow customizations. +- **`chain_spec_command?`** ++"string"++: Command to generate the chain spec. It can't be used in combination with `chain_spec_path`. +- **`default_args?`** ++"string[]"++: An array of arguments to use as default to pass to the command. +- **`default_overrides?`** ++"Override[]"++: An array of overrides to upload to the node. -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-overview.md -- Canonical (HTML): https://docs.polkadot.com/smart-contracts/overview/ -- Summary: Learn about smart contract development capabilities in the Polkadot ecosystem, either by leveraging Polkadot Hub or other alternatives. + ??? child "`Override` interface definition" + ```js + export interface Override { + local_path: string; + remote_name: string; + } + ``` -# Smart Contracts on Polkadot +- **`random_nominators_count?`** ++"number"++: If set and the stacking pallet is enabled, Zombienet will generate the input quantity of nominators and inject them into the genesis. +- **`max_nominations`** ++"number"++: The max number of nominations allowed by a nominator. Should match the value set in the runtime. Defaults to `24`. +- **`nodes?`** ++"Node[]"++: An array of nodes to spawn. It is further defined in the [Node Configuration](#node-configuration) section. +- **`node_groups?`** ++"NodeGroup[]"++: An array of node groups to spawn. It is further defined in the [Node Group Configuration](#node-group-configuration) section. +- **`total_node_in_group?`** ++"number"++: The total number of nodes in the group. Defaults to `1`. +- **`genesis`** ++"JSON"++: The genesis configuration. +- **`default_delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. -!!! smartcontract "PolkaVM Preview Release" - PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. -## Introduction + ??? child "`DelayNetworkSettings` interface definition" + ```js + export interface DelayNetworkSettings { + latency: string; + correlation?: string; // should be parsable as float by k8s + jitter?: string; + } + ``` -Polkadot offers developers multiple approaches to building and deploying smart contracts within its ecosystem. As a multi-chain network designed for interoperability, Polkadot provides various environments optimized for different developer preferences and application requirements. From native smart contract support on Polkadot Hub to specialized parachain environments, developers can choose the platform that best suits their technical needs while benefiting from Polkadot's shared security model and cross-chain messaging capabilities. +#### Node Configuration -Whether you're looking for Ethereum compatibility through EVM-based parachains like [Moonbeam](https://docs.moonbeam.network/){target=\_blank}, [Astar](https://docs.astar.network/){target=\_blank}, and [Acala](https://evmdocs.acala.network/){target=\_blank} or prefer PolkaVM-based development with [ink!](https://use.ink/docs/v6/){target=\_blank}, the Polkadot ecosystem accommodates a range of diverse developers. +One specific key capable of receiving more subkeys is the `nodes` key. This key is used to define further parameters for the nodes. The available keys: -These guides explore the diverse smart contract options available in the Polkadot ecosystem, helping developers understand the unique advantages of each approach and make informed decisions about where to deploy their decentralized applications. +- **`name`** ++"string"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`). +- **`image?`** ++"string"++: Override default Docker image to use for this node. +- **`command?`** ++"string"++: Override default command to run. +- **`command_with_args?`** ++"string"++: Override default command and arguments. +- **`args?`** ++"string[]"++: Arguments to be passed to the command. +- **`env?`** ++"envVars[]"++: Environment variables to set in the container. -## Native Smart Contracts + ??? child "`envVars` interface definition" + ```js + export interface EnvVars { + name: string; + value: string; + } + ``` -### Introduction +- **`prometheus_prefix?`** ++"string"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`. +- **`db_snapshot?`** ++"string"++: Database snapshot to use. +- **`substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead. -Polkadot Hub enables smart contract deployment and execution through PolkaVM, a cutting-edge virtual machine designed specifically for the Polkadot ecosystem. This native integration allows developers to deploy smart contracts directly on Polkadot's system chain while maintaining compatibility with Ethereum development tools and workflows. + ??? child "`SubstrateCliArgsVersion` enum definition" + ```js + export enum SubstrateCliArgsVersion { + V0 = 0, + V1 = 1, + V2 = 2, + V3 = 3, + } + ``` -### Smart Contract Development +- **`resources?`** ++"Resources"++: Represent the resources limits/reservations needed by the node. -The smart contract platform on Polkadot Hub combines _Polkadot's robust security and scalability_ with the extensive Ethereum development ecosystem. Developers can utilize familiar Ethereum libraries for contract interactions and leverage industry-standard development environments for writing and testing smart contracts. + ??? child "`Resources` interface definition" + ```js + export interface Resources { + resources: { + requests?: { + memory?: string; + cpu?: string; + }; + limits?: { + memory?: string; + cpu?: string; + }; + }; + } + ``` -Polkadot Hub provides _full Ethereum JSON-RPC API compatibility_, ensuring seamless integration with existing development tools and services. This compatibility enables developers to maintain their preferred workflows while building on Polkadot's native infrastructure. +- **`keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. +- **`validator`** ++"boolean"++: Pass the `--validator` flag to the command. Defaults to `true`. +- **`invulnerable`** ++"boolean"++: If true, add the node to invulnerables in the chain spec. Defaults to `false`. +- **`balance`** ++"number"++: Balance to set in balances for node's account. Defaults to `2000000000000`. +- **`bootnodes?`** ++"string[]"++: Array of bootnodes to use. +- **`add_to_bootnodes?`** ++"boolean"++: Add this node to the bootnode list. Defaults to `false`. +- **`ws_port?`** ++"number"++: WS port to use. +- **`rpc_port?`** ++"number"++: RPC port to use. +- **`prometheus_port?`** ++"number"++: Prometheus port to use. +- **`p2p_cert_hash?`** ++"string"++: Libp2p certhash to use with webRTC transport. +- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. -### Technical Architecture + ??? child "`DelayNetworkSettings` interface definition" + ```js + export interface DelayNetworkSettings { + latency: string; + correlation?: string; // should be parsable as float by k8s + jitter?: string; + } + ``` -PolkaVM, the underlying virtual machine, utilizes a RISC-V-based register architecture _optimized for the Polkadot ecosystem_. This design choice offers several advantages: +The following configuration file defines a minimal example for the relay chain, including the `nodes` key: -- Enhanced performance for smart contract execution. -- Improved gas efficiency for complex operations. -- Native compatibility with Polkadot's runtime environment. -- Optimized storage and state management. +=== "TOML" -### Development Tools and Resources + ```toml title="relaychain-example-nodes.toml" + [relaychain] + default_command = "polkadot" + default_image = "polkadot-debug:master" + chain = "rococo-local" + chain_spec_path = "INSERT_PATH_TO_CHAIN_SPEC" + default_args = ["--chain", "rococo-local"] -Polkadot Hub supports a comprehensive suite of development tools familiar to Ethereum developers. The platform integrates with popular development frameworks, testing environments, and deployment tools. Key features include: + [[relaychain.nodes]] + name = "alice" + validator = true + balance = 1000000000000 -- Contract development in Solidity or Rust. -- Support for standard Ethereum development libraries. -- Integration with widely used development environments. -- Access to blockchain explorers and indexing solutions. -- Compatibility with contract monitoring and management tools. + [[relaychain.nodes]] + name = "bob" + validator = true + balance = 1000000000000 + # ... -### Cross-Chain Capabilities + ``` -Smart contracts deployed on Polkadot Hub can leverage Polkadot's [cross-consensus messaging (XCM) protocol](/parachains/interoperability/get-started/){target=\_blank} protocol to seamlessly _transfer tokens and call functions on other blockchain networks_ within the Polkadot ecosystem, all without complex bridging infrastructure or third-party solutions. For further references, check the [Interoperability](/develop/interoperability/){target=\_blank} section. +=== "JSON" -### Use Cases + ```json title="relaychain-example-nodes.json" + { + "relaychain": { + "default_command": "polkadot", + "default_image": "polkadot-debug:master", + "chain": "rococo-local", + "chain_spec_path": "INSERT_PATH_TO_CHAIN-SPEC.JSON", + "default_args": ["--chain", "rococo-local"], + "nodes": [ + { + "name": "alice", + "validator": true, + "balance": 1000000000000 + }, + { + "name": "bob", + "validator": true, + "balance": 1000000000000 + } + ] + } + } -Polkadot Hub's smart contract platform is suitable for a wide range of applications: + ``` -- DeFi protocols leveraging _cross-chain capabilities_. -- NFT platforms utilizing Polkadot's native token standards. -- Governance systems integrated with Polkadot's democracy mechanisms. -- Cross-chain bridges and asset management solutions. +#### Node Group Configuration -## Other Smart Contract Environments +The `node_groups` key defines further parameters for the node groups. The available keys are: -Beyond Polkadot Hub's native PolkaVM support, the ecosystem offers two main alternatives for smart contract development: +- **`name`** ++"string"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`). +- **`image?`** ++"string"++: Override default Docker image to use for this node. +- **`command?`** ++"string"++: Override default command to run. +- **`args?`** ++"string[]"++: Arguments to be passed to the command. +- **`env?`** ++"envVars[]"++: Environment variables to set in the container. + + ??? child "`envVars` interface definition" + ```js + export interface EnvVars { + name: string; + value: string; + } + ``` -- **EVM-compatible parachains**: Provide access to Ethereum's extensive developer ecosystem, smart contract portability, and established tooling like Hardhat, Remix, Foundry, and OpenZeppelin. The main options include Moonbeam (the first full Ethereum-compatible parachain serving as an interoperability hub), Astar (featuring dual VM support for both EVM and WebAssembly contracts), and Acala (DeFi-focused with enhanced Acala EVM+ offering advanced DeFi primitives). +- **`overrides?`** ++"Override[]"++: Array of overrides definitions. -- **Rust (ink!)**: ink! is a Rust-based framework that can compile to PolkaVM. It uses [`#[ink(...)]`](https://use.ink/docs/v6/macros-attributes/){target=\_blank} attribute macros to create Polkadot SDK-compatible PolkaVM bytecode, offering strong memory safety from Rust, an advanced type system, high-performance PolkaVM execution, and platform independence with sandboxed security. + ??? child "`Override` interface definition" + ```js + export interface Override { + local_path: string; + remote_name: string; + } + ``` +- **`prometheus_prefix?`** ++"string"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`. +- **`db_snapshot?`** ++"string"++: Database snapshot to use. +- **`substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead. -Each environment provides unique advantages based on developer preferences and application requirements. + ??? child "`SubstrateCliArgsVersion` enum definition" + ```js + export enum SubstrateCliArgsVersion { + V0 = 0, + V1 = 1, + V2 = 2, + V3 = 3, + } + ``` -## Where to Go Next +- **`resources?`** ++"Resources"++: Represent the resources limits/reservations needed by the node. -Developers can use their existing Ethereum development tools and connect to Polkadot Hub's RPC endpoints. The platform's Ethereum compatibility layer ensures a smooth transition for teams already building on Ethereum-compatible chains. + ??? child "`Resources` interface definition" + ```js + export interface Resources { + resources: { + requests?: { + memory?: string; + cpu?: string; + }; + limits?: { + memory?: string; + cpu?: string; + }; + }; + } + ``` -Subsequent sections of this guide provide detailed information about specific development tools, advanced features, and best practices for building on Polkadot Hub. +- **`keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. +- **`count`** ++"number | string"++: Number of nodes to launch for this group. +- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. -
+ ??? child "`DelayNetworkSettings` interface definition" + ```js + export interface DelayNetworkSettings { + latency: string; + correlation?: string; // should be parsable as float by k8s + jitter?: string; + } + ``` -- Guide __Libraries__ +The following configuration file defines a minimal example for the relay chain, including the `node_groups` key: - --- +=== "TOML" - Explore essential libraries to optimize smart contract development and interaction. + ```toml title="relaychain-example-node-groups.toml" + [relaychain] + default_command = "polkadot" + default_image = "polkadot-debug:master" + chain = "rococo-local" + chain_spec_path = "INSERT_PATH_TO_CHAIN_SPEC" + default_args = ["--chain", "rococo-local"] - [:octicons-arrow-right-24: Reference](/smart-contracts/libraries/ethers-js/) + [[relaychain.node_groups]] + name = "group-1" + count = 2 + image = "polkadot-debug:master" + command = "polkadot" + args = ["--chain", "rococo-local"] + # ... -- Guide __Dev Environments__ + ``` - --- +=== "JSON" - Set up your development environment for seamless contract deployment and testing. + ```json title="relaychain-example-node-groups.json" + { + "relaychain": { + "default_command": "polkadot", + "default_image": "polkadot-debug:master", + "chain": "rococo-local", + "chain_spec_path": "INSERT_PATH_TO_CHAIN-SPEC.JSON", + "default_args": ["--chain", "rococo-local"], + "node_groups": [ + { + "name": "group-1", + "count": 2, + "image": "polkadot-debug:master", + "command": "polkadot", + "args": ["--chain", "rococo-local"] + } + ], + "...": {} + }, + "...": {} + } - [:octicons-arrow-right-24: Reference](/smart-contracts/dev-environments/local-dev-node/) + ``` -
+### Parachain Configuration +The `parachain` keyword defines further parameters for the parachain. The available keys are: ---- +- **`id`** ++"number"++: The id to assign to this parachain. Must be unique. +- **`chain?`** ++"string"++: The chain name. +- **`force_decorator?`** ++"string"++: Force the use of a specific decorator. +- **`genesis?`** ++"JSON"++: The genesis configuration. +- **`balance?`** ++"number"++: Balance to set in balances for parachain's account. +- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. -Page Title: Subxt Rust API + ??? child "`DelayNetworkSettings` interface definition" + ```js + export interface DelayNetworkSettings { + latency: string; + correlation?: string; // should be parsable as float by k8s + jitter?: string; + } + ``` -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-subxt.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/subxt/ -- Summary: Subxt is a Rust library for type-safe interaction with Polkadot SDK blockchains, enabling transactions, state queries, runtime API access, and more. +- **`add_to_genesis?`** ++"boolean"++: Flag to add parachain to genesis or register in runtime. Defaults to `true`. +- **`register_para?`** ++"boolean"++: Flag to specify whether the para should be registered. The `add_to_genesis` flag must be set to false for this flag to have any effect. Defaults to `true`. +- **`onboard_as_parachain?`** ++"boolean"++: Flag to specify whether the para should be onboarded as a parachain, rather than remaining a parathread. Defaults to `true`. +- **`genesis_wasm_path?`** ++"string"++: Path to the Wasm file to use. +- **`genesis_wasm_generator?`** ++"string"++: Command to generate the Wasm file. +- **`genesis_state_path?`** ++"string"++: Path to the state file to use. +- **`genesis_state_generator?`** ++"string"++: Command to generate the state file. +- **`chain_spec_path?`** ++"string"++: Path to the chain spec file. +- **`chain_spec_command?`** ++"string"++: Command to generate the chain spec. +- **`cumulus_based?`** ++"boolean"++: Flag to use cumulus command generation. Defaults to `true`. +- **`bootnodes?`** ++"string[]"++: Array of bootnodes to use. +- **`prometheus_prefix?`** ++"string"++: Parameter for customizing the metric's prefix for all parachain nodes/collators. Defaults to `substrate`. +- **`collator?`** ++"Collator"++: Further defined in the [Collator Configuration](#collator-configuration) section. +- **`collator_groups?`** ++"CollatorGroup[]"++: An array of collator groups to spawn. It is further defined in the [Collator Groups Configuration](#collator-groups-configuration) section. + +For example, the following configuration file defines a minimal example for the parachain: -# Subxt Rust API +=== "TOML" -## Introduction + ```toml title="parachain-example.toml" + [parachain] + id = 100 + add_to_genesis = true + cumulus_based = true + genesis_wasm_path = "INSERT_PATH_TO_WASM" + genesis_state_path = "INSERT_PATH_TO_STATE" + # ... -Subxt is a Rust library designed to interact with Polkadot SDK-based blockchains. It provides a type-safe interface for submitting transactions, querying on-chain state, and performing other blockchain interactions. By leveraging Rust's strong type system, subxt ensures that your code is validated at compile time, reducing runtime errors and improving reliability. + ``` -## Prerequisites +=== "JSON" -Before using subxt, ensure you have the following requirements: + ```json title="parachain-example.json" + { + "parachain": { + "id": 100, + "add_to_genesis": true, + "cumulus_based": true, + "genesis_wasm_path": "INSERT_PATH_TO_WASM", + "genesis_state_path": "INSERT_PATH_TO_STATE", + "...": {} + }, + "...": {} + } -- Rust and Cargo installed on your system. You can install them using [Rustup](https://rustup.rs/){target=\_blank}. -- A Rust project initialized. If you don't have one, create it with: - ```bash - cargo new my_project && cd my_project ``` -## Installation - -To use subxt in your project, you must install the necessary dependencies. Each plays a specific role in enabling interaction with the blockchain: +#### Collator Configuration -1. **Install the subxt CLI**: [`subxt-cli`](https://crates.io/crates/subxt-cli){target=\_blank} is a command-line tool that provides utilities for working with Polkadot SDK metadata. In the context of subxt, it is essential to download chain metadata, which is required to generate type-safe Rust interfaces for interacting with the blockchain. Install it using the following: +One specific key capable of receiving more subkeys is the `collator` key. This key defines further parameters for the nodes. The available keys are: - ```bash - cargo install subxt-cli@0.44.0 - ``` +- **`name`** ++"string"++: Name of the collator. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`). +- **`image?`** ++"string"++: Image to use for the collator. +- **`command_with_args?`** ++"string"++: Overrides both command and arguments for the collator. +- **`validator`** ++"boolean"++: Pass the `--validator` flag to the command. Defaults to `true`. +- **`invulnerable`** ++"boolean"++: If true, add the collator to invulnerables in the chain spec. Defaults to `false`. +- **`balance`** ++"number"++: Balance to set in balances for collator's account. Defaults to `2000000000000`. +- **`bootnodes?`** ++"string[]"++: Array of bootnodes to use. +- **`add_to_bootnodes?`** ++"boolean"++: Add this collator to the bootnode list. Defaults to `false`. +- **`ws_port?`** ++"number"++: WS port to use. +- **`rpc_port?`** ++"number"++: RPC port to use. +- **`prometheus_port?`** ++"number"++: Prometheus port to use. +- **`p2p_port?`** ++"number"++: P2P port to use. +- **`p2p_cert_hash?`** ++"string"++: Libp2p certhash to use with webRTC transport. +- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. -2. **Add core dependencies**: These dependencies are essential for interacting with the blockchain. + ??? child "`DelayNetworkSettings` interface definition" + ```js + export interface DelayNetworkSettings { + latency: string; + correlation?: string; // should be parsable as float by k8s + jitter?: string; + } + ``` - - **[subxt](https://crates.io/crates/subxt){target=\_blank}**: The main library for communicating with Polkadot SDK nodes. It handles RPC requests, encoding/decoding, and type generation. +- **`command?`** ++"string"++: Override default command to run. +- **`args?`** ++"string[]"++: Arguments to be passed to the command. +- **`env?`** ++"envVars[]"++: Environment variables to set in the container. - ```bash - cargo add subxt@0.44.0 + ??? child "`envVars` interface definition" + ```js + export interface EnvVars { + name: string; + value: string; + } ``` - - **[subxt-signer](https://crates.io/crates/subxt-signer){target=\_blank}**: Provides cryptographic functionality for signing transactions. Without this, you can only read data but cannot submit transactions. +- **`overrides?`** ++"Override[]"++: Array of overrides definitions. - ```bash - cargo add subxt-signer@0.44.0 + ??? child "`Override` interface definition" + ```js + export interface Override { + local_path: string; + remote_name: string; + } ``` - - **[tokio](https://crates.io/crates/tokio){target=\_blank}**: An asynchronous runtime for Rust. Since blockchain operations are async, Tokio enables the efficient handling of network requests. The `rt` feature enables Tokio's runtime, including the current-thread single-threaded scheduler, which is necessary for async execution. The `macros` feature provides procedural macros like `#[tokio::main]` to simplify runtime setup. +- **`prometheus_prefix?`** ++"string"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`. +- **`db_snapshot?`** ++"string"++: Database snapshot to use. +- **`substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead. - ```bash - cargo add tokio@1.44.2 --features rt,macros + ??? child "`SubstrateCliArgsVersion` enum definition" + ```js + export enum SubstrateCliArgsVersion { + V0 = 0, + V1 = 1, + V2 = 2, + V3 = 3, + } ``` - After adding the dependencies, your `Cargo.toml` should look like this: +- **`resources?`** ++"Resources"++: Represent the resources limits/reservations needed by the node. - ```toml - [package] - name = "my_project" - version = "0.1.0" - edition = "2021" + ??? child "`Resources` interface definition" + ```js + export interface Resources { + resources: { + requests?: { + memory?: string; + cpu?: string; + }; + limits?: { + memory?: string; + cpu?: string; + }; + }; + } + ``` - [dependencies] - subxt = "0.41.0" - subxt-signer = "0.41.0" - tokio = { version = "1.44.2", features = ["rt", "macros"] } +- **`keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. - ``` +The configuration file below defines a minimal example for the collator: -## Get Started +=== "TOML" -This guide will walk you through the fundamental operations of subxt, from setting up your environment to executing transactions and querying blockchain state. + ```toml title="collator-example.toml" + [parachain] + id = 100 + add_to_genesis = true + cumulus_based = true + genesis_wasm_path = "INSERT_PATH_TO_WASM" + genesis_state_path = "INSERT_PATH_TO_STATE" -### Download Chain Metadata + [[parachain.collators]] + name = "alice" + image = "polkadot-parachain" + command = "polkadot-parachain" + # ... -Before interacting with a blockchain, you need to retrieve its metadata. This metadata defines storage structures, extrinsics, and other runtime details. Use the `subxt-cli` tool to download the metadata, replacing `INSERT_NODE_URL` with the URL of the node you want to interact with: + ``` -```bash -subxt metadata --url INSERT_NODE_URL > polkadot_metadata.scale -``` +=== "JSON" -### Generate Type-Safe Interfaces + ```json title="collator-example.json" + { + "parachain": { + "id": 100, + "add_to_genesis": true, + "cumulus_based": true, + "genesis_wasm_path": "INSERT_PATH_TO_WASM", + "genesis_state_path": "INSERT_PATH_TO_STATE", + "collators": [ + { + "name": "alice", + "image": "polkadot-parachain", + "command": "polkadot-parachain", + "...": {} + } + ] + }, + "...": {} + } -Use the `#[subxt::subxt]` macro to generate a type-safe Rust interface from the downloaded metadata: + ``` -```rust -// Generate an interface that we can use from the node's metadata. -#[subxt::subxt(runtime_metadata_path = "./polkadot_metadata.scale")] -pub mod polkadot {} -``` +#### Collator Groups Configuration -Once subxt interfaces are generated, you can interact with your node in the following ways. You can use the links below to view the related subxt documentation: +The `collator_groups` key defines further parameters for the collator groups. The available keys are: -- **[Transactions](https://docs.rs/subxt/latest/subxt/book/usage/transactions/index.html){target=\_blank}**: Builds and submits transactions, monitors their inclusion in blocks, and retrieves associated events. -- **[Storage](https://docs.rs/subxt/latest/subxt/book/usage/storage/index.html){target=\_blank}**: Enables querying of node storage data. -- **[Events](https://docs.rs/subxt/latest/subxt/book/usage/events/index.html){target=\_blank}**: Retrieves events emitted from recent blocks. -- **[Constants](https://docs.rs/subxt/latest/subxt/book/usage/constants/index.html){target=\_blank}**: Accesses constant values stored in nodes that remain unchanged across a specific runtime version. -- **[Blocks](https://docs.rs/subxt/latest/subxt/book/usage/blocks/index.html){target=\_blank}**: Loads recent blocks or subscribes to new/finalized blocks, allowing examination of extrinsics, events, and storage at those blocks. -- **[Runtime APIs](https://docs.rs/subxt/latest/subxt/book/usage/runtime_apis/index.html){target=\_blank}**: Makes calls into pallet runtime APIs to fetch data. -- **[Custom values](https://docs.rs/subxt/latest/subxt/book/usage/custom_values/index.html){target=\_blank}**: Accesses "custom values" contained within metadata. -- **[Raw RPC calls](https://docs.rs/subxt/latest/subxt/book/usage/rpc/index.html){target=\_blank}**: Facilitates raw RPC requests to compatible nodes. +- **`name`** ++"string"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`). +- **`image?`** ++"string"++: Override default Docker image to use for this node. +- **`command?`** ++"string"++: Override default command to run. +- **`args?`** ++"string[]"++: Arguments to be passed to the command. +- **`env?`** ++"envVars[]"++: Environment variables to set in the container. -### Initialize the Subxt Client + ??? child "`envVars` interface definition" + ```js + export interface EnvVars { + name: string; + value: string; + } + ``` -To interact with a blockchain node using subxt, create an asynchronous main function and initialize the client. Replace `INSERT_NODE_URL` with the URL of your target node: +- **`overrides?`** ++"Override[]"++: Array of overrides definitions. -```rust -use std::str::FromStr; -use subxt::utils::AccountId32; -use subxt::{OnlineClient, PolkadotConfig}; -use subxt_signer::{bip39::Mnemonic,sr25519::Keypair}; + ??? child "`Override` interface definition" + ```js + export interface Override { + local_path: string; + remote_name: string; + } + ``` -// Generate an interface that we can use from the node's metadata. -#[subxt::subxt(runtime_metadata_path = "./polkadot_metadata.scale")] -pub mod polkadot {} +- **`prometheus_prefix?`** ++"string"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`. +- **`db_snapshot?`** ++"string"++: Database snapshot to use. +- **`substrate_cli_args_version?`** ++"SubstrateCliArgsVersion"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead. -#[tokio::main(flavor = "current_thread")] -async fn main() -> Result<(), Box> { - // Define the node URL. - const NODE_URL: &str = "INSERT_NODE_URL"; + ??? child "`SubstrateCliArgsVersion` enum definition" + ```js + export enum SubstrateCliArgsVersion { + V0 = 0, + V1 = 1, + V2 = 2, + V3 = 3, + } + ``` - // Initialize the Subxt client to interact with the blockchain. - let api = OnlineClient::::from_url(NODE_URL).await?; +- **`resources?`** ++"Resources"++: Represent the resources limits/reservations needed by the node. - // Your code here... + ??? child "`Resources` interface definition" + ```js + export interface Resources { + resources: { + requests?: { + memory?: string; + cpu?: string; + }; + limits?: { + memory?: string; + cpu?: string; + }; + }; + } + ``` - Ok(()) -} -``` +- **`keystore_key_types?`** ++"string[]"++: Defines which keystore keys should be created. +- **`count`** ++"number | string"++: Number of nodes to launch for this group. +- **`delay_network_settings?`** ++"DelayNetworkSettings"++: Sets the expected configuration to delay the network. -### Read Chain Data + ??? child "`DelayNetworkSettings` interface definition" + ```js + export interface DelayNetworkSettings { + latency: string; + correlation?: string; // should be parsable as float by k8s + jitter?: string; + } + ``` -subxt provides multiple ways to access on-chain data: +For instance, the configuration file below defines a minimal example for the collator groups: -- **Constants**: Constants are predefined values in the runtime that remain unchanged unless modified by a runtime upgrade. +=== "TOML" - For example, to retrieve the existential deposit, use: - - ```rust - // A query to obtain some constant. - let constant_query = polkadot::constants().balances().existential_deposit(); + ```toml title="collator-groups-example.toml" + [parachain] + id = 100 + add_to_genesis = true + cumulus_based = true + genesis_wasm_path = "INSERT_PATH_TO_WASM" + genesis_state_path = "INSERT_PATH_TO_STATE" - // Obtain the value. - let value = api.constants().at(&constant_query)?; + [[parachain.collator_groups]] + name = "group-1" + count = 2 + image = "polkadot-parachain" + command = "polkadot-parachain" + # ... - println!("Existential deposit: {:?}", value); ``` -- **State**: State refers to the current chain data, which updates with each block. +=== "JSON" - To fetch account information, replace `INSERT_ADDRESS` with the address you want to fetch data from and use: + ```json title="collator-groups-example.json" + { + "parachain": { + "id": 100, + "add_to_genesis": true, + "cumulus_based": true, + "genesis_wasm_path": "INSERT_PATH_TO_WASM", + "genesis_state_path": "INSERT_PATH_TO_STATE", + "collator_groups": [ + { + "name": "group-1", + "count": 2, + "image": "polkadot-parachain", + "command": "polkadot-parachain", + "...": {} + } + ] + }, + "...": {} + } - ```rust - // Define the target account address. - const ADDRESS: &str = "INSERT_ADDRESS"; - let account = AccountId32::from_str(ADDRESS).unwrap(); - - // Build a storage query to access account information. - let storage_query = polkadot::storage().system().account(&account.into()); - - // Fetch the latest state for the account. - let result = api - .storage() - .at_latest() - .await? - .fetch(&storage_query) - .await? - .unwrap(); - - println!("Account info: {:?}", result); ``` -### Submit Transactions - -To submit a transaction, you must construct an extrinsic, sign it with your private key, and send it to the blockchain. Replace `INSERT_DEST_ADDRESS` with the recipient's address, `INSERT_AMOUNT` with the amount to transfer, and `INSERT_SECRET_PHRASE` with the sender's mnemonic phrase: - -```rust - // Define the recipient address and transfer amount. - const DEST_ADDRESS: &str = "INSERT_DEST_ADDRESS"; - const AMOUNT: u128 = INSERT_AMOUNT; - - // Convert the recipient address into an `AccountId32`. - let dest = AccountId32::from_str(DEST_ADDRESS).unwrap(); - - // Build the balance transfer extrinsic. - let balance_transfer_tx = polkadot::tx() - .balances() - .transfer_allow_death(dest.into(), AMOUNT); - - // Load the sender's keypair from a mnemonic phrase. - const SECRET_PHRASE: &str = "INSERT_SECRET_PHRASE"; - let mnemonic = Mnemonic::parse(SECRET_PHRASE).unwrap(); - let sender_keypair = Keypair::from_phrase(&mnemonic, None).unwrap(); - - // Sign and submit the extrinsic, then wait for it to be finalized. - let events = api - .tx() - .sign_and_submit_then_watch_default(&balance_transfer_tx, &sender_keypair) - .await? - .wait_for_finalized_success() - .await?; - - // Check for a successful transfer event. - if let Some(event) = events.find_first::()? { - println!("Balance transfer successful: {:?}", event); - } -``` +### XCM Configuration -## Where to Go Next +You can use the `hrmp_channels` keyword to define further parameters for the XCM channels at start-up. The available keys are: -Now that you've covered the basics dive into the official [subxt documentation](https://docs.rs/subxt/latest/subxt/book/index.html){target=\_blank} for comprehensive reference materials and advanced features. +- **`hrmp_channels`** ++"HrmpChannelsConfig[]"++: Array of Horizontal Relay-routed Message Passing (HRMP) channel configurations. + ??? child "`HrmpChannelsConfig` interface definition" + ```js + export interface HrmpChannelsConfig { + sender: number; + recipient: number; + max_capacity: number; + max_message_size: number; + } + ``` + Each of the `HrmpChannelsConfig` keys are defined as follows: ---- + - **`sender` ++"number"++**: Parachain ID of the sender. + - **`recipient` ++"number"++**: Parachain ID of the recipient. + - **`max_capacity` ++"number"++**: Maximum capacity of the HRMP channel. + - **`max_message_size` ++"number"++**: Maximum message size allowed in the HRMP channel. -Page Title: Technical Reference Overview +## Where to Go Next -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference.md -- Canonical (HTML): https://docs.polkadot.com/reference/ -- Summary: Learn about Polkadot's technical architecture, governance framework, parachain ecosystem, and the tools you need to build and interact with the network. +
-## Introduction +- External __Zombienet Support__ -The Technical Reference section provides comprehensive documentation of Polkadot's architecture, core concepts, and development tooling. Whether you're exploring how Polkadot's relay chain coordinates parachains, understanding governance mechanisms, or building applications on the network, this reference covers the technical foundations you need. + --- -Polkadot is a multi-chain network that enables diverse, interconnected blockchains to share security and communicate seamlessly. Understanding how these components interact from the [relay chain](/polkadot-protocol/glossary#relay-chain){target=\_blank} that validates [parachains](/polkadot-protocol/glossary#parachain){target=\_blank} to the [governance](/reference/glossary#governance){target=\_blank} mechanisms that evolve the protocol is essential for developers, validators, and network participants. + [Parity Technologies](https://www.parity.io/){target=\_blank} has designed and developed this framework, now maintained by the Zombienet team. -This guide organizes technical documentation across five core areas: Polkadot Hub, Parachains, On-Chain Governance, Glossary, and Tools, each providing detailed information on different aspects of the Polkadot ecosystem. + For further support and information, refer to the following contact points: -## Polkadot Hub + [:octicons-arrow-right-24: Zombienet repository](https://github.com/paritytech/zombienet){target=\_blank} -[Polkadot Hub](/reference/polkadot-hub/){target=\_blank} is the entry point to Polkadot for all users and application developers. It provides access to essential Web3 services, including smart contracts, staking, governance, identity management, and cross-ecosystem interoperability—without requiring you to deploy or manage a parachain. + [:octicons-arrow-right-24: Element public channel](https://matrix.to/#/!FWyuEyNvIFygLnWNMh:parity.io?via=parity.io&via=matrix.org&via=web3.foundation){target=\_blank} -The Hub encompasses a set of core functionality that enables developers and users to build and interact with applications on Polkadot. Key capabilities include: -- **Smart contracts**: Deploy Ethereum-compatible smart contracts and build decentralized applications. -- **Assets and tokens**: Create, manage, and transfer fungible tokens and NFTs across the ecosystem. -- **Staking**: Participate in network security and earn rewards by staking DOT. -- **Governance**: Vote on proposals and participate in Polkadot's decentralized decision-making through OpenGov. -- **Identity services**: Register and manage on-chain identities, enabling access to governance roles and network opportunities. -- **Cross-chain interoperability**: Leverage XCM messaging to interact securely with other chains in the Polkadot ecosystem. -- **Collectives and DAOs**: Participate in governance collectives and decentralized autonomous organizations. +- Tutorial __Spawn a Basic Chain with Zombienet__ -## Parachains + --- -[Parachains](/reference/parachains/){target=\_blank} are specialized blockchains that connect to the Polkadot relay chain, inheriting its security while maintaining their own application-specific logic. The parachains documentation covers: + Learn to spawn, connect to and monitor a basic blockchain network with Zombienet, using customizable configurations for streamlined development and debugging. -- **Accounts**: Deep dive into account types, storage, and management on parachains. -- **Blocks, transactions and fees**: Understand block production, transaction inclusion, and fee mechanisms. -- **Consensus**: Learn how parachain blocks are validated and finalized through the relay chain's consensus. -- **Chain data**: Explore data structures, storage layouts, and state management. -- **Cryptography**: Study cryptographic primitives used in Polkadot SDK-based chains. -- **Data encoding**: Understand how data is encoded and decoded for blockchain compatibility. -- **Networks**: Learn about networking protocols and peer-to-peer communication. -- **Interoperability**: Discover [Cross-Consensus Messaging (XCM)](/parachains/interoperability/get-started/){target=\_blank}, the standard for cross-chain communication. -- **Randomness**: Understand how randomness is generated and used in Polkadot chains. -- **Node and runtime**: Learn about parachain nodes, runtime environments, and the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}. + [:octicons-arrow-right-24: Reference](/tutorials/polkadot-sdk/testing/spawn-basic-chain/) -## On-Chain Governance +
-[On-Chain governance](/reference/governance/){target=\_blank} is the decentralized decision-making mechanism for the Polkadot network. It manages the evolution and modification of the network's runtime logic, enabling community oversight and approval for proposed changes. The governance documentation details: -- **OpenGov framework**: Understand Polkadot's next-generation governance system with enhanced delegation, flexible tracks, and simultaneous referendums. -- **Origins and tracks**: Learn how governance proposals are categorized, prioritized, and executed based on their privilege level and complexity. -- **Voting and delegation**: Explore conviction voting, vote delegation, and how token holders participate in governance. -- **Governance evolution**: See how Polkadot's governance has evolved from Governance V1 to the current OpenGov system. +--- -## Glossary +Page Title: Set Up the Polkadot SDK Parachain Template -The [Glossary](/reference/glossary/){target=\_blank} provides quick-reference definitions for Polkadot-specific terminology. Essential terms include: +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-launch-a-parachain-set-up-the-parachain-template.md +- Canonical (HTML): https://docs.polkadot.com/parachains/launch-a-parachain/set-up-the-parachain-template/ +- Summary: Learn how to set up and run the Polkadot SDK Parachain Template locally, creating a ready-to-customize foundation for your parachain. -- Blockchain concepts (blocks, transactions, state) -- Consensus mechanisms (validators, collators, finality) -- Polkadot-specific terms (relay chain, parachain, XCM, FRAME) -- Network components (nodes, runtimes, storage) -- Governance terminology (origins, tracks, referendums) +# Set Up the Polkadot SDK Parachain Template -## Tools +## Introduction -The [Tools](/reference/tools/){target=\_blank} section documents essential development and interaction tools for the Polkadot ecosystem: +The [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank} includes several [templates](/parachains/customize-runtime/#starting-templates){target=\_blank} designed to help you quickly start building your own blockchain. Each template offers a different level of configuration, from minimal setups to feature-rich environments, allowing you to choose the foundation that best fits your project's needs. -- **Light clients**: Lightweight solutions for interacting with the network without running full nodes. -- **JavaScript/TypeScript tools**: Libraries like [Polkadot.js API](/reference/tools/polkadot-js-api/){target=\_blank} and [PAPI](/reference/tools/papi/){target=\_blank} for building applications. -- **Rust tools**: [Polkadart](/reference/tools/polkadart/){target=\_blank} and other Rust-based libraries for SDK development. -- **Python tools**: [py-substrate-interface](/reference/tools/py-substrate-interface/){target=\_blank} for Python developers. -- **Testing and development**: Tools like [Moonwall](/reference/tools/moonwall/){target=\_blank}, [Chopsticks](/reference/tools/chopsticks/){target=\_blank}, and [Omninode](/reference/tools/omninode/){target=\_blank} for smart contract and parachain testing. -- **Indexing and monitoring**: [Sidecar](/reference/tools/sidecar/){target=\_blank} for data indexing and [Dedot](/reference/tools/dedot/){target=\_blank} for substrate interaction. -- **Cross-chain tools**: [ParaSpell](/reference/tools/paraspell/){target=\_blank} for XCM integration and asset transfers. +Among these, the [Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank} provides a preconfigured runtime with commonly used pallets, making it an ideal starting point for most parachain development projects. -## Where to Go Next +This guide walks you through the full process of working with this template. You will: -For detailed exploration of specific areas, proceed to any of the main sections: +- Set up the Polkadot SDK Parachain Template. +- Understand the project structure and key components. +- Verify your template is ready for development. +- Run the parachain template locally in development mode. -
+By the end of this guide, you'll have a working template ready to customize and deploy as a parachain. -- Learn **Polkadot Hub** +## Prerequisites - --- +Before getting started, ensure you have done the following: - Understand the relay chain's role in coordinating parachains, providing shared security, and enabling governance. +- Completed the [Install Polkadot SDK](/parachains/install-polkadot-sdk/){target=\_blank} guide and successfully installed [Rust](https://www.rust-lang.org/){target=\_blank} and the required packages to set up your development environment. - [:octicons-arrow-right-24: Reference](/reference/polkadot-hub/) +For this tutorial series, you need to use Rust `1.86`. Newer versions of the compiler may not work with this parachain template version. -- Learn **Parachains** +Run the following commands to set up the correct Rust version: - --- +=== "macOS" - Deep dive into parachain architecture, consensus, data structures, and building application-specific blockchains. + ```bash + rustup install 1.86 + rustup default 1.86 + rustup target add wasm32-unknown-unknown --toolchain 1.86-aarch64-apple-darwin + rustup component add rust-src --toolchain 1.86-aarch64-apple-darwin + ``` - [:octicons-arrow-right-24: Reference](/reference/parachains/) +=== "Ubuntu" -- Learn **On-Chain Governance** + ```bash + rustup toolchain install 1.86.0 + rustup default 1.86.0 + rustup target add wasm32-unknown-unknown --toolchain 1.86.0 + rustup component add rust-src --toolchain 1.86.0 + ``` - --- +## Polkadot SDK Utility Tools - Explore Polkadot's decentralized governance framework and how to participate in network decision-making. +This tutorial requires two essential tools: - [:octicons-arrow-right-24: Reference](/reference/governance/) +- [**Chain spec builder**](https://crates.io/crates/staging-chain-spec-builder/10.0.0){target=\_blank}: A Polkadot SDK utility for generating chain specifications. Refer to the [Generate Chain Specs](/develop/parachains/deployment/generate-chain-specs/){target=\_blank} documentation for detailed usage. + + Install it by executing the following command: + + ```bash + cargo install --locked staging-chain-spec-builder@10.0.0 + ``` -- Guide **Glossary** + This command installs the `chain-spec-builder` binary. - --- +- [**Polkadot Omni Node**](https://crates.io/crates/polkadot-omni-node/0.5.0){target=\_blank}: A white-labeled binary, released as a part of Polkadot SDK that can act as the collator of a parachain in production, with all the related auxiliary functionalities that a normal collator node has: RPC server, archiving state, etc. Moreover, it can also run the Wasm blob of the parachain locally for testing and development. - Quick reference for Polkadot-specific terminology and concepts used throughout the documentation. + To install it, run the following command: - [:octicons-arrow-right-24: Reference](/reference/glossary/) + ```bash + cargo install --locked polkadot-omni-node@0.5.0 + ``` -- Guide **Tools** + This command installs the `polkadot-omni-node` binary. - --- +## Clone the Template - Discover development tools, libraries, and frameworks for building and interacting with Polkadot. +The [Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\_blank} provides a ready-to-use development environment for building with the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}. Follow these steps to set up the template: - [:octicons-arrow-right-24: Reference](/reference/tools/) +1. Clone the template repository: -
+ ```bash + git clone https://github.com/paritytech/polkadot-sdk-parachain-template.git parachain-template + ``` +2. Navigate into the project directory: ---- + ```bash + cd parachain-template + ``` -Page Title: Transactions +## Explore the Project Structure -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-transactions.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/transactions/ -- Summary: Learn how to construct, submit, and validate transactions in the Polkadot SDK, covering signed, unsigned, and inherent types of transactions. +Before building the template, take a moment to familiarize yourself with its structure. Understanding this organization will help you navigate the codebase as you develop your parachain. -# Transactions +The template follows a standard Polkadot SDK project layout: -## Introduction +```text +parachain-template/ +├── node/ # Node implementation and client +├── pallets/ # Custom pallets for your parachain +├── runtime/ # Runtime configuration and logic +├── Cargo.toml # Workspace configuration +└── README.md # Documentation +``` -Transactions are essential components of blockchain networks, enabling state changes and the execution of key operations. In the Polkadot SDK, transactions, often called extrinsics, come in multiple forms, including signed, unsigned, and inherent transactions. +Key directories explained: -This guide walks you through the different transaction types and how they're formatted, validated, and processed within the Polkadot ecosystem. You'll also learn how to customize transaction formats and construct transactions for FRAME-based runtimes, ensuring a complete understanding of how transactions are built and executed in Polkadot SDK-based chains. +- **runtime/**: Contains your parachain's state transition function and pallet configuration. This is where you'll define what your blockchain can do. +- **node/**: Houses the client implementation that runs your blockchain, handles networking, and manages the database. +- **pallets/**: Where you'll create custom business logic modules (pallets) for your specific use case. +- **Cargo.toml**: The workspace configuration that ties all components together. -## What Is a Transaction? +!!!note + The runtime is compiled to WebAssembly (Wasm), enabling forkless upgrades. The node binary remains constant while the runtime can be updated on-chain. -In the Polkadot SDK, transactions represent operations that modify the chain's state, bundled into blocks for execution. The term extrinsic is often used to refer to any data that originates outside the runtime and is included in the chain. While other blockchain systems typically refer to these operations as "transactions," the Polkadot SDK adopts the broader term "extrinsic" to capture the wide variety of data types that can be added to a block. +## Compile the Runtime -There are three primary types of transactions (extrinsics) in the Polkadot SDK: +Now that you understand the template structure, let's compile the runtime to ensure everything is working correctly. -- **Signed transactions**: Signed by the submitting account, often carrying transaction fees. -- **Unsigned transactions**: Submitted without a signature, often requiring custom validation logic. -- **Inherent transactions**: Typically inserted directly into blocks by block authoring nodes, without gossiping between peers. +1. Compile the runtime: -Each type serves a distinct purpose, and understanding when and how to use each is key to efficiently working with the Polkadot SDK. + ```bash + cargo build --release --locked + ``` -### Signed Transactions + !!!tip + Initial compilation may take several minutes, depending on your machine specifications. Use the `--release` flag for improved runtime performance compared to the default `--debug` build. If you need to troubleshoot issues, the `--debug` build provides better diagnostics. + + For production deployments, consider using a dedicated `--profile production` flag - this can provide an additional 15-30% performance improvement over the standard `--release` profile. -Signed transactions require an account's signature and typically involve submitting a request to execute a runtime call. The signature serves as a form of cryptographic proof that the sender has authorized the action, using their private key. These transactions often involve a transaction fee to cover the cost of execution and incentivize block producers. +2. Upon successful compilation, you should see output indicating the build was successful. The compiled runtime will be located at: + + `./target/release/wbuild/parachain-template-runtime/parachain_template_runtime.compact.compressed.wasm` -Signed transactions are the most common type of transaction and are integral to user-driven actions, such as token transfers. For instance, when you transfer tokens from one account to another, the sending account must sign the transaction to authorize the operation. +## Verify the Build -For example, the [`pallet_balances::Call::transfer_allow_death`](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/pallet/struct.Pallet.html#method.transfer_allow_death){target=\_blank} extrinsic in the Balances pallet allows you to transfer tokens. Since your account initiates this transaction, your account key is used to sign it. You'll also be responsible for paying the associated transaction fee, with the option to include an additional tip to incentivize faster inclusion in the block. +After compilation completes, verify that the runtime was created successfully by checking for the Wasm blob: -### Unsigned Transactions +```bash +ls -la ./target/release/wbuild/parachain-template-runtime/ +``` -Unsigned transactions do not require a signature or account-specific data from the sender. Unlike signed transactions, they do not come with any form of economic deterrent, such as fees, which makes them susceptible to spam or replay attacks. Custom validation logic must be implemented to mitigate these risks and ensure these transactions are secure. +You should see the `parachain_template_runtime.compact.compressed.wasm` file in the output, confirming the build was successful. -Unsigned transactions typically involve scenarios where including a fee or signature is unnecessary or counterproductive. However, due to the absence of fees, they require careful validation to protect the network. For example, [`pallet_im_online::Call::heartbeat`](https://paritytech.github.io/polkadot-sdk/master/pallet_im_online/pallet/struct.Pallet.html#method.heartbeat){target=\_blank} extrinsic allows validators to send a heartbeat signal, indicating they are active. Since only validators can make this call, the logic embedded in the transaction ensures that the sender is a validator, making the need for a signature or fee redundant. +## Run the Node Locally -Unsigned transactions are more resource-intensive than signed ones because custom validation is required, but they play a crucial role in certain operational scenarios, especially when regular user accounts aren't involved. +After successfully compiling your runtime, you can spin up a local chain and produce blocks. This process will start your local parachain using the Polkadot Omni Node and allow you to interact with it. You'll first need to generate a chain specification that defines your network's identity, initial connections, and genesis state, providing the foundational configuration for how your nodes connect and what initial state they agree upon. -### Inherent Transactions +Follow these steps to launch your node in development mode: -Inherent transactions are a specialized type of unsigned transaction that is used primarily for block authoring. Unlike signed or other unsigned transactions, inherent transactions are added directly by block producers and are not broadcasted to the network or stored in the transaction queue. They don't require signatures or the usual validation steps and are generally used to insert system-critical data directly into blocks. +1. Generate the chain specification file of your parachain: -A key example of an inherent transaction is inserting a timestamp into each block. The [`pallet_timestamp::Call::now`](https://paritytech.github.io/polkadot-sdk/master/pallet_timestamp/pallet/struct.Pallet.html#method.now-1){target=\_blank} extrinsic allows block authors to include the current time in the block they are producing. Since the block producer adds this information, there is no need for transaction validation, like signature verification. The validation in this case is done indirectly by the validators, who check whether the timestamp is within an acceptable range before finalizing the block. + ```bash + chain-spec-builder create -t development \ + --relay-chain paseo \ + --para-id 1000 \ + --runtime ./target/release/wbuild/parachain-template-runtime/parachain_template_runtime.compact.compressed.wasm \ + named-preset development + ``` -Another example is the [`paras_inherent::Call::enter`](https://paritytech.github.io/polkadot-sdk/master/polkadot_runtime_parachains/paras_inherent/pallet/struct.Pallet.html#method.enter){target=\_blank} extrinsic, which enables parachain collator nodes to send validation data to the relay chain. This inherent transaction ensures that the necessary parachain data is included in each block without the overhead of gossiped transactions. +2. Start the Omni Node with the generated chain spec. You'll start it in development mode (without a relay chain config), producing and finalizing blocks: -Inherent transactions serve a critical role in block authoring by allowing important operational data to be added directly to the chain without needing the validation processes required for standard transactions. + ```bash + polkadot-omni-node --chain ./chain_spec.json --dev + ``` -## Transaction Formats + The `--dev` option does the following: -Understanding the structure of signed and unsigned transactions is crucial for developers building on Polkadot SDK-based chains. Whether you're optimizing transaction processing, customizing formats, or interacting with the transaction pool, knowing the format of extrinsics, Polkadot's term for transactions, is essential. + - Deletes all active data (keys, blockchain database, networking information) when stopped. + - Ensures a clean working state each time you restart the node. -### Types of Transaction Formats +3. Verify that your node is running by reviewing the terminal output. You should see log messages indicating block production and finalization. -In Polkadot SDK-based chains, extrinsics can fall into three main categories: +4. Confirm that your blockchain is producing new blocks by checking if the number after `finalized` is increasing in the output. -- **Unchecked extrinsics**: Typically used for signed transactions that require validation. They contain a signature and additional data, such as a nonce and information for fee calculation. Unchecked extrinsics are named as such because they require validation checks before being accepted into the transaction pool. -- **Checked extrinsics**: Typically used for inherent extrinsics (unsigned transactions); these don't require signature verification. Instead, they carry information such as where the extrinsic originates and any additional data required for the block authoring process. -- **Opaque extrinsics**: Used when the format of an extrinsic is not yet fully committed or finalized. They are still decodable, but their structure can be flexible depending on the context. +The details of the log output will be explored in a later tutorial. For now, knowing that your node is running and producing blocks is sufficient. -### Signed Transaction Data Structure +## Interact with the Node -A signed transaction typically includes the following components: +When running the template node, it's accessible by default at `ws://localhost:9944`. To interact with your node using the [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} interface, follow these steps: -- **Signature**: Verifies the authenticity of the transaction sender. -- **Call**: The actual function or method call the transaction is requesting (for example, transferring funds). -- **Nonce**: Tracks the number of prior transactions sent from the account, helping to prevent replay attacks. -- **Tip**: An optional incentive to prioritize the transaction in block inclusion. -- **Additional data**: Includes details such as spec version, block hash, and genesis hash to ensure the transaction is valid within the correct runtime and chain context. +1. Open [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} in your web browser and click the network icon (which should be the Polkadot logo) in the top left corner: + + ![](/images/parachains/launch-a-parachain/set-up-the-parachain-template/parachain-template-01.webp) -Here's a simplified breakdown of how signed transactions are typically constructed in a Polkadot SDK runtime: +2. Connect to your local node: -``` code - + + -``` + 1. Scroll to the bottom and select **Development**. + 2. Choose **Custom**. + 3. Enter `ws://localhost:9944` in the **custom endpoint** input field. + 4. Click the **Switch** button. + + ![](/images/parachains/launch-a-parachain/set-up-the-parachain-template/parachain-template-02.webp) -Each part of the signed transaction has a purpose, ensuring the transaction's authenticity and context within the blockchain. +3. Once connected, you should see **parachain-template-runtime** in the top left corner, with the interface displaying information about your local blockchain. + + ![](/images/parachains/launch-a-parachain/set-up-the-parachain-template/parachain-template-03.webp) -### Signed Extensions +You are now connected to your local node and can interact with it through the Polkadot.js Apps interface. This tool enables you to explore blocks, execute transactions, and interact with your blockchain's features. For in-depth guidance on using the interface effectively, refer to the [Polkadot.js Guides](https://wiki.polkadot.com/general/polkadotjs/){target=\_blank} available on the Polkadot Wiki. -Polkadot SDK also provides the concept of [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}, which allow developers to extend extrinsics with additional data or validation logic before they are included in a block. The [`SignedExtension`](https://paritytech.github.io/try-runtime-cli/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} set helps enforce custom rules or protections, such as ensuring the transaction's validity or calculating priority. +## Stop the Node -The transaction queue regularly calls signed extensions to verify a transaction's validity before placing it in the ready queue. This safeguard ensures transactions won't fail in a block. Signed extensions are commonly used to enforce validation logic and protect the transaction pool from spam and replay attacks. +When you're done exploring your local node, you can stop it to remove any state changes you've made. Since you started the node with the `--dev` option, stopping the node will purge all persistent block data, allowing you to start fresh the next time. -In FRAME, a signed extension can hold any of the following types by default: +To stop the local node: -- **[`AccountId`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/runtime/types_common/type.AccountId.html){target=\_blank}**: To encode the sender's identity. -- **[`Call`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Call){target=\_blank}**: To encode the pallet call to be dispatched. This data is used to calculate transaction fees. -- **[`AdditionalSigned`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.AdditionalSigned){target=\_blank}**: To handle any additional data to go into the signed payload allowing you to attach any custom logic prior to dispatching a transaction. -- **[`Pre`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Pre){target=\_blank}**: To encode the information that can be passed from before a call is dispatched to after it gets dispatched. +1. Return to the terminal window where the node output is displayed. +2. Press `Control-C` to stop the running process. +3. Verify that your terminal returns to the prompt in the `parachain-template` directory. -Signed extensions can enforce checks like: +## Where to Go Next -- **[`CheckSpecVersion`](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/extensions/check_spec_version.rs.html){target=\_blank}**: Ensures the transaction is compatible with the runtime's current version. -- **[`CheckWeight`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.CheckWeight.html){target=\_blank}**: Calculates the weight (or computational cost) of the transaction, ensuring the block doesn't exceed the maximum allowed weight. +
-These extensions are critical in the transaction lifecycle, ensuring that only valid and prioritized transactions are processed. +- Tutorial __Deploy to Polkadot__ -## Transaction Construction + --- -Building transactions in the Polkadot SDK involves constructing a payload that can be verified, signed, and submitted for inclusion in a block. Each runtime in the Polkadot SDK has its own rules for validating and executing transactions, but there are common patterns for constructing a signed transaction. + Learn how to deploy your parachain template to a relay chain testnet. Configure your chain specification, register as a parachain, and start producing blocks. -### Construct a Signed Transaction + [:octicons-arrow-right-24: Get Started](/parachains/launch-a-parachain/deploy-to-polkadot.md) -A signed transaction in the Polkadot SDK includes various pieces of data to ensure security, prevent replay attacks, and prioritize processing. Here's an overview of how to construct one: +
-1. **Construct the unsigned payload**: Gather the necessary information for the call, including: - - **Pallet index**: Identifies the pallet where the runtime function resides. - - **Function index**: Specifies the particular function to call in the pallet. - - **Parameters**: Any additional arguments required by the function call. +--- -2. **Create a signing payload**: Once the unsigned payload is ready, additional data must be included: +Page Title: Smart Contracts Cookbook Index - - **Transaction nonce**: Unique identifier to prevent replay attacks. - - **Era information**: Defines how long the transaction is valid before it's dropped from the pool. - - **Block hash**: Ensures the transaction doesn't execute on the wrong chain or fork. +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/cookbook/ +- Summary: Explore our full collection of tutorials and guides to learn step-by-step how to build, deploy, and work with smart contracts on Polkadot. -3. **Sign the payload**: Using the sender's private key, sign the payload to ensure that the transaction can only be executed by the account holder. -4. **Serialize the signed payload**: Once signed, the transaction must be serialized into a binary format, ensuring the data is compact and easy to transmit over the network. -5. **Submit the serialized transaction**: Finally, submit the serialized transaction to the network, where it will enter the transaction pool and wait for processing by an authoring node. +# Smart Contracts Cookbook -The following is an example of how a signed transaction might look: +Welcome to the Polkadot smart contracts cookbook index. -``` rust -node_runtime::UncheckedExtrinsic::new_signed( - function.clone(), // some call - sp_runtime::AccountId32::from(sender.public()).into(), // some sending account - node_runtime::Signature::Sr25519(signature.clone()), // the account's signature - extra.clone(), // the signed extensions -) -``` +This page contains a list of all relevant tutorials and guides to help you get started coding smart contracts and dApps in Polkadot. -### Transaction Encoding -Before a transaction is sent to the network, it is serialized and encoded using a structured encoding process that ensures consistency and prevents tampering: -- **`[1]`**: Compact encoded length in bytes of the entire transaction. -- **`[2]`**: A u8 containing 1 byte to indicate whether the transaction is signed or unsigned (1 bit) and the encoded transaction version ID (7 bits). -- **`[3]`**: If signed, this field contains an account ID, an SR25519 signature, and some extra data. -- **`[4]`**: Encoded call data, including pallet and function indices and any required arguments. -This encoded format ensures consistency and efficiency in processing transactions across the network. By adhering to this format, applications can construct valid transactions and pass them to the network for execution. +## Get Tokens from the Faucet -To learn more about how compact encoding works using SCALE, see the [SCALE Codec](https://github.com/paritytech/parity-scale-codec){target=\_blank} README on GitHub. +| Title | Difficulty | Tools | Description | +|------------------------------------|:-----------:|-------|-----------------------------------------------------------------------------------------------------------------------| +| [Faucet](/smart-contracts/faucet/) | 🟢 Beginner | N/A | Learn how to obtain test tokens from Polkadot faucets for development and testing purposes across different networks. | -### Customize Transaction Construction +## EVM/PVM Smart Contracts -Although the basic steps for constructing transactions are consistent across Polkadot SDK-based chains, developers can customize transaction formats and validation rules. For example: +| Title | Difficulty | Tools | Description | +|---------------------------------------------------------------------------------------------------|:-----------:|--------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [Deploy an ERC-20 to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-erc20/remix/) | 🟢 Beginner | EVM Wallet, Polkadot Remix IDE | Deploy an ERC-20 token on Polkadot Hub using PolkaVM. This guide covers contract creation, compilation, deployment, and interaction via Polkadot Remix IDE. | +| [Deploy an NFT to Polkadot Hub](/smart-contracts/cookbook/smart-contracts/deploy-nft/remix/) | 🟢 Beginner | EVM Wallet, Polkadot Remix IDE | Deploy an NFT on Polkadot Hub using PolkaVM and OpenZeppelin. Learn how to compile, deploy, and interact with your contract using Polkadot Remix IDE. | -- **Custom pallets**: You can define new pallets with custom function calls, each with its own parameters and validation logic. -- **Signed extensions**: Developers can implement custom extensions that modify how transactions are prioritized, validated, or included in blocks. +## Port Ethereum DApps -By leveraging Polkadot SDK's modular design, developers can create highly specialized transaction logic tailored to their chain's needs. +| Title | Difficulty | Tools | Description | +|-------------------------------------------------------------------------------------|:---------------:|---------|----------------------------------------------------------------------------------------------------------------------------------| +| [Deploying Uniswap V2 on Polkadot](/smart-contracts/cookbook/eth-dapps/uniswap-v2/) | 🟡 Intermediate | Hardhat | Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. | -## Lifecycle of a Transaction -In the Polkadot SDK, transactions are often referred to as extrinsics because the data in transactions originates outside of the runtime. These transactions contain data that initiates changes to the chain state. The most common type of extrinsic is a signed transaction, which is cryptographically verified and typically incurs a fee. This section focuses on how signed transactions are processed, validated, and ultimately included in a block. +--- -### Define Transaction Properties +Page Title: Smart Contracts Overview -The Polkadot SDK runtime defines key transaction properties, such as: +- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-overview.md +- Canonical (HTML): https://docs.polkadot.com/smart-contracts/overview/ +- Summary: Learn about smart contract development capabilities in the Polkadot ecosystem, either by leveraging Polkadot Hub or other alternatives. -- **Transaction validity**: Ensures the transaction meets all runtime requirements. -- **Signed or unsigned**: Identifies whether a transaction needs to be signed by an account. -- **State changes**: Determines how the transaction modifies the state of the chain. +# Smart Contracts on Polkadot -Pallets, which compose the runtime's logic, define the specific transactions that your chain supports. When a user submits a transaction, such as a token transfer, it becomes a signed transaction, verified by the user's account signature. If the account has enough funds to cover fees, the transaction is executed, and the chain's state is updated accordingly. +!!! smartcontract "PolkaVM Preview Release" + PolkaVM smart contracts with Ethereum compatibility are in **early-stage development and may be unstable or incomplete**. +## Introduction -### Process on a Block Authoring Node +Polkadot offers developers multiple approaches to building and deploying smart contracts within its ecosystem. As a multi-chain network designed for interoperability, Polkadot provides various environments optimized for different developer preferences and application requirements. From native smart contract support on Polkadot Hub to specialized parachain environments, developers can choose the platform that best suits their technical needs while benefiting from Polkadot's shared security model and cross-chain messaging capabilities. -In Polkadot SDK-based networks, some nodes are authorized to author blocks. These nodes validate and process transactions. When a transaction is sent to a node that can produce blocks, it undergoes a lifecycle that involves several stages, including validation and execution. Non-authoring nodes gossip the transaction across the network until an authoring node receives it. The following diagram illustrates the lifecycle of a transaction that's submitted to a network and processed by an authoring node. +Whether you're looking for Ethereum compatibility through EVM-based parachains like [Moonbeam](https://docs.moonbeam.network/){target=\_blank}, [Astar](https://docs.astar.network/){target=\_blank}, and [Acala](https://evmdocs.acala.network/){target=\_blank} or prefer PolkaVM-based development with [ink!](https://use.ink/docs/v6/){target=\_blank}, the Polkadot ecosystem accommodates a range of diverse developers. -![Transaction lifecycle diagram](/images/reference/parachains/blocks-transactions-fees/transactions/transactions-01.webp){ style="background:white" } +These guides explore the diverse smart contract options available in the Polkadot ecosystem, helping developers understand the unique advantages of each approach and make informed decisions about where to deploy their decentralized applications. -### Validate and Queue +## Native Smart Contracts -Once a transaction reaches an authoring node, it undergoes an initial validation process to ensure it meets specific conditions defined in the runtime. This validation includes checks for: +### Introduction -- **Correct nonce**: Ensures the transaction is sequentially valid for the account. -- **Sufficient funds**: Confirms the account can cover any associated transaction fees. -- **Signature validity**: Verifies that the sender's signature matches the transaction data. +Polkadot Hub enables smart contract deployment and execution through PolkaVM, a cutting-edge virtual machine designed specifically for the Polkadot ecosystem. This native integration allows developers to deploy smart contracts directly on Polkadot's system chain while maintaining compatibility with Ethereum development tools and workflows. -After these checks, valid transactions are placed in the transaction pool, where they are queued for inclusion in a block. The transaction pool regularly re-validates queued transactions to ensure they remain valid before being processed. To reach consensus, two-thirds of the nodes must agree on the order of the transactions executed and the resulting state change. Transactions are validated and queued on the local node in a transaction pool to prepare for consensus. +### Smart Contract Development -#### Transaction Pool +The smart contract platform on Polkadot Hub combines _Polkadot's robust security and scalability_ with the extensive Ethereum development ecosystem. Developers can utilize familiar Ethereum libraries for contract interactions and leverage industry-standard development environments for writing and testing smart contracts. -The transaction pool is responsible for managing valid transactions. It ensures that only transactions that pass initial validity checks are queued. Transactions that fail validation, expire, or become invalid for other reasons are removed from the pool. +Polkadot Hub provides _full Ethereum JSON-RPC API compatibility_, ensuring seamless integration with existing development tools and services. This compatibility enables developers to maintain their preferred workflows while building on Polkadot's native infrastructure. -The transaction pool organizes transactions into two queues: +### Technical Architecture -- **Ready queue**: Transactions that are valid and ready to be included in a block. -- **Future queue**: Transactions that are not yet valid but could be in the future, such as transactions with a nonce too high for the current state. +PolkaVM, the underlying virtual machine, utilizes a RISC-V-based register architecture _optimized for the Polkadot ecosystem_. This design choice offers several advantages: -Details on how the transaction pool validates transactions, including fee and signature handling, can be found in the [`validate_transaction`](https://paritytech.github.io/polkadot-sdk/master/sp_transaction_pool/runtime_api/trait.TaggedTransactionQueue.html#method.validate_transaction){target=\_blank} method. +- Enhanced performance for smart contract execution. +- Improved gas efficiency for complex operations. +- Native compatibility with Polkadot's runtime environment. +- Optimized storage and state management. -#### Invalid Transactions +### Development Tools and Resources -If a transaction is invalid, for example, due to an invalid signature or insufficient funds, it is rejected and won't be added to the block. Invalid transactions might be rejected for reasons such as: +Polkadot Hub supports a comprehensive suite of development tools familiar to Ethereum developers. The platform integrates with popular development frameworks, testing environments, and deployment tools. Key features include: -- The transaction has already been included in a block. -- The transaction's signature does not match the sender. -- The transaction is too large to fit in the current block. +- Contract development in Solidity or Rust. +- Support for standard Ethereum development libraries. +- Integration with widely used development environments. +- Access to blockchain explorers and indexing solutions. +- Compatibility with contract monitoring and management tools. -### Transaction Ordering and Priority +### Cross-Chain Capabilities -When a node is selected as the next block author, it prioritizes transactions based on weight, length, and tip amount. The goal is to fill the block with high-priority transactions without exceeding its maximum size or computational limits. Transactions are ordered as follows: +Smart contracts deployed on Polkadot Hub can leverage Polkadot's [cross-consensus messaging (XCM) protocol](/parachains/interoperability/get-started/){target=\_blank} protocol to seamlessly _transfer tokens and call functions on other blockchain networks_ within the Polkadot ecosystem, all without complex bridging infrastructure or third-party solutions. For further references, check the [Interoperability](/develop/interoperability/){target=\_blank} section. -- **Inherents first**: Inherent transactions, such as block timestamp updates, are always placed first. -- **Nonce-based ordering**: Transactions from the same account are ordered by their nonce. -- **Fee-based ordering**: Among transactions with the same nonce or priority level, those with higher fees are prioritized. +### Use Cases -### Transaction Execution +Polkadot Hub's smart contract platform is suitable for a wide range of applications: -Once a block author selects transactions from the pool, the transactions are executed in priority order. As each transaction is processed, the state changes are written directly to the chain's storage. It's important to note that these changes are not cached, meaning a failed transaction won't revert earlier state changes, which could leave the block in an inconsistent state. +- DeFi protocols leveraging _cross-chain capabilities_. +- NFT platforms utilizing Polkadot's native token standards. +- Governance systems integrated with Polkadot's democracy mechanisms. +- Cross-chain bridges and asset management solutions. -Events are also written to storage. Runtime logic should not emit an event before performing the associated actions. If the associated transaction fails after the event was emitted, the event will not revert. +## Other Smart Contract Environments -## Transaction Mortality +Beyond Polkadot Hub's native PolkaVM support, the ecosystem offers two main alternatives for smart contract development: -Transactions in the network can be configured as either mortal (with expiration) or immortal (without expiration). Every transaction payload contains a block checkpoint (reference block number and hash) and an era/validity period that determines how many blocks after the checkpoint the transaction remains valid. +- **EVM-compatible parachains**: Provide access to Ethereum's extensive developer ecosystem, smart contract portability, and established tooling like Hardhat, Remix, Foundry, and OpenZeppelin. The main options include Moonbeam (the first full Ethereum-compatible parachain serving as an interoperability hub), Astar (featuring dual VM support for both EVM and WebAssembly contracts), and Acala (DeFi-focused with enhanced Acala EVM+ offering advanced DeFi primitives). -When a transaction is submitted, the network validates it against these parameters. If the transaction is not included in a block within the specified validity window, it is automatically removed from the transaction queue. +- **Rust (ink!)**: ink! is a Rust-based framework that can compile to PolkaVM. It uses [`#[ink(...)]`](https://use.ink/docs/v6/macros-attributes/){target=\_blank} attribute macros to create Polkadot SDK-compatible PolkaVM bytecode, offering strong memory safety from Rust, an advanced type system, high-performance PolkaVM execution, and platform independence with sandboxed security. -- **Mortal transactions**: Have a finite lifespan and will expire after a specified number of blocks. For example, a transaction with a block checkpoint of 1000 and a validity period of 64 blocks will be valid from blocks 1000 to 1064. -- **Immortal transactions**: Never expire and remain valid indefinitely. To create an immortal transaction, set the block checkpoint to 0 (genesis block), use the genesis hash as a reference, and set the validity period to 0. +Each environment provides unique advantages based on developer preferences and application requirements. -However, immortal transactions pose significant security risks through replay attacks. If an account is reaped (balance drops to zero, account removed) and later re-funded, malicious actors can replay old immortal transactions. +## Where to Go Next -The blockchain maintains only a limited number of prior block hashes for reference validation, called `BlockHashCount`. If your validity period exceeds `BlockHashCount`, the effective validity period becomes the minimum of your specified period and the block hash count. +Developers can use their existing Ethereum development tools and connect to Polkadot Hub's RPC endpoints. The platform's Ethereum compatibility layer ensures a smooth transition for teams already building on Ethereum-compatible chains. -## Unique Identifiers for Extrinsics +Subsequent sections of this guide provide detailed information about specific development tools, advanced features, and best practices for building on Polkadot Hub. -Transaction hashes are **not unique identifiers** in Polkadot SDK-based chains. +
-Key differences from traditional blockchains: +- Guide __Libraries__ -- Transaction hashes serve only as fingerprints of transaction information. -- Multiple valid transactions can share the same hash. -- Hash uniqueness assumptions lead to serious issues. + --- -For example, when an account is reaped (removed due to insufficient balance) and later recreated, it resets to nonce 0, allowing identical transactions to be valid at different points: + Explore essential libraries to optimize smart contract development and interaction. -| Block | Extrinsic Index | Hash | Origin | Nonce | Call | Result | -|-------|----------------|------|-----------|-------|---------------------|-------------------------------| -| 100 | 0 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Account A reaped | -| 150 | 5 | 0x02 | Account B | 4 | Transfer 7 DOT to A | Account A created (nonce = 0) | -| 200 | 2 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Successful transaction | + [:octicons-arrow-right-24: Reference](/smart-contracts/libraries/ethers-js/) -Notice that blocks 100 and 200 contain transactions with identical hashes (0x01) but are completely different, valid operations occurring at different times. +- Guide __Dev Environments__ -Additional complexity comes from Polkadot SDK's origin abstraction. Origins can represent collectives, governance bodies, or other non-account entities that don't maintain nonces like regular accounts and might dispatch identical calls multiple times with the same hash values. Each execution occurs in different chain states with different results. + --- -The correct way to uniquely identify an extrinsic on a Polkadot SDK-based chain is to use the block ID (height or hash) and the extrinsic index. Since the Polkadot SDK defines blocks as headers plus ordered arrays of extrinsics, the index position within a canonical block provides guaranteed uniqueness. + Set up your development environment for seamless contract deployment and testing. -## Additional Resources + [:octicons-arrow-right-24: Reference](/smart-contracts/dev-environments/local-dev-node/) -For a video overview of the lifecycle of transactions and the types of transactions that exist, see the [Transaction lifecycle](https://www.youtube.com/watch?v=3pfM0GOp02c){target=\_blank} seminar from Parity Tech. +
--- @@ -10718,351 +6077,6 @@ The system maintains precise conversion mechanisms between: This ensures accurate fee calculation while maintaining compatibility with existing Ethereum tools and workflows. ---- - -Page Title: Transactions Weights and Fees - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-fees.md -- Canonical (HTML): https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/fees/ -- Summary: Overview of transaction weights and fees in Polkadot SDK chains, detailing how fees are calculated using a defined formula and runtime specifics. - -# Transactions Weights and Fees - -## Introductions - -When transactions are executed, or data is stored on-chain, the activity changes the chain's state and consumes blockchain resources. Because the resources available to a blockchain are limited, managing how operations on-chain consume them is important. In addition to being limited in practical terms, such as storage capacity, blockchain resources represent a potential attack vector for malicious users. For example, a malicious user might attempt to overload the network with messages to stop the network from producing new blocks. To protect blockchain resources from being drained or overloaded, you need to manage how they are made available and how they are consumed. The resources to be aware of include: - -- Memory usage -- Storage input and output -- Computation -- Transaction and block size -- State database size - -The Polkadot SDK provides block authors with several ways to manage access to resources and to prevent individual components of the chain from consuming too much of any single resource. Two of the most important mechanisms available to block authors are weights and transaction fees. - -[Weights](/reference/glossary/#weight){target=\_blank} manage the time it takes to validate a block and characterize the time it takes to execute the calls in the block's body. By controlling the execution time a block can consume, weights set limits on storage input, output, and computation. - -Some of the weight allowed for a block is consumed as part of the block's initialization and finalization. The weight might also be used to execute mandatory inherent extrinsic calls. To help ensure blocks don’t consume too much execution time and prevent malicious users from overloading the system with unnecessary calls, weights are combined with transaction fees. - -[Transaction fees](/reference/parachains/blocks-transactions-fees/transactions/#transaction-fees){target=\_blank} provide an economic incentive to limit execution time, computation, and the number of calls required to perform operations. Transaction fees are also used to make the blockchain economically sustainable because they are typically applied to transactions initiated by users and deducted before a transaction request is executed. - -## How Fees are Calculated - -The final fee for a transaction is calculated using the following parameters: - -- **`base fee`**: This is the minimum amount a user pays for a transaction. It is declared a base weight in the runtime and converted to a fee using the [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} conversion. -- **`weight fee`**: A fee proportional to the execution time (input and output and computation) that a transaction consumes. -- **`length fee`**: A fee proportional to the encoded length of the transaction. -- **`tip`**: An optional tip to increase the transaction’s priority, giving it a higher chance to be included in the transaction queue. - -The base fee and proportional weight and length fees constitute the inclusion fee. The inclusion fee is the minimum fee that must be available for a transaction to be included in a block. - -```text -inclusion fee = base fee + weight fee + length fee -``` - -Transaction fees are withdrawn before the transaction is executed. After the transaction is executed, the weight can be adjusted to reflect the resources used. If a transaction uses fewer resources than expected, the transaction fee is corrected, and the adjusted transaction fee is deposited. - -## Using the Transaction Payment Pallet - -The [Transaction Payment pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/transaction-payment){target=\_blank} provides the basic logic for calculating the inclusion fee. You can also use the Transaction Payment pallet to: - -- Convert a weight value into a deductible fee based on a currency type using [`Config::WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank}. -- Update the fee for the next block by defining a multiplier based on the chain’s final state at the end of the previous block using [`Config::FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank}. -- Manage the withdrawal, refund, and deposit of transaction fees using [`Config::OnChargeTransaction`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.OnChargeTransaction){target=\_blank}. - -You can learn more about these configuration traits in the [Transaction Payment documentation](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_payment/index.html){target=\_blank}. - -### Understanding the Inclusion Fee - -The formula for calculating the inclusion fee is as follows: - -```text -inclusion_fee = base_fee + length_fee + [targeted_fee_adjustment * weight_fee] -``` - -And then, for calculating the final fee: - -```text -final_fee = inclusion_fee + tip -``` - -In the first formula, the `targeted_fee_adjustment` is a multiplier that can tune the final fee based on the network’s congestion. - -- The `base_fee` derived from the base weight covers inclusion overhead like signature verification. -- The `length_fee` is a per-byte fee that is multiplied by the length of the encoded extrinsic. -- The `weight_fee` fee is calculated using two parameters: - - The `ExtrinsicBaseWeight` that is declared in the runtime and applies to all extrinsics. - - The `#[pallet::weight]` annotation that accounts for an extrinsic's complexity. - -To convert the weight to `Currency`, the runtime must define a `WeightToFee` struct that implements a conversion function, [`Convert`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/struct.Pallet.html#method.weight_to_fee){target=\_blank}. - -Note that the extrinsic sender is charged the inclusion fee before the extrinsic is invoked. The fee is deducted from the sender's balance even if the transaction fails upon execution. - -### Accounts with an Insufficient Balance - -If an account does not have a sufficient balance to pay the inclusion fee and remain alive—that is, enough to pay the inclusion fee and maintain the minimum existential deposit—then you should ensure the transaction is canceled so that no fee is deducted and the transaction does not begin execution. - -The Polkadot SDK doesn't enforce this rollback behavior. However, this scenario would be rare because the transaction queue and block-making logic perform checks to prevent it before adding an extrinsic to a block. - -### Fee Multipliers - -The inclusion fee formula always results in the same fee for the same input. However, weight can be dynamic and—based on how [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} is defined—the final fee can include some degree of variability. -The Transaction Payment pallet provides the [`FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank} configurable parameter to account for this variability. - -The Polkadot network inspires the default update function and implements a targeted adjustment in which a target saturation level of block weight is defined. If the previous block is more saturated, the fees increase slightly. Similarly, if the last block has fewer transactions than the target, fees are decreased by a small amount. For more information about fee multiplier adjustments, see the [Web3 Research Page](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank}. - -## Transactions with Special Requirements - -Inclusion fees must be computable before execution and can only represent fixed logic. Some transactions warrant limiting resources with other strategies. For example: - -- Bonds are a type of fee that might be returned or slashed after some on-chain event. For example, you might want to require users to place a bond to participate in a vote. The bond might then be returned at the end of the referendum or slashed if the voter attempted malicious behavior. -- Deposits are fees that might be returned later. For example, you might require users to pay a deposit to execute an operation that uses storage. The user’s deposit could be returned if a subsequent operation frees up storage. -- Burn operations are used to pay for a transaction based on its internal logic. For example, a transaction might burn funds from the sender if the transaction creates new storage items to pay for the increased state size. -- Limits enable you to enforce constant or configurable limits on specific operations. For example, the default [Staking pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/staking){target=\_blank} only allows nominators to nominate 16 validators to limit the complexity of the validator election process. - -It is important to note that if you query the chain for a transaction fee, it only returns the inclusion fee. - -## Default Weight Annotations - -All dispatchable functions in the Polkadot SDK must specify a weight. The way of doing that is using the annotation-based system that lets you combine fixed values for database read/write weight and/or fixed values based on benchmarks. The most basic example would look like this: - -```rust -#[pallet::weight(100_000)] -fn my_dispatchable() { - // ... -} -``` - -Note that the [`ExtrinsicBaseWeight`](https://crates.parity.io/frame_support/weights/constants/struct.ExtrinsicBaseWeight.html){target=\_blank} is automatically added to the declared weight to account for the costs of simply including an empty extrinsic into a block. - -### Weights and Database Read/Write Operations - -To make weight annotations independent of the deployed database backend, they are defined as a constant and then used in the annotations when expressing database accesses performed by the dispatchable: - -```rust -#[pallet::weight(T::DbWeight::get().reads_writes(1, 2) + 20_000)] -fn my_dispatchable() { - // ... -} -``` - -This dispatchable allows one database to read and two to write, in addition to other things that add the additional 20,000. Database access is generally every time a value declared inside the [`#[pallet::storage]`](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/attr.storage.html){target=\_blank} block is accessed. However, unique accesses are counted because after a value is accessed, it is cached, and reaccessing it does not result in a database operation. That is: - -- Multiple reads of the exact value count as one read. -- Multiple writes of the exact value count as one write. -- Multiple reads of the same value, followed by a write to that value, count as one read and one write. -- A write followed by a read-only counts as one write. - -### Dispatch Classes - -Dispatches are broken into three classes: - -- Normal -- Operational -- Mandatory - -If a dispatch is not defined as `Operational` or `Mandatory` in the weight annotation, the dispatch is identified as `Normal` by default. You can specify that the dispatchable uses another class like this: - -```rust -#[pallet::dispatch((DispatchClass::Operational))] -fn my_dispatchable() { - // ... -} -``` - -This tuple notation also allows you to specify a final argument determining whether the user is charged based on the annotated weight. If you don't specify otherwise, `Pays::Yes` is assumed: - -```rust -#[pallet::dispatch(DispatchClass::Normal, Pays::No)] -fn my_dispatchable() { - // ... -} -``` - -#### Normal Dispatches - -Dispatches in this class represent normal user-triggered transactions. These types of dispatches only consume a portion of a block's total weight limit. For information about the maximum portion of a block that can be consumed for normal dispatches, see [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Normal dispatches are sent to the transaction pool. - -#### Operational Dispatches - -Unlike normal dispatches, which represent the usage of network capabilities, operational dispatches are those that provide network capabilities. Operational dispatches can consume the entire weight limit of a block. They are not bound by the [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Dispatches in this class are given maximum priority and are exempt from paying the [`length_fee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/){target=\_blank}. - -#### Mandatory Dispatches - -Mandatory dispatches are included in a block even if they cause the block to surpass its weight limit. You can only use the mandatory dispatch class for inherent transactions that the block author submits. This dispatch class is intended to represent functions in the block validation process. Because these dispatches are always included in a block regardless of the function weight, the validation process must prevent malicious nodes from abusing the function to craft valid but impossibly heavy blocks. You can typically accomplish this by ensuring that: - -- The operation performed is always light. -- The operation can only be included in a block once. - -To make it more difficult for malicious nodes to abuse mandatory dispatches, they cannot be included in blocks that return errors. This dispatch class serves the assumption that it is better to allow an overweight block to be created than not to allow any block to be created at all. - -### Dynamic Weights - -In addition to purely fixed weights and constants, the weight calculation can consider the input arguments of a dispatchable. The weight should be trivially computable from the input arguments with some basic arithmetic: - -```rust -use frame_support:: { - dispatch:: { - DispatchClass::Normal, - Pays::Yes, - }, - weights::Weight, -}; - -#[pallet::weight(FunctionOf( - |args: (&Vec,)| args.0.len().saturating_mul(10_000), - ) -] -fn handle_users(origin, calls: Vec) { - // Do something per user -} -``` - -## Post Dispatch Weight Correction - -Depending on the execution logic, a dispatchable function might consume less weight than was prescribed pre-dispatch. To correct weight, the function declares a different return type and returns its actual weight: - -```rust -#[pallet::weight(10_000 + 500_000_000)] -fn expensive_or_cheap(input: u64) -> DispatchResultWithPostInfo { - let was_heavy = do_calculation(input); - - if (was_heavy) { - // None means "no correction" from the weight annotation. - Ok(None.into()) - } else { - // Return the actual weight consumed. - Ok(Some(10_000).into()) - } -} -``` - -## Custom Fees - -You can also define custom fee systems through custom weight functions or inclusion fee functions. - -### Custom Weights - -Instead of using the default weight annotations, you can create a custom weight calculation type using the weights module. The custom weight calculation type must implement the following traits: - -- [`WeighData`](https://crates.parity.io/frame_support/weights/trait.WeighData.html){target=\_blank} to determine the weight of the dispatch. -- [`ClassifyDispatch`](https://crates.parity.io/frame_support/weights/trait.ClassifyDispatch.html){target=\_blank} to determine the class of the dispatch. -- [`PaysFee`](https://crates.parity.io/frame_support/weights/trait.PaysFee.html){target=\_blank} to determine whether the sender of the dispatch pays fees. - -The Polkadot SDK then bundles the output information of the three traits into the [`DispatchInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_support/dispatch/struct.DispatchInfo.html){target=\_blank} struct and provides it by implementing the [`GetDispatchInfo`](https://docs.rs/frame-support/latest/frame_support/dispatch/trait.GetDispatchInfo.html){target=\_blank} for all `Call` variants and opaque extrinsic types. This is used internally by the System and Executive modules. - -`ClassifyDispatch`, `WeighData`, and `PaysFee` are generic over T, which gets resolved into the tuple of all dispatch arguments except for the origin. The following example illustrates a struct that calculates the weight as `m * len(args)`, where `m` is a given multiplier and args is the concatenated tuple of all dispatch arguments. In this example, the dispatch class is `Operational` if the transaction has more than 100 bytes of length in arguments and will pay fees if the encoded length exceeds 10 bytes. - -```rust -struct LenWeight(u32); -impl WeighData for LenWeight { - fn weigh_data(&self, target: T) -> Weight { - let multiplier = self.0; - let encoded_len = target.encode().len() as u32; - multiplier * encoded_len - } -} - -impl ClassifyDispatch for LenWeight { - fn classify_dispatch(&self, target: T) -> DispatchClass { - let encoded_len = target.encode().len() as u32; - if encoded_len > 100 { - DispatchClass::Operational - } else { - DispatchClass::Normal - } - } -} - -impl PaysFee { - fn pays_fee(&self, target: T) -> Pays { - let encoded_len = target.encode().len() as u32; - if encoded_len > 10 { - Pays::Yes - } else { - Pays::No - } - } -} -``` - -A weight calculator function can also be coerced to the final type of the argument instead of defining it as a vague type that can be encoded. The code would roughly look like this: - -```rust -struct CustomWeight; -impl WeighData<(&u32, &u64)> for CustomWeight { - fn weigh_data(&self, target: (&u32, &u64)) -> Weight { - ... - } -} - -// given a dispatch: -#[pallet::call] -impl, I: 'static> Pallet { - #[pallet::weight(CustomWeight)] - fn foo(a: u32, b: u64) { ... } -} -``` - -In this example, the `CustomWeight` can only be used in conjunction with a dispatch with a particular signature `(u32, u64)`, as opposed to `LenWeight`, which can be used with anything because there aren't any assumptions about ``. - -#### Custom Inclusion Fee - -The following example illustrates how to customize your inclusion fee. You must configure the appropriate associated types in the respective module. - -```rust -// Assume this is the balance type -type Balance = u64; - -// Assume we want all the weights to have a `100 + 2 * w` conversion to fees -struct CustomWeightToFee; -impl WeightToFee for CustomWeightToFee { - fn convert(w: Weight) -> Balance { - let a = Balance::from(100); - let b = Balance::from(2); - let w = Balance::from(w); - a + b * w - } -} - -parameter_types! { - pub const ExtrinsicBaseWeight: Weight = 10_000_000; -} - -impl frame_system::Config for Runtime { - type ExtrinsicBaseWeight = ExtrinsicBaseWeight; -} - -parameter_types! { - pub const TransactionByteFee: Balance = 10; -} - -impl transaction_payment::Config { - type TransactionByteFee = TransactionByteFee; - type WeightToFee = CustomWeightToFee; - type FeeMultiplierUpdate = TargetedFeeAdjustment; -} - -struct TargetedFeeAdjustment(sp_std::marker::PhantomData); -impl> WeightToFee for TargetedFeeAdjustment { - fn convert(multiplier: Fixed128) -> Fixed128 { - // Don't change anything. Put any fee update info here. - multiplier - } -} -``` - -## Additional Resources - -You now know the weight system, how it affects transaction fee computation, and how to specify weights for your dispatchable calls. The next step is determining the correct weight for your dispatchable operations. You can use Substrate benchmarking functions and frame-benchmarking calls to test your functions with different parameters and empirically determine the proper weight in their worst-case scenarios. - -- [Benchmark](/parachains/customize-runtime/pallet-development/benchmark-pallet/) -- [`SignedExtension`](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} -- [Custom weights for the Example pallet](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/substrate/frame/examples/basic/src/weights.rs){target=\_blank} -- [Web3 Foundation Research](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank} - - --- Page Title: Troubleshooting Remix IDE @@ -13432,94 +8446,6 @@ Now that you have the foundation for using Web3.py with Polkadot Hub, consider e ---- - -Page Title: XCM Tools - -- Source (raw): https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-xcm-tools.md -- Canonical (HTML): https://docs.polkadot.com/reference/tools/xcm-tools/ -- Summary: Explore essential XCM tools across Polkadot, crafted to enhance cross-chain functionality and integration within the ecosystem. - -# XCM Tools - -## Introduction - -As described in the [Interoperability](/develop/interoperability){target=\_blank} section, XCM (Cross-Consensus Messaging) is a protocol used in the Polkadot and Kusama ecosystems to enable communication and interaction between chains. It facilitates cross-chain communication, allowing assets, data, and messages to flow seamlessly across the ecosystem. - -As XCM is central to enabling communication between blockchains, developers need robust tools to help interact with, build, and test XCM messages. Several XCM tools simplify working with the protocol by providing libraries, frameworks, and utilities that enhance the development process, ensuring that applications built within the Polkadot ecosystem can efficiently use cross-chain functionalities. - -## Popular XCM Tools - -### Moonsong Labs XCM Tools - -[Moonsong Labs XCM Tools](https://github.com/Moonsong-Labs/xcm-tools){target=\_blank} provides a collection of scripts for managing and testing XCM operations between Polkadot SDK-based runtimes. These tools allow performing tasks like asset registration, channel setup, and XCM initialization. Key features include: - -- **Asset registration**: Registers assets, setting units per second (up-front fees), and configuring error (revert) codes. -- **XCM initializer**: Initializes XCM, sets default XCM versions, and configures revert codes for XCM-related precompiles. -- **HRMP manipulator**: Manages HRMP channel actions, including opening, accepting, or closing channels. -- **XCM-Transactor-Info-Setter**: Configures transactor information, including extra weight and fee settings. -- **Decode XCM**: Decodes XCM messages on the relay chain or parachains to help interpret cross-chain communication. - -To get started, clone the repository and install the required dependencies: - -```bash -git clone https://github.com/Moonsong-Labs/xcm-tools && -cd xcm-tools && -yarn install -``` - -For a full overview of each script, visit the [scripts](https://github.com/Moonsong-Labs/xcm-tools/tree/main/scripts){target=\_blank} directory or refer to the [official documentation](https://github.com/Moonsong-Labs/xcm-tools/blob/main/README.md){target=\_blank} on GitHub. - -### ParaSpell - -[ParaSpell](/reference/tools/paraspell/){target=\_blank} is a collection of open-source XCM tools that streamline cross-chain asset transfers and interactions across the Polkadot and Kusama ecosystems. It provides developers with an intuitive interface to build, test, and deploy interoperable dApps, featuring message composition, decoding, and practical utilities for parachain interactions that simplify debugging and cross-chain communication optimization. - -### Astar XCM Tools - -The [Astar parachain](https://github.com/AstarNetwork/Astar/tree/master){target=\_blank} offers a crate with a set of utilities for interacting with the XCM protocol. The [xcm-tools](https://github.com/AstarNetwork/Astar/tree/master/bin/xcm-tools){target=\_blank} crate provides a straightforward method for users to locate a sovereign account or calculate an XC20 asset ID. Some commands included by the xcm-tools crate allow users to perform the following tasks: - -- **Sovereign accounts**: Obtain the sovereign account address for any parachain, either on the Relay Chain or for sibling parachains, using a simple command. -- **XC20 EVM addresses**: Generate XC20-compatible Ethereum addresses for assets by entering the asset ID, making it easy to integrate assets across Ethereum-compatible environments. -- **Remote accounts**: Retrieve remote account addresses needed for multi-location compatibility, using flexible options to specify account types and parachain IDs. - -To start using these tools, clone the [Astar repository](https://github.com/AstarNetwork/Astar){target=\_blank} and compile the xcm-tools package: - -```bash -git clone https://github.com/AstarNetwork/Astar && -cd Astar && -cargo build --release -p xcm-tools -``` - -After compiling, verify the setup with the following command: - -```bash -./target/release/xcm-tools --help -``` -For more details on using Astar xcm-tools, consult the [official documentation](https://docs.astar.network/docs/learn/interoperability/xcm/integration/tools/){target=\_blank}. - -### Chopsticks - -The Chopsticks library provides XCM functionality for testing XCM messages across networks, enabling you to fork multiple parachains along with a relay chain. For further details, see the [Chopsticks documentation](/tutorials/polkadot-sdk/testing/fork-live-chains/){target=\_blank} about XCM. - -### Moonbeam XCM SDK - -The [Moonbeam XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk){target=\_blank} enables developers to easily transfer assets between chains, either between parachains or between a parachain and the relay chain, within the Polkadot/Kusama ecosystem. With the SDK, you don't need to worry about determining the [Multilocation](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#7-universal-consensus-location-identifiers){target=\_blank} of the origin or destination assets or which extrinsics are used on which networks. - -The SDK consists of two main packages: - -- **[XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/sdk){target=\_blank}**: Core SDK for executing XCM transfers between chains in the Polkadot/Kusama ecosystem. -- **[MRL SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/mrl){target=\_blank}**: Extension of the XCM SDK for transferring liquidity into and across the Polkadot ecosystem from other ecosystems like Ethereum. - -Key features include: - -- **Simplified asset transfers**: Abstracts away complex multilocation determinations and extrinsic selection. -- **Cross-ecosystem support**: Enables transfers between Polkadot/Kusama chains and external ecosystems. -- **Developer-friendly API**: Provides intuitive interfaces for cross-chain functionality. -- **Comprehensive documentation**: Includes usage guides and API references for both packages. - -For detailed usage examples and API documentation, visit the [official Moonbeam XCM SDK documentation](https://moonbeam-foundation.github.io/xcm-sdk/latest/){target=\_blank}. - - --- Page Title: Zero to Hero Smart Contract DApp @@ -13764,7 +8690,7 @@ After deployment, you'll need the contract's Application Binary Interface (ABI) Now that you have your contract deployed, you're ready to build the dApp that will interact with it! -## Set Up the dApp Project +## Set Up the DApp Project Navigate to the root of the project, and create a new Next.js project called `dapp`: diff --git a/.ai/pages/chain-interactions-accounts-create-account.md b/.ai/pages/chain-interactions-accounts-create-account.md deleted file mode 100644 index 7794b8456..000000000 --- a/.ai/pages/chain-interactions-accounts-create-account.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -url: https://docs.polkadot.com/chain-interactions/accounts/create-account/ ---- - -TODO diff --git a/.ai/pages/chain-interactions-accounts-query-accounts.md b/.ai/pages/chain-interactions-accounts-query-accounts.md deleted file mode 100644 index 00241f7bb..000000000 --- a/.ai/pages/chain-interactions-accounts-query-accounts.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -url: https://docs.polkadot.com/chain-interactions/accounts/query-accounts/ ---- - -TODO diff --git a/.ai/pages/chain-interactions-query-data-query-rest.md b/.ai/pages/chain-interactions-query-data-query-rest.md deleted file mode 100644 index 1bee0d745..000000000 --- a/.ai/pages/chain-interactions-query-data-query-rest.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -url: https://docs.polkadot.com/chain-interactions/query-data/query-rest/ ---- - -TODO diff --git a/.ai/pages/chain-interactions-query-data-query-sdks.md b/.ai/pages/chain-interactions-query-data-query-sdks.md deleted file mode 100644 index 538d665ff..000000000 --- a/.ai/pages/chain-interactions-query-data-query-sdks.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -url: https://docs.polkadot.com/chain-interactions/query-data/query-sdks/ ---- - -TODO diff --git a/.ai/pages/chain-interactions-query-data-runtime-api-calls.md b/.ai/pages/chain-interactions-query-data-runtime-api-calls.md deleted file mode 100644 index 7c9eeaf30..000000000 --- a/.ai/pages/chain-interactions-query-data-runtime-api-calls.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -url: https://docs.polkadot.com/chain-interactions/query-data/runtime-api-calls/ ---- - -TODO diff --git a/.ai/pages/chain-interactions-send-transactions-calculate-transaction-fees.md b/.ai/pages/chain-interactions-send-transactions-calculate-transaction-fees.md deleted file mode 100644 index 1d2c06486..000000000 --- a/.ai/pages/chain-interactions-send-transactions-calculate-transaction-fees.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -url: https://docs.polkadot.com/chain-interactions/send-transactions/calculate-transaction-fees/ ---- - -TODO diff --git a/.ai/pages/chain-interactions-send-transactions-interoperability-debug-and-preview-xcms.md b/.ai/pages/chain-interactions-send-transactions-interoperability-debug-and-preview-xcms.md deleted file mode 100644 index ba718c4c6..000000000 --- a/.ai/pages/chain-interactions-send-transactions-interoperability-debug-and-preview-xcms.md +++ /dev/null @@ -1,512 +0,0 @@ ---- -title: Replay and Dry Run XCMs -description: Replay and dry-run XCMs using Chopsticks with full logging enabled. Diagnose issues, trace message flow, and debug complex cross-chain interactions. -url: https://docs.polkadot.com/chain-interactions/send-transactions/interoperability/debug-and-preview-xcms/ ---- - -# Replay and Dry Run XCMs Using Chopsticks - -## Introduction - -In this tutorial, you'll learn how to replay and dry-run XCMs using [Chopsticks](/parachains/testing/fork-a-parachain/){target=\_blank}, a powerful tool for forking live Polkadot SDK-based chains in your local environment. These techniques are essential for: - -- Debugging cross-chain message failures. -- Tracing execution across relay chains and parachains. -- Analyzing weight usage, error types, and message flow. -- Safely simulating XCMs without committing state changes. - -By the end of this guide, you'll be able to set up a local fork, capture and replay real XCMs, and use dry-run features to diagnose and resolve complex cross-chain issues. - -## Prerequisites - -Before you begin, make sure you have: - -- [Chopsticks](/parachains/testing/fork-a-parachain/){target=\_blank} installed (`npm i -g @acala-network/chopsticks`). -- Access to the endpoint or genesis file of the parachain you want to fork. -- The block number or hash where the XCM was sent. -- (Optional) A Chopsticks config file for repeated setups. - -If you haven't forked a chain before, see the [Fork a Chain with Chopsticks guide](/tutorials/polkadot-sdk/testing/fork-live-chains/){target=\_blank} or [Fork a Network Locally using Chopsticks](https://wiki.polkadot.com/learn/learn-guides-test-opengov-proposals/#fork-a-network-locally-using-chopsticks){target=\_blank} for step-by-step instructions. - -## Set Up Your Project - -Let's start by creating a dedicated workspace for your XCM replay and dry-run experiments. - -1. Create a new directory and navigate into it: - - ```bash - mkdir -p replay-xcm-tests - cd replay-xcm-tests - ``` - -2. Initialize a new Node project: - - ```bash - npm init -y - ``` - -3. Install Chopsticks globally (recommended to avoid conflicts with local installs): - - ```bash - npm install -g @acala-network/chopsticks@latest - ``` - -4. Install TypeScript and related tooling for local development: - - ```bash - npm install --save-dev typescript @types/node tsx - ``` - -5. Install the required Polkadot packages: - - ```bash - npm install polkadot-api @polkadot-labs/hdkd @polkadot-labs/hdkd-helpers - ``` - -6. Initialize the TypeScript config: - - ```bash - npx tsc --init - ``` - -## Capture the XCM to Replay - -To replay a specific XCM, identify: - -- The source and destination chains involved. -- The block number or height where the XCM was sent. -- Optionally, the call payload (if you plan to simulate it manually via development commands). - -You can use [Polkadot.js Apps](/tutorials/polkadot-sdk/testing/fork-live-chains/#use-polkadotjs-apps){target=\_blank}, [papi console](https://dev.papi.how/){target=\_blank}, or indexers such as [Subscan](https://polkadot.subscan.io/xcm_dashboard){target=\_blank} to locate and inspect the original XCM execution. - -## Fork the Relevant Chains - -Use Chopsticks to [fork the required chains](/tutorials/polkadot-sdk/testing/fork-live-chains/#xcm-testing){target=\_blank} at the appropriate block heights. - -### Set the Block Numbers - -Create/edit a `.env` file with the block heights for each chain. These should be just before the XCM is sent to allow a full replay: - -```text title=".env" -POLKADOT_BLOCK_NUMBER=26481107 -POLKADOT_ASSET_HUB_BLOCK_NUMBER=9079591 -ACALA_BLOCK_NUMBER=8826385 -``` - -### Enable Logging and Wasm Override - -Full execution logs only work if the runtime was compiled with logging enabled. Most live chains are built using the `production` profile, which disables logs. To enable logging, you'll need to override the Wasm with a locally built `release` or `debug` version. The `release` profile is faster to load in Chopsticks. - -1. Clone the `polkadot-fellows/runtimes` repository: - - ```bash - git clone git@github.com:polkadot-fellows/runtimes.git - ``` - -2. Build the Polkadot Asset Hub runtime: - - ```bash - cd runtimes - # Build with the `debug` profile (default): - # cargo build -p asset-hub-polkadot-runtime - - # Build with the `release` profile (faster to load in Chopsticks) - cargo build --release -p asset-hub-polkadot-runtime - ``` - -3. Copy the compiled Wasm to your working directory: - - ```bash - # Assuming you're still in the `runtimes` directory - mkdir -p ../wasms # or your /wasms path - - # Copy the compiled Wasm to your working directory: - - # If built with the `debug` profile: - # cp target/debug/wbuild/asset-hub-polkadot-runtime/asset_hub_polkadot_runtime.wasm ../wasms - - # If built with the `release` profile: - cp target/release/wbuild/asset-hub-polkadot-runtime/asset_hub_polkadot_runtime.compact.compressed.wasm ../wasms - ``` - -4. Download and modify a config file: - - ```bash - # Still in the `runtimes` directory - cd .. # Return to your replay-xcm-tests root - mkdir -p configs - wget https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/polkadot-asset-hub.yml -O configs/polkadot-asset-hub-override.yaml - ``` - -5. Edit `configs/polkadot-asset-hub-override.yaml` to include: - - {% raw %} - ```yaml title="configs/polkadot-asset-hub-override.yaml" - ... - runtime-log-level: 5 - # wasm-override: wasms/asset_hub_polkadot_runtime.wasm # Uncomment if using the `debug` build - wasm-override: wasms/asset_hub_polkadot_runtime.compact.compressed.wasm # Use this if you built with `release` - ... - ``` - {% endraw %} - -6. Start the forked chains using your custom config: - - ```bash - npx @acala-network/chopsticks xcm \ - -r polkadot \ - -p configs/polkadot-asset-hub-override.yaml \ - -p acala - ``` - - This command starts the relay chain and parachains locally, with full runtime execution logs enabled. Once the chains are running, you should see output indicating that the following RPC endpoints are available: - - - Polkadot Asset Hub RPC on `http://localhost:8000` - - Acala RPC on `http://localhost:8001` - - Polkadot RPC on `http://localhost:8002` - - You'll also see runtime logs such as: - -
- npx @acala-network/chopsticks xcm \ -r polkadot \ -p configs/polkadot-asset-hub-override.yaml \ -p acala - [09:29:14.988] INFO: Polkadot Asset Hub RPC listening on http://[::]:8000 and ws://[::]:8000 - [09:29:14.988] INFO: Loading config file https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/acala.yml - [09:29:15.984] INFO: Acala RPC listening on http://[::]:8001 and ws://[::]:8001 - [09:29:15.990] INFO (xcm): Connected parachains [1000,2000] - [09:29:15.990] INFO: Loading config file https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/polkadot.yml - [09:29:16.927] INFO: Polkadot RPC listening on http://[::]:8002 and ws://[::]:8002 - [09:29:16.984] INFO (xcm): Connected relaychain 'Polkadot' with parachain 'Polkadot Asset Hub' - [09:29:17.028] INFO (xcm): Connected relaychain 'Polkadot' with parachain 'Acala' -
- -## Identify and Extract the XCM - -To replay an XCM, you'll first need to identify the exact extrinsic that triggered it. In this example, we'll use block 9079592 on the Polkadot Asset Hub. - -1. Find and open the block on Subscan to inspect its extrinsics and events. In this case, the block is [9079592](https://assethub-polkadot.subscan.io/block/9079592){target=\_blank}. - -2. Copy the black hash. Look for the block hash at the top of the page. For block 9079592, the hash is: - - ```bash title="Block Hash" - 0xeb5a5737d47367dc1c02b978232283cdb096eb7e51d2eb22366a106a011347f6 - ``` - -3. Explore and view the block in [Polkadot.Js Apps](https://polkadot.js.org/apps){target=\_blank} using this direct link: [Block Hash Explorer](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fpolkadot-asset-hub-rpc.polkadot.io#/explorer/query/0xeb5a5737d47367dc1c02b978232283cdb096eb7e51d2eb22366a106a011347f6){target=\_blank}. - -4. Locate and decode the XCM extrinsic. Once you've found the extrinsic (e.g., 9079592-2), extract and decode its call data. For example, the call data is: - - ```bash title="Call Data" - 0xad028400fc39fcf04a8071b7409823b7c82427ce67910c6ed80aa0e5093aff234624c820016a30461702adc48213e5c9ee4d15c5a481c578cb5cbc935f0bd11fe8aee489082a745ffbbe94282f91b67daa6cb44920d77c30849c1d25f5f6c3e59015a3e383440055040000011f0803010100411f0300010100fc39fcf04a8071b7409823b7c82427ce67910c6ed80aa0e5093aff234624c8200304000002043205011f0092e81d790000000000 - ``` - -5. From the decoded view, copy the **hex-encoded call** (e.g. `0x1f08...0000`). You'll pass this into `api.txFromCallData(...)` to replay the XCM locally. - -## Replay the XCM - -Once your project is set up, you're ready to replay the XCM locally. - -This is useful for: - -- Diagnosing execution failures or weight limits. -- Inspecting all emitted events. -- Verifying behaviour before submitting a real transaction. - -### Add the Asset Hub Descriptor - -This will let you use type-safe APIs with PAPI: - -```bash -npx papi add assetHub -w ws://localhost:8000 -``` - -The script assumes the Polkadot Asset Hub is served on `ws://localhost:8000`. If you're using a different port or config, update the WebSocket endpoint in the script or descriptor. You can confirm the port by checking your terminal logs or by seeing [Launch Chopsticks](#launch-chopsticks). - -### Create a Replay Script - -Create a file named `replay-xcm.ts` and copy the following code into it: - -```ts -import { Binary, createClient, Transaction } from 'polkadot-api'; -import { withPolkadotSdkCompat } from 'polkadot-api/polkadot-sdk-compat'; -import { getPolkadotSigner } from 'polkadot-api/signer'; -import { getWsProvider } from 'polkadot-api/ws-provider/web'; -import { assetHub } from '@polkadot-api/descriptors'; -import { sr25519CreateDerive } from '@polkadot-labs/hdkd'; -import { - DEV_PHRASE, - entropyToMiniSecret, - mnemonicToEntropy, -} from '@polkadot-labs/hdkd-helpers'; - -const toHuman = (_key: any, value: any) => { - if (typeof value === 'bigint') { - return Number(value); - } - - if (value && typeof value === 'object' && typeof value.asHex === 'function') { - return value.asHex(); - } - - return value; -}; - -function getSigner() { - const entropy = mnemonicToEntropy(DEV_PHRASE); - const miniSecret = entropyToMiniSecret(entropy); - const derive = sr25519CreateDerive(miniSecret); - const alice = derive('//Alice'); - - return getPolkadotSigner(alice.publicKey, 'Sr25519', alice.sign); -} - -async function main() { - const provider = withPolkadotSdkCompat(getWsProvider('ws://localhost:8000')); - const client = createClient(provider); - const api = client.getTypedApi(assetHub); - const aliceSigner = getSigner(); - - const callData = Binary.fromHex( - '0x1f0803010100411f0300010100fc39fcf04a8071b7409823b7c82427ce67910c6ed80aa0e5093aff234624c8200304000002043205011f0092e81d790000000000', - ); - const tx: Transaction = - await api.txFromCallData(callData); - console.log('👀 Executing XCM:', JSON.stringify(tx.decodedCall, toHuman, 2)); - - await new Promise((resolve) => { - const subscription = tx.signSubmitAndWatch(aliceSigner).subscribe((ev) => { - if ( - ev.type === 'finalized' || - (ev.type === 'txBestBlocksState' && ev.found) - ) { - console.log( - `📦 Included in block #${ev.block.number}: ${ev.block.hash}`, - ); - - if (!ev.ok) { - const dispatchError = ev.dispatchError; - if (dispatchError.type === 'Module') { - const modErr: any = dispatchError.value; - console.error( - `❌ Dispatch error in module: ${modErr.type} → ${modErr.value?.type}`, - ); - } else { - console.error( - '❌ Dispatch error:', - JSON.stringify(dispatchError, toHuman, 2), - ); - } - } - - for (const event of ev.events) { - console.log( - '📣 Event:', - event.type, - JSON.stringify(event.value, toHuman, 2), - ); - } - - console.log('✅ Process completed, exiting...'); - subscription.unsubscribe(); - resolve(); - } - }); - }); - - client.destroy(); -} - -main().catch(console.error); - -``` - -### Execute the Replay Script - -Ensure Chopsticks is running and serving a chain that includes `pallet-xcm`, such as a Polkadot Asset Hub fork. Then run: - -```bash -npx tsx replay-xcm.ts -``` - -### Expected Output - -If everything is working, you'll see logs like: - -
- npx tsx replay-xcm.ts -
-executing xcm: {
-  "type": "polkadotxcm",
-  "value": {
-    "type": "limited_reserve_transfer_assets",
-    "value": {
-      "dest": { "parents": 0, "interior": { "X1": [{ "Parachain": 2006 }] } },
-      "beneficiary": { "parents": 0, "interior": { "X1": [{ "AccountId32": { "network": null, "id": "0x..." } }] } },
-      "assets": [{ "id": { "Concrete": { "parents": 0, "interior": "Here" } }, "fun": { "Fungible": 120000000000 } }],
-      "fee_asset_item": 0,
-      "weight_limit": { "type": "Unlimited" }
-    }
-  }
-}
-  
- 📦 Included in block #9079592: 0x227a11c64f6051ba2e090a13abd17e5f7581640a80f6c03fc2d43fac66ab7949 - 📣 Event: Balances { "type": "Upgraded", "value": { ... } } - 📣 Event: Balances { "type": "Withdraw", "value": { ... } } - 📣 Event: Assets { "type": "Transferred", "value": { ... } } - 📣 Event: PolkadotXcm { "type": "Attempted", "value": { ... } } - 📣 Event: Balances { "type": "Burned", "value": { ... } } - 📣 Event: Balances { "type": "Minted", "value": { ... } } - 📣 Event: PolkadotXcm { "type": "FeesPaid", "value": { ... } } - 📣 Event: XcmpQueue { "type": "XcmpMessageSent", "value": { ... } } - 📣 Event: PolkadotXcm { "type": "Sent", "value": { ... } } - 📣 Event: Balances { "type": "Deposit", "value": { ... } } - 📣 Event: TransactionPayment { "type": "TransactionFeePaid", "value": { ... } } - 📣 Event: System { "type": "ExtrinsicSuccess", "value": { ... } } - ✅ Process completed, exiting... -
- -## Dry Run the XCM - -To simulate the XCM without actually sending it, you can use the `dry_run_call` method. This lets you check whether the XCM would succeed without modifying any state. - -### Create a Dry Run Script - -Assuming you've the `tx` transaction from the previous step, you can create a new script, `dry-run-call.ts`, then paste in the following code: - -```ts -import { Binary, createClient, Enum } from 'polkadot-api'; -import { withPolkadotSdkCompat } from 'polkadot-api/polkadot-sdk-compat'; -import { getWsProvider } from 'polkadot-api/ws-provider/web'; -import { assetHub } from '@polkadot-api/descriptors'; -import { sr25519CreateDerive } from '@polkadot-labs/hdkd'; -import { - DEV_PHRASE, - entropyToMiniSecret, - mnemonicToEntropy, - ss58Address, -} from '@polkadot-labs/hdkd-helpers'; - -const XCM_VERSION = 5; - -async function main() { - const provider = withPolkadotSdkCompat(getWsProvider('ws://localhost:8000')); - const client = createClient(provider); - const api = client.getTypedApi(assetHub); - - const entropy = mnemonicToEntropy(DEV_PHRASE); - const miniSecret = entropyToMiniSecret(entropy); - const derive = sr25519CreateDerive(miniSecret); - const alice = derive('//Alice'); - const aliceAddress = ss58Address(alice.publicKey); - - const callData = Binary.fromHex( - '0x1f0803010100411f0300010100fc39fcf04a8071b7409823b7c82427ce67910c6ed80aa0e5093aff234624c8200304000002043205011f0092e81d790000000000', - ); - const tx: any = await api.txFromCallData(callData); - const origin = Enum('system', Enum('Signed', aliceAddress)); - const dryRunResult: any = await api.apis.DryRunApi.dry_run_call( - origin, - tx.decodedCall, - XCM_VERSION, - ); - console.dir(dryRunResult.value, { depth: null }); - - client.destroy(); -} - -main().catch(console.error); - -``` - -Ensure your local Chopsticks fork is running and the ports match those used in the script. - -### Execute the Dry Run Script - -```bash -npx tsx dry-run-call.ts -``` - -If successful, the dry run confirms that the XCM would execute correctly: - -
- npx tsx dry-run-call.ts -
-execution_result: {
-  "success": true,
-  "value": {
-    "post_info": { "actual_weight": 123456, "pays_fee": "Yes" },
-    "result": "Ok"
-  }
-}
-emitted_events: [ { "section": "Balances", "method": "Transfer", "data": { "from": "0x...", "to": "0x...", "amount": 1000000000 } } ]
-local_xcm: { "type": "SomeType", "value": { ... } }
-forwarded_xcms: []
-  
- ✅ Dry run succeeded - ✅ Process completed, exiting... -
- -If it fails, you'll receive detailed error information: - -
- npx tsx dry-run-call.ts -
-execution_result: {
-  "success": false,
-  "value": {
-    "post_info": { "actual_weight": 123456, "pays_fee": "Yes" },
-    "error": {
-      "type": "Module",
-      "value": {
-        "type": "PolkadotXcm",
-        "value": { "type": "LocalExecutionIncomplete", "value": null }
-      }
-    }
-  }
-}
-  
- ❌ Dry run failed: LocalExecutionIncomplete - ✅ Process completed, exiting... -
- -For more information, see: - -- [Dry Run Call](/develop/interoperability/xcm-runtime-apis/#dry-run-call){target=\_blank} to simulate a full extrinsic -- [Dry Run XCM](/develop/interoperability/xcm-runtime-apis/#dry-run-xcm){target=\_blank} to simulate a raw XCM - -## Review and Debug - -Replaying XCMs with full logging provides fine-grained control and visibility into cross-chain message behaviour. Chopsticks makes this possible in a safe, local environment – empowering developers to: - -- Debug complex message flows. -- Identify root causes of XCM failures. -- Improve observability for future integrations. - -## Where to Go Next - -
- -- External __Chopsticks Repository__ - - --- - - View the official Chopsticks GitHub repository. - - [:octicons-arrow-right-24: Get Started](https://github.com/AcalaNetwork/chopsticks/) - -- Guide __Polkadot XCM Docs__ - - --- - - Learn how to use XCM effectively. - - [:octicons-arrow-right-24: Get Started](/parachains/interoperability/get-started/) - -- Tutorial __XCM Runtime APIs__ - - --- - - Learn how to use XCM Runtime APIs. - - [:octicons-arrow-right-24: Get Started](/develop/interoperability/xcm-runtime-apis/) - -
diff --git a/.ai/pages/chain-interactions-send-transactions-interoperability-estimate-xcm-fees.md b/.ai/pages/chain-interactions-send-transactions-interoperability-estimate-xcm-fees.md deleted file mode 100644 index af70b2fb4..000000000 --- a/.ai/pages/chain-interactions-send-transactions-interoperability-estimate-xcm-fees.md +++ /dev/null @@ -1,1100 +0,0 @@ ---- -title: XCM Fee Estimation -description: This tutorial demonstrates how to estimate the fees for teleporting assets from the Paseo Asset Hub parachain to the Paseo Bridge Hub chain. -url: https://docs.polkadot.com/chain-interactions/send-transactions/interoperability/estimate-xcm-fees/ ---- - -# XCM Fee Estimation - -## Introduction - -When sending cross-chain messages, ensure that the transaction will be successful not only in the local chain but also in the destination chain and any intermediate chains. - -Sending cross-chain messages requires estimating the fees for the operation. - -This tutorial will demonstrate how to dry-run and estimate the fees for teleporting assets from the Paseo Asset Hub parachain to the Paseo Bridge Hub chain. - -## Fee Mechanism - -There are three types of fees that can be charged when sending a cross-chain message: - -- **Local execution fees**: Fees charged in the local chain for executing the message. -- **Delivery fees**: Fees charged for delivering the message to the destination chain. -- **Remote execution fees**: Fees charged in the destination chain for executing the message. - -If there are multiple intermediate chains, delivery fees and remote execution fees will be charged for each one. - -In this example, you will estimate the fees for teleporting assets from the Paseo Asset Hub parachain to the Paseo Bridge Hub chain. The fee structure will be as follows: - -```mermaid -flowchart LR - AssetHub[Paseo Asset Hub] -->|Delivery Fees| BridgeHub[Paseo Bridge Hub] - AssetHub -->|
Local
Execution
Fees| AssetHub - BridgeHub -->|
Remote
Execution
Fees| BridgeHub -``` - -The overall fees are `local_execution_fees` + `delivery_fees` + `remote_execution_fees`. - -## Environment Setup - -First, you need to set up your environment: - -1. Create a new directory and initialize the project: - - ```bash - mkdir xcm-fee-estimation && \ - cd xcm-fee-estimation - ``` - -2. Initialize the project: - - ```bash - npm init -y - ``` - -3. Install dev dependencies: - - ```bash - npm install --save-dev @types/node@^22.12.0 ts-node@^10.9.2 typescript@^5.7.3 - ``` - -4. Install dependencies: - - ```bash - npm install --save @polkadot-labs/hdkd@^0.0.13 @polkadot-labs/hdkd-helpers@^0.0.13 polkadot-api@1.9.5 - ``` - -5. Create TypeScript configuration: - - ```bash - npx tsc --init - ``` - -6. Generate the types for the Polkadot API for Paseo Bridge Hub and Paseo Asset Hub: - - ```bash - npx papi add paseoAssetHub -n paseo_asset_hub && \ - npx papi add paseoBridgeHub -w wss://bridge-hub-paseo.dotters.network - ``` - -7. Create a new file called `teleport-ah-to-bridge-hub.ts`: - - ```bash - touch teleport-ah-to-bridge-hub.ts - ``` - -8. Import the necessary modules. Add the following code to the `teleport-ah-to-bridge-hub.ts` file: - - ```typescript title="teleport-ah-to-bridge-hub.ts" - import { paseoAssetHub, paseoBridgeHub } from '@polkadot-api/descriptors'; - import { createClient, FixedSizeBinary, Enum } from 'polkadot-api'; - import { getWsProvider } from 'polkadot-api/ws-provider/node'; - import { withPolkadotSdkCompat } from 'polkadot-api/polkadot-sdk-compat'; - import { - XcmVersionedLocation, - XcmVersionedAssetId, - XcmV3Junctions, - XcmV3MultiassetFungibility, - XcmVersionedXcm, - XcmV5Instruction, - XcmV5Junctions, - XcmV5Junction, - XcmV5AssetFilter, - XcmV5WildAsset, - } from '@polkadot-api/descriptors'; - ``` - -9. Define constants and a `main` function where you will implement all the logic: - - ```typescript title="teleport-ah-to-bridge-hub.ts" - // 1 PAS = 10^10 units - const PAS_UNITS = 10_000_000_000n; // 1 PAS - const PAS_CENTS = 100_000_000n; // 0.01 PAS - - // Paseo Asset Hub constants - const PASEO_ASSET_HUB_RPC_ENDPOINT = 'ws://localhost:8001'; - const ASSET_HUB_ACCOUNT = '15oF4uVJwmo4TdGW7VfQxNLavjCXviqxT9S1MgbjMNHr6Sp5'; // Alice (Paseo Asset Hub) - - // Bridge Hub destination - const BRIDGE_HUB_RPC_ENDPOINT = 'ws://localhost:8000'; - const BRIDGE_HUB_PARA_ID = 1002; - const BRIDGE_HUB_BENEFICIARY = - async function main() { - // Code will go here - } - ``` - -All the following code explained in the subsequent sections must be added inside the `main` function. - -## Client and API Setup - -Now you are ready to start implementing the logic for the fee estimation for the teleport you want to perform. In this step, you will create the client for the Paseo Asset Hub parachain and generate the typed API to interact with the chain. Follow the steps below: - -Create the API client. You will need to create a client for the Paseo Asset Hub parachain: - -```typescript title="teleport-ah-to-bridge-hub.ts" - // Connect to the Asset Hub parachain - const assetHubClient = createClient( - withPolkadotSdkCompat(getWsProvider(PASEO_ASSET_HUB_RPC_ENDPOINT)), - ); - - // Get the typed API for Asset Hub - const assetHubApi = assetHubClient.getTypedApi(paseoAssetHub); -``` - -Ensure that you replace the endpoint URLs with the actual WebSocket endpoints. This example uses local chopsticks endpoints, but you can use public endpoints or run local nodes. - -## Create the XCM Message - -Now, you can construct a proper XCM message using the new XCM V5 instructions for teleporting from Asset Hub to the Bridge Hub Chain: - -```typescript title="teleport-ah-to-bridge-hub.ts" -function createTeleportXcmToBridgeHub(paraId: number) { - return XcmVersionedXcm.V5([ - // Withdraw PAS from Asset Hub (PAS on parachains is parents:1, interior: Here) - XcmV5Instruction.WithdrawAsset([ - { - id: { parents: 1, interior: XcmV5Junctions.Here() }, - fun: XcmV3MultiassetFungibility.Fungible(1n * PAS_UNITS), // 1 PAS - }, - ]), - // Pay local fees on Asset Hub in PAS - XcmV5Instruction.PayFees({ - asset: { - id: { parents: 1, interior: XcmV5Junctions.Here() }, - fun: XcmV3MultiassetFungibility.Fungible(10n * PAS_CENTS), // 0.01 PAS - }, - }), - // Send to Bridge Hub parachain (parents:1, interior: X1(Parachain(paraId))) - XcmV5Instruction.InitiateTransfer({ - destination: { - parents: 1, - interior: XcmV5Junctions.X1(XcmV5Junction.Parachain(paraId)), - }, - remote_fees: Enum( - 'Teleport', - XcmV5AssetFilter.Definite([ - { - id: { parents: 1, interior: XcmV5Junctions.Here() }, - fun: XcmV3MultiassetFungibility.Fungible(10n * PAS_CENTS), // 0.01 PAS - }, - ]), - ), - preserve_origin: false, - remote_xcm: [ - XcmV5Instruction.DepositAsset({ - assets: XcmV5AssetFilter.Wild(XcmV5WildAsset.AllCounted(1)), - beneficiary: { - parents: 0, - interior: XcmV5Junctions.X1( - XcmV5Junction.AccountId32({ - network: undefined, - id: FixedSizeBinary.fromAccountId32(BRIDGE_HUB_BENEFICIARY), - }), - ), - }, - }), - ], - assets: [ - Enum('Teleport', XcmV5AssetFilter.Wild(XcmV5WildAsset.AllCounted(1))), // Send everything. - ], - }), - ]); -} -``` - -## Fee Estimation Function - -Below is a four-step breakdown of the logic needed to estimate the fees for the teleport. - -First, you need to create the function that will estimate the fees for the teleport: - -```typescript title="teleport-ah-to-bridge-hub.ts" -async function estimateXcmFeesFromAssetHubToBridgeHub( - xcm: any, - assetHubApi: any, -) { - // Code will go here -} -``` - -1. **Local execution fees on Asset Hub**: Compute the XCM weight locally, then convert that weight to PAS using Asset Hub's view of PAS (`parents: 1, interior: Here`). Add the code to the function: - - ```typescript title="teleport-ah-to-bridge-hub.ts" - console.log('=== Fee Estimation Process (Asset Hub → Bridge Hub) ==='); - - // 1. LOCAL EXECUTION FEES on Asset Hub - console.log('1. Calculating local execution fees on Asset Hub...'); - let localExecutionFees = 0n; - - const weightResult = - await assetHubApi.apis.XcmPaymentApi.query_xcm_weight(xcm); - if (weightResult.success) { - console.log('✓ XCM weight (Asset Hub):', weightResult.value); - - // Convert weight to PAS fees from Asset Hub's perspective (parents:1, Here) - const executionFeesResult = - await assetHubApi.apis.XcmPaymentApi.query_weight_to_asset_fee( - weightResult.value, - XcmVersionedAssetId.V4({ - parents: 1, - interior: XcmV3Junctions.Here(), - }), - ); - - if (executionFeesResult.success) { - localExecutionFees = executionFeesResult.value; - console.log( - '✓ Local execution fees (Asset Hub):', - localExecutionFees.toString(), - 'PAS units', - ); - } else { - console.log( - '✗ Failed to calculate local execution fees:', - executionFeesResult.value, - ); - } - } else { - console.log( - '✗ Failed to query XCM weight on Asset Hub:', - weightResult.value, - ); - } - ``` - -2. **Dry-run and delivery fees to Bridge Hub**: Dry-run the XCM on Asset Hub to capture forwarded messages, locate the one targeting Bridge Hub (`parents: 1, interior: Here`), and ask for delivery fees. Add the code to the function: - - ```typescript title="teleport-ah-to-bridge-hub.ts" - // 2. DELIVERY FEES + REMOTE EXECUTION FEES - console.log('\n2. Calculating delivery and remote execution fees...'); - let deliveryFees = 0n; - let remoteExecutionFees = 0n; // Skipped (Bridge Hub descriptor not available) - - // Origin from Asset Hub perspective - const origin = XcmVersionedLocation.V5({ - parents: 0, - interior: XcmV5Junctions.X1( - XcmV5Junction.AccountId32({ - id: FixedSizeBinary.fromAccountId32(ASSET_HUB_ACCOUNT), - network: undefined, - }), - ), - }); - - // Dry run the XCM locally on Asset Hub - const dryRunResult = await assetHubApi.apis.DryRunApi.dry_run_xcm( - origin, - xcm, - ); - - if ( - dryRunResult.success && - dryRunResult.value.execution_result.type === 'Complete' - ) { - console.log('✓ Local dry run on Asset Hub successful'); - - const { forwarded_xcms: forwardedXcms } = dryRunResult.value; - - // Find the XCM message sent to Bridge Hub (parents:1, interior: X1(Parachain(1002))) - const bridgeHubXcmEntry = forwardedXcms.find( - ([location, _]: [any, any]) => - (location.type === 'V4' || location.type === 'V5') && - location.value.parents === 1 && - location.value.interior?.type === 'X1' && - location.value.interior.value?.type === 'Parachain' && - location.value.interior.value.value === BRIDGE_HUB_PARA_ID, - ); - - if (bridgeHubXcmEntry) { - const [destination, messages] = bridgeHubXcmEntry; - const remoteXcm = messages[0]; - - console.log('✓ Found XCM message to Bridge Hub'); - - // Calculate delivery fees from Asset Hub to Bridge Hub - const deliveryFeesResult = - await assetHubApi.apis.XcmPaymentApi.query_delivery_fees( - destination, - remoteXcm, - ); - - if ( - deliveryFeesResult.success && - deliveryFeesResult.value.type === 'V5' && - deliveryFeesResult.value.value[0]?.fun?.type === 'Fungible' - ) { - deliveryFees = deliveryFeesResult.value.value[0].fun.value; - console.log('✓ Delivery fees:', deliveryFees.toString(), 'PAS units'); - } else { - console.log('✗ Failed to calculate delivery fees:', deliveryFeesResult); - } - ``` - -3. **Remote execution fees on Bridge Hub**: Connect to Bridge Hub, recompute the forwarded XCM weight there, and convert weight to PAS (`parents: 0, interior: Here`). Add the code to the function: - - ```typescript title="teleport-ah-to-bridge-hub.ts" - // 3. REMOTE EXECUTION FEES on Bridge Hub - console.log('\n3. Calculating remote execution fees on Bridge Hub'); - try { - const bridgeHubClient = createClient( - withPolkadotSdkCompat(getWsProvider(BRIDGE_HUB_RPC_ENDPOINT)), - ); - const bridgeHubApi = bridgeHubClient.getTypedApi(paseoBridgeHub); - const remoteWeightResult = - await bridgeHubApi.apis.XcmPaymentApi.query_xcm_weight(remoteXcm); - const remoteFeesResult = - await bridgeHubApi.apis.XcmPaymentApi.query_weight_to_asset_fee( - remoteWeightResult.value as { - ref_time: bigint; - proof_size: bigint; - }, - XcmVersionedAssetId.V4({ - parents: 1, - interior: XcmV3Junctions.Here(), - }), - ); - bridgeHubClient.destroy(); - remoteExecutionFees = remoteFeesResult.value as bigint; - console.log( - '✓ Remote execution fees:', - remoteExecutionFees.toString(), - 'PAS units', - ); - } catch (error) { - console.error( - 'Error calculating remote execution fees on Bridge Hub:', - error, - ); - } - } else { - console.log('✗ No XCM message found to Bridge Hub'); - } - } else { - console.log('✗ Local dry run failed on Asset Hub:', dryRunResult.value); - } - ``` - -4. **Sum and return totals**: Aggregate all parts, print a short summary, and return a structured result. Add the code to the function: - - ```typescript title="teleport-ah-to-bridge-hub.ts" - // 4. TOTAL FEES - const totalFees = localExecutionFees + deliveryFees + remoteExecutionFees; - - console.log('\n=== Fee Summary (Asset Hub → Bridge Hub) ==='); - console.log( - 'Local execution fees:', - localExecutionFees.toString(), - 'PAS units', - ); - console.log('Delivery fees:', deliveryFees.toString(), 'PAS units'); - console.log( - 'Remote execution fees:', - remoteExecutionFees.toString(), - 'PAS units', - ); - console.log('TOTAL FEES:', totalFees.toString(), 'PAS units'); - console.log( - 'TOTAL FEES:', - (Number(totalFees) / Number(PAS_UNITS)).toFixed(4), - 'PAS', - ); - - return { - localExecutionFees, - deliveryFees, - remoteExecutionFees, - totalFees, - }; - } - ``` - -The full code for the fee estimation function is the following: - -??? code "Fee Estimation Function" - - ```typescript title="teleport-ah-to-bridge-hub.ts" - async function estimateXcmFeesFromAssetHubToBridgeHub( - xcm: any, - assetHubApi: any, - ) { - console.log('=== Fee Estimation Process (Asset Hub → Bridge Hub) ==='); - - // 1. LOCAL EXECUTION FEES on Asset Hub - console.log('1. Calculating local execution fees on Asset Hub...'); - let localExecutionFees = 0n; - - const weightResult = - await assetHubApi.apis.XcmPaymentApi.query_xcm_weight(xcm); - if (weightResult.success) { - console.log('✓ XCM weight (Asset Hub):', weightResult.value); - - // Convert weight to PAS fees from Asset Hub's perspective (parents:1, Here) - const executionFeesResult = - await assetHubApi.apis.XcmPaymentApi.query_weight_to_asset_fee( - weightResult.value, - XcmVersionedAssetId.V4({ - parents: 1, - interior: XcmV3Junctions.Here(), - }), - ); - - if (executionFeesResult.success) { - localExecutionFees = executionFeesResult.value; - console.log( - '✓ Local execution fees (Asset Hub):', - localExecutionFees.toString(), - 'PAS units', - ); - } else { - console.log( - '✗ Failed to calculate local execution fees:', - executionFeesResult.value, - ); - } - } else { - console.log( - '✗ Failed to query XCM weight on Asset Hub:', - weightResult.value, - ); - } - - // 2. DELIVERY FEES + REMOTE EXECUTION FEES - console.log('\n2. Calculating delivery and remote execution fees...'); - let deliveryFees = 0n; - let remoteExecutionFees = 0n; // Skipped (Bridge Hub descriptor not available) - - // Origin from Asset Hub perspective - const origin = XcmVersionedLocation.V5({ - parents: 0, - interior: XcmV5Junctions.X1( - XcmV5Junction.AccountId32({ - id: FixedSizeBinary.fromAccountId32(ASSET_HUB_ACCOUNT), - network: undefined, - }), - ), - }); - - // Dry run the XCM locally on Asset Hub - const dryRunResult = await assetHubApi.apis.DryRunApi.dry_run_xcm( - origin, - xcm, - ); - - if ( - dryRunResult.success && - dryRunResult.value.execution_result.type === 'Complete' - ) { - console.log('✓ Local dry run on Asset Hub successful'); - - const { forwarded_xcms: forwardedXcms } = dryRunResult.value; - - // Find the XCM message sent to Bridge Hub (parents:1, interior: X1(Parachain(1002))) - const bridgeHubXcmEntry = forwardedXcms.find( - ([location, _]: [any, any]) => - (location.type === 'V4' || location.type === 'V5') && - location.value.parents === 1 && - location.value.interior?.type === 'X1' && - location.value.interior.value?.type === 'Parachain' && - location.value.interior.value.value === BRIDGE_HUB_PARA_ID, - ); - - if (bridgeHubXcmEntry) { - const [destination, messages] = bridgeHubXcmEntry; - const remoteXcm = messages[0]; - - console.log('✓ Found XCM message to Bridge Hub'); - - // Calculate delivery fees from Asset Hub to Bridge Hub - const deliveryFeesResult = - await assetHubApi.apis.XcmPaymentApi.query_delivery_fees( - destination, - remoteXcm, - ); - - if ( - deliveryFeesResult.success && - deliveryFeesResult.value.type === 'V5' && - deliveryFeesResult.value.value[0]?.fun?.type === 'Fungible' - ) { - deliveryFees = deliveryFeesResult.value.value[0].fun.value; - console.log('✓ Delivery fees:', deliveryFees.toString(), 'PAS units'); - } else { - console.log('✗ Failed to calculate delivery fees:', deliveryFeesResult); - } - - // 3. REMOTE EXECUTION FEES on Bridge Hub - console.log('\n3. Calculating remote execution fees on Bridge Hub'); - try { - const bridgeHubClient = createClient( - withPolkadotSdkCompat(getWsProvider(BRIDGE_HUB_RPC_ENDPOINT)), - ); - const bridgeHubApi = bridgeHubClient.getTypedApi(paseoBridgeHub); - const remoteWeightResult = - await bridgeHubApi.apis.XcmPaymentApi.query_xcm_weight(remoteXcm); - const remoteFeesResult = - await bridgeHubApi.apis.XcmPaymentApi.query_weight_to_asset_fee( - remoteWeightResult.value as { - ref_time: bigint; - proof_size: bigint; - }, - XcmVersionedAssetId.V4({ - parents: 1, - interior: XcmV3Junctions.Here(), - }), - ); - bridgeHubClient.destroy(); - remoteExecutionFees = remoteFeesResult.value as bigint; - console.log( - '✓ Remote execution fees:', - remoteExecutionFees.toString(), - 'PAS units', - ); - } catch (error) { - console.error( - 'Error calculating remote execution fees on Bridge Hub:', - error, - ); - } - } else { - console.log('✗ No XCM message found to Bridge Hub'); - } - } else { - console.log('✗ Local dry run failed on Asset Hub:', dryRunResult.value); - } - - // 4. TOTAL FEES - const totalFees = localExecutionFees + deliveryFees + remoteExecutionFees; - - console.log('\n=== Fee Summary (Asset Hub → Bridge Hub) ==='); - console.log( - 'Local execution fees:', - localExecutionFees.toString(), - 'PAS units', - ); - console.log('Delivery fees:', deliveryFees.toString(), 'PAS units'); - console.log( - 'Remote execution fees:', - remoteExecutionFees.toString(), - 'PAS units', - ); - console.log('TOTAL FEES:', totalFees.toString(), 'PAS units'); - console.log( - 'TOTAL FEES:', - (Number(totalFees) / Number(PAS_UNITS)).toFixed(4), - 'PAS', - ); - - return { - localExecutionFees, - deliveryFees, - remoteExecutionFees, - totalFees, - }; - } - ``` - -## Complete Implementation - -Now put it all together in the main function: - -```typescript title="teleport-ah-to-bridge-hub.ts" -async function main() { - // Connect to the Asset Hub parachain - const assetHubClient = createClient( - withPolkadotSdkCompat(getWsProvider(PASEO_ASSET_HUB_RPC_ENDPOINT)), - ); - - // Get the typed API for Asset Hub - const assetHubApi = assetHubClient.getTypedApi(paseoAssetHub); - - try { - // Create the XCM message for teleport (Asset Hub → Bridge Hub) - const xcm = createTeleportXcmToBridgeHub(BRIDGE_HUB_PARA_ID); - - console.log('=== XCM Teleport: Paseo Asset Hub → Bridge Hub ==='); - console.log('From:', ASSET_HUB_ACCOUNT, '(Alice on Asset Hub)'); - console.log('To:', BRIDGE_HUB_BENEFICIARY, '(Beneficiary on Bridge Hub)'); - console.log('Amount:', '1 PAS'); - console.log(''); - - // Estimate all fees - const fees = await estimateXcmFeesFromAssetHubToBridgeHub(xcm, assetHubApi); - void fees; // prevent unused var under isolatedModules - - // Create the execute transaction on Asset Hub - const tx = assetHubApi.tx.PolkadotXcm.execute({ - message: xcm, - max_weight: { - ref_time: 6000000000n, - proof_size: 65536n, - }, - }); - - console.log('\n=== Transaction Details ==='); - console.log('Transaction hex:', (await tx.getEncodedData()).asHex()); - console.log('Ready to submit!'); - } catch (error) { - console.log('Error stack:', (error as Error).stack); - console.error('Error occurred:', (error as Error).message); - if ((error as Error).cause) { - console.dir((error as Error).cause, { depth: null }); - } - } finally { - // Ensure client is always destroyed - assetHubClient.destroy(); - } -} -``` - -## Full Code - -The full code for the complete implementation is the following: - -??? code "Teleport from Asset Hub to Bridge Hub" - - ```typescript title="teleport-ah-to-bridge-hub.ts" - import { paseoAssetHub, paseoBridgeHub } from '@polkadot-api/descriptors'; - import { createClient, FixedSizeBinary, Enum } from 'polkadot-api'; - import { getWsProvider } from 'polkadot-api/ws-provider/node'; - import { withPolkadotSdkCompat } from 'polkadot-api/polkadot-sdk-compat'; - import { - XcmVersionedLocation, - XcmVersionedAssetId, - XcmV3Junctions, - XcmV3MultiassetFungibility, - XcmVersionedXcm, - XcmV5Instruction, - XcmV5Junctions, - XcmV5Junction, - XcmV5AssetFilter, - XcmV5WildAsset, - } from '@polkadot-api/descriptors'; - - // 1 PAS = 10^10 units - const PAS_UNITS = 10_000_000_000n; // 1 PAS - const PAS_CENTS = 100_000_000n; // 0.01 PAS - - // Paseo Asset Hub constants - const PASEO_ASSET_HUB_RPC_ENDPOINT = 'ws://localhost:8001'; - const ASSET_HUB_ACCOUNT = '15oF4uVJwmo4TdGW7VfQxNLavjCXviqxT9S1MgbjMNHr6Sp5'; // Alice (Paseo Asset Hub) - - // Bridge Hub destination - const BRIDGE_HUB_RPC_ENDPOINT = 'ws://localhost:8000'; - const BRIDGE_HUB_PARA_ID = 1002; - const BRIDGE_HUB_BENEFICIARY = - '14E5nqKAp3oAJcmzgZhUD2RcptBeUBScxKHgJKU4HPNcKVf3'; // Bob (Bridge Hub) - - // Create the XCM message for teleport (Asset Hub → Bridge Hub) - function createTeleportXcmToBridgeHub(paraId: number) { - return XcmVersionedXcm.V5([ - // Withdraw PAS from Asset Hub (PAS on parachains is parents:1, interior: Here) - XcmV5Instruction.WithdrawAsset([ - { - id: { parents: 1, interior: XcmV5Junctions.Here() }, - fun: XcmV3MultiassetFungibility.Fungible(1n * PAS_UNITS), // 1 PAS - }, - ]), - // Pay local fees on Asset Hub in PAS - XcmV5Instruction.PayFees({ - asset: { - id: { parents: 1, interior: XcmV5Junctions.Here() }, - fun: XcmV3MultiassetFungibility.Fungible(10n * PAS_CENTS), // 0.01 PAS - }, - }), - // Send to Bridge Hub parachain (parents:1, interior: X1(Parachain(paraId))) - XcmV5Instruction.InitiateTransfer({ - destination: { - parents: 1, - interior: XcmV5Junctions.X1(XcmV5Junction.Parachain(paraId)), - }, - remote_fees: Enum( - 'Teleport', - XcmV5AssetFilter.Definite([ - { - id: { parents: 1, interior: XcmV5Junctions.Here() }, - fun: XcmV3MultiassetFungibility.Fungible(10n * PAS_CENTS), // 0.01 PAS - }, - ]), - ), - preserve_origin: false, - remote_xcm: [ - XcmV5Instruction.DepositAsset({ - assets: XcmV5AssetFilter.Wild(XcmV5WildAsset.AllCounted(1)), - beneficiary: { - parents: 0, - interior: XcmV5Junctions.X1( - XcmV5Junction.AccountId32({ - network: undefined, - id: FixedSizeBinary.fromAccountId32(BRIDGE_HUB_BENEFICIARY), - }), - ), - }, - }), - ], - assets: [ - Enum('Teleport', XcmV5AssetFilter.Wild(XcmV5WildAsset.AllCounted(1))), // Send everything. - ], - }), - ]); - } - - async function estimateXcmFeesFromAssetHubToBridgeHub( - xcm: any, - assetHubApi: any, - ) { - console.log('=== Fee Estimation Process (Asset Hub → Bridge Hub) ==='); - - // 1. LOCAL EXECUTION FEES on Asset Hub - console.log('1. Calculating local execution fees on Asset Hub...'); - let localExecutionFees = 0n; - - const weightResult = - await assetHubApi.apis.XcmPaymentApi.query_xcm_weight(xcm); - if (weightResult.success) { - console.log('✓ XCM weight (Asset Hub):', weightResult.value); - - // Convert weight to PAS fees from Asset Hub's perspective (parents:1, Here) - const executionFeesResult = - await assetHubApi.apis.XcmPaymentApi.query_weight_to_asset_fee( - weightResult.value, - XcmVersionedAssetId.V4({ - parents: 1, - interior: XcmV3Junctions.Here(), - }), - ); - - if (executionFeesResult.success) { - localExecutionFees = executionFeesResult.value; - console.log( - '✓ Local execution fees (Asset Hub):', - localExecutionFees.toString(), - 'PAS units', - ); - } else { - console.log( - '✗ Failed to calculate local execution fees:', - executionFeesResult.value, - ); - } - } else { - console.log( - '✗ Failed to query XCM weight on Asset Hub:', - weightResult.value, - ); - } - - // 2. DELIVERY FEES + REMOTE EXECUTION FEES - console.log('\n2. Calculating delivery and remote execution fees...'); - let deliveryFees = 0n; - let remoteExecutionFees = 0n; // Skipped (Bridge Hub descriptor not available) - - // Origin from Asset Hub perspective - const origin = XcmVersionedLocation.V5({ - parents: 0, - interior: XcmV5Junctions.X1( - XcmV5Junction.AccountId32({ - id: FixedSizeBinary.fromAccountId32(ASSET_HUB_ACCOUNT), - network: undefined, - }), - ), - }); - - // Dry run the XCM locally on Asset Hub - const dryRunResult = await assetHubApi.apis.DryRunApi.dry_run_xcm( - origin, - xcm, - ); - - if ( - dryRunResult.success && - dryRunResult.value.execution_result.type === 'Complete' - ) { - console.log('✓ Local dry run on Asset Hub successful'); - - const { forwarded_xcms: forwardedXcms } = dryRunResult.value; - - // Find the XCM message sent to Bridge Hub (parents:1, interior: X1(Parachain(1002))) - const bridgeHubXcmEntry = forwardedXcms.find( - ([location, _]: [any, any]) => - (location.type === 'V4' || location.type === 'V5') && - location.value.parents === 1 && - location.value.interior?.type === 'X1' && - location.value.interior.value?.type === 'Parachain' && - location.value.interior.value.value === BRIDGE_HUB_PARA_ID, - ); - - if (bridgeHubXcmEntry) { - const [destination, messages] = bridgeHubXcmEntry; - const remoteXcm = messages[0]; - - console.log('✓ Found XCM message to Bridge Hub'); - - // Calculate delivery fees from Asset Hub to Bridge Hub - const deliveryFeesResult = - await assetHubApi.apis.XcmPaymentApi.query_delivery_fees( - destination, - remoteXcm, - ); - - if ( - deliveryFeesResult.success && - deliveryFeesResult.value.type === 'V5' && - deliveryFeesResult.value.value[0]?.fun?.type === 'Fungible' - ) { - deliveryFees = deliveryFeesResult.value.value[0].fun.value; - console.log('✓ Delivery fees:', deliveryFees.toString(), 'PAS units'); - } else { - console.log('✗ Failed to calculate delivery fees:', deliveryFeesResult); - } - - // 3. REMOTE EXECUTION FEES on Bridge Hub - console.log('\n3. Calculating remote execution fees on Bridge Hub'); - try { - const bridgeHubClient = createClient( - withPolkadotSdkCompat(getWsProvider(BRIDGE_HUB_RPC_ENDPOINT)), - ); - const bridgeHubApi = bridgeHubClient.getTypedApi(paseoBridgeHub); - const remoteWeightResult = - await bridgeHubApi.apis.XcmPaymentApi.query_xcm_weight(remoteXcm); - const remoteFeesResult = - await bridgeHubApi.apis.XcmPaymentApi.query_weight_to_asset_fee( - remoteWeightResult.value as { - ref_time: bigint; - proof_size: bigint; - }, - XcmVersionedAssetId.V4({ - parents: 1, - interior: XcmV3Junctions.Here(), - }), - ); - bridgeHubClient.destroy(); - remoteExecutionFees = remoteFeesResult.value as bigint; - console.log( - '✓ Remote execution fees:', - remoteExecutionFees.toString(), - 'PAS units', - ); - } catch (error) { - console.error( - 'Error calculating remote execution fees on Bridge Hub:', - error, - ); - } - } else { - console.log('✗ No XCM message found to Bridge Hub'); - } - } else { - console.log('✗ Local dry run failed on Asset Hub:', dryRunResult.value); - } - - // 4. TOTAL FEES - const totalFees = localExecutionFees + deliveryFees + remoteExecutionFees; - - console.log('\n=== Fee Summary (Asset Hub → Bridge Hub) ==='); - console.log( - 'Local execution fees:', - localExecutionFees.toString(), - 'PAS units', - ); - console.log('Delivery fees:', deliveryFees.toString(), 'PAS units'); - console.log( - 'Remote execution fees:', - remoteExecutionFees.toString(), - 'PAS units', - ); - console.log('TOTAL FEES:', totalFees.toString(), 'PAS units'); - console.log( - 'TOTAL FEES:', - (Number(totalFees) / Number(PAS_UNITS)).toFixed(4), - 'PAS', - ); - - return { - localExecutionFees, - deliveryFees, - remoteExecutionFees, - totalFees, - }; - } - - async function main() { - // Connect to the Asset Hub parachain - const assetHubClient = createClient( - withPolkadotSdkCompat(getWsProvider(PASEO_ASSET_HUB_RPC_ENDPOINT)), - ); - - // Get the typed API for Asset Hub - const assetHubApi = assetHubClient.getTypedApi(paseoAssetHub); - - try { - // Create the XCM message for teleport (Asset Hub → Bridge Hub) - const xcm = createTeleportXcmToBridgeHub(BRIDGE_HUB_PARA_ID); - - console.log('=== XCM Teleport: Paseo Asset Hub → Bridge Hub ==='); - console.log('From:', ASSET_HUB_ACCOUNT, '(Alice on Asset Hub)'); - console.log('To:', BRIDGE_HUB_BENEFICIARY, '(Beneficiary on Bridge Hub)'); - console.log('Amount:', '1 PAS'); - console.log(''); - - // Estimate all fees - const fees = await estimateXcmFeesFromAssetHubToBridgeHub(xcm, assetHubApi); - void fees; // prevent unused var under isolatedModules - - // Create the execute transaction on Asset Hub - const tx = assetHubApi.tx.PolkadotXcm.execute({ - message: xcm, - max_weight: { - ref_time: 6000000000n, - proof_size: 65536n, - }, - }); - - console.log('\n=== Transaction Details ==='); - console.log('Transaction hex:', (await tx.getEncodedData()).asHex()); - console.log('Ready to submit!'); - } catch (error) { - console.log('Error stack:', (error as Error).stack); - console.error('Error occurred:', (error as Error).message); - if ((error as Error).cause) { - console.dir((error as Error).cause, { depth: null }); - } - } finally { - // Ensure client is always destroyed - assetHubClient.destroy(); - } - } - - main().catch(console.error); - - ``` - -## Running the Script - -Before running the script, you can use chopsticks to fork the Paseo Asset Hub and Paseo Bridge Hub chains locally. To do so, you can use the following files and commands: - -1. Create a new directory called `.chopsticks` and add the files: - - ??? code "paseo-bridge-hub.yml" - - {% raw %} - ```yaml title=".chopsticks/paseo-bridge-hub.yml" - endpoint: wss://bridge-hub-paseo.dotters.network - mock-signature-host: true - block: ${env.PASEO_BRIDGE_HUB_BLOCK_NUMBER} - db: ./db.sqlite - - import-storage: - Sudo: - Key: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY # Alice - System: - Account: - - - - - - 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY - - providers: 1 - data: - free: '10000000000000000000' - ``` - {% endraw %} - - ??? code "paseo-asset-hub.yml" - - {% raw %} - ```yaml title=".chopsticks/paseo-asset-hub.yml" - endpoint: wss://asset-hub-paseo-rpc.n.dwellir.com - mock-signature-host: true - block: ${env.PASEO_ASSET_HUB_BLOCK_NUMBER} - db: ./db.sqlite - - import-storage: - Sudo: - Key: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY # Alice - System: - Account: - - - - - - 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY - - providers: 1 - data: - free: '10000000000000000000' - ``` - {% endraw %} - -2. Run the following command to fork the Paseo Bridge Hub chain: - - ```bash - chopsticks --config=.chopsticks/paseo-bridge-hub.yml - ``` - - After running the command, you will see the following output: - -
- chopsticks --config=.chopsticks/paseo-bridge-hub.yml - [15:55:22.770] INFO: Paseo Bridge Hub RPC listening on http://[::]:8000 and ws://[::]:8000 - app: "chopsticks" -
- -3. Run the following command to fork the Paseo Asset Hub chain: - - ```bash - chopsticks --config=.chopsticks/paseo-asset-hub.yml - ``` - - After running the commands, you will see the following output: - -
- chopsticks --config=.chopsticks/paseo-asset-hub.yml - [15:55:22.770] INFO: Paseo Asset Hub Testnet RPC listening on http://[::]:8001 and ws://[::]:8001 - app: "chopsticks" -
- -4. Run the script: - - ```bash - npx ts-node teleport-ah-to-bridge-hub.ts - ``` - -After running the script, you will see the following output: - -
- npx ts-node teleport-ah-to-bridge-hub.ts -
-=== XCM Teleport: Paseo Asset Hub → Bridge Hub ===
-From: 15oF4uVJwmo4TdGW7VfQxNLavjCXviqxT9S1MgbjMNHr6Sp5 (Alice on Asset Hub)
-To: 14E5nqKAp3oAJcmzgZhUD2RcptBeUBScxKHgJKU4HPNcKVf3 (Beneficiary on Bridge Hub)
-Amount: 1 PAS
-
-=== Fee Estimation Process (Asset Hub → Bridge Hub) ===
-1. Calculating local execution fees on Asset Hub...
-✓ XCM weight (Asset Hub): { ref_time: 1462082000n, proof_size: 19578n }
-✓ Local execution fees (Asset Hub): 97890000 PAS units
-
-2. Calculating delivery and remote execution fees...
-✓ Local dry run on Asset Hub successful
-✓ Found XCM message to Bridge Hub
-✓ Delivery fees: 305150000 PAS units
-
-3. Calculating remote execution fees on Bridge Hub
-✓ Remote execution fees: 17965000 PAS units
-
-=== Fee Summary (Asset Hub → Bridge Hub) ===
-Local execution fees: 97890000 PAS units
-Delivery fees: 305150000 PAS units
-Remote execution fees: 17965000 PAS units
-TOTAL FEES: 421005000 PAS units
-TOTAL FEES: 0.0421 PAS
-
-=== Transaction Details ===
-Transaction hex: 0x1f03050c00040100000700e40b54023001000002286bee31010100a90f0100000401000002286bee000400010204040d010204000101008eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a480700bca0650102000400
-Ready to submit!
-
-
-
- -## Conclusion - -This approach provides accurate fee estimation for XCM teleports from Asset Hub to Bridge Hub Chain by properly simulating execution on both chains and utilizing dedicated runtime APIs for fee calculation. The fee breakdown helps you understand the cost structure of reverse cross-chain operations (parachain → bridge hub chain) and ensures your transactions have sufficient funds to complete successfully. - -The key insight is understanding how asset references change based on the perspective of each chain in the XCM ecosystem, which is crucial for proper fee estimation and XCM construction. diff --git a/.ai/pages/chain-interactions-send-transactions-interoperability-transfer-assets-out-of-polkadot.md b/.ai/pages/chain-interactions-send-transactions-interoperability-transfer-assets-out-of-polkadot.md deleted file mode 100644 index 8ac3036a2..000000000 --- a/.ai/pages/chain-interactions-send-transactions-interoperability-transfer-assets-out-of-polkadot.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -url: https://docs.polkadot.com/chain-interactions/send-transactions/interoperability/transfer-assets-out-of-polkadot/ ---- - -TODO diff --git a/.ai/pages/chain-interactions-send-transactions-interoperability-transfer-assets-parachains.md b/.ai/pages/chain-interactions-send-transactions-interoperability-transfer-assets-parachains.md deleted file mode 100644 index 8b85b616f..000000000 --- a/.ai/pages/chain-interactions-send-transactions-interoperability-transfer-assets-parachains.md +++ /dev/null @@ -1,882 +0,0 @@ ---- -title: Transfer Assets Between Parachains -description: A step-by-step guide to using the ParaSpell XCM SDK to build, verify, and execute a transfer from one Parachain to another. -url: https://docs.polkadot.com/chain-interactions/send-transactions/interoperability/transfer-assets-parachains/ ---- - -# Transfer Assets Between Parachains - -## Introduction - -This guide walks you through transferring tokens between two parachains using the [ParaSpell XCM SDK](/reference/tools/paraspell/){target=\_blank}. This example utilizes [Asset Hub](/polkadot-protocol/architecture/system-chains/asset-hub/){target=\_blank} and the [People Chain](/polkadot-protocol/architecture/system-chains/people/){target=\_blank}. However, the same approach can be applied to transfers between other parachains. - -For development purposes, this guide will use the [Polkadot TestNet](/develop/networks/#paseo){target=\_blank}, so the transferred token will be PAS. - -In this guide, you will: - -- Build an XCM transfer transaction using ParaSpell XCM SDK. -- Perform a dry run to validate the transfer. -- Verify the [Existential Deposit (ED)](/reference/glossary/#existential-deposit){target=\_blank} requirement on the destination chain. -- Retrieve information regarding the transfer, along with fee estimates. -- Submit the transaction. - -### Prerequisites - -Before you begin, ensure you have the following: - -- Knowledge of the [fundamentals of Polkadot](/parachains/get-started/){target=\_blank}. -- Basic understanding of [XCM](/parachains/interoperability/get-started/){target=\_blank}. -- Basic familiarity with JavaScript or TypeScript. -- Installed [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm){target=\_blank}, a JavaScript and TypeScript package manager. - -## Initialize Your Project - -Create the project folder: - -```bash -mkdir paraspell-transfer && \ -cd paraspell-transfer -``` - -Initialize the JavaScript project: - -```bash -npm init -y -``` - -Install dev dependencies: - -```bash -npm install --save-dev @types/node@^22.12.0 tsx@^4.20.6 typescript@^5.7.3 -``` - -Install the required dependencies: - -```bash -npm install --save @paraspell/sdk@11.12.6 polkadot-api@1.20.0 @polkadot-labs/hdkd-helpers@0.0.26 @polkadot-labs/hdkd@0.0.25 -``` - -Now add the following setup code to `index.ts`: - -```ts title="index.ts" -import { Builder, hasDryRunSupport } from '@paraspell/sdk'; -import { - entropyToMiniSecret, - mnemonicToEntropy, - ss58Address, -} from '@polkadot-labs/hdkd-helpers'; -import { getPolkadotSigner } from 'polkadot-api/signer'; -import { sr25519CreateDerive } from '@polkadot-labs/hdkd'; -import { inspect } from 'util'; - -// PAS token has 10 decimals -const PAS_UNITS = 10_000_000_000n; - -const SEED_PHRASE = - 'INSERT_YOUR_SEED_PHRASE'; - -// Create Sr25519 signer from mnemonic -function getSigner() { - const entropy = mnemonicToEntropy(SEED_PHRASE); - const miniSecret = entropyToMiniSecret(entropy); - const derive = sr25519CreateDerive(miniSecret); - const keyPair = derive(''); - return getPolkadotSigner(keyPair.publicKey, 'Sr25519', keyPair.sign); -} - -const RECIPIENT_ADDRESS = ss58Address(getSigner().publicKey); -const SENDER_ADDRESS = ss58Address(getSigner().publicKey); -``` - -Replace the `INSERT_YOUR_SEED_PHRASE` with the seed phrase from your Polkadot development account. - -Be sure to fund this account with some PAS tokens on the Paseo Asset Hub using the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1000){target=_blank}. - -!!!warning "Security Warning" - Never commit your mnemonic phrase to production code. Use environment variables or secure key management systems. - -## Build a Token Transfer Transaction - -The next step is to build the transaction that you intend to execute. - -In this example, you will transfer 10 PAS tokens from Paseo's Asset Hub to Paseo's People Chain system parachain. - -Add the ParaSpell transaction code to your `index.ts` file: - -```ts title="index.ts" -async function transfer() { - const signer = getSigner(); - - const tx = await Builder() - .from('AssetHubPaseo') - .to('PeoplePaseo') - .currency({ - symbol: 'PAS', - amount: 10n * PAS_UNITS, // 10 PAS - }) - .address(RECIPIENT_ADDRESS) - .build(); - - console.log('Built transaction:', inspect(tx, { colors: true, depth: null })); - - const result = await tx.signAndSubmit(signer); - console.log(inspect(result, { colors: true, depth: null })); - process.exit(0); -} -``` - -Do not execute it just yet. You will perform a dry run of this transaction first to ensure it works as expected. - -## Perform a Dry Run - -Dry runs simulate the transaction without broadcasting it, allowing you to confirm success in advance. - -Add the following dry run code to your `index.ts` script: - -```ts title="index.ts" -async function dryRunTransfer() { - if (!hasDryRunSupport('AssetHubPaseo')) { - console.log('Dry run is not supported on AssetHubPaseo.'); - return; - } - - const tx = await Builder() - .from('AssetHubPaseo') - .to('PeoplePaseo') - .currency({ - symbol: 'PAS', - amount: 10n * PAS_UNITS, - }) - .address(RECIPIENT_ADDRESS) - .senderAddress(SENDER_ADDRESS) - .dryRun(); - - console.log(inspect(tx, { colors: true, depth: null })); - process.exit(0); -} - -dryRunTransfer(); -``` -Run the script using the following command: - -```bash -npx tsx index.ts -``` - -The result of the dry run will look similar to the following example output: - -
- npx tsx index.ts - { - failureReason: undefined, - failureChain: undefined, - origin: { - success: true, - fee: 17965000n, - currency: 'PAS', - asset: { - symbol: 'PAS', - isNative: true, - decimals: 10, - existentialDeposit: '100000000', - location: { parents: 1, interior: { Here: null } }, - isFeeAsset: true, - amount: 100000000000n - }, - weight: undefined, - forwardedXcms: [ - { - type: 'V3', - value: { - parents: 1, - interior: { type: 'X1', value: { type: 'Parachain', value: 1004 } } - } - }, - [ - { - type: 'V3', - value: [ - { - type: 'ReceiveTeleportedAsset', - value: [ - { - id: { - type: 'Concrete', - value: { - parents: 1, - interior: { type: 'Here', value: undefined } - } - }, - fun: { type: 'Fungible', value: 100000000000n } - } - ] - }, - { type: 'ClearOrigin', value: undefined }, - { - type: 'BuyExecution', - value: { - fees: { - id: { - type: 'Concrete', - value: { - parents: 1, - interior: { type: 'Here', value: undefined } - } - }, - fun: { type: 'Fungible', value: 100000000000n } - }, - weight_limit: { type: 'Unlimited', value: undefined } - } - }, - { - type: 'DepositAsset', - value: { - assets: { - type: 'Wild', - value: { type: 'AllCounted', value: 1 } - }, - beneficiary: { - parents: 0, - interior: { - type: 'X1', - value: { - type: 'AccountId32', - value: { - network: undefined, - id: FixedSizeBinary { - asText: [Function (anonymous)], - asHex: [Function (anonymous)], - asOpaqueHex: [Function (anonymous)], - asBytes: [Function (anonymous)], - asOpaqueBytes: [Function (anonymous)] - } - } - } - } - } - } - }, - { - type: 'SetTopic', - value: FixedSizeBinary { - asText: [Function (anonymous)], - asHex: [Function (anonymous)], - asOpaqueHex: [Function (anonymous)], - asBytes: [Function (anonymous)], - asOpaqueBytes: [Function (anonymous)] - } - } - ] - } - ] - ], - destParaId: 1004 - }, - assetHub: undefined, - bridgeHub: undefined, - destination: { - success: true, - fee: 817598n, - currency: 'PAS', - asset: { - symbol: 'PAS', - isNative: true, - decimals: 10, - existentialDeposit: '1000000000', - location: { parents: 1, interior: { Here: null } }, - isFeeAsset: true - }, - weight: { refTime: 176858000n, proofSize: 0n }, - forwardedXcms: [], - destParaId: undefined - }, - hops: [] -} -
-## Verify the Existential Deposit - -Check if the recipient account meets the [Existential Deposit (ED)](/polkadot-protocol/glossary/#existential-deposit){target=\_blank} requirement before sending by using [`verifyEdOnDestination`](https://paraspell.github.io/docs/sdk/xcmUtils.html#verify-ed-on-destination){target=\_blank}: - -```ts title="index.ts" -async function verifyED() { - const isValid = await Builder() - .from('AssetHubPaseo') - .to('PeoplePaseo') - .currency({ - symbol: 'PAS', - amount: 10n * PAS_UNITS, - }) - .address(RECIPIENT_ADDRESS) - .senderAddress(SENDER_ADDRESS) - .verifyEdOnDestination(); - - console.log(`ED verification ${isValid ? 'successful' : 'failed'}.`); - process.exit(0); -} - -verifyED(); -``` -Comment out the `dryRunTransfer()` function so that it is not executed again. Then, execute the `verifyED()` by running the following command: - -```bash -npx tsx index.ts -``` - -After that, you will get output confirming the ED which will look similar to the following: - -
- npx tsx index.ts - ED verification successful. -
-## Get Transfer Info and Fee Estimates - -Before sending an XCM transaction, it is helpful to estimate the fees associated with executing and delivering the cross-chain message. - -ParaSpell has a helpful function for this: [`getTransferInfo()`](https://paraspell.github.io/docs/sdk/xcmUtils.html#xcm-transfer-info){target=\_blank}. This function returns an estimate of the associated XCM fees, along with the account's balance before and after the fees are paid. - -```ts title="index.ts" -async function XcmTransferInfo() { - const info = await Builder() - .from('AssetHubPaseo') - .to('PeoplePaseo') - .currency({ - symbol: 'PAS', - amount: 10n * PAS_UNITS, - }) - .address(RECIPIENT_ADDRESS) - .senderAddress(SENDER_ADDRESS) - .getTransferInfo(); - - console.log('Transfer Info:', info); - process.exit(0); -} - -XcmTransferInfo(); -``` - -Comment out the `verifyED()` function so it doesn't execute again. Then, execute the `XcmTransferInfo()` function by running the following command: - -```bash -npx tsx index.ts -``` - -You will see all the information for your transfer similar to the following example: - -
- npx tsx index.ts - Transfer Info: { - chain: { - origin: "AssetHubPaseo", - destination: "PeoplePaseo", - ecosystem: "PAS", - }, - origin: { - selectedCurrency: { - sufficient: true, - balance: 9799197260420n, - balanceAfter: 9699197260420n, - currencySymbol: "PAS", - asset: [Object ...], - existentialDeposit: 100000000n, - }, - xcmFee: { - sufficient: true, - fee: 17965000n, - balance: 9799197260420n, - balanceAfter: 9799179295420n, - currencySymbol: "PAS", - asset: [Object ...], - }, - }, - assetHub: undefined, - bridgeHub: undefined, - hops: [], - destination: { - receivedCurrency: { - sufficient: true, - receivedAmount: 99999182402n, - balance: 199998364804n, - balanceAfter: 299997547206n, - currencySymbol: "PAS", - asset: [Object ...], - existentialDeposit: 1000000000n, - }, - xcmFee: { - fee: 817598n, - balance: 199998364804n, - balanceAfter: 299997547206n, - currencySymbol: "PAS", - asset: [Object ...], - }, - }, -} -
-Now that you have: - -- Completed a successful dry run of the transaction. -- Verified the existential deposit on the recipient account. -- Obtained an estimate of the associated XCM fees. - -You can execute the transfer function by adding the following function call: - -```typescript title="index.ts" -transfer(); -``` - -Comment out the `XcmTransferInfo()` function so it doesn't execute again. Then, execute the transfer by running the following command: - -```bash -npx tsx index.ts -``` - -Your `transfer` function will submit the transaction, and you will get the following output: - -
- npx tsx index.ts - ... - Built transaction: { - getPaymentInfo: [AsyncFunction: getPaymentInfo], - getEstimatedFees: [AsyncFunction: getEstimatedFees], - decodedCall: { - type: 'PolkadotXcm', - value: { - type: 'limited_teleport_assets', - value: { - dest: { - type: 'V5', - value: { - parents: 1, - interior: { type: 'X1', value: { type: 'Parachain', value: 1004 } } - } - }, - beneficiary: { - type: 'V5', - value: { - parents: 0, - interior: { - type: 'X1', - value: { - type: 'AccountId32', - value: { - network: undefined, - id: FixedSizeBinary { - asText: [Function (anonymous)], - asHex: [Function (anonymous)], - asOpaqueHex: [Function (anonymous)], - asBytes: [Function (anonymous)], - asOpaqueBytes: [Function (anonymous)] - } - } - } - } - } - }, - assets: { - type: 'V5', - value: [ - { - id: { parents: 1, interior: { type: 'Here', value: null } }, - fun: { type: 'Fungible', value: 100000000000n } - } - ] - }, - fee_asset_item: 0, - weight_limit: { type: 'Unlimited' } - } - } - }, - getEncodedData: [Function: getEncodedData], - sign: [Function: sign], - signSubmitAndWatch: [Function: signSubmitAndWatch], - signAndSubmit: [Function: signAndSubmit] -} -
-Once the transaction is successfully included in a block, you will see the recipient's account balance updated, and you will receive output similar to the following. - -???- code "Successful Transaction Submission" - This output will be returned once the transaction has been successfully included in a block. - -
- ... - { - txHash: '0x6fbecc0b284adcff46ab39872659c2567395c865adef5f8cbea72f25b6042609', - block: { - index: 2, - number: 2524809, - hash: '0xa39a96d5921402c6e8f67e48b8395d6b21382c72d4d30f8497a0e9f890bc0d4c' - }, - ok: true, - events: [ - { - type: 'Balances', - value: { - type: 'Withdraw', - value: { - who: '15DMtB5BDCJqw4uZtByTWXGqViAVx7XjRsxWbTH5tfrHLe8j', - amount: 15668864n - } - }, - topics: [] - }, - { - type: 'Balances', - value: { - type: 'Burned', - value: { - who: '15DMtB5BDCJqw4uZtByTWXGqViAVx7XjRsxWbTH5tfrHLe8j', - amount: 100000000000n - } - }, - topics: [] - }, - { - type: 'PolkadotXcm', - value: { - type: 'Attempted', - value: { - outcome: { - type: 'Complete', - value: { used: { ref_time: 190990000n, proof_size: 3593n } } - } - } - }, - topics: [] - }, - { - type: 'Balances', - value: { - type: 'Burned', - value: { - who: '15DMtB5BDCJqw4uZtByTWXGqViAVx7XjRsxWbTH5tfrHLe8j', - amount: 304850000n - } - }, - topics: [] - }, - { - type: 'Balances', - value: { - type: 'Minted', - value: { - who: '14xmwinmCEz6oRrFdczHKqHgWNMiCysE2KrA4jXXAAM1Eogk', - amount: 304850000n - } - }, - topics: [] - }, - { - type: 'PolkadotXcm', - value: { - type: 'FeesPaid', - value: { - paying: { - parents: 0, - interior: { - type: 'X1', - value: { - type: 'AccountId32', - value: { - network: { type: 'Polkadot', value: undefined }, - id: FixedSizeBinary { - asText: [Function (anonymous)], - asHex: [Function (anonymous)], - asOpaqueHex: [Function (anonymous)], - asBytes: [Function (anonymous)], - asOpaqueBytes: [Function (anonymous)] - } - } - } - } - }, - fees: [ - { - id: { - parents: 1, - interior: { type: 'Here', value: undefined } - }, - fun: { type: 'Fungible', value: 304850000n } - } - ] - } - }, - topics: [] - }, - { - type: 'XcmpQueue', - value: { - type: 'XcmpMessageSent', - value: { - message_hash: FixedSizeBinary { - asText: [Function (anonymous)], - asHex: [Function (anonymous)], - asOpaqueHex: [Function (anonymous)], - asBytes: [Function (anonymous)], - asOpaqueBytes: [Function (anonymous)] - } - } - }, - topics: [] - }, - { - type: 'PolkadotXcm', - value: { - type: 'Sent', - value: { - origin: { - parents: 0, - interior: { - type: 'X1', - value: { - type: 'AccountId32', - value: { - network: { type: 'Polkadot', value: undefined }, - id: FixedSizeBinary { - asText: [Function (anonymous)], - asHex: [Function (anonymous)], - asOpaqueHex: [Function (anonymous)], - asBytes: [Function (anonymous)], - asOpaqueBytes: [Function (anonymous)] - } - } - } - } - }, - destination: { - parents: 1, - interior: { type: 'X1', value: { type: 'Parachain', value: 1002 } } - }, - message: [ - { - type: 'ReceiveTeleportedAsset', - value: [ - { - id: { - parents: 1, - interior: { type: 'Here', value: undefined } - }, - fun: { type: 'Fungible', value: 100000000000n } - } - ] - }, - { type: 'ClearOrigin', value: undefined }, - { - type: 'BuyExecution', - value: { - fees: { - id: { - parents: 1, - interior: { type: 'Here', value: undefined } - }, - fun: { type: 'Fungible', value: 100000000000n } - }, - weight_limit: { type: 'Unlimited', value: undefined } - } - }, - { - type: 'DepositAsset', - value: { - assets: { - type: 'Wild', - value: { type: 'AllCounted', value: 1 } - }, - beneficiary: { - parents: 0, - interior: { - type: 'X1', - value: { - type: 'AccountId32', - value: { - network: undefined, - id: FixedSizeBinary { - asText: [Function (anonymous)], - asHex: [Function (anonymous)], - asOpaqueHex: [Function (anonymous)], - asBytes: [Function (anonymous)], - asOpaqueBytes: [Function (anonymous)] - } - } - } - } - } - } - } - ], - message_id: FixedSizeBinary { - asText: [Function (anonymous)], - asHex: [Function (anonymous)], - asOpaqueHex: [Function (anonymous)], - asBytes: [Function (anonymous)], - asOpaqueBytes: [Function (anonymous)] - } - } - }, - topics: [] - }, - { - type: 'Balances', - value: { - type: 'Deposit', - value: { - who: '13UVJyLgBASGhE2ok3TvxUfaQBGUt88JCcdYjHvUhvQkFTTx', - amount: 15668864n - } - }, - topics: [] - }, - { - type: 'TransactionPayment', - value: { - type: 'TransactionFeePaid', - value: { - who: '15DMtB5BDCJqw4uZtByTWXGqViAVx7XjRsxWbTH5tfrHLe8j', - actual_fee: 15668864n, - tip: 0n - } - }, - topics: [] - }, - { - type: 'System', - value: { - type: 'ExtrinsicSuccess', - value: { - dispatch_info: { - weight: { ref_time: 952851000n, proof_size: 13382n }, - class: { type: 'Normal', value: undefined }, - pays_fee: { type: 'Yes', value: undefined } - } - } - }, - topics: [] - } - ] - } -
-After executing the transfer, check the account balance on [Polkadot.js Apps](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fsys.turboflakes.io%2Fasset-hub-paseo){target=\_blank} for [Paseo's Asset Hub](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fsys.turboflakes.io%2Fasset-hub-paseo#/accounts){target=\_blank} and [Paseo's People Chain](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fsys.ibp.network%2Fpeople-paseo#/accounts){target=\_blank}. - -You should see: - -- The recipient account now has 10 more PAS tokens. -- The sender account has the transfer amount (10 PAS) + the fees amount debited from their account balance. - -You have now successfully created and sent a cross-chain transfer using the ParaSpell XCM SDK! - -???- code "Full Code" - - ```typescript title="index.ts" - import { Builder, hasDryRunSupport } from '@paraspell/sdk'; - import { - entropyToMiniSecret, - mnemonicToEntropy, - ss58Address, - } from '@polkadot-labs/hdkd-helpers'; - import { getPolkadotSigner } from 'polkadot-api/signer'; - import { sr25519CreateDerive } from '@polkadot-labs/hdkd'; - import { inspect } from 'util'; - - // PAS token has 10 decimals - const PAS_UNITS = 10_000_000_000n; - - const SEED_PHRASE = - 'INSERT_YOUR_SEED_PHRASE'; - - // Create Sr25519 signer from mnemonic - function getSigner() { - const entropy = mnemonicToEntropy(SEED_PHRASE); - const miniSecret = entropyToMiniSecret(entropy); - const derive = sr25519CreateDerive(miniSecret); - const keyPair = derive(''); - return getPolkadotSigner(keyPair.publicKey, 'Sr25519', keyPair.sign); - } - - const RECIPIENT_ADDRESS = ss58Address(getSigner().publicKey); - const SENDER_ADDRESS = ss58Address(getSigner().publicKey); - - async function transfer() { - const signer = getSigner(); - - const tx = await Builder() - .from('AssetHubPaseo') - .to('PeoplePaseo') - .currency({ - symbol: 'PAS', - amount: 10n * PAS_UNITS, // 10 PAS - }) - .address(RECIPIENT_ADDRESS) - .build(); - - console.log('Built transaction:', inspect(tx, { colors: true, depth: null })); - - const result = await tx.signAndSubmit(signer); - console.log(inspect(result, { colors: true, depth: null })); - process.exit(0); - } - - async function dryRunTransfer() { - if (!hasDryRunSupport('AssetHubPaseo')) { - console.log('Dry run is not supported on AssetHubPaseo.'); - return; - } - - const tx = await Builder() - .from('AssetHubPaseo') - .to('PeoplePaseo') - .currency({ - symbol: 'PAS', - amount: 10n * PAS_UNITS, - }) - .address(RECIPIENT_ADDRESS) - .senderAddress(SENDER_ADDRESS) - .dryRun(); - - console.log(inspect(tx, { colors: true, depth: null })); - process.exit(0); - } - - dryRunTransfer(); - - async function verifyED() { - const isValid = await Builder() - .from('AssetHubPaseo') - .to('PeoplePaseo') - .currency({ - symbol: 'PAS', - amount: 10n * PAS_UNITS, - }) - .address(RECIPIENT_ADDRESS) - .senderAddress(SENDER_ADDRESS) - .verifyEdOnDestination(); - - console.log(`ED verification ${isValid ? 'successful' : 'failed'}.`); - process.exit(0); - } - - verifyED(); - - async function XcmTransferInfo() { - const info = await Builder() - .from('AssetHubPaseo') - .to('PeoplePaseo') - .currency({ - symbol: 'PAS', - amount: 10n * PAS_UNITS, - }) - .address(RECIPIENT_ADDRESS) - .senderAddress(SENDER_ADDRESS) - .getTransferInfo(); - - console.log('Transfer Info:', info); - process.exit(0); - } - - XcmTransferInfo(); - - transfer(); - - ``` - -## Next Steps - -- Read the Docs: Dive deeper into the features of the [ParaSpell XCM SDK](https://paraspell.github.io/docs/sdk/getting-started.html){target=\_blank} documentation. - -- Learn about XCM: Understand the underlying protocol by visiting the [Introduction to XCM page](/parachains/interoperability/get-started/) in the Polkadot Docs. diff --git a/.ai/pages/chain-interactions-send-transactions-pay-fees-with-different-tokens.md b/.ai/pages/chain-interactions-send-transactions-pay-fees-with-different-tokens.md deleted file mode 100644 index c27802cd6..000000000 --- a/.ai/pages/chain-interactions-send-transactions-pay-fees-with-different-tokens.md +++ /dev/null @@ -1,308 +0,0 @@ ---- -title: Send a Transaction While Paying the Fee with a Different Token -description: This tutorial demonstrates how to send a DOT transfer transaction while paying the fees using a different token on the Asset Hub. -url: https://docs.polkadot.com/chain-interactions/send-transactions/pay-fees-with-different-tokens/ ---- - -# Send a Transaction While Paying the Fee with a Different Token - -## Introduction - -The Asset Hub provides a powerful feature that allows users to pay transaction fees using alternative tokens instead of the native token of the chain. - -This tutorial demonstrates how to send a DOT transfer transaction while paying the fees using a different token (USDT in this example) on the Asset Hub. - -## Environment Setup - -Let's set up the development environment for this tutorial: - -1. Create a new directory and initialize the project: - - ```bash - mkdir fee-payment-tutorial && \ - cd fee-payment-tutorial - ``` - -2. Initialize the project: - - ```bash - npm init -y - ``` - -3. Install dev dependencies: - - ```bash - npm install --save-dev @types/node@^22.12.0 ts-node@^10.9.2 typescript@^5.7.3 - ``` - -4. Install dependencies: - - ```bash - npm install --save @polkadot-labs/hdkd@^0.0.13 @polkadot-labs/hdkd-helpers@^0.0.13 polkadot-api@1.9.5 - ``` - -5. Create TypeScript configuration: - - ```bash - npx tsc --init && npm pkg set type=module - ``` - - The command `npm pkg set type=module` is used to set the type of the project to module. This is necessary to use the `import` statement in the TypeScript code. - -6. Generate Polkadot API types for Asset Hub: - - ```bash - npx papi add assetHub -n polkadot_asset_hub - ``` - -7. Create a new file called `fee-payment-transaction.ts`: - - ```bash - touch fee-payment-transaction.ts - ``` - -## Local Asset Hub Setup - -Before running the script, you'll need to fork the Asset Hub locally using Chopsticks: - -```bash -chopsticks -c polkadot-asset-hub -``` - -This command forks the Asset Hub chain, making it available at `ws://localhost:8000`. By running `polkadot-asset-hub`, you're using the Asset Hub fork with the configuration specified in the [`polkadot-asset-hub.yml`](https://github.com/AcalaNetwork/chopsticks/blob/master/configs/polkadot-asset-hub.yml){target=_blank} file. This configuration defines Alice's account with USDT assets. If you want to use a different chain, ensure the account you're using has the necessary assets. - -## Implementation - -In the following sections, you'll set up imports and constants, create a transaction signer, and connect to the Polkadot Asset Hub chain. Then, you'll create and send a DOT transfer transaction, requesting that fees be paid in USDT instead of DOT. - -### Import Dependencies - -Add the following imports to your `fee-payment-transaction.ts` file: - -```typescript title="fee-payment-transaction.ts" -import { sr25519CreateDerive } from "@polkadot-labs/hdkd"; -import { - DEV_PHRASE, - entropyToMiniSecret, - mnemonicToEntropy, -} from "@polkadot-labs/hdkd-helpers"; -import { getPolkadotSigner } from "polkadot-api/signer"; -import { createClient } from "polkadot-api"; -import { assetHub } from "@polkadot-api/descriptors"; -import { withPolkadotSdkCompat } from "polkadot-api/polkadot-sdk-compat"; -import { getWsProvider } from "polkadot-api/ws-provider/node"; -import { MultiAddress } from "@polkadot-api/descriptors"; -``` - -### Define Constants - -Define the constants for your transaction: - -```typescript title="fee-payment-transaction.ts" -const TARGET_ADDRESS = "14E5nqKAp3oAJcmzgZhUD2RcptBeUBScxKHgJKU4HPNcKVf3"; // Bob's address -const TRANSFER_AMOUNT = 3_000_000_000n; // 3 DOT -const USD_ASSET_ID = 1337; -``` - -### Create a Signer - -Create a signer using Alice's development account: - -```typescript title="fee-payment-transaction.ts" -const createSigner = async () => { - const entropy = mnemonicToEntropy(DEV_PHRASE); - const miniSecret = entropyToMiniSecret(entropy); - const derive = sr25519CreateDerive(miniSecret); - const hdkdKeyPair = derive("//Alice"); - const polkadotSigner = getPolkadotSigner( - hdkdKeyPair.publicKey, - "Sr25519", - hdkdKeyPair.sign - ); - return polkadotSigner; -}; -``` - -This function will return a signer that can be used to sign the transaction. - -### Setup the Client and API - -Create the client connection to the local Asset Hub: - -```typescript title="fee-payment-transaction.ts" -const client = createClient( - withPolkadotSdkCompat( - getWsProvider("ws://localhost:8000") // Chopsticks Asset Hub - ) -); - -const api = client.getTypedApi(assetHub); -``` - -### Create the Transaction - -Create a standard DOT transfer transaction: - -```typescript title="fee-payment-transaction.ts" -const tx = api.tx.Balances.transfer_keep_alive({ - dest: MultiAddress.Id(TARGET_ADDRESS), - value: BigInt(TRANSFER_AMOUNT), -}); -``` - -This creates a transaction that transfers 3 DOT to Bob's address while keeping Alice's account alive. - -### Sign and Submit with Alternative Fee Payment - -The key part of this tutorial is specifying an alternative asset for fee payment. This is done through the `asset` parameter in the `signAndSubmit` options: - -```typescript title="fee-payment-transaction.ts" -const signer = await createSigner(); - -const result = await tx.signAndSubmit(signer, { - asset: { - parents: 0, - interior: { - type: "X2", - value: [ - { type: "PalletInstance", value: 50 }, - { type: "GeneralIndex", value: BigInt(USD_ASSET_ID) }, - ], - }, - }, -}); - -const { txHash, ok, block, events } = result; -console.log(`Tx finalized: ${txHash} (ok=${ok})`); -console.log(`Block: #${block.number} ${block.hash} [tx index ${block.index}]`); - -console.log("Events:"); -for (const ev of events) { - const type = (ev as any).type ?? "unknown"; - console.log(`- ${type}`); -} - -process.exit(0); -``` - -This specifies that the fees should be paid using the USDT asset. - -## Full Code - -The full code for the complete implementation is the following: - -??? code "Complete Code" - - ```typescript title="fee-payment-transaction.ts" - import { sr25519CreateDerive } from "@polkadot-labs/hdkd"; - import { - DEV_PHRASE, - entropyToMiniSecret, - mnemonicToEntropy, - } from "@polkadot-labs/hdkd-helpers"; - import { getPolkadotSigner } from "polkadot-api/signer"; - import { createClient } from "polkadot-api"; - import { assetHub } from "@polkadot-api/descriptors"; - import { withPolkadotSdkCompat } from "polkadot-api/polkadot-sdk-compat"; - import { getWsProvider } from "polkadot-api/ws-provider/node"; - import { MultiAddress } from "@polkadot-api/descriptors"; - - const TARGET_ADDRESS = "14E5nqKAp3oAJcmzgZhUD2RcptBeUBScxKHgJKU4HPNcKVf3"; // Bob's address - const TRANSFER_AMOUNT = 3_000_000_000n; // 3 DOT - const USD_ASSET_ID = 1337; - - const createSigner = async () => { - const entropy = mnemonicToEntropy(DEV_PHRASE); - const miniSecret = entropyToMiniSecret(entropy); - const derive = sr25519CreateDerive(miniSecret); - const hdkdKeyPair = derive("//Alice"); - const polkadotSigner = getPolkadotSigner( - hdkdKeyPair.publicKey, - "Sr25519", - hdkdKeyPair.sign - ); - return polkadotSigner; - }; - - const client = createClient( - withPolkadotSdkCompat( - getWsProvider("ws://localhost:8000") // Chopsticks Asset Hub - ) - ); - - const api = client.getTypedApi(assetHub); - - const tx = api.tx.Balances.transfer_keep_alive({ - dest: MultiAddress.Id(TARGET_ADDRESS), - value: BigInt(TRANSFER_AMOUNT), - }); - - const signer = await createSigner(); - - const result = await tx.signAndSubmit(signer, { - asset: { - parents: 0, - interior: { - type: "X2", - value: [ - { type: "PalletInstance", value: 50 }, - { type: "GeneralIndex", value: BigInt(USD_ASSET_ID) }, - ], - }, - }, - }); - - const { txHash, ok, block, events } = result; - console.log(`Tx finalized: ${txHash} (ok=${ok})`); - console.log(`Block: #${block.number} ${block.hash} [tx index ${block.index}]`); - - console.log("Events:"); - for (const ev of events) { - const type = (ev as any).type ?? "unknown"; - console.log(`- ${type}`); - } - - process.exit(0); - ``` - -## Running the Script - -To run the script: - -```bash -npx ts-node fee-payment-transaction.ts -``` - -## Expected Output - -When you run the script successfully, you should see output similar to: - -
- npx ts-node fee-payment-transaction.ts -
-Tx finalized: 0x771956fdf40b3741bdc3c1e981a6daacbe5521877ad1915542e7413bb4a820bc (ok=true)
-Block: #9645060 0x57710514f168b5c444c8e47b1e1a31dd9e7bc7e9a51d8d25ccdbc6053e159f6b [tx index 2]
-Events:
-- Assets
-- Balances
-- Assets
-- AssetConversion
-- Balances
-- Balances
-- AssetTxPayment
-- System
-
-
-The key events to look for are: - -- **Assets**: The asset was transferred. -- **Balances**: The fees were paid using the alternative asset. -- **AssetConversion**: The fees were converted to the alternative asset. -- **AssetTxPayment**: The fees were paid using the alternative asset. -- **System**: The transaction was successful. - -## Conclusion - -Paying transaction fees with alternative tokens on Asset Hub provides significant flexibility for users and applications. - -The key takeaway is understanding how to specify alternative assets using the XCM location format, which opens up possibilities for building applications that can operate entirely using specific token ecosystems while still leveraging the full power of the network. diff --git a/.ai/pages/chain-interactions-send-transactions-with-sdks.md b/.ai/pages/chain-interactions-send-transactions-with-sdks.md deleted file mode 100644 index 9c52f2374..000000000 --- a/.ai/pages/chain-interactions-send-transactions-with-sdks.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -url: https://docs.polkadot.com/chain-interactions/send-transactions/with-sdks/ ---- - -TODO diff --git a/.ai/pages/chain-interactions-token-operations-convert-assets.md b/.ai/pages/chain-interactions-token-operations-convert-assets.md deleted file mode 100644 index 3d057db56..000000000 --- a/.ai/pages/chain-interactions-token-operations-convert-assets.md +++ /dev/null @@ -1,356 +0,0 @@ ---- -title: Convert Assets on Asset Hub -description: A guide detailing the step-by-step process of converting assets on Asset Hub, helping users efficiently navigate asset management on the platform. -categories: dApps -url: https://docs.polkadot.com/chain-interactions/token-operations/convert-assets/ ---- - -# Convert Assets on Asset Hub - -## Introduction - -Asset Conversion is an Automated Market Maker (AMM) utilizing [Uniswap V2](https://github.com/Uniswap/v2-core){target=\_blank} logic and implemented as a pallet on Polkadot's Asset Hub. - -This guide will provide detailed information about the key functionalities offered by the [Asset Conversion](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/asset-conversion){target=\_blank} pallet on Asset Hub, including: - -- Creating a liquidity pool. -- Adding liquidity to a pool. -- Swapping assets. -- Withdrawing liquidity from a pool. - -## Prerequisites - -Before converting assets on Asset Hub, you must ensure you have: - -- Access to the [Polkadot.js Apps](https://polkadot.js.org/apps){target=\_blank} interface and a connection with the intended blockchain. -- A funded wallet containing the assets you wish to convert and enough available funds to cover the transaction fees. -- An asset registered on Asset Hub that you want to convert. If you haven't created an asset on Asset Hub yet, refer to the [Register a Local Asset](/chain-interactions/token-operations/register-local-asset/){target=\_blank} or [Register a Foreign Asset](/chain-interactions/token-operations/register-foreign-asset/){target=\_blank} documentation to create an asset. - -## Create a Liquidity Pool - -If an asset on Asset Hub does not have an existing liquidity pool, the first step is to create one. - -The asset conversion pallet provides the `createPool` extrinsic to create a new liquidity pool, creating an empty liquidity pool and a new `LP token` asset. - -!!! tip - A testing token with the asset ID `1112` and the name `PPM` was created for this example. - -As stated in the [Test Environment Setup](#test-environment-setup) section, this tutorial is based on the assumption that you have an instance of Polkadot Asset Hub running locally. Therefore, the demo liquidity pool will be created between DOT and PPM tokens. However, the same steps can be applied to any other asset on Asset Hub. - -From the Asset Hub perspective, the Multilocation that identifies the PPM token is the following: - -```javascript -{ - parents: 0, - interior: { - X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }] - } -} -``` - -The `PalletInstance` value of `50` represents the Assets pallet on Asset Hub. The `GeneralIndex` value of `1112` is the PPM asset's asset ID. - -To create the liquidity pool, you can follow these steps: - -1. Navigate to the **Extrinsics** section on the Polkadot.js Apps interface: - - 1. Select **Developer** from the top menu. - 2. Click on **Extrinsics** from the dropdown menu. - - ![Extrinsics Section](/images/chain-interactions/token-operations/convert-assets/convert-assets-01.webp) - -2. Select extrinsic to create the pool: - - 1. Select the **`AssetConversion`** pallet. - 2. Choose the **`createPool`** extrinsic from the list of available extrinsics. - - ![Create Pool Extrinsic](/images/chain-interactions/token-operations/convert-assets/convert-assets-02.webp) - -3. Fill in the required fields: - - 1. **`asset1`**: The Multilocation of the first asset in the pool. In this case, it is the DOT token, which the following Multilocation represents. - - ```javascript - { - parents: 0, - interior: 'Here' - } - ``` - - 2. **`asset2`**: The second asset's Multilocation within the pool. This refers to the PPM token, which the following Multilocation identifies. - - ```javascript - { - parents: 0, - interior: { - X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }] - } - } - ``` - - 3. Click on **Submit Transaction** to create the liquidity pool. - - ![Create Pool Fields](/images/chain-interactions/token-operations/convert-assets/convert-assets-03.webp) - -Signing and submitting the transaction triggers the creation of the liquidity pool. To verify the new pool's creation, check the **Explorer** section on the Polkadot.js Apps interface and ensure that the **`PoolCreated`** event was emitted. - -![Pool Created Event](/images/chain-interactions/token-operations/convert-assets/convert-assets-04.webp) - -As the preceding image shows, the **`lpToken`** ID created for this pool is 19. This ID is essential to identify the liquidity pool and associated LP tokens. - -## Add Liquidity to a Pool - -The `addLiquidity` extrinsic allows users to provide liquidity to a pool of two assets. Users specify their preferred amounts for both assets and minimum acceptable quantities. The function determines the best asset contribution, which may vary from the amounts desired but won't fall below the specified minimums. Providers receive liquidity tokens representing their pool portion in return for their contribution. - -To add liquidity to a pool, follow these steps: - -1. Navigate to the **Extrinsics** section on the Polkadot.js Apps interface: - - 1. Select **Developer** from the top menu. - 2. Click on **Extrinsics** from the dropdown menu. - - ![Extrinsics Section](/images/chain-interactions/token-operations/convert-assets/convert-assets-01.webp) - -2. Select extrinsic to add liqudity: - - 1. Select the **`assetConversion`** pallet. - 2. Choose the **`addLiquidity`** extrinsic from the list of available extrinsics. - - ![Add Liquidity Extrinsic](/images/chain-interactions/token-operations/convert-assets/convert-assets-05.webp) - -3. Fill in the required fields: - - 1. **`asset1`**: The Multilocation of the first asset in the pool. In this case, it is the DOT token, which the following Multilocation represents. - - ```javascript - { - parents: 0, - interior: 'Here' - } - ``` - - 2. **`asset2`**: The second asset's Multilocation within the pool. This refers to the PPM token, which the following Multilocation identifies. - - ```javascript - { - parents: 0, - interior: { - X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }] - } - } - ``` - - 3. **`amount1Desired`**: The amount of the first asset that will be contributed to the pool. - 4. **`amount2Desired`**: The quantity of the second asset intended for pool contribution. - 5. **`amount1Min`**: The minimum amount of the first asset that will be contributed. - 6. **`amount2Min`**: The lowest acceptable quantity of the second asset for contribution. - 7. **`mintTo`**: The account to which the liquidity tokens will be minted. - 8. Click on **Submit Transaction** to add liquidity to the pool. - - ![Add Liquidity Fields](/images/chain-interactions/token-operations/convert-assets/convert-assets-06.webp) - - !!! warning - Ensure that the appropriate amount of tokens provided has been minted previously and is available in your account before adding liquidity to the pool. - - In this case, the liquidity provided to the pool is between DOT tokens and PPM tokens with the asset ID 1112 on Polkadot Asset Hub. The intention is to provide liquidity for 1 DOT token (`u128` value of 1000000000000 as it has 10 decimals) and 1 PPM token (`u128` value of 1000000000000 as it also has 10 decimals). - -Signing and submitting the transaction adds liquidity to the pool. To verify the liquidity addition, check the **Explorer** section on the Polkadot.js Apps interface and ensure that the **`LiquidityAdded`** event was emitted. - -![Liquidity Added Event](/images/chain-interactions/token-operations/convert-assets/convert-assets-07.webp) - -## Swap Assets - -### Swap from an Exact Amount of Tokens - -The asset conversion pallet enables users to exchange a specific quantity of one asset for another in a designated liquidity pool by swapping them for an exact amount of tokens. It guarantees the user will receive at least a predetermined minimum amount of the second asset. This function increases trading predictability and allows users to conduct asset exchanges with confidence that they are assured a minimum return. - -To swap assets for an exact amount of tokens, follow these steps: - -1. Navigate to the **Extrinsics** section on the Polkadot.js Apps interface: - - 1. Select **Developer** from the top menu. - 2. Click on **Extrinsics** from the dropdown menu. - - ![Extrinsics Section](/images/chain-interactions/token-operations/convert-assets/convert-assets-01.webp) - -2. Select extrinsic to swap assets: - - 1. Select the **`AssetConversion`** pallet. - 2. Choose the **`swapExactTokensForTokens`** extrinsic from the list of available extrinsics. - - ![Swap From Exact Tokens Extrinsic](/images/chain-interactions/token-operations/convert-assets/convert-assets-08.webp) - -3. Fill in the required fields: - - 1. **`path: Vec`**: An array of Multilocations representing the path of the swap. The first and last elements of the array are the input and output assets, respectively. In this case, the path consists of two elements: - - - **`0: StagingXcmV3MultiLocation`**: The Multilocation of the first asset in the pool. In this case, it is the DOT token, which the following Multilocation represents. - - ```javascript - { - parents: 0, - interior: 'Here' - } - ``` - - - **`1: StagingXcmV3MultiLocation`**: The second asset's Multilocation within the pool. This refers to the PPM token, which the following Multilocation identifies. - - ```javascript - { - parents: 0, - interior: { - X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }] - } - } - ``` - - 2. **`amountOut`**: The exact amount of the second asset that the user wants to receive. - 3. **`amountInMax`**: The maximum amount of the first asset that the user is willing to swap. - 4. **`sendTo`**: The account to which the swapped assets will be sent. - 5. **`keepAlive`**: A boolean value that determines whether the pool should be kept alive after the swap. - 6. Click on **Submit Transaction** to swap assets for an exact amount of tokens. - - ![Swap For Exact Tokens Fields](/images/chain-interactions/token-operations/convert-assets/convert-assets-09.webp) - - !!! warning - Ensure that the appropriate amount of tokens provided has been minted previously and is available in your account before adding liquidity to the pool. - - In this case, the intention is to swap 0.01 DOT token (u128 value of 100000000000 as it has 10 decimals) for 0.04 PPM token (u128 value of 400000000000 as it also has 10 decimals). - -Signing and submitting the transaction will execute the swap. To verify execution, check the **Explorer** section on the Polkadot.js Apps interface and make sure that the **`SwapExecuted`** event was emitted. - -![Swap From Exact Tokens Event](/images/chain-interactions/token-operations/convert-assets/convert-assets-10.webp) - -### Swap to an Exact Amount of Tokens - -Conversely, the Asset Conversion pallet comes with a function that allows users to trade a variable amount of one asset to acquire a precise quantity of another. It ensures that users stay within a set maximum of the initial asset to obtain the desired amount of the second asset. This provides a method to control transaction costs while achieving the intended result. - -To swap assets for an exact amount of tokens, follow these steps: - -1. Navigate to the **Extrinsics** section on the Polkadot.js Apps interface: - - 1. Select **Developer** from the top menu. - 2. Click on **Extrinsics** from the dropdown menu. - - ![Extrinsics Section](/images/chain-interactions/token-operations/convert-assets/convert-assets-01.webp) - -2. Select extrinsic to swap tokens: - - 1. Select the **`AssetConversion`** pallet. - 2. Choose the **`swapTokensForExactTokens`** extrinsic from the list of available extrinsics. - - ![Swap Tokens For Exact Tokens Extrinsic](/images/chain-interactions/token-operations/convert-assets/convert-assets-11.webp) - -3. Fill in the required fields: - - 1. **`path: Vec`**: An array of Multilocations representing the path of the swap. The first and last elements of the array are the input and output assets, respectively. In this case, the path consists of two elements: - - **`0: StagingXcmV3MultiLocation`**: The Multilocation of the first asset in the pool. In this case, it is the PPM token, which the following Multilocation represents. - - ```javascript - { - parents: 0, - interior: { - X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }] - } - } - ``` - - - **`1: StagingXcmV3MultiLocation`**: The second asset's Multilocation within the pool. This refers to the DOT token, which the following Multilocation identifies. - - ```javascript - { - parents: 0, - interior: 'Here' - } - ``` - - 2. **`amountOut`**: The exact amount of the second asset that the user wants to receive. - 3. **`amountInMax`**: The maximum amount of the first asset that the user is willing to swap. - 4. **`sendTo`**: The account to which the swapped assets will be sent. - 5. **`keepAlive`**: A boolean value that determines whether the pool should be kept alive after the swap. - 6. Click on **Submit Transaction** to swap assets for an exact amount of tokens. - - ![Swap Tokens For Exact Tokens Fields](/images/chain-interactions/token-operations/convert-assets/convert-assets-12.webp) - - !!! warning - Before swapping assets, ensure that the tokens provided have been minted previously and are available in your account. - - In this case, the intention is to swap 0.01 DOT token (`u128` value of 100000000000 as it has ten decimals) for 0.04 PPM token (`u128` value of 400000000000 as it also has ten decimals). - -Signing and submitting the transaction will execute the swap. To verify execution, check the **Explorer** section on the Polkadot.js Apps interface and make sure that the **`SwapExecuted`** event was emitted. - -![Swap Tokens For Exact Tokens Event](/images/chain-interactions/token-operations/convert-assets/convert-assets-13.webp) - -## Withdraw Liquidity from a Pool - -The Asset Conversion pallet provides the `removeLiquidity` extrinsic to remove liquidity from a pool. This function allows users to withdraw the liquidity they offered from a pool, returning the original assets. When calling this function, users specify the number of liquidity tokens (representing their share in the pool) they wish to burn. They also set minimum acceptable amounts for the assets they expect to receive back. This mechanism ensures that users can control the minimum value they receive, protecting against unfavorable price movements during the withdrawal process. - -To withdraw liquidity from a pool, follow these steps: - -1. Navigate to the **Extrinsics** section on the Polkadot.js Apps interface: - - 1. Select **Developer** from the top menu. - 2. Click on **Extrinsics** from the dropdown menu. - - ![Extrinsics Section](/images/chain-interactions/token-operations/convert-assets/convert-assets-01.webp) - -2. Select extrinsic to withdraw liqudity from a pool: - - 1. Select the **`AssetConversion`** pallet. - 2. Choose the **`removeLiquidity`** extrinsic from the list of available extrinsics. - - ![Remove Liquidity Extrinsic](/images/chain-interactions/token-operations/convert-assets/convert-assets-14.webp) - -3. Fill in the required fields: - - 1. **`asset1`**: The Multilocation of the first asset in the pool. In this case, it is the DOT token, which the following Multilocation represents. - - ```javascript - { - parents: 0, - interior: 'Here' - } - ``` - - 2. **`asset2`**: The second asset's Multilocation within the pool. This refers to the PPM token, which the following Multilocation identifies. - - ```javascript - { - parents: 0, - interior: { - X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }] - } - } - ``` - - 3. **`lpTokenBurn`**: The number of liquidity tokens to burn. - 4. **`amount1MinReceived`**: The minimum amount of the first asset that the user expects to receive. - 5. **`amount2MinReceived`**: The minimum quantity of the second asset the user expects to receive. - 6. **`withdrawTo`**: The account to which the withdrawn assets will be sent. - 7. Click on **Submit Transaction** to withdraw liquidity from the pool. - - ![Remove Liquidity Fields](/images/chain-interactions/token-operations/convert-assets/convert-assets-15.webp) - - !!! warning - Ensure that the tokens provided have been minted previously and are available in your account before withdrawing liquidity from the pool. - - In this case, the intention is to withdraw 0.05 liquidity tokens from the pool, expecting to receive 0.004 DOT token (`u128` value of 40000000000 as it has 10 decimals) and 0.04 PPM token (`u128` value of 400000000000 as it also has 10 decimals). - -Signing and submitting the transaction will initiate the withdrawal of liquidity from the pool. To verify the withdrawal, check the **Explorer** section on the Polkadot.js Apps interface and ensure that the **`LiquidityRemoved`** event was emitted. - -![Remove Liquidity Event](/images/chain-interactions/token-operations/convert-assets/convert-assets-16.webp) - -## Test Environment Setup - -To test the Asset Conversion pallet, you can set up a local test environment to simulate different scenarios. This guide uses Chopsticks to spin up an instance of Polkadot Asset Hub. For further details on using Chopsticks, please refer to the [Chopsticks documentation](/develop/toolkit/parachains/fork-chains/chopsticks/get-started){target=\_blank}. - -To set up a local test environment, execute the following command: - -```bash -npx @acala-network/chopsticks \ ---config=https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/polkadot-asset-hub.yml -``` - -This command initiates a lazy fork of Polkadot Asset Hub, including the most recent block information from the network. For Kusama Asset Hub testing, simply switch out `polkadot-asset-hub.yml` with `kusama-asset-hub.yml` in the command. - -You now have a local Asset Hub instance up and running, ready for you to test various asset conversion procedures. The process here mirrors what you'd do on MainNet. After completing a transaction on TestNet, you can apply the same steps to convert assets on MainNet. diff --git a/.ai/pages/chain-interactions-token-operations-register-foreign-asset.md b/.ai/pages/chain-interactions-token-operations-register-foreign-asset.md deleted file mode 100644 index 17a11089b..000000000 --- a/.ai/pages/chain-interactions-token-operations-register-foreign-asset.md +++ /dev/null @@ -1,139 +0,0 @@ ---- -title: Register a Foreign Asset on Asset Hub -description: An in-depth guide to registering a foreign asset on the Asset Hub parachain, providing clear, step-by-step instructions. -categories: dApps -url: https://docs.polkadot.com/chain-interactions/token-operations/register-foreign-asset/ ---- - -# Register a Foreign Asset on Asset Hub - -## Introduction - -As outlined in the [Asset Hub Overview](/polkadot-protocol/architecture/system-chains/asset-hub){target=\_blank}, Asset Hub supports two categories of assets: local and foreign. Local assets are created on the Asset Hub system parachain and are identified by integer IDs. On the other hand, foreign assets, which originate outside of Asset Hub, are recognized by [Multilocations](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#7-universal-consensus-location-identifiers){target=\_blank}. - -When registering a foreign asset on Asset Hub, it's essential to notice that the process involves communication between two parachains. The Asset Hub parachain will be the destination of the foreign asset, while the source parachain will be the origin of the asset. The communication between the two parachains is facilitated by the [Cross-Chain Message Passing (XCMP)](/parachains/interoperability/get-started/){target=\_blank} protocol. - -This guide will take you through the process of registering a foreign asset on the Asset Hub parachain. - -## Prerequisites - -The Asset Hub parachain is one of the system parachains on a relay chain, such as [Polkadot](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fpolkadot.api.onfinality.io%2Fpublic-ws#/explorer){target=\_blank} or [Kusama](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fkusama.api.onfinality.io%2Fpublic-ws#/explorer){target=\_blank}. To interact with these parachains, you can use the [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank} interface for: - -- [Polkadot Asset Hub](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fasset-hub-polkadot-rpc.dwellir.com#/explorer){target=\_blank} -- [Kusama Asset Hub](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fsys.ibp.network%2Fstatemine#/explorer){target=\_blank} - -For testing purposes, you can also interact with the Asset Hub instance on the following test networks: - -- [Paseo Asset Hub](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fpas-rpc.stakeworld.io%2Fassethub#/explorer){target=\_blank} - -Before you start, ensure that you have: - -- Access to the Polkadot.js Apps interface, and you are connected to the desired chain. -- A parachain that supports the XCMP protocol to interact with the Asset Hub parachain. -- A funded wallet to pay for the transaction fees and subsequent registration of the foreign asset. - -This guide will use Polkadot, its local Asset Hub instance, and the [Astar](https://astar.network/){target=\_blank} parachain (`ID` 2006), as stated in the [Test Environment Setup](#test-environment-setup) section. However, the process is the same for other relay chains and their respective Asset Hub parachain, regardless of the network you are using and the parachain owner of the foreign asset. - -## Steps to Register a Foreign Asset - -### Asset Hub - -1. Open the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and connect to the Asset Hub parachain using the network selector in the top left corner. - - - Testing foreign asset registration is recommended on TestNet before proceeding to MainNet. If you haven't set up a local testing environment yet, consult the [Environment setup](#test-environment-setup) guide. After setting up, connect to the Local Node (Chopsticks) at `ws://127.0.0.1:8000`. - - For live network operations, connect to the Asset Hub parachain. You can choose either Polkadot or Kusama Asset Hub from the dropdown menu, selecting your preferred RPC provider. - -2. Navigate to the **Extrinsics** page: - - 1. Click on the **Developer** tab from the top navigation bar. - 2. Select **Extrinsics** from the dropdown. - - ![Access to Developer Extrinsics section](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-01.webp) - -3. Select the Foreign Assets pallet: - - 3. Select the **`foreignAssets`** pallet from the dropdown list. - 4. Choose the **`create`** extrinsic. - - ![Select the Foreign Asset pallet](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-02.webp) - -3. Fill out the required fields and click on the copy icon to copy the **encoded call data** to your clipboard. The fields to be filled are: - - - **id**: As this is a foreign asset, the ID will be represented by a Multilocation that reflects its origin. For this case, the Multilocation of the asset will be from the source parachain perspective. - - ```javascript - { parents: 1, interior: { X1: [{ Parachain: 2006 }] } } - ``` - - - **admin**: Refers to the account that will be the admin of this asset. This account will be able to manage the asset, including updating its metadata. As the registered asset corresponds to a native asset of the source parachain, the admin account should be the sovereign account of the source parachain. - - The sovereign account can be obtained through [Substrate Utilities](https://www.shawntabrizi.com/substrate-js-utilities/){target=\_blank}. - - Ensure that **Sibling** is selected and that the **Para ID** corresponds to the source parachain. In this case, since the guide follows the test setup stated in the [Test Environment Setup](#test-environment-setup) section, the **Para ID** is `2006`. - - ![Get parachain sovereign account](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-03.webp) - - - - **`minBalance`**: The minimum balance required to hold this asset. - - ![Fill out the required fields](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-04.webp) - - !!! tip - If you need an example of the encoded call data, you can copy the following: - ``` - 0x3500010100591f007369626cd6070000000000000000000000000000000000000000000000000000a0860100000000000000000000000000 - ``` - -### Source Parachain - -1. Navigate to the **Developer > Extrinsics** section. -2. Create the extrinsic to register the foreign asset through XCM: - - 1. Paste the **encoded call data** copied in the previous step. - 2. Click the **Submit Transaction** button. - - ![Register foreign asset through XCM](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-05.webp) - - This XCM call involves withdrawing DOT from the sibling account of the parachain, using it to initiate an execution. The transaction will be carried out with XCM as the origin kind, and will be a hex-encoded call to create a foreign asset on Asset Hub for the specified parachain asset multilocation. Any surplus will be refunded, and the asset will be deposited into the sibling account. - - !!! warning - Note that the sovereign account on the Asset Hub parachain must have a sufficient balance to cover the XCM `BuyExecution` instruction. If the account does not have enough balance, the transaction will fail. - - If you want to have the whole XCM call ready to be copied, go to the **Developer > Extrinsics > Decode** section and paste the following hex-encoded call data: - - ```text - 0x6300330003010100a10f030c000400010000070010a5d4e81300010000070010a5d4e80006030700b4f13501419ce03500010100591f007369626cd607000000000000000000000000000000000000000000000000000000000000000000000000000000000000 - ``` - - Be sure to replace the encoded call data with the one you copied in the previous step. - -After the transaction is successfully executed, the foreign asset will be registered on the Asset Hub parachain. - -## Asset Registration Verification - -To confirm that a foreign asset has been successfully accepted and registered on the Asset Hub parachain, you can navigate to the `Network > Explorer` section of the Polkadot.js Apps interface for Asset Hub. You should be able to see an event that includes the following details: - -![Asset registration event](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-06.webp) - -In the image above, the **success** field indicates whether the asset registration was successful. - -## Test Environment Setup - -To test the foreign asset registration process before deploying it on a live network, you can set up a local parachain environment. This guide uses Chopsticks to simulate that process. For more information on using Chopsticks, please refer to the [Chopsticks documentation](/develop/toolkit/parachains/fork-chains/chopsticks/get-started){target=\_blank}. - -To set up a test environment, run the following command: - -```bash -npx @acala-network/chopsticks xcm \ ---r polkadot \ ---p polkadot-asset-hub \ ---p astar -``` - -The preceding command will create a lazy fork of Polkadot as the relay chain, its Asset Hub instance, and the Astar parachain. The `xcm` parameter enables communication through the XCMP protocol between the relay chain and the parachains, allowing the registration of foreign assets on Asset Hub. For further information on the chopsticks usage of the XCMP protocol, refer to the [XCM Testing](/tutorials/polkadot-sdk/testing/fork-live-chains/#xcm-testing){target=\_blank} section of the Chopsticks documentation. - -After executing the command, the terminal will display output indicating the Polkadot relay chain, the Polkadot Asset Hub, and the Astar parachain are running locally and connected through XCM. You can access them individually via the Polkadot.js Apps interface. - -- [Polkadot Relay Chain](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Flocalhost%3A8002#/explorer){target=\_blank} -- [Polkadot Asset Hub](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Flocalhost%3A8000#/explorer){target=\_blank} -- [Astar Parachain](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Flocalhost%3A8001#/explorer){target=\_blank} diff --git a/.ai/pages/chain-interactions-token-operations-register-local-asset.md b/.ai/pages/chain-interactions-token-operations-register-local-asset.md deleted file mode 100644 index 0f257f3e2..000000000 --- a/.ai/pages/chain-interactions-token-operations-register-local-asset.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: Register a Local Asset -description: Comprehensive guide to registering a local asset on the Asset Hub system parachain, including step-by-step instructions. -categories: Basics, dApps -url: https://docs.polkadot.com/chain-interactions/token-operations/register-local-asset/ ---- - -# Register a Local Asset on Asset Hub - -## Introduction - -As detailed in the [Asset Hub Overview](/polkadot-protocol/architecture/system-chains/asset-hub){target=\_blank} page, Asset Hub accommodates two types of assets: local and foreign. Local assets are those that were created in Asset Hub and are identifiable by an integer ID. On the other hand, foreign assets originate from a sibling parachain and are identified by a Multilocation. - -This guide will take you through the steps of registering a local asset on the Asset Hub parachain. - -## Prerequisites - -Before you begin, ensure you have access to the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and a funded wallet with DOT or KSM. - -- For Polkadot Asset Hub, you would need a deposit of 10 DOT and around 0.201 DOT for the metadata. -- For Kusama Asset Hub, the deposit is 0.1 KSM and around 0.000669 KSM for the metadata. - -You need to ensure that your Asset Hub account balance is a bit more than the sum of those two deposits, which should seamlessly account for the required deposits and transaction fees. - -## Steps to Register a Local Asset - -To register a local asset on the Asset Hub parachain, follow these steps: - -1. Open the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank} interface and connect to the Asset Hub parachain using the network selector in the top left corner. - - - You may prefer to test local asset registration on TestNet before registering the asset on a MainNet hub. If you still need to set up a local testing environment, review the [Environment setup](#test-setup-environment) section for instructions. Once the local environment is set up, connect to the Local Node (Chopsticks) available on `ws://127.0.0.1:8000`. - - For the live network, connect to the **Asset Hub** parachain. Either Polkadot or Kusama Asset Hub can be selected from the dropdown list, choosing the desired RPC provider. - -2. Click on the **Network** tab on the top navigation bar and select **Assets** from the dropdown list. - - ![Access to Asset Hub through Polkadot.JS](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-01.webp) - -3. Now, you need to examine all the registered asset IDs. This step is crucial to ensure that the asset ID you are about to register is unique. Asset IDs are displayed in the **assets** column. - - ![Asset IDs on Asset Hub](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-02.webp) - -4. Once you have confirmed that the asset ID is unique, click on the **Create** button on the top right corner of the page. - - ![Create a new asset](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-03.webp) - -5. Fill in the required fields in the **Create Asset** form: - - 1. **creator account**: The account to be used for creating this asset and setting up the initial metadata. - 2. **asset name**: The descriptive name of the asset you are registering. - 3. **asset symbol**: The symbol that will be used to represent the asset. - 4. **asset decimals**: The number of decimal places for this token, with a maximum of 20 allowed through the user interface. - 5. **minimum balance**: The minimum balance for the asset. This is specified in the units and decimals as requested. - 6. **asset ID**: The selected id for the asset. This should not match an already-existing asset id. - 7. Click on the **Next** button. - - ![Create Asset Form](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-04.webp) - -6. Choose the accounts for the roles listed below: - - 1. **admin account**: The account designated for continuous administration of the token. - 2. **issuer account**: The account that will be used for issuing this token. - 3. **freezer account**: The account that will be used for performing token freezing operations. - 4. Click on the **Create** button. - - ![Admin, Issuer, Freezer accounts](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-05.webp) - -7. Click on the **Sign and Submit** button to complete the asset registration process. - - ![Sign and Submit](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-06.webp) - -## Verify Asset Registration - -After completing these steps, the asset will be successfully registered. You can now view your asset listed on the [**Assets**](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fasset-hub-polkadot-rpc.dwellir.com#/assets){target=\_blank} section of the Polkadot.js Apps interface. - -![Asset listed on Polkadot.js Apps](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-07.webp) - -!!! tip - Take into consideration that the **Assets** section’s link may differ depending on the network you are using. For the local environment, enter `ws://127.0.0.1:8000` into the **Custom Endpoint** field. - -In this way, you have successfully registered a local asset on the Asset Hub parachain. - -For an in-depth explanation about Asset Hub and its features, see the [Asset Hub](/chain-interactions/token-operations/convert-assets/){target=\_blank} entry in the Polkadot Wiki. - -## Test Setup Environment - -You can set up a local parachain environment to test the asset registration process before deploying it on the live network. This guide uses Chopsticks to simulate that process. For further information on chopsticks usage, refer to the [Chopsticks](/develop/toolkit/parachains/fork-chains/chopsticks/get-started){target=\_blank} documentation. - -To set up a test environment, execute the following command: - -```bash -npx @acala-network/chopsticks \ ---config=https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/polkadot-asset-hub.yml -``` - -The above command will spawn a lazy fork of Polkadot Asset Hub with the latest block data from the network. If you need to test Kusama Asset Hub, replace `polkadot-asset-hub.yml` with `kusama-asset-hub.yml` in the command. - -An Asset Hub instance is now running locally, and you can proceed with the asset registration process. Note that the local registration process does not differ from the live network process. Once you have a successful TestNet transaction, you can use the same steps to register the asset on MainNet. diff --git a/.ai/pages/chain-interactions.md b/.ai/pages/chain-interactions.md deleted file mode 100644 index dfb4dde67..000000000 --- a/.ai/pages/chain-interactions.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Chain Interactions Overview -description: Learn how to query data, send transactions, enable cross-chain communication, and manage accounts across the Polkadot ecosystem. -categories: Chain Interactions -url: https://docs.polkadot.com/chain-interactions/ ---- - -# Chain Interactions - -## Introduction - -Chain interactions form the foundation of building applications on Polkadot. Whether you're querying on-chain data, executing transactions, enabling cross-chain communication, or managing accounts, understanding how to interact with Polkadot-based chains is essential for application developers. - -This section provides comprehensive guidance on the various ways to interact with Polkadot chains, from basic queries to complex cross-chain operations. You'll learn how to: - -- Query on-chain state and subscribe to blockchain events. -- Send transactions and manage their lifecycle. -- Enable interoperability between parachains through XCM. -- Manage tokens and perform token operations. -- Create and manage accounts programmatically. - -Whether you're building a frontend application, a backend service, or integrating with the Polkadot ecosystem, these guides will equip you with the knowledge and tools to effectively interact with chains across the network. - -## Core Interaction Patterns - -### Query On-Chain Data - -Accessing blockchain state is fundamental to building responsive applications. Polkadot offers several methods to query on-chain data, each suited for different use cases. - -- **[SDK integration](/chain-interactions/query-data/query-sdks/)**: Programmatically read blockchain state using: - - - [Polkadot API (PAPI)](/reference/tools/papi/) - - [Polkadot.js](/reference/tools/polkadot-js-api/) - - [Dedot](/reference/tools/dedot/) - - [Python Substrate Interface](/reference/tools/py-substrate-interface/) - - [Subxt](/reference/tools/subxt/) - -- **[REST API access](/chain-interactions/query-data/query-rest/)**: Query chain data through standardized REST endpoints for simpler integration. -- **[Runtime API calls](/chain-interactions/query-data/runtime-api-calls/)**: Execute runtime APIs directly for specialized queries and operations. - -### Send Transactions - -Transactions are the primary mechanism for modifying blockchain state. Understanding transaction construction, signing, and submission is crucial for building interactive applications. - -- **[Transaction construction](/chain-interactions/send-transactions/with-sdks/)**: Build transactions using various SDKs with proper encoding and formatting. -- **[Fee estimation](/chain-interactions/send-transactions/calculate-transaction-fees/)**: Calculate transaction fees to ensure sufficient balance and optimize costs. -- **[Multi-token fees](/chain-interactions/send-transactions/pay-fees-with-different-tokens/)**: Learn how to pay transaction fees with different tokens on supported chains. - -### Send Cross-Chain Transactions - -Polkadot enables native cross-chain capabilities through Cross-Consensus Messaging (XCM), allowing chains to securely communicate and transfer assets across the ecosystem. - -- **[Transfer assets between parachains](/chain-interactions/send-transactions/interoperability/transfer-assets-parachains/)**: Understand how to construct and send XCM messages using [ParaSpell XCM SDK](/reference/tools/paraspell/){target=\_blank} and [Polkadot API (PAPI)](/reference/tools/papi/){target=\_blank}. -- **[Transfer assets out of Polkadot](/chain-interactions/send-transactions/interoperability/transfer-assets-out-of-polkadot/)**: Connect to blockchains outside the Polkadot ecosystem using [Snowbridge](https://wiki.polkadot.com/learn/learn-snowbridge/){target=\_blank} and other bridge solutions. - -### Manage Tokens - -Polkadot Hub provides a unified platform for managing assets across the ecosystem. Understanding token operations is essential for DeFi applications and multi-chain asset management. - -- **[Local asset registration](/chain-interactions/token-operations/register-local-asset/)**: Learn how assets created in Asset Hub are registered on the network. -- **[Foregin asset registration](/chain-interactions/token-operations/register-foreign-asset/)**: Learn how assets created outside of Asset Hub are registered on the network. -- **[Convert assets](/chain-interactions/token-operations/convert-assets/)**: Convert, swap, and manage assets on-chain using the Asset Conversion pallet. -- **Asset Hub integration**: Interact with Polkadot's central asset management hub using [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\_blank}. - -### Manage Accounts - -Account management forms the basis of user identity and authentication in blockchain applications. Learn how to create, manage, and query accounts programmatically. - -- **[Account creation](/chain-interactions/accounts/create-account/)**: Generate accounts using various SDKs in Rust, Python, and JavaScript. -- **[Account queries](/chain-interactions/accounts/query-accounts/)**: Retrieve account information including balances, nonces, and metadata. - -## Development Tools and SDKs - -The Polkadot ecosystem offers a rich set of tools and libraries to facilitate chain interactions: - -- **[Polkadot API (PAPI)](/reference/tools/papi/)**: Modern, type-safe TypeScript library with full metadata support. -- **[Polkadot.js](/reference/tools/polkadot-js-api/)**: Comprehensive JavaScript library with extensive ecosystem support. -- **[Dedot](/reference/tools/dedot/)**: Lightweight TypeScript library optimized for performance. -- **[Python Substrate Interface](/reference/tools/py-substrate-interface/)**: Polkadot Substrate Interface for streamlined development. -- **[Subxt](/reference/tools/subxt/)**: Rust library for building robust substrate-based applications. -- **[Polkadot.js Apps](https://polkadot.js.org/apps/)**: Web-based interface for exploring and interacting with chains. - -Each tool has its strengths, and choosing the right one depends on your project requirements, programming language preference, and specific use cases. - -## Next Steps - -Explore the sections below to dive deeper into specific chain interaction patterns: - -- **[Query On-Chain Data](/chain-interactions/query-data/query-sdks/)**: Learn to read blockchain state efficiently. -- **[Send Transactions](/chain-interactions/send-transactions/with-sdks/)**: Master transaction construction and submission. -- **[Send Cross-Chain Transactions](/chain-interactions/send-transactions/interoperability/transfer-assets-parachains/)**: Enable cross-chain communication with XCM. -- **[Manage Tokens](/chain-interactions/token-operations/register-local-asset/)**: Manage assets across the Polkadot ecosystem. -- **[Manage Accounts](/chain-interactions/accounts/create-account/)**: Create and query accounts programmatically. - -Each section provides practical examples, code snippets, and comprehensive guides to help you build production-ready applications on Polkadot. diff --git a/.ai/pages/parachains-interoperability-get-started.md b/.ai/pages/parachains-interoperability-get-started.md index bb8008ceb..a7e59e626 100644 --- a/.ai/pages/parachains-interoperability-get-started.md +++ b/.ai/pages/parachains-interoperability-get-started.md @@ -1,11 +1,11 @@ --- -title: Introduction to XCM +title: Get Started with XCM description: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. categories: Basics, Polkadot Protocol url: https://docs.polkadot.com/parachains/interoperability/get-started/ --- -# Introduction to XCM +# Get Started with XCM ## Introduction diff --git a/.ai/pages/parachains-testing-fork-a-parachain.md b/.ai/pages/parachains-testing-fork-a-parachain.md index 6bb56dbff..73df0a187 100644 --- a/.ai/pages/parachains-testing-fork-a-parachain.md +++ b/.ai/pages/parachains-testing-fork-a-parachain.md @@ -1,11 +1,11 @@ --- -title: Get Started +title: Fork a Parachain Using Chopsticks description: Simplify Polkadot SDK development with Chopsticks. Learn essential features, how to install Chopsticks, and how to configure local blockchain forks. categories: Parachains, Tooling url: https://docs.polkadot.com/parachains/testing/fork-a-parachain/ --- -# Get Started +# Fork a Parachain Using Chopsticks ## Introduction diff --git a/.ai/pages/parachains-testing-run-a-parachain-network.md b/.ai/pages/parachains-testing-run-a-parachain-network.md index afc7dda6e..a922abdce 100644 --- a/.ai/pages/parachains-testing-run-a-parachain-network.md +++ b/.ai/pages/parachains-testing-run-a-parachain-network.md @@ -1,11 +1,11 @@ --- -title: Get Started +title: Run a Parachain Network description: Quickly install and configure Zombienet to deploy and test Polkadot-based blockchain networks with this comprehensive getting-started guide. categories: Parachains, Tooling url: https://docs.polkadot.com/parachains/testing/run-a-parachain-network/ --- -# Get Started +# Run a Parachain Network Using Zombienet ## Introduction diff --git a/.ai/pages/reference-glossary.md b/.ai/pages/reference-glossary.md deleted file mode 100644 index fc82d8bc8..000000000 --- a/.ai/pages/reference-glossary.md +++ /dev/null @@ -1,365 +0,0 @@ ---- -title: Glossary -description: Glossary of terms used within the Polkadot ecosystem, Polkadot SDK, its subsequent libraries, and other relevant Web3 terminology. -categories: Reference -url: https://docs.polkadot.com/reference/glossary/ ---- - -# Glossary - -Key definitions, concepts, and terminology specific to the Polkadot ecosystem are included here. - -Additional glossaries from around the ecosystem you might find helpful: - -- [Polkadot Wiki Glossary](https://wiki.polkadot.com/general/glossary){target=\_blank} -- [Polkadot SDK Glossary](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/glossary/index.html){target=\_blank} - -## Authority - -The role in a blockchain that can participate in consensus mechanisms. - -- **[GRANDPA](#grandpa)**: The authorities vote on chains they consider final. -- **[Blind Assignment of Blockchain Extension](#blind-assignment-of-blockchain-extension-babe) (BABE)**: The authorities are also [block authors](#block-author). - -Authority sets can be used as a basis for consensus mechanisms such as the [Nominated Proof of Stake (NPoS)](#nominated-proof-of-stake-npos) protocol. - -## Authority Round (Aura) - -A deterministic [consensus](#consensus) protocol where block production is limited to a rotating list of [authorities](#authority) that take turns creating blocks. In authority round (Aura) consensus, most online authorities are assumed to be honest. It is often used in combination with [GRANDPA](#grandpa) as a [hybrid consensus](#hybrid-consensus) protocol. - -Learn more by reading the official [Aura consensus algorithm](https://openethereum.github.io/Aura){target=\_blank} wiki article. - -## Blind Assignment of Blockchain Extension (BABE) - -A [block authoring](#block-author) protocol similar to [Aura](#authority-round-aura), except [authorities](#authority) win [slots](#slot) based on a Verifiable Random Function (VRF) instead of the round-robin selection method. The winning authority can select a chain and submit a new block. - -Learn more by reading the official Web3 Foundation [BABE research document](https://research.web3.foundation/Polkadot/protocols/block-production/Babe){target=\_blank}. - -## Block Author - -The node responsible for the creation of a block, also called _block producers_. In a Proof of Work (PoW) blockchain, these nodes are called _miners_. - -## Byzantine Fault Tolerance (BFT) - -The ability of a distributed computer network to remain operational if a certain proportion of its nodes or [authorities](#authority) are defective or behaving maliciously. A distributed network is typically considered Byzantine fault tolerant if it can remain functional, with up to one-third of nodes assumed to be defective, offline, actively malicious, and part of a coordinated attack. - -### Byzantine Failure - -The loss of a network service due to node failures that exceed the proportion of nodes required to reach consensus. - -### Practical Byzantine Fault Tolerance (pBFT) - -An early approach to Byzantine fault tolerance (BFT), practical Byzantine fault tolerance (pBFT) systems tolerate Byzantine behavior from up to one-third of participants. - -The communication overhead for such systems is `O(n²)`, where `n` is the number of nodes (participants) in the system. - -### Preimage - -A preimage is the data that is input into a hash function to calculate a hash. Since a hash function is a [one-way function](https://en.wikipedia.org/wiki/One-way_function){target=\_blank}, the output, the hash, cannot be used to reveal the input, the preimage. - -## Call - -In the context of pallets containing functions to be dispatched to the runtime, `Call` is an enumeration data type that describes the functions that can be dispatched with one variant per pallet. A `Call` represents a [dispatch](#dispatchable) data structure object. - -## Chain Specification - -A chain specification file defines the properties required to run a node in an active or new Polkadot SDK-built network. It often contains the initial genesis runtime code, network properties (such as the network's name), the initial state for some pallets, and the boot node list. The chain specification file makes it easy to use a single Polkadot SDK codebase as the foundation for multiple independently configured chains. - -## Collator - -An [author](#block-author) of a [parachain](#parachain) network. -They aren't [authorities](#authority) in themselves, as they require a [relay chain](#relay-chain) to coordinate [consensus](#consensus). - -More details are found on the [Polkadot Collator Wiki](https://wiki.polkadot.com/learn/learn-collator/){target=\_blank}. - -## Collective - -Most often used to refer to an instance of the Collective pallet on Polkadot SDK-based networks such as [Kusama](#kusama) or [Polkadot](#polkadot) if the Collective pallet is part of the FRAME-based runtime for the network. - -## Consensus - -Consensus is the process blockchain nodes use to agree on a chain's canonical fork. It is composed of [authorship](#block-author), finality, and [fork-choice rule](#fork-choice-rulestrategy). In the Polkadot ecosystem, these three components are usually separate and the term consensus often refers specifically to authorship. - -See also [hybrid consensus](#hybrid-consensus). - -## Consensus Algorithm - -Ensures a set of [actors](#authority)—who don't necessarily trust each other—can reach an agreement about the state as the result of some computation. Most consensus algorithms assume that up to one-third of the actors or nodes can be [Byzantine fault tolerant](#byzantine-fault-tolerance-bft). - -Consensus algorithms are generally concerned with ensuring two properties: - -- **Safety**: Indicating that all honest nodes eventually agreed on the state of the chain. -- **Liveness**: Indicating the ability of the chain to keep progressing. - -## Consensus Engine - -The node subsystem responsible for consensus tasks. - -For detailed information about the consensus strategies of the [Polkadot](#polkadot) network, see the [Polkadot Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} blog series. - -See also [hybrid consensus](#hybrid-consensus). - -## Coretime - -The time allocated for utilizing a core, measured in relay chain blocks. There are two types of coretime: *on-demand* and *bulk*. - -On-demand coretime refers to coretime acquired through bidding in near real-time for the validation of a single parachain block on one of the cores reserved specifically for on-demand orders. They are available as an on-demand coretime pool. Set of cores that are available on-demand. Cores reserved through bulk coretime could also be made available in the on-demand coretime pool, in parts or in entirety. - -Bulk coretime is a fixed duration of continuous coretime represented by an NFT that can be split, shared, or resold. It is managed by the [Broker pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_broker/index.html){target=\_blank}. - -## Development Phrase - -A [mnemonic phrase](https://en.wikipedia.org/wiki/Mnemonic#For_numerical_sequences_and_mathematical_operations){target=\_blank} that is intentionally made public. - -Well-known development accounts, such as Alice, Bob, Charlie, Dave, Eve, and Ferdie, are generated from the same secret phrase: - -``` -bottom drive obey lake curtain smoke basket hold race lonely fit walk -``` - -Many tools in the Polkadot SDK ecosystem, such as [`subkey`](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/bin/utils/subkey){target=\_blank}, allow you to implicitly specify an account using a derivation path such as `//Alice`. - -## Digest - -An extensible field of the [block header](#header) that encodes information needed by several actors in a blockchain network, including: - -- [Light clients](#light-client) for chain synchronization. -- Consensus engines for block verification. -- The runtime itself, in the case of pre-runtime digests. - -## Dispatchable - -Function objects that act as the entry points in FRAME [pallets](#pallet). Internal or external entities can call them to interact with the blockchain’s state. They are a core aspect of the runtime logic, handling [transactions](#transaction) and other state-changing operations. - -## Events - -A means of recording that some particular [state](#state) transition happened. - -In the context of [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities), events are composable data types that each [pallet](#pallet) can individually define. Events in FRAME are implemented as a set of transient storage items inspected immediately after a block has been executed and reset during block initialization. - -## Executor - -A means of executing a function call in a given [runtime](#runtime) with a set of dependencies. -There are two orchestration engines in Polkadot SDK, _WebAssembly_ and _native_. - -- The _native executor_ uses a natively compiled runtime embedded in the node to execute calls. This is a performance optimization available to up-to-date nodes. - -- The _WebAssembly executor_ uses a [Wasm](#webassembly-wasm) binary and a Wasm interpreter to execute calls. The binary is guaranteed to be up-to-date regardless of the version of the blockchain node because it is persisted in the [state](#state) of the Polkadot SDK-based chain. - -## Existential Deposit - -The minimum balance an account is allowed to have in the [Balances pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/index.html){target=\_blank}. Accounts cannot be created with a balance less than the existential deposit amount. - -If an account balance drops below this amount, the Balances pallet uses [a FRAME System API](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.dec_ref){target=\_blank} to drop its references to that account. - -If the Balances pallet reference to an account is dropped, the account can be [reaped](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.allow_death){target=\_blank}. - -## Extrinsic - -A general term for data that originates outside the runtime, is included in a block, and leads to some action. This includes user-initiated transactions and inherent transactions placed into the block by the block builder. - -It is a SCALE-encoded array typically consisting of a version number, signature, and varying data types indicating the resulting runtime function to be called. Extrinsics can take two forms: [inherents](#inherent-transactions) and [transactions](#transaction). - -For more technical details, see the [Polkadot spec](https://spec.polkadot.network/id-extrinsics){target=\_blank}. - -## Fork Choice Rule/Strategy - -A fork choice rule or strategy helps determine which chain is valid when reconciling several network forks. A common fork choice rule is the [longest chain](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/struct.LongestChain.html){target=\_blank}, in which the chain with the most blocks is selected. - -## FRAME (Framework for Runtime Aggregation of Modularized Entities) - -Enables developers to create blockchain [runtime](#runtime) environments from a modular set of components called [pallets](#pallet). It utilizes a set of procedural macros to construct runtimes. - -[Visit the Polkadot SDK docs for more details on FRAME.](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank} - -## Full Node - -A node that prunes historical states, keeping only recently finalized block states to reduce storage needs. Full nodes provide current chain state access and allow direct submission and validation of [extrinsics](#extrinsic), maintaining network decentralization. - -## Genesis Configuration - -A mechanism for specifying the initial state of a blockchain. By convention, this initial state or first block is commonly referred to as the genesis state or genesis block. The genesis configuration for Polkadot SDK-based chains is accomplished by way of a [chain specification](#chain-specification) file. - -## GRANDPA - -A deterministic finality mechanism for blockchains that is implemented in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. - -The [formal specification](https://github.com/w3f/consensus/blob/master/pdf/grandpa-old.pdf){target=\_blank} is maintained by the [Web3 Foundation](https://web3.foundation/){target=\_blank}. - -## Header - -A structure that aggregates the information used to summarize a block. Primarily, it consists of cryptographic information used by [light clients](#light-client) to get minimally secure but very efficient chain synchronization. - -## Hybrid Consensus - -A blockchain consensus protocol that consists of independent or loosely coupled mechanisms for [block production](#block-author) and finality. - -Hybrid consensus allows the chain to grow as fast as probabilistic consensus protocols, such as [Aura](#authority-round-aura), while maintaining the same level of security as deterministic finality consensus protocols, such as [GRANDPA](#grandpa). - -## Inherent Transactions - -A special type of unsigned transaction, referred to as _inherents_, that enables a block authoring node to insert information that doesn't require validation directly into a block. - -Only the block-authoring node that calls the inherent transaction function can insert data into its block. In general, validators assume the data inserted using an inherent transaction is valid and reasonable even if it can't be deterministically verified. - -## JSON-RPC - -A stateless, lightweight remote procedure call protocol encoded in JavaScript Object Notation (JSON). JSON-RPC provides a standard way to call functions on a remote system by using JSON. - -For Polkadot SDK, this protocol is implemented through the [Parity JSON-RPC](https://github.com/paritytech/jsonrpc){target=\_blank} crate. - -## Keystore - -A subsystem for managing keys for the purpose of producing new blocks. - -## Kusama - -[Kusama](https://kusama.network/){target=\_blank} is a Polkadot SDK-based blockchain that implements a design similar to the [Polkadot](#polkadot) network. - -Kusama is a [canary](https://en.wiktionary.org/wiki/canary_in_a_coal_mine){target=\_blank} network and is referred to as [Polkadot's "wild cousin."](https://wiki.polkadot.com/learn/learn-comparisons-kusama/){target=\_blank}. - -As a canary network, Kusama is expected to be more stable than a test network like [Westend](#westend) but less stable than a production network like [Polkadot](#polkadot). Kusama is controlled by its network participants and is intended to be stable enough to encourage meaningful experimentation. - -## libp2p - -A peer-to-peer networking stack that allows the use of many transport mechanisms, including WebSockets (usable in a web browser). - -Polkadot SDK uses the [Rust implementation](https://github.com/libp2p/rust-libp2p){target=\_blank} of the `libp2p` networking stack. - -## Light Client - -A type of blockchain node that doesn't store the [chain state](#state) or produce blocks. - -A light client can verify cryptographic primitives and provides a [remote procedure call (RPC)](https://en.wikipedia.org/wiki/Remote_procedure_call){target=\_blank} server, enabling blockchain users to interact with the network. - -## Metadata - -Data that provides information about one or more aspects of a system. -The metadata that exposes information about a Polkadot SDK blockchain enables you to interact with that system. - -## Nominated Proof of Stake (NPoS) - -A method for determining [validators](#validator) or _[authorities](#authority)_ based on a willingness to commit their stake to the proper functioning of one or more block-producing nodes. - -## Oracle - -An entity that connects a blockchain to a non-blockchain data source. Oracles enable the blockchain to access and act upon information from existing data sources and incorporate data from non-blockchain systems and services. - -## Origin - -A [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitive that identifies the source of a [dispatched](#dispatchable) function call into the [runtime](#runtime). The FRAME System pallet defines three built-in [origins](#origin). As a [pallet](#pallet) developer, you can also define custom origins, such as those defined by the [Collective pallet](https://paritytech.github.io/substrate/master/pallet_collective/enum.RawOrigin.html){target=\_blank}. - -## Pallet - -A module that can be used to extend the capabilities of a [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities)-based [runtime](#runtime). -Pallets bundle domain-specific logic with runtime primitives like [events](#events) and [storage items](#storage-item). - -## Parachain - -A parachain is a blockchain that derives shared infrastructure and security from a _[relay chain](#relay-chain)_. -You can learn more about parachains on the [Polkadot Wiki](https://wiki.polkadot.com/learn/learn-parachains/){target=\_blank}. - -## Paseo - -Paseo TestNet provisions testing on Polkadot's "production" runtime, which means less chance of feature or code mismatch when developing parachain apps. Specifically, after the [Polkadot Technical fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} proposes a runtime upgrade for Polkadot, this TestNet is updated, giving a period where the TestNet will be ahead of Polkadot to allow for testing. - -## Polkadot - -The [Polkadot network](https://polkadot.com/){target=\_blank} is a blockchain that serves as the central hub of a heterogeneous blockchain network. It serves the role of the [relay chain](#relay-chain) and provides shared infrastructure and security to support [parachains](#parachain). - -## Polkadot Cloud - -Polkadot Cloud is a platform for deploying resilient, customizable and scalable Web3 applications through Polkadot's functionality. It encompasses the wider Polkadot network infrastructure and security layer where parachains operate. The platform enables users to launch Ethereum-compatible chains, build specialized blockchains, and flexibly manage computing resources through on-demand or bulk coretime purchases. Initially launched with basic parachain functionality, Polkadot Cloud has evolved to offer enhanced flexibility with features like coretime, elastic scaling, and async backing for improved performance. - -## Polkadot Hub - -Polkadot Hub is a Layer 1 platform that serves as the primary entry point to the Polkadot ecosystem, providing essential functionality without requiring parachain deployment. It offers core services including smart contracts, identity management, staking, governance, and interoperability with other ecosystems, making it simple and fast for both builders and users to get started in Web3. - -## PolkaVM - -PolkaVM is a custom virtual machine optimized for performance, leveraging a RISC-V-based architecture to support Solidity and any language that compiles to RISC-V. It is specifically designed for the Polkadot ecosystem, enabling smart contract deployment and execution. - -## Relay Chain - -Relay chains are blockchains that provide shared infrastructure and security to the [parachains](#parachain) in the network. In addition to providing [consensus](#consensus) capabilities, relay chains allow parachains to communicate and exchange digital assets without needing to trust one another. - -## Rococo - -A [parachain](#parachain) test network for the Polkadot network. The [Rococo](#rococo) network is a Polkadot SDK-based blockchain with an October 14, 2024 deprecation date. Development teams are encouraged to use the Paseo TestNet instead. - -## Runtime - -The runtime represents the [state transition function](#state-transition-function-stf) for a blockchain. In Polkadot SDK, the runtime is stored as a [Wasm](#webassembly-wasm) binary in the chain state. The Runtime is stored under a unique state key and can be modified during the execution of the state transition function. - -## Slot - -A fixed, equal interval of time used by consensus engines such as [Aura](#authority-round-aura) and [BABE](#blind-assignment-of-blockchain-extension-babe). In each slot, a subset of [authorities](#authority) is permitted, or obliged, to [author](#block-author) a block. - -## Sovereign Account - -The unique account identifier for each chain in the relay chain ecosystem. It is often used in cross-consensus (XCM) interactions to sign XCM messages sent to the relay chain or other chains in the ecosystem. - -The sovereign account for each chain is a root-level account that can only be accessed using the Sudo pallet or through governance. The account identifier is calculated by concatenating the Blake2 hash of a specific text string and the registered parachain identifier. - -## SS58 Address Format - -A public key address based on the Bitcoin [`Base-58-check`](https://en.bitcoin.it/wiki/Base58Check_encoding){target=\_blank} encoding. Each Polkadot SDK SS58 address uses a `base-58` encoded value to identify a specific account on a specific Polkadot SDK-based chain - -The [canonical `ss58-registry`](https://github.com/paritytech/ss58-registry){target=\_blank} provides additional details about the address format used by different Polkadot SDK-based chains, including the network prefix and website used for different networks - -## State Transition Function (STF) - -The logic of a blockchain that determines how the state changes when a block is processed. In Polkadot SDK, the state transition function is effectively equivalent to the [runtime](#runtime). - -## Storage Item - -[FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitives that provide type-safe data persistence capabilities to the [runtime](#runtime). -Learn more in the [storage items](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/index.html){target=\_blank} reference document in the Polkadot SDK. - -## Substrate - -A flexible framework for building modular, efficient, and upgradeable blockchains. Substrate is written in the [Rust](https://www.rust-lang.org/){target=\_blank} programming language and is maintained by [Parity Technologies](https://www.parity.io/){target=\_blank}. - -## Transaction - -An [extrinsic](#extrinsic) that includes a signature that can be used to verify the account authorizing it inherently or via [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}. - -## Transaction Era - -A definable period expressed as a range of block numbers during which a transaction can be included in a block. -Transaction eras are used to protect against transaction replay attacks if an account is reaped and its replay-protecting nonce is reset to zero. - -## Trie (Patricia Merkle Tree) - -A data structure used to represent sets of key-value pairs and enables the items in the data set to be stored and retrieved using a cryptographic hash. Because incremental changes to the data set result in a new hash, retrieving data is efficient even if the data set is very large. With this data structure, you can also prove whether the data set includes any particular key-value pair without access to the entire data set. - -In Polkadot SDK-based blockchains, state is stored in a trie data structure that supports the efficient creation of incremental digests. This trie is exposed to the [runtime](#runtime) as [a simple key/value map](#storage-item) where both keys and values can be arbitrary byte arrays. - -## Validator - -A validator is a node that participates in the consensus mechanism of the network. Its roles include block production, transaction validation, network integrity, and security maintenance. - -## WebAssembly (Wasm) - -An execution architecture that allows for the efficient, platform-neutral expression of -deterministic, machine-executable logic. - -[Wasm](https://webassembly.org/){target=\_blank} can be compiled from many languages, including -the [Rust](https://www.rust-lang.org/){target=\_blank} programming language. Polkadot SDK-based chains use a Wasm binary to provide portable [runtimes](#runtime) that can be included as part of the chain's state. - -## Weight - -A convention used in Polkadot SDK-based blockchains to measure and manage the time it takes to validate a block. -Polkadot SDK defines one unit of weight as one picosecond of execution time on reference hardware. - -The maximum block weight should be equivalent to one-third of the target block time with an allocation of one-third each for: - -- Block construction -- Network propagation -- Import and verification - -By defining weights, you can trade-off the number of transactions per second and the hardware required to maintain the target block time appropriate for your use case. Weights are defined in the runtime, meaning you can tune them using runtime updates to keep up with hardware and software improvements. - -## Westend - -Westend is a Parity-maintained, Polkadot SDK-based blockchain that serves as a test network for the [Polkadot](#polkadot) network. diff --git a/.ai/pages/reference-governance-origins-tracks.md b/.ai/pages/reference-governance-origins-tracks.md deleted file mode 100644 index 72c121a77..000000000 --- a/.ai/pages/reference-governance-origins-tracks.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Origins and Tracks -description: Explore Polkadot's OpenGov origins and tracks system, defining privilege levels, decision processes, and tailored pathways for network proposals. -categories: Polkadot Protocol -url: https://docs.polkadot.com/reference/governance/origins-tracks/ ---- - -# Origins and Tracks - -## Introduction - -Polkadot's OpenGov system empowers decentralized decision-making and active community participation by tailoring the governance process to the impact of proposed changes. Through a system of origins and tracks, OpenGov ensures that every referendum receives the appropriate scrutiny, balancing security, inclusivity, and efficiency. - -This guide will help you understand the role of origins in classifying proposals by privilege and priority. You will learn how tracks guide proposals through tailored stages like voting, confirmation, and enactment and how to select the correct origin for your referendum to align with community expectations and network governance. - -Origins and tracks are vital in streamlining the governance workflow and maintaining Polkadot's resilience and adaptability. - -## Origins - -Origins are the foundation of Polkadot's OpenGov governance system. They categorize proposals by privilege and define their decision-making rules. Each origin corresponds to a specific level of importance and risk, guiding how referendums progress through the governance process. - -- High-privilege origins like Root Origin govern critical network changes, such as core software upgrades. -- Lower-privilege origins like Small Spender handle minor requests, such as community project funding under 10,000 DOT. - -Proposers select an origin based on the nature of their referendum. Origins determine parameters like approval thresholds, required deposits, and timeframes for voting and confirmation. Each origin is paired with a track, which acts as a roadmap for the proposal's lifecycle, including preparation, voting, and enactment. - -For a detailed list of origins and their associated parameters, see the [Polkadot OpenGov Origins](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/){target=\_blank} entry in the Polkadot Wiki. - -## Tracks - -Tracks define a referendum's journey from submission to enactment, tailoring governance parameters to the impact of proposed changes. Each track operates independently and includes several key stages: - -- **Preparation**: Time for community discussion before voting begins. -- **Voting**: Period for token holders to cast their votes. -- **Decision**: Finalization of results and determination of the proposal's outcome. -- **Confirmation**: Period to verify sustained community support before enactment. -- **Enactment**: Final waiting period before the proposal takes effect. - -Tracks customize these stages with parameters like decision deposit requirements, voting durations, and approval thresholds, ensuring proposals from each origin receive the required scrutiny and process. For example, a runtime upgrade in the Root Origin track will have longer timeframes and stricter thresholds than a treasury request in the Small Spender track. - -## Additional Resources - -- For a list of origins and tracks for Polkadot and Kusama, including associated parameters, see the [Origins and Tracks Info](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#origins-and-tracks-info){target=\_blank} entry in the Polkadot Wiki. - -- For a deeper dive into the approval and support system, see the [Approval and Support](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#approval-and-support){target=\_blank} entry of the Polkadot Wiki. diff --git a/.ai/pages/reference-governance.md b/.ai/pages/reference-governance.md deleted file mode 100644 index 891fb4cb9..000000000 --- a/.ai/pages/reference-governance.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: On-Chain Governance Overview -description: Discover Polkadot’s cutting-edge OpenGov system, enabling transparent, decentralized decision-making through direct democracy and flexible governance tracks. -categories: Basics, Polkadot Protocol -url: https://docs.polkadot.com/reference/governance/ ---- - -# On-Chain Governance - -## Introduction - -Polkadot’s governance system exemplifies decentralized decision-making, empowering its community of stakeholders to shape the network’s future through active participation. The latest evolution, OpenGov, builds on Polkadot’s foundation by providing a more inclusive and efficient governance model. - -This guide will explain the principles and structure of OpenGov and walk you through its key components, such as Origins, Tracks, and Delegation. You will learn about improvements over earlier governance systems, including streamlined voting processes and enhanced stakeholder participation. - -With OpenGov, Polkadot achieves a flexible, scalable, and democratic governance framework that allows multiple proposals to proceed simultaneously, ensuring the network evolves in alignment with its community's needs. - -## Governance Evolution - -Polkadot’s governance journey began with [Governance V1](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#governance-summary){target=\_blank}, a system that proved effective in managing treasury funds and protocol upgrades. However, it faced limitations, such as: - -- Slow voting cycles, causing delays in decision-making. -- Inflexibility in handling multiple referendums, restricting scalability. - -To address these challenges, Polkadot introduced OpenGov, a governance model designed for greater inclusivity, efficiency, and scalability. OpenGov replaces the centralized structures of Governance V1, such as the Council and Technical Committee, with a fully decentralized and dynamic framework. - -For a full comparison of the historic and current governance models, visit the [Gov1 vs. Polkadot OpenGov](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#gov1-vs-polkadot-opengov){target=\_blank} section of the Polkadot Wiki. - -## OpenGov Key Features - -OpenGov transforms Polkadot’s governance into a decentralized, stakeholder-driven model, eliminating centralized decision-making bodies like the Council. Key enhancements include: - -- **Decentralization**: Shifts all decision-making power to the public, ensuring a more democratic process. -- **Enhanced delegation**: Allows users to delegate their votes to trusted experts across specific governance tracks. -- **Simultaneous referendums**: Multiple proposals can progress at once, enabling faster decision-making. -- **Polkadot Technical Fellowship**: A broad, community-driven group replacing the centralized Technical Committee. - -This new system ensures Polkadot governance remains agile and inclusive, even as the ecosystem grows. - -## Origins and Tracks - -In OpenGov, origins and tracks are central to managing proposals and votes. - -- **Origin**: Determines the authority level of a proposal (e.g., Treasury, Root) which decides the track of all referendums from that origin. -- **Track**: Define the procedural flow of a proposal, such as voting duration, approval thresholds, and enactment timelines. - -Developers must be aware that referendums from different origins and tracks will take varying amounts of time to reach approval and enactment. The [Polkadot Technical Fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank} has the option to shorten this timeline by whitelisting a proposal and allowing it to be enacted through the [Whitelist Caller](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#whitelisted-caller){target=\_blank} origin. - -Visit [Origins and Tracks Info](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#origins-and-tracks){target=\_blank} for details on current origins and tracks, associated terminology, and parameters. - -## Referendums - -In OpenGov, anyone can submit a referendum, fostering an open and participatory system. The timeline for a referendum depends on the privilege level of the origin with more significant changes offering more time for community voting and participation before enactment. - -The timeline for an individual referendum includes four distinct periods: - -- **Lead-in**: A minimum amount of time to allow for community participation, available room in the origin, and payment of the decision deposit. Voting is open during this period. -- **Decision**: Voting continues. -- **Confirmation**: Referendum must meet [approval and support](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#approval-and-support){target=\_blank} criteria during entire period to avoid rejection. -- **Enactment**: Changes approved by the referendum are executed. - -### Vote on Referendums - -Voters can vote with their tokens on each referendum. Polkadot uses a voluntary token locking mechanism, called conviction voting, as a way for voters to increase their voting power. A token holder signals they have a stronger preference for approving a proposal based upon their willingness to lock up tokens. Longer voluntary token locks are seen as a signal of continual approval and translate to increased voting weight. - -See [Voting on a Referendum](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank} for a deeper look at conviction voting and related token locks. - -### Delegate Voting Power - -The OpenGov system also supports multi-role delegations, allowing token holders to assign their voting power on different tracks to entities with expertise in those areas. - -For example, if a token holder lacks the technical knowledge to evaluate proposals on the [Root track](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#root){target=\_blank}, they can delegate their voting power for that track to an expert they trust to vote in the best interest of the network. This ensures informed decision-making across tracks while maintaining flexibility for token holders. - -Visit [Multirole Delegation](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#multirole-delegation){target=\_blank} for more details on delegating voting power. - -### Cancel a Referendum - -Polkadot OpenGov has two origins for rejecting ongoing referendums: - -- [**Referendum Canceller**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-canceller){target=\_blank}: Cancels an active referendum when non-malicious errors occur and refunds the deposits to the originators. -- [**Referendum Killer**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-killer){target=\_blank}: Used for urgent, malicious cases this origin instantly terminates an active referendum and slashes deposits. - -See [Cancelling, Killing, and Blacklisting](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#cancelling-killing--blacklisting){target=\_blank} for additional information on rejecting referendums. - -## Additional Resources - -- **[Democracy pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/democracy/src){target=\_blank}**: Handles administration of general stakeholder voting. -- **[Gov2: Polkadot’s Next Generation of Decentralised Governance](https://medium.com/polkadot-network/gov2-polkadots-next-generation-of-decentralised-governance-4d9ef657d11b){target=\_blank}**: Medium article by Gavin Wood. -- **[Polkadot Direction](https://matrix.to/#/#Polkadot-Direction:parity.io){target=\_blank}**: Matrix Element client. -- **[Polkassembly](https://polkadot.polkassembly.io/){target=\_blank}**: OpenGov dashboard and UI. -- **[Polkadot.js Apps Governance](https://polkadot.js.org/apps/#/referenda){target=\_blank}**: Overview of active referendums. diff --git a/.ai/pages/reference-parachains-accounts.md b/.ai/pages/reference-parachains-accounts.md deleted file mode 100644 index 5ee42fd0a..000000000 --- a/.ai/pages/reference-parachains-accounts.md +++ /dev/null @@ -1,395 +0,0 @@ ---- -title: Polkadot SDK Accounts -description: Learn about account structures, balances, and address formats in the Polkadot SDK, including how to manage lifecycle, references, and balances. -categories: Basics, Polkadot Protocol -url: https://docs.polkadot.com/reference/parachains/accounts/ ---- - -# Accounts - -## Introduction - -Accounts are essential for managing identity, transactions, and governance on the network in the Polkadot SDK. Understanding these components is critical for seamless development and operation on the network, whether you're building or interacting with Polkadot-based chains. - -This page will guide you through the essential aspects of accounts, including their data structure, balance types, reference counters, and address formats. You’ll learn how accounts are managed within the runtime, how balances are categorized, and how addresses are encoded and validated. - -## Account Data Structure - -Accounts are foundational to any blockchain, and the Polkadot SDK provides a flexible management system. This section explains how the Polkadot SDK defines accounts and manages their lifecycle through data structures within the runtime. - -### Account - -The [`Account` data type](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/type.Account.html){target=\_blank} is a storage map within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank} that links an account ID to its corresponding data. This structure is fundamental for mapping account-related information within the chain. - -The code snippet below shows how accounts are defined: - -```rs - /// The full account information for a particular account ID. - #[pallet::storage] - #[pallet::getter(fn account)] - pub type Account = StorageMap< - _, - Blake2_128Concat, - T::AccountId, - AccountInfo, - ValueQuery, - >; -``` - -The preceding code block defines a storage map named `Account`. The `StorageMap` is a type of on-chain storage that maps keys to values. In the `Account` map, the key is an account ID, and the value is the account's information. Here, `T` represents the generic parameter for the runtime configuration, which is defined by the pallet's configuration trait (`Config`). - -The `StorageMap` consists of the following parameters: - -- **`_`**: Used in macro expansion and acts as a placeholder for the storage prefix type. Tells the macro to insert the default prefix during expansion. -- **`Blake2_128Concat`**: The hashing function applied to keys in the storage map. -- **`T: :AccountId`**: Represents the key type, which corresponds to the account’s unique ID. -- **`AccountInfo`**: The value type stored in the map. For each account ID, the map stores an `AccountInfo` struct containing: - - - **`T::Nonce`**: A nonce for the account, which is incremented with each transaction to ensure transaction uniqueness. - - **`T: :AccountData`**: Custom account data defined by the runtime configuration, which could include balances, locked funds, or other relevant information. - -- **`ValueQuery`**: Defines how queries to the storage map behave when no value is found; returns a default value instead of `None`. - -For a detailed explanation of storage maps, see the [`StorageMap`](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/struct.StorageMap.html){target=\_blank} entry in the Rust docs. - -### Account Info - -The `AccountInfo` structure is another key element within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\_blank}, providing more granular details about each account's state. This structure tracks vital data, such as the number of transactions and the account’s relationships with other modules. - -```rs -/// Information of an account. -#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)] -pub struct AccountInfo { - /// The number of transactions this account has sent. - pub nonce: Nonce, - /// The number of other modules that currently depend on this account's existence. The account - /// cannot be reaped until this is zero. - pub consumers: RefCount, - /// The number of other modules that allow this account to exist. The account may not be reaped - /// until this and `sufficients` are both zero. - pub providers: RefCount, - /// The number of modules that allow this account to exist for their own purposes only. The - /// account may not be reaped until this and `providers` are both zero. - pub sufficients: RefCount, - /// The additional data that belongs to this account. Used to store the balance(s) in a lot of - /// chains. - pub data: AccountData, -} -``` - -The `AccountInfo` structure includes the following components: - -- **`nonce`**: Tracks the number of transactions initiated by the account, which ensures transaction uniqueness and prevents replay attacks. -- **`consumers`**: Counts how many other modules or pallets rely on this account’s existence. The account cannot be removed from the chain (reaped) until this count reaches zero. -- **`providers`**: Tracks how many modules permit this account’s existence. An account can only be reaped once both `providers` and `sufficients` are zero. -- **`sufficients`**: Represents the number of modules that allow the account to exist for internal purposes, independent of any other modules. -- **`AccountData`**: A flexible data structure that can be customized in the runtime configuration, usually containing balances or other user-specific data. - -This structure helps manage an account's state and prevents its premature removal while it is still referenced by other on-chain data or modules. The [`AccountInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.AccountInfo.html){target=\_blank} structure can vary as long as it satisfies the trait bounds defined by the `AccountData` associated type in the [`frame-system::pallet::Config`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/trait.Config.html){target=\_blank} trait. - -### Account Reference Counters - -Polkadot SDK uses reference counters to track an account’s dependencies across different runtime modules. These counters ensure that accounts remain active while data is associated with them. - -The reference counters include: - -- **`consumers`**: Prevents account removal while other pallets still rely on the account. -- **`providers`**: Ensures an account is active before other pallets store data related to it. -- **`sufficients`**: Indicates the account’s independence, ensuring it can exist even without a native token balance, such as when holding sufficient alternative assets. - -#### Providers Reference Counters - -The `providers` counter ensures that an account is ready to be depended upon by other runtime modules. For example, it is incremented when an account has a balance above the existential deposit, which marks the account as active. - -The system requires this reference counter to be greater than zero for the `consumers` counter to be incremented, ensuring the account is stable before any dependencies are added. - -#### Consumers Reference Counters - -The `consumers` counter ensures that the account cannot be reaped until all references to it across the runtime have been removed. This check prevents the accidental deletion of accounts that still have active on-chain data. - -It is the user’s responsibility to clear out any data from other runtime modules if they wish to remove their account and reclaim their existential deposit. - -#### Sufficients Reference Counter - -The `sufficients` counter tracks accounts that can exist independently without relying on a native account balance. This is useful for accounts holding other types of assets, like tokens, without needing a minimum balance in the native token. - -For instance, the [Assets pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_assets/index.html){target=\_blank}, may increment this counter for an account holding sufficient tokens. - -#### Account Deactivation - -In Polkadot SDK-based chains, an account is deactivated when its reference counters (such as `providers`, `consumers`, and `sufficient`) reach zero. These counters ensure the account remains active as long as other runtime modules or pallets reference it. - -When all dependencies are cleared and the counters drop to zero, the account becomes deactivated and may be removed from the chain (reaped). This is particularly important in Polkadot SDK-based blockchains, where accounts with balances below the existential deposit threshold are pruned from storage to conserve state resources. - -Each pallet that references an account has cleanup functions that decrement these counters when the pallet no longer depends on the account. Once these counters reach zero, the account is marked for deactivation. - -#### Updating Counters - -The Polkadot SDK provides runtime developers with various methods to manage account lifecycle events, such as deactivation or incrementing reference counters. These methods ensure that accounts cannot be reaped while still in use. - -The following helper functions manage these counters: - -- **`inc_consumers()`**: Increments the `consumer` reference counter for an account, signaling that another pallet depends on it. -- **`dec_consumers()`**: Decrements the `consumer` reference counter, signaling that a pallet no longer relies on the account. -- **`inc_providers()`**: Increments the `provider` reference counter, ensuring the account remains active. -- **`dec_providers()`**: Decrements the `provider` reference counter, allowing for account deactivation when no longer in use. -- **`inc_sufficients()`**: Increments the `sufficient` reference counter for accounts that hold sufficient assets. -- **`dec_sufficients()`**: Decrements the `sufficient` reference counter. - -To ensure proper account cleanup and lifecycle management, a corresponding decrement should be made for each increment action. - -The `System` pallet offers three query functions to assist developers in tracking account states: - -- **[`can_inc_consumer()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_inc_consumer){target=\_blank}**: Checks if the account can safely increment the consumer reference. -- **[`can_dec_provider()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_dec_provider){target=\_blank}**: Ensures that no consumers exist before allowing the decrement of the provider counter. -- **[`is_provider_required()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.is_provider_required){target=\_blank}**: Verifies whether the account still has any active consumer references. - -This modular and flexible system of reference counters tightly controls the lifecycle of accounts in Polkadot SDK-based blockchains, preventing the accidental removal or retention of unneeded accounts. You can refer to the [System pallet Rust docs](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html){target=\_blank} for more details. - - -## Account Balance Types - -In the Polkadot ecosystem, account balances are categorized into different types based on how the funds are utilized and their availability. These balance types determine the actions that can be performed, such as transferring tokens, paying transaction fees, or participating in governance activities. Understanding these balance types helps developers manage user accounts and implement balance-dependent logic. - -!!! note "A more efficient distribution of account balance types is in development" - Soon, pallets in the Polkadot SDK will implement the [`Fungible` trait](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} (see the [tracking issue](https://github.com/paritytech/polkadot-sdk/issues/226){target=\_blank} for more details). For example, the [`transaction-storage`](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_storage/index.html){target=\_blank} pallet changed the implementation of the [`Currency`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/currency/index.html){target=\_blank} trait (see the [Refactor transaction storage pallet to use fungible traits](https://github.com/paritytech/polkadot-sdk/pull/1800){target=\_blank} PR for further details): - - ```rust - type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; - ``` - - To the [`Fungible`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\_blank} trait: - - ```rust - type BalanceOf = <::Currency as FnInspect<::AccountId>>::Balance; - ``` - - This update will enable more efficient use of account balances, allowing the free balance to be utilized for on-chain activities such as setting proxies and managing identities. - -### Balance Types - -The five main balance types are: - -- **Free balance**: Represents the total tokens available to the account for any on-chain activity, including staking, governance, and voting. However, it may not be fully spendable or transferrable if portions of it are locked or reserved. -- **Locked balance**: Portions of the free balance that cannot be spent or transferred because they are tied up in specific activities like [staking](https://wiki.polkadot.com/learn/learn-staking/#nominating-validators){target=\_blank}, [vesting](https://wiki.polkadot.com/learn/learn-guides-transfers/#vested-transfers-with-the-polkadot-js-ui){target=\_blank}, or participating in [governance](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\_blank}. While the tokens remain part of the free balance, they are non-transferable for the duration of the lock. -- **Reserved balance**: Funds locked by specific system actions, such as setting up an [identity](https://wiki.polkadot.com/learn/learn-identity/){target=\_blank}, creating [proxies](https://wiki.polkadot.com/learn/learn-proxies/){target=\_blank}, or submitting [deposits for governance proposals](https://wiki.polkadot.com/learn/learn-guides-polkadot-opengov/#claiming-opengov-deposits){target=\_blank}. These tokens are not part of the free balance and cannot be spent unless they are unreserved. -- **Spendable balance**: The portion of the free balance that is available for immediate spending or transfers. It is calculated by subtracting the maximum of locked or reserved amounts from the free balance, ensuring that existential deposit limits are met. -- **Untouchable balance**: Funds that cannot be directly spent or transferred but may still be utilized for on-chain activities, such as governance participation or staking. These tokens are typically tied to certain actions or locked for a specific period. - -The spendable balance is calculated as follows: - -```text -spendable = free - max(locked - reserved, ED) -``` - -Here, `free`, `locked`, and `reserved` are defined above. The `ED` represents the [existential deposit](https://wiki.polkadot.com/learn/learn-accounts/#existential-deposit-and-reaping){target=\_blank}, the minimum balance required to keep an account active and prevent it from being reaped. You may find you can't see all balance types when looking at your account via a wallet. Wallet providers often display only spendable, locked, and reserved balances. - -### Locks - -Locks are applied to an account's free balance, preventing that portion from being spent or transferred. Locks are automatically placed when an account participates in specific on-chain activities, such as staking or governance. Although multiple locks may be applied simultaneously, they do not stack. Instead, the largest lock determines the total amount of locked tokens. - -Locks follow these basic rules: - -- If different locks apply to varying amounts, the largest lock amount takes precedence. -- If multiple locks apply to the same amount, the lock with the longest duration governs when the balance can be unlocked. - -#### Locks Example - -Consider an example where an account has 80 DOT locked for both staking and governance purposes like so: - -- 80 DOT is staked with a 28-day lock period. -- 24 DOT is locked for governance with a 1x conviction and a 7-day lock period. -- 4 DOT is locked for governance with a 6x conviction and a 224-day lock period. - -In this case, the total locked amount is 80 DOT because only the largest lock (80 DOT from staking) governs the locked balance. These 80 DOT will be released at different times based on the lock durations. In this example, the 24 DOT locked for governance will be released first since the shortest lock period is seven days. The 80 DOT stake with a 28-day lock period is released next. Now, all that remains locked is the 4 DOT for governance. After 224 days, all 80 DOT (minus the existential deposit) will be free and transferable. - -![Illustration of Lock Example](/images/reference/parachains/accounts/accounts-01.webp) - -#### Edge Cases for Locks - -In scenarios where multiple convictions and lock periods are active, the lock duration and amount are determined by the longest period and largest amount. For example, if you delegate with different convictions and attempt to undelegate during an active lock period, the lock may be extended for the full amount of tokens. For a detailed discussion on edge case lock behavior, see this [Stack Exchange post](https://substrate.stackexchange.com/questions/5067/delegating-and-undelegating-during-the-lock-period-extends-it-for-the-initial-am){target=\_blank}. - -### Balance Types on Polkadot.js - -Polkadot.js provides a user-friendly interface for managing and visualizing various account balances on Polkadot and Kusama networks. When interacting with Polkadot.js, you will encounter multiple balance types that are critical for understanding how your funds are distributed and restricted. This section explains how different balances are displayed in the Polkadot.js UI and what each type represents. - -![](/images/reference/parachains/accounts/accounts-02.webp) - -The most common balance types displayed on Polkadot.js are: - -- **Total balance**: The total number of tokens available in the account. This includes all tokens, whether they are transferable, locked, reserved, or vested. However, the total balance does not always reflect what can be spent immediately. In this example, the total balance is 0.6274 KSM. - -- **Transferable balance**: Shows how many tokens are immediately available for transfer. It is calculated by subtracting the locked and reserved balances from the total balance. For example, if an account has a total balance of 0.6274 KSM and a transferable balance of 0.0106 KSM, only the latter amount can be sent or spent freely. - -- **Vested balance**: Tokens that allocated to the account but released according to a specific schedule. Vested tokens remain locked and cannot be transferred until fully vested. For example, an account with a vested balance of 0.2500 KSM means that this amount is owned but not yet transferable. - -- **Locked balance**: Tokens that are temporarily restricted from being transferred or spent. These locks typically result from participating in staking, governance, or vested transfers. In Polkadot.js, locked balances do not stack—only the largest lock is applied. For instance, if an account has 0.5500 KSM locked for governance and staking, the locked balance would display 0.5500 KSM, not the sum of all locked amounts. - -- **Reserved balance**: Refers to tokens locked for specific on-chain actions, such as setting an identity, creating a proxy, or making governance deposits. Reserved tokens are not part of the free balance, but can be freed by performing certain actions. For example, removing an identity would unreserve those funds. - -- **Bonded balance**: The tokens locked for staking purposes. Bonded tokens are not transferable until they are unbonded after the unbonding period. - -- **Redeemable balance**: The number of tokens that have completed the unbonding period and are ready to be unlocked and transferred again. For example, if an account has a redeemable balance of 0.1000 KSM, those tokens are now available for spending. - -- **Democracy balance**: Reflects the number of tokens locked for governance activities, such as voting on referenda. These tokens are locked for the duration of the governance action and are only released after the lock period ends. - -By understanding these balance types and their implications, developers and users can better manage their funds and engage with on-chain activities more effectively. - -## Address Formats - -The SS58 address format is a core component of the Polkadot SDK that enables accounts to be uniquely identified across Polkadot-based networks. This format is a modified version of Bitcoin's Base58Check encoding, specifically designed to accommodate the multi-chain nature of the Polkadot ecosystem. SS58 encoding allows each chain to define its own set of addresses while maintaining compatibility and checksum validation for security. - -### Basic Format - -SS58 addresses consist of three main components: - -```text -base58encode(concat(,
, )) -``` - -- **Address type**: A byte or set of bytes that define the network (or chain) for which the address is intended. This ensures that addresses are unique across different Polkadot SDK-based chains. -- **Address**: The public key of the account encoded as bytes. -- **Checksum**: A hash-based checksum which ensures that addresses are valid and unaltered. The checksum is derived from the concatenated address type and address components, ensuring integrity. - -The encoding process transforms the concatenated components into a Base58 string, providing a compact and human-readable format that avoids easily confused characters (e.g., zero '0', capital 'O', lowercase 'l'). This encoding function ([`encode`](https://docs.rs/bs58/latest/bs58/fn.encode.html){target=\_blank}) is implemented exactly as defined in Bitcoin and IPFS specifications, using the same alphabet as both implementations. - -For more details about the SS58 address format implementation, see the [`Ss58Codec`](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Ss58Codec.html){target=\_blank} trait in the Rust Docs. - -### Address Type - -The address type defines how an address is interpreted and to which network it belongs. Polkadot SDK uses different prefixes to distinguish between various chains and address formats: - -- **Address types `0-63`**: Simple addresses, commonly used for network identifiers. -- **Address types `64-127`**: Full addresses that support a wider range of network identifiers. -- **Address types `128-255`**: Reserved for future address format extensions. - -For example, Polkadot’s main network uses an address type of 0, while Kusama uses 2. This ensures that addresses can be used without confusion between networks. - -The address type is always encoded as part of the SS58 address, making it easy to quickly identify the network. Refer to the [SS58 registry](https://github.com/paritytech/ss58-registry){target=\_blank} for the canonical listing of all address type identifiers and how they map to Polkadot SDK-based networks. - -### Address Length - -SS58 addresses can have different lengths depending on the specific format. Address lengths range from as short as 3 to 35 bytes, depending on the complexity of the address and network requirements. This flexibility allows SS58 addresses to adapt to different chains while providing a secure encoding mechanism. - -| Total | Type | Raw account | Checksum | -|-------|------|-------------|----------| -| 3 | 1 | 1 | 1 | -| 4 | 1 | 2 | 1 | -| 5 | 1 | 2 | 2 | -| 6 | 1 | 4 | 1 | -| 7 | 1 | 4 | 2 | -| 8 | 1 | 4 | 3 | -| 9 | 1 | 4 | 4 | -| 10 | 1 | 8 | 1 | -| 11 | 1 | 8 | 2 | -| 12 | 1 | 8 | 3 | -| 13 | 1 | 8 | 4 | -| 14 | 1 | 8 | 5 | -| 15 | 1 | 8 | 6 | -| 16 | 1 | 8 | 7 | -| 17 | 1 | 8 | 8 | -| 35 | 1 | 32 | 2 | - -SS58 addresses also support different payload sizes, allowing a flexible range of account identifiers. - -### Checksum Types - -A checksum is applied to validate SS58 addresses. Polkadot SDK uses a Blake2b-512 hash function to calculate the checksum, which is appended to the address before encoding. The checksum length can vary depending on the address format (e.g., 1-byte, 2-byte, or longer), providing varying levels of validation strength. - -The checksum ensures that an address is not modified or corrupted, adding an extra layer of security for account management. - -### Validating Addresses - -SS58 addresses can be validated using the subkey command-line interface or the Polkadot.js API. These tools help ensure an address is correctly formatted and valid for the intended network. The following sections will provide an overview of how validation works with these tools. - -#### Using Subkey - -[Subkey](https://paritytech.github.io/polkadot-sdk/master/subkey/index.html){target=\_blank} is a CLI tool provided by Polkadot SDK for generating and managing keys. It can inspect and validate SS58 addresses. - -The `inspect` command gets a public key and an SS58 address from the provided secret URI. The basic syntax for the `subkey inspect` command is: - -```bash -subkey inspect [flags] [options] uri -``` - -For the `uri` command-line argument, you can specify the secret seed phrase, a hex-encoded private key, or an SS58 address. If the input is a valid address, the `subkey` program displays the corresponding hex-encoded public key, account identifier, and SS58 addresses. - -For example, to inspect the public keys derived from a secret seed phrase, you can run a command similar to the following: - -```bash -subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" -``` - -The command displays output similar to the following: - -
- subkey inspect "caution juice atom organ advance problem want pledge someone senior holiday very" - Secret phrase `caution juice atom organ advance problem want pledge someone senior holiday very` is account: - Secret seed: 0xc8fa03532fb22ee1f7f6908b9c02b4e72483f0dbd66e4cd456b8f34c6230b849 - Public key (hex): 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - Public key (SS58): 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR - Account ID: 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746 - SS58 Address: 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR -
- -The `subkey` program assumes an address is based on a public/private key pair. If you inspect an address, the command returns the 32-byte account identifier. - -However, not all addresses in Polkadot SDK-based networks are based on keys. - -Depending on the command-line options you specify and the input you provided, the command output might also display the network for which the address has been encoded. For example: - -```bash -subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" -``` - -The command displays output similar to the following: - -
- subkey inspect "12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU" - Public Key URI `12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU` is account: - Network ID/Version: polkadot - Public key (hex): 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Account ID: 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a - Public key (SS58): 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU - SS58 Address: 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU -
- -#### Using Polkadot.js API - -To verify an address in JavaScript or TypeScript projects, you can use the functions built into the [Polkadot.js API](https://polkadot.js.org/docs/){target=\_blank}. For example: - -```js -// Import Polkadot.js API dependencies -const { decodeAddress, encodeAddress } = require('@polkadot/keyring'); -const { hexToU8a, isHex } = require('@polkadot/util'); - -// Specify an address to test. -const address = 'INSERT_ADDRESS_TO_TEST'; - -// Check address -const isValidSubstrateAddress = () => { - try { - encodeAddress(isHex(address) ? hexToU8a(address) : decodeAddress(address)); - - return true; - } catch (error) { - return false; - } -}; - -// Query result -const isValid = isValidSubstrateAddress(); -console.log(isValid); - -``` - -If the function returns `true`, the specified address is a valid address. - -#### Other SS58 Implementations - -Support for encoding and decoding Polkadot SDK SS58 addresses has been implemented in several other languages and libraries. - -- **Crystal**: [`wyhaines/base58.cr`](https://github.com/wyhaines/base58.cr){target=\_blank} -- **Go**: [`itering/subscan-plugin`](https://github.com/itering/subscan-plugin){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **TypeScript**: [`subsquid/squid-sdk`](https://github.com/subsquid/squid-sdk){target=\_blank} diff --git a/.ai/pages/reference-parachains-blocks-transactions-fees-blocks.md b/.ai/pages/reference-parachains-blocks-transactions-fees-blocks.md deleted file mode 100644 index 5c5a60dd1..000000000 --- a/.ai/pages/reference-parachains-blocks-transactions-fees-blocks.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Blocks -description: Understand how blocks are produced, validated, and imported in Polkadot SDK-based blockchains, covering initialization, finalization, and authoring processes. -categories: Basics, Polkadot Protocol -url: https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/blocks/ ---- - -# Blocks - -## Introduction - -In the Polkadot SDK, blocks are fundamental to the functioning of the blockchain, serving as containers for [transactions](/reference/parachains/blocks-transactions-fees/transactions/){target=\_blank} and changes to the chain's state. Blocks consist of headers and an array of transactions, ensuring the integrity and validity of operations on the network. This guide explores the essential components of a block, the process of block production, and how blocks are validated and imported across the network. By understanding these concepts, developers can better grasp how blockchains maintain security, consistency, and performance within the Polkadot ecosystem. - -## What is a Block? - -In the Polkadot SDK, a block is a fundamental unit that encapsulates both the header and an array of transactions. The block header includes critical metadata to ensure the integrity and sequence of the blockchain. Here's a breakdown of its components: - -- **Block height**: Indicates the number of blocks created in the chain so far. -- **Parent hash**: The hash of the previous block, providing a link to maintain the blockchain's immutability. -- **Transaction root**: Cryptographic digest summarizing all transactions in the block. -- **State root**: A cryptographic digest representing the post-execution state. -- **Digest**: Additional information that can be attached to a block, such as consensus-related messages. - -Each transaction is part of a series that is executed according to the runtime's rules. The transaction root is a cryptographic digest of this series, which prevents alterations and enables succinct verification by light clients. This verification process allows light clients to confirm whether a transaction exists in a block with only the block header, avoiding downloading the entire block. - -## Block Production - -When an authoring node is authorized to create a new block, it selects transactions from the transaction queue based on priority. This step, known as block production, relies heavily on the executive module to manage the initialization and finalization of blocks. The process is summarized as follows: - -### Initialize Block - -The block initialization process begins with a series of function calls that prepare the block for transaction execution: - -1. **Call `on_initialize`**: The executive module calls the [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} hook from the system pallet and other runtime pallets to prepare for the block's transactions. -2. **Coordinate runtime calls**: Coordinates function calls in the order defined by the transaction queue. -3. **Verify information**: Once [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\_blank} functions are executed, the executive module checks the parent hash in the block header and the trie root to verify information is consistent. - -### Finalize Block - -Once transactions are processed, the block must be finalized before being broadcast to the network. The finalization steps are as follows: - -1. **Call `on_finalize`**: The executive module calls the [`on_finalize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_finalize){target=\_blank} hooks in each pallet to ensure any remaining state updates or checks are completed before the block is sealed and published. -2. **Verify information**: The block's digest and storage root in the header are checked against the initialized block to ensure consistency. -3. **Call `on_idle`**: The [`on_idle`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_idle){target=\_blank} hook is triggered to process any remaining tasks using the leftover weight from the block. - -## Block Authoring and Import - -Once the block is finalized, it is gossiped to other nodes in the network. Nodes follow this procedure: - -1. **Receive transactions**: The authoring node collects transactions from the network. -2. **Validate**: Transactions are checked for validity. -3. **Queue**: Valid transactions are placed in the transaction pool for execution. -4. **Execute**: State changes are made as the transactions are executed. -5. **Publish**: The finalized block is broadcast to the network. - -### Block Import Queue - -After a block is published, other nodes on the network can import it into their chain state. The block import queue is part of the outer node in every Polkadot SDK-based node and ensures incoming blocks are valid before adding them to the node's state. - -In most cases, you don't need to know details about how transactions are gossiped or how other nodes on the network import blocks. The following traits are relevant, however, if you plan to write any custom consensus logic or want a deeper dive into the block import queue: - -- **[`ImportQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.ImportQueue.html){target=\_blank}**: The trait that defines the block import queue. -- **[`Link`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Link.html){target=\_blank}**: The trait that defines the link between the block import queue and the network. -- **[`BasicQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/struct.BasicQueue.html){target=\_blank}**: A basic implementation of the block import queue. -- **[`Verifier`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Verifier.html){target=\_blank}**: The trait that defines the block verifier. -- **[`BlockImport`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/block_import/trait.BlockImport.html){target=\_blank}**: The trait that defines the block import process. - -These traits govern how blocks are validated and imported across the network, ensuring consistency and security. - -## Additional Resources - -To learn more about the block structure in the Polkadot SDK runtime, see the [`Block` reference](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.Block.html){target=\_blank} entry in the Rust Docs. diff --git a/.ai/pages/reference-parachains-blocks-transactions-fees-fees.md b/.ai/pages/reference-parachains-blocks-transactions-fees-fees.md deleted file mode 100644 index 474cd6537..000000000 --- a/.ai/pages/reference-parachains-blocks-transactions-fees-fees.md +++ /dev/null @@ -1,342 +0,0 @@ ---- -title: Transactions Weights and Fees -description: Overview of transaction weights and fees in Polkadot SDK chains, detailing how fees are calculated using a defined formula and runtime specifics. -categories: Basics, Polkadot Protocol -url: https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/fees/ ---- - -# Transactions Weights and Fees - -## Introductions - -When transactions are executed, or data is stored on-chain, the activity changes the chain's state and consumes blockchain resources. Because the resources available to a blockchain are limited, managing how operations on-chain consume them is important. In addition to being limited in practical terms, such as storage capacity, blockchain resources represent a potential attack vector for malicious users. For example, a malicious user might attempt to overload the network with messages to stop the network from producing new blocks. To protect blockchain resources from being drained or overloaded, you need to manage how they are made available and how they are consumed. The resources to be aware of include: - -- Memory usage -- Storage input and output -- Computation -- Transaction and block size -- State database size - -The Polkadot SDK provides block authors with several ways to manage access to resources and to prevent individual components of the chain from consuming too much of any single resource. Two of the most important mechanisms available to block authors are weights and transaction fees. - -[Weights](/reference/glossary/#weight){target=\_blank} manage the time it takes to validate a block and characterize the time it takes to execute the calls in the block's body. By controlling the execution time a block can consume, weights set limits on storage input, output, and computation. - -Some of the weight allowed for a block is consumed as part of the block's initialization and finalization. The weight might also be used to execute mandatory inherent extrinsic calls. To help ensure blocks don’t consume too much execution time and prevent malicious users from overloading the system with unnecessary calls, weights are combined with transaction fees. - -[Transaction fees](/reference/parachains/blocks-transactions-fees/transactions/#transaction-fees){target=\_blank} provide an economic incentive to limit execution time, computation, and the number of calls required to perform operations. Transaction fees are also used to make the blockchain economically sustainable because they are typically applied to transactions initiated by users and deducted before a transaction request is executed. - -## How Fees are Calculated - -The final fee for a transaction is calculated using the following parameters: - -- **`base fee`**: This is the minimum amount a user pays for a transaction. It is declared a base weight in the runtime and converted to a fee using the [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} conversion. -- **`weight fee`**: A fee proportional to the execution time (input and output and computation) that a transaction consumes. -- **`length fee`**: A fee proportional to the encoded length of the transaction. -- **`tip`**: An optional tip to increase the transaction’s priority, giving it a higher chance to be included in the transaction queue. - -The base fee and proportional weight and length fees constitute the inclusion fee. The inclusion fee is the minimum fee that must be available for a transaction to be included in a block. - -```text -inclusion fee = base fee + weight fee + length fee -``` - -Transaction fees are withdrawn before the transaction is executed. After the transaction is executed, the weight can be adjusted to reflect the resources used. If a transaction uses fewer resources than expected, the transaction fee is corrected, and the adjusted transaction fee is deposited. - -## Using the Transaction Payment Pallet - -The [Transaction Payment pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/transaction-payment){target=\_blank} provides the basic logic for calculating the inclusion fee. You can also use the Transaction Payment pallet to: - -- Convert a weight value into a deductible fee based on a currency type using [`Config::WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank}. -- Update the fee for the next block by defining a multiplier based on the chain’s final state at the end of the previous block using [`Config::FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank}. -- Manage the withdrawal, refund, and deposit of transaction fees using [`Config::OnChargeTransaction`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.OnChargeTransaction){target=\_blank}. - -You can learn more about these configuration traits in the [Transaction Payment documentation](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_payment/index.html){target=\_blank}. - -### Understanding the Inclusion Fee - -The formula for calculating the inclusion fee is as follows: - -```text -inclusion_fee = base_fee + length_fee + [targeted_fee_adjustment * weight_fee] -``` - -And then, for calculating the final fee: - -```text -final_fee = inclusion_fee + tip -``` - -In the first formula, the `targeted_fee_adjustment` is a multiplier that can tune the final fee based on the network’s congestion. - -- The `base_fee` derived from the base weight covers inclusion overhead like signature verification. -- The `length_fee` is a per-byte fee that is multiplied by the length of the encoded extrinsic. -- The `weight_fee` fee is calculated using two parameters: - - The `ExtrinsicBaseWeight` that is declared in the runtime and applies to all extrinsics. - - The `#[pallet::weight]` annotation that accounts for an extrinsic's complexity. - -To convert the weight to `Currency`, the runtime must define a `WeightToFee` struct that implements a conversion function, [`Convert`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/struct.Pallet.html#method.weight_to_fee){target=\_blank}. - -Note that the extrinsic sender is charged the inclusion fee before the extrinsic is invoked. The fee is deducted from the sender's balance even if the transaction fails upon execution. - -### Accounts with an Insufficient Balance - -If an account does not have a sufficient balance to pay the inclusion fee and remain alive—that is, enough to pay the inclusion fee and maintain the minimum existential deposit—then you should ensure the transaction is canceled so that no fee is deducted and the transaction does not begin execution. - -The Polkadot SDK doesn't enforce this rollback behavior. However, this scenario would be rare because the transaction queue and block-making logic perform checks to prevent it before adding an extrinsic to a block. - -### Fee Multipliers - -The inclusion fee formula always results in the same fee for the same input. However, weight can be dynamic and—based on how [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\_blank} is defined—the final fee can include some degree of variability. -The Transaction Payment pallet provides the [`FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\_blank} configurable parameter to account for this variability. - -The Polkadot network inspires the default update function and implements a targeted adjustment in which a target saturation level of block weight is defined. If the previous block is more saturated, the fees increase slightly. Similarly, if the last block has fewer transactions than the target, fees are decreased by a small amount. For more information about fee multiplier adjustments, see the [Web3 Research Page](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank}. - -## Transactions with Special Requirements - -Inclusion fees must be computable before execution and can only represent fixed logic. Some transactions warrant limiting resources with other strategies. For example: - -- Bonds are a type of fee that might be returned or slashed after some on-chain event. For example, you might want to require users to place a bond to participate in a vote. The bond might then be returned at the end of the referendum or slashed if the voter attempted malicious behavior. -- Deposits are fees that might be returned later. For example, you might require users to pay a deposit to execute an operation that uses storage. The user’s deposit could be returned if a subsequent operation frees up storage. -- Burn operations are used to pay for a transaction based on its internal logic. For example, a transaction might burn funds from the sender if the transaction creates new storage items to pay for the increased state size. -- Limits enable you to enforce constant or configurable limits on specific operations. For example, the default [Staking pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/staking){target=\_blank} only allows nominators to nominate 16 validators to limit the complexity of the validator election process. - -It is important to note that if you query the chain for a transaction fee, it only returns the inclusion fee. - -## Default Weight Annotations - -All dispatchable functions in the Polkadot SDK must specify a weight. The way of doing that is using the annotation-based system that lets you combine fixed values for database read/write weight and/or fixed values based on benchmarks. The most basic example would look like this: - -```rust -#[pallet::weight(100_000)] -fn my_dispatchable() { - // ... -} -``` - -Note that the [`ExtrinsicBaseWeight`](https://crates.parity.io/frame_support/weights/constants/struct.ExtrinsicBaseWeight.html){target=\_blank} is automatically added to the declared weight to account for the costs of simply including an empty extrinsic into a block. - -### Weights and Database Read/Write Operations - -To make weight annotations independent of the deployed database backend, they are defined as a constant and then used in the annotations when expressing database accesses performed by the dispatchable: - -```rust -#[pallet::weight(T::DbWeight::get().reads_writes(1, 2) + 20_000)] -fn my_dispatchable() { - // ... -} -``` - -This dispatchable allows one database to read and two to write, in addition to other things that add the additional 20,000. Database access is generally every time a value declared inside the [`#[pallet::storage]`](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/attr.storage.html){target=\_blank} block is accessed. However, unique accesses are counted because after a value is accessed, it is cached, and reaccessing it does not result in a database operation. That is: - -- Multiple reads of the exact value count as one read. -- Multiple writes of the exact value count as one write. -- Multiple reads of the same value, followed by a write to that value, count as one read and one write. -- A write followed by a read-only counts as one write. - -### Dispatch Classes - -Dispatches are broken into three classes: - -- Normal -- Operational -- Mandatory - -If a dispatch is not defined as `Operational` or `Mandatory` in the weight annotation, the dispatch is identified as `Normal` by default. You can specify that the dispatchable uses another class like this: - -```rust -#[pallet::dispatch((DispatchClass::Operational))] -fn my_dispatchable() { - // ... -} -``` - -This tuple notation also allows you to specify a final argument determining whether the user is charged based on the annotated weight. If you don't specify otherwise, `Pays::Yes` is assumed: - -```rust -#[pallet::dispatch(DispatchClass::Normal, Pays::No)] -fn my_dispatchable() { - // ... -} -``` - -#### Normal Dispatches - -Dispatches in this class represent normal user-triggered transactions. These types of dispatches only consume a portion of a block's total weight limit. For information about the maximum portion of a block that can be consumed for normal dispatches, see [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Normal dispatches are sent to the transaction pool. - -#### Operational Dispatches - -Unlike normal dispatches, which represent the usage of network capabilities, operational dispatches are those that provide network capabilities. Operational dispatches can consume the entire weight limit of a block. They are not bound by the [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\_blank}. Dispatches in this class are given maximum priority and are exempt from paying the [`length_fee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/){target=\_blank}. - -#### Mandatory Dispatches - -Mandatory dispatches are included in a block even if they cause the block to surpass its weight limit. You can only use the mandatory dispatch class for inherent transactions that the block author submits. This dispatch class is intended to represent functions in the block validation process. Because these dispatches are always included in a block regardless of the function weight, the validation process must prevent malicious nodes from abusing the function to craft valid but impossibly heavy blocks. You can typically accomplish this by ensuring that: - -- The operation performed is always light. -- The operation can only be included in a block once. - -To make it more difficult for malicious nodes to abuse mandatory dispatches, they cannot be included in blocks that return errors. This dispatch class serves the assumption that it is better to allow an overweight block to be created than not to allow any block to be created at all. - -### Dynamic Weights - -In addition to purely fixed weights and constants, the weight calculation can consider the input arguments of a dispatchable. The weight should be trivially computable from the input arguments with some basic arithmetic: - -```rust -use frame_support:: { - dispatch:: { - DispatchClass::Normal, - Pays::Yes, - }, - weights::Weight, -}; - -#[pallet::weight(FunctionOf( - |args: (&Vec,)| args.0.len().saturating_mul(10_000), - ) -] -fn handle_users(origin, calls: Vec) { - // Do something per user -} -``` - -## Post Dispatch Weight Correction - -Depending on the execution logic, a dispatchable function might consume less weight than was prescribed pre-dispatch. To correct weight, the function declares a different return type and returns its actual weight: - -```rust -#[pallet::weight(10_000 + 500_000_000)] -fn expensive_or_cheap(input: u64) -> DispatchResultWithPostInfo { - let was_heavy = do_calculation(input); - - if (was_heavy) { - // None means "no correction" from the weight annotation. - Ok(None.into()) - } else { - // Return the actual weight consumed. - Ok(Some(10_000).into()) - } -} -``` - -## Custom Fees - -You can also define custom fee systems through custom weight functions or inclusion fee functions. - -### Custom Weights - -Instead of using the default weight annotations, you can create a custom weight calculation type using the weights module. The custom weight calculation type must implement the following traits: - -- [`WeighData`](https://crates.parity.io/frame_support/weights/trait.WeighData.html){target=\_blank} to determine the weight of the dispatch. -- [`ClassifyDispatch`](https://crates.parity.io/frame_support/weights/trait.ClassifyDispatch.html){target=\_blank} to determine the class of the dispatch. -- [`PaysFee`](https://crates.parity.io/frame_support/weights/trait.PaysFee.html){target=\_blank} to determine whether the sender of the dispatch pays fees. - -The Polkadot SDK then bundles the output information of the three traits into the [`DispatchInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_support/dispatch/struct.DispatchInfo.html){target=\_blank} struct and provides it by implementing the [`GetDispatchInfo`](https://docs.rs/frame-support/latest/frame_support/dispatch/trait.GetDispatchInfo.html){target=\_blank} for all `Call` variants and opaque extrinsic types. This is used internally by the System and Executive modules. - -`ClassifyDispatch`, `WeighData`, and `PaysFee` are generic over T, which gets resolved into the tuple of all dispatch arguments except for the origin. The following example illustrates a struct that calculates the weight as `m * len(args)`, where `m` is a given multiplier and args is the concatenated tuple of all dispatch arguments. In this example, the dispatch class is `Operational` if the transaction has more than 100 bytes of length in arguments and will pay fees if the encoded length exceeds 10 bytes. - -```rust -struct LenWeight(u32); -impl WeighData for LenWeight { - fn weigh_data(&self, target: T) -> Weight { - let multiplier = self.0; - let encoded_len = target.encode().len() as u32; - multiplier * encoded_len - } -} - -impl ClassifyDispatch for LenWeight { - fn classify_dispatch(&self, target: T) -> DispatchClass { - let encoded_len = target.encode().len() as u32; - if encoded_len > 100 { - DispatchClass::Operational - } else { - DispatchClass::Normal - } - } -} - -impl PaysFee { - fn pays_fee(&self, target: T) -> Pays { - let encoded_len = target.encode().len() as u32; - if encoded_len > 10 { - Pays::Yes - } else { - Pays::No - } - } -} -``` - -A weight calculator function can also be coerced to the final type of the argument instead of defining it as a vague type that can be encoded. The code would roughly look like this: - -```rust -struct CustomWeight; -impl WeighData<(&u32, &u64)> for CustomWeight { - fn weigh_data(&self, target: (&u32, &u64)) -> Weight { - ... - } -} - -// given a dispatch: -#[pallet::call] -impl, I: 'static> Pallet { - #[pallet::weight(CustomWeight)] - fn foo(a: u32, b: u64) { ... } -} -``` - -In this example, the `CustomWeight` can only be used in conjunction with a dispatch with a particular signature `(u32, u64)`, as opposed to `LenWeight`, which can be used with anything because there aren't any assumptions about ``. - -#### Custom Inclusion Fee - -The following example illustrates how to customize your inclusion fee. You must configure the appropriate associated types in the respective module. - -```rust -// Assume this is the balance type -type Balance = u64; - -// Assume we want all the weights to have a `100 + 2 * w` conversion to fees -struct CustomWeightToFee; -impl WeightToFee for CustomWeightToFee { - fn convert(w: Weight) -> Balance { - let a = Balance::from(100); - let b = Balance::from(2); - let w = Balance::from(w); - a + b * w - } -} - -parameter_types! { - pub const ExtrinsicBaseWeight: Weight = 10_000_000; -} - -impl frame_system::Config for Runtime { - type ExtrinsicBaseWeight = ExtrinsicBaseWeight; -} - -parameter_types! { - pub const TransactionByteFee: Balance = 10; -} - -impl transaction_payment::Config { - type TransactionByteFee = TransactionByteFee; - type WeightToFee = CustomWeightToFee; - type FeeMultiplierUpdate = TargetedFeeAdjustment; -} - -struct TargetedFeeAdjustment(sp_std::marker::PhantomData); -impl> WeightToFee for TargetedFeeAdjustment { - fn convert(multiplier: Fixed128) -> Fixed128 { - // Don't change anything. Put any fee update info here. - multiplier - } -} -``` - -## Additional Resources - -You now know the weight system, how it affects transaction fee computation, and how to specify weights for your dispatchable calls. The next step is determining the correct weight for your dispatchable operations. You can use Substrate benchmarking functions and frame-benchmarking calls to test your functions with different parameters and empirically determine the proper weight in their worst-case scenarios. - -- [Benchmark](/parachains/customize-runtime/pallet-development/benchmark-pallet/) -- [`SignedExtension`](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} -- [Custom weights for the Example pallet](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/substrate/frame/examples/basic/src/weights.rs){target=\_blank} -- [Web3 Foundation Research](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\_blank} diff --git a/.ai/pages/reference-parachains-blocks-transactions-fees-transactions.md b/.ai/pages/reference-parachains-blocks-transactions-fees-transactions.md deleted file mode 100644 index 41d2ef16f..000000000 --- a/.ai/pages/reference-parachains-blocks-transactions-fees-transactions.md +++ /dev/null @@ -1,264 +0,0 @@ ---- -title: Transactions -description: Learn how to construct, submit, and validate transactions in the Polkadot SDK, covering signed, unsigned, and inherent types of transactions. -categories: Basics, Polkadot Protocol -url: https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/transactions/ ---- - -# Transactions - -## Introduction - -Transactions are essential components of blockchain networks, enabling state changes and the execution of key operations. In the Polkadot SDK, transactions, often called extrinsics, come in multiple forms, including signed, unsigned, and inherent transactions. - -This guide walks you through the different transaction types and how they're formatted, validated, and processed within the Polkadot ecosystem. You'll also learn how to customize transaction formats and construct transactions for FRAME-based runtimes, ensuring a complete understanding of how transactions are built and executed in Polkadot SDK-based chains. - -## What Is a Transaction? - -In the Polkadot SDK, transactions represent operations that modify the chain's state, bundled into blocks for execution. The term extrinsic is often used to refer to any data that originates outside the runtime and is included in the chain. While other blockchain systems typically refer to these operations as "transactions," the Polkadot SDK adopts the broader term "extrinsic" to capture the wide variety of data types that can be added to a block. - -There are three primary types of transactions (extrinsics) in the Polkadot SDK: - -- **Signed transactions**: Signed by the submitting account, often carrying transaction fees. -- **Unsigned transactions**: Submitted without a signature, often requiring custom validation logic. -- **Inherent transactions**: Typically inserted directly into blocks by block authoring nodes, without gossiping between peers. - -Each type serves a distinct purpose, and understanding when and how to use each is key to efficiently working with the Polkadot SDK. - -### Signed Transactions - -Signed transactions require an account's signature and typically involve submitting a request to execute a runtime call. The signature serves as a form of cryptographic proof that the sender has authorized the action, using their private key. These transactions often involve a transaction fee to cover the cost of execution and incentivize block producers. - -Signed transactions are the most common type of transaction and are integral to user-driven actions, such as token transfers. For instance, when you transfer tokens from one account to another, the sending account must sign the transaction to authorize the operation. - -For example, the [`pallet_balances::Call::transfer_allow_death`](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/pallet/struct.Pallet.html#method.transfer_allow_death){target=\_blank} extrinsic in the Balances pallet allows you to transfer tokens. Since your account initiates this transaction, your account key is used to sign it. You'll also be responsible for paying the associated transaction fee, with the option to include an additional tip to incentivize faster inclusion in the block. - -### Unsigned Transactions - -Unsigned transactions do not require a signature or account-specific data from the sender. Unlike signed transactions, they do not come with any form of economic deterrent, such as fees, which makes them susceptible to spam or replay attacks. Custom validation logic must be implemented to mitigate these risks and ensure these transactions are secure. - -Unsigned transactions typically involve scenarios where including a fee or signature is unnecessary or counterproductive. However, due to the absence of fees, they require careful validation to protect the network. For example, [`pallet_im_online::Call::heartbeat`](https://paritytech.github.io/polkadot-sdk/master/pallet_im_online/pallet/struct.Pallet.html#method.heartbeat){target=\_blank} extrinsic allows validators to send a heartbeat signal, indicating they are active. Since only validators can make this call, the logic embedded in the transaction ensures that the sender is a validator, making the need for a signature or fee redundant. - -Unsigned transactions are more resource-intensive than signed ones because custom validation is required, but they play a crucial role in certain operational scenarios, especially when regular user accounts aren't involved. - -### Inherent Transactions - -Inherent transactions are a specialized type of unsigned transaction that is used primarily for block authoring. Unlike signed or other unsigned transactions, inherent transactions are added directly by block producers and are not broadcasted to the network or stored in the transaction queue. They don't require signatures or the usual validation steps and are generally used to insert system-critical data directly into blocks. - -A key example of an inherent transaction is inserting a timestamp into each block. The [`pallet_timestamp::Call::now`](https://paritytech.github.io/polkadot-sdk/master/pallet_timestamp/pallet/struct.Pallet.html#method.now-1){target=\_blank} extrinsic allows block authors to include the current time in the block they are producing. Since the block producer adds this information, there is no need for transaction validation, like signature verification. The validation in this case is done indirectly by the validators, who check whether the timestamp is within an acceptable range before finalizing the block. - -Another example is the [`paras_inherent::Call::enter`](https://paritytech.github.io/polkadot-sdk/master/polkadot_runtime_parachains/paras_inherent/pallet/struct.Pallet.html#method.enter){target=\_blank} extrinsic, which enables parachain collator nodes to send validation data to the relay chain. This inherent transaction ensures that the necessary parachain data is included in each block without the overhead of gossiped transactions. - -Inherent transactions serve a critical role in block authoring by allowing important operational data to be added directly to the chain without needing the validation processes required for standard transactions. - -## Transaction Formats - -Understanding the structure of signed and unsigned transactions is crucial for developers building on Polkadot SDK-based chains. Whether you're optimizing transaction processing, customizing formats, or interacting with the transaction pool, knowing the format of extrinsics, Polkadot's term for transactions, is essential. - -### Types of Transaction Formats - -In Polkadot SDK-based chains, extrinsics can fall into three main categories: - -- **Unchecked extrinsics**: Typically used for signed transactions that require validation. They contain a signature and additional data, such as a nonce and information for fee calculation. Unchecked extrinsics are named as such because they require validation checks before being accepted into the transaction pool. -- **Checked extrinsics**: Typically used for inherent extrinsics (unsigned transactions); these don't require signature verification. Instead, they carry information such as where the extrinsic originates and any additional data required for the block authoring process. -- **Opaque extrinsics**: Used when the format of an extrinsic is not yet fully committed or finalized. They are still decodable, but their structure can be flexible depending on the context. - -### Signed Transaction Data Structure - -A signed transaction typically includes the following components: - -- **Signature**: Verifies the authenticity of the transaction sender. -- **Call**: The actual function or method call the transaction is requesting (for example, transferring funds). -- **Nonce**: Tracks the number of prior transactions sent from the account, helping to prevent replay attacks. -- **Tip**: An optional incentive to prioritize the transaction in block inclusion. -- **Additional data**: Includes details such as spec version, block hash, and genesis hash to ensure the transaction is valid within the correct runtime and chain context. - -Here's a simplified breakdown of how signed transactions are typically constructed in a Polkadot SDK runtime: - -``` code - + + -``` - -Each part of the signed transaction has a purpose, ensuring the transaction's authenticity and context within the blockchain. - -### Signed Extensions - -Polkadot SDK also provides the concept of [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\_blank}, which allow developers to extend extrinsics with additional data or validation logic before they are included in a block. The [`SignedExtension`](https://paritytech.github.io/try-runtime-cli/sp_runtime/traits/trait.SignedExtension.html){target=\_blank} set helps enforce custom rules or protections, such as ensuring the transaction's validity or calculating priority. - -The transaction queue regularly calls signed extensions to verify a transaction's validity before placing it in the ready queue. This safeguard ensures transactions won't fail in a block. Signed extensions are commonly used to enforce validation logic and protect the transaction pool from spam and replay attacks. - -In FRAME, a signed extension can hold any of the following types by default: - -- **[`AccountId`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/runtime/types_common/type.AccountId.html){target=\_blank}**: To encode the sender's identity. -- **[`Call`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Call){target=\_blank}**: To encode the pallet call to be dispatched. This data is used to calculate transaction fees. -- **[`AdditionalSigned`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.AdditionalSigned){target=\_blank}**: To handle any additional data to go into the signed payload allowing you to attach any custom logic prior to dispatching a transaction. -- **[`Pre`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Pre){target=\_blank}**: To encode the information that can be passed from before a call is dispatched to after it gets dispatched. - -Signed extensions can enforce checks like: - -- **[`CheckSpecVersion`](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/extensions/check_spec_version.rs.html){target=\_blank}**: Ensures the transaction is compatible with the runtime's current version. -- **[`CheckWeight`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.CheckWeight.html){target=\_blank}**: Calculates the weight (or computational cost) of the transaction, ensuring the block doesn't exceed the maximum allowed weight. - -These extensions are critical in the transaction lifecycle, ensuring that only valid and prioritized transactions are processed. - -## Transaction Construction - -Building transactions in the Polkadot SDK involves constructing a payload that can be verified, signed, and submitted for inclusion in a block. Each runtime in the Polkadot SDK has its own rules for validating and executing transactions, but there are common patterns for constructing a signed transaction. - -### Construct a Signed Transaction - -A signed transaction in the Polkadot SDK includes various pieces of data to ensure security, prevent replay attacks, and prioritize processing. Here's an overview of how to construct one: - -1. **Construct the unsigned payload**: Gather the necessary information for the call, including: - - - **Pallet index**: Identifies the pallet where the runtime function resides. - - **Function index**: Specifies the particular function to call in the pallet. - - **Parameters**: Any additional arguments required by the function call. - -2. **Create a signing payload**: Once the unsigned payload is ready, additional data must be included: - - - **Transaction nonce**: Unique identifier to prevent replay attacks. - - **Era information**: Defines how long the transaction is valid before it's dropped from the pool. - - **Block hash**: Ensures the transaction doesn't execute on the wrong chain or fork. - -3. **Sign the payload**: Using the sender's private key, sign the payload to ensure that the transaction can only be executed by the account holder. -4. **Serialize the signed payload**: Once signed, the transaction must be serialized into a binary format, ensuring the data is compact and easy to transmit over the network. -5. **Submit the serialized transaction**: Finally, submit the serialized transaction to the network, where it will enter the transaction pool and wait for processing by an authoring node. - -The following is an example of how a signed transaction might look: - -``` rust -node_runtime::UncheckedExtrinsic::new_signed( - function.clone(), // some call - sp_runtime::AccountId32::from(sender.public()).into(), // some sending account - node_runtime::Signature::Sr25519(signature.clone()), // the account's signature - extra.clone(), // the signed extensions -) -``` - -### Transaction Encoding - -Before a transaction is sent to the network, it is serialized and encoded using a structured encoding process that ensures consistency and prevents tampering: - -- **`[1]`**: Compact encoded length in bytes of the entire transaction. -- **`[2]`**: A u8 containing 1 byte to indicate whether the transaction is signed or unsigned (1 bit) and the encoded transaction version ID (7 bits). -- **`[3]`**: If signed, this field contains an account ID, an SR25519 signature, and some extra data. -- **`[4]`**: Encoded call data, including pallet and function indices and any required arguments. - -This encoded format ensures consistency and efficiency in processing transactions across the network. By adhering to this format, applications can construct valid transactions and pass them to the network for execution. - -To learn more about how compact encoding works using SCALE, see the [SCALE Codec](https://github.com/paritytech/parity-scale-codec){target=\_blank} README on GitHub. - -### Customize Transaction Construction - -Although the basic steps for constructing transactions are consistent across Polkadot SDK-based chains, developers can customize transaction formats and validation rules. For example: - -- **Custom pallets**: You can define new pallets with custom function calls, each with its own parameters and validation logic. -- **Signed extensions**: Developers can implement custom extensions that modify how transactions are prioritized, validated, or included in blocks. - -By leveraging Polkadot SDK's modular design, developers can create highly specialized transaction logic tailored to their chain's needs. - -## Lifecycle of a Transaction - -In the Polkadot SDK, transactions are often referred to as extrinsics because the data in transactions originates outside of the runtime. These transactions contain data that initiates changes to the chain state. The most common type of extrinsic is a signed transaction, which is cryptographically verified and typically incurs a fee. This section focuses on how signed transactions are processed, validated, and ultimately included in a block. - -### Define Transaction Properties - -The Polkadot SDK runtime defines key transaction properties, such as: - -- **Transaction validity**: Ensures the transaction meets all runtime requirements. -- **Signed or unsigned**: Identifies whether a transaction needs to be signed by an account. -- **State changes**: Determines how the transaction modifies the state of the chain. - -Pallets, which compose the runtime's logic, define the specific transactions that your chain supports. When a user submits a transaction, such as a token transfer, it becomes a signed transaction, verified by the user's account signature. If the account has enough funds to cover fees, the transaction is executed, and the chain's state is updated accordingly. - -### Process on a Block Authoring Node - -In Polkadot SDK-based networks, some nodes are authorized to author blocks. These nodes validate and process transactions. When a transaction is sent to a node that can produce blocks, it undergoes a lifecycle that involves several stages, including validation and execution. Non-authoring nodes gossip the transaction across the network until an authoring node receives it. The following diagram illustrates the lifecycle of a transaction that's submitted to a network and processed by an authoring node. - -![Transaction lifecycle diagram](/images/reference/parachains/blocks-transactions-fees/transactions/transactions-01.webp){ style="background:white" } - -### Validate and Queue - -Once a transaction reaches an authoring node, it undergoes an initial validation process to ensure it meets specific conditions defined in the runtime. This validation includes checks for: - -- **Correct nonce**: Ensures the transaction is sequentially valid for the account. -- **Sufficient funds**: Confirms the account can cover any associated transaction fees. -- **Signature validity**: Verifies that the sender's signature matches the transaction data. - -After these checks, valid transactions are placed in the transaction pool, where they are queued for inclusion in a block. The transaction pool regularly re-validates queued transactions to ensure they remain valid before being processed. To reach consensus, two-thirds of the nodes must agree on the order of the transactions executed and the resulting state change. Transactions are validated and queued on the local node in a transaction pool to prepare for consensus. - -#### Transaction Pool - -The transaction pool is responsible for managing valid transactions. It ensures that only transactions that pass initial validity checks are queued. Transactions that fail validation, expire, or become invalid for other reasons are removed from the pool. - -The transaction pool organizes transactions into two queues: - -- **Ready queue**: Transactions that are valid and ready to be included in a block. -- **Future queue**: Transactions that are not yet valid but could be in the future, such as transactions with a nonce too high for the current state. - -Details on how the transaction pool validates transactions, including fee and signature handling, can be found in the [`validate_transaction`](https://paritytech.github.io/polkadot-sdk/master/sp_transaction_pool/runtime_api/trait.TaggedTransactionQueue.html#method.validate_transaction){target=\_blank} method. - -#### Invalid Transactions - -If a transaction is invalid, for example, due to an invalid signature or insufficient funds, it is rejected and won't be added to the block. Invalid transactions might be rejected for reasons such as: - -- The transaction has already been included in a block. -- The transaction's signature does not match the sender. -- The transaction is too large to fit in the current block. - -### Transaction Ordering and Priority - -When a node is selected as the next block author, it prioritizes transactions based on weight, length, and tip amount. The goal is to fill the block with high-priority transactions without exceeding its maximum size or computational limits. Transactions are ordered as follows: - -- **Inherents first**: Inherent transactions, such as block timestamp updates, are always placed first. -- **Nonce-based ordering**: Transactions from the same account are ordered by their nonce. -- **Fee-based ordering**: Among transactions with the same nonce or priority level, those with higher fees are prioritized. - -### Transaction Execution - -Once a block author selects transactions from the pool, the transactions are executed in priority order. As each transaction is processed, the state changes are written directly to the chain's storage. It's important to note that these changes are not cached, meaning a failed transaction won't revert earlier state changes, which could leave the block in an inconsistent state. - -Events are also written to storage. Runtime logic should not emit an event before performing the associated actions. If the associated transaction fails after the event was emitted, the event will not revert. - -## Transaction Mortality - -Transactions in the network can be configured as either mortal (with expiration) or immortal (without expiration). Every transaction payload contains a block checkpoint (reference block number and hash) and an era/validity period that determines how many blocks after the checkpoint the transaction remains valid. - -When a transaction is submitted, the network validates it against these parameters. If the transaction is not included in a block within the specified validity window, it is automatically removed from the transaction queue. - -- **Mortal transactions**: Have a finite lifespan and will expire after a specified number of blocks. For example, a transaction with a block checkpoint of 1000 and a validity period of 64 blocks will be valid from blocks 1000 to 1064. - -- **Immortal transactions**: Never expire and remain valid indefinitely. To create an immortal transaction, set the block checkpoint to 0 (genesis block), use the genesis hash as a reference, and set the validity period to 0. - -However, immortal transactions pose significant security risks through replay attacks. If an account is reaped (balance drops to zero, account removed) and later re-funded, malicious actors can replay old immortal transactions. - -The blockchain maintains only a limited number of prior block hashes for reference validation, called `BlockHashCount`. If your validity period exceeds `BlockHashCount`, the effective validity period becomes the minimum of your specified period and the block hash count. - -## Unique Identifiers for Extrinsics - -Transaction hashes are **not unique identifiers** in Polkadot SDK-based chains. - -Key differences from traditional blockchains: - -- Transaction hashes serve only as fingerprints of transaction information. -- Multiple valid transactions can share the same hash. -- Hash uniqueness assumptions lead to serious issues. - -For example, when an account is reaped (removed due to insufficient balance) and later recreated, it resets to nonce 0, allowing identical transactions to be valid at different points: - -| Block | Extrinsic Index | Hash | Origin | Nonce | Call | Result | -|-------|----------------|------|-----------|-------|---------------------|-------------------------------| -| 100 | 0 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Account A reaped | -| 150 | 5 | 0x02 | Account B | 4 | Transfer 7 DOT to A | Account A created (nonce = 0) | -| 200 | 2 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Successful transaction | - -Notice that blocks 100 and 200 contain transactions with identical hashes (0x01) but are completely different, valid operations occurring at different times. - -Additional complexity comes from Polkadot SDK's origin abstraction. Origins can represent collectives, governance bodies, or other non-account entities that don't maintain nonces like regular accounts and might dispatch identical calls multiple times with the same hash values. Each execution occurs in different chain states with different results. - -The correct way to uniquely identify an extrinsic on a Polkadot SDK-based chain is to use the block ID (height or hash) and the extrinsic index. Since the Polkadot SDK defines blocks as headers plus ordered arrays of extrinsics, the index position within a canonical block provides guaranteed uniqueness. - -## Additional Resources - -For a video overview of the lifecycle of transactions and the types of transactions that exist, see the [Transaction lifecycle](https://www.youtube.com/watch?v=3pfM0GOp02c){target=\_blank} seminar from Parity Tech. diff --git a/.ai/pages/reference-parachains-chain-data.md b/.ai/pages/reference-parachains-chain-data.md deleted file mode 100644 index dd62f40aa..000000000 --- a/.ai/pages/reference-parachains-chain-data.md +++ /dev/null @@ -1,356 +0,0 @@ ---- -title: Chain Data -description: Learn how to expose and utilize chain data for blockchain applications. Discover runtime metadata, RPC APIs, and tools for efficient development. -categories: Basics, Polkadot Protocol -url: https://docs.polkadot.com/reference/parachains/chain-data/ ---- - -# Chain Data - -## Introduction - -Understanding and leveraging on-chain data is a fundamental aspect of blockchain development. Whether you're building frontend applications or backend systems, accessing and decoding runtime metadata is vital to interacting with the blockchain. This guide introduces you to the tools and processes for generating and retrieving metadata, explains its role in application development, and outlines the additional APIs available for interacting with a Polkadot node. By mastering these components, you can ensure seamless communication between your applications and the blockchain. - -## Application Development - -You might not be directly involved in building frontend applications as a blockchain developer. However, most applications that run on a blockchain require some form of frontend or user-facing client to enable users or other programs to access and modify the data that the blockchain stores. For example, you might develop a browser-based, mobile, or desktop application that allows users to submit transactions, post articles, view their assets, or track previous activity. The backend for that application is configured in the runtime logic for your blockchain, but the frontend client makes the runtime features accessible to your users. - -For your custom chain to be useful to others, you'll need to provide a client application that allows users to view, interact with, or update information that the blockchain keeps track of. In this article, you'll learn how to expose information about your runtime so that client applications can use it, see examples of the information exposed, and explore tools and libraries that use it. - -## Understand Metadata - -Polkadot SDK-based blockchain networks are designed to expose their runtime information, allowing developers to learn granular details regarding pallets, RPC calls, and runtime APIs. The metadata also exposes their related documentation. The chain's metadata is [SCALE-encoded](/reference/parachains/data-encoding/){target=\_blank}, allowing for the development of browser-based, mobile, or desktop applications to support the chain's runtime upgrades seamlessly. It is also possible to develop applications compatible with multiple Polkadot SDK-based chains simultaneously. - -## Expose Runtime Information as Metadata - -To interact with a node or the state of the blockchain, you need to know how to connect to the chain and access the exposed runtime features. This interaction involves a Remote Procedure Call (RPC) through a node endpoint address, commonly through a secure web socket connection. - -An application developer typically needs to know the contents of the runtime logic, including the following details: - -- Version of the runtime the application is connecting to. -- Supported APIs. -- Implemented pallets. -- Defined functions and corresponding type signatures. -- Defined custom types. -- Exposed parameters users can set. - -As the Polkadot SDK is modular and provides a composable framework for building blockchains, there are limitless opportunities to customize the schema of properties. Each runtime can be configured with its properties, including function calls and types, which can be changed over time with runtime upgrades. - -The Polkadot SDK enables you to generate the runtime metadata schema to capture information unique to a runtime. The metadata for a runtime describes the pallets in use and types defined for a specific runtime version. The metadata includes information about each pallet's storage items, functions, events, errors, and constants. The metadata also provides type definitions for any custom types included in the runtime. - -Metadata provides a complete inventory of a chain's runtime. It is key to enabling client applications to interact with the node, parse responses, and correctly format message payloads sent back to that chain. - -## Generate Metadata - -To efficiently use the blockchain's networking resources and minimize the data transmitted over the network, the metadata schema is encoded using the [Parity SCALE Codec](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank}. This encoding is done automatically through the [`scale-info`](https://docs.rs/scale-info/latest/scale_info/){target=\_blank}crate. - -At a high level, generating the metadata involves the following steps: - -1. The pallets in the runtime logic expose callable functions, types, parameters, and documentation that need to be encoded in the metadata. -2. The `scale-info` crate collects type information for the pallets in the runtime, builds a registry of the pallets that exist in a particular runtime, and the relevant types for each pallet in the registry. The type information is detailed enough to enable encoding and decoding for every type. -3. The [`frame-metadata`](https://github.com/paritytech/frame-metadata){target=\_blank} crate describes the structure of the runtime based on the registry provided by the `scale-info` crate. -4. Nodes provide the RPC method `state_getMetadata` to return a complete description of all the types in the current runtime as a hex-encoded vector of SCALE-encoded bytes. - -## Retrieve Runtime Metadata - -The type information provided by the metadata enables applications to communicate with nodes using different runtime versions and across chains that expose different calls, events, types, and storage items. The metadata also allows libraries to generate a substantial portion of the code needed to communicate with a given node, enabling libraries like [`subxt`](https://github.com/paritytech/subxt){target=\_blank} to generate frontend interfaces that are specific to a target chain. - -### Use Polkadot.js - -Visit the [Polkadot.js Portal](https://polkadot.js.org/apps/#/rpc){target=\_blank} and select the **Developer** dropdown in the top banner. Select **RPC Calls** to make the call to request metadata. Follow these steps to make the RPC call: - -1. Select **state** as the endpoint to call. -2. Select **`getMetadata(at)`** as the method to call. -3. Click **Submit RPC call** to submit the call and return the metadata in JSON format. - -### Use Curl - -You can fetch the metadata for the network by calling the node's RPC endpoint. This request returns the metadata in bytes rather than human-readable JSON: - -```sh -curl -H "Content-Type: application/json" \ --d '{"id":1, "jsonrpc":"2.0", "method": "state_getMetadata"}' \ -https://rpc.polkadot.io - -``` - -### Use Subxt - -[`subxt`](https://github.com/paritytech/subxt){target=\_blank} may also be used to fetch the metadata of any data in a human-readable JSON format: - -```sh -subxt metadata --url wss://rpc.polkadot.io --format json > spec.json -``` - -Another option is to use the [`subxt` explorer web UI](https://paritytech.github.io/subxt-explorer/#/){target=\_blank}. - -## Client Applications and Metadata - -The metadata exposes the expected way to decode each type, meaning applications can send, retrieve, and process application information without manual encoding and decoding. Client applications must use the [SCALE codec library](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\_blank} to encode and decode RPC payloads to use the metadata. Client applications use the metadata to interact with the node, parse responses, and format message payloads sent to the node. - -## Metadata Format - -Although the SCALE-encoded bytes can be decoded using the `frame-metadata` and [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} libraries, there are other tools, such as `subxt` and the Polkadot-JS API, that can convert the raw data to human-readable JSON format. - -The types and type definitions included in the metadata returned by the `state_getMetadata` RPC call depend on the runtime's metadata version. - -In general, the metadata includes the following information: - -- A constant identifying the file as containing metadata. -- The version of the metadata format used in the runtime. -- Type definitions for all types used in the runtime and generated by the `scale-info` crate. -- Pallet information for the pallets included in the runtime in the order that they are defined in the `construct_runtime` macro. - -!!!tip - Depending on the frontend library used (such as the [Polkadot API](https://papi.how/){target=\_blank}), they may format the metadata differently than the raw format shown. - -The following example illustrates a condensed and annotated section of metadata decoded and converted to JSON: - -```json -[ - 1635018093, - { - "V14": { - "types": { - "types": [{}] - }, - "pallets": [{}], - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [{}] - }, - "ty": 141 - } - } -] - -``` - -The constant `1635018093` is a magic number that identifies the file as a metadata file. The rest of the metadata is divided into the `types`, `pallets`, and `extrinsic` sections: - -- The `types` section contains an index of the types and information about each type's type signature. -- The `pallets` section contains information about each pallet in the runtime. -- The `extrinsic` section describes the type identifier and transaction format version that the runtime uses. - -Different extrinsic versions can have varying formats, especially when considering [signed transactions](/reference/parachains/blocks-transactions-fees/transactions/#signed-transactions){target=\_blank}. - -### Pallets - -The following is a condensed and annotated example of metadata for a single element in the `pallets` array (the [`sudo`](https://paritytech.github.io/polkadot-sdk/master/pallet_sudo/index.html){target=\_blank} pallet): - -```json -{ - "name": "Sudo", - "storage": { - "prefix": "Sudo", - "entries": [ - { - "name": "Key", - "modifier": "Optional", - "ty": { - "Plain": 0 - }, - "default": [0], - "docs": ["The `AccountId` of the sudo key."] - } - ] - }, - "calls": { - "ty": 117 - }, - "event": { - "ty": 42 - }, - "constants": [], - "error": { - "ty": 124 - }, - "index": 8 -} - -``` - -Every element metadata contains the name of the pallet it represents and information about its storage, calls, events, and errors. You can look up details about the definition of the calls, events, and errors by viewing the type index identifier. The type index identifier is the `u32` integer used to access the type information for that item. For example, the type index identifier for calls in the Sudo pallet is 117. If you view information for that type identifier in the `types` section of the metadata, it provides information about the available calls, including the documentation for each call. - -For example, the following is a condensed excerpt of the calls for the Sudo pallet: - -```json -{ - "id": 117, - "type": { - "path": ["pallet_sudo", "pallet", "Call"], - "params": [ - { - "name": "T", - "type": null - } - ], - "def": { - "variant": { - "variants": [ - { - "name": "sudo", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 0, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "sudo_unchecked_weight", - "fields": [ - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - }, - { - "name": "weight", - "type": 8, - "typeName": "Weight" - } - ], - "index": 1, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Root` origin" - ] - }, - { - "name": "set_key", - "fields": [ - { - "name": "new", - "type": 103, - "typeName": "AccountIdLookupOf" - } - ], - "index": 2, - "docs": [ - "Authenticates current sudo key, sets the given AccountId (`new`) as the new sudo" - ] - }, - { - "name": "sudo_as", - "fields": [ - { - "name": "who", - "type": 103, - "typeName": "AccountIdLookupOf" - }, - { - "name": "call", - "type": 114, - "typeName": "Box<::RuntimeCall>" - } - ], - "index": 3, - "docs": [ - "Authenticates sudo key, dispatches a function call with `Signed` origin from a given account" - ] - } - ] - } - } - } -} - -``` - -For each field, you can access type information and metadata for the following: - -- **Storage metadata**: Provides the information required to enable applications to get information for specific storage items. -- **Call metadata**: Includes information about the runtime calls defined by the `#[pallet]` macro including call names, arguments and documentation. -- **Event metadata**: Provides the metadata generated by the `#[pallet::event]` macro, including the name, arguments, and documentation for each pallet event. -- **Constants metadata**: Provides metadata generated by the `#[pallet::constant]` macro, including the name, type, and hex-encoded value of the constant. -- **Error metadata**: Provides metadata generated by the `#[pallet::error]` macro, including the name and documentation for each pallet error. - -!!!tip - Type identifiers change from time to time, so you should avoid relying on specific type identifiers in your applications. - -### Extrinsic - -The runtime generates extrinsic metadata and provides useful information about transaction format. When decoded, the metadata contains the transaction version and the list of signed extensions. - -For example: - -```json -{ - "extrinsic": { - "ty": 126, - "version": 4, - "signed_extensions": [ - { - "identifier": "CheckNonZeroSender", - "ty": 132, - "additional_signed": 41 - }, - { - "identifier": "CheckSpecVersion", - "ty": 133, - "additional_signed": 4 - }, - { - "identifier": "CheckTxVersion", - "ty": 134, - "additional_signed": 4 - }, - { - "identifier": "CheckGenesis", - "ty": 135, - "additional_signed": 11 - }, - { - "identifier": "CheckMortality", - "ty": 136, - "additional_signed": 11 - }, - { - "identifier": "CheckNonce", - "ty": 138, - "additional_signed": 41 - }, - { - "identifier": "CheckWeight", - "ty": 139, - "additional_signed": 41 - }, - { - "identifier": "ChargeTransactionPayment", - "ty": 140, - "additional_signed": 41 - } - ] - }, - "ty": 141 -} - -``` - -The type system is [composite](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/frame_runtime_types/index.html){target=\_blank}, meaning each type identifier contains a reference to a specific type or to another type identifier that provides information about the associated primitive types. - -For example, you can encode the `BitVec` type, but to decode it properly, you must know the types used for the `Order` and `Store` types. To find type information for `Order` and `Store`, you can use the path in the decoded JSON to locate their type identifiers. - -## Included RPC APIs - -A standard node comes with the following APIs to interact with a node: - -- **[`AuthorApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/author/trait.AuthorApiServer.html){target=\_blank}**: Make calls into a full node, including authoring extrinsics and verifying session keys. -- **[`ChainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/chain/trait.ChainApiServer.html){target=\_blank}**: Retrieve block header and finality information. -- **[`OffchainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/offchain/trait.OffchainApiServer.html){target=\_blank}**: Make RPC calls for off-chain workers. -- **[`StateApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/state/trait.StateApiServer.html){target=\_blank}**: Query information about on-chain state such as runtime version, storage items, and proofs. -- **[`SystemApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/system/trait.SystemApiServer.html){target=\_blank}**: Retrieve information about network state, such as connected peers and node roles. - -## Additional Resources - -The following tools can help you locate and decode metadata: - -- [Subxt Explorer](https://paritytech.github.io/subxt-explorer/#/){target=\_blank} -- [Metadata Portal 🌗](https://github.com/paritytech/metadata-portal){target=\_blank} -- [De[code] Sub[strate]](https://github.com/paritytech/desub){target=\_blank} diff --git a/.ai/pages/reference-parachains-consensus-async-backing.md b/.ai/pages/reference-parachains-consensus-async-backing.md deleted file mode 100644 index adabf852a..000000000 --- a/.ai/pages/reference-parachains-consensus-async-backing.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -url: https://docs.polkadot.com/reference/parachains/consensus/async-backing/ ---- - -TODO diff --git a/.ai/pages/reference-parachains-consensus-elastic-scaling.md b/.ai/pages/reference-parachains-consensus-elastic-scaling.md deleted file mode 100644 index c826d5b68..000000000 --- a/.ai/pages/reference-parachains-consensus-elastic-scaling.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Elastic Scaling -description: Learn how elastic scaling in Polkadot boosts parachain throughput, reduces latency, and supports dynamic, cost-efficient resource allocation. -categories: Polkadot Protocol -url: https://docs.polkadot.com/reference/parachains/consensus/elastic-scaling/ ---- - -# Elastic Scaling - -## Introduction - -Polkadot's architecture delivers scalability and security through its shared security model, where the relay chain coordinates and validates multiple parallel chains. - -Elastic scaling enhances this architecture by allowing parachains to utilize multiple computational cores simultaneously, breaking the previous 1:1 relationship between parachain and relay chain blocks. - -This technical advancement enables parachains to process multiple blocks within a single relay chain block, significantly increasing throughput capabilities. By leveraging [Agile Coretime](/polkadot-protocol/architecture/polkadot-chain/agile-coretime){target=\_blank}, parachains can dynamically adjust their processing capacity based on demand, creating an efficient and responsive infrastructure for high-throughput applications. - -## How Elastic Scaling Works - -Elastic scaling enables parachains to process multiple blocks in parallel by utilizing additional cores on the relay chain. This section provides a technical analysis of the performance advantages and details of the implementation. - -Consider a parachain that needs to process four consecutive parablocks. With traditional single-core allocation, the validation process follows a strictly sequential pattern. Each parablock undergoes a two-phase process on the relay chain: - -1. **Backing phase**: Validators create and distribute validity statements. -2. **Inclusion phase**: The parablock is included in the relay chain after availability verification. - -Throughout the following diagrams, specific notation is used to represent different components of the system: - -- **R1, R2, ...**: Relay chain blocks (produced at ~6-second intervals). -- **P1, P2, ...**: Parachain blocks that need validation and inclusion. -- **C1, C2, ...**: Cores on the relay chain. - -In the single-core scenario (assuming a 6-second relay chain block time), processing four parablocks requires approximately 30 seconds: - -```mermaid -sequenceDiagram - participant R1 as R1 - participant R2 as R2 - participant R3 as R3 - participant R4 as R4 - participant R5 as R5 - - Note over R1,R5: Single Core Scenario - - rect rgb(200, 220, 240) - Note right of R1: Core C1 - R1->>R1: Back P1 - R2->>R2: Include P1 - R2->>R2: Back P2 - R3->>R3: Include P2 - R3->>R3: Back P3 - R4->>R4: Include P3 - R4->>R4: Back P4 - R5->>R5: Include P4 - end -``` - -With elastic scaling utilizing two cores simultaneously, the same four parablocks can be processed in approximately 18 seconds: - -```mermaid -sequenceDiagram - participant R1 as R1 - participant R2 as R2 - participant R3 as R3 - participant R4 as R4 - participant R5 as R5 - - Note over R1,R3: Multi-Core Scenario - - rect rgb(200, 220, 240) - Note right of R1: Core C1 - R1->>R1: Back P1 - R2->>R2: Include P1 - R2->>R2: Back P2 - R3->>R3: Include P2 - end - - rect rgb(220, 200, 240) - Note right of R1: Core C2 - R1->>R1: Back P3 - R2->>R2: Include P3 - R2->>R2: Back P4 - R3->>R3: Include P4 - end -``` - -To help interpret the sequence diagrams above, note the following key elements: - -- The horizontal axis represents time progression through relay chain blocks (R1-R5). -- Each colored rectangle shows processing on a specific core (C1 or C2). -- In the single-core scenario, all blocks must be processed sequentially on one core. -- In the multi-core scenario, blocks are processed in parallel across multiple cores, reducing total time. - -The relay chain processes these multiple parablocks as independent validation units during the backing, availability, and approval phases. However, during inclusion, it verifies that their state roots align properly to maintain chain consistency. - -From an implementation perspective: - -- **Parachain side**: Collators must increase their block production rate to utilize multiple cores fully. -- **Validation process**: Each core operates independently, but with coordinated state verification. -- **Resource management**: Cores are dynamically allocated based on parachain requirements. -- **State consistency**: While backed and processed in parallel, the parablocks maintain sequential state transitions. - -## Benefits of Elastic Scaling - -- **Increased throughput**: Multiple concurrent cores enable parachains to process transactions at multiples of their previous capacity. By allowing multiple parachain blocks to be validated within each relay chain block cycle, applications can achieve significantly higher transaction volumes. - -- **Lower latency**: Transaction finality improves substantially with multi-core processing. Parachains currently achieve 2-second latency with three cores, with projected improvements to 500ms using 12 cores, enabling near-real-time application responsiveness. - -- **Resource efficiency**: Applications acquire computational resources precisely matched to their needs, eliminating wasteful over-provisioning. Coretime can be purchased at granular intervals (blocks, hours, days), creating cost-effective operations, particularly for applications with variable transaction patterns. - -- **Scalable growth**: New applications can launch with minimal initial resource commitment and scale dynamically as adoption increases. This eliminates the traditional paradox of either over-allocating resources (increasing costs) or under-allocating (degrading performance) during growth phases. - -- **Workload distribution**: Parachains intelligently distribute workloads across cores during peak demand periods and release resources when traffic subsides. Paired with secondary coretime markets, this ensures maximum resource utilization across the entire network ecosystem. - -- **Reliable performance**: End-users experience reliable application performance regardless of network congestion levels. Applications maintain responsiveness even during traffic spikes, eliminating performance degradation that commonly impacts blockchain applications during high-demand periods. - -## Use Cases - -Elastic scaling enables applications to dynamically adjust their resource consumption based on real-time demand. This is especially valuable for decentralized applications where usage patterns can be highly variable. The following examples illustrate common scenarios where elastic scaling delivers significant performance and cost-efficiency benefits. - -### Handling Sudden Traffic Spikes - -Many decentralized applications experience unpredictable, high-volume traffic bursts, especially in gaming, DeFi protocols, NFT auctions, messaging platforms, and social media. Elastic scaling allows these systems to acquire additional coretime during peak usage and release it during quieter periods, ensuring responsiveness without incurring constant high infrastructure costs. - -### Supporting Early-Stage Growth - -Startups and new projects often begin with uncertain or volatile demand. With elastic scaling, teams can launch with minimal compute resources (e.g., a single core) and gradually scale as adoption increases. This prevents overprovisioning and enables cost-efficient growth until the application is ready for more permanent or horizontal scaling. - -### Scaling Massive IoT Networks - -Internet of Things (IoT) applications often involve processing data from millions of devices in real time. Elastic scaling supports this need by enabling high-throughput transaction processing as demand fluctuates. Combined with Polkadot’s shared security model, it provides a reliable and privacy-preserving foundation for large-scale IoT deployments. - -### Powering Real-Time, Low-Latency Systems - -Applications like payment processors, trading platforms, gaming engines, or real-time data feeds require fast, consistent performance. Elastic scaling can reduce execution latency during demand spikes, helping ensure low-latency, reliable service even under heavy load. diff --git a/.ai/pages/reference-parachains-consensus.md b/.ai/pages/reference-parachains-consensus.md deleted file mode 100644 index 7f1a8ec17..000000000 --- a/.ai/pages/reference-parachains-consensus.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -url: https://docs.polkadot.com/reference/parachains/consensus/ ---- - -TODO diff --git a/.ai/pages/reference-parachains-cryptography.md b/.ai/pages/reference-parachains-cryptography.md deleted file mode 100644 index 07407b2e4..000000000 --- a/.ai/pages/reference-parachains-cryptography.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -title: Cryptography -description: A concise guide to cryptography in blockchain, covering hash functions, encryption types, digital signatures, and elliptic curve applications. -categories: Basics, Polkadot Protocol -url: https://docs.polkadot.com/reference/parachains/cryptography/ ---- - -# Cryptography - -## Introduction - -Cryptography forms the backbone of blockchain technology, providing the mathematical verifiability crucial for consensus systems, data integrity, and user security. While a deep understanding of the underlying mathematical processes isn't necessary for most blockchain developers, grasping the fundamental applications of cryptography is essential. This page comprehensively overviews cryptographic implementations used across Polkadot SDK-based chains and the broader blockchain ecosystem. - -## Hash Functions - -Hash functions are fundamental to blockchain technology, creating a unique digital fingerprint for any piece of data, including simple text, images, or any other form of file. They map input data of any size to a fixed-size output (typically 32 bytes) using complex mathematical operations. Hashing is used to verify data integrity, create digital signatures, and provide a secure way to store passwords. This form of mapping is known as the ["pigeonhole principle,"](https://en.wikipedia.org/wiki/Pigeonhole_principle){target=\_blank} it is primarily implemented to efficiently and verifiably identify data from large sets. - -### Key Properties of Hash Functions - -- **Deterministic**: The same input always produces the same output. -- **Quick computation**: It's easy to calculate the hash value for any given input. -- **Pre-image resistance**: It's infeasible to generate the input data from its hash. -- **Small changes in input yield large changes in output**: Known as the ["avalanche effect"](https://en.wikipedia.org/wiki/Avalanche_effect){target=\_blank}. -- **Collision resistance**: The probabilities are extremely low to find two different inputs with the same hash. - -### Blake2 - -The Polkadot SDK utilizes Blake2, a state-of-the-art hashing method that offers: - -- Equal or greater security compared to [SHA-2](https://en.wikipedia.org/wiki/SHA-2){target=\_blank}. -- Significantly faster performance than other algorithms. - -These properties make Blake2 ideal for blockchain systems, reducing sync times for new nodes and lowering the resources required for validation. For detailed technical specifications about Blake2, see the [official Blake2 paper](https://www.blake2.net/blake2.pdf){target=\_blank}. - -## Types of Cryptography - -There are two different ways that cryptographic algorithms are implemented: symmetric cryptography and asymmetric cryptography. - -### Symmetric Cryptography - -Symmetric encryption is a branch of cryptography that isn't based on one-way functions, unlike asymmetric cryptography. It uses the same cryptographic key to encrypt plain text and decrypt the resulting ciphertext. - -Symmetric cryptography is a type of encryption that has been used throughout history, such as the Enigma Cipher and the Caesar Cipher. It is still widely used today and can be found in Web2 and Web3 applications alike. There is only one single key, and a recipient must also have access to it to access the contained information. - -#### Advantages {: #symmetric-advantages } - -- Fast and efficient for large amounts of data. -- Requires less computational power. - -#### Disadvantages {: #symmetric-disadvantages } - -- Key distribution can be challenging. -- Scalability issues in systems with many users. - -### Asymmetric Cryptography - -Asymmetric encryption is a type of cryptography that uses two different keys, known as a keypair: a public key, used to encrypt plain text, and a private counterpart, used to decrypt the ciphertext. - -The public key encrypts a fixed-length message that can only be decrypted with the recipient's private key and, sometimes, a set password. The public key can be used to cryptographically verify that the corresponding private key was used to create a piece of data without compromising the private key, such as with digital signatures. This has obvious implications for identity, ownership, and properties and is used in many different protocols across Web2 and Web3. - -#### Advantages {: #asymmetric-advantages } - -- Solves the key distribution problem. -- Enables digital signatures and secure key exchange. - -#### Disadvantages {: #asymmetric-disadvantages } - -- Slower than symmetric encryption. -- Requires more computational resources. - -### Trade-offs and Compromises - -Symmetric cryptography is faster and requires fewer bits in the key to achieve the same level of security that asymmetric cryptography provides. However, it requires a shared secret before communication can occur, which poses issues to its integrity and a potential compromise point. On the other hand, asymmetric cryptography doesn't require the secret to be shared ahead of time, allowing for far better end-user security. - -Hybrid symmetric and asymmetric cryptography is often used to overcome the engineering issues of asymmetric cryptography, as it is slower and requires more bits in the key to achieve the same level of security. It encrypts a key and then uses the comparatively lightweight symmetric cipher to do the "heavy lifting" with the message. - -## Digital Signatures - -Digital signatures are a way of verifying the authenticity of a document or message using asymmetric keypairs. They are used to ensure that a sender or signer's document or message hasn't been tampered with in transit, and for recipients to verify that the data is accurate and from the expected sender. - -Signing digital signatures only requires a low-level understanding of mathematics and cryptography. For a conceptual example -- when signing a check, it is expected that it cannot be cashed multiple times. This isn't a feature of the signature system but rather the check serialization system. The bank will check that the serial number on the check hasn't already been used. Digital signatures essentially combine these two concepts, allowing the signature to provide the serialization via a unique cryptographic fingerprint that cannot be reproduced. - -Unlike pen-and-paper signatures, knowledge of a digital signature cannot be used to create other signatures. Digital signatures are often used in bureaucratic processes, as they are more secure than simply scanning in a signature and pasting it onto a document. - -Polkadot SDK provides multiple different cryptographic schemes and is generic so that it can support anything that implements the [`Pair` trait](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Pair.html){target=\_blank}. - -### Example of Creating a Digital Signature - -The process of creating and verifying a digital signature involves several steps: - -1. The sender creates a hash of the message. -2. The hash is encrypted using the sender's private key, creating the signature. -3. The message and signature are sent to the recipient. -4. The recipient decrypts the signature using the sender's public key. -5. The recipient hashes the received message and compares it to the decrypted hash. - -If the hashes match, the signature is valid, confirming the message's integrity and the sender's identity. - -## Elliptic Curve - -Blockchain technology requires the ability to have multiple keys creating a signature for block proposal and validation. To this end, Elliptic Curve Digital Signature Algorithm (ECDSA) and Schnorr signatures are two of the most commonly used methods. While ECDSA is a far simpler implementation, Schnorr signatures are more efficient when it comes to multi-signatures. - -Schnorr signatures bring some noticeable features over the ECDSA/EdDSA schemes: - -- It is better for hierarchical deterministic key derivations. -- It allows for native multi-signature through [signature aggregation](https://bitcoincore.org/en/2017/03/23/schnorr-signature-aggregation/){target=\_blank}. -- It is generally more resistant to misuse. - -One sacrifice that is made when using Schnorr signatures over ECDSA is that both require 64 bytes, but only ECDSA signatures communicate their public key. - -### Various Implementations - -- **[ECDSA](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm){target=\_blank}**: Polkadot SDK provides an ECDSA signature scheme using the [secp256k1](https://en.bitcoin.it/wiki/Secp256k1){target=\_blank} curve. This is the same cryptographic algorithm used to secure [Bitcoin](https://en.wikipedia.org/wiki/Bitcoin){target=\_blank} and [Ethereum](https://en.wikipedia.org/wiki/Ethereum){target=\_blank}. - -- **[Ed25519](https://en.wikipedia.org/wiki/EdDSA#Ed25519){target=\_blank}**: An EdDSA signature scheme using [Curve25519](https://en.wikipedia.org/wiki/Curve25519){target=\_blank}. It is carefully engineered at several levels of design and implementation to achieve very high speeds without compromising security. - -- **[SR25519](https://research.web3.foundation/Polkadot/security/keys/accounts-more){target=\_blank}**: Based on the same underlying curve as Ed25519. However, it uses Schnorr signatures instead of the EdDSA scheme. diff --git a/.ai/pages/reference-parachains-data-encoding.md b/.ai/pages/reference-parachains-data-encoding.md deleted file mode 100644 index 4e8a72194..000000000 --- a/.ai/pages/reference-parachains-data-encoding.md +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: Data Encoding -description: SCALE codec enables fast, efficient data encoding, ideal for resource-constrained environments like Wasm, supporting custom types and compact encoding. -categories: Basics, Polkadot Protocol -url: https://docs.polkadot.com/reference/parachains/data-encoding/ ---- - -# Data Encoding - -## Introduction - -The Polkadot SDK uses a lightweight and efficient encoding/decoding mechanism to optimize data transmission across the network. This mechanism, known as the _SCALE_ codec, is used for serializing and deserializing data. - -The SCALE codec enables communication between the runtime and the outer node. This mechanism is designed for high-performance, copy-free data encoding and decoding in resource-constrained environments like the Polkadot SDK [Wasm runtime](/develop/parachains/deployment/build-deterministic-runtime/#introduction){target=\_blank}. - -It is not self-describing, meaning the decoding context must fully know the encoded data types. - -Parity's libraries utilize the [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\_blank} crate (a Rust implementation of the SCALE codec) to handle encoding and decoding for interactions between RPCs and the runtime. - -The `codec` mechanism is ideal for Polkadot SDK-based chains because: - -- It is lightweight compared to generic serialization frameworks like [`serde`](https://serde.rs/){target=\_blank}, which add unnecessary bulk to binaries. -- It doesn’t rely on Rust’s `libstd`, making it compatible with `no_std` environments like Wasm runtime. -- It integrates seamlessly with Rust, allowing easy derivation of encoding and decoding logic for new types using `#[derive(Encode, Decode)]`. - -Defining a custom encoding scheme in the Polkadot SDK-based chains, rather than using an existing Rust codec library, is crucial for enabling cross-platform and multi-language support. - -## SCALE Codec - -The codec is implemented using the following traits: - -- [`Encode`](#encode) -- [`Decode`](#decode) -- [`CompactAs`](#compactas) -- [`HasCompact`](#hascompact) -- [`EncodeLike`](#encodelike) - -### Encode - -The [`Encode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Encode.html){target=\_blank} trait handles data encoding into SCALE format and includes the following key functions: - -- **`size_hint(&self) -> usize`**: Estimates the number of bytes required for encoding to prevent multiple memory allocations. This should be inexpensive and avoid complex operations. Optional if the size isn’t known. -- **`encode_to(&self, dest: &mut T)`**: Encodes the data, appending it to a destination buffer. -- **`encode(&self) -> Vec`**: Encodes the data and returns it as a byte vector. -- **`using_encoded R>(&self, f: F) -> R`**: Encodes the data and passes it to a closure, returning the result. -- **`encoded_size(&self) -> usize`**: Calculates the encoded size. Should be used when the encoded data isn’t required. - -!!!tip - For best performance, value types should override `using_encoded`, and allocating types should override `encode_to`. It's recommended to implement `size_hint` for all types where possible. - -### Decode - -The [`Decode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Decode.html){target=\_blank} trait handles decoding SCALE-encoded data back into the appropriate types: - -- **`fn decode(value: &mut I) -> Result`**: Decodes data from the SCALE format, returning an error if decoding fails. - -### CompactAs - -The [`CompactAs`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.CompactAs.html){target=\_blank} trait wraps custom types for compact encoding: - -- **`encode_as(&self) -> &Self::As`**: Encodes the type as a compact type. -- **`decode_from(_: Self::As) -> Result`**: decodes from a compact encoded type. - -### HasCompact - -The [`HasCompact`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.HasCompact.html){target=\_blank} trait indicates a type supports compact encoding. - -### EncodeLike - -The [`EncodeLike`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.EncodeLike.html){target=\_blank} trait is used to ensure multiple types that encode similarly are accepted by the same function. When using `derive`, it is automatically implemented. - -### Data Types - -The table below outlines how the Rust implementation of the Parity SCALE codec encodes different data types. - -| Type | Description | Example SCALE Decoded Value | SCALE Encoded Value | -|-------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------| -| Boolean | Boolean values are encoded using the least significant bit of a single byte. | `false` / `true` | `0x00` / `0x01` | -| Compact/general integers | A "compact" or general integer encoding is sufficient for encoding large integers (up to 2^536) and is more efficient at encoding most values than the fixed-width version. | `unsigned integer 0` / `unsigned integer 1` / `unsigned integer 42` / `unsigned integer 69` / `unsigned integer 65535` / `BigInt(100000000000000)` | `0x00` / `0x04` / `0xa8` / `0x1501` / `0xfeff0300` / `0x0b00407a10f35a` | -| Enumerations (tagged-unions) | A fixed number of variants, each mutually exclusive and potentially implying a further value or series of values. Encoded as the first byte identifying the index of the variant that the value is. Any further bytes are used to encode any data that the variant implies. Thus, no more than 256 variants are supported. | `Int(42)` and `Bool(true)` where `enum IntOrBool { Int(u8), Bool(bool) }` | `0x002a` and `0x0101` | -| Fixed-width integers | Basic integers are encoded using a fixed-width little-endian (LE) format. | `signed 8-bit integer 69` / `unsigned 16-bit integer 42` / `unsigned 32-bit integer 16777215` | `0x45` / `0x2a00` / `0xffffff00` | -| Options | One or zero values of a particular type. | `Some` / `None` | `0x01` followed by the encoded value / `0x00` | -| Results | Results are commonly used enumerations which indicate whether certain operations were successful or unsuccessful. | `Ok(42)` / `Err(false)` | `0x002a` / `0x0100` | -| Strings | Strings are Vectors of bytes (Vec) containing a valid UTF8 sequence. | | | -| Structs | For structures, the values are named, but that is irrelevant for the encoding (names are ignored - only order matters). | `SortedVecAsc::from([3, 5, 2, 8])` | `[3, 2, 5, 8] ` | -| Tuples | A fixed-size series of values, each with a possibly different but predetermined and fixed type. This is simply the concatenation of each encoded value. | Tuple of compact unsigned integer and boolean: `(3, false)` | `0x0c00` | -| Vectors (lists, series, sets) | A collection of same-typed values is encoded, prefixed with a compact encoding of the number of items, followed by each item's encoding concatenated in turn. | Vector of unsigned `16`-bit integers: `[4, 8, 15, 16, 23, 42]` | `0x18040008000f00100017002a00` | - -## Encode and Decode Rust Trait Implementations - -Here's how the `Encode` and `Decode` traits are implemented: - - -```rust -use parity_scale_codec::{Encode, Decode}; - -[derive(Debug, PartialEq, Encode, Decode)] -enum EnumType { - #[codec(index = 15)] - A, - B(u32, u64), - C { - a: u32, - b: u64, - }, -} - -let a = EnumType::A; -let b = EnumType::B(1, 2); -let c = EnumType::C { a: 1, b: 2 }; - -a.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x0f"); -}); - -b.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); - -c.using_encoded(|ref slice| { - assert_eq!(slice, &b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"); -}); - -let mut da: &[u8] = b"\x0f"; -assert_eq!(EnumType::decode(&mut da).ok(), Some(a)); - -let mut db: &[u8] = b"\x01\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut db).ok(), Some(b)); - -let mut dc: &[u8] = b"\x02\x01\0\0\0\x02\0\0\0\0\0\0\0"; -assert_eq!(EnumType::decode(&mut dc).ok(), Some(c)); - -let mut dz: &[u8] = &[0]; -assert_eq!(EnumType::decode(&mut dz).ok(), None); -``` - -## SCALE Codec Libraries - -Several SCALE codec implementations are available in various languages. Here's a list of them: - -- **AssemblyScript**: [`LimeChain/as-scale-codec`](https://github.com/LimeChain/as-scale-codec){target=\_blank} -- **C**: [`MatthewDarnell/cScale`](https://github.com/MatthewDarnell/cScale){target=\_blank} -- **C++**: [`qdrvm/scale-codec-cpp`](https://github.com/qdrvm/scale-codec-cpp){target=\_blank} -- **JavaScript**: [`polkadot-js/api`](https://github.com/polkadot-js/api){target=\_blank} -- **Dart**: [`leonardocustodio/polkadart`](https://github.com/leonardocustodio/polkadart){target=\_blank} -- **Haskell**: [`airalab/hs-web3`](https://github.com/airalab/hs-web3/tree/master/packages/scale){target=\_blank} -- **Golang**: [`itering/scale.go`](https://github.com/itering/scale.go){target=\_blank} -- **Java**: [`splix/polkaj`](https://github.com/splix/polkaj){target=\_blank} -- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\_blank} -- **Ruby**: [` wuminzhe/scale_rb`](https://github.com/wuminzhe/scale_rb){target=\_blank} -- **TypeScript**: [`parity-scale-codec-ts`](https://github.com/tjjfvi/subshape){target=\_blank}, [`scale-ts`](https://github.com/unstoppablejs/unstoppablejs/tree/main/packages/scale-ts#scale-ts){target=\_blank}, [`soramitsu/scale-codec-js-library`](https://github.com/soramitsu/scale-codec-js-library){target=\_blank}, [`subsquid/scale-codec`](https://github.com/subsquid/squid-sdk/tree/master/substrate/scale-codec){target=\_blank} diff --git a/.ai/pages/reference-parachains-interoperability.md b/.ai/pages/reference-parachains-interoperability.md deleted file mode 100644 index 8427e3355..000000000 --- a/.ai/pages/reference-parachains-interoperability.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Interoperability -description: Explore the importance of interoperability in the Polkadot ecosystem, covering XCM, bridges, and cross-chain communication. -categories: Basics, Polkadot Protocol -url: https://docs.polkadot.com/reference/parachains/interoperability/ ---- - -# Interoperability - -## Introduction - -Interoperability lies at the heart of the Polkadot ecosystem, enabling communication and collaboration across a diverse range of blockchains. By bridging the gaps between parachains, relay chains, and even external networks, Polkadot unlocks the potential for truly decentralized applications, efficient resource sharing, and scalable solutions. - -Polkadot’s design ensures that blockchains can transcend their individual limitations by working together as part of a unified system. This cooperative architecture is what sets Polkadot apart in the blockchain landscape. - -## Why Interoperability Matters - -The blockchain ecosystem is inherently fragmented. Different blockchains excel in specialized domains such as finance, gaming, or supply chain management, but these chains function in isolation without interoperability. This lack of connectivity stifles the broader utility of blockchain technology. - -Interoperability solves this problem by enabling blockchains to: - -- **Collaborate across networks**: Chains can interact to share assets, functionality, and data, creating synergies that amplify their individual strengths. -- **Achieve greater scalability**: Specialized chains can offload tasks to others, optimizing performance and resource utilization. -- **Expand use-case potential**: Cross-chain applications can leverage features from multiple blockchains, unlocking novel user experiences and solutions. - -In the Polkadot ecosystem, interoperability transforms a collection of isolated chains into a cohesive, efficient network, pushing the boundaries of what blockchains can achieve together. - -## Key Mechanisms for Interoperability - -At the core of Polkadot's cross-chain collaboration are foundational technologies designed to break down barriers between networks. These mechanisms empower blockchains to communicate, share resources, and operate as a cohesive ecosystem. - -### Cross-Consensus Messaging (XCM): The Backbone of Communication - -Polkadot's Cross-Consensus Messaging (XCM) is the standard framework for interaction between parachains, relay chains, and, eventually, external blockchains. XCM provides a trustless, secure messaging format for exchanging assets, sharing data, and executing cross-chain operations. - -Through XCM, decentralized applications can: - -- Transfer tokens and other assets across chains. -- Coordinate complex workflows that span multiple blockchains. -- Enable seamless user experiences where underlying blockchain differences are invisible. -- XCM exemplifies Polkadot’s commitment to creating a robust and interoperable ecosystem. - -For further information about XCM, check the [Introduction to XCM](/parachains/interoperability/get-started/){target=\_blank} article. - -### Bridges: Connecting External Networks - -While XCM enables interoperability within the Polkadot ecosystem, bridges extend this functionality to external blockchains such as Ethereum and Bitcoin. By connecting these networks, bridges allow Polkadot-based chains to access external liquidity, additional functionalities, and broader user bases. - -With bridges, developers and users gain the ability to: - -- Integrate external assets into Polkadot-based applications. -- Combine the strengths of Polkadot’s scalability with the liquidity of other networks. -- Facilitate accurate multi-chain applications that transcend ecosystem boundaries. - -For more information about bridges in the Polkadot ecosystem, see the [Bridge Hub](/reference/polkadot-hub/bridging/){target=\_blank} guide. - -## The Polkadot Advantage - -Polkadot was purpose-built for interoperability. Unlike networks that add interoperability as an afterthought, Polkadot integrates it as a fundamental design principle. This approach offers several distinct advantages: - -- **Developer empowerment**: Polkadot’s interoperability tools allow developers to build applications that leverage multiple chains’ capabilities without added complexity. -- **Enhanced ecosystem collaboration**: Chains in Polkadot can focus on their unique strengths while contributing to the ecosystem’s overall growth. -- **Future-proofing blockchain**: By enabling seamless communication, Polkadot ensures its ecosystem can adapt to evolving demands and technologies. - -## Looking Ahead - -Polkadot’s vision of interoperability extends beyond technical functionality, representing a shift towards a more collaborative blockchain landscape. By enabling chains to work together, Polkadot fosters innovation, efficiency, and accessibility, paving the way for a decentralized future where blockchains are not isolated competitors but interconnected collaborators. diff --git a/.ai/pages/reference-parachains-networks.md b/.ai/pages/reference-parachains-networks.md deleted file mode 100644 index 118cfbffe..000000000 --- a/.ai/pages/reference-parachains-networks.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Networks -description: Explore Polkadot's testing and production networks, including Westend, Kusama, and Paseo, for efficient development, deployment, and testing. -categories: Basics, Polkadot Protocol, Networks -url: https://docs.polkadot.com/reference/parachains/networks/ ---- - -# Networks - -## Introduction - -The Polkadot ecosystem is built on a robust set of networks designed to enable secure and scalable development. Whether you are testing new features or deploying to live production, Polkadot offers several layers of networks tailored for each stage of the development process. From local environments to experimental networks like Kusama and community-run TestNets such as Paseo, developers can thoroughly test, iterate, and validate their applications. This guide will introduce you to Polkadot's various networks and explain how they fit into the development workflow. - -## Network Overview - -Polkadot's development process is structured to ensure new features and upgrades are rigorously tested before being deployed on live production networks. The progression follows a well-defined path, starting from local environments and advancing through TestNets, ultimately reaching the Polkadot MainNet. The diagram below outlines the typical progression of the Polkadot development cycle: - -``` mermaid -flowchart LR - id1[Local] --> id2[Westend] --> id4[Kusama] --> id5[Polkadot] - id1[Local] --> id3[Paseo] --> id5[Polkadot] -``` - -This flow ensures developers can thoroughly test and iterate without risking real tokens or affecting production networks. Testing tools like [Chopsticks](#chopsticks) and various TestNets make it easier to experiment safely before releasing to production. - -A typical journey through the Polkadot core protocol development process might look like this: - -1. **Local development node**: Development starts in a local environment, where developers can create, test, and iterate on upgrades or new features using a local development node. This stage allows rapid experimentation in an isolated setup without any external dependencies. - -2. **Westend**: After testing locally, upgrades are deployed to [Westend](#westend), Polkadot's primary TestNet. Westend simulates real-world conditions without using real tokens, making it the ideal place for rigorous feature testing before moving on to production networks. - -3. **Kusama**: Once features have passed extensive testing on Westend, they move to Kusama, Polkadot's experimental and fast-moving "canary" network. Kusama operates as a high-fidelity testing ground with actual economic incentives, giving developers insights into how their features will perform in a real-world environment. - -4. **Polkadot**: After passing tests on Westend and Kusama, features are considered ready for deployment to Polkadot, the live production network. - - In addition, parachain developers can leverage local TestNets like [Zombienet](#zombienet) and deploy upgrades on parachain TestNets. - -5. **Paseo**: For parachain and dApp developers, Paseo serves as a community-run TestNet that mirrors Polkadot's runtime. Like Westend for core protocol development, Paseo provides a testing ground for parachain development without affecting live networks. - -!!!note - The Rococo TestNet deprecation date was October 14, 2024. Teams should use Westend for Polkadot protocol and feature testing and Paseo for chain development-related testing. - -## Polkadot Development Networks - -Development and testing are crucial to building robust dApps and parachains and performing network upgrades within the Polkadot ecosystem. To achieve this, developers can leverage various networks and tools that provide a risk-free environment for experimentation and validation before deploying features to live networks. These networks help avoid the costs and risks associated with real tokens, enabling testing for functionalities like governance, cross-chain messaging, and runtime upgrades. - -## Kusama Network - -Kusama is the experimental version of Polkadot, designed for developers who want to move quickly and test their applications in a real-world environment with economic incentives. Kusama serves as a production-grade testing ground where developers can deploy features and upgrades with the pressure of game theory and economics in mind. It mirrors Polkadot but operates as a more flexible space for innovation. - -The native token for Kusama is KSM. For more information about KSM, visit the [Native Assets](https://wiki.polkadot.com/kusama/kusama-getting-started/){target=\_blank} page. - -## Test Networks - -The following test networks provide controlled environments for testing upgrades and new features. TestNet tokens are available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\_blank}. - -### Westend - -Westend is Polkadot's primary permanent TestNet. Unlike temporary test networks, Westend is not reset to the genesis block, making it an ongoing environment for testing Polkadot core features. Managed by Parity Technologies, Westend ensures that developers can test features in a real-world simulation without using actual tokens. - -The native token for Westend is WND. More details about WND can be found on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_2){target=\_blank} page. - -### Paseo - -[Paseo](https://github.com/paseo-network){target=\_blank} is a community-managed TestNet designed for parachain and dApp developers. It mirrors Polkadot's runtime and is maintained by Polkadot community members. Paseo provides a dedicated space for parachain developers to test their applications in a Polkadot-like environment without the risks associated with live networks. - -The native token for Paseo is PAS. Additional information on PAS is available on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_1){target=\_blank} page. - -## Local Test Networks - -Local test networks are an essential part of the development cycle for blockchain developers using the Polkadot SDK. They allow for fast, iterative testing in controlled, private environments without connecting to public TestNets. Developers can quickly spin up local instances to experiment, debug, and validate their code before deploying to larger TestNets like Westend or Paseo. Two key tools for local network testing are Zombienet and Chopsticks. - -### Zombienet - -[Zombienet](https://github.com/paritytech/zombienet){target=\_blank} is a flexible testing framework for Polkadot SDK-based blockchains. It enables developers to create and manage ephemeral, short-lived networks. This feature makes Zombienet particularly useful for quick iterations, as it allows you to run multiple local networks concurrently, mimicking different runtime conditions. Whether you're developing a parachain or testing your custom blockchain logic, Zombienet gives you the tools to automate local testing. - -Key features of Zombienet include: - -- Creating dynamic, local networks with different configurations. -- Running parachains and relay chains in a simulated environment. -- Efficient testing of network components like cross-chain messaging and governance. - -Zombienet is ideal for developers looking to test quickly and thoroughly before moving to more resource-intensive public TestNets. - -### Chopsticks - -[Chopsticks](https://github.com/AcalaNetwork/chopsticks){target=\_blank} is a tool designed to create forks of Polkadot SDK-based blockchains, allowing developers to interact with network forks as part of their testing process. This capability makes Chopsticks a powerful option for testing upgrades, runtime changes, or cross-chain applications in a forked network environment. - -Key features of Chopsticks include: - -- Forking live Polkadot SDK-based blockchains for isolated testing. -- Simulating cross-chain messages in a private, controlled setup. -- Debugging network behavior by interacting with the fork in real-time. - -Chopsticks provides a controlled environment for developers to safely explore the effects of runtime changes. It ensures that network behavior is tested and verified before upgrades are deployed to live networks. diff --git a/.ai/pages/reference-parachains-node-and-runtime.md b/.ai/pages/reference-parachains-node-and-runtime.md deleted file mode 100644 index 050ac6aab..000000000 --- a/.ai/pages/reference-parachains-node-and-runtime.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: Node and Runtime -description: Learn how Polkadot SDK-based nodes function, how the client and runtime are separated, and how they communicate using SCALE-encoded data. -categories: Basics, Polkadot Protocol -url: https://docs.polkadot.com/reference/parachains/node-and-runtime/ ---- - -# Node and Runtime - -## Introduction - -Every blockchain platform relies on a decentralized network of computers, called nodes, that communicate with each other about transactions and blocks. In this context, a node refers to the software running on the connected devices rather than the physical or virtual machines in the network. - -Polkadot SDK-based nodes consist of two main components, each with distinct responsibilities: the client (also called node) and the runtime. - -If the system were a monolithic protocol, any modification would require updating the entire system. Instead, Polkadot achieves true upgradeability by defining an immutable meta-protocol (the client) and a protocol (the runtime) that can be upgraded independently. - -This separation gives the [Polkadot Relay Chain](/polkadot-protocol/architecture/polkadot-chain){target=\_blank} and all connected [parachains](/polkadot-protocol/architecture/parachains){target=\_blank} an evolutionary advantage over other blockchain platforms. - -## Architectural Principles - -The Polkadot SDK-based blockchain architecture is fundamentally built on two distinct yet interconnected components: - -- Client (Meta-protocol): - - Handles the foundational infrastructure of the blockchain. - - Manages runtime execution, networking, consensus, and other off-chain components. - - Provides an immutable base layer that ensures network stability. - - Upgradable only through hard forks. - -- Runtime (Protocol): - - Defines the blockchain's state transition logic. - - Determines the specific rules and behaviors of the blockchain. - - Compiled to WebAssembly (Wasm) for platform-independent execution. - - Capable of being upgraded without network-wide forking. - -### Advantages of this Architecture - -- **Forkless upgrades**: Runtime can be updated without disrupting the entire network. -- **Modularity**: Clear separation allows independent development of client and runtime. -- **Flexibility**: Enables rapid iteration and evolution of blockchain logic. -- **Performance**: WebAssembly compilation provides efficient, cross-platform execution. - -## Node (Client) - -The node, also known as the client, is the core component responsible for executing the Wasm runtime and orchestrating various essential blockchain components. It ensures the correct execution of the state transition function and manages multiple critical subsystems, including: - -- **Wasm execution**: Runs the blockchain runtime, which defines the state transition rules. -- **Database management**: Stores blockchain data. -- **Networking**: Facilitates peer-to-peer communication, block propagation, and transaction gossiping. -- **Transaction pool (Mempool)**: Manages pending transactions before they are included in a block. -- **Consensus mechanism**: Ensures agreement on the blockchain state across nodes. -- **RPC services**: Provides external interfaces for applications and users to interact with the node. - -## Runtime - -The runtime is more than just a set of rules. It's the fundamental logic engine that defines a blockchain's entire behavior. In Polkadot SDK-based blockchains, the runtime represents a complete, self-contained description of the blockchain's state transition function. - -### Characteristics - -The runtime is distinguished by three key characteristics: - -- **Business logic**: Defines the complete application-specific blockchain behavior. -- **WebAssembly compilation**: Ensures platform-independent, secure execution. -- **On-chain storage**: Stored within the blockchain's state, allowing dynamic updates. - -### Key Functions - -The runtime performs several critical functions, such as: - -- Define state transition rules. -- Implement blockchain-specific logic. -- Manage account interactions. -- Control transaction processing. -- Define governance mechanisms. -- Handle custom pallets and modules. - -## Communication Between Node and Runtime - -The client and runtime communicate exclusively using [SCALE-encoded](/polkadot-protocol/parachain-basics/data-encoding){target=\_blank} communication. This ensures efficient and compact data exchange between the two components. - -### Runtime APIs - -The Runtime API consists of well-defined functions and constants a client assumes are implemented in the Runtime Wasm blob. These APIs enable the client to interact with the runtime to execute blockchain operations and retrieve information. The client invokes these APIs to: - -- Build, execute, and finalize blocks. -- Access metadata. -- Access consensus related information. -- Handle transaction execution. - -### Host Functions - -During execution, the runtime can access certain external client functionalities via host functions. The specific functions the client exposes allow the runtime to perform operations outside the WebAssembly domain. Host functions enable the runtime to: - -- Perform cryptographic operations. -- Access the current blockchain state. -- Handle storage modifications. -- Allocate memory. diff --git a/.ai/pages/reference-parachains-randomness.md b/.ai/pages/reference-parachains-randomness.md deleted file mode 100644 index 26b96542b..000000000 --- a/.ai/pages/reference-parachains-randomness.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: Randomness -description: Explore the importance of randomness in PoS blockchains, focusing on Polkadot’s VRF-based approach to ensure fairness and security in validator selection. -categories: Basics, Polkadot Protocol -url: https://docs.polkadot.com/reference/parachains/randomness/ ---- - -# Randomness - -## Introduction - -Randomness is crucial in Proof of Stake (PoS) blockchains to ensure a fair and unpredictable distribution of validator duties. However, computers are inherently deterministic, meaning the same input always produces the same output. What we typically refer to as "random" numbers on a computer are actually pseudo-random. These numbers rely on an initial "seed," which can come from external sources like [atmospheric noise](https://www.random.org/randomness/){target=\_blank}, [heart rates](https://mdpi.altmetric.com/details/47574324){target=\_blank}, or even [lava lamps](https://en.wikipedia.org/wiki/Lavarand){target=\_blank}. While this may seem random, given the same "seed," the same sequence of numbers will always be generated. - -In a global blockchain network, relying on real-world entropy for randomness isn’t feasible because these inputs vary by time and location. If nodes use different inputs, blockchains can fork. Hence, real-world randomness isn't suitable for use as a seed in blockchain systems. - -Currently, two primary methods for generating randomness in blockchains are used: [`RANDAO`](#randao) and [`VRF`](#vrf) (Verifiable Random Function). Polkadot adopts the `VRF` approach for its randomness. - -## VRF - -A Verifiable Random Function (VRF) is a cryptographic function that generates a random number and proof that ensures the submitter produced the number. This proof allows anyone to verify the validity of the random number. - -Polkadot's VRF is similar to the one used in [**Ouroboros Praos**](https://eprint.iacr.org/2017/573.pdf){target=\_blank}, which secures randomness for block production in systems like [BABE](/reference/polkadot-hub/consensus-and-security/pos-consensus/#block-production-babe){target=\_blank} (Polkadot’s block production mechanism). - -The key difference is that Polkadot's VRF doesn’t rely on a central clock—avoiding the issue of whose clock to trust. Instead, it uses its own past results and slot numbers to simulate time and determine future outcomes. - -### How VRF Works - -Slots on Polkadot are discrete units of time, each lasting six seconds, and can potentially hold a block. Multiple slots form an epoch, with 2400 slots making up one four-hour epoch. - -In each slot, validators execute a "die roll" using a VRF. The VRF uses three inputs: - -1. A "secret key," unique to each validator, is used for the die roll. -2. An epoch randomness value, derived from the hash of VRF outputs from blocks two epochs ago (N-2), so past randomness influences the current epoch (N). -3. The current slot number. - -This process helps maintain fair randomness across the network. - -Here is a graphical representation: - -![](/images/reference/parachains/randomness/randomness-01.webp) - -The VRF produces two outputs: a result (the random number) and a proof (verifying that the number was generated correctly). - -The result is checked by the validator against a protocol threshold. If it's below the threshold, the validator becomes a candidate for block production in that slot. - -The validator then attempts to create a block, submitting it along with the `PROOF` and `RESULT`. - -So, VRF can be expressed like: - -`(RESULT, PROOF) = VRF(SECRET, EPOCH_RANDOMNESS_VALUE, CURRENT_SLOT_NUMBER)` - -Put simply, performing a "VRF roll" generates a random number along with proof that the number was genuinely produced and not arbitrarily chosen. - -After executing the VRF, the `RESULT` is compared to a protocol-defined `THRESHOLD`. If the `RESULT` is below the `THRESHOLD`, the validator becomes a valid candidate to propose a block for that slot. Otherwise, the validator skips the slot. - -As a result, there may be multiple validators eligible to propose a block for a slot. In this case, the block accepted by other nodes will prevail, provided it is on the chain with the latest finalized block as determined by the GRANDPA finality gadget. It's also possible for no block producers to be available for a slot, in which case the AURA consensus takes over. AURA is a fallback mechanism that randomly selects a validator to produce a block, running in parallel with BABE and only stepping in when no block producers exist for a slot. Otherwise, it remains inactive. - -Because validators roll independently, no block candidates may appear in some slots if all roll numbers are above the threshold. - -To verify resolution of this issue and that Polkadot block times remain near constant-time, see the [PoS Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\_blank} page of this documentation. - -## RANDAO - -An alternative on-chain randomness method is Ethereum's RANDAO, where validators perform thousands of hashes on a seed and publish the final hash during a round. The collective input from all validators forms the random number, and as long as one honest validator participates, the randomness is secure. - -To enhance security, RANDAO can optionally be combined with a Verifiable Delay Function (VDF), ensuring that randomness can't be predicted or manipulated during computation. - -For more information about RANDAO, see the [Randomness - RANDAO](https://eth2book.info/capella/part2/building_blocks/randomness/){target=\_blank} section of the Upgrading Ethereum documentation. - -## VDFs - -Verifiable Delay Functions (VDFs) are time-bound computations that, even on parallel computers, take a set amount of time to complete. - -They produce a unique result that can be quickly verified publicly. When combined with RANDAO, feeding RANDAO's output into a VDF introduces a delay that nullifies an attacker's chance to influence the randomness. - -However, VDF likely requires specialized ASIC devices to run separately from standard nodes. - -!!!warning - While only one is needed to secure the system, and they will be open-source and inexpensive, running VDF devices involves significant costs without direct incentives, adding friction for blockchain users. - -## Additional Resources - -For more information about the reasoning for choices made along with proofs, see Polkadot's research on blockchain randomness and sortition in the [Block production](https://research.web3.foundation/Polkadot/protocols/block-production){target=\_blank} entry of the Polkadot Wiki. - -For a discussion with Web3 Foundation researchers about when and under what conditions Polkadot's randomness can be utilized, see the [Discussion on Randomness used in Polkadot](https://github.com/use-ink/ink/issues/57){target=\_blank} issue on GitHub. diff --git a/.ai/pages/reference-parachains.md b/.ai/pages/reference-parachains.md deleted file mode 100644 index 8f1c746c5..000000000 --- a/.ai/pages/reference-parachains.md +++ /dev/null @@ -1,187 +0,0 @@ ---- -title: Parachains Overview -description: Learn about parachains, specialized blockchains on Polkadot that gain shared security and interoperability. Discover how they work and the tools to build them. -categories: Basics, Parachains -url: https://docs.polkadot.com/reference/parachains/ ---- - -# Parachains Overview - -## Introduction - -A parachain is a specialized blockchain that connects to the Polkadot relay chain, benefiting from shared security, interoperability, and scalability. Parachains are built using the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}, a powerful toolkit written in Rust that provides everything needed to create custom blockchain logic while integrating seamlessly with the Polkadot network. - -Unlike standalone blockchains that must bootstrap their own validator sets and security, parachains leverage Polkadot's pooled security model. This allows parachain developers to focus on their application-specific functionality rather than consensus and security infrastructure. Parachains can communicate with each other through Cross-Consensus Messaging (XCM), enabling seamless interoperability across the Polkadot ecosystem. - -Key capabilities that parachains provide include: - -- **Shared security**: Inherit security from Polkadot's validator set without maintaining your own. -- **Interoperability**: Communicate trustlessly with other parachains via XCM. -- **Scalability**: Process transactions in parallel with other parachains. -- **Customization**: Build application-specific logic tailored to your use case. -- **Upgradeability**: Upgrade runtime logic without hard forks. - -## Polkadot SDK: Parachain Architecture - -Building a parachain involves understanding and utilizing several key components of the Polkadot SDK: - -![](/images/reference/parachains/index/overview-01.webp) - -- **[Substrate](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/substrate/index.html){target=\_blank}**: The foundation providing core blockchain primitives and libraries. -- **[FRAME](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\_blank}**: A modular framework for building your parachain's runtime logic. -- **[Cumulus](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/cumulus/index.html){target=\_blank}**: Essential libraries and pallets that enable parachain functionality. -- **[XCM (Cross Consensus Messaging)](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/xcm/index.html){target=\_blank}**: The messaging format for communicating with other parachains and the relay chain. -- **[Polkadot](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/polkadot/index.html){target=\_blank}**: The relay chain that provides security and coordination. - -### Substrate: The Foundation - -Substrate provides the core infrastructure that every parachain is built upon. It handles the low-level blockchain functionality, allowing you to focus on your application's unique features. Substrate includes implementations for networking, database management, consensus participation, and the execution environment for your runtime. - -Every Polkadot SDK node consists of two main components: - -- **Client (Host)**: Handles infrastructure services. - - - Native binary that runs on validator and collator nodes. - - Executes the Wasm-compiled runtime. - - Manages networking, database, mempool, and block production. - - Interfaces with the relay chain for validation. - -- **Runtime (State Transition Function)**: Contains your business logic. - - - Defines how your Polkadot SDK node processes transactions. - - Compiled to [Wasm](https://webassembly.org/){target=\_blank} for deterministic execution. - - Stored on-chain and upgradeable via governance. - -```mermaid -%%{init: {'flowchart': {'padding': 5, 'nodeSpacing': 50, 'rankSpacing': 10}}}%% -graph TB - classDef title font-size:20px,font-weight:bold,stroke-width:0px - classDef clientStyle font-size:16px,font-weight:bold - classDef clientSubNodeStyle margin-top:10px - classDef runtimeCallExecutorStyle padding-top:10px - - subgraph sg1[Parachain
Node] - direction TB - - I[RuntimeCall Executor] - B[Wasm Runtime - STF] - - subgraph sg2[Client] - direction TB - C[Network and Blockchain
Infrastructure Services
+ Relay Chain Interface] - end - - I --> B - end - - class sg1 title - class sg2 clientStyle - class C clientSubNodeStyle - class I runtimeCallExecutorStyle - -``` - -### FRAME: Building Blocks for Your Runtime - -FRAME provides modular components called [pallets](/reference/glossary#pallet){target=\_blank} that you can compose to build your parachain's runtime. Each pallet provides specific functionality that you can customize and configure for your needs. This modular approach allows you to quickly assemble complex functionality without writing everything from scratch. - -```mermaid -graph LR - subgraph SP["Parachain Runtime"] - direction LR - Timestamp ~~~ Aura ~~~ ParachainSystem - Balances ~~~ TransactionPayment ~~~ Sudo - subgraph Timestamp["Timestamp"] - SS1[Custom Config] - end - subgraph Aura["Aura"] - SS2[Custom Config] - end - subgraph ParachainSystem["Parachain System"] - SS3[Custom Config] - end - subgraph Balances["Balances"] - SS4[Custom Config] - end - subgraph TransactionPayment["Transaction Payment"] - SS5[Custom Config] - end - subgraph Sudo["Sudo"] - SS6[Custom Config] - end - style Timestamp stroke:#FF69B4 - style Aura stroke:#FF69B4 - style ParachainSystem stroke:#FF69B4 - style Balances stroke:#FF69B4 - style TransactionPayment stroke:#FF69B4 - style Sudo stroke:#FF69B4 - style SS1 stroke-dasharray: 5 - style SS2 stroke-dasharray: 5 - style SS3 stroke-dasharray: 5 - style SS4 stroke-dasharray: 5 - style SS5 stroke-dasharray: 5 - style SS6 stroke-dasharray: 5 - - end - subgraph AP["Available FRAME Pallets"] - direction LR - A1[Aura]~~~A2[Parachain
System]~~~A3[Transaction
Payment]~~~A4[Sudo] - B1[Identity]~~~B2[Balances]~~~B3[Assets]~~~B4[EVM] - C1[Timestamp]~~~C2[Staking]~~~C3[Contracts]~~~C4[and more...] - end - AP --> SP -``` - -### Cumulus: Parachain-Specific Functionality - -Cumulus is what transforms a Polkadot SDK-based runtime into a parachain-capable runtime. It provides the essential components for communicating with the relay chain, participating in Polkadot's consensus, and handling parachain-specific operations like block validation and collation. - -Key Cumulus components include: - -- **Parachain system pallet**: Core parachain functionality and relay chain communication. -- **Collator consensus**: Block production logic for parachain collators. -- **Relay chain interface**: APIs for interacting with the Polkadot relay chain. -- **Validation data**: Handling proof-of-validity data required by relay chain validators. - -## Where to Go Next - -Building a parachain requires understanding the relationship between your chain and the Polkadot relay chain. The Polkadot SDK provides all the tools needed to design custom runtime logic, enable cross-chain communication, and deploy your parachain to production. - -The following sections provide detailed guidance on each aspect of parachain development, from initial design through deployment and ongoing maintenance. - -
- -- Guide __Launch a Simple Parachain__ - - --- - - Walk through the complete parachain launch flow: from setup and deployment to obtaining coretime. - - [:octicons-arrow-right-24: Deploy](/parachains/launch-a-parachain/set-up-the-parachain-template/) - - -- Guide __Customize Your Runtime__ - - --- - - Design your parachain's runtime logic and choose appropriate pallets for your use case. - - [:octicons-arrow-right-24: Get Started](/parachains/customize-runtime/) - -- Guide __Interoperability__ - - --- - - Implement XCM for trustless cross-chain communication with other parachains. - - [:octicons-arrow-right-24: Learn More](/parachains/interoperability/get-started/) - -- Guide __Runtime Upgrades__ - - --- - - Upgrade your parachain's runtime without hard forks using forkless upgrade mechanisms. - - [:octicons-arrow-right-24: Maintain](/parachains/runtime-maintenance/runtime-upgrades/) - -
diff --git a/.ai/pages/reference-polkadot-hub-assets-and-smart-contracts.md b/.ai/pages/reference-polkadot-hub-assets-and-smart-contracts.md deleted file mode 100644 index 4773cc0df..000000000 --- a/.ai/pages/reference-polkadot-hub-assets-and-smart-contracts.md +++ /dev/null @@ -1,225 +0,0 @@ ---- -title: Asset Hub -description: Learn about Asset Hub in Polkadot, managing on-chain assets, foreign asset integration, and using XCM for cross-chain asset transfers. -categories: Polkadot Protocol -url: https://docs.polkadot.com/reference/polkadot-hub/assets-and-smart-contracts/ ---- - -# Asset Hub - -## Introduction - -The Asset Hub is a critical component in the Polkadot ecosystem, enabling the management of fungible and non-fungible assets across the network. Since the relay chain focuses on maintaining security and consensus without direct asset management, Asset Hub provides a streamlined platform for creating, managing, and using on-chain assets in a fee-efficient manner. This guide outlines the core features of Asset Hub, including how it handles asset operations, cross-chain transfers, and asset integration using XCM, as well as essential tools like [API Sidecar](#api-sidecar) and [`TxWrapper`](#txwrapper) for developers working with on-chain assets. - -## Assets Basics - -In the Polkadot ecosystem, the relay chain does not natively support additional assets beyond its native token (DOT for Polkadot, KSM for Kusama). The Asset Hub parachain on Polkadot and Kusama provides a fungible and non-fungible assets framework. Asset Hub allows developers and users to create, manage, and use assets across the ecosystem. - -Asset creators can use Asset Hub to track their asset issuance across multiple parachains and manage assets through operations such as minting, burning, and transferring. Projects that need a standardized method of handling on-chain assets will find this particularly useful. The fungible asset interface provided by Asset Hub closely resembles Ethereum's ERC-20 standard but is directly integrated into Polkadot's runtime, making it more efficient in terms of speed and transaction fees. - -Integrating with Asset Hub offers several key benefits, particularly for infrastructure providers and users: - -- **Support for non-native on-chain assets**: Asset Hub enables seamless asset creation and management, allowing projects to develop tokens or assets that can interact with the broader ecosystem. -- **Lower transaction fees**: Asset Hub offers significantly lower transaction costs—approximately one-tenth of the fees on the relay chain, providing cost-efficiency for regular operations. -- **Reduced deposit requirements**: Depositing assets in Asset Hub is more accessible, with deposit requirements that are around one one-hundredth of those on the relay chain. -- **Payment of transaction fees with non-native assets**: Users can pay transaction fees in assets other than the native token (DOT or KSM), offering more flexibility for developers and users. - -Assets created on the Asset Hub are stored as part of a map, where each asset has a unique ID that links to information about the asset, including details like: - -- The management team. -- The total supply. -- The number of accounts holding the asset. -- **Sufficiency for account existence**: Whether the asset alone is enough to maintain an account without a native token balance. -- The metadata of the asset, including its name, symbol, and the number of decimals for representation. - -Some assets can be regarded as sufficient to maintain an account's existence, meaning that users can create accounts on the network without needing a native token balance (i.e., no existential deposit required). Developers can also set minimum balances for their assets. If an account's balance drops below the minimum, the balance is considered dust and may be cleared. - -## Assets Pallet - -The Polkadot SDK's Assets pallet is a powerful module designated for creating and managing fungible asset classes with a fixed supply. It offers a secure and flexible way to issue, transfer, freeze, and destroy assets. The pallet supports various operations and includes permissioned and non-permissioned functions to cater to simple and advanced use cases. - -Visit the [Assets Pallet Rust docs](https://paritytech.github.io/polkadot-sdk/master/pallet_assets/index.html){target=\_blank} for more in-depth information. - -### Key Features - -Key features of the Assets pallet include: - -- **Asset issuance**: Allows the creation of a new asset, where the total supply is assigned to the creator's account. -- **Asset transfer**: Enables transferring assets between accounts while maintaining a balance in both accounts. -- **Asset freezing**: Prevents transfers of a specific asset from one account, locking it from further transactions. -- **Asset destruction**: Allows accounts to burn or destroy their holdings, removing those assets from circulation. -- **Non-custodial transfers**: A non-custodial mechanism to enable one account to approve a transfer of assets on behalf of another. - -### Main Functions - -The Assets pallet provides a broad interface for managing fungible assets. Some of the main dispatchable functions include: - -- **`create()`**: Create a new asset class by placing a deposit, applicable when asset creation is permissionless. -- **`issue()`**: Mint a fixed supply of a new asset and assign it to the creator's account. -- **`transfer()`**: Transfer a specified amount of an asset between two accounts. -- **`approve_transfer()`**: Approve a non-custodial transfer, allowing a third party to move assets between accounts. -- **`destroy()`**: Destroy an entire asset class, removing it permanently from the chain. -- **`freeze()` and `thaw()`**: Administrators or privileged users can lock or unlock assets from being transferred. - -For a full list of dispatchable and privileged functions, see the [dispatchables Rust docs](https://docs.rs/pallet-assets/latest/pallet_assets/pallet/enum.Call.html){target=\_blank}. - -### Querying Functions - -The Assets pallet exposes several key querying functions that developers can interact with programmatically. These functions allow you to query asset information and perform operations essential for managing assets across accounts. The two main querying functions are: - -- **`balance(asset_id, account)`**: Retrieves the balance of a given asset for a specified account. Useful for checking the holdings of an asset class across different accounts. - -- **`total_supply(asset_id)`**: Returns the total supply of the asset identified by `asset_id`. Allows users to verify how much of the asset exists on-chain. - -In addition to these basic functions, other utility functions are available for querying asset metadata and performing asset transfers. You can view the complete list of querying functions in the [Struct Pallet Rust docs](https://docs.rs/pallet-assets/latest/pallet_assets/pallet/struct.Pallet.html){target=\_blank}. - -### Permission Models and Roles - -The Assets pallet incorporates a robust permission model, enabling control over who can perform specific operations like minting, transferring, or freezing assets. The key roles within the permission model are: - -- **Admin**: Can freeze (preventing transfers) and forcibly transfer assets between accounts. Admins also have the power to reduce the balance of an asset class across arbitrary accounts. They manage the more sensitive and administrative aspects of the asset class. -- **Issuer**: Responsible for minting new tokens. When new assets are created, the Issuer is the account that controls their distribution to other accounts. -- **Freezer**: Can lock the transfer of assets from an account, preventing the account holder from moving their balance. This function is useful for freezing accounts involved in disputes or fraud. -- **Owner**: Has overarching control, including destroying an entire asset class. Owners can also set or update the Issuer, Freezer, and Admin roles. - -These permissions provide fine-grained control over assets, enabling developers and asset managers to ensure secure, controlled operations. Each of these roles is crucial for managing asset lifecycles and ensuring that assets are used appropriately across the network. - -### Asset Freezing - -The Assets pallet allows you to freeze assets. This feature prevents transfers or spending from a specific account, effectively locking the balance of an asset class until it is explicitly unfrozen. Asset freezing is beneficial when assets are restricted due to security concerns or disputes. - -Freezing assets is controlled by the Freezer role, as mentioned earlier. Only the account with the Freezer privilege can perform these operations. Here are the key freezing functions: - -- **`freeze(asset_id, account)`**: Locks the specified asset of the account. While the asset is frozen, no transfers can be made from the frozen account. -- **`thaw(asset_id, account)`**: Corresponding function for unfreezing, allowing the asset to be transferred again. - -This approach enables secure and flexible asset management, providing administrators the tools to control asset movement in special circumstances. - -### Non-Custodial Transfers (Approval API) - -The Assets pallet also supports non-custodial transfers through the Approval API. This feature allows one account to approve another account to transfer a specific amount of its assets to a third-party recipient without granting full control over the account's balance. Non-custodial transfers enable secure transactions where trust is required between multiple parties. - -Here's a brief overview of the key functions for non-custodial asset transfers: - -- **`approve_transfer(asset_id, delegate, amount)`**: Approves a delegate to transfer up to a certain amount of the asset on behalf of the original account holder. -- **`cancel_approval(asset_id, delegate)`**: Cancels a previous approval for the delegate. Once canceled, the delegate no longer has permission to transfer the approved amount. -- **`transfer_approved(asset_id, owner, recipient, amount)`**: Executes the approved asset transfer from the owner’s account to the recipient. The delegate account can call this function once approval is granted. - -These delegated operations make it easier to manage multi-step transactions and dApps that require complex asset flows between participants. - -## Foreign Assets - -Foreign assets in Asset Hub refer to assets originating from external blockchains or parachains that are registered in the Asset Hub. These assets are typically native tokens from other parachains within the Polkadot ecosystem or bridged tokens from external blockchains such as Ethereum. - -Once a foreign asset is registered in the Asset Hub by its originating blockchain's root origin, users are able to send these tokens to the Asset Hub and interact with them as they would any other asset within the Polkadot ecosystem. - -### Handling Foreign Assets - -The Foreign Assets pallet, an instance of the Assets pallet, manages these assets. Since foreign assets are integrated into the same interface as native assets, developers can use the same functionalities, such as transferring and querying balances. However, there are important distinctions when dealing with foreign assets. - -- **Asset identifier**: Unlike native assets, foreign assets are identified using an XCM Multilocation rather than a simple numeric `AssetId`. This multilocation identifier represents the cross-chain location of the asset and provides a standardized way to reference it across different parachains and relay chains. - -- **Transfers**: Once registered in the Asset Hub, foreign assets can be transferred between accounts, just like native assets. Users can also send these assets back to their originating blockchain if supported by the relevant cross-chain messaging mechanisms. - -## Integration - -Asset Hub supports a variety of integration tools that make it easy for developers to manage assets and interact with the blockchain in their applications. The tools and libraries provided by Parity Technologies enable streamlined operations, such as querying asset information, building transactions, and monitoring cross-chain asset transfers. - -Developers can integrate Asset Hub into their projects using these core tools: - -### API Sidecar - -[API Sidecar](https://github.com/paritytech/substrate-api-sidecar){target=\_blank} is a RESTful service that can be deployed alongside Polkadot and Kusama nodes. It provides endpoints to retrieve real-time blockchain data, including asset information. When used with Asset Hub, Sidecar allows querying: - -- **Asset look-ups**: Retrieve specific assets using `AssetId`. -- **Asset balances**: View the balance of a particular asset on Asset Hub. - -Public instances of API Sidecar connected to Asset Hub are available, such as: - -- [Polkadot Asset Hub Sidecar](https://polkadot-asset-hub-public-sidecar.parity-chains.parity.io/){target=\_blank} -- [Kusama Asset Hub Sidecar](https://kusama-asset-hub-public-sidecar.parity-chains.parity.io/){target=\_blank} - -These public instances are primarily for ad-hoc testing and quick checks. - -### TxWrapper - -[`TxWrapper`](https://github.com/paritytech/txwrapper-core){target=\_blank} is a library that simplifies constructing and signing transactions for Polkadot SDK-based chains, including Polkadot and Kusama. This tool includes support for working with Asset Hub, enabling developers to: - -- Construct offline transactions. -- Leverage asset-specific functions such as minting, burning, and transferring assets. - -`TxWrapper` provides the flexibility needed to integrate asset operations into custom applications while maintaining the security and efficiency of Polkadot's transaction model. - - -### Parachain Node - -To fully leverage the Asset Hub's functionality, developers will need to run a system parachain node. Setting up an Asset Hub node allows users to interact with the parachain in real time, syncing data and participating in the broader Polkadot ecosystem. Guidelines for setting up an [Asset Hub node](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/cumulus#asset-hub-){target=\_blank} are available in the Parity documentation. - -Using these integration tools, developers can manage assets seamlessly and integrate Asset Hub functionality into their applications, leveraging Polkadot's powerful infrastructure. - -## XCM Transfer Monitoring - -Since Asset Hub facilitates cross-chain asset transfers across the Polkadot ecosystem, XCM transfer monitoring becomes an essential practice for developers and infrastructure providers. This section outlines how to monitor the cross-chain movement of assets between parachains, the relay chain, and other systems. - -### Monitor XCM Deposits - -As assets move between chains, tracking the cross-chain transfers in real time is crucial. Whether assets are transferred via a teleport from system parachains or through a reserve-backed transfer from any other parachain, each transfer emits a relevant event (such as the `balances.minted` event). - -To ensure accurate monitoring of these events: - -- **Track XCM deposits**: Query every new block created in the relay chain or Asset Hub, loop through the events array, and filter for any `balances.minted` events which confirm the asset was successfully transferred to the account. -- **Track event origins**: Each `balances.minted` event points to a specific address. By monitoring this, service providers can verify that assets have arrived in the correct account. - -### Track XCM Information Back to the Source - -While the `balances.minted` event confirms the arrival of assets, there may be instances where you need to trace the origin of the cross-chain message that triggered the event. In such cases, you can: - -1. Query the relevant chain at the block where the `balances.minted` event was emitted. -2. Look for a `messageQueue(Processed)` event within that block's initialization. This event contains a parameter (`Id`) that identifies the cross-chain message received by the relay chain or Asset Hub. You can use this `Id` to trace the message back to its origin chain, offering full visibility of the asset transfer's journey. - -### Practical Monitoring Examples - -The preceding sections outline the process of monitoring XCM deposits to specific accounts and then tracing back the origin of these deposits. The process of tracking an XCM transfer and the specific events to monitor may vary based on the direction of the XCM message. Here are some examples to showcase the slight differences: - -- **Transfer from parachain to relay chain**: Track `parachainsystem(UpwardMessageSent)` on the parachain and `messagequeue(Processed)` on the relay chain. -- **Transfer from relay chain to parachain**: Track `xcmPallet(sent)` on the relay chain and `dmpqueue(ExecutedDownward)` on the parachain. -- **Transfer between parachains**: Track `xcmpqueue(XcmpMessageSent)` on the system parachain and `xcmpqueue(Success)` on the destination parachain. - -### Monitor for Failed XCM Transfers - -Sometimes, XCM transfers may fail due to liquidity or other errors. Failed transfers emit specific error events, which are key to resolving issues in asset transfers. Monitoring for these failure events helps catch issues before they affect asset balances. - -- **Relay chain to system parachain**: Look for the `dmpqueue(ExecutedDownward)` event on the parachain with an `Incomplete` outcome and an error type such as `UntrustedReserveLocation`. -- **Parachain to parachain**: Monitor for `xcmpqueue(Fail)` on the destination parachain with error types like `TooExpensive`. - -For detailed error management in XCM, see Gavin Wood's blog post on [XCM Execution and Error Management](https://polkadot.com/blog/xcm-part-three-execution-and-error-management/){target=\_blank}. - -## Where to Go Next - -
- -- Tutorial __Register a Local Asset__ - - --- - - Comprehensive guide to registering a local asset on the Asset Hub system parachain, including step-by-step instructions. - - [:octicons-arrow-right-24: Reference](/chain-interactions/token-operations/register-local-asset/) - -- Tutorial __Register a Foreign Asset__ - - --- - - An in-depth guide to registering a foreign asset on the Asset Hub parachain, providing clear, step-by-step instructions. - - [:octicons-arrow-right-24: Reference](/chain-interactions/token-operations/register-foreign-asset/) - -- Tutorial __Convert Assets__ - - --- - - A guide detailing the step-by-step process of converting assets on Asset Hub, helping users efficiently navigate asset management on the platform. - - [:octicons-arrow-right-24: Reference](/chain-interactions/token-operations/convert-assets/) - -
diff --git a/.ai/pages/reference-polkadot-hub-bridging.md b/.ai/pages/reference-polkadot-hub-bridging.md deleted file mode 100644 index ba5c3816a..000000000 --- a/.ai/pages/reference-polkadot-hub-bridging.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Bridge Hub -description: Learn about the Bridge Hub system parachain, a parachain that facilitates the interactions from Polkadot to the rest of Web3. -categories: Polkadot Protocol -url: https://docs.polkadot.com/reference/polkadot-hub/bridging/ ---- - -# Bridge Hub - -## Introduction - -The Bridge Hub system parachain plays a crucial role in facilitating trustless interactions between Polkadot, Kusama, Ethereum, and other blockchain ecosystems. By implementing on-chain light clients and supporting protocols like BEEFY and GRANDPA, Bridge Hub ensures seamless message transmission and state verification across chains. It also provides essential [pallets](/reference/glossary/#pallet){target=\_blank} for sending and receiving messages, making it a cornerstone of Polkadot’s interoperability framework. With built-in support for XCM (Cross-Consensus Messaging), Bridge Hub enables secure, efficient communication between diverse blockchain networks. - -This guide covers the architecture, components, and deployment of the Bridge Hub system. You'll explore its trustless bridging mechanisms, key pallets for various blockchains, and specific implementations like Snowbridge and the Polkadot <> Kusama bridge. By the end, you'll understand how Bridge Hub enhances connectivity within the Polkadot ecosystem and beyond. - -## Trustless Bridging - -Bridge Hub provides a mode of trustless bridging through its implementation of on-chain light clients and trustless relayers. Trustless bridges are essentially two one-way bridges, where each chain has a method of verifying the state of the other in a trustless manner through consensus proofs. In this context, "trustless" refers to the lack of need to trust a human when interacting with various system components. Trustless systems are based instead on trusting mathematics, cryptography, and code. The target chain and source chain both provide ways of verifying one another's state and actions (such as a transfer) based on the consensus and finality of both chains rather than an external mechanism controlled by a third party. - -[BEEFY (Bridge Efficiency Enabling Finality Yielder)](/reference/polkadot-hub/consensus-and-security/pos-consensus/#bridging-beefy){target=\_blank} is instrumental in this solution. It provides a more efficient way to verify the consensus on the relay chain. It allows the participants in a network to verify finality proofs, meaning a remote chain like Ethereum can verify the state of Polkadot at a given block height. - -For example, the Ethereum and Polkadot bridging solution that [Snowbridge](https://docs.snowbridge.network/){target=\_blank} implements involves two light clients: one which verifies the state of Polkadot and the other which verifies the state of Ethereum. The light client for Polkadot is implemented in the runtime as a pallet, whereas the light client for Ethereum is implemented as a smart contract on the beacon chain. - -## Bridging Components - -In any given Bridge Hub implementation (Kusama, Polkadot, or other relay chains), there are a few primary pallets that are utilized: - -- **[Pallet Bridge GRANDPA](https://paritytech.github.io/polkadot-sdk/master/pallet_bridge_grandpa/index.html){target=\_blank}**: An on-chain GRANDPA light client for Substrate based chains. -- **[Pallet Bridge Parachains](https://paritytech.github.io/polkadot-sdk/master/pallet_bridge_parachains/index.html){target=\_blank}**: A finality module for parachains. -- **[Pallet Bridge Messages](https://paritytech.github.io/polkadot-sdk/master/pallet_bridge_messages/index.html){target=\_blank}**: A pallet which allows sending, receiving, and tracking of inbound and outbound messages. -- **[Pallet XCM Bridge](https://paritytech.github.io/polkadot-sdk/master/pallet_xcm_bridge_hub/index.html){target=\_blank}**: A pallet which, with the Bridge Messages pallet, adds XCM support to bridge pallets. - -### Ethereum-Specific Support - -Bridge Hub also has a set of components and pallets that support a bridge between Polkadot and Ethereum through [Snowbridge](https://github.com/Snowfork/snowbridge){target=\_blank}. - -To view the complete list of which pallets are included in Bridge Hub, visit the Subscan [Runtime Modules](https://bridgehub-polkadot.subscan.io/runtime){target=\_blank} page. Alternatively, the source code for those pallets can be found in the Polkadot SDK [Snowbridge Pallets](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/bridges/snowbridge/pallets){target=\_blank} repository. - -## Deployed Bridges - -- [**Snowbridge**](https://wiki.polkadot.com/learn/learn-snowbridge/){target=\_blank}: A general-purpose, trustless bridge between Polkadot and Ethereum. -- [**Hyperbridge**](https://wiki.polkadot.com/learn/learn-hyperbridge/){target=\_blank}: A cross-chain solution built as an interoperability coprocessor, providing state-proof-based interoperability across all blockchains. -- [**Polkadot <> Kusama Bridge**](https://wiki.polkadot.com/learn/learn-dot-ksm-bridge/){target=\_blank}: A bridge that utilizes relayers to bridge the Polkadot and Kusama relay chains trustlessly. - -## Where to Go Next - -- Go over the Bridge Hub README in the Polkadot SDK [Bridge-hub Parachains](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/cumulus/parachains/runtimes/bridge-hubs/README.md){target=\_blank} repository. -- Take a deeper dive into bridging architecture in the Polkadot SDK [High-Level Bridge](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/bridges/docs/high-level-overview.md){target=\_blank} documentation. -- Read more about [BEEFY and Bridging in the Polkadot Wiki](/reference/polkadot-hub/consensus-and-security/pos-consensus/#bridging-beefy){target=\_blank}. diff --git a/.ai/pages/reference-polkadot-hub-collectives-and-daos.md b/.ai/pages/reference-polkadot-hub-collectives-and-daos.md deleted file mode 100644 index 0a35af313..000000000 --- a/.ai/pages/reference-polkadot-hub-collectives-and-daos.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: Collectives Chain -description: Learn how the Collectives chain provides infrastructure for governance organizations, enabling decentralized network stewardship and decision-making. -categories: Polkadot Protocol -url: https://docs.polkadot.com/reference/polkadot-hub/collectives-and-daos/ ---- - -## Introduction - -Established through [Referendum 81](https://polkadot-old.polkassembly.io/referendum/81){target=\_blank}, the Collectives chain operates as a dedicated parachain exclusive to the Polkadot network with no counterpart on Kusama. This specialized infrastructure provides a foundation for various on-chain governance groups essential to Polkadot's ecosystem. - -The architecture enables entire networks to function as unified entities, allowing them to present cohesive positions and participate in cross-network governance through [Bridge Hub](/polkadot-protocol/architecture/system-chains/bridge-hub){target=\_blank}. This capability represents a fundamental advancement in Web3 principles, eliminating dependencies on traditional third-party intermediaries such as legal systems or jurisdictional authorities. - -## Key Collectives - -The Collectives chain hosts several important governance bodies: - -- [**Polkadot Technical Fellowship**](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\_blank}: A self-governing assembly of protocol experts and developers who oversee technical aspects of the Polkadot and Kusama networks. The Fellowship operates both on-chain through the collectives system and off-chain via GitHub repositories, public discussion forums, and monthly development calls that are publicly accessible. - -- [**Polkadot Alliance**](https://wiki.polkadot.com/general/glossary/#polkadot-alliance){target=\_blank}: A consortium founded by seven leading parachain projects (Acala, Astar, Interlay, Kilt, Moonbeam, Phala, and Subscan) to establish development standards and ethical guidelines within the ecosystem. This ranked collective, comprised of "Fellows" and "Allies," focuses on promoting best practices and identifying potential bad actors. Membership is primarily designed for organizations, projects, and other networks rather than individuals. - -These collectives serve as pillars of Polkadot's decentralized governance model, enabling community-driven decision-making and establishing technical standards that shape the network's evolution. Through structured on-chain representation, they provide transparent mechanisms for ecosystem development while maintaining the core Web3 principles of trustlessness and decentralization. diff --git a/.ai/pages/reference-polkadot-hub-consensus-and-security-agile-coretime.md b/.ai/pages/reference-polkadot-hub-consensus-and-security-agile-coretime.md deleted file mode 100644 index 3efbd5901..000000000 --- a/.ai/pages/reference-polkadot-hub-consensus-and-security-agile-coretime.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: Agile Coretime -description: Explore the efficient scheduling mechanisms to access Polkadot cores to produce blockspace continuously or on-demand. -categories: Polkadot Protocol -url: https://docs.polkadot.com/reference/polkadot-hub/consensus-and-security/agile-coretime/ ---- - -# Agile Coretime - -## Introduction - -Agile Coretime is the [scheduling](https://en.wikipedia.org/wiki/Scheduling_(computing)){target=\_blank} framework on Polkadot that lets parachains efficiently access cores, which comprise an active validator set tasked with parablock validation. As the first blockchain to enable a flexible scheduling system for blockspace production, Polkadot offers unparalleled adaptability for parachains. - -``` mermaid -graph TB - A[Cores Designation] - B[Bulk Coretime] - C[On-Demand Coretime] - A --continuous--> B - A --flexible--> C -``` - -Cores can be designated to a parachain either continuously through [bulk coretime](#bulk-coretime) or dynamically via [on-demand coretime](#on-demand-coretime). Additionally, Polkadot supports scheduling multiple cores in parallel through [elastic scaling](https://wiki.polkadot.com/learn/learn-elastic-scaling/){target=\_blank}, which is a feature under active development on Polkadot. This flexibility empowers parachains to optimize their resource usage and block production according to their unique needs. - -In this guide, you'll learn how bulk coretime enables continuous core access with features like interlacing and splitting, and how on-demand coretime provides flexible, pay-per-use scheduling for parachains. For a deep dive on Agile Coretime and its terminology, refer to the [Wiki doc](https://wiki.polkadot.com/learn/learn-agile-coretime/#introduction-to-agile-coretime){target=\_blank}. - -## Bulk Coretime - -Bulk coretime is a fixed duration of continuous coretime represented by an NFT that can be purchased through [coretime sales](#coretime-sales) in DOT and can be split, shared, or resold. Currently, the duration of bulk coretime is set to 28 days. Coretime purchased in bulk and assigned to a single parachain is eligible for a price-capped renewal, providing a form of rent-controlled access, which is important for predicting the running costs in the near future. Suppose the bulk coretime is [interlaced](#coretime-interlacing) or [split](#coretime-splitting) or is kept idle without assigning it to a parachain. In that case, it will be ineligible for the price-capped renewal. - -### Coretime Interlacing - -It is the action of dividing bulk coretime across multiple parachains that produce blocks spaced uniformly in time. For example, think of multiple parachains taking turns producing blocks, demonstrating a simple form of interlacing. This feature can be used by parachains with a low transaction volume and need not continuously produce blocks. - -### Coretime Splitting - -It is the action of dividing bulk coretime into multiple contiguous regions. This feature can be used by parachains that need to produce blocks continuously but do not require the whole 28 days of bulk coretime and require only part of it. - -## On-Demand Coretime - -Polkadot has dedicated cores assigned to provide core time on demand. These cores are excluded from the coretime sales and are reserved for on-demand parachains, which pay in DOT per block. diff --git a/.ai/pages/reference-polkadot-hub-consensus-and-security-pos-consensus.md b/.ai/pages/reference-polkadot-hub-consensus-and-security-pos-consensus.md deleted file mode 100644 index db10157e0..000000000 --- a/.ai/pages/reference-polkadot-hub-consensus-and-security-pos-consensus.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Proof of Stake Consensus -description: Explore Polkadot's consensus protocols for secure, scalable, and decentralized network operation, including NPoS, BABE, GRANDPA, and BEEFY. -categories: Polkadot Protocol -url: https://docs.polkadot.com/reference/polkadot-hub/consensus-and-security/pos-consensus/ ---- - -# Proof of Stake Consensus - -## Introduction - -Polkadot's Proof of Stake consensus model leverages a unique hybrid approach by design to promote decentralized and secure network operations. In traditional Proof of Stake (PoS) systems, a node's ability to validate transactions is tied to its token holdings, which can lead to centralization risks and limited validator participation. Polkadot addresses these concerns through its [Nominated Proof of Stake (NPoS)](/reference/glossary/#nominated-proof-of-stake-npos){target=\_blank} model and a combination of advanced consensus mechanisms to ensure efficient block production and strong finality guarantees. This combination enables the Polkadot network to scale while maintaining security and decentralization. - -## Nominated Proof of Stake - -Polkadot uses Nominated Proof of Stake (NPoS) to select the validator set and secure the network. This model is designed to maximize decentralization and security by balancing the roles of [validators](https://wiki.polkadot.com/learn/learn-validator/){target=\_blank} and [nominators](https://wiki.polkadot.com/learn/learn-nominator/){target=\_blank}. - -- **Validators**: Play a key role in maintaining the network's integrity. They produce new blocks, validate parachain blocks, and ensure the finality of transactions across the relay chain. -- **Nominators**: Support the network by selecting validators to back with their stake. This mechanism allows users who don't want to run a validator node to still participate in securing the network and earn rewards based on the validators they support. - -In Polkadot's NPoS system, nominators can delegate their tokens to trusted validators, giving them voting power in selecting validators while spreading security responsibilities across the network. - -## Hybrid Consensus - -Polkadot employs a hybrid consensus model that combines two key protocols: a finality gadget called [GRANDPA](#finality-gadget-grandpa) and a block production mechanism known as [BABE](#block-production-babe). This hybrid approach enables the network to benefit from both rapid block production and provable finality, ensuring security and performance. - -The hybrid consensus model has some key advantages: - -- **Probabilistic finality**: With BABE constantly producing new blocks, Polkadot ensures that the network continues to make progress, even when a final decision has not yet been reached on which chain is the true canonical chain. - -- **Provable finality**: GRANDPA guarantees that once a block is finalized, it can never be reverted, ensuring that all network participants agree on the finalized chain. - -By using separate protocols for block production and finality, Polkadot can achieve rapid block creation and strong guarantees of finality while avoiding the typical trade-offs seen in traditional consensus mechanisms. - -## Block Production - BABE - -Blind Assignment for Blockchain Extension (BABE) is Polkadot's block production mechanism, working with GRANDPA to ensure blocks are produced consistently across the network. As validators participate in BABE, they are assigned block production slots through a randomness-based lottery system. This helps determine which validator is responsible for producing a block at a given time. BABE shares similarities with [Ouroboros Praos](https://eprint.iacr.org/2017/573.pdf){target=\_blank} but differs in key aspects like chain selection rules and slot timing. - -Key features of BABE include: - -- **Epochs and slots**: BABE operates in phases called epochs, each of which is divided into slots (around 6 seconds per slot). Validators are assigned slots at the beginning of each epoch based on stake and randomness. - -- **Randomized block production**: Validators enter a lottery to determine which will produce a block in a specific slot. This randomness is sourced from the relay chain's [randomness cycle](/reference/parachains/randomness/){target=\_blank}. - -- **Multiple block producers per slot**: In some cases, more than one validator might win the lottery for the same slot, resulting in multiple blocks being produced. These blocks are broadcasted, and the network's fork choice rule helps decide which chain to follow. - -- **Handling empty slots**: If no validators win the lottery for a slot, a secondary selection algorithm ensures that a block is still produced. Validators selected through this method always produce a block, ensuring no slots are skipped. - -BABE's combination of randomness and slot allocation creates a secure, decentralized system for consistent block production while also allowing for fork resolution when multiple validators produce blocks for the same slot. - -### Validator Participation - -In BABE, validators participate in a lottery for every slot to determine whether they are responsible for producing a block during that slot. This process's randomness ensures a decentralized and unpredictable block production mechanism. - -There are two lottery outcomes for any given slot that initiate additional processes: - -- **Multiple validators in a slot**: Due to the randomness, multiple validators can be selected to produce a block for the same slot. When this happens, each validator produces a block and broadcasts it to the network resulting in a race condition. The network's topology and latency then determine which block reaches the majority of nodes first. BABE allows both chains to continue building until the finalization process resolves which one becomes canonical. The [Fork Choice](#fork-choice) rule is then used to decide which chain the network should follow. - -- **No validators in a slot**: On occasions when no validator is selected by the lottery, a [secondary validator selection algorithm](https://spec.polkadot.network/sect-block-production#defn-babe-secondary-slots){target=\_blank} steps in. This backup ensures that a block is still produced, preventing skipped slots. However, if the primary block produced by a verifiable random function [(VRF)-selected](/reference/parachains/randomness/#vrf){target=\_blank} validator exists for that slot, the secondary block will be ignored. As a result, every slot will have either a primary or a secondary block. - -This design ensures continuous block production, even in cases of multiple competing validators or an absence of selected validators. - -### Additional Resources - -For further technical insights about BABE, including cryptographic details and formal proofs, see the [BABE paper](https://research.web3.foundation/Polkadot/protocols/block-production/Babe){target=\_blank} from Web3 Foundation. - -For BABE technical definitions, constants, and formulas, see the [Block Production Lottery](https://spec.polkadot.network/sect-block-production#sect-block-production-lottery){target=\_blank} section of the Polkadot Protocol Specification. - -## Finality Gadget - GRANDPA - -GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) serves as the finality gadget for Polkadot's relay chain. Operating alongside the BABE block production mechanism, it ensures provable finality, giving participants confidence that blocks finalized by GRANDPA cannot be reverted. - -Key features of GRANDPA include: - -- **Independent finality service**: GRANDPA runs separately from the block production process, operating in parallel to ensure seamless finalization. -- **Chain-based finalization**: Instead of finalizing one block at a time, GRANDPA finalizes entire chains, speeding up the process significantly. -- **Batch finalization**: Can finalize multiple blocks in a single round, enhancing efficiency and minimizing delays in the network. -- **Partial synchrony tolerance**: GRANDPA works effectively in a partially synchronous network environment, managing both asynchronous and synchronous conditions. -- **Byzantine fault tolerance**: Can handle up to 1/5 Byzantine (malicious) nodes, ensuring the system remains secure even when faced with adversarial behavior. - -??? note "What is GHOST?" - [GHOST (Greedy Heaviest-Observed Subtree)](https://eprint.iacr.org/2018/104.pdf){target=\blank} is a consensus protocol used in blockchain networks to select the heaviest branch in a block tree. Unlike traditional longest-chain rules, GHOST can more efficiently handle high block production rates by considering the weight of subtrees rather than just the chain length. - -### Probabilistic vs. Provable Finality - -In traditional Proof of Work (PoW) blockchains, finality is probabilistic. As blocks are added to the chain, the probability that a block is final increases, but it can never be guaranteed. Eventual consensus means that all nodes will agree on a single version of the blockchain over time, but this process can be unpredictable and slow. - -Conversely, GRANDPA provides provable finality, which means that once a block is finalized, it is irreversible. By using Byzantine fault-tolerant agreements, GRANDPA finalizes blocks more efficiently and securely than probabilistic mechanisms like Nakamoto consensus. Like Ethereum's Casper the Friendly Finality Gadget (FFG), GRANDPA ensures that finalized blocks cannot be reverted, offering stronger consensus guarantees. - -### Additional Resources - -For technical insights, including formal proofs and detailed algorithms, see the [GRANDPA paper](https://github.com/w3f/consensus/blob/master/pdf/grandpa.pdf){target=\_blank} from Web3 Foundation. - -For a deeper look at the code behind GRANDPA, see the following GitHub repositories: - -- [GRANDPA Rust implementation](https://github.com/paritytech/finality-grandpa){target=\_blank} -- [GRANDPA Pallet](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/substrate/frame/grandpa/src/lib.rs){target=\_blank} - -## Fork Choice - -The fork choice of the relay chain combines BABE and GRANDPA: - -1. BABE must always build on the chain that GRANDPA has finalized. -2. When there are forks after the finalized head, BABE builds on the chain with the most primary blocks to provide probabilistic finality. - -![Fork choice diagram](/images/reference/polkadot-hub/consensus-and-security/pos-consensus/consensus-protocols-01.webp) - -In the preceding diagram, finalized blocks are black, and non-finalized blocks are yellow. Primary blocks are labeled '1', and secondary blocks are labeled '2.' The topmost chain is the longest chain originating from the last finalized block, but it is not selected because it only has one primary block at the time of evaluation. In comparison, the one below it originates from the last finalized block and has three primary blocks. - -### Additional Resources - -To learn more about how BABE and GRANDPA work together to produce and finalize blocks on Kusama, see this [Block Production and Finalization in Polkadot](https://youtu.be/FiEAnVECa8c){target=\_blank} talk from Web3 Foundation's Bill Laboon. - -For an in-depth academic discussion about Polkadot's hybrid consensus model, see this [Block Production and Finalization in Polkadot: Understanding the BABE and GRANDPA Protocols](https://www.youtube.com/watch?v=1CuTSluL7v4&t=4s){target=\_blank} MIT Cryptoeconomic Systems 2020 talk by Web3 Foundation's Bill Laboon. - -## Bridging - BEEFY - -Bridge Efficiency Enabling Finality Yielder (BEEFY) is a specialized protocol that extends the finality guarantees provided by GRANDPA. It is specifically designed to facilitate efficient bridging between Polkadot relay chains (such as Polkadot and Kusama) and external blockchains like Ethereum. While GRANDPA is well-suited for finalizing blocks within Polkadot, it has limitations when bridging external chains that weren't built with Polkadot's interoperability features in mind. BEEFY addresses these limitations by ensuring other networks can efficiently verify finality proofs. - -Key features of BEEFY include: - -- **Efficient finality proof verification**: BEEFY enables external networks to easily verify Polkadot finality proofs, ensuring seamless communication between chains. -- **Merkle Mountain Ranges (MMR)**: This data structure is used to efficiently store and transmit proofs between chains, optimizing data storage and reducing transmission overhead. -- **ECDSA signature schemes**: BEEFY uses ECDSA signatures, which are widely supported on Ethereum and other EVM-based chains, making integration with these ecosystems smoother. -- **Light client optimization**: BEEFY reduces the computational burden on light clients by allowing them to check for a super-majority of validator votes rather than needing to process all validator signatures, improving performance. - -### Additional Resources - -For BEEFY technical definitions, constants, and formulas, see the [Bridge design (BEEFY)](https://spec.polkadot.network/sect-finality#sect-grandpa-beefy){target=\_blank} section of the Polkadot Protocol Specification. diff --git a/.ai/pages/reference-polkadot-hub-consensus-and-security-relay-chain.md b/.ai/pages/reference-polkadot-hub-consensus-and-security-relay-chain.md deleted file mode 100644 index 94eee0632..000000000 --- a/.ai/pages/reference-polkadot-hub-consensus-and-security-relay-chain.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -title: Overview of the Polkadot Relay Chain -description: Explore Polkadot's core architecture, including its multi-chain vision, shared security, and the DOT token's governance and staking roles. -categories: Basics, Polkadot Protocol, Parachains -url: https://docs.polkadot.com/reference/polkadot-hub/consensus-and-security/relay-chain/ ---- - -# Overview - -## Introduction - -Polkadot is a next-generation blockchain protocol designed to support a multi-chain future by enabling secure communication and interoperability between different blockchains. Built as a Layer-0 protocol, Polkadot introduces innovations like application-specific Layer-1 chains ([parachains](/polkadot-protocol/architecture/parachains/){targe=\_blank}), shared security through [Nominated Proof of Stake (NPoS)](/reference/glossary/#nominated-proof-of-stake-npos){target=\_blank}, and cross-chain interactions via its native [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank}. - -This guide covers key aspects of Polkadot’s architecture, including its high-level protocol structure, blockspace commoditization, and the role of its native token, DOT, in governance, staking, and resource allocation. - -## Polkadot 1.0 - -Polkadot 1.0 represents the state of Polkadot as of 2023, coinciding with the release of [Polkadot runtime v1.0.0](https://github.com/paritytech/polkadot/releases/tag/v1.0.0){target=\_blank}. This section will focus on Polkadot 1.0, along with philosophical insights into network resilience and blockspace. - -As a Layer-0 blockchain, Polkadot contributes to the multi-chain vision through several key innovations and initiatives, including: - -- **Application-specific Layer-1 blockchains (parachains)**: Polkadot's sharded network allows for parallel transaction processing, with shards that can have unique state transition functions, enabling custom-built L1 chains optimized for specific applications. - -- **Shared security and scalability**: L1 chains connected to Polkadot benefit from its [Nominated Proof of Stake (NPoS)](/reference/polkadot-hub/consensus-and-security/pos-consensus/#nominated-proof-of-stake){target=\_blank} system, providing security out-of-the-box without the need to bootstrap their own. - -- **Secure interoperability**: Polkadot's native interoperability enables seamless data and value exchange between parachains. This interoperability can also be used outside of the ecosystem for bridging with external networks. - -- **Resilient infrastructure**: Decentralized and scalable, Polkadot ensures ongoing support for development and community initiatives via its on-chain [treasury](https://wiki.polkadot.com/learn/learn-polkadot-opengov-treasury/){target=\_blank} and governance. - -- **Rapid L1 development**: The [Polkadot SDK](/reference/parachains/){target=\_blank} allows fast, flexible creation and deployment of Layer-1 chains. - -- **Cultivating the next generation of Web3 developers**: Polkadot supports the growth of Web3 core developers through initiatives such as. - - - [Polkadot Blockchain Academy](https://polkadot.com/blockchain-academy){target=\_blank} - - [EdX courses](https://www.edx.org/school/web3x){target=\_blank} - - Rust and Substrate courses (coming soon) - -### High-Level Architecture - -Polkadot features a chain that serves as the central component of the system. This chain is depicted as a ring encircled by several parachains that are connected to it. - -According to Polkadot's design, any blockchain that can compile to WebAssembly (Wasm) and adheres to the Parachains Protocol becomes a parachain on the Polkadot network. - -Here’s a high-level overview of the Polkadot protocol architecture: - -![](/images/reference/polkadot-hub/consensus-and-security/relay-chain/relay-chain-01.webp){ style="background:white" } - -Parachains propose blocks to Polkadot validators, who check for availability and validity before finalizing them. With the relay chain providing security, collators—full nodes of parachains—can focus on their tasks without needing strong incentives. - -The [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\_blank} allows parachains to exchange messages freely, leveraging the chain's security for trust-free communication. - -In order to interact with chains that want to use their own finalization process (e.g., Bitcoin), Polkadot has [bridges](/reference/parachains/interoperability/#bridges-connecting-external-networks){target=\_blank} that offer two-way compatibility, meaning that transactions can be made between different parachains. - -### Polkadot's Additional Functionalities - -Historically, obtaining core slots on Polkadot chain relied upon crowdloans and auctions. Chain cores were leased through auctions for three-month periods, up to a maximum of two years. Crowdloans enabled users to securely lend funds to teams for lease deposits in exchange for pre-sale tokens, which is the only way to access slots on Polkadot 1.0. Auctions are now deprecated in favor of [coretime](/polkadot-protocol/architecture/system-chains/coretime/){target=\_blank}. - -Additionally, the chain handles [staking](https://wiki.polkadot.com/learn/learn-staking/){target=\_blank}, [accounts](/reference/parachains/accounts/){target=\_blank}, balances, and [governance](/reference/governance/){target=\_blank}. - -#### Agile Coretime - -The new and more efficient way of obtaining core on Polkadot is to go through the process of purchasing coretime. - -[Agile coretime](/reference/polkadot-hub/consensus-and-security/agile-coretime/){target=\_blank} improves the efficient use of Polkadot's network resources and offers economic flexibility for developers, extending Polkadot's capabilities far beyond the original vision outlined in the [whitepaper](https://polkadot.com/papers/Polkadot-whitepaper.pdf){target=\_blank}. - -It enables parachains to purchase monthly "bulk" allocations of coretime (the time allocated for utilizing a core, measured in Polkadot relay chain blocks), ensuring heavy-duty parachains that can author a block every six seconds with [Asynchronous Backing](https://wiki.polkadot.com/learn/learn-async-backing/#asynchronous-backing){target=\_blank} can reliably renew their coretime each month. Although six-second block times are now the default, parachains have the option of producing blocks less frequently. - -Renewal orders are prioritized over new orders, offering stability against price fluctuations and helping parachains budget more effectively for project costs. - -### Polkadot's Resilience - -Decentralization is a vital component of blockchain networks, but it comes with trade-offs: - -- An overly decentralized network may face challenges in reaching consensus and require significant energy to operate. -- Also, a network that achieves consensus quickly risks centralization, making it easier to manipulate or attack. - -A network should be decentralized enough to prevent manipulative or malicious influence. In this sense, decentralization is a tool for achieving resilience. - -Polkadot 1.0 currently achieves resilience through several strategies: - -- **Nominated Proof of Stake (NPoS)**: Ensures that the stake per validator is maximized and evenly distributed among validators. - -- **Decentralized nodes**: Designed to encourage operators to join the network. This program aims to expand and diversify the validators in the ecosystem who aim to become independent of the program during their term. Feel free to explore more about the program on the official [Decentralized Nodes](https://nodes.web3.foundation/){target=\_blank} page. - -- **On-chain treasury and governance**: Known as [OpenGov](/reference/governance/){target=\_blank}, this system allows every decision to be made through public referenda, enabling any token holder to cast a vote. - -### Polkadot's Blockspace - -Polkadot 1.0’s design allows for the commoditization of blockspace. - -Blockspace is a blockchain's capacity to finalize and commit operations, encompassing its security, computing, and storage capabilities. Its characteristics can vary across different blockchains, affecting security, flexibility, and availability. - -- **Security**: Measures the robustness of blockspace in Proof of Stake (PoS) networks linked to the stake locked on validator nodes, the variance in stake among validators, and the total number of validators. It also considers social centralization (how many validators are owned by single operators) and physical centralization (how many validators run on the same service provider). - -- **Flexibility**: Reflects the functionalities and types of data that can be stored, with high-quality data essential to avoid bottlenecks in critical processes. - -- **Availability**: Indicates how easily users can access blockspace. It should be easily accessible, allowing diverse business models to thrive, ideally regulated by a marketplace based on demand and supplemented by options for "second-hand" blockspace. - -Polkadot is built on core blockspace principles, but there's room for improvement. Tasks like balance transfers, staking, and governance are managed on the relay chain. - -Delegating these responsibilities to [system chains](/polkadot-protocol/architecture/system-chains/){target=\_blank} could enhance flexibility and allow the relay chain to concentrate on providing shared security and interoperability. - -For more information about blockspace, watch [Robert Habermeier’s interview](https://www.youtube.com/watch?v=e1vISppPwe4){target=\_blank} or read his [technical blog post](https://www.rob.tech/blog/polkadot-blockspace-over-blockchains/){target=\_blank}. - -## DOT Token - -DOT is the native token of the Polkadot network, much like BTC for Bitcoin and Ether for the Ethereum blockchain. DOT has 10 decimals, uses the Planck base unit, and has a balance type of `u128`. The same is true for Kusama's KSM token with the exception of having 12 decimals. - -### Redenomination of DOT - -Polkadot conducted a community poll, which ended on 27 July 2020 at block 888,888, to decide whether to redenominate the DOT token. The stakeholders chose to redenominate the token, changing the value of 1 DOT from 1e12 plancks to 1e10 plancks. - -Importantly, this did not affect the network's total number of base units (plancks); it only affects how a single DOT is represented. The redenomination became effective 72 hours after transfers were enabled, occurring at block 1,248,328 on 21 August 2020 around 16:50 UTC. - -### The Planck Unit - -The smallest unit of account balance on Polkadot SDK-based blockchains (such as Polkadot and Kusama) is called _Planck_, named after the Planck length, the smallest measurable distance in the physical universe. - -Similar to how BTC's smallest unit is the Satoshi and ETH's is the Wei, Polkadot's native token DOT equals 1e10 Planck, while Kusama's native token KSM equals 1e12 Planck. - -### Uses for DOT - -DOT serves three primary functions within the Polkadot network: - -- **Governance**: It is used to participate in the governance of the network. -- **Staking**: DOT is staked to support the network's operation and security. -- **Buying coretime**: Used to purchase coretime in-bulk or on-demand and access the chain to benefit from Polkadot's security and interoperability. - -Additionally, DOT can serve as a transferable token. For example, DOT, held in the treasury, can be allocated to teams developing projects that benefit the Polkadot ecosystem. - -## JAM and the Road Ahead - -The Join-Accumulate Machine (JAM) represents a transformative redesign of Polkadot's core architecture, envisioned as the successor to the current relay chain. Unlike traditional blockchain architectures, JAM introduces a unique computational model that processes work through two primary functions: - -- **Join**: Handles data integration. -- **Accumulate**: Folds computations into the chain's state. - -JAM removes many of the opinions and constraints of the current relay chain while maintaining its core security properties. Expected improvements include: - -- **Permissionless code execution**: JAM is designed to be more generic and flexible, allowing for permissionless code execution through services that can be deployed without governance approval. -- **More effective block time utilization**: JAM's efficient pipeline processing model places the prior state root in block headers instead of the posterior state root, enabling more effective utilization of block time for computations. - -This architectural evolution promises to enhance Polkadot's scalability and flexibility while maintaining robust security guarantees. JAM is planned to be rolled out to Polkadot as a single, complete upgrade rather than a stream of smaller updates. This approach seeks to minimize the developer overhead required to address any breaking changes. diff --git a/.ai/pages/reference-polkadot-hub-people-and-identity.md b/.ai/pages/reference-polkadot-hub-people-and-identity.md deleted file mode 100644 index 7cfca970e..000000000 --- a/.ai/pages/reference-polkadot-hub-people-and-identity.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: People Chain -description: Learn how People chain secures decentralized identity management, empowering users to control and verify digital identities without central authorities. -categories: Polkadot Protocol -url: https://docs.polkadot.com/reference/polkadot-hub/people-and-identity/ ---- - -# People Chain - -## Introduction - -People chain is a specialized parachain within the Polkadot ecosystem dedicated to secure, decentralized identity management. - -This solution empowers users to create, control, and verify their digital identities without reliance on centralized authorities. By prioritizing user sovereignty and data privacy, People chain establishes a foundation for trusted interactions throughout the Polkadot ecosystem while returning control of personal information to individuals. - -## Identity Management System - -People chain provides a comprehensive identity framework allowing users to: - -- Establish verifiable on-chain identities. -- Control disclosure of personal information. -- Receive verification from trusted registrars. -- Link multiple accounts under a unified identity. - -Users must reserve funds in a bond to store their information on chain. These funds are locked, not spent, and returned when the identity is cleared. - -### Sub-Identities - -The platform supports hierarchical identity structures through sub-accounts: - -- Primary accounts can establish up to 100 linked sub-accounts. -- Each sub-account maintains its own distinct identity. -- All sub-accounts require a separate bond deposit. - -## Verification Process - -### Judgment Requests - -After establishing an on-chain identity, users can request verification from [registrars](#registrars): - -1. Users specify the maximum fee they're willing to pay for judgment. -2. Only registrars whose fees fall below this threshold can provide verification. -3. Registrars assess the provided information and issue a judgment. - -### Judgment Classifications - -Registrars can assign the following confidence levels to identity information: - -- **Unknown**: Default status; no judgment rendered yet. -- **Reasonable**: Data appears valid but without formal verification (standard for most verified identities). -- **Known good**: Information certified correct through formal verification (requires documentation; limited to registrars). -- **Out of date**: Previously verified information that requires updating. -- **Low quality**: Imprecise information requiring correction. -- **Erroneous**: Incorrect information, potentially indicating fraudulent intent. - -A temporary "Fee Paid" status indicates judgment in progress. Both "Fee Paid" and "Erroneous" statuses lock identity information from modification until resolved. - -### Registrars - -Registrars serve as trusted verification authorities within the People chain ecosystem. These entities validate user identities and provide attestations that build trust in the network. - -- Registrars set specific fees for their verification services. -- They can specialize in verifying particular identity fields. -- Verification costs vary based on complexity and thoroughness. - -When requesting verification, users specify their maximum acceptable fee. Only registrars whose fees fall below this threshold can provide judgment. Upon completing the verification process, the user pays the registrar's fee, and the registrar issues an appropriate confidence level classification based on their assessment. - -Multiple registrars operate across the Polkadot and People chain ecosystems, each with unique specializations and fee structures. To request verification: - -1. Research available registrars and their verification requirements. -2. Contact your chosen registrar directly through their specified channels. -3. Submit required documentation according to their verification process. -4. Pay the associated verification fee. - -You must contact specific registrars individually to request judgment. Each registrar maintains its own verification procedures and communication channels. - -## Where to Go Next - -
- -- External __Polkadot.js Guides about Identity__ - - --- - - Step-by-step instructions for managing identities through the Polkadot.js interface, with practical examples and visual guides. - - [:octicons-arrow-right-24: Reference](https://wiki.polkadot.com/learn/learn-guides-identity/) - -- External __How to Set and Clear an Identity__ - - --- - - Practical walkthrough covering identity setup and removal process on People chain. - - [:octicons-arrow-right-24: Reference](https://support.polkadot.network/support/solutions/articles/65000181981-how-to-set-and-clear-an-identity) - -- External __People Chain Runtime Implementation__ - - --- - - Source code for the People chain runtime, detailing the technical architecture of decentralized identity management. - - [:octicons-arrow-right-24: Reference](https://github.com/polkadot-fellows/runtimes/tree/main/system-parachains/people) - -
diff --git a/.ai/pages/reference-polkadot-hub.md b/.ai/pages/reference-polkadot-hub.md deleted file mode 100644 index 1eae456d6..000000000 --- a/.ai/pages/reference-polkadot-hub.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -url: https://docs.polkadot.com/reference/polkadot-hub/ ---- - -TODO diff --git a/.ai/pages/reference-tools-chopsticks.md b/.ai/pages/reference-tools-chopsticks.md deleted file mode 100644 index 61efd3be3..000000000 --- a/.ai/pages/reference-tools-chopsticks.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -url: https://docs.polkadot.com/reference/tools/chopsticks/ ---- - -TODO diff --git a/.ai/pages/reference-tools-dedot.md b/.ai/pages/reference-tools-dedot.md deleted file mode 100644 index 1580e7ca0..000000000 --- a/.ai/pages/reference-tools-dedot.md +++ /dev/null @@ -1,249 +0,0 @@ ---- -title: Dedot -description: Dedot is a next-gen JavaScript client for Polkadot and Polkadot SDK-based blockchains, offering lightweight, tree-shakable APIs with strong TypeScript support. -categories: Tooling, Dapps -url: https://docs.polkadot.com/reference/tools/dedot/ ---- - -# Dedot - -## Introduction - -[Dedot](https://github.com/dedotdev/dedot){target=\_blank} is a next-generation JavaScript client for Polkadot and Polkadot SDK-based blockchains. Designed to elevate the dApp development experience, Dedot is built and optimized to be lightweight and tree-shakable, offering precise types and APIs suggestions for individual Polkadot SDK-based blockchains and [ink! smart contracts](https://use.ink/){target=\_blank}. - -### Key Features - -- **Lightweight and tree-shakable**: No more bn.js or WebAssembly blobs, optimized for dapps bundle size. -- **Fully typed API**: Comprehensive TypeScript support for seamless on-chain interaction and ink! smart contract integration. -- **Multi-version JSON-RPC support**: Compatible with both [legacy](https://github.com/w3f/PSPs/blob/master/PSPs/drafts/psp-6.md){target=\_blank} and [new](https://paritytech.github.io/json-rpc-interface-spec/introduction.html){target=\_blank} JSON-RPC APIs for broad ecosystem interoperability. -- **Light client support**: Designed to work with light clients such as [Smoldot](https://github.com/smol-dot/smoldot){target=\_blank}. -- **Native TypeScript for scale codec**: Implements scale codec parsing directly in TypeScript without relying on custom wrappers. -- **Wallet integration**: Works out-of-the-box with [@polkadot/extension-based](https://github.com/polkadot-js/extension?tab=readme-ov-file#api-interface){target=\_blank} wallets. -- **Familiar API design**: Similar API style to Polkadot.js for easy and fast migration. - -## Installation - -To add Dedot to your project, use the following command: - -=== "npm" - - ```bash - npm i dedot - ``` - -=== "pnpm" - - ```bash - pnpm add dedot - ``` - -=== "yarn" - - ```bash - yarn add dedot - ``` - -To enable auto-completion/IntelliSense for individual chains, install the [`@dedot/chaintypes`](https://www.npmjs.com/package/@dedot/chaintypes){target=\_blank} package as a development dependency: - -=== "npm" - - ```bash - npm i -D @dedot/chaintypes - ``` - -=== "pnpm" - - ```bash - pnpm add -D @dedot/chaintypes - ``` - -=== "yarn" - - ```bash - yarn add -D @dedot/chaintypes - ``` - -## Get Started - -### Initialize a Client Instance - -To connect to and interact with different networks, Dedot provides two client options depending on your needs: - -- **[`DedotClient`](https://docs.dedot.dev/clients-and-providers/clients#dedotclient){target=\_blank}**: Interacts with chains via the [new JSON-RPC APIs](https://paritytech.github.io/json-rpc-interface-spec/introduction.html){target=\_blank}. -- **[`LegacyClient`](https://docs.dedot.dev/clients-and-providers/clients#legacyclient){target=\_blank}**: Interacts with chains via the [legacy JSON-RPC APIs](https://github.com/w3f/PSPs/blob/master/PSPs/drafts/psp-6.md){target=\_blank}. - -Use the following snippets to connect to Polkadot using `DedotClient`: - -=== "WebSocket" - - ```typescript - import { DedotClient, WsProvider } from 'dedot'; - import type { PolkadotApi } from '@dedot/chaintypes'; - - // Initialize providers & clients - const provider = new WsProvider('wss://rpc.polkadot.io'); - const client = await DedotClient.new(provider); - - ``` - -=== "Light Client (Smoldot)" - - ```typescript - import { DedotClient, SmoldotProvider } from 'dedot'; - import type { PolkadotApi } from '@dedot/chaintypes'; - import * as smoldot from 'smoldot'; - - // import `polkadot` chain spec to connect to Polkadot - import { polkadot } from '@substrate/connect-known-chains'; - - // Start smoldot instance & initialize a chain - const client = smoldot.start(); - const chain = await client.addChain({ chainSpec: polkadot }); - - // Initialize providers & clients - const provider = new SmoldotProvider(chain); - const client = await DedotClient.new(provider); - - ``` - -If the node doesn't support new JSON-RPC APIs yet, you can connect to the network using the `LegacyClient`, which is built on top of the legacy JSON-RPC APIs. - -```typescript -import { LegacyClient, WsProvider } from 'dedot'; -import type { PolkadotApi } from '@dedot/chaintypes'; - -const provider = new WsProvider('wss://rpc.polkadot.io'); -const client = await LegacyClient.new(provider); - -``` - -### Enable Type and API Suggestions - -It is recommended to specify the `ChainApi` interface (e.g., `PolkadotApi` in the example in the previous section) of the chain you want to interact with. This enables type and API suggestions/autocompletion for that particular chain (via IntelliSense). If you don't specify a `ChainApi` interface, a default `SubstrateApi` interface will be used. - -```typescript -import { DedotClient, WsProvider } from 'dedot'; -import type { PolkadotApi, KusamaApi } from '@dedot/chaintypes'; - -const polkadotClient = await DedotClient.new( - new WsProvider('wss://rpc.polkadot.io') -); -const kusamaClient = await DedotClient.new( - new WsProvider('wss://kusama-rpc.polkadot.io') -); -const genericClient = await DedotClient.new( - new WsProvider('ws://localhost:9944') -); - -``` - -If you don't find the `ChainApi` for the network you're working with in [the list](https://github.com/dedotdev/chaintypes?tab=readme-ov-file#supported-networks){target=\_blank}, you can generate the `ChainApi` (types and APIs) using the built-in [`dedot` cli](https://docs.dedot.dev/cli){target=\_blank}. - -```bash -# Generate ChainApi interface for Polkadot network via rpc endpoint: wss://rpc.polkadot.io -npx dedot chaintypes -w wss://rpc.polkadot.io -``` - -Or open a pull request to add your favorite network to the [`@dedot/chaintypes`](https://github.com/dedotdev/chaintypes){target=\_blank} repo. - -### Read On-Chain Data - -Dedot provides several ways to read data from the chain: - -- **Access runtime constants**: Use the syntax `client.consts..` to inspect runtime constants (parameter types). - - ```typescript - const ss58Prefix = client.consts.system.ss58Prefix; - console.log('Polkadot ss58Prefix:', ss58Prefix); - - ``` - -- **Storage queries**: Use the syntax `client.query..` to query on-chain storage. - - ```typescript - const balance = await client.query.system.account('INSERT_ADDRESS'); - console.log('Balance:', balance.data.free); - - ``` - -- **Subscribe to storage changes**: - - ```typescript - const unsub = await client.query.system.number((blockNumber) => { - console.log(`Current block number: ${blockNumber}`); - }); - - ``` - -- **Call Runtime APIs**: Use the syntax `client.call..` to execute Runtime APIs. - - ```typescript - const metadata = await client.call.metadata.metadataAtVersion(15); - console.log('Metadata V15', metadata); - - ``` - -- **Watch on-chain events**: Use the syntax `client.events..` to access pallet events. - - ```typescript - const unsub = await client.events.system.NewAccount.watch((events) => { - console.log('New Account Created', events); - }); - - ``` - -### Sign and Send Transactions - -Sign the transaction using `IKeyringPair` from Keyring ([`@polkadot/keyring`](https://polkadot.js.org/docs/keyring/start/sign-verify/){target=\_blank}) and send the transaction. - -```typescript -import { cryptoWaitReady } from '@polkadot/util-crypto'; -import { Keyring } from '@polkadot/keyring'; -// Setup keyring -await cryptoWaitReady(); -const keyring = new Keyring({ type: 'sr25519' }); -const alice = keyring.addFromUri('//Alice'); -// Send transaction -const unsub = await client.tx.balances - .transferKeepAlive('INSERT_DEST_ADDRESS', 2_000_000_000_000n) - .signAndSend(alice, async ({ status }) => { - console.log('Transaction status', status.type); - if (status.type === 'BestChainBlockIncluded') { - console.log(`Transaction is included in best block`); - } - if (status.type === 'Finalized') { - console.log( - `Transaction completed at block hash ${status.value.blockHash}` - ); - await unsub(); - } - }); - -``` - -You can also use `Signer` from wallet extensions: - -```typescript -const injected = await window.injectedWeb3['polkadot-js'].enable('My dApp'); -const account = (await injected.accounts.get())[0]; -const signer = injected.signer; -const unsub = await client.tx.balances - .transferKeepAlive('INSERT_DEST_ADDRESS', 2_000_000_000_000n) - .signAndSend(account.address, { signer }, async ({ status }) => { - console.log('Transaction status', status.type); - if (status.type === 'BestChainBlockIncluded') { - console.log(`Transaction is included in best block`); - } - if (status.type === 'Finalized') { - console.log( - `Transaction completed at block hash ${status.value.blockHash}` - ); - await unsub(); - } - }); - -``` - -## Where to Go Next - -For more detailed information about Dedot, check the [official documentation](https://dedot.dev/){target=\_blank}. diff --git a/.ai/pages/reference-tools-light-clients.md b/.ai/pages/reference-tools-light-clients.md deleted file mode 100644 index 9d14cdac5..000000000 --- a/.ai/pages/reference-tools-light-clients.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: Light Clients -description: Light clients enable secure and efficient blockchain interaction without running a full node. Learn everything you need to know about light clients on Polkadot. -categories: Parachains, Tooling -url: https://docs.polkadot.com/reference/tools/light-clients/ ---- - -# Light Clients - -## Introduction - -Light clients enable secure and efficient blockchain interaction without running a full node. They provide a trust-minimized alternative to JSON-RPC by verifying data through cryptographic proofs rather than blindly trusting remote nodes. - -This guide covers: - -- What light clients are and how they work. -- Their advantages compared to full nodes and JSON-RPC. -- Available implementations in the Polkadot ecosystem. -- How to use light clients in your applications. - -Light clients are particularly valuable for resource-constrained environments and applications requiring secure, decentralized blockchain access without the overhead of maintaining full nodes. - -!!!note "Light node or light client?" - The terms _light node_ and _light client_ are interchangeable. Both refer to a blockchain client that syncs without downloading the entire blockchain state. All nodes in a blockchain network are fundamentally clients, engaging in peer-to-peer communication. - -## Light Clients Workflow - -Unlike JSON-RPC interfaces, where an application must maintain a list of providers or rely on a single node, light clients are not limited to or dependent on a single node. They use cryptographic proofs to verify the blockchain's state, ensuring it is up-to-date and accurate. By verifying only block headers, light clients avoid syncing the entire state, making them ideal for resource-constrained environments. - -```mermaid -flowchart LR -DAPP([dApp])-- Query Account Info -->LC([Light Client]) -LC -- Request --> FN(((Full Node))) -LC -- Response --> DAPP -FN -- Response (validated via Merkle proof) --> LC -``` - -In the diagram above, the decentralized application queries on-chain account information through the light client. The light client runs as part of the application and requires minimal memory and computational resources. It uses Merkle proofs to verify the state retrieved from a full node in a trust-minimized manner. Polkadot-compatible light clients utilize [warp syncing](https://spec.polkadot.network/sect-lightclient#sect-sync-warp-lightclient){target=\_blank}, which downloads only block headers. - -Light clients can quickly verify the blockchain's state, including [GRANDPA finality](/polkadot-protocol/glossary#grandpa){target=\_blank} justifications. - -!!!note "What does it mean to be trust-minimized?" - _Trust-minimized_ means that the light client does not need to fully trust the full node from which it retrieves the state. This is achieved through the use of Merkle proofs, which allow the light client to verify the correctness of the state by checking the Merkle tree root. - -## JSON-RPC and Light Client Comparison - -Another common method of communication between a user interface (UI) and a node is through the JSON-RPC protocol. Generally, the UI retrieves information from the node, fetches network or [pallet](/polkadot-protocol/glossary#pallet){target=\_blank} data, and interacts with the blockchain. This is typically done in one of two ways: - -- **User-controlled nodes**: The UI connects to a node client installed on the user's machine. - - These nodes are secure, but installation and maintenance can be inconvenient. -- **Publicly accessible nodes**: The UI connects to a third-party-owned publicly accessible node client. - - These nodes are convenient but centralized and less secure. Applications must maintain a list of backup nodes in case the primary node becomes unavailable. - -While light clients still communicate with [full nodes](/polkadot-protocol/glossary#full-node), they offer significant advantages for applications requiring a secure alternative to running a full node: - -| Full Node | Light Client | -| :---------------------------------------------------------------------------------------------: | :------------------------------------------------------------: | -| Fully verifies all blocks of the chain | Verifies only the authenticity of blocks | -| Stores previous block data and the chain's storage in a database | Does not require a database | -| Installation, maintenance, and execution are resource-intensive and require technical expertise | No installation is typically included as part of the application | - -## Using Light Clients - -The [`smoldot`](https://github.com/smol-dot/smoldot){target=\_blank} client is the cornerstone of light client implementation for Polkadot SDK-based chains. It provides the primitives needed to build light clients and is also integrated into libraries such as [PAPI](#papi-light-client-support). - -### PAPI Light Client Support - -The [Polkadot API (PAPI)](/develop/toolkit/api-libraries/papi){target=\_blank} library natively supports light client configurations powered by [`smoldot`](https://github.com/smol-dot/smoldot){target=\_blank}. This allows developers to connect to multiple chains simultaneously using a light client. - -### Substrate Connect - Browser Extension - -The [Substrate Connect browser extension](https://www.npmjs.com/package/@substrate/connect-extension-protocol){target=\_blank} enables end-users to interact with applications connected to multiple blockchains or to connect their own blockchains to supported applications. - -Establishing a sufficient number of peers can be challenging due to browser limitations on WebSocket connections from HTTPS pages, as many nodes require TLS. The Substrate Connect browser extension addresses this limitation by keeping chains synced in the background, enabling faster application performance. - -Substrate Connect automatically detects whether the user has the extension installed. If not, an in-page Wasm light client is created for them. - -## Resources - -- [What is a light client and why you should care?](https://medium.com/paritytech/what-is-a-light-client-and-why-you-should-care-75f813ae2670){target=\_blank} -- [Introducing Substrate Connect: Browser-Based Light Clients for Connecting to Substrate Chains](https://www.parity.io/blog/introducing-substrate-connect){target=\_blank} -- [Substrate Connect GitHub Repository](https://github.com/paritytech/substrate-connect/tree/master/projects/extension){target=\_blank} -- [Light Clients - Polkadot Specification](https://spec.polkadot.network/sect-lightclient){target=\_blank} diff --git a/.ai/pages/reference-tools-moonwall.md b/.ai/pages/reference-tools-moonwall.md deleted file mode 100644 index 03bce9823..000000000 --- a/.ai/pages/reference-tools-moonwall.md +++ /dev/null @@ -1,288 +0,0 @@ ---- -title: E2E Testing with Moonwall -description: Enhance blockchain end-to-end testing with Moonwall's standardized environment setup, comprehensive configuration management, and simple network interactions. -categories: Parachains, Tooling -url: https://docs.polkadot.com/reference/tools/moonwall/ ---- - -# E2E Testing with Moonwall - -## Introduction - -Moonwall is an end-to-end testing framework designed explicitly for Polkadot SDK-based blockchain networks. It addresses one of the most significant challenges in blockchain development: managing complex test environments and network configurations. - -Moonwall consolidates this complexity by providing the following: - -- A centralized configuration management system that explicitly defines all network parameters. -- A standardized approach to environment setup across different Substrate-based chains. -- Built-in utilities for common testing scenarios and network interactions. - -Developers can focus on writing meaningful tests rather than managing infrastructure complexities or searching through documentation for configuration options. - -## Prerequisites - -Before you begin, ensure you have the following installed: - -- [Node.js](https://nodejs.org/en/){target=\_blank} (version 20.10 or higher). -- A package manager such as [npm](https://www.npmjs.com/){target=\_blank}, [yarn](https://yarnpkg.com/){target=\_blank}, or [pnpm](https://pnpm.io/){target=\_blank}. - -## Install Moonwall - -Moonwall can be installed globally for system-wide access or locally within specific projects. This section covers both installation methods. - -!!! tip - This documentation corresponds to Moonwall version `5.15.0`. To avoid compatibility issues with the documented features, ensure you're using the matching version. - -### Global Installation - -Global installation provides system-wide access to the Moonwall CLI, making it ideal for developers working across multiple blockchain projects. Install it by running one of the following commands: - -=== "npm" - - ```bash - npm install -g @moonwall/cli@5.15.0 - ``` - -=== "pnpm" - - ```bash - pnpm -g install @moonwall/cli@5.15.0 - ``` - -=== "yarn" - - ```bash - yarn global add @moonwall/cli@5.15.0 - ``` - -Now, you can run the `moonwall` command from your terminal. - -### Local Installation - -Local installation is recommended for better dependency management and version control within a specific project. First, initialize your project: - -```bash -mkdir my-moonwall-project -cd my-moonwall-project -npm init -y -``` - -Then, install it as a local dependency: - -=== "npm" - - ```bash - npm install @moonwall/cli@5.15.0 - ``` - -=== "pnpm" - - ```bash - pnpm install @moonwall/cli@5.15.0 - ``` - -=== "yarn" - - ```bash - yarn add @moonwall/cli@5.15.0 - ``` - -## Initialize Moonwall - -The `moonwall init` command launches an interactive wizard to create your configuration file: - -```bash -moonwall init -``` - -During setup, you will see prompts for the following parameters: - -- **`label`**: Identifies your test configuration. -- **`global timeout`**: Maximum time (ms) for test execution. -- **`environment name`**: Name for your testing environment. -- **`network foundation`**: Type of blockchain environment to use. -- **`tests directory`**: Location of your test files. - -Select `Enter` to accept defaults or input custom values. You should see something like this: - -
- moonwall init - ✔ Provide a label for the config file moonwall_config - ✔ Provide a global timeout value 30000 - ✔ Provide a name for this environment default_env - ✔ What type of network foundation is this? dev - ✔ Provide the path for where tests for this environment are kept tests/ - ? Would you like to generate this config? (no to restart from beginning) (Y/n) -
- -The wizard generates a `moonwall.config` file: - -```json -{ - "label": "moonwall_config", - "defaultTestTimeout": 30000, - "environments": [ - { - "name": "default_env", - "testFileDir": ["tests/"], - "foundation": { - "type": "dev" - } - } - ] -} - -``` - -The default configuration requires specific details about your blockchain node and test requirements: - -- The `foundation` object defines how your test blockchain node will be launched and managed. The dev foundation, which runs a local node binary, is used for local development. - - For more information about available options, check the [Foundations](https://moonsong-labs.github.io/moonwall/guide/intro/foundations.html){target=\_blank} section. - -- The `connections` array specifies how your tests will interact with the blockchain node. This typically includes provider configuration and endpoint details. - - A provider is a tool that allows you or your application to connect to a blockchain network and simplifies the low-level details of the process. A provider handles submitting transactions, reading state, and more. For more information on available providers, check the [Providers supported](https://moonsong-labs.github.io/moonwall/guide/intro/providers.html#providers-supported){target=\_blank} page in the Moonwall documentation. - -Here's a complete configuration example for testing a local node using Polkadot.js as a provider: - -```json -{ - "label": "moonwall_config", - "defaultTestTimeout": 30000, - "environments": [ - { - "name": "default_env", - "testFileDir": ["tests/"], - "foundation": { - "launchSpec": [ - { - "binPath": "./node-template", - "newRpcBehaviour": true, - "ports": { "rpcPort": 9944 } - } - ], - "type": "dev" - }, - "connections": [ - { - "name": "myconnection", - "type": "polkadotJs", - "endpoints": ["ws://127.0.0.1:9944"] - } - ] - } - ] -} - -``` - -## Writing Tests - -Moonwall uses the [`describeSuite`](https://github.com/Moonsong-Labs/moonwall/blob/7568048c52e9f7844f38fb4796ae9e1b9205fdaa/packages/cli/src/lib/runnerContext.ts#L65){target=\_blank} function to define test suites, like using [Mocha](https://mochajs.org/){target=\_blank}. Each test suite requires the following: - -- **`id`**: Unique identifier for the suite. -- **`title`**: Descriptive name for the suite. -- **`foundationMethods`**: Specifies the testing environment (e.g., `dev` for local node testing). -- **`testCases`**: A callback function that houses the individual test cases of this suite. - -The following example shows how to test a balance transfer between two accounts: - -```ts -import '@polkadot/api-augment'; -import { describeSuite, expect } from '@moonwall/cli'; -import { Keyring } from '@polkadot/api'; - -describeSuite({ - id: 'D1', - title: 'Demo suite', - foundationMethods: 'dev', - testCases: ({ it, context, log }) => { - it({ - id: 'T1', - title: 'Test Case', - test: async () => { - // Set up polkadot.js API and testing accounts - let api = context.polkadotJs(); - let alice = new Keyring({ type: 'sr25519' }).addFromUri('//Alice'); - let charlie = new Keyring({ type: 'sr25519' }).addFromUri('//Charlie'); - - // Query Charlie's account balance before transfer - const balanceBefore = (await api.query.system.account(charlie.address)) - .data.free; - - // Before transfer, Charlie's account balance should be 0 - expect(balanceBefore.toString()).toEqual('0'); - log('Balance before: ' + balanceBefore.toString()); - - // Transfer from Alice to Charlie - const amount = 1000000000000000; - await api.tx.balances - .transferAllowDeath(charlie.address, amount) - .signAndSend(alice); - - // Wait for the transaction to be included in a block. - // This is necessary because the balance is not updated immediately. - // Block time is 6 seconds. - await new Promise((resolve) => setTimeout(resolve, 6000)); - - // Query Charlie's account balance after transfer - const balanceAfter = (await api.query.system.account(charlie.address)) - .data.free; - - // After transfer, Charlie's account balance should be 1000000000000000 - expect(balanceAfter.toString()).toEqual(amount.toString()); - log('Balance after: ' + balanceAfter.toString()); - }, - }); - }, -}); - -``` - -This test demonstrates several key concepts: - -- Initializing the Polkadot.js API through Moonwall's context and setting up test accounts. -- Querying on-chain state. -- Executing transactions. -- Waiting for block inclusion. -- Verifying results using assertions. - -## Running the Tests - -Execute your tests using the `test` Moonwall CLI command. For the default environment setup run: - -```bash -moonwall test default_env -c moonwall.config -``` - -The test runner will output detailed results showing: - -- Test suite execution status. -- Individual test case results. -- Execution time. -- Detailed logs and error messages (if any). - -Example output: -
- moonwall test default_env -c moonwall.config - stdout | tests/test1.ts > 🗃️ D1 Demo suite > 📁 D1T1 Test Case - 2025-01-21T19:27:55.624Z test:default_env Balance before: 0 - - stdout | tests/test1.ts > 🗃️ D1 Demo suite > 📁 D1T1 Test Case - 2025-01-21T19:28:01.637Z test:default_env Balance after: 1000000000000000 - - ✓ default_env tests/test1.ts (1 test) 6443ms - ✓ 🗃️ D1 Demo suite > 📁 D1T1 Test Case 6028ms - - Test Files 1 passed (1) - Tests 1 passed (1) - Start at 16:27:53 - Duration 7.95s (transform 72ms, setup 0ms, collect 1.31s, tests 6.44s, environment 0ms, prepare 46ms) - - ✅ All tests passed -
- -## Where to Go Next - -For a comprehensive guide to Moonwall's full capabilities, available configurations, and advanced usage, see the official [Moonwall](https://moonsong-labs.github.io/moonwall/){target=\_blank} documentation. diff --git a/.ai/pages/reference-tools-omninode.md b/.ai/pages/reference-tools-omninode.md deleted file mode 100644 index 40d0db6e5..000000000 --- a/.ai/pages/reference-tools-omninode.md +++ /dev/null @@ -1,187 +0,0 @@ ---- -title: Polkadot Omni Node -description: Run parachain nodes easily with the polkadot-omni-node, a white-labeled binary that can run parachain nodes using a single pre-built solution. -categories: Parachains, Tooling -url: https://docs.polkadot.com/reference/tools/omninode/ ---- - -# Polkadot Omni Node - -## Introduction - -The [`polkadot-omni-node`](https://crates.io/crates/polkadot-omni-node/0.7.0){target=\_blank} crate is a versatile, pre-built binary designed to simplify running parachains in the Polkadot ecosystem. Unlike traditional node binaries that are tightly coupled to specific runtime code, the `polkadot-omni-node` operates using an external [chain specification](/polkadot-protocol/glossary#chain-specification){target=\_blank} file, allowing it to adapt dynamically to different parachains. - -This approach enables it to act as a white-labeled node binary, capable of running most parachains that do not require custom node-level logic or extensions. Developers can leverage this flexibility to test, deploy, or operate parachain nodes without maintaining a dedicated codebase for each network. - -This guide provides step-by-step instructions for installing the `polkadot-omni-node`, obtaining a chain specification, and spinning up a parachain node. - -## Prerequisites - -Before getting started, ensure you have the following prerequisites: - -- **[Rust](https://rust-lang.org/tools/install/){target=\_blank}**: Required to build and install the `polkadot-omni-node` binary. - -Ensure Rust's `cargo` command is available in your terminal by running: - -```bash -cargo --version -``` - -## Install Polkadot Omni Node - -To install `polkadot-omni-node` globally using `cargo`, run: - -```bash -cargo install --locked polkadot-omni-node@0.7.0 -``` - -This command downloads and installs version 0.7.0 of the binary, making it available system-wide. - -To confirm the installation, run: - -```bash -polkadot-omni-node --version -``` - -You should see the installed version number printed to the terminal, confirming a successful installation. - -## Obtain Chain Specifications - -The `polkadot-omni-node` binary uses a chain specification file to configure and launch a parachain node. This file defines the parachain's genesis state and network settings. - -The most common source for official chain specifications is the [`paritytech/chainspecs`](https://github.com/paritytech/chainspecs){target=\_blank} repository. These specifications are also browsable in a user-friendly format via the [Chainspec Collection](https://paritytech.github.io/chainspecs/){target=\_blank} website. - -To obtain a chain specification: - -1. Visit the [Chainspec Collection](https://paritytech.github.io/chainspecs/){target=\_blank} website. -2. Find the parachain you want to run. -3. Click the chain spec to open it. -4. Copy the JSON content and save it locally as a `.json` file, e.g., `chain_spec.json`. - -## Run a Parachain Full Node - -Once you've installed `polkadot-omni-node` and saved the appropriate chain specification file, you can start a full node for your chosen parachain. - -To see all available flags and configuration options, run: - -```bash -polkadot-omni-node --help -``` - -To launch the node, run the following command, replacing `./INSERT_PARACHAIN_CHAIN_SPEC.json` with the actual path to your saved chain spec file. - -This command will: - -- Load the chain specification. -- Initialize the node using the provided network configuration. -- Begin syncing with the parachain network. - -```bash -polkadot-omni-node --chain ./INSERT_PARACHAIN_CHAIN_SPEC.json --sync warp -``` - -- The `--chain` flag tells the `polkadot-omni-node` which parachain to run by pointing to its chain specification file. -- The `--sync warp` flag enables warp sync, allowing the node to quickly catch up to the latest finalized state. Historical blocks are fetched in the background as the node continues operating. - -Once started, the node will begin connecting to peers and syncing with the network. You’ll see logs in your terminal reflecting its progress. - -## Interact with the Node - -By default, `polkadot-omni-node` exposes a WebSocket endpoint at `ws://localhost:9944`, which you can use to interact with the running node. You can connect using: - -- **[Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\_blank}**: A web-based interface for exploring and interacting with Polkadot SDK-based chains. -- Custom scripts using compatible [libraries](/develop/toolkit/api-libraries/){target=\_blank}. - -Once connected, you can review blocks, call extrinsics, inspect storage, and interact with the runtime. - -## Parachain Compatibility - -The `polkadot-omni-node` is designed to work with most parachains out of the box; however, your parachain's runtime must meet specific requirements and follow certain conventions to be compatible. This section outlines what your runtime needs to implement and configure to work seamlessly with the `polkadot-omni-node`: - -- Your runtime must implement the required runtime APIs (see below). -- Your runtime must include and configure the required pallets. - -The [`parachain-template`](https://github.com/paritytech/polkadot-sdk-parachain-template/tree/v0.0.4){target=_blank} provides a complete reference implementation that is fully compatible with the `polkadot-omni-node`. You can use it as a starting point or reference for ensuring your runtime meets all compatibility requirements. - -### Required Runtime APIs - -Your parachain runtime must implement the following runtime APIs for the `polkadot-omni-node` to function properly: - -- **GetParachainInfo Runtime API**: The omni-node requires the [`GetParachainInfo`](https://paritytech.github.io/polkadot-sdk/master/cumulus_primitives_core/trait.GetParachainInfo.html){target=\_blank} runtime API to identify and configure the parachain correctly. This API provides the parachain ID to the node. - - ```rust title="runtime/src/apis.rs" - impl cumulus_primitives_core::GetParachainInfo for Runtime { - fn parachain_id() -> cumulus_primitives_core::ParaId { - // Return your parachain ID - ParachainInfo::parachain_id() - } - } - ``` - -- **Aura Runtime API**: For consensus, the `polkadot-omni-node` expects the [Aura runtime API](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/runtime/apis/trait.AuraApi.html){target=\_blank} to be implemented. - - ```rust title="runtime/src/apis.rs" - impl sp_consensus_aura::AuraApi for Runtime { - fn slot_duration() -> sp_consensus_aura::SlotDuration { - sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION) - } - - fn authorities() -> Vec { - Aura::authorities().into_inner() - } - } - ``` - -### Required Pallets - -Your runtime must include and properly configure the following pallets: - -- **System Pallet**: The System pallet ([`frame-system`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/prelude/frame_system/index.html){target=\_blank}) is fundamental and must be configured with appropriate types. - - ```rust title="runtime/src/lib.rs" - #[frame_support::runtime] - impl frame_system::Config for Runtime { - type Block = Block; - type BlockNumber = BlockNumber; - // ... other configurations - } - - // Must be named "System" for omni-node compatibility - pub type System = frame_system::Pallet; - ``` - -- **ParachainSystem Pallet**: This pallet ([`cumulus-pallet-parachain-system`](https://paritytech.github.io/polkadot-sdk/master/cumulus_pallet_parachain_system/index.html){target=\_blank}) enables parachain functionality and handles low-level details of being a parachain. - - ```rust title="runtime/src/lib.rs" - impl cumulus_pallet_parachain_system::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type OnSystemEvent = (); - // ... other configurations - } - - // Must be named "ParachainSystem" for omni-node compatibility - pub type ParachainSystem = cumulus_pallet_parachain_system::Pallet; - ``` - -- **Aura Pallet**: For block authoring consensus ([`pallet-aura`](https://paritytech.github.io/polkadot-sdk/master/pallet_aura/index.html){target=\_blank}). - - ```rust title="runtime/src/lib.rs" - impl pallet_aura::Config for Runtime { - type AuthorityId = AuraId; - type DisabledValidators = (); - type MaxAuthorities = MaxAuthorities; - type AllowMultipleBlocksPerSlot = ConstBool; - } - - pub type Aura = pallet_aura::Pallet; - ``` - -- **ParachainInfo Pallet**: Provides parachain metadata ([`parachain-info`](https://paritytech.github.io/polkadot-sdk/master/staging_parachain_info/index.html){target=\_blank}). - - ```rust title="runtime/src/lib.rs" - impl parachain_info::Config for Runtime {} - - pub type ParachainInfo = parachain_info::Pallet; - ``` - -If you're migrating an existing parachain to use the `polkadot-omni-node`, you may need to perform runtime upgrades to add the required runtime APIs and pallets. Follow the standard parachain [runtime upgrade](/parachains/runtime-maintenance/runtime-upgrades/){target=\_blank} procedures to implement these changes on your live network. diff --git a/.ai/pages/reference-tools-papi.md b/.ai/pages/reference-tools-papi.md deleted file mode 100644 index dce9d5063..000000000 --- a/.ai/pages/reference-tools-papi.md +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: Polkadot-API -description: Polkadot-API (PAPI) is a modular, composable library set designed for efficient interaction with Polkadot chains, prioritizing a "light-client first" approach. -categories: Tooling, Dapps -url: https://docs.polkadot.com/reference/tools/papi/ ---- - -# Polkadot-API - -## Introduction - -[Polkadot-API](https://github.com/polkadot-api/polkadot-api){target=\_blank} (PAPI) is a set of libraries built to be modular, composable, and grounded in a “light-client first” approach. Its primary aim is to equip dApp developers with an extensive toolkit for building fully decentralized applications. - -PAPI is optimized for light-client functionality, using the new JSON-RPC spec to support decentralized interactions fully. It provides strong TypeScript support with types and documentation generated directly from on-chain metadata, and it offers seamless access to storage reads, constants, transactions, events, and runtime calls. Developers can connect to multiple chains simultaneously and prepare for runtime updates through multi-descriptor generation and compatibility checks. PAPI is lightweight and performant, leveraging native BigInt, dynamic imports, and modular subpaths to avoid bundling unnecessary assets. It supports promise-based and observable-based APIs, integrates easily with Polkadot.js extensions, and offers signing options through browser extensions or private keys. - -## Get Started - -### API Instantiation - -To instantiate the API, you can install the package by using the following command: - -=== "npm" - - ```bash - npm i polkadot-api@1.17.2 - ``` - -=== "pnpm" - - ```bash - pnpm add polkadot-api@1.17.2 - ``` - -=== "yarn" - - ```bash - yarn add polkadot-api@1.17.2 - ``` - -Then, obtain the latest metadata from the target chain and generate the necessary types: - -```bash -# Add the target chain -npx papi add dot -n polkadot -``` - -The `papi add` command initializes the library by generating the corresponding types needed for the chain used. It assigns the chain a custom name and specifies downloading metadata from the Polkadot chain. You can replace `dot` with the name you prefer or with another chain if you want to add a different one. Once the latest metadata is downloaded, generate the required types: - -```bash -# Generate the necessary types -npx papi -``` - -You can now set up a [`PolkadotClient`](https://github.com/polkadot-api/polkadot-api/blob/main/packages/client/src/types.ts#L153){target=\_blank} with your chosen provider to begin interacting with the API. Choose from Smoldot via WebWorker, Node.js, or direct usage, or connect through the WSS provider. The examples below show how to configure each option for your setup. - -=== "Smoldot (WebWorker)" - - ```typescript - // `dot` is the identifier assigned during `npx papi add` - import { dot } from '@polkadot-api/descriptors'; - import { createClient } from 'polkadot-api'; - import { getSmProvider } from 'polkadot-api/sm-provider'; - import { chainSpec } from 'polkadot-api/chains/polkadot'; - import { startFromWorker } from 'polkadot-api/smoldot/from-worker'; - import SmWorker from 'polkadot-api/smoldot/worker?worker'; - - const worker = new SmWorker(); - const smoldot = startFromWorker(worker); - const chain = await smoldot.addChain({ chainSpec }); - - // Establish connection to the Polkadot relay chain - const client = createClient(getSmProvider(chain)); - - // To interact with the chain, obtain the `TypedApi`, which provides - // the necessary types for every API call on this chain - const dotApi = client.getTypedApi(dot); - - ``` - -=== "Smoldot (Node.js)" - - ```typescript - // `dot` is the alias assigned during `npx papi add` - import { dot } from '@polkadot-api/descriptors'; - import { createClient } from 'polkadot-api'; - import { getSmProvider } from 'polkadot-api/sm-provider'; - import { chainSpec } from 'polkadot-api/chains/polkadot'; - import { startFromWorker } from 'polkadot-api/smoldot/from-node-worker'; - import { fileURLToPath } from 'url'; - import { Worker } from 'worker_threads'; - - // Get the path for the worker file in ESM - const workerPath = fileURLToPath( - import.meta.resolve('polkadot-api/smoldot/node-worker'), - ); - - const worker = new Worker(workerPath); - const smoldot = startFromWorker(worker); - const chain = await smoldot.addChain({ chainSpec }); - - // Set up a client to connect to the Polkadot relay chain - const client = createClient(getSmProvider(chain)); - - // To interact with the chain's API, use `TypedApi` for access to - // all the necessary types and calls associated with this chain - const dotApi = client.getTypedApi(dot); - - ``` - -=== "Smoldot" - - ```typescript - // `dot` is the alias assigned when running `npx papi add` - import { dot } from '@polkadot-api/descriptors'; - import { createClient } from 'polkadot-api'; - import { getSmProvider } from 'polkadot-api/sm-provider'; - import { chainSpec } from 'polkadot-api/chains/polkadot'; - import { start } from 'polkadot-api/smoldot'; - - // Initialize Smoldot client - const smoldot = start(); - const chain = await smoldot.addChain({ chainSpec }); - - // Set up a client to connect to the Polkadot relay chain - const client = createClient(getSmProvider(chain)); - - // Access the `TypedApi` to interact with all available chain calls and types - const dotApi = client.getTypedApi(dot); - - ``` - -=== "WSS" - - ```typescript - // `dot` is the identifier assigned when executing `npx papi add` - import { dot } from '@polkadot-api/descriptors'; - import { createClient } from 'polkadot-api'; - // Use this import for Node.js environments - import { getWsProvider } from 'polkadot-api/ws-provider/web'; - import { withPolkadotSdkCompat } from 'polkadot-api/polkadot-sdk-compat'; - - // Establish a connection to the Polkadot relay chain - const client = createClient( - // The Polkadot SDK nodes may have compatibility issues; using this enhancer is recommended. - // Refer to the Requirements page for additional details - withPolkadotSdkCompat(getWsProvider('wss://dot-rpc.stakeworld.io')), - ); - - // To interact with the chain, obtain the `TypedApi`, which provides - // the types for all available calls in that chain - const dotApi = client.getTypedApi(dot); - - ``` - -Now that you have set up the client, you can interact with the chain by reading and sending transactions. - -### Reading Chain Data - -The `TypedApi` provides a streamlined way to read blockchain data through three main interfaces, each designed for specific data access patterns: - -- **Constants**: Access fixed values or configurations on the blockchain using the `constants` interface. - - ```typescript - const version = await typedApi.constants.System.Version(); - ``` - -- **Storage queries**: Retrieve stored values by querying the blockchain’s storage via the `query` interface. - - ```typescript - const asset = await api.query.ForeignAssets.Asset.getValue( - token.location, - { at: 'best' }, - ); - ``` - -- **Runtime APIs**: Interact directly with runtime APIs using the `apis` interface. - - ```typescript - const metadata = await typedApi.apis.Metadata.metadata(); - ``` - -To learn more about the different actions you can perform with the `TypedApi`, refer to the [TypedApi reference](https://papi.how/typed){target=\_blank}. - -### Sending Transactions - -In PAPI, the `TypedApi` provides the `tx` and `txFromCallData` methods to send transactions. - -- The `tx` method allows you to directly send a transaction with the specified parameters by using the `typedApi.tx.Pallet.Call` pattern: - - ```typescript - const tx: Transaction = typedApi.tx.Pallet.Call({arg1, arg2, arg3}); - ``` - - For instance, to execute the `balances.transferKeepAlive` call, you can use the following snippet: - - ```typescript - import { MultiAddress } from '@polkadot-api/descriptors'; - - const tx: Transaction = typedApi.tx.Balances.transfer_keep_alive({ - dest: MultiAddress.Id('INSERT_DESTINATION_ADDRESS'), - value: BigInt(INSERT_VALUE), - }); - - ``` - - Ensure you replace `INSERT_DESTINATION_ADDRESS` and `INSERT_VALUE` with the actual destination address and value, respectively. - -- The `txFromCallData` method allows you to send a transaction using the call data. This option accepts binary call data and constructs the transaction from it. It validates the input upon creation and will throw an error if invalid data is provided. The pattern is as follows: - - ```typescript - const callData = Binary.fromHex('0x...'); - const tx: Transaction = typedApi.txFromCallData(callData); - ``` - - For instance, to execute a transaction using the call data, you can use the following snippet: - - ```typescript - const callData = Binary.fromHex('0x00002470617065726d6f6f6e'); - const tx: Transaction = typedApi.txFromCallData(callData); - ``` - -For more information about sending transactions, refer to the [Transactions](https://papi.how/typed/tx#transactions){target=\_blank} page. - -## Where to Go Next - -For an in-depth guide on how to use PAPI, refer to the official [PAPI](https://papi.how/){target=\_blank} documentation. diff --git a/.ai/pages/reference-tools-paraspell.md b/.ai/pages/reference-tools-paraspell.md deleted file mode 100644 index f285118e8..000000000 --- a/.ai/pages/reference-tools-paraspell.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: ParaSpell XCM SDK -description: A powerful open-source library that simplifies XCM integration, enabling developers to easily build interoperable dApps on Polkadot. -url: https://docs.polkadot.com/reference/tools/paraspell/ ---- - -# ParaSpell XCM SDK - -## Introduction - -[ParaSpell](https://paraspell.github.io/docs/){target=\_blank} is a comprehensive suite of open-source tools designed to simplify cross-chain interactions within the Polkadot ecosystem. At its core, ParaSpell is dedicated to enhancing the functionality of the [XCM (Cross-Consensus Messaging)](/parachains/interoperability/get-started/){target=\_blank} protocol by providing developers with a unified and streamlined experience for building interoperable decentralized applications (dApps). - -The primary goal of ParaSpell is to abstract away the complexities of the XCM protocol. While XCM is a powerful feature of the Polkadot network, its implementation can vary significantly between different parachains. ParaSpell addresses this challenge by providing a standardized set of tools that enable developers to easily integrate cross-chain functionality into their applications, saving valuable time and effort. ParaSpell is a "common good" software, meaning it is free, open-source, and dedicated to the growth of the Polkadot ecosystem. - -The ParaSpell suite includes: - -- **[XCM SDK](https://paraspell.xyz/#xcm-sdk){target=\_blank}**: Provides a unified layer to incorporate XCM into decentralized applications, simplifying complex cross-chain interactions. -- **[XCM API](https://paraspell.xyz/#xcm-api){target=\_blank}**: Offers an efficient, package-free approach to integrating XCM functionality while offloading heavy computing tasks, minimizing costs and improving application performance. -- **[XCM Router](https://paraspell.xyz/#xcm-router){target=\_blank}**: Enables cross-chain asset swaps in a single command, allowing developers to send one asset type (such as DOT on Polkadot) and receive a different asset on another chain (like ASTR on Astar). -- **[XCM Analyser](https://paraspell.xyz/#xcm-analyser){target=\_blank}**: Decodes and translates complex XCM multilocation data into readable information, supporting easier troubleshooting and debugging. -- **[XCM Visualizator](https://paraspell.xyz/#xcm-visualizator){target=\_blank}**: A tool designed to give developers a clear, interactive view of XCM activity across the Polkadot ecosystem, providing insights into cross-chain communication flow. -- **[XCM Playground](https://paraspell.xyz/#try-it){target=\_blank}**: An interactive playground for testing different XCM scenarios. - -### ParaSpell XCM SDK - -The [ParaSpell XCM SDK](https://paraspell.github.io/docs/sdk/getting-started.html){target=\_blank} is a core component of the ParaSpell toolset and a foundational library for developers looking to leverage XCM in their applications. It is the first and only XCM SDK in the ecosystem to support both PolkadotJS and Polkadot API, providing developers with flexibility and choice. - -The SDK simplifies the process of creating and sending XCM messages by providing a user-friendly builder pattern. This allows developers to construct complex XCM calls with just a few lines of code, reducing the likelihood of errors and ensuring that messages are constructed correctly. - -By using the ParaSpell XCM SDK, developers can significantly accelerate their development workflow and build powerful, interoperable dApps that take full advantage of the Polkadot network's cross-chain capabilities. - -## Install ParaSpell - -If you want to use ParaSpell in your project you can add it as a dependency with the following command: - -=== "npm" - - ```bash - npm install --save @paraspell/sdk@11.12.6 - ``` - -=== "pnpm" - - ```bash - pnpm add @paraspell/sdk@11.12.6 - ``` - -=== "yarn" - - ```bash - yarn add @paraspell/sdk@11.12.6 - ``` - - -## Where to Go Next - -Explore more about ParaSpell through these resources: - -
- -- Tutorial __Transfer Assets Between Parachains__ - - --- - - Learn how to transfer assets across chains with ParaSpell. - - [:octicons-arrow-right-24: Get Started](/chain-interactions/send-transactions/interoperability/transfer-assets-parachains/) - -
diff --git a/.ai/pages/reference-tools-polkadart.md b/.ai/pages/reference-tools-polkadart.md deleted file mode 100644 index 7ea7262dd..000000000 --- a/.ai/pages/reference-tools-polkadart.md +++ /dev/null @@ -1,168 +0,0 @@ ---- -title: Polkadart -description: Polkadart is a type-safe, native Dart, SDK for Polkadot and any compatible Polkadot-SDK blockchain network. -categories: Tooling, Dapps -url: https://docs.polkadot.com/reference/tools/polkadart/ ---- - -# Polkadart - -Polkadart is the most comprehensive Dart/Flutter SDK for interacting with Polkadot, Substrate, and other compatible blockchain networks. Designed with a Dart-first approach and type-safe APIs, it provides everything developers need to build powerful decentralized applications. - -This page will outline some of the core components of Polkadart. For more details, refer to the [official documentation](https://polkadart.dev){target=\_blank}. - -## Installation - -Add Polkadart to your `pubspec.yaml`: - -=== "All packages" - - ```bash - dart pub add polkadart polkadart_cli polkadart_keyring polkadart_scale_codec secp256k1_ecdsa sr25519 ss58 substrate_bip39 substrate_metadata - ``` - -=== "Core only" - - ```bash - dart pub add polkadart polkadart_cli polkadart_keyring - ``` - -For type-safe API generation, add the following to your `pubspec.yaml`: - -{% raw %} -```yaml title="pubspec.yaml" -polkadart: - output_dir: lib/generated - chains: - polkadot: wss://rpc.polkadot.io - kusama: wss://kusama-rpc.polkadot.io - custom: wss://your-node.example.com -``` -{% endraw %} - -## Get Started - -### Type Generation - -Polkadart provides a CLI tool to generate type definitions from any Polkadot-SDK compatible blockchain network. This allows you to build type-safe Dart applications without dealing with the low-level details of the blockchain. - -### Run Generator - -```bash -dart run polkadart_cli:generate -v -``` - -### Use Generated Types - -```dart -import 'package:your_app/generated/polkadot/polkadot.dart'; -import 'package:polkadart/polkadart.dart'; -import 'package:ss58/ss58.dart'; - -final provider = Provider.fromUri(Uri.parse('wss://rpc.polkadot.io')); -final polkadot = Polkadot(provider); - -// Account from SS58 address -final account = Address.decode('19t9Q2ay58hMDaeg6eeBhqmHsRnc2jDMV3cYYw9zbc59HLj'); - -// Retrieve Account Balance -final accountInfo = await polkadot.query.system.account(account.pubkey); -print('Balance: ${accountInfo.data.free}') -``` - -### Creating an API Instance - -An API instance is required to interact with the blockchain. Polkadart provides a `Provider` class that allows you to connect to any network. - -```dart -import 'package:demo/generated/polkadot/polkadot.dart'; -import 'package:polkadart/provider.dart'; - -Future main(List arguments) async { - final provider = Provider.fromUri(Uri.parse('wss://rpc.polkadot.io')); - final polkadot = Polkadot(provider); -} -``` - -### Reading Chain Data - -Besides querying the data using the `query` from the generated API, you can also use the State API for querying storage data, metadata, runtime information, and other chain information. - -```dart -final stateApi = StateApi(provider); - -// Get current runtime version -final runtimeVersion = await stateApi.getRuntimeVersion(); -print(runtimeVersion.toJson()); - -// Get metadata -final metadata = await stateApi.getMetadata(); -print('Metadata version: ${metadata.version}'); -``` - -### Subscribe to New Blocks - -You can subscribe to new blocks on the blockchain using the `subscribe` method. - -```dart -final subscription = await provider.subscribe('chain_subscribeNewHeads', []); - -subscription.stream.forEach((response) { - print('New head: ${response.result}'); -}); -``` - -### Send a Transaction - -Perhaps the most common operation done in any blockchain is transferring funds. Here you can see how that can be done using Polkadart: - -```dart -final wallet = await KeyPair.sr25519.fromUri("//Alice"); -print('Alice\' wallet: ${wallet.address}'); - -// Get information necessary to build a proper extrinsic -final runtimeVersion = await polkadot.rpc.state.getRuntimeVersion(); -final currentBlockNumber = (await polkadot.query.system.number()) - 1; -final currentBlockHash = await polkadot.query.system.blockHash(currentBlockNumber); -final genesisHash = await polkadot.query.system.blockHash(0); -final nonce = await polkadot.rpc.system.accountNextIndex(wallet.address); - -// Make the encoded call -final multiAddress = $MultiAddress().id(wallet.publicKey.bytes); -final transferCall = polkadot.tx.balances.transferKeepAlive(dest: multiAddress, value: BigInt.one).encode(); - -// Make the payload -final payload = SigningPayload( - method: transferCall, - specVersion: runtimeVersion.specVersion, - transactionVersion: runtimeVersion.transactionVersion, - genesisHash: encodeHex(genesisHash), - blockHash: encodeHex(currentBlockHash), - blockNumber: currentBlockNumber, - eraPeriod: 64, - nonce: nonce, - tip: 0, -).encode(polkadot.registry); - -// Sign the payload and build the final extrinsic -final signature = wallet.sign(payload); -final extrinsic = ExtrinsicPayload( - signer: wallet.bytes(), - method: transferCall, - signature: signature, - eraPeriod: 64, - blockNumber: currentBlockNumber, - nonce: nonce, - tip: 0, -).encode(polkadot.registry, SignatureType.sr25519); - -// Send the extrinsic to the blockchain -final author = AuthorApi(provider); -await author.submitAndWatchExtrinsic(extrinsic, (data) { - print(data); -}); -``` - -## Where to Go Next - -To dive deeper into Polkadart, refer to the [official Polkadart documentation](https://polkadart.dev/){target=\_blank}, where you can find comprehensive guides for common use cases and advanced usage. diff --git a/.ai/pages/reference-tools-polkadot-js-api.md b/.ai/pages/reference-tools-polkadot-js-api.md deleted file mode 100644 index d04cab65a..000000000 --- a/.ai/pages/reference-tools-polkadot-js-api.md +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: Polkadot.js API -description: Interact with Polkadot SDK-based chains easily using the Polkadot.js API. Query chain data, submit transactions, and more via JavaScript or Typescript. -categories: Tooling, Dapps -url: https://docs.polkadot.com/reference/tools/polkadot-js-api/ ---- - -# Polkadot.js API - -!!! warning "Maintenance Mode Only" - The Polkadot.js API is now in maintenance mode and is no longer actively developed. New projects should use [Dedot](/develop/toolkit/api-libraries/dedot){target=\_blank} (TypeScript-first API) or [Polkadot API](/develop/toolkit/api-libraries/papi){target=\_blank} (modern, type-safe API) as actively maintained alternatives. - -## Introduction - -The [Polkadot.js API](https://github.com/polkadot-js/api){target=\_blank} uses JavaScript/TypeScript to interact with Polkadot SDK-based chains. It allows you to query nodes, read chain state, and submit transactions through a dynamic, auto-generated API interface. - -### Dynamic API Generation - -Unlike traditional static APIs, the Polkadot.js API generates its interfaces automatically when connecting to a node. Here's what happens when you connect: - -1. The API connects to your node. -2. It retrieves the chain's metadata. -3. Based on this metadata, it creates specific endpoints in this format: `api...
`. - -### Available API Categories - -You can access three main categories of chain interactions: - -- **[Runtime constants](https://polkadot.js.org/docs/api/start/api.consts){target=\_blank}** (`api.consts`): - - - Access runtime constants directly. - - Returns values immediately without function calls. - - **Example**: `api.consts.balances.existentialDeposit` - -- **[State queries](https://polkadot.js.org/docs/api/start/api.query/){target=\_blank}** (`api.query`): - - - Read chain state. - - **Example**: `api.query.system.account(accountId)` - -- **[Transactions](https://polkadot.js.org/docs/api/start/api.tx/){target=\_blank}** (`api.tx`): - - Submit extrinsics (transactions). - - **Example**: `api.tx.balances.transfer(accountId, value)` - -The available methods and interfaces will automatically reflect what's possible on your connected chain. - -## Installation - -To add the Polkadot.js API to your project, use the following command to install the version `16.4.7` which supports any Polkadot SDK-based chain: - -=== "npm" - ```bash - npm i @polkadot/api@16.4.7 - ``` - -=== "pnpm" - ```bash - pnpm add @polkadot/api@16.4.7 - ``` - -=== "yarn" - ```bash - yarn add @polkadot/api@16.4.7 - ``` - -For more detailed information about installation, see the [Installation](https://polkadot.js.org/docs/api/start/install/){target=\_blank} section in the official Polkadot.js API documentation. - -## Get Started - -### Creating an API Instance - -To interact with a Polkadot SDK-based chain, you must establish a connection through an API instance. The API provides methods for querying chain state, sending transactions, and subscribing to updates. - -To create an API connection: - -```js -import { ApiPromise, WsProvider } from '@polkadot/api'; - -// Create a WebSocket provider -const wsProvider = new WsProvider('wss://rpc.polkadot.io'); - -// Initialize the API -const api = await ApiPromise.create({ provider: wsProvider }); - -// Verify the connection by getting the chain's genesis hash -console.log('Genesis Hash:', api.genesisHash.toHex()); - -``` - -!!!warning - All `await` operations must be wrapped in an async function or block since the API uses promises for asynchronous operations. - -### Reading Chain Data - -The API provides several ways to read data from the chain. You can access: - -- **Constants**: Values that are fixed in the runtime and don't change without a runtime upgrade. - - ```js - // Get the minimum balance required for a new account - const minBalance = api.consts.balances.existentialDeposit.toNumber(); - - ``` - -- **State**: Current chain state that updates with each block. - - ```js - // Example address - const address = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFabHE'; - - // Get current timestamp - const timestamp = await api.query.timestamp.now(); - - // Get account information - const { nonce, data: balance } = await api.query.system.account(address); - - console.log(` - Timestamp: ${timestamp} - Free Balance: ${balance.free} - Nonce: ${nonce} - `); - - ``` - -### Sending Transactions - -Transactions (also called extrinsics) modify the chain state. Before sending a transaction, you need: - -- A funded account with sufficient balance to pay transaction fees. -- The account's keypair for signing. - -To make a transfer: - -```js -// Assuming you have an `alice` keypair from the Keyring -const recipient = 'INSERT_RECIPIENT_ADDRESS'; -const amount = 'INSERT_VALUE'; // Amount in the smallest unit (e.g., Planck for DOT) - -// Sign and send a transfer -const txHash = await api.tx.balances - .transfer(recipient, amount) - .signAndSend(alice); - -console.log('Transaction Hash:', txHash); - -``` - -The `alice` keypair in the example comes from a `Keyring` object. For more details about managing keypairs, see the [Keyring documentation](https://polkadot.js.org/docs/keyring){target=\_blank}. - -## Where to Go Next - -For more detailed information about the Polkadot.js API, check the [official documentation](https://polkadot.js.org/docs/){target=\_blank}. diff --git a/.ai/pages/reference-tools-py-substrate-interface.md b/.ai/pages/reference-tools-py-substrate-interface.md deleted file mode 100644 index d719afeb0..000000000 --- a/.ai/pages/reference-tools-py-substrate-interface.md +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: Python Substrate Interface -description: Learn how to connect to Polkadot SDK-based nodes, query data, submit transactions, and manage blockchain interactions using the Python Substrate Interface. -categories: Tooling, Dapps -url: https://docs.polkadot.com/reference/tools/py-substrate-interface/ ---- - -# Python Substrate Interface - -## Introduction - -The [Python Substrate Interface](https://github.com/polkascan/py-substrate-interface){target=\_blank} is a powerful library that enables interaction with Polkadot SDK-based chains. It provides essential functionality for: - -- Querying on-chain storage. -- Composing and submitting extrinsics. -- SCALE encoding/decoding. -- Interacting with Substrate runtime metadata. -- Managing blockchain interactions through convenient utility methods. - -## Installation - -Install the library using `pip`: - -```py -pip install substrate-interface -``` - -For more installation details, see the [Installation](https://jamdottech.github.io/py-polkadot-sdk/getting-started/installation/){target=\_blank} section in the official Python Substrate Interface documentation. - -## Get Started - -This guide will walk you through the basic operations with the Python Substrate Interface: connecting to a node, reading chain state, and submitting transactions. - -### Establishing Connection - -The first step is to establish a connection to a Polkadot SDK-based node. You can connect to either a local or remote node: - -```py -from substrateinterface import SubstrateInterface - -# Connect to a node using websocket -substrate = SubstrateInterface( - # For local node: "ws://127.0.0.1:9944" - # For Polkadot: "wss://rpc.polkadot.io" - # For Kusama: "wss://kusama-rpc.polkadot.io" - url="INSERT_WS_URL" -) - -# Verify connection -print(f"Connected to chain: {substrate.chain}") - -``` - -### Reading Chain State - -You can query various on-chain storage items. To retrieve data, you need to specify three key pieces of information: - -- **Pallet name**: Module or pallet that contains the storage item you want to access. -- **Storage item**: Specific storage entry you want to query within the pallet. -- **Required parameters**: Any parameters needed to retrieve the desired data. - -Here's an example of how to check an account's balance and other details: - -```py -# ... - -# Query account balance and info -account_info = substrate.query( - module="System", # The pallet name - storage_function="Account", # The storage item - params=["INSERT_ADDRESS"], # Account address in SS58 format -) - -# Access account details from the result -free_balance = account_info.value["data"]["free"] -reserved = account_info.value["data"]["reserved"] -nonce = account_info.value["nonce"] - -print( - f""" - Account Details: - - Free Balance: {free_balance} - - Reserved: {reserved} - - Nonce: {nonce} - """ -) - -``` - -### Submitting Transactions - -To modify the chain state, you need to submit transactions (extrinsics). Before proceeding, ensure you have: - -- A funded account with sufficient balance to pay transaction fees. -- Access to the account's keypair. - -Here's how to create and submit a balance transfer: - -```py -#... - -# Compose the transfer call -call = substrate.compose_call( - call_module="Balances", # The pallet name - call_function="transfer_keep_alive", # The extrinsic function - call_params={ - 'dest': 'INSERT_ADDRESS', # Recipient's address - 'value': 'INSERT_VALUE' # Amount in smallest unit (e.g., Planck for DOT) - } -) - -# Create a signed extrinsic -extrinsic = substrate.create_signed_extrinsic( - call=call, keypair=keypair # Your keypair for signing -) - -# Submit and wait for inclusion -receipt = substrate.submit_extrinsic( - extrinsic, wait_for_inclusion=True # Wait until the transaction is in a block -) - -if receipt.is_success: - print( - f""" - Transaction successful: - - Extrinsic Hash: {receipt.extrinsic_hash} - - Block Hash: {receipt.block_hash} - """ - ) -else: - print(f"Transaction failed: {receipt.error_message}") - -``` - -The `keypair` object is essential for signing transactions. See the [Keypair](https://jamdottech.github.io/py-polkadot-sdk/reference/keypair/){target=\_blank} documentation for more details. - -## Where to Go Next - -Now that you understand the basics, you can: - -- Explore more complex queries and transactions. -- Learn about batch transactions and utility functions. -- Discover how to work with custom pallets and types. - -For comprehensive reference materials and advanced features, see the [Python Substrate Interface](https://jamdottech.github.io/py-polkadot-sdk/){target=\_blank} documentation. diff --git a/.ai/pages/reference-tools-sidecar.md b/.ai/pages/reference-tools-sidecar.md deleted file mode 100644 index 5ea46ab69..000000000 --- a/.ai/pages/reference-tools-sidecar.md +++ /dev/null @@ -1,152 +0,0 @@ ---- -title: Sidecar REST API -description: Learn about Substrate API Sidecar, a REST service that provides endpoints for interacting with Polkadot SDK-based chains and simplifies blockchain interactions. -categories: Tooling, Dapps -url: https://docs.polkadot.com/reference/tools/sidecar/ ---- - -# Sidecar API - -## Introduction - -The [Sidecar REST API](https://github.com/paritytech/substrate-api-sidecar){target=\_blank} is a service that provides a REST interface for interacting with Polkadot SDK-based blockchains. With this API, developers can easily access a broad range of endpoints for nodes, accounts, transactions, parachains, and more. - -Sidecar functions as a caching layer between your application and a Polkadot SDK-based node, offering standardized REST endpoints that simplify interactions without requiring complex, direct RPC calls. This approach is especially valuable for developers who prefer REST APIs or build applications in languages with limited WebSocket support. - -Some of the key features of the Sidecar API include: - -- **REST API interface**: Provides a familiar REST API interface for interacting with Polkadot SDK-based chains. -- **Standardized endpoints**: Offers consistent endpoint formats across different chain implementations. -- **Caching layer**: Acts as a caching layer to improve performance and reduce direct node requests. -- **Multiple chain support**: Works with any Polkadot SDK-based chain, including Polkadot, Kusama, and custom chains. - -## Prerequisites - -Sidecar API requires Node.js version 18.14 LTS or higher. Verify your Node.js version: - -```bash -node --version -``` - -If you need to install or update Node.js, visit the [official Node.js website](https://nodejs.org/){target=\_blank} to download and install the latest LTS version. - -## Installation - -To install Substrate API Sidecar, use one of the following commands: - -=== "npm" - - ```bash - npm install -g @substrate/api-sidecar - ``` - -=== "pnpm" - - ```bash - pnpm install -g @substrate/api-sidecar - ``` - -=== "yarn" - - ```bash - yarn global add @substrate/api-sidecar - ``` - -You can confirm the installation by running: - -```bash -substrate-api-sidecar --version -``` - -For more information about the Sidecar API installation, see the [installation and usage](https://github.com/paritytech/substrate-api-sidecar?tab=readme-ov-file#npm-package-installation-and-usage){target=\_blank} section of the Sidecar API README. - -## Usage - -To use the Sidecar API, you have two options: - -- **Local node**: Run a node locally, which Sidecar will connect to by default, requiring no additional configuration. To start, run the following: - - ```bash - substrate-api-sidecar - ``` - -- **Remote node**: Connect Sidecar to a remote node by specifying the RPC endpoint for that chain. For example, to gain access to the Polkadot Asset Hub associated endpoints. - - ```bash - SAS_SUBSTRATE_URL=wss://polkadot-asset-hub-rpc.polkadot.io substrate-api-sidecar - ``` - - For more configuration details, see the [Configuration](https://github.com/paritytech/substrate-api-sidecar?tab=readme-ov-file#configuration){target=\_blank} section of the Sidecar API documentation. - -Once the Sidecar API is running, you’ll see output similar to this: - -
- SAS_SUBSTRATE_URL=wss://polkadot-asset-hub-rpc.polkadot.io substrate-api-sidecar -
- SAS: - 📦 LOG: - ✅ LEVEL: "info" - ✅ JSON: false - ✅ FILTER_RPC: false - ✅ STRIP_ANSI: false - ✅ WRITE: false - ✅ WRITE_PATH: "/opt/homebrew/lib/node_modules/@substrate/api-sidecar/build/src/logs" - ✅ WRITE_MAX_FILE_SIZE: 5242880 - ✅ WRITE_MAX_FILES: 5 - 📦 SUBSTRATE: - ✅ URL: "wss://polkadot-asset-hub-rpc.polkadot.io" - ✅ TYPES_BUNDLE: undefined - ✅ TYPES_CHAIN: undefined - ✅ TYPES_SPEC: undefined - ✅ TYPES: undefined - ✅ CACHE_CAPACITY: undefined - 📦 EXPRESS: - ✅ BIND_HOST: "127.0.0.1" - ✅ PORT: 8080 - ✅ KEEP_ALIVE_TIMEOUT: 5000 - 📦 METRICS: - ✅ ENABLED: false - ✅ PROM_HOST: "127.0.0.1" - ✅ PROM_PORT: 9100 - ✅ LOKI_HOST: "127.0.0.1" - ✅ LOKI_PORT: 3100 - ✅ INCLUDE_QUERYPARAMS: false -
- 2024-11-06 08:06:01 info: Version: 19.3.0 - 2024-11-06 08:06:02 warn: API/INIT: RPC methods not decorated: chainHead_v1_body, chainHead_v1_call, chainHead_v1_continue, chainHead_v1_follow, chainHead_v1_header, chainHead_v1_stopOperation, chainHead_v1_storage, chainHead_v1_unfollow, chainHead_v1_unpin, chainSpec_v1_chainName, chainSpec_v1_genesisHash, chainSpec_v1_properties, transactionWatch_v1_submitAndWatch, transactionWatch_v1_unwatch, transaction_v1_broadcast, transaction_v1_stop - 2024-11-06 08:06:02 info: Connected to chain Polkadot Asset Hub on the statemint client at wss://polkadot-asset-hub-rpc.polkadot.io - 2024-11-06 08:06:02 info: Listening on http://127.0.0.1:8080/ - 2024-11-06 08:06:02 info: Check the root endpoint (http://127.0.0.1:8080/) to see the available endpoints for the current node -
-With Sidecar running, you can access the exposed endpoints via a browser, [`Postman`](https://www.postman.com/){target=\_blank}, [`curl`](https://curl.se/){target=\_blank}, or your preferred tool. - -### Endpoints - -Sidecar API provides a set of REST endpoints that allow you to query different aspects of the chain, including blocks, accounts, and transactions. Each endpoint offers specific insights into the chain’s state and activities. - -For example, to retrieve the version of the node, use the `/node/version` endpoint: - -```bash -curl -X 'GET' \ - 'http://127.0.0.1:8080/node/version' \ - -H 'accept: application/json' -``` - -Alternatively, you can access `http://127.0.0.1:8080/node/version` directly in a browser since it’s a `GET` request. - -In response, you’ll see output similar to this (assuming you’re connected to Polkadot Asset Hub): - -
- curl -X 'GET' 'http://127.0.0.1:8080/node/version' -H 'accept: application/json' -
- { - "clientVersion": "1.16.1-835e0767fe8", - "clientImplName": "statemint", - "chain": "Polkadot Asset Hub" - } -
-For a complete list of available endpoints and their documentation, visit the [Sidecar API list endpoints](https://paritytech.github.io/substrate-api-sidecar/dist/){target=\_blank}. You can learn about the endpoints and how to use them in your applications. - -## Where to Go Next - -To dive deeper, refer to the [official Sidecar documentation](https://github.com/paritytech/substrate-api-sidecar?tab=readme-ov-file#substrateapi-sidecar){target=\_blank}. This provides a comprehensive guide to the available configurations and advanced usage. diff --git a/.ai/pages/reference-tools-subxt.md b/.ai/pages/reference-tools-subxt.md deleted file mode 100644 index d0406c923..000000000 --- a/.ai/pages/reference-tools-subxt.md +++ /dev/null @@ -1,210 +0,0 @@ ---- -title: Subxt Rust API -description: Subxt is a Rust library for type-safe interaction with Polkadot SDK blockchains, enabling transactions, state queries, runtime API access, and more. -categories: Tooling, Dapps -url: https://docs.polkadot.com/reference/tools/subxt/ ---- - -# Subxt Rust API - -## Introduction - -Subxt is a Rust library designed to interact with Polkadot SDK-based blockchains. It provides a type-safe interface for submitting transactions, querying on-chain state, and performing other blockchain interactions. By leveraging Rust's strong type system, subxt ensures that your code is validated at compile time, reducing runtime errors and improving reliability. - -## Prerequisites - -Before using subxt, ensure you have the following requirements: - -- Rust and Cargo installed on your system. You can install them using [Rustup](https://rustup.rs/){target=\_blank}. -- A Rust project initialized. If you don't have one, create it with: - ```bash - cargo new my_project && cd my_project - ``` - -## Installation - -To use subxt in your project, you must install the necessary dependencies. Each plays a specific role in enabling interaction with the blockchain: - -1. **Install the subxt CLI**: [`subxt-cli`](https://crates.io/crates/subxt-cli){target=\_blank} is a command-line tool that provides utilities for working with Polkadot SDK metadata. In the context of subxt, it is essential to download chain metadata, which is required to generate type-safe Rust interfaces for interacting with the blockchain. Install it using the following: - - ```bash - cargo install subxt-cli@0.44.0 - ``` - -2. **Add core dependencies**: These dependencies are essential for interacting with the blockchain. - - - **[subxt](https://crates.io/crates/subxt){target=\_blank}**: The main library for communicating with Polkadot SDK nodes. It handles RPC requests, encoding/decoding, and type generation. - - ```bash - cargo add subxt@0.44.0 - ``` - - - **[subxt-signer](https://crates.io/crates/subxt-signer){target=\_blank}**: Provides cryptographic functionality for signing transactions. Without this, you can only read data but cannot submit transactions. - - ```bash - cargo add subxt-signer@0.44.0 - ``` - - - **[tokio](https://crates.io/crates/tokio){target=\_blank}**: An asynchronous runtime for Rust. Since blockchain operations are async, Tokio enables the efficient handling of network requests. The `rt` feature enables Tokio's runtime, including the current-thread single-threaded scheduler, which is necessary for async execution. The `macros` feature provides procedural macros like `#[tokio::main]` to simplify runtime setup. - - ```bash - cargo add tokio@1.44.2 --features rt,macros - ``` - - After adding the dependencies, your `Cargo.toml` should look like this: - - ```toml - [package] - name = "my_project" - version = "0.1.0" - edition = "2021" - - [dependencies] - subxt = "0.41.0" - subxt-signer = "0.41.0" - tokio = { version = "1.44.2", features = ["rt", "macros"] } - - ``` - -## Get Started - -This guide will walk you through the fundamental operations of subxt, from setting up your environment to executing transactions and querying blockchain state. - -### Download Chain Metadata - -Before interacting with a blockchain, you need to retrieve its metadata. This metadata defines storage structures, extrinsics, and other runtime details. Use the `subxt-cli` tool to download the metadata, replacing `INSERT_NODE_URL` with the URL of the node you want to interact with: - -```bash -subxt metadata --url INSERT_NODE_URL > polkadot_metadata.scale -``` - -### Generate Type-Safe Interfaces - -Use the `#[subxt::subxt]` macro to generate a type-safe Rust interface from the downloaded metadata: - -```rust -// Generate an interface that we can use from the node's metadata. -#[subxt::subxt(runtime_metadata_path = "./polkadot_metadata.scale")] -pub mod polkadot {} -``` - -Once subxt interfaces are generated, you can interact with your node in the following ways. You can use the links below to view the related subxt documentation: - -- **[Transactions](https://docs.rs/subxt/latest/subxt/book/usage/transactions/index.html){target=\_blank}**: Builds and submits transactions, monitors their inclusion in blocks, and retrieves associated events. -- **[Storage](https://docs.rs/subxt/latest/subxt/book/usage/storage/index.html){target=\_blank}**: Enables querying of node storage data. -- **[Events](https://docs.rs/subxt/latest/subxt/book/usage/events/index.html){target=\_blank}**: Retrieves events emitted from recent blocks. -- **[Constants](https://docs.rs/subxt/latest/subxt/book/usage/constants/index.html){target=\_blank}**: Accesses constant values stored in nodes that remain unchanged across a specific runtime version. -- **[Blocks](https://docs.rs/subxt/latest/subxt/book/usage/blocks/index.html){target=\_blank}**: Loads recent blocks or subscribes to new/finalized blocks, allowing examination of extrinsics, events, and storage at those blocks. -- **[Runtime APIs](https://docs.rs/subxt/latest/subxt/book/usage/runtime_apis/index.html){target=\_blank}**: Makes calls into pallet runtime APIs to fetch data. -- **[Custom values](https://docs.rs/subxt/latest/subxt/book/usage/custom_values/index.html){target=\_blank}**: Accesses "custom values" contained within metadata. -- **[Raw RPC calls](https://docs.rs/subxt/latest/subxt/book/usage/rpc/index.html){target=\_blank}**: Facilitates raw RPC requests to compatible nodes. - -### Initialize the Subxt Client - -To interact with a blockchain node using subxt, create an asynchronous main function and initialize the client. Replace `INSERT_NODE_URL` with the URL of your target node: - -```rust -use std::str::FromStr; -use subxt::utils::AccountId32; -use subxt::{OnlineClient, PolkadotConfig}; -use subxt_signer::{bip39::Mnemonic,sr25519::Keypair}; - -// Generate an interface that we can use from the node's metadata. -#[subxt::subxt(runtime_metadata_path = "./polkadot_metadata.scale")] -pub mod polkadot {} - -#[tokio::main(flavor = "current_thread")] -async fn main() -> Result<(), Box> { - // Define the node URL. - const NODE_URL: &str = "INSERT_NODE_URL"; - - // Initialize the Subxt client to interact with the blockchain. - let api = OnlineClient::::from_url(NODE_URL).await?; - - // Your code here... - - Ok(()) -} -``` - -### Read Chain Data - -subxt provides multiple ways to access on-chain data: - -- **Constants**: Constants are predefined values in the runtime that remain unchanged unless modified by a runtime upgrade. - - For example, to retrieve the existential deposit, use: - - ```rust - // A query to obtain some constant. - let constant_query = polkadot::constants().balances().existential_deposit(); - - // Obtain the value. - let value = api.constants().at(&constant_query)?; - - println!("Existential deposit: {:?}", value); - ``` - -- **State**: State refers to the current chain data, which updates with each block. - - To fetch account information, replace `INSERT_ADDRESS` with the address you want to fetch data from and use: - - ```rust - // Define the target account address. - const ADDRESS: &str = "INSERT_ADDRESS"; - let account = AccountId32::from_str(ADDRESS).unwrap(); - - // Build a storage query to access account information. - let storage_query = polkadot::storage().system().account(&account.into()); - - // Fetch the latest state for the account. - let result = api - .storage() - .at_latest() - .await? - .fetch(&storage_query) - .await? - .unwrap(); - - println!("Account info: {:?}", result); - ``` - -### Submit Transactions - -To submit a transaction, you must construct an extrinsic, sign it with your private key, and send it to the blockchain. Replace `INSERT_DEST_ADDRESS` with the recipient's address, `INSERT_AMOUNT` with the amount to transfer, and `INSERT_SECRET_PHRASE` with the sender's mnemonic phrase: - -```rust - // Define the recipient address and transfer amount. - const DEST_ADDRESS: &str = "INSERT_DEST_ADDRESS"; - const AMOUNT: u128 = INSERT_AMOUNT; - - // Convert the recipient address into an `AccountId32`. - let dest = AccountId32::from_str(DEST_ADDRESS).unwrap(); - - // Build the balance transfer extrinsic. - let balance_transfer_tx = polkadot::tx() - .balances() - .transfer_allow_death(dest.into(), AMOUNT); - - // Load the sender's keypair from a mnemonic phrase. - const SECRET_PHRASE: &str = "INSERT_SECRET_PHRASE"; - let mnemonic = Mnemonic::parse(SECRET_PHRASE).unwrap(); - let sender_keypair = Keypair::from_phrase(&mnemonic, None).unwrap(); - - // Sign and submit the extrinsic, then wait for it to be finalized. - let events = api - .tx() - .sign_and_submit_then_watch_default(&balance_transfer_tx, &sender_keypair) - .await? - .wait_for_finalized_success() - .await?; - - // Check for a successful transfer event. - if let Some(event) = events.find_first::()? { - println!("Balance transfer successful: {:?}", event); - } -``` - -## Where to Go Next - -Now that you've covered the basics dive into the official [subxt documentation](https://docs.rs/subxt/latest/subxt/book/index.html){target=\_blank} for comprehensive reference materials and advanced features. diff --git a/.ai/pages/reference-tools-xcm-tools.md b/.ai/pages/reference-tools-xcm-tools.md deleted file mode 100644 index dad6dfb50..000000000 --- a/.ai/pages/reference-tools-xcm-tools.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: XCM Tools -description: Explore essential XCM tools across Polkadot, crafted to enhance cross-chain functionality and integration within the ecosystem. -categories: Basics, Tooling, Dapps -url: https://docs.polkadot.com/reference/tools/xcm-tools/ ---- - -# XCM Tools - -## Introduction - -As described in the [Interoperability](/develop/interoperability){target=\_blank} section, XCM (Cross-Consensus Messaging) is a protocol used in the Polkadot and Kusama ecosystems to enable communication and interaction between chains. It facilitates cross-chain communication, allowing assets, data, and messages to flow seamlessly across the ecosystem. - -As XCM is central to enabling communication between blockchains, developers need robust tools to help interact with, build, and test XCM messages. Several XCM tools simplify working with the protocol by providing libraries, frameworks, and utilities that enhance the development process, ensuring that applications built within the Polkadot ecosystem can efficiently use cross-chain functionalities. - -## Popular XCM Tools - -### Moonsong Labs XCM Tools - -[Moonsong Labs XCM Tools](https://github.com/Moonsong-Labs/xcm-tools){target=\_blank} provides a collection of scripts for managing and testing XCM operations between Polkadot SDK-based runtimes. These tools allow performing tasks like asset registration, channel setup, and XCM initialization. Key features include: - -- **Asset registration**: Registers assets, setting units per second (up-front fees), and configuring error (revert) codes. -- **XCM initializer**: Initializes XCM, sets default XCM versions, and configures revert codes for XCM-related precompiles. -- **HRMP manipulator**: Manages HRMP channel actions, including opening, accepting, or closing channels. -- **XCM-Transactor-Info-Setter**: Configures transactor information, including extra weight and fee settings. -- **Decode XCM**: Decodes XCM messages on the relay chain or parachains to help interpret cross-chain communication. - -To get started, clone the repository and install the required dependencies: - -```bash -git clone https://github.com/Moonsong-Labs/xcm-tools && -cd xcm-tools && -yarn install -``` - -For a full overview of each script, visit the [scripts](https://github.com/Moonsong-Labs/xcm-tools/tree/main/scripts){target=\_blank} directory or refer to the [official documentation](https://github.com/Moonsong-Labs/xcm-tools/blob/main/README.md){target=\_blank} on GitHub. - -### ParaSpell - -[ParaSpell](/reference/tools/paraspell/){target=\_blank} is a collection of open-source XCM tools that streamline cross-chain asset transfers and interactions across the Polkadot and Kusama ecosystems. It provides developers with an intuitive interface to build, test, and deploy interoperable dApps, featuring message composition, decoding, and practical utilities for parachain interactions that simplify debugging and cross-chain communication optimization. - -### Astar XCM Tools - -The [Astar parachain](https://github.com/AstarNetwork/Astar/tree/master){target=\_blank} offers a crate with a set of utilities for interacting with the XCM protocol. The [xcm-tools](https://github.com/AstarNetwork/Astar/tree/master/bin/xcm-tools){target=\_blank} crate provides a straightforward method for users to locate a sovereign account or calculate an XC20 asset ID. Some commands included by the xcm-tools crate allow users to perform the following tasks: - -- **Sovereign accounts**: Obtain the sovereign account address for any parachain, either on the Relay Chain or for sibling parachains, using a simple command. -- **XC20 EVM addresses**: Generate XC20-compatible Ethereum addresses for assets by entering the asset ID, making it easy to integrate assets across Ethereum-compatible environments. -- **Remote accounts**: Retrieve remote account addresses needed for multi-location compatibility, using flexible options to specify account types and parachain IDs. - -To start using these tools, clone the [Astar repository](https://github.com/AstarNetwork/Astar){target=\_blank} and compile the xcm-tools package: - -```bash -git clone https://github.com/AstarNetwork/Astar && -cd Astar && -cargo build --release -p xcm-tools -``` - -After compiling, verify the setup with the following command: - -```bash -./target/release/xcm-tools --help -``` -For more details on using Astar xcm-tools, consult the [official documentation](https://docs.astar.network/docs/learn/interoperability/xcm/integration/tools/){target=\_blank}. - -### Chopsticks - -The Chopsticks library provides XCM functionality for testing XCM messages across networks, enabling you to fork multiple parachains along with a relay chain. For further details, see the [Chopsticks documentation](/tutorials/polkadot-sdk/testing/fork-live-chains/){target=\_blank} about XCM. - -### Moonbeam XCM SDK - -The [Moonbeam XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk){target=\_blank} enables developers to easily transfer assets between chains, either between parachains or between a parachain and the relay chain, within the Polkadot/Kusama ecosystem. With the SDK, you don't need to worry about determining the [Multilocation](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#7-universal-consensus-location-identifiers){target=\_blank} of the origin or destination assets or which extrinsics are used on which networks. - -The SDK consists of two main packages: - -- **[XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/sdk){target=\_blank}**: Core SDK for executing XCM transfers between chains in the Polkadot/Kusama ecosystem. -- **[MRL SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/mrl){target=\_blank}**: Extension of the XCM SDK for transferring liquidity into and across the Polkadot ecosystem from other ecosystems like Ethereum. - -Key features include: - -- **Simplified asset transfers**: Abstracts away complex multilocation determinations and extrinsic selection. -- **Cross-ecosystem support**: Enables transfers between Polkadot/Kusama chains and external ecosystems. -- **Developer-friendly API**: Provides intuitive interfaces for cross-chain functionality. -- **Comprehensive documentation**: Includes usage guides and API references for both packages. - -For detailed usage examples and API documentation, visit the [official Moonbeam XCM SDK documentation](https://moonbeam-foundation.github.io/xcm-sdk/latest/){target=\_blank}. diff --git a/.ai/pages/reference-tools-zombienet.md b/.ai/pages/reference-tools-zombienet.md deleted file mode 100644 index 0b80ea446..000000000 --- a/.ai/pages/reference-tools-zombienet.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -url: https://docs.polkadot.com/reference/tools/zombienet/ ---- - -TODO diff --git a/.ai/pages/reference.md b/.ai/pages/reference.md deleted file mode 100644 index 59bc64741..000000000 --- a/.ai/pages/reference.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: Technical Reference Overview -description: Learn about Polkadot's technical architecture, governance framework, parachain ecosystem, and the tools you need to build and interact with the network. -categories: Basics, Polkadot Protocol, Reference -url: https://docs.polkadot.com/reference/ ---- - -## Introduction - -The Technical Reference section provides comprehensive documentation of Polkadot's architecture, core concepts, and development tooling. Whether you're exploring how Polkadot's relay chain coordinates parachains, understanding governance mechanisms, or building applications on the network, this reference covers the technical foundations you need. - -Polkadot is a multi-chain network that enables diverse, interconnected blockchains to share security and communicate seamlessly. Understanding how these components interact from the [relay chain](/polkadot-protocol/glossary#relay-chain){target=\_blank} that validates [parachains](/polkadot-protocol/glossary#parachain){target=\_blank} to the [governance](/reference/glossary#governance){target=\_blank} mechanisms that evolve the protocol is essential for developers, validators, and network participants. - -This guide organizes technical documentation across five core areas: Polkadot Hub, Parachains, On-Chain Governance, Glossary, and Tools, each providing detailed information on different aspects of the Polkadot ecosystem. - -## Polkadot Hub - -[Polkadot Hub](/reference/polkadot-hub/){target=\_blank} is the entry point to Polkadot for all users and application developers. It provides access to essential Web3 services, including smart contracts, staking, governance, identity management, and cross-ecosystem interoperability—without requiring you to deploy or manage a parachain. - -The Hub encompasses a set of core functionality that enables developers and users to build and interact with applications on Polkadot. Key capabilities include: - -- **Smart contracts**: Deploy Ethereum-compatible smart contracts and build decentralized applications. -- **Assets and tokens**: Create, manage, and transfer fungible tokens and NFTs across the ecosystem. -- **Staking**: Participate in network security and earn rewards by staking DOT. -- **Governance**: Vote on proposals and participate in Polkadot's decentralized decision-making through OpenGov. -- **Identity services**: Register and manage on-chain identities, enabling access to governance roles and network opportunities. -- **Cross-chain interoperability**: Leverage XCM messaging to interact securely with other chains in the Polkadot ecosystem. -- **Collectives and DAOs**: Participate in governance collectives and decentralized autonomous organizations. - -## Parachains - -[Parachains](/reference/parachains/){target=\_blank} are specialized blockchains that connect to the Polkadot relay chain, inheriting its security while maintaining their own application-specific logic. The parachains documentation covers: - -- **Accounts**: Deep dive into account types, storage, and management on parachains. -- **Blocks, transactions and fees**: Understand block production, transaction inclusion, and fee mechanisms. -- **Consensus**: Learn how parachain blocks are validated and finalized through the relay chain's consensus. -- **Chain data**: Explore data structures, storage layouts, and state management. -- **Cryptography**: Study cryptographic primitives used in Polkadot SDK-based chains. -- **Data encoding**: Understand how data is encoded and decoded for blockchain compatibility. -- **Networks**: Learn about networking protocols and peer-to-peer communication. -- **Interoperability**: Discover [Cross-Consensus Messaging (XCM)](/parachains/interoperability/get-started/){target=\_blank}, the standard for cross-chain communication. -- **Randomness**: Understand how randomness is generated and used in Polkadot chains. -- **Node and runtime**: Learn about parachain nodes, runtime environments, and the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\_blank}. - -## On-Chain Governance - -[On-Chain governance](/reference/governance/){target=\_blank} is the decentralized decision-making mechanism for the Polkadot network. It manages the evolution and modification of the network's runtime logic, enabling community oversight and approval for proposed changes. The governance documentation details: - -- **OpenGov framework**: Understand Polkadot's next-generation governance system with enhanced delegation, flexible tracks, and simultaneous referendums. -- **Origins and tracks**: Learn how governance proposals are categorized, prioritized, and executed based on their privilege level and complexity. -- **Voting and delegation**: Explore conviction voting, vote delegation, and how token holders participate in governance. -- **Governance evolution**: See how Polkadot's governance has evolved from Governance V1 to the current OpenGov system. - -## Glossary - -The [Glossary](/reference/glossary/){target=\_blank} provides quick-reference definitions for Polkadot-specific terminology. Essential terms include: - -- Blockchain concepts (blocks, transactions, state) -- Consensus mechanisms (validators, collators, finality) -- Polkadot-specific terms (relay chain, parachain, XCM, FRAME) -- Network components (nodes, runtimes, storage) -- Governance terminology (origins, tracks, referendums) - -## Tools - -The [Tools](/reference/tools/){target=\_blank} section documents essential development and interaction tools for the Polkadot ecosystem: - -- **Light clients**: Lightweight solutions for interacting with the network without running full nodes. -- **JavaScript/TypeScript tools**: Libraries like [Polkadot.js API](/reference/tools/polkadot-js-api/){target=\_blank} and [PAPI](/reference/tools/papi/){target=\_blank} for building applications. -- **Rust tools**: [Polkadart](/reference/tools/polkadart/){target=\_blank} and other Rust-based libraries for SDK development. -- **Python tools**: [py-substrate-interface](/reference/tools/py-substrate-interface/){target=\_blank} for Python developers. -- **Testing and development**: Tools like [Moonwall](/reference/tools/moonwall/){target=\_blank}, [Chopsticks](/reference/tools/chopsticks/){target=\_blank}, and [Omninode](/reference/tools/omninode/){target=\_blank} for smart contract and parachain testing. -- **Indexing and monitoring**: [Sidecar](/reference/tools/sidecar/){target=\_blank} for data indexing and [Dedot](/reference/tools/dedot/){target=\_blank} for substrate interaction. -- **Cross-chain tools**: [ParaSpell](/reference/tools/paraspell/){target=\_blank} for XCM integration and asset transfers. - -## Where to Go Next - -For detailed exploration of specific areas, proceed to any of the main sections: - -
- -- Learn **Polkadot Hub** - - --- - - Understand the relay chain's role in coordinating parachains, providing shared security, and enabling governance. - - [:octicons-arrow-right-24: Reference](/reference/polkadot-hub/) - -- Learn **Parachains** - - --- - - Deep dive into parachain architecture, consensus, data structures, and building application-specific blockchains. - - [:octicons-arrow-right-24: Reference](/reference/parachains/) - -- Learn **On-Chain Governance** - - --- - - Explore Polkadot's decentralized governance framework and how to participate in network decision-making. - - [:octicons-arrow-right-24: Reference](/reference/governance/) - -- Guide **Glossary** - - --- - - Quick reference for Polkadot-specific terminology and concepts used throughout the documentation. - - [:octicons-arrow-right-24: Reference](/reference/glossary/) - -- Guide **Tools** - - --- - - Discover development tools, libraries, and frameworks for building and interacting with Polkadot. - - [:octicons-arrow-right-24: Reference](/reference/tools/) - -
diff --git a/.ai/pages/smart-contracts-cookbook-dapps-zero-to-hero.md b/.ai/pages/smart-contracts-cookbook-dapps-zero-to-hero.md index b0cc72fa0..c97d65455 100644 --- a/.ai/pages/smart-contracts-cookbook-dapps-zero-to-hero.md +++ b/.ai/pages/smart-contracts-cookbook-dapps-zero-to-hero.md @@ -241,7 +241,7 @@ After deployment, you'll need the contract's Application Binary Interface (ABI) Now that you have your contract deployed, you're ready to build the dApp that will interact with it! -## Set Up the dApp Project +## Set Up the DApp Project Navigate to the root of the project, and create a new Next.js project called `dapp`: diff --git a/.ai/pages/smart-contracts-faucet.md b/.ai/pages/smart-contracts-faucet.md index 3cf7691c3..65da79ac1 100644 --- a/.ai/pages/smart-contracts-faucet.md +++ b/.ai/pages/smart-contracts-faucet.md @@ -1,5 +1,5 @@ --- -title: Faucet +title: Get Tokens from the Official Faucet description: Learn how to obtain test tokens from Polkadot faucets for development and testing purposes across different networks. categories: Smart Contracts url: https://docs.polkadot.com/smart-contracts/faucet/ diff --git a/.ai/pages/smart-contracts-for-eth-devs-gas-model.md b/.ai/pages/smart-contracts-for-eth-devs-gas-model.md index cf3071ada..ebe94d4f0 100644 --- a/.ai/pages/smart-contracts-for-eth-devs-gas-model.md +++ b/.ai/pages/smart-contracts-for-eth-devs-gas-model.md @@ -6,7 +6,7 @@ url: https://docs.polkadot.com/smart-contracts/for-eth-devs/gas-model/ # Gas Model -## Overview +## Introduction The Polkadot Hub implements a gas model that bridges Ethereum's familiar gas concept with Polkadot's more sophisticated resource metering system. This page explains how gas works in the Polkadot Hub and what developers need to know when building smart contracts. diff --git a/.ai/pages/smart-contracts-integrations-.indexers.md b/.ai/pages/smart-contracts-integrations-.indexers.md new file mode 100644 index 000000000..8d162612d --- /dev/null +++ b/.ai/pages/smart-contracts-integrations-.indexers.md @@ -0,0 +1,5 @@ +--- +url: https://docs.polkadot.com/smart-contracts/integrations/.indexers/ +--- + +TODO diff --git a/.ai/pages/smart-contracts-integrations-.oracles.md b/.ai/pages/smart-contracts-integrations-.oracles.md new file mode 100644 index 000000000..2bedccd9e --- /dev/null +++ b/.ai/pages/smart-contracts-integrations-.oracles.md @@ -0,0 +1,5 @@ +--- +url: https://docs.polkadot.com/smart-contracts/integrations/.oracles/ +--- + +TODO diff --git a/.ai/pages/smart-contracts-integrations-indexers.md b/.ai/pages/smart-contracts-integrations-indexers.md deleted file mode 100644 index 492eac73a..000000000 --- a/.ai/pages/smart-contracts-integrations-indexers.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -url: https://docs.polkadot.com/smart-contracts/integrations/indexers/ ---- - -TODO diff --git a/.ai/pages/smart-contracts-integrations-oracles.md b/.ai/pages/smart-contracts-integrations-oracles.md deleted file mode 100644 index 942fc9a57..000000000 --- a/.ai/pages/smart-contracts-integrations-oracles.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -url: https://docs.polkadot.com/smart-contracts/integrations/oracles/ ---- - -TODO diff --git a/.ai/site-index.json b/.ai/site-index.json index 6100c0b46..36994d4c2 100644 --- a/.ai/site-index.json +++ b/.ai/site-index.json @@ -1,336 +1,213 @@ [ { - "id": "chain-interactions-accounts-create-account", - "title": "chain-interactions-accounts-create-account", - "slug": "chain-interactions-accounts-create-account", - "categories": [ - "Uncategorized" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-accounts-create-account.md", - "html_url": "https://docs.polkadot.com/chain-interactions/accounts/create-account/", - "preview": "TODO", - "outline": [], - "stats": { - "chars": 5, - "words": 1, - "headings": 0, - "estimated_token_count_total": 0 - }, - "hash": "sha256:56ba36249ea8216ad513b13df3de6c0e490ba214897674d30331f1c7e7edbef3", - "token_estimator": "heuristic-v1" - }, - { - "id": "chain-interactions-accounts-query-accounts", - "title": "chain-interactions-accounts-query-accounts", - "slug": "chain-interactions-accounts-query-accounts", - "categories": [ - "Uncategorized" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-accounts-query-accounts.md", - "html_url": "https://docs.polkadot.com/chain-interactions/accounts/query-accounts/", - "preview": "TODO", - "outline": [], - "stats": { - "chars": 5, - "words": 1, - "headings": 0, - "estimated_token_count_total": 0 - }, - "hash": "sha256:56ba36249ea8216ad513b13df3de6c0e490ba214897674d30331f1c7e7edbef3", - "token_estimator": "heuristic-v1" - }, - { - "id": "chain-interactions-query-data-query-rest", - "title": "chain-interactions-query-data-query-rest", - "slug": "chain-interactions-query-data-query-rest", - "categories": [ - "Uncategorized" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-query-data-query-rest.md", - "html_url": "https://docs.polkadot.com/chain-interactions/query-data/query-rest/", - "preview": "TODO", - "outline": [], - "stats": { - "chars": 5, - "words": 1, - "headings": 0, - "estimated_token_count_total": 0 - }, - "hash": "sha256:56ba36249ea8216ad513b13df3de6c0e490ba214897674d30331f1c7e7edbef3", - "token_estimator": "heuristic-v1" - }, - { - "id": "chain-interactions-query-data-query-sdks", - "title": "chain-interactions-query-data-query-sdks", - "slug": "chain-interactions-query-data-query-sdks", - "categories": [ - "Uncategorized" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-query-data-query-sdks.md", - "html_url": "https://docs.polkadot.com/chain-interactions/query-data/query-sdks/", - "preview": "TODO", - "outline": [], - "stats": { - "chars": 5, - "words": 1, - "headings": 0, - "estimated_token_count_total": 0 - }, - "hash": "sha256:56ba36249ea8216ad513b13df3de6c0e490ba214897674d30331f1c7e7edbef3", - "token_estimator": "heuristic-v1" - }, - { - "id": "chain-interactions-query-data-runtime-api-calls", - "title": "chain-interactions-query-data-runtime-api-calls", - "slug": "chain-interactions-query-data-runtime-api-calls", + "id": "get-support-ai-ready-docs", + "title": "AI Ready Docs", + "slug": "get-support-ai-ready-docs", "categories": [ "Uncategorized" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-query-data-runtime-api-calls.md", - "html_url": "https://docs.polkadot.com/chain-interactions/query-data/runtime-api-calls/", - "preview": "TODO", - "outline": [], - "stats": { - "chars": 5, - "words": 1, - "headings": 0, - "estimated_token_count_total": 0 - }, - "hash": "sha256:56ba36249ea8216ad513b13df3de6c0e490ba214897674d30331f1c7e7edbef3", - "token_estimator": "heuristic-v1" - }, - { - "id": "chain-interactions-send-transactions-calculate-transaction-fees", - "title": "chain-interactions-send-transactions-calculate-transaction-fees", - "slug": "chain-interactions-send-transactions-calculate-transaction-fees", - "categories": [ - "Uncategorized" + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/get-support-ai-ready-docs.md", + "html_url": "https://docs.polkadot.com/get-support/ai-ready-docs/", + "preview": "Polkadot provides files to make documentation content available in a structure optimized for use with large language models (LLMs) and AI tools. These resources help build AI assistants, power code search, or enable custom tooling trained on Polkadot’s documentation.", + "outline": [ + { + "depth": 2, + "title": "How to Use These Files", + "anchor": "how-to-use-these-files" + }, + { + "depth": 2, + "title": "Download LLM Files", + "anchor": "download-llm-files" + } ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-send-transactions-calculate-transaction-fees.md", - "html_url": "https://docs.polkadot.com/chain-interactions/send-transactions/calculate-transaction-fees/", - "preview": "TODO", - "outline": [], "stats": { - "chars": 5, - "words": 1, - "headings": 0, - "estimated_token_count_total": 0 + "chars": 7998, + "words": 825, + "headings": 2, + "estimated_token_count_total": 2232 }, - "hash": "sha256:56ba36249ea8216ad513b13df3de6c0e490ba214897674d30331f1c7e7edbef3", + "hash": "sha256:5a8da69a5cea8bd598ee4d102b9abed5d1a29153802a567e22bb4ee720410b32", "token_estimator": "heuristic-v1" }, { - "id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", - "title": "Replay and Dry Run XCMs", - "slug": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", + "id": "get-support-explore-resources", + "title": "Subscribe to Updates", + "slug": "get-support-explore-resources", "categories": [ "Uncategorized" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-send-transactions-interoperability-debug-and-preview-xcms.md", - "html_url": "https://docs.polkadot.com/chain-interactions/send-transactions/interoperability/debug-and-preview-xcms/", - "preview": "In this tutorial, you'll learn how to replay and dry-run XCMs using [Chopsticks](/parachains/testing/fork-a-parachain/){target=\\_blank}, a powerful tool for forking live Polkadot SDK-based chains in your local environment. These techniques are essential for:", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/get-support-explore-resources.md", + "html_url": "https://docs.polkadot.com/get-support/explore-resources/", + "preview": "Looking for answers beyond the documentation? These platforms are full of useful content and experienced developers sharing insights.", "outline": [ { "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" - }, - { - "depth": 2, - "title": "Set Up Your Project", - "anchor": "set-up-your-project" + "title": "🧠 Stack Exchange", + "anchor": "stack-exchange" }, { "depth": 2, - "title": "Capture the XCM to Replay", - "anchor": "capture-the-xcm-to-replay" + "title": "🧵 Reddit: r/Polkadot", + "anchor": "reddit-rpolkadot" }, { "depth": 2, - "title": "Fork the Relevant Chains", - "anchor": "fork-the-relevant-chains" - }, - { - "depth": 3, - "title": "Set the Block Numbers", - "anchor": "set-the-block-numbers" - }, - { - "depth": 3, - "title": "Enable Logging and Wasm Override", - "anchor": "enable-logging-and-wasm-override" + "title": "💬 Discord (Community Threads Only)", + "anchor": "discord-community-threads-only" }, { "depth": 2, - "title": "Identify and Extract the XCM", - "anchor": "identify-and-extract-the-xcm" + "title": "🎥 YouTube: @PolkadotNetwork", + "anchor": "youtube-polkadotnetwork" }, { "depth": 2, - "title": "Replay the XCM", - "anchor": "replay-the-xcm" - }, - { - "depth": 3, - "title": "Add the Asset Hub Descriptor", - "anchor": "add-the-asset-hub-descriptor" + "title": "Community-Led Platforms and Ecosystem Updates", + "anchor": "community-led-platforms-and-ecosystem-updates" }, { "depth": 3, - "title": "Create a Replay Script", - "anchor": "create-a-replay-script" + "title": "🔷 X (Twitter): Official Accounts", + "anchor": "x-twitter-official-accounts" }, { "depth": 3, - "title": "Execute the Replay Script", - "anchor": "execute-the-replay-script" + "title": "🔁 X (Twitter): Community Accounts", + "anchor": "x-twitter-community-accounts" }, { "depth": 3, - "title": "Expected Output", - "anchor": "expected-output" - }, - { - "depth": 2, - "title": "Dry Run the XCM", - "anchor": "dry-run-the-xcm" + "title": "🗣️ Polkadot Forum", + "anchor": "polkadot-forum" }, { "depth": 3, - "title": "Create a Dry Run Script", - "anchor": "create-a-dry-run-script" + "title": "🧑‍⚖️ Polkassembly: OpenGov", + "anchor": "polkassembly-opengov" }, { "depth": 3, - "title": "Execute the Dry Run Script", - "anchor": "execute-the-dry-run-script" - }, - { - "depth": 2, - "title": "Review and Debug", - "anchor": "review-and-debug" - }, - { - "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" + "title": "📸 Instagram", + "anchor": "instagram" } ], "stats": { - "chars": 18942, - "words": 2362, - "headings": 18, - "estimated_token_count_total": 4830 + "chars": 2426, + "words": 295, + "headings": 10, + "estimated_token_count_total": 579 }, - "hash": "sha256:a6bf7623a535e7a9162c0913b07bd59d43c8535025ad8225fb3e5adc83084c7a", + "hash": "sha256:670221ac20ab1f1b550ba2a1db06cd924c24bd3afc4d8a768b617d8a409243cb", "token_estimator": "heuristic-v1" }, { - "id": "chain-interactions-send-transactions-interoperability-estimate-xcm-fees", - "title": "XCM Fee Estimation", - "slug": "chain-interactions-send-transactions-interoperability-estimate-xcm-fees", + "id": "get-support-get-in-touch", + "title": "Get in Touch", + "slug": "get-support-get-in-touch", "categories": [ "Uncategorized" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-send-transactions-interoperability-estimate-xcm-fees.md", - "html_url": "https://docs.polkadot.com/chain-interactions/send-transactions/interoperability/estimate-xcm-fees/", - "preview": "When sending cross-chain messages, ensure that the transaction will be successful not only in the local chain but also in the destination chain and any intermediate chains.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/get-support-get-in-touch.md", + "html_url": "https://docs.polkadot.com/get-support/get-in-touch/", + "preview": "Use one of the channels below to get live technical support or ask questions.", "outline": [ { "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Fee Mechanism", - "anchor": "fee-mechanism" - }, - { - "depth": 2, - "title": "Environment Setup", - "anchor": "environment-setup" - }, - { - "depth": 2, - "title": "Client and API Setup", - "anchor": "client-and-api-setup" + "title": "Need Help Fast?", + "anchor": "need-help-fast" }, { "depth": 2, - "title": "Create the XCM Message", - "anchor": "create-the-xcm-message" + "title": "📱 Telegram: Polkadot Developer Support", + "anchor": "telegram-polkadot-developer-support" }, { "depth": 2, - "title": "Fee Estimation Function", - "anchor": "fee-estimation-function" + "title": "🔌 Discord: Polkadot Official Server", + "anchor": "discord-polkadot-official-server" }, { "depth": 2, - "title": "Complete Implementation", - "anchor": "complete-implementation" - }, + "title": "🧬 Matrix: Polkadot Developer Support", + "anchor": "matrix-polkadot-developer-support" + } + ], + "stats": { + "chars": 1949, + "words": 258, + "headings": 4, + "estimated_token_count_total": 557 + }, + "hash": "sha256:993e93b05c8fbdfc2f7510c61ac86bc4c2ff0f03e573695b2f260933c8b62f78", + "token_estimator": "heuristic-v1" + }, + { + "id": "get-support", + "title": "Support", + "slug": "get-support", + "categories": [ + "Uncategorized" + ], + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/get-support.md", + "html_url": "https://docs.polkadot.com/get-support/", + "preview": "Use one of the channels below to get live technical support or ask questions.", + "outline": [ { "depth": 2, - "title": "Full Code", - "anchor": "full-code" + "title": "Need More than Just Documentation?", + "anchor": "need-more-than-just-documentation" }, { "depth": 2, - "title": "Running the Script", - "anchor": "running-the-script" + "title": "What You Can Do Here", + "anchor": "what-you-can-do-here" }, { "depth": 2, - "title": "Conclusion", - "anchor": "conclusion" + "title": "Help Us Improve", + "anchor": "help-us-improve" } ], "stats": { - "chars": 38625, - "words": 3786, - "headings": 10, - "estimated_token_count_total": 7755 + "chars": 1658, + "words": 244, + "headings": 3, + "estimated_token_count_total": 280 }, - "hash": "sha256:086a87823ab67ceac102358030e316583cd733c0ec326316e7f29061fe7f6934", + "hash": "sha256:5bdc575ac798a971867a15651c2b4d5139bf0b1fe6854d1865deff280ae6d7f6", "token_estimator": "heuristic-v1" }, { - "id": "chain-interactions-send-transactions-interoperability-transfer-assets-out-of-polkadot", - "title": "chain-interactions-send-transactions-interoperability-transfer-assets-out-of-polkadot", - "slug": "chain-interactions-send-transactions-interoperability-transfer-assets-out-of-polkadot", + "id": "index", + "title": "Polkadot Developer Docs", + "slug": "index", "categories": [ "Uncategorized" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-send-transactions-interoperability-transfer-assets-out-of-polkadot.md", - "html_url": "https://docs.polkadot.com/chain-interactions/send-transactions/interoperability/transfer-assets-out-of-polkadot/", - "preview": "TODO", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/index.md", + "html_url": "https://docs.polkadot.com/index/", + "preview": "Explore everything you need to start building on top of Polkadot, a protocol that provides parachains with shared security and interoperability using XCM.", "outline": [], "stats": { - "chars": 5, - "words": 1, + "chars": 0, + "words": 0, "headings": 0, "estimated_token_count_total": 0 }, - "hash": "sha256:56ba36249ea8216ad513b13df3de6c0e490ba214897674d30331f1c7e7edbef3", + "hash": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "token_estimator": "heuristic-v1" }, { - "id": "chain-interactions-send-transactions-interoperability-transfer-assets-parachains", - "title": "Transfer Assets Between Parachains", - "slug": "chain-interactions-send-transactions-interoperability-transfer-assets-parachains", + "id": "nodes-and-validators-run-a-node-bootnode", + "title": "Set Up a Bootnode", + "slug": "nodes-and-validators-run-a-node-bootnode", "categories": [ - "Uncategorized" + "Infrastructure" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-send-transactions-interoperability-transfer-assets-parachains.md", - "html_url": "https://docs.polkadot.com/chain-interactions/send-transactions/interoperability/transfer-assets-parachains/", - "preview": "This guide walks you through transferring tokens between two parachains using the [ParaSpell XCM SDK](/reference/tools/paraspell/){target=\\_blank}. This example utilizes [Asset Hub](/polkadot-protocol/architecture/system-chains/asset-hub/){target=\\_blank} and the [People Chain](/polkadot-protocol/architecture/system-chains/people/){target=\\_blank}. However, the same approach can be applied to transfers between other parachains.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-node-bootnode.md", + "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-node/bootnode/", + "preview": "Bootnodes are essential for helping blockchain nodes discover peers and join the network. When a node starts, it needs to find other nodes, and bootnodes provide an initial point of contact. Once connected, a node can expand its peer connections and play its role in the network, like participating as a validator.", "outline": [ { "depth": 2, @@ -338,3116 +215,65 @@ "anchor": "introduction" }, { - "depth": 3, + "depth": 2, "title": "Prerequisites", "anchor": "prerequisites" }, { "depth": 2, - "title": "Initialize Your Project", - "anchor": "initialize-your-project" + "title": "Accessing the Bootnode", + "anchor": "accessing-the-bootnode" }, { "depth": 2, - "title": "Build a Token Transfer Transaction", - "anchor": "build-a-token-transfer-transaction" - }, - { - "depth": 2, - "title": "Perform a Dry Run", - "anchor": "perform-a-dry-run" - }, - { - "depth": 2, - "title": "Verify the Existential Deposit", - "anchor": "verify-the-existential-deposit" - }, - { - "depth": 2, - "title": "Get Transfer Info and Fee Estimates", - "anchor": "get-transfer-info-and-fee-estimates" - }, - { - "depth": 2, - "title": "Next Steps", - "anchor": "next-steps" - } - ], - "stats": { - "chars": 26764, - "words": 2289, - "headings": 8, - "estimated_token_count_total": 5257 - }, - "hash": "sha256:681b3f8e3bae1727c0f3742484dfc58ac817ad131199adb1f6f802592006fc69", - "token_estimator": "heuristic-v1" - }, - { - "id": "chain-interactions-send-transactions-pay-fees-with-different-tokens", - "title": "Send a Transaction While Paying the Fee with a Different Token", - "slug": "chain-interactions-send-transactions-pay-fees-with-different-tokens", - "categories": [ - "Uncategorized" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-send-transactions-pay-fees-with-different-tokens.md", - "html_url": "https://docs.polkadot.com/chain-interactions/send-transactions/pay-fees-with-different-tokens/", - "preview": "The Asset Hub provides a powerful feature that allows users to pay transaction fees using alternative tokens instead of the native token of the chain.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Environment Setup", - "anchor": "environment-setup" - }, - { - "depth": 2, - "title": "Local Asset Hub Setup", - "anchor": "local-asset-hub-setup" - }, - { - "depth": 2, - "title": "Implementation", - "anchor": "implementation" - }, - { - "depth": 3, - "title": "Import Dependencies", - "anchor": "import-dependencies" - }, - { - "depth": 3, - "title": "Define Constants", - "anchor": "define-constants" - }, - { - "depth": 3, - "title": "Create a Signer", - "anchor": "create-a-signer" - }, - { - "depth": 3, - "title": "Setup the Client and API", - "anchor": "setup-the-client-and-api" - }, - { - "depth": 3, - "title": "Create the Transaction", - "anchor": "create-the-transaction" - }, - { - "depth": 3, - "title": "Sign and Submit with Alternative Fee Payment", - "anchor": "sign-and-submit-with-alternative-fee-payment" - }, - { - "depth": 2, - "title": "Full Code", - "anchor": "full-code" - }, - { - "depth": 2, - "title": "Running the Script", - "anchor": "running-the-script" - }, - { - "depth": 2, - "title": "Expected Output", - "anchor": "expected-output" - }, - { - "depth": 2, - "title": "Conclusion", - "anchor": "conclusion" - } - ], - "stats": { - "chars": 9257, - "words": 1126, - "headings": 14, - "estimated_token_count_total": 2132 - }, - "hash": "sha256:1b9efd2fe00b251d3b4054c9cfcb55f9b5a1384238eeaca81a6f1542fc36d75c", - "token_estimator": "heuristic-v1" - }, - { - "id": "chain-interactions-send-transactions-with-sdks", - "title": "chain-interactions-send-transactions-with-sdks", - "slug": "chain-interactions-send-transactions-with-sdks", - "categories": [ - "Uncategorized" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-send-transactions-with-sdks.md", - "html_url": "https://docs.polkadot.com/chain-interactions/send-transactions/with-sdks/", - "preview": "TODO", - "outline": [], - "stats": { - "chars": 5, - "words": 1, - "headings": 0, - "estimated_token_count_total": 0 - }, - "hash": "sha256:56ba36249ea8216ad513b13df3de6c0e490ba214897674d30331f1c7e7edbef3", - "token_estimator": "heuristic-v1" - }, - { - "id": "chain-interactions-token-operations-convert-assets", - "title": "Convert Assets on Asset Hub", - "slug": "chain-interactions-token-operations-convert-assets", - "categories": [ - "dApps" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-token-operations-convert-assets.md", - "html_url": "https://docs.polkadot.com/chain-interactions/token-operations/convert-assets/", - "preview": "Asset Conversion is an Automated Market Maker (AMM) utilizing [Uniswap V2](https://github.com/Uniswap/v2-core){target=\\_blank} logic and implemented as a pallet on Polkadot's Asset Hub.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" - }, - { - "depth": 2, - "title": "Create a Liquidity Pool", - "anchor": "create-a-liquidity-pool" - }, - { - "depth": 2, - "title": "Add Liquidity to a Pool", - "anchor": "add-liquidity-to-a-pool" - }, - { - "depth": 2, - "title": "Swap Assets", - "anchor": "swap-assets" - }, - { - "depth": 3, - "title": "Swap from an Exact Amount of Tokens", - "anchor": "swap-from-an-exact-amount-of-tokens" - }, - { - "depth": 3, - "title": "Swap to an Exact Amount of Tokens", - "anchor": "swap-to-an-exact-amount-of-tokens" - }, - { - "depth": 2, - "title": "Withdraw Liquidity from a Pool", - "anchor": "withdraw-liquidity-from-a-pool" - }, - { - "depth": 2, - "title": "Test Environment Setup", - "anchor": "test-environment-setup" - } - ], - "stats": { - "chars": 18507, - "words": 2590, - "headings": 9, - "estimated_token_count_total": 4063 - }, - "hash": "sha256:bd07cdae71bf63786994865d2f33fba5f7bf8855dce6399414ad44ab0ec6635c", - "token_estimator": "heuristic-v1" - }, - { - "id": "chain-interactions-token-operations-register-foreign-asset", - "title": "Register a Foreign Asset on Asset Hub", - "slug": "chain-interactions-token-operations-register-foreign-asset", - "categories": [ - "dApps" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-token-operations-register-foreign-asset.md", - "html_url": "https://docs.polkadot.com/chain-interactions/token-operations/register-foreign-asset/", - "preview": "As outlined in the [Asset Hub Overview](/polkadot-protocol/architecture/system-chains/asset-hub){target=\\_blank}, Asset Hub supports two categories of assets: local and foreign. Local assets are created on the Asset Hub system parachain and are identified by integer IDs. On the other hand, foreign assets, which originate outside of Asset Hub, are recognized by [Multilocations](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#7-universal-consensus-location-identifiers){target=\\_b", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" - }, - { - "depth": 2, - "title": "Steps to Register a Foreign Asset", - "anchor": "steps-to-register-a-foreign-asset" - }, - { - "depth": 3, - "title": "Asset Hub", - "anchor": "asset-hub" - }, - { - "depth": 3, - "title": "Source Parachain", - "anchor": "source-parachain" - }, - { - "depth": 2, - "title": "Asset Registration Verification", - "anchor": "asset-registration-verification" - }, - { - "depth": 2, - "title": "Test Environment Setup", - "anchor": "test-environment-setup" - } - ], - "stats": { - "chars": 9757, - "words": 1422, - "headings": 7, - "estimated_token_count_total": 2225 - }, - "hash": "sha256:e916033f54c2874eb5ce9a43d58af058eb935429f73b7b1acc7da1592218e0b8", - "token_estimator": "heuristic-v1" - }, - { - "id": "chain-interactions-token-operations-register-local-asset", - "title": "Register a Local Asset", - "slug": "chain-interactions-token-operations-register-local-asset", - "categories": [ - "Basics", - "dApps" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-token-operations-register-local-asset.md", - "html_url": "https://docs.polkadot.com/chain-interactions/token-operations/register-local-asset/", - "preview": "As detailed in the [Asset Hub Overview](/polkadot-protocol/architecture/system-chains/asset-hub){target=\\_blank} page, Asset Hub accommodates two types of assets: local and foreign. Local assets are those that were created in Asset Hub and are identifiable by an integer ID. On the other hand, foreign assets originate from a sibling parachain and are identified by a Multilocation.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" - }, - { - "depth": 2, - "title": "Steps to Register a Local Asset", - "anchor": "steps-to-register-a-local-asset" - }, - { - "depth": 2, - "title": "Verify Asset Registration", - "anchor": "verify-asset-registration" - }, - { - "depth": 2, - "title": "Test Setup Environment", - "anchor": "test-setup-environment" - } - ], - "stats": { - "chars": 6355, - "words": 1015, - "headings": 5, - "estimated_token_count_total": 1523 - }, - "hash": "sha256:d9d85827d2c14bff8dd6b3301617345430cf63db603e37859720713004ecafae", - "token_estimator": "heuristic-v1" - }, - { - "id": "chain-interactions", - "title": "Chain Interactions Overview", - "slug": "chain-interactions", - "categories": [ - "Chain Interactions" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions.md", - "html_url": "https://docs.polkadot.com/chain-interactions/", - "preview": "Chain interactions form the foundation of building applications on Polkadot. Whether you're querying on-chain data, executing transactions, enabling cross-chain communication, or managing accounts, understanding how to interact with Polkadot-based chains is essential for application developers.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Core Interaction Patterns", - "anchor": "core-interaction-patterns" - }, - { - "depth": 3, - "title": "Query On-Chain Data", - "anchor": "query-on-chain-data" - }, - { - "depth": 3, - "title": "Send Transactions", - "anchor": "send-transactions" - }, - { - "depth": 3, - "title": "Send Cross-Chain Transactions", - "anchor": "send-cross-chain-transactions" - }, - { - "depth": 3, - "title": "Manage Tokens", - "anchor": "manage-tokens" - }, - { - "depth": 3, - "title": "Manage Accounts", - "anchor": "manage-accounts" - }, - { - "depth": 2, - "title": "Development Tools and SDKs", - "anchor": "development-tools-and-sdks" - }, - { - "depth": 2, - "title": "Next Steps", - "anchor": "next-steps" - } - ], - "stats": { - "chars": 6632, - "words": 831, - "headings": 9, - "estimated_token_count_total": 1488 - }, - "hash": "sha256:ff1d106bd19f80de0c8108b0a658cfef83d73a4560a012ace9c842acdeefd1a5", - "token_estimator": "heuristic-v1" - }, - { - "id": "get-support-ai-ready-docs", - "title": "AI Ready Docs", - "slug": "get-support-ai-ready-docs", - "categories": [ - "Uncategorized" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/get-support-ai-ready-docs.md", - "html_url": "https://docs.polkadot.com/get-support/ai-ready-docs/", - "preview": "Polkadot provides files to make documentation content available in a structure optimized for use with large language models (LLMs) and AI tools. These resources help build AI assistants, power code search, or enable custom tooling trained on Polkadot’s documentation.", - "outline": [ - { - "depth": 2, - "title": "How to Use These Files", - "anchor": "how-to-use-these-files" - }, - { - "depth": 2, - "title": "Download LLM Files", - "anchor": "download-llm-files" - } - ], - "stats": { - "chars": 7998, - "words": 825, - "headings": 2, - "estimated_token_count_total": 2232 - }, - "hash": "sha256:5a8da69a5cea8bd598ee4d102b9abed5d1a29153802a567e22bb4ee720410b32", - "token_estimator": "heuristic-v1" - }, - { - "id": "get-support-explore-resources", - "title": "Subscribe to Updates", - "slug": "get-support-explore-resources", - "categories": [ - "Uncategorized" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/get-support-explore-resources.md", - "html_url": "https://docs.polkadot.com/get-support/explore-resources/", - "preview": "Looking for answers beyond the documentation? These platforms are full of useful content and experienced developers sharing insights.", - "outline": [ - { - "depth": 2, - "title": "🧠 Stack Exchange", - "anchor": "stack-exchange" - }, - { - "depth": 2, - "title": "🧵 Reddit: r/Polkadot", - "anchor": "reddit-rpolkadot" - }, - { - "depth": 2, - "title": "💬 Discord (Community Threads Only)", - "anchor": "discord-community-threads-only" - }, - { - "depth": 2, - "title": "🎥 YouTube: @PolkadotNetwork", - "anchor": "youtube-polkadotnetwork" - }, - { - "depth": 2, - "title": "Community-Led Platforms and Ecosystem Updates", - "anchor": "community-led-platforms-and-ecosystem-updates" - }, - { - "depth": 3, - "title": "🔷 X (Twitter): Official Accounts", - "anchor": "x-twitter-official-accounts" - }, - { - "depth": 3, - "title": "🔁 X (Twitter): Community Accounts", - "anchor": "x-twitter-community-accounts" - }, - { - "depth": 3, - "title": "🗣️ Polkadot Forum", - "anchor": "polkadot-forum" - }, - { - "depth": 3, - "title": "🧑‍⚖️ Polkassembly: OpenGov", - "anchor": "polkassembly-opengov" - }, - { - "depth": 3, - "title": "📸 Instagram", - "anchor": "instagram" - } - ], - "stats": { - "chars": 2426, - "words": 295, - "headings": 10, - "estimated_token_count_total": 579 - }, - "hash": "sha256:670221ac20ab1f1b550ba2a1db06cd924c24bd3afc4d8a768b617d8a409243cb", - "token_estimator": "heuristic-v1" - }, - { - "id": "get-support-get-in-touch", - "title": "Get in Touch", - "slug": "get-support-get-in-touch", - "categories": [ - "Uncategorized" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/get-support-get-in-touch.md", - "html_url": "https://docs.polkadot.com/get-support/get-in-touch/", - "preview": "Use one of the channels below to get live technical support or ask questions.", - "outline": [ - { - "depth": 2, - "title": "Need Help Fast?", - "anchor": "need-help-fast" - }, - { - "depth": 2, - "title": "📱 Telegram: Polkadot Developer Support", - "anchor": "telegram-polkadot-developer-support" - }, - { - "depth": 2, - "title": "🔌 Discord: Polkadot Official Server", - "anchor": "discord-polkadot-official-server" - }, - { - "depth": 2, - "title": "🧬 Matrix: Polkadot Developer Support", - "anchor": "matrix-polkadot-developer-support" - } - ], - "stats": { - "chars": 1949, - "words": 258, - "headings": 4, - "estimated_token_count_total": 557 - }, - "hash": "sha256:993e93b05c8fbdfc2f7510c61ac86bc4c2ff0f03e573695b2f260933c8b62f78", - "token_estimator": "heuristic-v1" - }, - { - "id": "get-support", - "title": "Support", - "slug": "get-support", - "categories": [ - "Uncategorized" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/get-support.md", - "html_url": "https://docs.polkadot.com/get-support/", - "preview": "Use one of the channels below to get live technical support or ask questions.", - "outline": [ - { - "depth": 2, - "title": "Need More than Just Documentation?", - "anchor": "need-more-than-just-documentation" - }, - { - "depth": 2, - "title": "What You Can Do Here", - "anchor": "what-you-can-do-here" - }, - { - "depth": 2, - "title": "Help Us Improve", - "anchor": "help-us-improve" - } - ], - "stats": { - "chars": 1658, - "words": 244, - "headings": 3, - "estimated_token_count_total": 280 - }, - "hash": "sha256:5bdc575ac798a971867a15651c2b4d5139bf0b1fe6854d1865deff280ae6d7f6", - "token_estimator": "heuristic-v1" - }, - { - "id": "index", - "title": "Polkadot Developer Docs", - "slug": "index", - "categories": [ - "Uncategorized" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/index.md", - "html_url": "https://docs.polkadot.com/index/", - "preview": "Explore everything you need to start building on top of Polkadot, a protocol that provides parachains with shared security and interoperability using XCM.", - "outline": [], - "stats": { - "chars": 0, - "words": 0, - "headings": 0, - "estimated_token_count_total": 0 - }, - "hash": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "token_estimator": "heuristic-v1" - }, - { - "id": "nodes-and-validators-run-a-node-bootnode", - "title": "Set Up a Bootnode", - "slug": "nodes-and-validators-run-a-node-bootnode", - "categories": [ - "Infrastructure" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-node-bootnode.md", - "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-node/bootnode/", - "preview": "Bootnodes are essential for helping blockchain nodes discover peers and join the network. When a node starts, it needs to find other nodes, and bootnodes provide an initial point of contact. Once connected, a node can expand its peer connections and play its role in the network, like participating as a validator.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" - }, - { - "depth": 2, - "title": "Accessing the Bootnode", - "anchor": "accessing-the-bootnode" - }, - { - "depth": 2, - "title": "Node Key", - "anchor": "node-key" - }, - { - "depth": 2, - "title": "Running the Bootnode", - "anchor": "running-the-bootnode" - }, - { - "depth": 2, - "title": "Testing Bootnode Connection", - "anchor": "testing-bootnode-connection" - }, - { - "depth": 3, - "title": "P2P", - "anchor": "p2p" - }, - { - "depth": 3, - "title": "P2P/WS", - "anchor": "p2pws" - }, - { - "depth": 3, - "title": "P2P/WSS", - "anchor": "p2pwss" - } - ], - "stats": { - "chars": 4538, - "words": 647, - "headings": 9, - "estimated_token_count_total": 1044 - }, - "hash": "sha256:d84a5af1a0237a911d25a68c077f508ebbce608f673ef4f9055e8e434daa96b9", - "token_estimator": "heuristic-v1" - }, - { - "id": "nodes-and-validators-run-a-node-full-node", - "title": "Set Up a Node", - "slug": "nodes-and-validators-run-a-node-full-node", - "categories": [ - "Infrastructure" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-node-full-node.md", - "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-node/full-node/", - "preview": "Running a node on Polkadot provides direct interaction with the network, enhanced privacy, and full control over RPC requests, transactions, and data queries. As the backbone of the network, nodes ensure decentralized data propagation, transaction validation, and seamless communication across the ecosystem.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Set Up a Node", - "anchor": "set-up-a-node" - }, - { - "depth": 3, - "title": "Prerequisites", - "anchor": "prerequisites" - }, - { - "depth": 3, - "title": "Install and Build the Polkadot Binary", - "anchor": "install-and-build-the-polkadot-binary" - }, - { - "depth": 3, - "title": "Use Docker", - "anchor": "use-docker" - }, - { - "depth": 2, - "title": "Configure and Run Your Node", - "anchor": "configure-and-run-your-node" - }, - { - "depth": 3, - "title": "RPC Configurations", - "anchor": "rpc-configurations" - }, - { - "depth": 2, - "title": "Sync Your Node", - "anchor": "sync-your-node" - }, - { - "depth": 3, - "title": "Connect to Your Node", - "anchor": "connect-to-your-node" - } - ], - "stats": { - "chars": 15944, - "words": 2481, - "headings": 9, - "estimated_token_count_total": 4196 - }, - "hash": "sha256:924fab837818610c825be5cefde0a7bacd46985b4fa05cfa0376a941105b9869", - "token_estimator": "heuristic-v1" - }, - { - "id": "nodes-and-validators-run-a-node-secure-wss", - "title": "Set Up Secure WebSocket", - "slug": "nodes-and-validators-run-a-node-secure-wss", - "categories": [ - "Infrastructure" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-node-secure-wss.md", - "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-node/secure-wss/", - "preview": "Ensuring secure WebSocket communication is crucial for maintaining the integrity and security of a Polkadot or Kusama node when interacting with remote clients. This guide walks you through setting up a secure WebSocket (WSS) connection for your node by leveraging SSL encryption with popular web server proxies like nginx or Apache.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Secure a WebSocket Port", - "anchor": "secure-a-websocket-port" - }, - { - "depth": 3, - "title": "Obtain an SSL Certificate", - "anchor": "obtain-an-ssl-certificate" - }, - { - "depth": 2, - "title": "Install a Proxy Server", - "anchor": "install-a-proxy-server" - }, - { - "depth": 3, - "title": "Use nginx", - "anchor": "use-nginx" - }, - { - "depth": 3, - "title": "Use Apache2", - "anchor": "use-apache2" - }, - { - "depth": 2, - "title": "Connect to the Node", - "anchor": "connect-to-the-node" - } - ], - "stats": { - "chars": 5568, - "words": 774, - "headings": 7, - "estimated_token_count_total": 1280 - }, - "hash": "sha256:992082e4ad87348b283f6c37ea886ae0e7bf016852b6470000876f3d169c65a4", - "token_estimator": "heuristic-v1" - }, - { - "id": "nodes-and-validators-run-a-validator-onboarding-and-offboarding-key-management", - "title": "Validator Key Management", - "slug": "nodes-and-validators-run-a-validator-onboarding-and-offboarding-key-management", - "categories": [ - "Infrastructure" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-onboarding-and-offboarding-key-management.md", - "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/onboarding-and-offboarding/key-management/", - "preview": "After setting up your node environment as shown in the [Setup](/nodes-and-validators/run-a-validator/onboarding-and-offboarding/set-up-validator/){target=\\_blank} section, you'll need to configure multiple keys for your validator to operate properly. This includes setting up session keys, which are essential for participating in the consensus process, and configuring a node key that maintains a stable network identity. This guide walks you through the key management process, showing you how to g", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Set Session Keys", - "anchor": "set-session-keys" - }, - { - "depth": 3, - "title": "Generate Session Keys", - "anchor": "generate-session-keys" - }, - { - "depth": 3, - "title": "Submit Transaction to Set Keys", - "anchor": "submit-transaction-to-set-keys" - }, - { - "depth": 3, - "title": "Verify Session Key Setup", - "anchor": "verify-session-key-setup" - }, - { - "depth": 2, - "title": "Set the Node Key", - "anchor": "set-the-node-key" - }, - { - "depth": 3, - "title": "Generate the Node Key", - "anchor": "generate-the-node-key" - }, - { - "depth": 3, - "title": "Set Node Key", - "anchor": "set-node-key" - } - ], - "stats": { - "chars": 8227, - "words": 1183, - "headings": 8, - "estimated_token_count_total": 1840 - }, - "hash": "sha256:0fb5a83835aab263c0b9aa886028c8aa8a2d6d0897d7b9fff4b5258835d30dfe", - "token_estimator": "heuristic-v1" - }, - { - "id": "nodes-and-validators-run-a-validator-onboarding-and-offboarding-set-up-validator", - "title": "Set Up a Validator", - "slug": "nodes-and-validators-run-a-validator-onboarding-and-offboarding-set-up-validator", - "categories": [ - "Infrastructure" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-onboarding-and-offboarding-set-up-validator.md", - "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/onboarding-and-offboarding/set-up-validator/", - "preview": "Setting up a Polkadot validator node is essential for securing the network and earning staking rewards. This guide walks you through the technical steps to set up a validator, from installing the necessary software to managing keys and synchronizing your node with the chain.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" - }, - { - "depth": 2, - "title": "Initial Setup", - "anchor": "initial-setup" - }, - { - "depth": 3, - "title": "Install Network Time Protocol Client", - "anchor": "install-network-time-protocol-client" - }, - { - "depth": 3, - "title": "Verify Landlock is Activated", - "anchor": "verify-landlock-is-activated" - }, - { - "depth": 2, - "title": "Install the Polkadot Binaries", - "anchor": "install-the-polkadot-binaries" - }, - { - "depth": 3, - "title": "Install from Official Releases", - "anchor": "install-from-official-releases" - }, - { - "depth": 3, - "title": "Install with Package Managers", - "anchor": "install-with-package-managers" - }, - { - "depth": 3, - "title": "Install with Ansible", - "anchor": "install-with-ansible" - }, - { - "depth": 3, - "title": "Install with Docker", - "anchor": "install-with-docker" - }, - { - "depth": 3, - "title": "Build from Sources", - "anchor": "build-from-sources" - }, - { - "depth": 2, - "title": "Verify Installation", - "anchor": "verify-installation" - } - ], - "stats": { - "chars": 11921, - "words": 1678, - "headings": 12, - "estimated_token_count_total": 2592 - }, - "hash": "sha256:d2c1c91734bc8185057d8eeec6829ea91e0316f7ba884c5dc3922a5e5778815e", - "token_estimator": "heuristic-v1" - }, - { - "id": "nodes-and-validators-run-a-validator-onboarding-and-offboarding-start-validating", - "title": "Start Validating", - "slug": "nodes-and-validators-run-a-validator-onboarding-and-offboarding-start-validating", - "categories": [ - "Infrastructure" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-onboarding-and-offboarding-start-validating.md", - "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/onboarding-and-offboarding/start-validating/", - "preview": "After configuring your node keys as shown in the [Key Management](/nodes-and-validators/run-a-validator/onboarding-and-offboarding/key-management/){target=\\_blank} section and ensuring your system is set up, you're ready to begin the validator setup process. This guide will walk you through choosing a network, synchronizing your node with the blockchain, bonding your DOT tokens, and starting your validator.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Choose a Network", - "anchor": "choose-a-network" - }, - { - "depth": 2, - "title": "Synchronize Chain Data", - "anchor": "synchronize-chain-data" - }, - { - "depth": 3, - "title": "Database Snapshot Services", - "anchor": "database-snapshot-services" - }, - { - "depth": 2, - "title": "Bond DOT", - "anchor": "bond-dot" - }, - { - "depth": 3, - "title": "Bonding DOT on Polkadot.js Apps", - "anchor": "bonding-dot-on-polkadotjs-apps" - }, - { - "depth": 2, - "title": "Validate", - "anchor": "validate" - }, - { - "depth": 3, - "title": "Verify Sync via Telemetry", - "anchor": "verify-sync-via-telemetry" - }, - { - "depth": 3, - "title": "Activate using Polkadot.js Apps", - "anchor": "activate-using-polkadotjs-apps" - }, - { - "depth": 3, - "title": "Monitor Validation Status and Slots", - "anchor": "monitor-validation-status-and-slots" - }, - { - "depth": 2, - "title": "Run a Validator Using Systemd", - "anchor": "run-a-validator-using-systemd" - }, - { - "depth": 3, - "title": "Create the Systemd Service File", - "anchor": "create-the-systemd-service-file" - }, - { - "depth": 3, - "title": "Run the Service", - "anchor": "run-the-service" - } - ], - "stats": { - "chars": 15820, - "words": 2446, - "headings": 13, - "estimated_token_count_total": 3861 - }, - "hash": "sha256:67a43e787805244196e1e9cb962069292c69ed5fdb1110df57c942019892b953", - "token_estimator": "heuristic-v1" - }, - { - "id": "nodes-and-validators-run-a-validator-onboarding-and-offboarding-stop-validating", - "title": "Stop Validating", - "slug": "nodes-and-validators-run-a-validator-onboarding-and-offboarding-stop-validating", - "categories": [ - "Infrastructure" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-onboarding-and-offboarding-stop-validating.md", - "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/onboarding-and-offboarding/stop-validating/", - "preview": "If you're ready to stop validating on Polkadot, there are essential steps to ensure a smooth transition while protecting your funds and account integrity. Whether you're taking a break for maintenance or unbonding entirely, you'll need to chill your validator, purge session keys, and unbond your tokens. This guide explains how to use Polkadot's tools and extrinsics to safely withdraw from validation activities, safeguarding your account's future usability.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Pause Versus Stop", - "anchor": "pause-versus-stop" - }, - { - "depth": 2, - "title": "Chill Validator", - "anchor": "chill-validator" - }, - { - "depth": 2, - "title": "Purge Validator Session Keys", - "anchor": "purge-validator-session-keys" - }, - { - "depth": 2, - "title": "Unbond Your Tokens", - "anchor": "unbond-your-tokens" - } - ], - "stats": { - "chars": 3230, - "words": 500, - "headings": 5, - "estimated_token_count_total": 629 - }, - "hash": "sha256:0d6db361bfa7a3022849bbe39989bfdac0429537498d7f534adadec131afca98", - "token_estimator": "heuristic-v1" - }, - { - "id": "nodes-and-validators-run-a-validator-operational-tasks-general-management", - "title": "General Management", - "slug": "nodes-and-validators-run-a-validator-operational-tasks-general-management", - "categories": [ - "Infrastructure" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-operational-tasks-general-management.md", - "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/operational-tasks/general-management/", - "preview": "Validator performance is pivotal in maintaining the security and stability of the Polkadot network. As a validator, optimizing your setup ensures efficient transaction processing, minimizes latency, and maintains system reliability during high-demand periods. Proper configuration and proactive monitoring also help mitigate risks like slashing and service interruptions.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Configuration Optimization", - "anchor": "configuration-optimization" - }, - { - "depth": 3, - "title": "Deactivate Simultaneous Multithreading", - "anchor": "deactivate-simultaneous-multithreading" - }, - { - "depth": 3, - "title": "Deactivate Automatic NUMA Balancing", - "anchor": "deactivate-automatic-numa-balancing" - }, - { - "depth": 3, - "title": "Spectre and Meltdown Mitigations", - "anchor": "spectre-and-meltdown-mitigations" - }, - { - "depth": 2, - "title": "Monitor Your Node", - "anchor": "monitor-your-node" - }, - { - "depth": 3, - "title": "Environment Setup", - "anchor": "environment-setup" - }, - { - "depth": 3, - "title": "Install and Configure Prometheus", - "anchor": "install-and-configure-prometheus" - }, - { - "depth": 3, - "title": "Start Prometheus", - "anchor": "start-prometheus" - }, - { - "depth": 3, - "title": "Install and Configure Grafana", - "anchor": "install-and-configure-grafana" - }, - { - "depth": 3, - "title": "Install and Configure Alertmanager", - "anchor": "install-and-configure-alertmanager" - }, - { - "depth": 2, - "title": "Secure Your Validator", - "anchor": "secure-your-validator" - }, - { - "depth": 3, - "title": "Key Management", - "anchor": "key-management" - }, - { - "depth": 3, - "title": "Signing Outside the Client", - "anchor": "signing-outside-the-client" - }, - { - "depth": 3, - "title": "Secure-Validator Mode", - "anchor": "secure-validator-mode" - }, - { - "depth": 3, - "title": "Linux Best Practices", - "anchor": "linux-best-practices" - }, - { - "depth": 3, - "title": "Validator Best Practices", - "anchor": "validator-best-practices" - }, - { - "depth": 2, - "title": "Additional Resources", - "anchor": "additional-resources" - } - ], - "stats": { - "chars": 26673, - "words": 3357, - "headings": 18, - "estimated_token_count_total": 5866 - }, - "hash": "sha256:81eb0fe77f05155f1ec0511cd066120fc9994961e9d91e21b6666377e65b4586", - "token_estimator": "heuristic-v1" - }, - { - "id": "nodes-and-validators-run-a-validator-operational-tasks-pause-validating", - "title": "Pause Validating", - "slug": "nodes-and-validators-run-a-validator-operational-tasks-pause-validating", - "categories": [ - "Infrastructure" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-operational-tasks-pause-validating.md", - "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/operational-tasks/pause-validating/", - "preview": "If you need to temporarily stop participating in Polkadot staking activities without fully unbonding your funds, chilling your account allows you to do so efficiently. Chilling removes your node from active validation or nomination in the next era while keeping your funds bonded, making it ideal for planned downtimes or temporary pauses.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Chilling Your Node", - "anchor": "chilling-your-node" - }, - { - "depth": 2, - "title": "Staking Election Timing Considerations", - "anchor": "staking-election-timing-considerations" - }, - { - "depth": 2, - "title": "Chilling as a Nominator", - "anchor": "chilling-as-a-nominator" - }, - { - "depth": 2, - "title": "Chilling as a Validator", - "anchor": "chilling-as-a-validator" - }, - { - "depth": 2, - "title": "Chill Other", - "anchor": "chill-other" - } - ], - "stats": { - "chars": 4439, - "words": 679, - "headings": 6, - "estimated_token_count_total": 861 - }, - "hash": "sha256:1af153570ce57bd5b52d08493a300996765686f2a6d04519a2e0aa91191612c1", - "token_estimator": "heuristic-v1" - }, - { - "id": "nodes-and-validators-run-a-validator-operational-tasks-upgrade-your-node", - "title": "Upgrade a Validator Node", - "slug": "nodes-and-validators-run-a-validator-operational-tasks-upgrade-your-node", - "categories": [ - "Infrastructure" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-operational-tasks-upgrade-your-node.md", - "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/operational-tasks/upgrade-your-node/", - "preview": "Upgrading a Polkadot validator node is essential for staying current with network updates and maintaining optimal performance. This guide covers routine and extended maintenance scenarios, including software upgrades and major server changes. Following these steps, you can manage session keys and transition smoothly between servers without risking downtime, slashing, or network disruptions. The process requires strategic planning, especially if you need to perform long-lead maintenance, ensuring", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" - }, - { - "depth": 2, - "title": "Session Keys", - "anchor": "session-keys" - }, - { - "depth": 2, - "title": "Keystore", - "anchor": "keystore" - }, - { - "depth": 2, - "title": "Upgrade Using Backup Validator", - "anchor": "upgrade-using-backup-validator" - }, - { - "depth": 3, - "title": "Session `N`", - "anchor": "session-n" - }, - { - "depth": 3, - "title": "Session `N+3`", - "anchor": "session-n3" - } - ], - "stats": { - "chars": 5650, - "words": 851, - "headings": 7, - "estimated_token_count_total": 1185 - }, - "hash": "sha256:888230b128d8c648c4f06a18d3b1d1b06dd1bf22a0de4add1f28210ffccb2549", - "token_estimator": "heuristic-v1" - }, - { - "id": "nodes-and-validators-run-a-validator-requirements", - "title": "Validator Requirements", - "slug": "nodes-and-validators-run-a-validator-requirements", - "categories": [ - "Infrastructure" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-requirements.md", - "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/requirements/", - "preview": "Running a validator in the Polkadot ecosystem is essential for maintaining network security and decentralization. Validators are responsible for validating transactions and adding new blocks to the chain, ensuring the system operates smoothly. In return for their services, validators earn rewards. However, the role comes with inherent risks, such as slashing penalties for misbehavior or technical failures. If you’re new to validation, starting on Kusama provides a lower-stakes environment to gai", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" - }, - { - "depth": 2, - "title": "Minimum Hardware Requirements", - "anchor": "minimum-hardware-requirements" - }, - { - "depth": 2, - "title": "VPS Provider List", - "anchor": "vps-provider-list" - }, - { - "depth": 2, - "title": "Minimum Bond Requirement", - "anchor": "minimum-bond-requirement" - } - ], - "stats": { - "chars": 6842, - "words": 944, - "headings": 5, - "estimated_token_count_total": 1485 - }, - "hash": "sha256:46435b97c37ef6798d2c75c69df31c5e5f07e04b218c370ec5af6b1838d43aac", - "token_estimator": "heuristic-v1" - }, - { - "id": "nodes-and-validators-run-a-validator-staking-mechanics-offenses-and-slashes", - "title": "Offenses and Slashes", - "slug": "nodes-and-validators-run-a-validator-staking-mechanics-offenses-and-slashes", - "categories": [ - "Infrastructure" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-staking-mechanics-offenses-and-slashes.md", - "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/staking-mechanics/offenses-and-slashes/", - "preview": "In Polkadot's Nominated Proof of Stake (NPoS) system, validator misconduct is deterred through a combination of slashing, disabling, and reputation penalties. Validators and nominators who stake tokens face consequences for validator misbehavior, which range from token slashes to restrictions on network participation.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Offenses", - "anchor": "offenses" - }, - { - "depth": 3, - "title": "Invalid Votes", - "anchor": "invalid-votes" - }, - { - "depth": 3, - "title": "Equivocations", - "anchor": "equivocations" - }, - { - "depth": 2, - "title": "Penalties", - "anchor": "penalties" - }, - { - "depth": 3, - "title": "Slashing", - "anchor": "slashing" - }, - { - "depth": 3, - "title": "Disabling", - "anchor": "disabling" - }, - { - "depth": 3, - "title": "Reputation Changes", - "anchor": "reputation-changes" - }, - { - "depth": 3, - "title": "Penalties by Offense", - "anchor": "penalties-by-offense" - } - ], - "stats": { - "chars": 15427, - "words": 2103, - "headings": 9, - "estimated_token_count_total": 3409 - }, - "hash": "sha256:abe6bedab04f463ec07f554977b8d6355a5d2fad9bcda01cbe58568152295daa", - "token_estimator": "heuristic-v1" - }, - { - "id": "nodes-and-validators-run-a-validator-staking-mechanics-rewards", - "title": "Rewards Payout", - "slug": "nodes-and-validators-run-a-validator-staking-mechanics-rewards", - "categories": [ - "Infrastructure" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-staking-mechanics-rewards.md", - "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/staking-mechanics/rewards/", - "preview": "Understanding how rewards are distributed to validators and nominators is essential for network participants. In Polkadot and Kusama, validators earn rewards based on their era points, which are accrued through actions like block production and parachain validation.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Era Points", - "anchor": "era-points" - }, - { - "depth": 2, - "title": "Reward Variance", - "anchor": "reward-variance" - }, - { - "depth": 2, - "title": "Payout Scheme", - "anchor": "payout-scheme" - }, - { - "depth": 2, - "title": "Running Multiple Validators", - "anchor": "running-multiple-validators" - }, - { - "depth": 2, - "title": "Nominators and Validator Payments", - "anchor": "nominators-and-validator-payments" - } - ], - "stats": { - "chars": 10976, - "words": 1753, - "headings": 6, - "estimated_token_count_total": 2588 - }, - "hash": "sha256:d5d6d72eb2cf10f624d84c65f2274f7df90acb5d071bf170bc8eae8d98a810a5", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-customize-runtime-add-existing-pallets", - "title": "Add an Existing Pallet to the Runtime", - "slug": "parachains-customize-runtime-add-existing-pallets", - "categories": [ - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime-add-existing-pallets.md", - "html_url": "https://docs.polkadot.com/parachains/customize-runtime/add-existing-pallets/", - "preview": "The [Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\\_blank} provides a functional runtime that includes default [FRAME](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\\_blank} development modules ([pallets](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/pallet/index.html){target=\\_blank}) to help you get started building a custo", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Check Prerequisites", - "anchor": "check-prerequisites" - }, - { - "depth": 2, - "title": "Add an Existing Polkadot SDK Pallet to Your Runtime", - "anchor": "add-an-existing-polkadot-sdk-pallet-to-your-runtime" - }, - { - "depth": 3, - "title": "Add an Existing Pallet as a Dependency", - "anchor": "add-an-existing-pallet-as-a-dependency" - }, - { - "depth": 3, - "title": "Enable Standard Library Features", - "anchor": "enable-standard-library-features" - }, - { - "depth": 3, - "title": "Review the Config Trait", - "anchor": "review-the-config-trait" - }, - { - "depth": 3, - "title": "Implement the Config Trait", - "anchor": "implement-the-config-trait" - }, - { - "depth": 3, - "title": "Add to Runtime Construct", - "anchor": "add-to-runtime-construct" - }, - { - "depth": 3, - "title": "Verify the Runtime Compiles", - "anchor": "verify-the-runtime-compiles" - }, - { - "depth": 2, - "title": "Run Your Chain Locally", - "anchor": "run-your-chain-locally" - }, - { - "depth": 3, - "title": "Generate a Chain Specification", - "anchor": "generate-a-chain-specification" - }, - { - "depth": 3, - "title": "Start the Parachain Node", - "anchor": "start-the-parachain-node" - }, - { - "depth": 3, - "title": "Interact with the Pallet", - "anchor": "interact-with-the-pallet" - }, - { - "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" - } - ], - "stats": { - "chars": 11924, - "words": 1585, - "headings": 14, - "estimated_token_count_total": 2724 - }, - "hash": "sha256:93d123cbaaccc2515b4a70be8e1327b4f75b1051d16c5e3daf5a2035af7b7ca3", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-customize-runtime-add-pallet-instances", - "title": "Add Multiple Pallet Instances", - "slug": "parachains-customize-runtime-add-pallet-instances", - "categories": [ - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime-add-pallet-instances.md", - "html_url": "https://docs.polkadot.com/parachains/customize-runtime/add-pallet-instances/", - "preview": "The [Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\\_blank} provides a solid foundation for building custom parachains. While most pallets are typically included as single instances within a runtime, some scenarios benefit from running multiple instances of the same pallet with different configurations. This approach lets you reuse pallet logic without reimplementing it, enabling diverse functionality from a single codebase.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Check Prerequisites", - "anchor": "check-prerequisites" - }, - { - "depth": 2, - "title": "Understanding Instantiable Pallets", - "anchor": "understanding-instantiable-pallets" - }, - { - "depth": 3, - "title": "Identifying an Instantiable Pallet", - "anchor": "identifying-an-instantiable-pallet" - }, - { - "depth": 3, - "title": "How Instance Generics Work", - "anchor": "how-instance-generics-work" - }, - { - "depth": 2, - "title": "Add Multiple Instances of a Pallet to Your Runtime", - "anchor": "add-multiple-instances-of-a-pallet-to-your-runtime" - }, - { - "depth": 3, - "title": "Add the Pallet as a Dependency", - "anchor": "add-the-pallet-as-a-dependency" - }, - { - "depth": 3, - "title": "Enable Standard Library Features", - "anchor": "enable-standard-library-features" - }, - { - "depth": 3, - "title": "Review the Config Trait", - "anchor": "review-the-config-trait" - }, - { - "depth": 3, - "title": "Define Pallet Parameters", - "anchor": "define-pallet-parameters" - }, - { - "depth": 3, - "title": "Create Instance Type Definitions", - "anchor": "create-instance-type-definitions" - }, - { - "depth": 3, - "title": "Implement Config Trait for First Instance", - "anchor": "implement-config-trait-for-first-instance" - }, - { - "depth": 3, - "title": "Implement Config Trait for Second Instance", - "anchor": "implement-config-trait-for-second-instance" - }, - { - "depth": 3, - "title": "Add Instances to Runtime Construct", - "anchor": "add-instances-to-runtime-construct" - }, - { - "depth": 3, - "title": "Verify the Runtime Compiles", - "anchor": "verify-the-runtime-compiles" - }, - { - "depth": 2, - "title": "Run Your Chain Locally", - "anchor": "run-your-chain-locally" - }, - { - "depth": 3, - "title": "Generate a Chain Specification", - "anchor": "generate-a-chain-specification" - }, - { - "depth": 3, - "title": "Start the Parachain Node", - "anchor": "start-the-parachain-node" - }, - { - "depth": 3, - "title": "Interact with Both Pallet Instances", - "anchor": "interact-with-both-pallet-instances" - }, - { - "depth": 3, - "title": "Test Instance Independence", - "anchor": "test-instance-independence" - }, - { - "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" - } - ], - "stats": { - "chars": 17923, - "words": 2203, - "headings": 21, - "estimated_token_count_total": 3811 - }, - "hash": "sha256:d83e574726c524fa017236eb5e3b8a0676d598be4da1ce4fe25a60141baeee49", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-customize-runtime-add-smart-contract-functionality", - "title": "Add Smart Contract Functionality", - "slug": "parachains-customize-runtime-add-smart-contract-functionality", - "categories": [ - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime-add-smart-contract-functionality.md", - "html_url": "https://docs.polkadot.com/parachains/customize-runtime/add-smart-contract-functionality/", - "preview": "When building your custom blockchain with the Polkadot SDK, you can add smart contract capabilities through specialized pallets. These pallets enable users to deploy and execute smart contracts, enhancing your chain's programmability and allowing developers to build decentralized applications on your network.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "pallet-revive", - "anchor": "pallet-revive" - }, - { - "depth": 3, - "title": "Core Components", - "anchor": "core-components" - }, - { - "depth": 3, - "title": "Supported Languages and Compilers", - "anchor": "supported-languages-and-compilers" - }, - { - "depth": 3, - "title": "How It Works", - "anchor": "how-it-works" - }, - { - "depth": 3, - "title": "Key Benefits", - "anchor": "key-benefits" - }, - { - "depth": 3, - "title": "Implementation Examples", - "anchor": "implementation-examples" - }, - { - "depth": 2, - "title": "Frontier", - "anchor": "frontier" - }, - { - "depth": 3, - "title": "Integration Options", - "anchor": "integration-options" - }, - { - "depth": 3, - "title": "EVM Execution Only", - "anchor": "evm-execution-only" - }, - { - "depth": 3, - "title": "Full Ethereum Compatibility", - "anchor": "full-ethereum-compatibility" - }, - { - "depth": 3, - "title": "Key Benefits", - "anchor": "key-benefits-2" - }, - { - "depth": 3, - "title": "Implementation Examples", - "anchor": "implementation-examples-2" - }, - { - "depth": 2, - "title": "pallet-contracts (Legacy)", - "anchor": "pallet-contracts-legacy" - }, - { - "depth": 3, - "title": "Implementation Example", - "anchor": "implementation-example" - }, - { - "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" - } - ], - "stats": { - "chars": 6655, - "words": 833, - "headings": 16, - "estimated_token_count_total": 1631 - }, - "hash": "sha256:6297bb5e0809fdd0585d6170054599f7ab4a3ce7c687ad03ae43092057c493b7", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-customize-runtime-pallet-development-add-pallet-to-runtime", - "title": "Add Pallets to the Runtime", - "slug": "parachains-customize-runtime-pallet-development-add-pallet-to-runtime", - "categories": [ - "Basics", - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime-pallet-development-add-pallet-to-runtime.md", - "html_url": "https://docs.polkadot.com/parachains/customize-runtime/pallet-development/add-pallet-to-runtime/", - "preview": "In previous tutorials, you learned how to [create a custom pallet](/tutorials/polkadot-sdk/parachains/zero-to-hero/build-custom-pallet/){target=\\_blank} and [test it](/tutorials/polkadot-sdk/parachains/zero-to-hero/pallet-unit-testing/){target=\\_blank}. The next step is to include this pallet in your runtime, integrating it into the core logic of your blockchain.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Add the Pallets as Dependencies", - "anchor": "add-the-pallets-as-dependencies" - }, - { - "depth": 3, - "title": "Update the Runtime Configuration", - "anchor": "update-the-runtime-configuration" - }, - { - "depth": 2, - "title": "Recompile the Runtime", - "anchor": "recompile-the-runtime" - }, - { - "depth": 2, - "title": "Run Your Chain Locally", - "anchor": "run-your-chain-locally" - }, - { - "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" - } - ], - "stats": { - "chars": 13091, - "words": 1522, - "headings": 6, - "estimated_token_count_total": 3091 - }, - "hash": "sha256:87add0ae178e4970601a27efccadb58eff1375d19819201034ba2829914f1cd5", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-customize-runtime-pallet-development-benchmark-pallet", - "title": "Benchmarking FRAME Pallets", - "slug": "parachains-customize-runtime-pallet-development-benchmark-pallet", - "categories": [ - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime-pallet-development-benchmark-pallet.md", - "html_url": "https://docs.polkadot.com/parachains/customize-runtime/pallet-development/benchmark-pallet/", - "preview": "Benchmarking is a critical component of developing efficient and secure blockchain runtimes. In the Polkadot ecosystem, accurately benchmarking your custom pallets ensures that each extrinsic has a precise [weight](/reference/glossary/#weight){target=\\_blank}, representing its computational and storage demands. This process is vital for maintaining the blockchain's performance and preventing potential vulnerabilities, such as Denial of Service (DoS) attacks.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "The Case for Benchmarking", - "anchor": "the-case-for-benchmarking" - }, - { - "depth": 3, - "title": "Benchmarking and Weight", - "anchor": "benchmarking-and-weight" - }, - { - "depth": 2, - "title": "Benchmarking Process", - "anchor": "benchmarking-process" - }, - { - "depth": 3, - "title": "Prepare Your Environment", - "anchor": "prepare-your-environment" - }, - { - "depth": 3, - "title": "Write Benchmark Tests", - "anchor": "write-benchmark-tests" - }, - { - "depth": 3, - "title": "Add Benchmarks to Runtime", - "anchor": "add-benchmarks-to-runtime" - }, - { - "depth": 3, - "title": "Run Benchmarks", - "anchor": "run-benchmarks" - }, - { - "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" - } - ], - "stats": { - "chars": 14715, - "words": 1879, - "headings": 9, - "estimated_token_count_total": 3338 - }, - "hash": "sha256:915bc91edd56cdedd516e871dbe450d70c9f99fb467cc00ff231ea3a74f61d96", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-customize-runtime-pallet-development-create-a-pallet", - "title": "Create a Custom Pallet", - "slug": "parachains-customize-runtime-pallet-development-create-a-pallet", - "categories": [ - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime-pallet-development-create-a-pallet.md", - "html_url": "https://docs.polkadot.com/parachains/customize-runtime/pallet-development/create-a-pallet/", - "preview": "[Framework for Runtime Aggregation of Modular Entities (FRAME)](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\\_blank} provides a powerful set of tools for blockchain development through modular components called [pallets](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/pallet/index.html){target=\\_blank}. These Rust-based runtime modules allow you to build custom blockchain functional", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" - }, - { - "depth": 2, - "title": "Core Pallet Components", - "anchor": "core-pallet-components" - }, - { - "depth": 2, - "title": "Create the Pallet Project", - "anchor": "create-the-pallet-project" - }, - { - "depth": 2, - "title": "Configure Dependencies", - "anchor": "configure-dependencies" - }, - { - "depth": 2, - "title": "Initialize the Pallet Structure", - "anchor": "initialize-the-pallet-structure" - }, - { - "depth": 2, - "title": "Configure the Pallet", - "anchor": "configure-the-pallet" - }, - { - "depth": 2, - "title": "Define Events", - "anchor": "define-events" - }, - { - "depth": 2, - "title": "Define Errors", - "anchor": "define-errors" - }, - { - "depth": 2, - "title": "Add Storage Items", - "anchor": "add-storage-items" - }, - { - "depth": 2, - "title": "Configure Genesis State", - "anchor": "configure-genesis-state" - }, - { - "depth": 2, - "title": "Implement Dispatchable Functions", - "anchor": "implement-dispatchable-functions" - }, - { - "depth": 3, - "title": "Dispatchable Function Details", - "anchor": "dispatchable-function-details" - }, - { - "depth": 2, - "title": "Verify Pallet Compilation", - "anchor": "verify-pallet-compilation" - }, - { - "depth": 2, - "title": "Add the Pallet to Your Runtime", - "anchor": "add-the-pallet-to-your-runtime" - }, - { - "depth": 3, - "title": "Add Runtime Dependency", - "anchor": "add-runtime-dependency" - }, - { - "depth": 3, - "title": "Implement the Config Trait", - "anchor": "implement-the-config-trait" - }, - { - "depth": 3, - "title": "Add to Runtime Construct", - "anchor": "add-to-runtime-construct" - }, - { - "depth": 3, - "title": "Configure Genesis for Your Runtime", - "anchor": "configure-genesis-for-your-runtime" - }, - { - "depth": 3, - "title": "Verify Runtime Compilation", - "anchor": "verify-runtime-compilation" - }, - { - "depth": 2, - "title": "Run Your Chain Locally", - "anchor": "run-your-chain-locally" - }, - { - "depth": 3, - "title": "Generate a Chain Specification", - "anchor": "generate-a-chain-specification" - }, - { - "depth": 3, - "title": "Start the Parachain Node", - "anchor": "start-the-parachain-node" - }, - { - "depth": 2, - "title": "Interact with Your Pallet", - "anchor": "interact-with-your-pallet" - }, - { - "depth": 2, - "title": "Key Takeaways", - "anchor": "key-takeaways" - }, - { - "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" - } - ], - "stats": { - "chars": 26671, - "words": 3041, - "headings": 26, - "estimated_token_count_total": 6113 - }, - "hash": "sha256:607e283aaa1295de0af191d97de7f6f87afb722c601a447821fde6a09b97f1af", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-customize-runtime-pallet-development-mock-runtime", - "title": "Mock Your Runtime", - "slug": "parachains-customize-runtime-pallet-development-mock-runtime", - "categories": [ - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime-pallet-development-mock-runtime.md", - "html_url": "https://docs.polkadot.com/parachains/customize-runtime/pallet-development/mock-runtime/", - "preview": "Testing is a critical part of pallet development. Before integrating your pallet into a full runtime, you need a way to test its functionality in isolation. A mock runtime provides a minimal, simulated blockchain environment where you can verify your pallet's logic without the overhead of running a full node.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" - }, - { - "depth": 2, - "title": "Understand Mock Runtimes", - "anchor": "understand-mock-runtimes" - }, - { - "depth": 2, - "title": "Create the Mock Runtime Module", - "anchor": "create-the-mock-runtime-module" - }, - { - "depth": 2, - "title": "Set Up Basic Mock", - "anchor": "set-up-basic-mock" - }, - { - "depth": 2, - "title": "Implement Essential Configuration", - "anchor": "implement-essential-configuration" - }, - { - "depth": 2, - "title": "Implement Your Pallet's Configuration", - "anchor": "implement-your-pallets-configuration" - }, - { - "depth": 2, - "title": "Configure Genesis Storage", - "anchor": "configure-genesis-storage" - }, - { - "depth": 3, - "title": "Basic Test Environment", - "anchor": "basic-test-environment" - }, - { - "depth": 3, - "title": "Custom Genesis Configurations", - "anchor": "custom-genesis-configurations" - }, - { - "depth": 2, - "title": "Verify Mock Compilation", - "anchor": "verify-mock-compilation" - }, - { - "depth": 2, - "title": "Key Takeaways", - "anchor": "key-takeaways" - }, - { - "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" - } - ], - "stats": { - "chars": 11766, - "words": 1369, - "headings": 13, - "estimated_token_count_total": 2514 - }, - "hash": "sha256:dd784a5d2daebb9a885fe09f6a967e6c84958d96ddb38d8366eabe9d860fa539", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-customize-runtime-pallet-development-pallet-testing", - "title": "Pallet Testing", - "slug": "parachains-customize-runtime-pallet-development-pallet-testing", - "categories": [ - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime-pallet-development-pallet-testing.md", - "html_url": "https://docs.polkadot.com/parachains/customize-runtime/pallet-development/pallet-testing/", - "preview": "Unit testing in the Polkadot SDK helps ensure that the functions provided by a pallet behave as expected. It also confirms that data and events associated with a pallet are processed correctly during interactions. The Polkadot SDK offers a set of APIs to create a test environment to simulate runtime and mock transaction execution for extrinsics and queries.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Writing Unit Tests", - "anchor": "writing-unit-tests" - }, - { - "depth": 3, - "title": "Test Initialization", - "anchor": "test-initialization" - }, - { - "depth": 3, - "title": "Function Call Testing", - "anchor": "function-call-testing" - }, - { - "depth": 3, - "title": "Storage Testing", - "anchor": "storage-testing" - }, - { - "depth": 3, - "title": "Event Testing", - "anchor": "event-testing" - }, - { - "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" - } - ], - "stats": { - "chars": 6892, - "words": 911, - "headings": 7, - "estimated_token_count_total": 1563 - }, - "hash": "sha256:8568dfa238b9a649a4e6e60510625c2e7879b76a93187b0b8b8dccf6bc467ae6", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-customize-runtime", - "title": "Overview of FRAME", - "slug": "parachains-customize-runtime", - "categories": [ - "Basics", - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime.md", - "html_url": "https://docs.polkadot.com/parachains/customize-runtime/", - "preview": "A blockchain runtime is more than just a fixed set of rules—it's a dynamic foundation that you can shape to match your specific needs. With Polkadot SDK's [FRAME (Framework for Runtime Aggregation of Modularized Entities)](/reference/glossary/#frame-framework-for-runtime-aggregation-of-modularized-entities){target=\\_blank}, customizing your runtime is straightforward and modular. Instead of building everything from scratch, you combine pre-built pallets with your own custom logic to create a run", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Understanding Your Runtime", - "anchor": "understanding-your-runtime" - }, - { - "depth": 2, - "title": "Runtime Architecture", - "anchor": "runtime-architecture" - }, - { - "depth": 2, - "title": "Building Blocks: Pallets", - "anchor": "building-blocks-pallets" - }, - { - "depth": 3, - "title": "Pre-Built Pallets vs. Custom Pallets", - "anchor": "pre-built-pallets-vs-custom-pallets" - }, - { - "depth": 3, - "title": "Pallet Structure", - "anchor": "pallet-structure" - }, - { - "depth": 2, - "title": "How Runtime Customization Works", - "anchor": "how-runtime-customization-works" - }, - { - "depth": 2, - "title": "Starting Templates", - "anchor": "starting-templates" - }, - { - "depth": 2, - "title": "Key Customization Scenarios", - "anchor": "key-customization-scenarios" - } - ], - "stats": { - "chars": 8237, - "words": 1101, - "headings": 9, - "estimated_token_count_total": 1828 - }, - "hash": "sha256:28501589d5290f932b55cd3319f6a3fd78d7297ba42810da5ad2784a297224fd", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-get-started", - "title": "Get Started with Parachain Development", - "slug": "parachains-get-started", - "categories": [ - "Basics", - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-get-started.md", - "html_url": "https://docs.polkadot.com/parachains/get-started/", - "preview": "The following sections provide practical recipes for building parachains on Polkadot—each focused on specific development scenarios with step-by-step, hands-on examples.", - "outline": [ - { - "depth": 2, - "title": "Quick Start Guides", - "anchor": "quick-start-guides" - }, - { - "depth": 2, - "title": "Launch a Simple Parachain", - "anchor": "launch-a-simple-parachain" - }, - { - "depth": 2, - "title": "Customize Your Runtime", - "anchor": "customize-your-runtime" - }, - { - "depth": 3, - "title": "Pallet Development", - "anchor": "pallet-development" - }, - { - "depth": 2, - "title": "Testing", - "anchor": "testing" - }, - { - "depth": 2, - "title": "Runtime Upgrades and Maintenance", - "anchor": "runtime-upgrades-and-maintenance" - }, - { - "depth": 2, - "title": "Interoperability", - "anchor": "interoperability" - }, - { - "depth": 2, - "title": "Integrations", - "anchor": "integrations" - }, - { - "depth": 2, - "title": "Additional Resources", - "anchor": "additional-resources" - } - ], - "stats": { - "chars": 7941, - "words": 631, - "headings": 9, - "estimated_token_count_total": 2292 - }, - "hash": "sha256:759ed27cf3d473445e33141089b652082c42a2c59eb822d6b506146fd9555e13", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-install-polkadot-sdk", - "title": "Install Polkadot SDK", - "slug": "parachains-install-polkadot-sdk", - "categories": [ - "Basics", - "Tooling" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-install-polkadot-sdk.md", - "html_url": "https://docs.polkadot.com/parachains/install-polkadot-sdk/", - "preview": "This guide provides step-by-step instructions for installing the Polkadot SDK on macOS, Linux, and Windows. The installation process consists of two main parts:", - "outline": [ - { - "depth": 2, - "title": "Install Dependencies: macOS", - "anchor": "install-dependencies-macos" - }, - { - "depth": 3, - "title": "Before You Begin {: #before-you-begin-mac-os }", - "anchor": "before-you-begin-before-you-begin-mac-os" - }, - { - "depth": 3, - "title": "Install Homebrew", - "anchor": "install-homebrew" - }, - { - "depth": 3, - "title": "Support for Apple Silicon", - "anchor": "support-for-apple-silicon" - }, - { - "depth": 3, - "title": "Install Required Packages and Rust {: #install-required-packages-and-rust-mac-os }", - "anchor": "install-required-packages-and-rust-install-required-packages-and-rust-mac-os" - }, - { - "depth": 2, - "title": "Install Dependencies: Linux", - "anchor": "install-dependencies-linux" - }, - { - "depth": 3, - "title": "Before You Begin {: #before-you-begin-linux }", - "anchor": "before-you-begin-before-you-begin-linux" - }, - { - "depth": 3, - "title": "Install Required Packages and Rust {: #install-required-packages-and-rust-linux }", - "anchor": "install-required-packages-and-rust-install-required-packages-and-rust-linux" - }, - { - "depth": 2, - "title": "Install Dependencies: Windows (WSL)", - "anchor": "install-dependencies-windows-wsl" - }, - { - "depth": 3, - "title": "Before You Begin {: #before-you-begin-windows-wls }", - "anchor": "before-you-begin-before-you-begin-windows-wls" - }, - { - "depth": 3, - "title": "Set Up Windows Subsystem for Linux", - "anchor": "set-up-windows-subsystem-for-linux" - }, - { - "depth": 3, - "title": "Install Required Packages and Rust {: #install-required-packages-and-rust-windows-wls }", - "anchor": "install-required-packages-and-rust-install-required-packages-and-rust-windows-wls" - }, - { - "depth": 2, - "title": "Build the Polkadot SDK", - "anchor": "build-the-polkadot-sdk" - }, - { - "depth": 3, - "title": "Clone the Polkadot SDK", - "anchor": "clone-the-polkadot-sdk" - }, - { - "depth": 3, - "title": "Compile the Polkadot SDK", - "anchor": "compile-the-polkadot-sdk" - }, - { - "depth": 3, - "title": "Verify the Build", - "anchor": "verify-the-build" - }, - { - "depth": 2, - "title": "Optional: Run the Kitchensink Node", - "anchor": "optional-run-the-kitchensink-node" - }, - { - "depth": 3, - "title": "Run the Kitchensink Node in Development Mode", - "anchor": "run-the-kitchensink-node-in-development-mode" - }, - { - "depth": 3, - "title": "Interact with the Kitchensink Node", - "anchor": "interact-with-the-kitchensink-node" - }, - { - "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" - } - ], - "stats": { - "chars": 16051, - "words": 2312, - "headings": 20, - "estimated_token_count_total": 3345 - }, - "hash": "sha256:a52c05b623f3780f14be3a5f36b3d79a6c1965c2fbfd6864b512a9a70c47cd60", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-integrations-indexers", - "title": "Indexers", - "slug": "parachains-integrations-indexers", - "categories": [ - "Tooling", - "Dapps" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-indexers.md", - "html_url": "https://docs.polkadot.com/parachains/integrations/indexers/", - "preview": "Blockchain data is inherently sequential and distributed, with information stored chronologically across numerous blocks. While retrieving data from a single block through JSON-RPC API calls is straightforward, more complex queries that span multiple blocks present significant challenges:", - "outline": [ - { - "depth": 2, - "title": "The Challenge of Blockchain Data Access", - "anchor": "the-challenge-of-blockchain-data-access" - }, - { - "depth": 2, - "title": "What is a Blockchain Indexer?", - "anchor": "what-is-a-blockchain-indexer" - }, - { - "depth": 2, - "title": "Indexer Implementations", - "anchor": "indexer-implementations" - } - ], - "stats": { - "chars": 2230, - "words": 302, - "headings": 3, - "estimated_token_count_total": 428 - }, - "hash": "sha256:cfcc76bb24779c9b613f2c046b6f99a0f2529c25fd82287d804f6b945b936227", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-integrations-oracles", - "title": "Oracles", - "slug": "parachains-integrations-oracles", - "categories": [ - "Tooling", - "Dapps" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-oracles.md", - "html_url": "https://docs.polkadot.com/parachains/integrations/oracles/", - "preview": "Oracles enable blockchains to access external data sources. Since blockchains operate as isolated networks, they cannot natively interact with external systems - this limitation is known as the \"blockchain oracle problem.\" Oracles solves this by extracting data from external sources (like APIs, IoT devices, or other blockchains), validating it, and submitting it on-chain.", - "outline": [ - { - "depth": 2, - "title": "What is a Blockchain Oracle?", - "anchor": "what-is-a-blockchain-oracle" - }, - { - "depth": 2, - "title": "Oracle Implementations", - "anchor": "oracle-implementations" - } - ], - "stats": { - "chars": 1343, - "words": 181, - "headings": 2, - "estimated_token_count_total": 245 - }, - "hash": "sha256:6d8e01281a5895fd2bc4438b24c170c72a496de0b838626a53e87685aea4aa25", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-integrations-wallets", - "title": "Wallets", - "slug": "parachains-integrations-wallets", - "categories": [ - "Tooling", - "Dapps" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-wallets.md", - "html_url": "https://docs.polkadot.com/parachains/integrations/wallets/", - "preview": "A wallet serves as your gateway to interacting with blockchain networks. Rather than storing funds, wallets secure your private keys, controlling access to your blockchain assets. Your private key provides complete control over all permitted transactions on your blockchain account, making it essential to keep it secure.", - "outline": [ - { - "depth": 2, - "title": "What is a Blockchain Wallet?", - "anchor": "what-is-a-blockchain-wallet" - }, - { - "depth": 2, - "title": "Hot Wallets", - "anchor": "hot-wallets" - }, - { - "depth": 2, - "title": "Cold Wallets", - "anchor": "cold-wallets" - }, - { - "depth": 2, - "title": "Wallet Tools", - "anchor": "wallet-tools" - } - ], - "stats": { - "chars": 3588, - "words": 489, - "headings": 4, - "estimated_token_count_total": 786 - }, - "hash": "sha256:1c65342056983806d639fb8393fdfbdf2ef644ffd41ed749947a16fb3839753d", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-interoperability-channels-between-parachains", - "title": "Opening HRMP Channels Between Parachains", - "slug": "parachains-interoperability-channels-between-parachains", - "categories": [ - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-channels-between-parachains.md", - "html_url": "https://docs.polkadot.com/parachains/interoperability/channels-between-parachains/", - "preview": "For establishing communication channels between parachains on the Polkadot network using the Horizontal Relay-routed Message Passing (HRMP) protocol, the following steps are required:", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" - }, - { - "depth": 2, - "title": "Procedure to Initiate an HRMP Channel", - "anchor": "procedure-to-initiate-an-hrmp-channel" - }, - { - "depth": 3, - "title": "Fund Sender Sovereign Account", - "anchor": "fund-sender-sovereign-account" - }, - { - "depth": 3, - "title": "Create Channel Opening Extrinsic", - "anchor": "create-channel-opening-extrinsic" - }, - { - "depth": 3, - "title": "Craft and Submit the XCM Message from the Sender", - "anchor": "craft-and-submit-the-xcm-message-from-the-sender" - }, - { - "depth": 2, - "title": "Procedure to Accept an HRMP Channel", - "anchor": "procedure-to-accept-an-hrmp-channel" - }, - { - "depth": 3, - "title": "Fund Receiver Sovereign Account", - "anchor": "fund-receiver-sovereign-account" - }, - { - "depth": 3, - "title": "Create Channel Accepting Extrinsic", - "anchor": "create-channel-accepting-extrinsic" - }, - { - "depth": 3, - "title": "Craft and Submit the XCM Message from the Receiver", - "anchor": "craft-and-submit-the-xcm-message-from-the-receiver" - } - ], - "stats": { - "chars": 10934, - "words": 1549, - "headings": 10, - "estimated_token_count_total": 2285 - }, - "hash": "sha256:b8de1228b9976765accd18ff724038bed6f2449367f500bc3177ab2a053abe63", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-interoperability-channels-with-system-parachains", - "title": "Opening HRMP Channels with System Parachains", - "slug": "parachains-interoperability-channels-with-system-parachains", - "categories": [ - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-channels-with-system-parachains.md", - "html_url": "https://docs.polkadot.com/parachains/interoperability/channels-with-system-parachains/", - "preview": "While establishing Horizontal Relay-routed Message Passing (HRMP) channels between regular parachains involves a two-step request and acceptance procedure, opening channels with system parachains follows a more straightforward approach.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" - }, - { - "depth": 2, - "title": "Procedure to Establish an HRMP Channel", - "anchor": "procedure-to-establish-an-hrmp-channel" - }, - { - "depth": 3, - "title": "Fund Parachain Sovereign Account", - "anchor": "fund-parachain-sovereign-account" - }, - { - "depth": 3, - "title": "Create Establish Channel with System Extrinsic", - "anchor": "create-establish-channel-with-system-extrinsic" - }, - { - "depth": 3, - "title": "Craft and Submit the XCM Message", - "anchor": "craft-and-submit-the-xcm-message" - } - ], - "stats": { - "chars": 7203, - "words": 889, - "headings": 6, - "estimated_token_count_total": 1427 - }, - "hash": "sha256:b501d99c464fb049d46676827b6a325a195c90617becc4a7db305441c115350a", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-interoperability-get-started", - "title": "Introduction to XCM", - "slug": "parachains-interoperability-get-started", - "categories": [ - "Basics", - "Polkadot Protocol" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md", - "html_url": "https://docs.polkadot.com/parachains/interoperability/get-started/", - "preview": "Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Messaging Format", - "anchor": "messaging-format" - }, - { - "depth": 2, - "title": "The Four Principles of XCM", - "anchor": "the-four-principles-of-xcm" - }, - { - "depth": 2, - "title": "The XCM Tech Stack", - "anchor": "the-xcm-tech-stack" - }, - { - "depth": 2, - "title": "Core Functionalities of XCM", - "anchor": "core-functionalities-of-xcm" - }, - { - "depth": 2, - "title": "XCM Example", - "anchor": "xcm-example" - }, - { - "depth": 2, - "title": "Overview", - "anchor": "overview" - } - ], - "stats": { - "chars": 7450, - "words": 974, - "headings": 7, - "estimated_token_count_total": 1501 - }, - "hash": "sha256:3b26606dd5310c4b8ade5d05270ebf1e06f59afcda4ca2b985e07948215a197e", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-launch-a-parachain-deploy-to-polkadot", - "title": "Deploy on Polkadot", - "slug": "parachains-launch-a-parachain-deploy-to-polkadot", - "categories": [ - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-launch-a-parachain-deploy-to-polkadot.md", - "html_url": "https://docs.polkadot.com/parachains/launch-a-parachain/deploy-to-polkadot/", - "preview": "Previously, you learned how to [choose and set up a parachain template](/parachains/launch-a-parachain/choose-a-template/){target=\\_blank}. Now, you'll take the next step towards a production-like environment by deploying your parachain to the Polkadot TestNet. Deploying to a TestNet is a crucial step for validating your parachain's functionality and preparing it for eventual MainNet deployment.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Get Started with an Account and Tokens", - "anchor": "get-started-with-an-account-and-tokens" - }, - { - "depth": 2, - "title": "Reserve a Parachain Identifier", - "anchor": "reserve-a-parachain-identifier" - }, - { - "depth": 2, - "title": "Generate Custom Keys for Your Collators", - "anchor": "generate-custom-keys-for-your-collators" - }, - { - "depth": 2, - "title": "Generate the Chain Specification", - "anchor": "generate-the-chain-specification" - }, - { - "depth": 2, - "title": "Export Required Files", - "anchor": "export-required-files" - }, - { - "depth": 2, - "title": "Register a Parathread", - "anchor": "register-a-parathread" - }, - { - "depth": 2, - "title": "Start the Collator Node", - "anchor": "start-the-collator-node" - }, - { - "depth": 2, - "title": "Producing Blocks", - "anchor": "producing-blocks" - } - ], - "stats": { - "chars": 20252, - "words": 2357, - "headings": 9, - "estimated_token_count_total": 4129 - }, - "hash": "sha256:7309d3487c653951bf264013eb3402a72a1cbb5e0b6f89ae4e678f239cd63b80", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-launch-a-parachain-obtain-coretime", - "title": "Obtain Coretime", - "slug": "parachains-launch-a-parachain-obtain-coretime", - "categories": [ - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-launch-a-parachain-obtain-coretime.md", - "html_url": "https://docs.polkadot.com/parachains/launch-a-parachain/obtain-coretime/", - "preview": "After deploying a parachain to Paseo in the [Deploy on Polkadot](/parachains/launch-a-parachain/deploy-to-polkadot/){target=\\_blank} tutorial, the next critical step is obtaining coretime. Coretime is the mechanism through which validation resources are allocated from the relay chain to your parachain. Your parachain can only produce and finalize blocks on the relay chain by obtaining coretime.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" - }, - { - "depth": 2, - "title": "Order On-Demand Coretime", - "anchor": "order-on-demand-coretime" - }, - { - "depth": 3, - "title": "On-Demand Extrinsics", - "anchor": "on-demand-extrinsics" - }, - { - "depth": 3, - "title": "Place an On-Demand Order", - "anchor": "place-an-on-demand-order" - }, - { - "depth": 2, - "title": "Purchase Bulk Coretime", - "anchor": "purchase-bulk-coretime" - }, - { - "depth": 3, - "title": "Connect Your Wallet to RegionX", - "anchor": "connect-your-wallet-to-regionx" - }, - { - "depth": 3, - "title": "Obtain Coretime Chain Funds", - "anchor": "obtain-coretime-chain-funds" - }, - { - "depth": 3, - "title": "Purchase a Core", - "anchor": "purchase-a-core" - }, - { - "depth": 3, - "title": "Verify Your Purchase", - "anchor": "verify-your-purchase" - }, - { - "depth": 3, - "title": "Assign Your Parachain to the Core", - "anchor": "assign-your-parachain-to-the-core" - }, - { - "depth": 2, - "title": "Next Steps", - "anchor": "next-steps" - } - ], - "stats": { - "chars": 9049, - "words": 1345, - "headings": 12, - "estimated_token_count_total": 2103 - }, - "hash": "sha256:15154f211753665d9af70dc81d15ceb3f0954e3febf9282c68c0074881d620c6", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-launch-a-parachain-set-up-the-parachain-template", - "title": "Set Up the Polkadot SDK Parachain Template", - "slug": "parachains-launch-a-parachain-set-up-the-parachain-template", - "categories": [ - "Basics", - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-launch-a-parachain-set-up-the-parachain-template.md", - "html_url": "https://docs.polkadot.com/parachains/launch-a-parachain/set-up-the-parachain-template/", - "preview": "The [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\\_blank} includes several [templates](/parachains/customize-runtime/#starting-templates){target=\\_blank} designed to help you quickly start building your own blockchain. Each template offers a different level of configuration, from minimal setups to feature-rich environments, allowing you to choose the foundation that best fits your project's needs.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" - }, - { - "depth": 2, - "title": "Polkadot SDK Utility Tools", - "anchor": "polkadot-sdk-utility-tools" - }, - { - "depth": 2, - "title": "Clone the Template", - "anchor": "clone-the-template" - }, - { - "depth": 2, - "title": "Explore the Project Structure", - "anchor": "explore-the-project-structure" - }, - { - "depth": 2, - "title": "Compile the Runtime", - "anchor": "compile-the-runtime" - }, - { - "depth": 2, - "title": "Verify the Build", - "anchor": "verify-the-build" - }, - { - "depth": 2, - "title": "Run the Node Locally", - "anchor": "run-the-node-locally" - }, - { - "depth": 2, - "title": "Interact with the Node", - "anchor": "interact-with-the-node" - }, - { - "depth": 2, - "title": "Stop the Node", - "anchor": "stop-the-node" - }, - { - "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" - } - ], - "stats": { - "chars": 10588, - "words": 1510, - "headings": 11, - "estimated_token_count_total": 2375 - }, - "hash": "sha256:380063fe7c00ae8bde05fa76688b8ae4902e6566147f1cfe0e0260ad1aa05aa6", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-runtime-maintenance-runtime-upgrades", - "title": "Runtime Upgrades", - "slug": "parachains-runtime-maintenance-runtime-upgrades", - "categories": [ - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-runtime-maintenance-runtime-upgrades.md", - "html_url": "https://docs.polkadot.com/parachains/runtime-maintenance/runtime-upgrades/", - "preview": "One of the defining features of Polkadot SDK-based blockchains is the ability to perform forkless runtime upgrades. Unlike traditional blockchains, which require hard forks and node coordination for upgrades, Polkadot networks enable seamless updates without network disruption.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "How Runtime Upgrades Work", - "anchor": "how-runtime-upgrades-work" - }, - { - "depth": 3, - "title": "Runtime Versioning", - "anchor": "runtime-versioning" - }, - { - "depth": 3, - "title": "Accessing the Runtime Version", - "anchor": "accessing-the-runtime-version" - }, - { - "depth": 2, - "title": "Storage Migrations", - "anchor": "storage-migrations" - } - ], - "stats": { - "chars": 5837, - "words": 811, - "headings": 5, - "estimated_token_count_total": 1161 - }, - "hash": "sha256:ec31270001a6cd9d0a8ecb7974ad161d5c1ef4d3023d5a6af9fbc5a6ca46cbca", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-runtime-maintenance-storage-migrations", - "title": "Storage Migrations", - "slug": "parachains-runtime-maintenance-storage-migrations", - "categories": [ - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-runtime-maintenance-storage-migrations.md", - "html_url": "https://docs.polkadot.com/parachains/runtime-maintenance/storage-migrations/", - "preview": "Storage migrations are a crucial part of the runtime upgrade process. They allow you to update the [storage items](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/attr.storage.html){target=\\_blank} of your blockchain, adapting to changes in the runtime. Whenever you change the encoding or data types used to represent data in storage, you'll need to provide a storage migration to ensure the runtime can correctly interpret the existing stored values in the new runtime", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Storage Migration Scenarios", - "anchor": "storage-migration-scenarios" - }, - { - "depth": 2, - "title": "Implement Storage Migrations", - "anchor": "implement-storage-migrations" - }, - { - "depth": 3, - "title": "Core Migration Function", - "anchor": "core-migration-function" - }, - { - "depth": 3, - "title": "Migration Testing Hooks", - "anchor": "migration-testing-hooks" - }, - { - "depth": 3, - "title": "Migration Structure", - "anchor": "migration-structure" - }, - { - "depth": 3, - "title": "Migration Organization", - "anchor": "migration-organization" - }, - { - "depth": 3, - "title": "Scheduling Migrations", - "anchor": "scheduling-migrations" - }, - { - "depth": 2, - "title": "Single-Block Migrations", - "anchor": "single-block-migrations" - }, - { - "depth": 2, - "title": "Multi Block Migrations", - "anchor": "multi-block-migrations" - } - ], - "stats": { - "chars": 18500, - "words": 2363, - "headings": 10, - "estimated_token_count_total": 4014 - }, - "hash": "sha256:55dc252fdecf1590048ce8d009b822e90231442abe81e9593cf1635944a31336", - "token_estimator": "heuristic-v1" - }, - { - "id": "parachains-runtime-maintenance-unlock-parachains", - "title": "Unlock a Parachain", - "slug": "parachains-runtime-maintenance-unlock-parachains", - "categories": [ - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-runtime-maintenance-unlock-parachains.md", - "html_url": "https://docs.polkadot.com/parachains/runtime-maintenance/unlock-parachains/", - "preview": "Parachain locks are a critical security mechanism in the Polkadot ecosystem designed to maintain decentralization during the parachain lifecycle. These locks prevent potential centralization risks that could emerge during the early stages of parachain operation.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" + "title": "Node Key", + "anchor": "node-key" }, { "depth": 2, - "title": "Check If the Parachain Is Locked", - "anchor": "check-if-the-parachain-is-locked" + "title": "Running the Bootnode", + "anchor": "running-the-bootnode" }, { "depth": 2, - "title": "How to Unlock a Parachain", - "anchor": "how-to-unlock-a-parachain" + "title": "Testing Bootnode Connection", + "anchor": "testing-bootnode-connection" }, { "depth": 3, - "title": "Prepare the Unlock Call", - "anchor": "prepare-the-unlock-call" + "title": "P2P", + "anchor": "p2p" }, { "depth": 3, - "title": "Fund the Sovereign Account", - "anchor": "fund-the-sovereign-account" + "title": "P2P/WS", + "anchor": "p2pws" }, { "depth": 3, - "title": "Craft and Submit the XCM", - "anchor": "craft-and-submit-the-xcm" + "title": "P2P/WSS", + "anchor": "p2pwss" } ], "stats": { - "chars": 9232, - "words": 1276, - "headings": 6, - "estimated_token_count_total": 2028 + "chars": 4538, + "words": 647, + "headings": 9, + "estimated_token_count_total": 1044 }, - "hash": "sha256:e408d05199cc184fc6fe8bb212efb3c9aa6cb79258977e07566692176c912def", + "hash": "sha256:d84a5af1a0237a911d25a68c077f508ebbce608f673ef4f9055e8e434daa96b9", "token_estimator": "heuristic-v1" }, { - "id": "parachains-testing-fork-a-parachain", - "title": "Get Started", - "slug": "parachains-testing-fork-a-parachain", + "id": "nodes-and-validators-run-a-node-full-node", + "title": "Set Up a Node", + "slug": "nodes-and-validators-run-a-node-full-node", "categories": [ - "Parachains", - "Tooling" + "Infrastructure" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-fork-a-parachain.md", - "html_url": "https://docs.polkadot.com/parachains/testing/fork-a-parachain/", - "preview": "[Chopsticks](https://github.com/AcalaNetwork/chopsticks/){target=\\_blank}, developed by the [Acala Foundation](https://github.com/AcalaNetwork){target=\\_blank}, is a versatile tool tailored for developers working on Polkadot SDK-based blockchains. With Chopsticks, you can fork live chains locally, replay blocks to analyze extrinsics, and simulate complex scenarios like XCM interactions all without deploying to a live network.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-node-full-node.md", + "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-node/full-node/", + "preview": "Running a node on Polkadot provides direct interaction with the network, enhanced privacy, and full control over RPC requests, transactions, and data queries. As the backbone of the network, nodes ensure decentralized data propagation, transaction validation, and seamless communication across the ecosystem.", "outline": [ { "depth": 2, @@ -3456,70 +282,64 @@ }, { "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" + "title": "Set Up a Node", + "anchor": "set-up-a-node" }, { - "depth": 2, - "title": "Install Chopsticks", - "anchor": "install-chopsticks" + "depth": 3, + "title": "Prerequisites", + "anchor": "prerequisites" }, { "depth": 3, - "title": "Global Installation", - "anchor": "global-installation" + "title": "Install and Build the Polkadot Binary", + "anchor": "install-and-build-the-polkadot-binary" }, { "depth": 3, - "title": "Local Installation", - "anchor": "local-installation" + "title": "Use Docker", + "anchor": "use-docker" }, { "depth": 2, - "title": "Configure Chopsticks", - "anchor": "configure-chopsticks" - }, - { - "depth": 3, - "title": "Configuration File", - "anchor": "configuration-file" + "title": "Configure and Run Your Node", + "anchor": "configure-and-run-your-node" }, { "depth": 3, - "title": "CLI Flags", - "anchor": "cli-flags" + "title": "RPC Configurations", + "anchor": "rpc-configurations" }, { "depth": 2, - "title": "WebSocket Commands", - "anchor": "websocket-commands" + "title": "Sync Your Node", + "anchor": "sync-your-node" }, { - "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" + "depth": 3, + "title": "Connect to Your Node", + "anchor": "connect-to-your-node" } ], "stats": { - "chars": 10894, - "words": 1330, - "headings": 10, - "estimated_token_count_total": 2614 + "chars": 15944, + "words": 2481, + "headings": 9, + "estimated_token_count_total": 4196 }, - "hash": "sha256:4325cdd697814b8043db808da3dee86d3d9c6fc7dd523aae7fe8914d59d1b39c", + "hash": "sha256:924fab837818610c825be5cefde0a7bacd46985b4fa05cfa0376a941105b9869", "token_estimator": "heuristic-v1" }, { - "id": "parachains-testing-run-a-parachain-network", - "title": "Get Started", - "slug": "parachains-testing-run-a-parachain-network", + "id": "nodes-and-validators-run-a-node-secure-wss", + "title": "Set Up Secure WebSocket", + "slug": "nodes-and-validators-run-a-node-secure-wss", "categories": [ - "Parachains", - "Tooling" + "Infrastructure" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-run-a-parachain-network.md", - "html_url": "https://docs.polkadot.com/parachains/testing/run-a-parachain-network/", - "preview": "Zombienet is a robust testing framework designed for Polkadot SDK-based blockchain networks. It enables developers to efficiently deploy and test ephemeral blockchain environments on platforms like Kubernetes, Podman, and native setups. With its simple and versatile CLI, Zombienet provides an all-in-one solution for spawning networks, running tests, and validating performance.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-node-secure-wss.md", + "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-node/secure-wss/", + "preview": "Ensuring secure WebSocket communication is crucial for maintaining the integrity and security of a Polkadot or Kusama node when interacting with remote clients. This guide walks you through setting up a secure WebSocket (WSS) connection for your node by leveraging SSL encryption with popular web server proxies like nginx or Apache.", "outline": [ { "depth": 2, @@ -3528,425 +348,490 @@ }, { "depth": 2, - "title": "Install Zombienet", - "anchor": "install-zombienet" - }, - { - "depth": 2, - "title": "Providers", - "anchor": "providers" - }, - { - "depth": 3, - "title": "Kubernetes", - "anchor": "kubernetes" - }, - { - "depth": 3, - "title": "Podman", - "anchor": "podman" + "title": "Secure a WebSocket Port", + "anchor": "secure-a-websocket-port" }, { "depth": 3, - "title": "Local Provider", - "anchor": "local-provider" + "title": "Obtain an SSL Certificate", + "anchor": "obtain-an-ssl-certificate" }, { "depth": 2, - "title": "Configure Zombienet", - "anchor": "configure-zombienet" - }, - { - "depth": 3, - "title": "Configuration Files", - "anchor": "configuration-files" - }, - { - "depth": 3, - "title": "CLI Usage", - "anchor": "cli-usage" - }, - { - "depth": 3, - "title": "Settings", - "anchor": "settings" - }, - { - "depth": 3, - "title": "Relay Chain Configuration", - "anchor": "relay-chain-configuration" + "title": "Install a Proxy Server", + "anchor": "install-a-proxy-server" }, { "depth": 3, - "title": "Parachain Configuration", - "anchor": "parachain-configuration" + "title": "Use nginx", + "anchor": "use-nginx" }, { "depth": 3, - "title": "XCM Configuration", - "anchor": "xcm-configuration" + "title": "Use Apache2", + "anchor": "use-apache2" }, { "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" + "title": "Connect to the Node", + "anchor": "connect-to-the-node" } ], "stats": { - "chars": 41636, - "words": 4599, - "headings": 14, - "estimated_token_count_total": 9871 + "chars": 5568, + "words": 774, + "headings": 7, + "estimated_token_count_total": 1280 }, - "hash": "sha256:0d7e04fd952cc9d5bd8cdbfd87cc4004c5f95e896a16bc7f89dfc4caeac8f371", + "hash": "sha256:992082e4ad87348b283f6c37ea886ae0e7bf016852b6470000876f3d169c65a4", "token_estimator": "heuristic-v1" }, { - "id": "reference-glossary", - "title": "Glossary", - "slug": "reference-glossary", + "id": "nodes-and-validators-run-a-validator-onboarding-and-offboarding-key-management", + "title": "Validator Key Management", + "slug": "nodes-and-validators-run-a-validator-onboarding-and-offboarding-key-management", "categories": [ - "Reference" + "Infrastructure" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-glossary.md", - "html_url": "https://docs.polkadot.com/reference/glossary/", - "preview": "Key definitions, concepts, and terminology specific to the Polkadot ecosystem are included here.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-onboarding-and-offboarding-key-management.md", + "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/onboarding-and-offboarding/key-management/", + "preview": "After setting up your node environment as shown in the [Setup](/nodes-and-validators/run-a-validator/onboarding-and-offboarding/set-up-validator/){target=\\_blank} section, you'll need to configure multiple keys for your validator to operate properly. This includes setting up session keys, which are essential for participating in the consensus process, and configuring a node key that maintains a stable network identity. This guide walks you through the key management process, showing you how to g", "outline": [ { "depth": 2, - "title": "Authority", - "anchor": "authority" - }, - { - "depth": 2, - "title": "Authority Round (Aura)", - "anchor": "authority-round-aura" + "title": "Introduction", + "anchor": "introduction" }, { "depth": 2, - "title": "Blind Assignment of Blockchain Extension (BABE)", - "anchor": "blind-assignment-of-blockchain-extension-babe" + "title": "Set Session Keys", + "anchor": "set-session-keys" }, { - "depth": 2, - "title": "Block Author", - "anchor": "block-author" + "depth": 3, + "title": "Generate Session Keys", + "anchor": "generate-session-keys" }, { - "depth": 2, - "title": "Byzantine Fault Tolerance (BFT)", - "anchor": "byzantine-fault-tolerance-bft" + "depth": 3, + "title": "Submit Transaction to Set Keys", + "anchor": "submit-transaction-to-set-keys" }, { "depth": 3, - "title": "Byzantine Failure", - "anchor": "byzantine-failure" + "title": "Verify Session Key Setup", + "anchor": "verify-session-key-setup" }, { - "depth": 3, - "title": "Practical Byzantine Fault Tolerance (pBFT)", - "anchor": "practical-byzantine-fault-tolerance-pbft" + "depth": 2, + "title": "Set the Node Key", + "anchor": "set-the-node-key" }, { "depth": 3, - "title": "Preimage", - "anchor": "preimage" + "title": "Generate the Node Key", + "anchor": "generate-the-node-key" }, { - "depth": 2, - "title": "Call", - "anchor": "call" - }, + "depth": 3, + "title": "Set Node Key", + "anchor": "set-node-key" + } + ], + "stats": { + "chars": 8227, + "words": 1183, + "headings": 8, + "estimated_token_count_total": 1840 + }, + "hash": "sha256:0fb5a83835aab263c0b9aa886028c8aa8a2d6d0897d7b9fff4b5258835d30dfe", + "token_estimator": "heuristic-v1" + }, + { + "id": "nodes-and-validators-run-a-validator-onboarding-and-offboarding-set-up-validator", + "title": "Set Up a Validator", + "slug": "nodes-and-validators-run-a-validator-onboarding-and-offboarding-set-up-validator", + "categories": [ + "Infrastructure" + ], + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-onboarding-and-offboarding-set-up-validator.md", + "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/onboarding-and-offboarding/set-up-validator/", + "preview": "Setting up a Polkadot validator node is essential for securing the network and earning staking rewards. This guide walks you through the technical steps to set up a validator, from installing the necessary software to managing keys and synchronizing your node with the chain.", + "outline": [ { "depth": 2, - "title": "Chain Specification", - "anchor": "chain-specification" + "title": "Introduction", + "anchor": "introduction" }, { "depth": 2, - "title": "Collator", - "anchor": "collator" + "title": "Prerequisites", + "anchor": "prerequisites" }, { "depth": 2, - "title": "Collective", - "anchor": "collective" + "title": "Initial Setup", + "anchor": "initial-setup" }, { - "depth": 2, - "title": "Consensus", - "anchor": "consensus" + "depth": 3, + "title": "Install Network Time Protocol Client", + "anchor": "install-network-time-protocol-client" }, { - "depth": 2, - "title": "Consensus Algorithm", - "anchor": "consensus-algorithm" + "depth": 3, + "title": "Verify Landlock is Activated", + "anchor": "verify-landlock-is-activated" }, { "depth": 2, - "title": "Consensus Engine", - "anchor": "consensus-engine" + "title": "Install the Polkadot Binaries", + "anchor": "install-the-polkadot-binaries" }, { - "depth": 2, - "title": "Coretime", - "anchor": "coretime" + "depth": 3, + "title": "Install from Official Releases", + "anchor": "install-from-official-releases" }, { - "depth": 2, - "title": "Development Phrase", - "anchor": "development-phrase" + "depth": 3, + "title": "Install with Package Managers", + "anchor": "install-with-package-managers" }, { - "depth": 2, - "title": "Digest", - "anchor": "digest" + "depth": 3, + "title": "Install with Ansible", + "anchor": "install-with-ansible" }, { - "depth": 2, - "title": "Dispatchable", - "anchor": "dispatchable" + "depth": 3, + "title": "Install with Docker", + "anchor": "install-with-docker" }, { - "depth": 2, - "title": "Events", - "anchor": "events" + "depth": 3, + "title": "Build from Sources", + "anchor": "build-from-sources" }, { "depth": 2, - "title": "Executor", - "anchor": "executor" - }, + "title": "Verify Installation", + "anchor": "verify-installation" + } + ], + "stats": { + "chars": 11921, + "words": 1678, + "headings": 12, + "estimated_token_count_total": 2592 + }, + "hash": "sha256:d2c1c91734bc8185057d8eeec6829ea91e0316f7ba884c5dc3922a5e5778815e", + "token_estimator": "heuristic-v1" + }, + { + "id": "nodes-and-validators-run-a-validator-onboarding-and-offboarding-start-validating", + "title": "Start Validating", + "slug": "nodes-and-validators-run-a-validator-onboarding-and-offboarding-start-validating", + "categories": [ + "Infrastructure" + ], + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-onboarding-and-offboarding-start-validating.md", + "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/onboarding-and-offboarding/start-validating/", + "preview": "After configuring your node keys as shown in the [Key Management](/nodes-and-validators/run-a-validator/onboarding-and-offboarding/key-management/){target=\\_blank} section and ensuring your system is set up, you're ready to begin the validator setup process. This guide will walk you through choosing a network, synchronizing your node with the blockchain, bonding your DOT tokens, and starting your validator.", + "outline": [ { "depth": 2, - "title": "Existential Deposit", - "anchor": "existential-deposit" + "title": "Introduction", + "anchor": "introduction" }, { "depth": 2, - "title": "Extrinsic", - "anchor": "extrinsic" + "title": "Choose a Network", + "anchor": "choose-a-network" }, { "depth": 2, - "title": "Fork Choice Rule/Strategy", - "anchor": "fork-choice-rulestrategy" + "title": "Synchronize Chain Data", + "anchor": "synchronize-chain-data" }, { - "depth": 2, - "title": "FRAME (Framework for Runtime Aggregation of Modularized Entities)", - "anchor": "frame-framework-for-runtime-aggregation-of-modularized-entities" + "depth": 3, + "title": "Database Snapshot Services", + "anchor": "database-snapshot-services" }, { "depth": 2, - "title": "Full Node", - "anchor": "full-node" + "title": "Bond DOT", + "anchor": "bond-dot" }, { - "depth": 2, - "title": "Genesis Configuration", - "anchor": "genesis-configuration" + "depth": 3, + "title": "Bonding DOT on Polkadot.js Apps", + "anchor": "bonding-dot-on-polkadotjs-apps" }, { "depth": 2, - "title": "GRANDPA", - "anchor": "grandpa" + "title": "Validate", + "anchor": "validate" }, { - "depth": 2, - "title": "Header", - "anchor": "header" + "depth": 3, + "title": "Verify Sync via Telemetry", + "anchor": "verify-sync-via-telemetry" }, { - "depth": 2, - "title": "Hybrid Consensus", - "anchor": "hybrid-consensus" + "depth": 3, + "title": "Activate using Polkadot.js Apps", + "anchor": "activate-using-polkadotjs-apps" }, { - "depth": 2, - "title": "Inherent Transactions", - "anchor": "inherent-transactions" + "depth": 3, + "title": "Monitor Validation Status and Slots", + "anchor": "monitor-validation-status-and-slots" }, { "depth": 2, - "title": "JSON-RPC", - "anchor": "json-rpc" + "title": "Run a Validator Using Systemd", + "anchor": "run-a-validator-using-systemd" }, { - "depth": 2, - "title": "Keystore", - "anchor": "keystore" + "depth": 3, + "title": "Create the Systemd Service File", + "anchor": "create-the-systemd-service-file" }, { - "depth": 2, - "title": "Kusama", - "anchor": "kusama" - }, + "depth": 3, + "title": "Run the Service", + "anchor": "run-the-service" + } + ], + "stats": { + "chars": 15820, + "words": 2446, + "headings": 13, + "estimated_token_count_total": 3861 + }, + "hash": "sha256:67a43e787805244196e1e9cb962069292c69ed5fdb1110df57c942019892b953", + "token_estimator": "heuristic-v1" + }, + { + "id": "nodes-and-validators-run-a-validator-onboarding-and-offboarding-stop-validating", + "title": "Stop Validating", + "slug": "nodes-and-validators-run-a-validator-onboarding-and-offboarding-stop-validating", + "categories": [ + "Infrastructure" + ], + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-onboarding-and-offboarding-stop-validating.md", + "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/onboarding-and-offboarding/stop-validating/", + "preview": "If you're ready to stop validating on Polkadot, there are essential steps to ensure a smooth transition while protecting your funds and account integrity. Whether you're taking a break for maintenance or unbonding entirely, you'll need to chill your validator, purge session keys, and unbond your tokens. This guide explains how to use Polkadot's tools and extrinsics to safely withdraw from validation activities, safeguarding your account's future usability.", + "outline": [ { "depth": 2, - "title": "libp2p", - "anchor": "libp2p" + "title": "Introduction", + "anchor": "introduction" }, { "depth": 2, - "title": "Light Client", - "anchor": "light-client" + "title": "Pause Versus Stop", + "anchor": "pause-versus-stop" }, { "depth": 2, - "title": "Metadata", - "anchor": "metadata" + "title": "Chill Validator", + "anchor": "chill-validator" }, { "depth": 2, - "title": "Nominated Proof of Stake (NPoS)", - "anchor": "nominated-proof-of-stake-npos" + "title": "Purge Validator Session Keys", + "anchor": "purge-validator-session-keys" }, { "depth": 2, - "title": "Oracle", - "anchor": "oracle" - }, + "title": "Unbond Your Tokens", + "anchor": "unbond-your-tokens" + } + ], + "stats": { + "chars": 3230, + "words": 500, + "headings": 5, + "estimated_token_count_total": 629 + }, + "hash": "sha256:0d6db361bfa7a3022849bbe39989bfdac0429537498d7f534adadec131afca98", + "token_estimator": "heuristic-v1" + }, + { + "id": "nodes-and-validators-run-a-validator-operational-tasks-general-management", + "title": "General Management", + "slug": "nodes-and-validators-run-a-validator-operational-tasks-general-management", + "categories": [ + "Infrastructure" + ], + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-operational-tasks-general-management.md", + "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/operational-tasks/general-management/", + "preview": "Validator performance is pivotal in maintaining the security and stability of the Polkadot network. As a validator, optimizing your setup ensures efficient transaction processing, minimizes latency, and maintains system reliability during high-demand periods. Proper configuration and proactive monitoring also help mitigate risks like slashing and service interruptions.", + "outline": [ { "depth": 2, - "title": "Origin", - "anchor": "origin" + "title": "Introduction", + "anchor": "introduction" }, { "depth": 2, - "title": "Pallet", - "anchor": "pallet" + "title": "Configuration Optimization", + "anchor": "configuration-optimization" }, { - "depth": 2, - "title": "Parachain", - "anchor": "parachain" + "depth": 3, + "title": "Deactivate Simultaneous Multithreading", + "anchor": "deactivate-simultaneous-multithreading" }, { - "depth": 2, - "title": "Paseo", - "anchor": "paseo" + "depth": 3, + "title": "Deactivate Automatic NUMA Balancing", + "anchor": "deactivate-automatic-numa-balancing" }, { - "depth": 2, - "title": "Polkadot", - "anchor": "polkadot" + "depth": 3, + "title": "Spectre and Meltdown Mitigations", + "anchor": "spectre-and-meltdown-mitigations" }, { "depth": 2, - "title": "Polkadot Cloud", - "anchor": "polkadot-cloud" + "title": "Monitor Your Node", + "anchor": "monitor-your-node" }, { - "depth": 2, - "title": "Polkadot Hub", - "anchor": "polkadot-hub" + "depth": 3, + "title": "Environment Setup", + "anchor": "environment-setup" }, { - "depth": 2, - "title": "PolkaVM", - "anchor": "polkavm" + "depth": 3, + "title": "Install and Configure Prometheus", + "anchor": "install-and-configure-prometheus" }, { - "depth": 2, - "title": "Relay Chain", - "anchor": "relay-chain" + "depth": 3, + "title": "Start Prometheus", + "anchor": "start-prometheus" }, { - "depth": 2, - "title": "Rococo", - "anchor": "rococo" + "depth": 3, + "title": "Install and Configure Grafana", + "anchor": "install-and-configure-grafana" }, { - "depth": 2, - "title": "Runtime", - "anchor": "runtime" + "depth": 3, + "title": "Install and Configure Alertmanager", + "anchor": "install-and-configure-alertmanager" }, { "depth": 2, - "title": "Slot", - "anchor": "slot" + "title": "Secure Your Validator", + "anchor": "secure-your-validator" }, { - "depth": 2, - "title": "Sovereign Account", - "anchor": "sovereign-account" + "depth": 3, + "title": "Key Management", + "anchor": "key-management" }, { - "depth": 2, - "title": "SS58 Address Format", - "anchor": "ss58-address-format" + "depth": 3, + "title": "Signing Outside the Client", + "anchor": "signing-outside-the-client" }, { - "depth": 2, - "title": "State Transition Function (STF)", - "anchor": "state-transition-function-stf" + "depth": 3, + "title": "Secure-Validator Mode", + "anchor": "secure-validator-mode" }, { - "depth": 2, - "title": "Storage Item", - "anchor": "storage-item" + "depth": 3, + "title": "Linux Best Practices", + "anchor": "linux-best-practices" }, { - "depth": 2, - "title": "Substrate", - "anchor": "substrate" + "depth": 3, + "title": "Validator Best Practices", + "anchor": "validator-best-practices" }, { "depth": 2, - "title": "Transaction", - "anchor": "transaction" - }, + "title": "Additional Resources", + "anchor": "additional-resources" + } + ], + "stats": { + "chars": 26673, + "words": 3357, + "headings": 18, + "estimated_token_count_total": 5866 + }, + "hash": "sha256:81eb0fe77f05155f1ec0511cd066120fc9994961e9d91e21b6666377e65b4586", + "token_estimator": "heuristic-v1" + }, + { + "id": "nodes-and-validators-run-a-validator-operational-tasks-pause-validating", + "title": "Pause Validating", + "slug": "nodes-and-validators-run-a-validator-operational-tasks-pause-validating", + "categories": [ + "Infrastructure" + ], + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-operational-tasks-pause-validating.md", + "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/operational-tasks/pause-validating/", + "preview": "If you need to temporarily stop participating in Polkadot staking activities without fully unbonding your funds, chilling your account allows you to do so efficiently. Chilling removes your node from active validation or nomination in the next era while keeping your funds bonded, making it ideal for planned downtimes or temporary pauses.", + "outline": [ { "depth": 2, - "title": "Transaction Era", - "anchor": "transaction-era" + "title": "Introduction", + "anchor": "introduction" }, { "depth": 2, - "title": "Trie (Patricia Merkle Tree)", - "anchor": "trie-patricia-merkle-tree" + "title": "Chilling Your Node", + "anchor": "chilling-your-node" }, { "depth": 2, - "title": "Validator", - "anchor": "validator" + "title": "Staking Election Timing Considerations", + "anchor": "staking-election-timing-considerations" }, { "depth": 2, - "title": "WebAssembly (Wasm)", - "anchor": "webassembly-wasm" + "title": "Chilling as a Nominator", + "anchor": "chilling-as-a-nominator" }, { "depth": 2, - "title": "Weight", - "anchor": "weight" + "title": "Chilling as a Validator", + "anchor": "chilling-as-a-validator" }, { "depth": 2, - "title": "Westend", - "anchor": "westend" + "title": "Chill Other", + "anchor": "chill-other" } ], "stats": { - "chars": 24739, - "words": 3626, - "headings": 63, - "estimated_token_count_total": 5273 + "chars": 4439, + "words": 679, + "headings": 6, + "estimated_token_count_total": 861 }, - "hash": "sha256:40bd67811e7eabc79ca5d105eae388b19380d9f035022da17fc0d6bb173c817c", + "hash": "sha256:1af153570ce57bd5b52d08493a300996765686f2a6d04519a2e0aa91191612c1", "token_estimator": "heuristic-v1" }, { - "id": "reference-governance-origins-tracks", - "title": "Origins and Tracks", - "slug": "reference-governance-origins-tracks", + "id": "nodes-and-validators-run-a-validator-operational-tasks-upgrade-your-node", + "title": "Upgrade a Validator Node", + "slug": "nodes-and-validators-run-a-validator-operational-tasks-upgrade-your-node", "categories": [ - "Polkadot Protocol" + "Infrastructure" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-governance-origins-tracks.md", - "html_url": "https://docs.polkadot.com/reference/governance/origins-tracks/", - "preview": "Polkadot's OpenGov system empowers decentralized decision-making and active community participation by tailoring the governance process to the impact of proposed changes. Through a system of origins and tracks, OpenGov ensures that every referendum receives the appropriate scrutiny, balancing security, inclusivity, and efficiency.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-operational-tasks-upgrade-your-node.md", + "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/operational-tasks/upgrade-your-node/", + "preview": "Upgrading a Polkadot validator node is essential for staying current with network updates and maintaining optimal performance. This guide covers routine and extended maintenance scenarios, including software upgrades and major server changes. Following these steps, you can manage session keys and transition smoothly between servers without risking downtime, slashing, or network disruptions. The process requires strategic planning, especially if you need to perform long-lead maintenance, ensuring", "outline": [ { "depth": 2, @@ -3955,40 +840,54 @@ }, { "depth": 2, - "title": "Origins", - "anchor": "origins" + "title": "Prerequisites", + "anchor": "prerequisites" }, { "depth": 2, - "title": "Tracks", - "anchor": "tracks" + "title": "Session Keys", + "anchor": "session-keys" }, { "depth": 2, - "title": "Additional Resources", - "anchor": "additional-resources" + "title": "Keystore", + "anchor": "keystore" + }, + { + "depth": 2, + "title": "Upgrade Using Backup Validator", + "anchor": "upgrade-using-backup-validator" + }, + { + "depth": 3, + "title": "Session `N`", + "anchor": "session-n" + }, + { + "depth": 3, + "title": "Session `N+3`", + "anchor": "session-n3" } ], "stats": { - "chars": 3333, - "words": 469, - "headings": 4, - "estimated_token_count_total": 631 + "chars": 5650, + "words": 851, + "headings": 7, + "estimated_token_count_total": 1185 }, - "hash": "sha256:baba9dd41091b792d09005d55d3df0bf65b35f42b40ebe63caf425a0978a22b0", + "hash": "sha256:888230b128d8c648c4f06a18d3b1d1b06dd1bf22a0de4add1f28210ffccb2549", "token_estimator": "heuristic-v1" }, { - "id": "reference-governance", - "title": "On-Chain Governance Overview", - "slug": "reference-governance", + "id": "nodes-and-validators-run-a-validator-requirements", + "title": "Validator Requirements", + "slug": "nodes-and-validators-run-a-validator-requirements", "categories": [ - "Basics", - "Polkadot Protocol" + "Infrastructure" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-governance.md", - "html_url": "https://docs.polkadot.com/reference/governance/", - "preview": "Polkadot’s governance system exemplifies decentralized decision-making, empowering its community of stakeholders to shape the network’s future through active participation. The latest evolution, OpenGov, builds on Polkadot’s foundation by providing a more inclusive and efficient governance model.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-requirements.md", + "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/requirements/", + "preview": "Running a validator in the Polkadot ecosystem is essential for maintaining network security and decentralization. Validators are responsible for validating transactions and adding new blocks to the chain, ensuring the system operates smoothly. In return for their services, validators earn rewards. However, the role comes with inherent risks, such as slashing penalties for misbehavior or technical failures. If you’re new to validation, starting on Kusama provides a lower-stakes environment to gai", "outline": [ { "depth": 2, @@ -3997,65 +896,44 @@ }, { "depth": 2, - "title": "Governance Evolution", - "anchor": "governance-evolution" - }, - { - "depth": 2, - "title": "OpenGov Key Features", - "anchor": "opengov-key-features" + "title": "Prerequisites", + "anchor": "prerequisites" }, { "depth": 2, - "title": "Origins and Tracks", - "anchor": "origins-and-tracks" + "title": "Minimum Hardware Requirements", + "anchor": "minimum-hardware-requirements" }, { "depth": 2, - "title": "Referendums", - "anchor": "referendums" - }, - { - "depth": 3, - "title": "Vote on Referendums", - "anchor": "vote-on-referendums" - }, - { - "depth": 3, - "title": "Delegate Voting Power", - "anchor": "delegate-voting-power" - }, - { - "depth": 3, - "title": "Cancel a Referendum", - "anchor": "cancel-a-referendum" + "title": "VPS Provider List", + "anchor": "vps-provider-list" }, { "depth": 2, - "title": "Additional Resources", - "anchor": "additional-resources" + "title": "Minimum Bond Requirement", + "anchor": "minimum-bond-requirement" } ], "stats": { - "chars": 7493, - "words": 1019, - "headings": 9, - "estimated_token_count_total": 1611 + "chars": 6842, + "words": 944, + "headings": 5, + "estimated_token_count_total": 1485 }, - "hash": "sha256:62beec261e72529f70e07a641177d489d2c8872f9c9d618cbadf1ac0fd881986", + "hash": "sha256:46435b97c37ef6798d2c75c69df31c5e5f07e04b218c370ec5af6b1838d43aac", "token_estimator": "heuristic-v1" }, { - "id": "reference-parachains-accounts", - "title": "Polkadot SDK Accounts", - "slug": "reference-parachains-accounts", + "id": "nodes-and-validators-run-a-validator-staking-mechanics-offenses-and-slashes", + "title": "Offenses and Slashes", + "slug": "nodes-and-validators-run-a-validator-staking-mechanics-offenses-and-slashes", "categories": [ - "Basics", - "Polkadot Protocol" + "Infrastructure" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-accounts.md", - "html_url": "https://docs.polkadot.com/reference/parachains/accounts/", - "preview": "Accounts are essential for managing identity, transactions, and governance on the network in the Polkadot SDK. Understanding these components is critical for seamless development and operation on the network, whether you're building or interacting with Polkadot-based chains.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-staking-mechanics-offenses-and-slashes.md", + "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/staking-mechanics/offenses-and-slashes/", + "preview": "In Polkadot's Nominated Proof of Stake (NPoS) system, validator misconduct is deterred through a combination of slashing, disabling, and reputation penalties. Validators and nominators who stake tokens face consequences for validator misbehavior, which range from token slashes to restrictions on network participation.", "outline": [ { "depth": 2, @@ -4064,95 +942,64 @@ }, { "depth": 2, - "title": "Account Data Structure", - "anchor": "account-data-structure" - }, - { - "depth": 3, - "title": "Account", - "anchor": "account" - }, - { - "depth": 3, - "title": "Account Info", - "anchor": "account-info" - }, - { - "depth": 3, - "title": "Account Reference Counters", - "anchor": "account-reference-counters" - }, - { - "depth": 2, - "title": "Account Balance Types", - "anchor": "account-balance-types" - }, - { - "depth": 3, - "title": "Balance Types", - "anchor": "balance-types" + "title": "Offenses", + "anchor": "offenses" }, { "depth": 3, - "title": "Locks", - "anchor": "locks" + "title": "Invalid Votes", + "anchor": "invalid-votes" }, { "depth": 3, - "title": "Balance Types on Polkadot.js", - "anchor": "balance-types-on-polkadotjs" + "title": "Equivocations", + "anchor": "equivocations" }, { "depth": 2, - "title": "Address Formats", - "anchor": "address-formats" - }, - { - "depth": 3, - "title": "Basic Format", - "anchor": "basic-format" + "title": "Penalties", + "anchor": "penalties" }, { "depth": 3, - "title": "Address Type", - "anchor": "address-type" + "title": "Slashing", + "anchor": "slashing" }, { "depth": 3, - "title": "Address Length", - "anchor": "address-length" + "title": "Disabling", + "anchor": "disabling" }, { "depth": 3, - "title": "Checksum Types", - "anchor": "checksum-types" + "title": "Reputation Changes", + "anchor": "reputation-changes" }, { "depth": 3, - "title": "Validating Addresses", - "anchor": "validating-addresses" + "title": "Penalties by Offense", + "anchor": "penalties-by-offense" } ], "stats": { - "chars": 29604, - "words": 4194, - "headings": 15, - "estimated_token_count_total": 6507 + "chars": 15427, + "words": 2103, + "headings": 9, + "estimated_token_count_total": 3409 }, - "hash": "sha256:0104a9132a69345a2faac37fca0e2853a2ded1efb009511a83a98d44509ab887", + "hash": "sha256:abe6bedab04f463ec07f554977b8d6355a5d2fad9bcda01cbe58568152295daa", "token_estimator": "heuristic-v1" }, { - "id": "reference-parachains-blocks-transactions-fees-blocks", - "title": "Blocks", - "slug": "reference-parachains-blocks-transactions-fees-blocks", + "id": "nodes-and-validators-run-a-validator-staking-mechanics-rewards", + "title": "Rewards Payout", + "slug": "nodes-and-validators-run-a-validator-staking-mechanics-rewards", "categories": [ - "Basics", - "Polkadot Protocol" + "Infrastructure" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-blocks.md", - "html_url": "https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/blocks/", - "preview": "In the Polkadot SDK, blocks are fundamental to the functioning of the blockchain, serving as containers for [transactions](/reference/parachains/blocks-transactions-fees/transactions/){target=\\_blank} and changes to the chain's state. Blocks consist of headers and an array of transactions, ensuring the integrity and validity of operations on the network. This guide explores the essential components of a block, the process of block production, and how blocks are validated and imported across the", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/nodes-and-validators-run-a-validator-staking-mechanics-rewards.md", + "html_url": "https://docs.polkadot.com/nodes-and-validators/run-a-validator/staking-mechanics/rewards/", + "preview": "Understanding how rewards are distributed to validators and nominators is essential for network participants. In Polkadot and Kusama, validators earn rewards based on their era points, which are accrued through actions like block production and parachain validation.", "outline": [ { "depth": 2, @@ -4161,157 +1008,140 @@ }, { "depth": 2, - "title": "What is a Block?", - "anchor": "what-is-a-block" + "title": "Era Points", + "anchor": "era-points" }, { "depth": 2, - "title": "Block Production", - "anchor": "block-production" - }, - { - "depth": 3, - "title": "Initialize Block", - "anchor": "initialize-block" - }, - { - "depth": 3, - "title": "Finalize Block", - "anchor": "finalize-block" + "title": "Reward Variance", + "anchor": "reward-variance" }, { "depth": 2, - "title": "Block Authoring and Import", - "anchor": "block-authoring-and-import" + "title": "Payout Scheme", + "anchor": "payout-scheme" }, { - "depth": 3, - "title": "Block Import Queue", - "anchor": "block-import-queue" + "depth": 2, + "title": "Running Multiple Validators", + "anchor": "running-multiple-validators" }, { "depth": 2, - "title": "Additional Resources", - "anchor": "additional-resources" + "title": "Nominators and Validator Payments", + "anchor": "nominators-and-validator-payments" } ], "stats": { - "chars": 6252, - "words": 910, - "headings": 8, - "estimated_token_count_total": 1395 + "chars": 10976, + "words": 1753, + "headings": 6, + "estimated_token_count_total": 2588 }, - "hash": "sha256:424783c102bea5dae5b8749635858c6c59055563442a98f57521f0027dafa8d3", + "hash": "sha256:d5d6d72eb2cf10f624d84c65f2274f7df90acb5d071bf170bc8eae8d98a810a5", "token_estimator": "heuristic-v1" }, { - "id": "reference-parachains-blocks-transactions-fees-fees", - "title": "Transactions Weights and Fees", - "slug": "reference-parachains-blocks-transactions-fees-fees", + "id": "parachains-customize-runtime-add-existing-pallets", + "title": "Add an Existing Pallet to the Runtime", + "slug": "parachains-customize-runtime-add-existing-pallets", "categories": [ - "Basics", - "Polkadot Protocol" + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-fees.md", - "html_url": "https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/fees/", - "preview": "When transactions are executed, or data is stored on-chain, the activity changes the chain's state and consumes blockchain resources. Because the resources available to a blockchain are limited, managing how operations on-chain consume them is important. In addition to being limited in practical terms, such as storage capacity, blockchain resources represent a potential attack vector for malicious users. For example, a malicious user might attempt to overload the network with messages to stop th", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime-add-existing-pallets.md", + "html_url": "https://docs.polkadot.com/parachains/customize-runtime/add-existing-pallets/", + "preview": "The [Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\\_blank} provides a functional runtime that includes default [FRAME](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\\_blank} development modules ([pallets](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/pallet/index.html){target=\\_blank}) to help you get started building a custo", "outline": [ { "depth": 2, - "title": "Introductions", - "anchor": "introductions" + "title": "Introduction", + "anchor": "introduction" }, { "depth": 2, - "title": "How Fees are Calculated", - "anchor": "how-fees-are-calculated" + "title": "Check Prerequisites", + "anchor": "check-prerequisites" }, { "depth": 2, - "title": "Using the Transaction Payment Pallet", - "anchor": "using-the-transaction-payment-pallet" + "title": "Add an Existing Polkadot SDK Pallet to Your Runtime", + "anchor": "add-an-existing-polkadot-sdk-pallet-to-your-runtime" }, { "depth": 3, - "title": "Understanding the Inclusion Fee", - "anchor": "understanding-the-inclusion-fee" + "title": "Add an Existing Pallet as a Dependency", + "anchor": "add-an-existing-pallet-as-a-dependency" }, { "depth": 3, - "title": "Accounts with an Insufficient Balance", - "anchor": "accounts-with-an-insufficient-balance" + "title": "Enable Standard Library Features", + "anchor": "enable-standard-library-features" }, { "depth": 3, - "title": "Fee Multipliers", - "anchor": "fee-multipliers" - }, - { - "depth": 2, - "title": "Transactions with Special Requirements", - "anchor": "transactions-with-special-requirements" - }, - { - "depth": 2, - "title": "Default Weight Annotations", - "anchor": "default-weight-annotations" + "title": "Review the Config Trait", + "anchor": "review-the-config-trait" }, { "depth": 3, - "title": "Weights and Database Read/Write Operations", - "anchor": "weights-and-database-readwrite-operations" + "title": "Implement the Config Trait", + "anchor": "implement-the-config-trait" }, { "depth": 3, - "title": "Dispatch Classes", - "anchor": "dispatch-classes" + "title": "Add to Runtime Construct", + "anchor": "add-to-runtime-construct" }, { "depth": 3, - "title": "Dynamic Weights", - "anchor": "dynamic-weights" + "title": "Verify the Runtime Compiles", + "anchor": "verify-the-runtime-compiles" }, { "depth": 2, - "title": "Post Dispatch Weight Correction", - "anchor": "post-dispatch-weight-correction" + "title": "Run Your Chain Locally", + "anchor": "run-your-chain-locally" }, { - "depth": 2, - "title": "Custom Fees", - "anchor": "custom-fees" + "depth": 3, + "title": "Generate a Chain Specification", + "anchor": "generate-a-chain-specification" + }, + { + "depth": 3, + "title": "Start the Parachain Node", + "anchor": "start-the-parachain-node" }, { "depth": 3, - "title": "Custom Weights", - "anchor": "custom-weights" + "title": "Interact with the Pallet", + "anchor": "interact-with-the-pallet" }, { "depth": 2, - "title": "Additional Resources", - "anchor": "additional-resources" + "title": "Where to Go Next", + "anchor": "where-to-go-next" } ], "stats": { - "chars": 20800, - "words": 2917, - "headings": 15, - "estimated_token_count_total": 4464 + "chars": 11924, + "words": 1585, + "headings": 14, + "estimated_token_count_total": 2724 }, - "hash": "sha256:7d0c3fa7982b3e1843adb8f27422456397580b3a3eba5047b381da8517742536", + "hash": "sha256:93d123cbaaccc2515b4a70be8e1327b4f75b1051d16c5e3daf5a2035af7b7ca3", "token_estimator": "heuristic-v1" }, { - "id": "reference-parachains-blocks-transactions-fees-transactions", - "title": "Transactions", - "slug": "reference-parachains-blocks-transactions-fees-transactions", + "id": "parachains-customize-runtime-add-pallet-instances", + "title": "Add Multiple Pallet Instances", + "slug": "parachains-customize-runtime-add-pallet-instances", "categories": [ - "Basics", - "Polkadot Protocol" + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-transactions.md", - "html_url": "https://docs.polkadot.com/reference/parachains/blocks-transactions-fees/transactions/", - "preview": "Transactions are essential components of blockchain networks, enabling state changes and the execution of key operations. In the Polkadot SDK, transactions, often called extrinsics, come in multiple forms, including signed, unsigned, and inherent transactions.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime-add-pallet-instances.md", + "html_url": "https://docs.polkadot.com/parachains/customize-runtime/add-pallet-instances/", + "preview": "The [Polkadot SDK Parachain Template](https://github.com/paritytech/polkadot-sdk-parachain-template){target=\\_blank} provides a solid foundation for building custom parachains. While most pallets are typically included as single instances within a runtime, some scenarios benefit from running multiple instances of the same pallet with different configurations. This approach lets you reuse pallet logic without reimplementing it, enabling diverse functionality from a single codebase.", "outline": [ { "depth": 2, @@ -4320,246 +1150,124 @@ }, { "depth": 2, - "title": "What Is a Transaction?", - "anchor": "what-is-a-transaction" - }, - { - "depth": 3, - "title": "Signed Transactions", - "anchor": "signed-transactions" - }, - { - "depth": 3, - "title": "Unsigned Transactions", - "anchor": "unsigned-transactions" - }, - { - "depth": 3, - "title": "Inherent Transactions", - "anchor": "inherent-transactions" - }, - { - "depth": 2, - "title": "Transaction Formats", - "anchor": "transaction-formats" - }, - { - "depth": 3, - "title": "Types of Transaction Formats", - "anchor": "types-of-transaction-formats" - }, - { - "depth": 3, - "title": "Signed Transaction Data Structure", - "anchor": "signed-transaction-data-structure" - }, - { - "depth": 3, - "title": "Signed Extensions", - "anchor": "signed-extensions" + "title": "Check Prerequisites", + "anchor": "check-prerequisites" }, { "depth": 2, - "title": "Transaction Construction", - "anchor": "transaction-construction" - }, - { - "depth": 3, - "title": "Construct a Signed Transaction", - "anchor": "construct-a-signed-transaction" + "title": "Understanding Instantiable Pallets", + "anchor": "understanding-instantiable-pallets" }, { "depth": 3, - "title": "Transaction Encoding", - "anchor": "transaction-encoding" + "title": "Identifying an Instantiable Pallet", + "anchor": "identifying-an-instantiable-pallet" }, { "depth": 3, - "title": "Customize Transaction Construction", - "anchor": "customize-transaction-construction" + "title": "How Instance Generics Work", + "anchor": "how-instance-generics-work" }, { "depth": 2, - "title": "Lifecycle of a Transaction", - "anchor": "lifecycle-of-a-transaction" - }, - { - "depth": 3, - "title": "Define Transaction Properties", - "anchor": "define-transaction-properties" - }, - { - "depth": 3, - "title": "Process on a Block Authoring Node", - "anchor": "process-on-a-block-authoring-node" + "title": "Add Multiple Instances of a Pallet to Your Runtime", + "anchor": "add-multiple-instances-of-a-pallet-to-your-runtime" }, { "depth": 3, - "title": "Validate and Queue", - "anchor": "validate-and-queue" + "title": "Add the Pallet as a Dependency", + "anchor": "add-the-pallet-as-a-dependency" }, { "depth": 3, - "title": "Transaction Ordering and Priority", - "anchor": "transaction-ordering-and-priority" + "title": "Enable Standard Library Features", + "anchor": "enable-standard-library-features" }, { "depth": 3, - "title": "Transaction Execution", - "anchor": "transaction-execution" - }, - { - "depth": 2, - "title": "Transaction Mortality", - "anchor": "transaction-mortality" - }, - { - "depth": 2, - "title": "Unique Identifiers for Extrinsics", - "anchor": "unique-identifiers-for-extrinsics" - }, - { - "depth": 2, - "title": "Additional Resources", - "anchor": "additional-resources" - } - ], - "stats": { - "chars": 23610, - "words": 3333, - "headings": 22, - "estimated_token_count_total": 4708 - }, - "hash": "sha256:66726634d3a51cd9c471621054a6e5f09c8061dca6144b64c8bcf45626359617", - "token_estimator": "heuristic-v1" - }, - { - "id": "reference-parachains-chain-data", - "title": "Chain Data", - "slug": "reference-parachains-chain-data", - "categories": [ - "Basics", - "Polkadot Protocol" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-chain-data.md", - "html_url": "https://docs.polkadot.com/reference/parachains/chain-data/", - "preview": "Understanding and leveraging on-chain data is a fundamental aspect of blockchain development. Whether you're building frontend applications or backend systems, accessing and decoding runtime metadata is vital to interacting with the blockchain. This guide introduces you to the tools and processes for generating and retrieving metadata, explains its role in application development, and outlines the additional APIs available for interacting with a Polkadot node. By mastering these components, you", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Application Development", - "anchor": "application-development" - }, - { - "depth": 2, - "title": "Understand Metadata", - "anchor": "understand-metadata" + "title": "Review the Config Trait", + "anchor": "review-the-config-trait" }, { - "depth": 2, - "title": "Expose Runtime Information as Metadata", - "anchor": "expose-runtime-information-as-metadata" + "depth": 3, + "title": "Define Pallet Parameters", + "anchor": "define-pallet-parameters" }, { - "depth": 2, - "title": "Generate Metadata", - "anchor": "generate-metadata" + "depth": 3, + "title": "Create Instance Type Definitions", + "anchor": "create-instance-type-definitions" }, { - "depth": 2, - "title": "Retrieve Runtime Metadata", - "anchor": "retrieve-runtime-metadata" + "depth": 3, + "title": "Implement Config Trait for First Instance", + "anchor": "implement-config-trait-for-first-instance" }, { "depth": 3, - "title": "Use Polkadot.js", - "anchor": "use-polkadotjs" + "title": "Implement Config Trait for Second Instance", + "anchor": "implement-config-trait-for-second-instance" }, { "depth": 3, - "title": "Use Curl", - "anchor": "use-curl" + "title": "Add Instances to Runtime Construct", + "anchor": "add-instances-to-runtime-construct" }, { "depth": 3, - "title": "Use Subxt", - "anchor": "use-subxt" + "title": "Verify the Runtime Compiles", + "anchor": "verify-the-runtime-compiles" }, { "depth": 2, - "title": "Client Applications and Metadata", - "anchor": "client-applications-and-metadata" + "title": "Run Your Chain Locally", + "anchor": "run-your-chain-locally" }, { - "depth": 2, - "title": "Metadata Format", - "anchor": "metadata-format" + "depth": 3, + "title": "Generate a Chain Specification", + "anchor": "generate-a-chain-specification" }, { "depth": 3, - "title": "Pallets", - "anchor": "pallets" + "title": "Start the Parachain Node", + "anchor": "start-the-parachain-node" }, { "depth": 3, - "title": "Extrinsic", - "anchor": "extrinsic" + "title": "Interact with Both Pallet Instances", + "anchor": "interact-with-both-pallet-instances" }, { - "depth": 2, - "title": "Included RPC APIs", - "anchor": "included-rpc-apis" + "depth": 3, + "title": "Test Instance Independence", + "anchor": "test-instance-independence" }, { "depth": 2, - "title": "Additional Resources", - "anchor": "additional-resources" + "title": "Where to Go Next", + "anchor": "where-to-go-next" } ], "stats": { - "chars": 18650, - "words": 2216, - "headings": 15, - "estimated_token_count_total": 3774 - }, - "hash": "sha256:49238d1e9e2c33e0fcd3a84b5e30f0d3840d7d23a783b538875e0a23f38efc1d", - "token_estimator": "heuristic-v1" - }, - { - "id": "reference-parachains-consensus-async-backing", - "title": "reference-parachains-consensus-async-backing", - "slug": "reference-parachains-consensus-async-backing", - "categories": [ - "Uncategorized" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-consensus-async-backing.md", - "html_url": "https://docs.polkadot.com/reference/parachains/consensus/async-backing/", - "preview": "TODO", - "outline": [], - "stats": { - "chars": 5, - "words": 1, - "headings": 0, - "estimated_token_count_total": 0 + "chars": 17923, + "words": 2203, + "headings": 21, + "estimated_token_count_total": 3811 }, - "hash": "sha256:56ba36249ea8216ad513b13df3de6c0e490ba214897674d30331f1c7e7edbef3", + "hash": "sha256:d83e574726c524fa017236eb5e3b8a0676d598be4da1ce4fe25a60141baeee49", "token_estimator": "heuristic-v1" }, { - "id": "reference-parachains-consensus-elastic-scaling", - "title": "Elastic Scaling", - "slug": "reference-parachains-consensus-elastic-scaling", + "id": "parachains-customize-runtime-add-smart-contract-functionality", + "title": "Add Smart Contract Functionality", + "slug": "parachains-customize-runtime-add-smart-contract-functionality", "categories": [ - "Polkadot Protocol" + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-consensus-elastic-scaling.md", - "html_url": "https://docs.polkadot.com/reference/parachains/consensus/elastic-scaling/", - "preview": "Polkadot's architecture delivers scalability and security through its shared security model, where the relay chain coordinates and validates multiple parallel chains.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime-add-smart-contract-functionality.md", + "html_url": "https://docs.polkadot.com/parachains/customize-runtime/add-smart-contract-functionality/", + "preview": "When building your custom blockchain with the Polkadot SDK, you can add smart contract capabilities through specialized pallets. These pallets enable users to deploy and execute smart contracts, enhancing your chain's programmability and allowing developers to build decentralized applications on your network.", "outline": [ { "depth": 2, @@ -4568,162 +1276,100 @@ }, { "depth": 2, - "title": "How Elastic Scaling Works", - "anchor": "how-elastic-scaling-works" - }, - { - "depth": 2, - "title": "Benefits of Elastic Scaling", - "anchor": "benefits-of-elastic-scaling" + "title": "pallet-revive", + "anchor": "pallet-revive" }, { - "depth": 2, - "title": "Use Cases", - "anchor": "use-cases" + "depth": 3, + "title": "Core Components", + "anchor": "core-components" }, { "depth": 3, - "title": "Handling Sudden Traffic Spikes", - "anchor": "handling-sudden-traffic-spikes" + "title": "Supported Languages and Compilers", + "anchor": "supported-languages-and-compilers" }, { "depth": 3, - "title": "Supporting Early-Stage Growth", - "anchor": "supporting-early-stage-growth" + "title": "How It Works", + "anchor": "how-it-works" }, { "depth": 3, - "title": "Scaling Massive IoT Networks", - "anchor": "scaling-massive-iot-networks" + "title": "Key Benefits", + "anchor": "key-benefits" }, { "depth": 3, - "title": "Powering Real-Time, Low-Latency Systems", - "anchor": "powering-real-time-low-latency-systems" - } - ], - "stats": { - "chars": 7871, - "words": 1047, - "headings": 8, - "estimated_token_count_total": 1440 - }, - "hash": "sha256:2d228c52844df8952520fafdd3e6f0e26bfd2f32b5ee60c6241cf7d38603643c", - "token_estimator": "heuristic-v1" - }, - { - "id": "reference-parachains-consensus", - "title": "reference-parachains-consensus", - "slug": "reference-parachains-consensus", - "categories": [ - "Uncategorized" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-consensus.md", - "html_url": "https://docs.polkadot.com/reference/parachains/consensus/", - "preview": "TODO", - "outline": [], - "stats": { - "chars": 5, - "words": 1, - "headings": 0, - "estimated_token_count_total": 0 - }, - "hash": "sha256:56ba36249ea8216ad513b13df3de6c0e490ba214897674d30331f1c7e7edbef3", - "token_estimator": "heuristic-v1" - }, - { - "id": "reference-parachains-cryptography", - "title": "Cryptography", - "slug": "reference-parachains-cryptography", - "categories": [ - "Basics", - "Polkadot Protocol" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-cryptography.md", - "html_url": "https://docs.polkadot.com/reference/parachains/cryptography/", - "preview": "Cryptography forms the backbone of blockchain technology, providing the mathematical verifiability crucial for consensus systems, data integrity, and user security. While a deep understanding of the underlying mathematical processes isn't necessary for most blockchain developers, grasping the fundamental applications of cryptography is essential. This page comprehensively overviews cryptographic implementations used across Polkadot SDK-based chains and the broader blockchain ecosystem.", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" + "title": "Implementation Examples", + "anchor": "implementation-examples" }, { "depth": 2, - "title": "Hash Functions", - "anchor": "hash-functions" + "title": "Frontier", + "anchor": "frontier" }, { "depth": 3, - "title": "Key Properties of Hash Functions", - "anchor": "key-properties-of-hash-functions" + "title": "Integration Options", + "anchor": "integration-options" }, { "depth": 3, - "title": "Blake2", - "anchor": "blake2" - }, - { - "depth": 2, - "title": "Types of Cryptography", - "anchor": "types-of-cryptography" + "title": "EVM Execution Only", + "anchor": "evm-execution-only" }, { "depth": 3, - "title": "Symmetric Cryptography", - "anchor": "symmetric-cryptography" + "title": "Full Ethereum Compatibility", + "anchor": "full-ethereum-compatibility" }, { "depth": 3, - "title": "Asymmetric Cryptography", - "anchor": "asymmetric-cryptography" + "title": "Key Benefits", + "anchor": "key-benefits-2" }, { "depth": 3, - "title": "Trade-offs and Compromises", - "anchor": "trade-offs-and-compromises" + "title": "Implementation Examples", + "anchor": "implementation-examples-2" }, { "depth": 2, - "title": "Digital Signatures", - "anchor": "digital-signatures" + "title": "pallet-contracts (Legacy)", + "anchor": "pallet-contracts-legacy" }, { "depth": 3, - "title": "Example of Creating a Digital Signature", - "anchor": "example-of-creating-a-digital-signature" + "title": "Implementation Example", + "anchor": "implementation-example" }, { "depth": 2, - "title": "Elliptic Curve", - "anchor": "elliptic-curve" - }, - { - "depth": 3, - "title": "Various Implementations", - "anchor": "various-implementations" + "title": "Where to Go Next", + "anchor": "where-to-go-next" } ], "stats": { - "chars": 8860, - "words": 1293, - "headings": 12, - "estimated_token_count_total": 1797 + "chars": 6655, + "words": 833, + "headings": 16, + "estimated_token_count_total": 1631 }, - "hash": "sha256:259dcef86aadc513675258b665cc3940db65af6eb32a5db85da6ac339966fa60", + "hash": "sha256:6297bb5e0809fdd0585d6170054599f7ab4a3ce7c687ad03ae43092057c493b7", "token_estimator": "heuristic-v1" }, { - "id": "reference-parachains-data-encoding", - "title": "Data Encoding", - "slug": "reference-parachains-data-encoding", + "id": "parachains-customize-runtime-pallet-development-add-pallet-to-runtime", + "title": "Add Pallets to the Runtime", + "slug": "parachains-customize-runtime-pallet-development-add-pallet-to-runtime", "categories": [ "Basics", - "Polkadot Protocol" + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-data-encoding.md", - "html_url": "https://docs.polkadot.com/reference/parachains/data-encoding/", - "preview": "The Polkadot SDK uses a lightweight and efficient encoding/decoding mechanism to optimize data transmission across the network. This mechanism, known as the _SCALE_ codec, is used for serializing and deserializing data.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime-pallet-development-add-pallet-to-runtime.md", + "html_url": "https://docs.polkadot.com/parachains/customize-runtime/pallet-development/add-pallet-to-runtime/", + "preview": "In previous tutorials, you learned how to [create a custom pallet](/tutorials/polkadot-sdk/parachains/zero-to-hero/build-custom-pallet/){target=\\_blank} and [test it](/tutorials/polkadot-sdk/parachains/zero-to-hero/pallet-unit-testing/){target=\\_blank}. The next step is to include this pallet in your runtime, integrating it into the core logic of your blockchain.", "outline": [ { "depth": 2, @@ -4732,70 +1378,49 @@ }, { "depth": 2, - "title": "SCALE Codec", - "anchor": "scale-codec" - }, - { - "depth": 3, - "title": "Encode", - "anchor": "encode" - }, - { - "depth": 3, - "title": "Decode", - "anchor": "decode" - }, - { - "depth": 3, - "title": "CompactAs", - "anchor": "compactas" - }, - { - "depth": 3, - "title": "HasCompact", - "anchor": "hascompact" + "title": "Add the Pallets as Dependencies", + "anchor": "add-the-pallets-as-dependencies" }, { "depth": 3, - "title": "EncodeLike", - "anchor": "encodelike" + "title": "Update the Runtime Configuration", + "anchor": "update-the-runtime-configuration" }, { - "depth": 3, - "title": "Data Types", - "anchor": "data-types" + "depth": 2, + "title": "Recompile the Runtime", + "anchor": "recompile-the-runtime" }, { "depth": 2, - "title": "Encode and Decode Rust Trait Implementations", - "anchor": "encode-and-decode-rust-trait-implementations" + "title": "Run Your Chain Locally", + "anchor": "run-your-chain-locally" }, { "depth": 2, - "title": "SCALE Codec Libraries", - "anchor": "scale-codec-libraries" + "title": "Where to Go Next", + "anchor": "where-to-go-next" } ], "stats": { - "chars": 13629, - "words": 1314, - "headings": 10, - "estimated_token_count_total": 3213 + "chars": 13091, + "words": 1522, + "headings": 6, + "estimated_token_count_total": 3091 }, - "hash": "sha256:e448294b6e52291ac0add5fa6533572814e6cd27af42bdaccc2000b86f52d775", + "hash": "sha256:87add0ae178e4970601a27efccadb58eff1375d19819201034ba2829914f1cd5", "token_estimator": "heuristic-v1" }, { - "id": "reference-parachains-interoperability", - "title": "Interoperability", - "slug": "reference-parachains-interoperability", + "id": "parachains-customize-runtime-pallet-development-benchmark-pallet", + "title": "Benchmarking FRAME Pallets", + "slug": "parachains-customize-runtime-pallet-development-benchmark-pallet", "categories": [ - "Basics", - "Polkadot Protocol" + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-interoperability.md", - "html_url": "https://docs.polkadot.com/reference/parachains/interoperability/", - "preview": "Interoperability lies at the heart of the Polkadot ecosystem, enabling communication and collaboration across a diverse range of blockchains. By bridging the gaps between parachains, relay chains, and even external networks, Polkadot unlocks the potential for truly decentralized applications, efficient resource sharing, and scalable solutions.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime-pallet-development-benchmark-pallet.md", + "html_url": "https://docs.polkadot.com/parachains/customize-runtime/pallet-development/benchmark-pallet/", + "preview": "Benchmarking is a critical component of developing efficient and secure blockchain runtimes. In the Polkadot ecosystem, accurately benchmarking your custom pallets ensures that each extrinsic has a precise [weight](/reference/glossary/#weight){target=\\_blank}, representing its computational and storage demands. This process is vital for maintaining the blockchain's performance and preventing potential vulnerabilities, such as Denial of Service (DoS) attacks.", "outline": [ { "depth": 2, @@ -4804,200 +1429,215 @@ }, { "depth": 2, - "title": "Why Interoperability Matters", - "anchor": "why-interoperability-matters" + "title": "The Case for Benchmarking", + "anchor": "the-case-for-benchmarking" + }, + { + "depth": 3, + "title": "Benchmarking and Weight", + "anchor": "benchmarking-and-weight" }, { "depth": 2, - "title": "Key Mechanisms for Interoperability", - "anchor": "key-mechanisms-for-interoperability" + "title": "Benchmarking Process", + "anchor": "benchmarking-process" }, { "depth": 3, - "title": "Cross-Consensus Messaging (XCM): The Backbone of Communication", - "anchor": "cross-consensus-messaging-xcm-the-backbone-of-communication" + "title": "Prepare Your Environment", + "anchor": "prepare-your-environment" }, { "depth": 3, - "title": "Bridges: Connecting External Networks", - "anchor": "bridges-connecting-external-networks" + "title": "Write Benchmark Tests", + "anchor": "write-benchmark-tests" }, { - "depth": 2, - "title": "The Polkadot Advantage", - "anchor": "the-polkadot-advantage" + "depth": 3, + "title": "Add Benchmarks to Runtime", + "anchor": "add-benchmarks-to-runtime" + }, + { + "depth": 3, + "title": "Run Benchmarks", + "anchor": "run-benchmarks" }, { "depth": 2, - "title": "Looking Ahead", - "anchor": "looking-ahead" + "title": "Where to Go Next", + "anchor": "where-to-go-next" } ], "stats": { - "chars": 4635, - "words": 584, - "headings": 7, - "estimated_token_count_total": 772 + "chars": 14715, + "words": 1879, + "headings": 9, + "estimated_token_count_total": 3338 }, - "hash": "sha256:11bb4f113bdda5852a3115e64d5ba47f8eccd4e3619a05ad960ab3a541f31346", + "hash": "sha256:915bc91edd56cdedd516e871dbe450d70c9f99fb467cc00ff231ea3a74f61d96", "token_estimator": "heuristic-v1" }, { - "id": "reference-parachains-networks", - "title": "Networks", - "slug": "reference-parachains-networks", + "id": "parachains-customize-runtime-pallet-development-create-a-pallet", + "title": "Create a Custom Pallet", + "slug": "parachains-customize-runtime-pallet-development-create-a-pallet", "categories": [ - "Basics", - "Polkadot Protocol", - "Networks" + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-networks.md", - "html_url": "https://docs.polkadot.com/reference/parachains/networks/", - "preview": "The Polkadot ecosystem is built on a robust set of networks designed to enable secure and scalable development. Whether you are testing new features or deploying to live production, Polkadot offers several layers of networks tailored for each stage of the development process. From local environments to experimental networks like Kusama and community-run TestNets such as Paseo, developers can thoroughly test, iterate, and validate their applications. This guide will introduce you to Polkadot's va", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime-pallet-development-create-a-pallet.md", + "html_url": "https://docs.polkadot.com/parachains/customize-runtime/pallet-development/create-a-pallet/", + "preview": "[Framework for Runtime Aggregation of Modular Entities (FRAME)](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\\_blank} provides a powerful set of tools for blockchain development through modular components called [pallets](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/pallet/index.html){target=\\_blank}. These Rust-based runtime modules allow you to build custom blockchain functional", "outline": [ { "depth": 2, - "title": "Introduction", - "anchor": "introduction" + "title": "Introduction", + "anchor": "introduction" + }, + { + "depth": 2, + "title": "Prerequisites", + "anchor": "prerequisites" + }, + { + "depth": 2, + "title": "Core Pallet Components", + "anchor": "core-pallet-components" + }, + { + "depth": 2, + "title": "Create the Pallet Project", + "anchor": "create-the-pallet-project" + }, + { + "depth": 2, + "title": "Configure Dependencies", + "anchor": "configure-dependencies" + }, + { + "depth": 2, + "title": "Initialize the Pallet Structure", + "anchor": "initialize-the-pallet-structure" + }, + { + "depth": 2, + "title": "Configure the Pallet", + "anchor": "configure-the-pallet" }, { "depth": 2, - "title": "Network Overview", - "anchor": "network-overview" + "title": "Define Events", + "anchor": "define-events" }, { "depth": 2, - "title": "Polkadot Development Networks", - "anchor": "polkadot-development-networks" + "title": "Define Errors", + "anchor": "define-errors" }, { "depth": 2, - "title": "Kusama Network", - "anchor": "kusama-network" + "title": "Add Storage Items", + "anchor": "add-storage-items" }, { "depth": 2, - "title": "Test Networks", - "anchor": "test-networks" + "title": "Configure Genesis State", + "anchor": "configure-genesis-state" }, { - "depth": 3, - "title": "Westend", - "anchor": "westend" + "depth": 2, + "title": "Implement Dispatchable Functions", + "anchor": "implement-dispatchable-functions" }, { "depth": 3, - "title": "Paseo", - "anchor": "paseo" + "title": "Dispatchable Function Details", + "anchor": "dispatchable-function-details" }, { "depth": 2, - "title": "Local Test Networks", - "anchor": "local-test-networks" + "title": "Verify Pallet Compilation", + "anchor": "verify-pallet-compilation" }, { - "depth": 3, - "title": "Zombienet", - "anchor": "zombienet" + "depth": 2, + "title": "Add the Pallet to Your Runtime", + "anchor": "add-the-pallet-to-your-runtime" }, { "depth": 3, - "title": "Chopsticks", - "anchor": "chopsticks" - } - ], - "stats": { - "chars": 7834, - "words": 1111, - "headings": 10, - "estimated_token_count_total": 1473 - }, - "hash": "sha256:e49e063a2cc0fb5a48c6cdc3de266bb6e025a006940fea8e90cc4d5f9884900f", - "token_estimator": "heuristic-v1" - }, - { - "id": "reference-parachains-node-and-runtime", - "title": "Node and Runtime", - "slug": "reference-parachains-node-and-runtime", - "categories": [ - "Basics", - "Polkadot Protocol" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-node-and-runtime.md", - "html_url": "https://docs.polkadot.com/reference/parachains/node-and-runtime/", - "preview": "Every blockchain platform relies on a decentralized network of computers, called nodes, that communicate with each other about transactions and blocks. In this context, a node refers to the software running on the connected devices rather than the physical or virtual machines in the network.", - "outline": [ + "title": "Add Runtime Dependency", + "anchor": "add-runtime-dependency" + }, { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" + "depth": 3, + "title": "Implement the Config Trait", + "anchor": "implement-the-config-trait" }, { - "depth": 2, - "title": "Architectural Principles", - "anchor": "architectural-principles" + "depth": 3, + "title": "Add to Runtime Construct", + "anchor": "add-to-runtime-construct" }, { "depth": 3, - "title": "Advantages of this Architecture", - "anchor": "advantages-of-this-architecture" + "title": "Configure Genesis for Your Runtime", + "anchor": "configure-genesis-for-your-runtime" }, { - "depth": 2, - "title": "Node (Client)", - "anchor": "node-client" + "depth": 3, + "title": "Verify Runtime Compilation", + "anchor": "verify-runtime-compilation" }, { "depth": 2, - "title": "Runtime", - "anchor": "runtime" + "title": "Run Your Chain Locally", + "anchor": "run-your-chain-locally" }, { "depth": 3, - "title": "Characteristics", - "anchor": "characteristics" + "title": "Generate a Chain Specification", + "anchor": "generate-a-chain-specification" }, { "depth": 3, - "title": "Key Functions", - "anchor": "key-functions" + "title": "Start the Parachain Node", + "anchor": "start-the-parachain-node" }, { "depth": 2, - "title": "Communication Between Node and Runtime", - "anchor": "communication-between-node-and-runtime" + "title": "Interact with Your Pallet", + "anchor": "interact-with-your-pallet" }, { - "depth": 3, - "title": "Runtime APIs", - "anchor": "runtime-apis" + "depth": 2, + "title": "Key Takeaways", + "anchor": "key-takeaways" }, { - "depth": 3, - "title": "Host Functions", - "anchor": "host-functions" + "depth": 2, + "title": "Where to Go Next", + "anchor": "where-to-go-next" } ], "stats": { - "chars": 4937, - "words": 628, - "headings": 10, - "estimated_token_count_total": 914 + "chars": 26671, + "words": 3041, + "headings": 26, + "estimated_token_count_total": 6113 }, - "hash": "sha256:8122e21c149d0863cfe3b37fc5606bcdb91668e9d265f0f05451a61ff70e4e93", + "hash": "sha256:607e283aaa1295de0af191d97de7f6f87afb722c601a447821fde6a09b97f1af", "token_estimator": "heuristic-v1" }, { - "id": "reference-parachains-randomness", - "title": "Randomness", - "slug": "reference-parachains-randomness", + "id": "parachains-customize-runtime-pallet-development-mock-runtime", + "title": "Mock Your Runtime", + "slug": "parachains-customize-runtime-pallet-development-mock-runtime", "categories": [ - "Basics", - "Polkadot Protocol" + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-randomness.md", - "html_url": "https://docs.polkadot.com/reference/parachains/randomness/", - "preview": "Randomness is crucial in Proof of Stake (PoS) blockchains to ensure a fair and unpredictable distribution of validator duties. However, computers are inherently deterministic, meaning the same input always produces the same output. What we typically refer to as \"random\" numbers on a computer are actually pseudo-random. These numbers rely on an initial \"seed,\" which can come from external sources like [atmospheric noise](https://www.random.org/randomness/){target=\\_blank}, [heart rates](https://m", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime-pallet-development-mock-runtime.md", + "html_url": "https://docs.polkadot.com/parachains/customize-runtime/pallet-development/mock-runtime/", + "preview": "Testing is a critical part of pallet development. Before integrating your pallet into a full runtime, you need a way to test its functionality in isolation. A mock runtime provides a minimal, simulated blockchain environment where you can verify your pallet's logic without the overhead of running a full node.", "outline": [ { "depth": 2, @@ -5006,75 +1646,58 @@ }, { "depth": 2, - "title": "VRF", - "anchor": "vrf" + "title": "Prerequisites", + "anchor": "prerequisites" }, { - "depth": 3, - "title": "How VRF Works", - "anchor": "how-vrf-works" + "depth": 2, + "title": "Understand Mock Runtimes", + "anchor": "understand-mock-runtimes" }, { "depth": 2, - "title": "RANDAO", - "anchor": "randao" + "title": "Create the Mock Runtime Module", + "anchor": "create-the-mock-runtime-module" }, { "depth": 2, - "title": "VDFs", - "anchor": "vdfs" + "title": "Set Up Basic Mock", + "anchor": "set-up-basic-mock" }, { "depth": 2, - "title": "Additional Resources", - "anchor": "additional-resources" - } - ], - "stats": { - "chars": 6503, - "words": 1005, - "headings": 6, - "estimated_token_count_total": 1388 - }, - "hash": "sha256:c7d8a5a4263fd21af458ab0bd102377104affdf2431b4fe74eeff4ebe62a4a81", - "token_estimator": "heuristic-v1" - }, - { - "id": "reference-parachains", - "title": "Parachains Overview", - "slug": "reference-parachains", - "categories": [ - "Basics", - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains.md", - "html_url": "https://docs.polkadot.com/reference/parachains/", - "preview": "A parachain is a specialized blockchain that connects to the Polkadot relay chain, benefiting from shared security, interoperability, and scalability. Parachains are built using the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\\_blank}, a powerful toolkit written in Rust that provides everything needed to create custom blockchain logic while integrating seamlessly with the Polkadot network.", - "outline": [ + "title": "Implement Essential Configuration", + "anchor": "implement-essential-configuration" + }, { "depth": 2, - "title": "Introduction", - "anchor": "introduction" + "title": "Implement Your Pallet's Configuration", + "anchor": "implement-your-pallets-configuration" }, { "depth": 2, - "title": "Polkadot SDK: Parachain Architecture", - "anchor": "polkadot-sdk-parachain-architecture" + "title": "Configure Genesis Storage", + "anchor": "configure-genesis-storage" }, { "depth": 3, - "title": "Substrate: The Foundation", - "anchor": "substrate-the-foundation" + "title": "Basic Test Environment", + "anchor": "basic-test-environment" }, { "depth": 3, - "title": "FRAME: Building Blocks for Your Runtime", - "anchor": "frame-building-blocks-for-your-runtime" + "title": "Custom Genesis Configurations", + "anchor": "custom-genesis-configurations" }, { - "depth": 3, - "title": "Cumulus: Parachain-Specific Functionality", - "anchor": "cumulus-parachain-specific-functionality" + "depth": 2, + "title": "Verify Mock Compilation", + "anchor": "verify-mock-compilation" + }, + { + "depth": 2, + "title": "Key Takeaways", + "anchor": "key-takeaways" }, { "depth": 2, @@ -5083,24 +1706,24 @@ } ], "stats": { - "chars": 8495, - "words": 1029, - "headings": 6, - "estimated_token_count_total": 1759 + "chars": 11766, + "words": 1369, + "headings": 13, + "estimated_token_count_total": 2514 }, - "hash": "sha256:ecb0d9459e08920db7d2d59dc7c01aba7a91ce8c9e39256bd0c3efa473dbaa17", + "hash": "sha256:dd784a5d2daebb9a885fe09f6a967e6c84958d96ddb38d8366eabe9d860fa539", "token_estimator": "heuristic-v1" }, { - "id": "reference-polkadot-hub-assets-and-smart-contracts", - "title": "Asset Hub", - "slug": "reference-polkadot-hub-assets-and-smart-contracts", + "id": "parachains-customize-runtime-pallet-development-pallet-testing", + "title": "Pallet Testing", + "slug": "parachains-customize-runtime-pallet-development-pallet-testing", "categories": [ - "Polkadot Protocol" + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-assets-and-smart-contracts.md", - "html_url": "https://docs.polkadot.com/reference/polkadot-hub/assets-and-smart-contracts/", - "preview": "The Asset Hub is a critical component in the Polkadot ecosystem, enabling the management of fungible and non-fungible assets across the network. Since the relay chain focuses on maintaining security and consensus without direct asset management, Asset Hub provides a streamlined platform for creating, managing, and using on-chain assets in a fee-efficient manner. This guide outlines the core features of Asset Hub, including how it handles asset operations, cross-chain transfers, and asset integra", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime-pallet-development-pallet-testing.md", + "html_url": "https://docs.polkadot.com/parachains/customize-runtime/pallet-development/pallet-testing/", + "preview": "Unit testing in the Polkadot SDK helps ensure that the functions provided by a pallet behave as expected. It also confirms that data and events associated with a pallet are processed correctly during interactions. The Polkadot SDK offers a set of APIs to create a test environment to simulate runtime and mock transaction execution for extrinsics and queries.", "outline": [ { "depth": 2, @@ -5109,98 +1732,28 @@ }, { "depth": 2, - "title": "Assets Basics", - "anchor": "assets-basics" - }, - { - "depth": 2, - "title": "Assets Pallet", - "anchor": "assets-pallet" - }, - { - "depth": 3, - "title": "Key Features", - "anchor": "key-features" - }, - { - "depth": 3, - "title": "Main Functions", - "anchor": "main-functions" - }, - { - "depth": 3, - "title": "Querying Functions", - "anchor": "querying-functions" - }, - { - "depth": 3, - "title": "Permission Models and Roles", - "anchor": "permission-models-and-roles" - }, - { - "depth": 3, - "title": "Asset Freezing", - "anchor": "asset-freezing" - }, - { - "depth": 3, - "title": "Non-Custodial Transfers (Approval API)", - "anchor": "non-custodial-transfers-approval-api" - }, - { - "depth": 2, - "title": "Foreign Assets", - "anchor": "foreign-assets" - }, - { - "depth": 3, - "title": "Handling Foreign Assets", - "anchor": "handling-foreign-assets" - }, - { - "depth": 2, - "title": "Integration", - "anchor": "integration" - }, - { - "depth": 3, - "title": "API Sidecar", - "anchor": "api-sidecar" - }, - { - "depth": 3, - "title": "TxWrapper", - "anchor": "txwrapper" - }, - { - "depth": 3, - "title": "Parachain Node", - "anchor": "parachain-node" - }, - { - "depth": 2, - "title": "XCM Transfer Monitoring", - "anchor": "xcm-transfer-monitoring" + "title": "Writing Unit Tests", + "anchor": "writing-unit-tests" }, { "depth": 3, - "title": "Monitor XCM Deposits", - "anchor": "monitor-xcm-deposits" + "title": "Test Initialization", + "anchor": "test-initialization" }, { "depth": 3, - "title": "Track XCM Information Back to the Source", - "anchor": "track-xcm-information-back-to-the-source" + "title": "Function Call Testing", + "anchor": "function-call-testing" }, { "depth": 3, - "title": "Practical Monitoring Examples", - "anchor": "practical-monitoring-examples" + "title": "Storage Testing", + "anchor": "storage-testing" }, { "depth": 3, - "title": "Monitor for Failed XCM Transfers", - "anchor": "monitor-for-failed-xcm-transfers" + "title": "Event Testing", + "anchor": "event-testing" }, { "depth": 2, @@ -5209,24 +1762,25 @@ } ], "stats": { - "chars": 18211, - "words": 2649, - "headings": 21, - "estimated_token_count_total": 3678 + "chars": 6892, + "words": 911, + "headings": 7, + "estimated_token_count_total": 1563 }, - "hash": "sha256:3d10c04cffc5f737ff75b079d661c2c1904629d23ae1e415e64fd6ae4e98759e", + "hash": "sha256:8568dfa238b9a649a4e6e60510625c2e7879b76a93187b0b8b8dccf6bc467ae6", "token_estimator": "heuristic-v1" }, { - "id": "reference-polkadot-hub-bridging", - "title": "Bridge Hub", - "slug": "reference-polkadot-hub-bridging", + "id": "parachains-customize-runtime", + "title": "Overview of FRAME", + "slug": "parachains-customize-runtime", "categories": [ - "Polkadot Protocol" + "Basics", + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-bridging.md", - "html_url": "https://docs.polkadot.com/reference/polkadot-hub/bridging/", - "preview": "The Bridge Hub system parachain plays a crucial role in facilitating trustless interactions between Polkadot, Kusama, Ethereum, and other blockchain ecosystems. By implementing on-chain light clients and supporting protocols like BEEFY and GRANDPA, Bridge Hub ensures seamless message transmission and state verification across chains. It also provides essential [pallets](/reference/glossary/#pallet){target=\\_blank} for sending and receiving messages, making it a cornerstone of Polkadot’s interope", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime.md", + "html_url": "https://docs.polkadot.com/parachains/customize-runtime/", + "preview": "A blockchain runtime is more than just a fixed set of rules—it's a dynamic foundation that you can shape to match your specific needs. With Polkadot SDK's [FRAME (Framework for Runtime Aggregation of Modularized Entities)](/reference/glossary/#frame-framework-for-runtime-aggregation-of-modularized-entities){target=\\_blank}, customizing your runtime is straightforward and modular. Instead of building everything from scratch, you combine pre-built pallets with your own custom logic to create a run", "outline": [ { "depth": 2, @@ -5235,392 +1789,364 @@ }, { "depth": 2, - "title": "Trustless Bridging", - "anchor": "trustless-bridging" + "title": "Understanding Your Runtime", + "anchor": "understanding-your-runtime" + }, + { + "depth": 2, + "title": "Runtime Architecture", + "anchor": "runtime-architecture" }, { "depth": 2, - "title": "Bridging Components", - "anchor": "bridging-components" + "title": "Building Blocks: Pallets", + "anchor": "building-blocks-pallets" }, { "depth": 3, - "title": "Ethereum-Specific Support", - "anchor": "ethereum-specific-support" + "title": "Pre-Built Pallets vs. Custom Pallets", + "anchor": "pre-built-pallets-vs-custom-pallets" }, { - "depth": 2, - "title": "Deployed Bridges", - "anchor": "deployed-bridges" + "depth": 3, + "title": "Pallet Structure", + "anchor": "pallet-structure" }, { "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" - } - ], - "stats": { - "chars": 5467, - "words": 776, - "headings": 6, - "estimated_token_count_total": 1220 - }, - "hash": "sha256:86734ba8bcdea7913f488edf666a6104bed0a18649d57abde82c149c41c2b871", - "token_estimator": "heuristic-v1" - }, - { - "id": "reference-polkadot-hub-collectives-and-daos", - "title": "Collectives Chain", - "slug": "reference-polkadot-hub-collectives-and-daos", - "categories": [ - "Polkadot Protocol" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-collectives-and-daos.md", - "html_url": "https://docs.polkadot.com/reference/polkadot-hub/collectives-and-daos/", - "preview": "Established through [Referendum 81](https://polkadot-old.polkassembly.io/referendum/81){target=\\_blank}, the Collectives chain operates as a dedicated parachain exclusive to the Polkadot network with no counterpart on Kusama. This specialized infrastructure provides a foundation for various on-chain governance groups essential to Polkadot's ecosystem.", - "outline": [ + "title": "How Runtime Customization Works", + "anchor": "how-runtime-customization-works" + }, { "depth": 2, - "title": "Introduction", - "anchor": "introduction" + "title": "Starting Templates", + "anchor": "starting-templates" }, { "depth": 2, - "title": "Key Collectives", - "anchor": "key-collectives" + "title": "Key Customization Scenarios", + "anchor": "key-customization-scenarios" } ], "stats": { - "chars": 2288, - "words": 293, - "headings": 2, - "estimated_token_count_total": 424 + "chars": 8237, + "words": 1101, + "headings": 9, + "estimated_token_count_total": 1828 }, - "hash": "sha256:59ec351fbb8d3a392e90f4f5bf6b62f58b21d6d7a900c5e367e5d2e09ecb3aca", + "hash": "sha256:28501589d5290f932b55cd3319f6a3fd78d7297ba42810da5ad2784a297224fd", "token_estimator": "heuristic-v1" }, { - "id": "reference-polkadot-hub-consensus-and-security-agile-coretime", - "title": "Agile Coretime", - "slug": "reference-polkadot-hub-consensus-and-security-agile-coretime", + "id": "parachains-get-started", + "title": "Get Started with Parachain Development", + "slug": "parachains-get-started", "categories": [ - "Polkadot Protocol" + "Basics", + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-agile-coretime.md", - "html_url": "https://docs.polkadot.com/reference/polkadot-hub/consensus-and-security/agile-coretime/", - "preview": "Agile Coretime is the [scheduling](https://en.wikipedia.org/wiki/Scheduling_(computing)){target=\\_blank} framework on Polkadot that lets parachains efficiently access cores, which comprise an active validator set tasked with parablock validation. As the first blockchain to enable a flexible scheduling system for blockspace production, Polkadot offers unparalleled adaptability for parachains.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-get-started.md", + "html_url": "https://docs.polkadot.com/parachains/get-started/", + "preview": "The following sections provide practical recipes for building parachains on Polkadot—each focused on specific development scenarios with step-by-step, hands-on examples.", "outline": [ { "depth": 2, - "title": "Introduction", - "anchor": "introduction" + "title": "Quick Start Guides", + "anchor": "quick-start-guides" }, { "depth": 2, - "title": "Bulk Coretime", - "anchor": "bulk-coretime" + "title": "Launch a Simple Parachain", + "anchor": "launch-a-simple-parachain" }, { - "depth": 3, - "title": "Coretime Interlacing", - "anchor": "coretime-interlacing" + "depth": 2, + "title": "Customize Your Runtime", + "anchor": "customize-your-runtime" }, { "depth": 3, - "title": "Coretime Splitting", - "anchor": "coretime-splitting" + "title": "Pallet Development", + "anchor": "pallet-development" + }, + { + "depth": 2, + "title": "Testing", + "anchor": "testing" + }, + { + "depth": 2, + "title": "Runtime Upgrades and Maintenance", + "anchor": "runtime-upgrades-and-maintenance" + }, + { + "depth": 2, + "title": "Interoperability", + "anchor": "interoperability" + }, + { + "depth": 2, + "title": "Integrations", + "anchor": "integrations" }, { "depth": 2, - "title": "On-Demand Coretime", - "anchor": "on-demand-coretime" + "title": "Additional Resources", + "anchor": "additional-resources" } ], "stats": { - "chars": 3028, - "words": 452, - "headings": 5, - "estimated_token_count_total": 619 + "chars": 7941, + "words": 631, + "headings": 9, + "estimated_token_count_total": 2292 }, - "hash": "sha256:00be43ac8d666bbe15c5c2fa5a5085697d0bb5a6f341ebbb943a209f0be355df", + "hash": "sha256:759ed27cf3d473445e33141089b652082c42a2c59eb822d6b506146fd9555e13", "token_estimator": "heuristic-v1" }, { - "id": "reference-polkadot-hub-consensus-and-security-pos-consensus", - "title": "Proof of Stake Consensus", - "slug": "reference-polkadot-hub-consensus-and-security-pos-consensus", + "id": "parachains-install-polkadot-sdk", + "title": "Install Polkadot SDK", + "slug": "parachains-install-polkadot-sdk", "categories": [ - "Polkadot Protocol" + "Basics", + "Tooling" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-pos-consensus.md", - "html_url": "https://docs.polkadot.com/reference/polkadot-hub/consensus-and-security/pos-consensus/", - "preview": "Polkadot's Proof of Stake consensus model leverages a unique hybrid approach by design to promote decentralized and secure network operations. In traditional Proof of Stake (PoS) systems, a node's ability to validate transactions is tied to its token holdings, which can lead to centralization risks and limited validator participation. Polkadot addresses these concerns through its [Nominated Proof of Stake (NPoS)](/reference/glossary/#nominated-proof-of-stake-npos){target=\\_blank} model and a com", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-install-polkadot-sdk.md", + "html_url": "https://docs.polkadot.com/parachains/install-polkadot-sdk/", + "preview": "This guide provides step-by-step instructions for installing the Polkadot SDK on macOS, Linux, and Windows. The installation process consists of two main parts:", "outline": [ { "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Nominated Proof of Stake", - "anchor": "nominated-proof-of-stake" + "title": "Install Dependencies: macOS", + "anchor": "install-dependencies-macos" }, { - "depth": 2, - "title": "Hybrid Consensus", - "anchor": "hybrid-consensus" + "depth": 3, + "title": "Before You Begin {: #before-you-begin-mac-os }", + "anchor": "before-you-begin-before-you-begin-mac-os" }, { - "depth": 2, - "title": "Block Production - BABE", - "anchor": "block-production-babe" + "depth": 3, + "title": "Install Homebrew", + "anchor": "install-homebrew" }, { "depth": 3, - "title": "Validator Participation", - "anchor": "validator-participation" + "title": "Support for Apple Silicon", + "anchor": "support-for-apple-silicon" }, { "depth": 3, - "title": "Additional Resources", - "anchor": "additional-resources" + "title": "Install Required Packages and Rust {: #install-required-packages-and-rust-mac-os }", + "anchor": "install-required-packages-and-rust-install-required-packages-and-rust-mac-os" }, { "depth": 2, - "title": "Finality Gadget - GRANDPA", - "anchor": "finality-gadget-grandpa" + "title": "Install Dependencies: Linux", + "anchor": "install-dependencies-linux" }, { "depth": 3, - "title": "Probabilistic vs. Provable Finality", - "anchor": "probabilistic-vs-provable-finality" + "title": "Before You Begin {: #before-you-begin-linux }", + "anchor": "before-you-begin-before-you-begin-linux" }, { "depth": 3, - "title": "Additional Resources", - "anchor": "additional-resources-2" + "title": "Install Required Packages and Rust {: #install-required-packages-and-rust-linux }", + "anchor": "install-required-packages-and-rust-install-required-packages-and-rust-linux" }, { "depth": 2, - "title": "Fork Choice", - "anchor": "fork-choice" + "title": "Install Dependencies: Windows (WSL)", + "anchor": "install-dependencies-windows-wsl" }, { "depth": 3, - "title": "Additional Resources", - "anchor": "additional-resources-3" + "title": "Before You Begin {: #before-you-begin-windows-wls }", + "anchor": "before-you-begin-before-you-begin-windows-wls" }, { - "depth": 2, - "title": "Bridging - BEEFY", - "anchor": "bridging-beefy" + "depth": 3, + "title": "Set Up Windows Subsystem for Linux", + "anchor": "set-up-windows-subsystem-for-linux" }, { "depth": 3, - "title": "Additional Resources", - "anchor": "additional-resources-4" - } - ], - "stats": { - "chars": 12753, - "words": 1834, - "headings": 13, - "estimated_token_count_total": 2526 - }, - "hash": "sha256:231fc555eefe5f910fb36e0c03945147d0fb235272850797391751f4444b0a9c", - "token_estimator": "heuristic-v1" - }, - { - "id": "reference-polkadot-hub-consensus-and-security-relay-chain", - "title": "Overview of the Polkadot Relay Chain", - "slug": "reference-polkadot-hub-consensus-and-security-relay-chain", - "categories": [ - "Basics", - "Polkadot Protocol", - "Parachains" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-relay-chain.md", - "html_url": "https://docs.polkadot.com/reference/polkadot-hub/consensus-and-security/relay-chain/", - "preview": "Polkadot is a next-generation blockchain protocol designed to support a multi-chain future by enabling secure communication and interoperability between different blockchains. Built as a Layer-0 protocol, Polkadot introduces innovations like application-specific Layer-1 chains ([parachains](/polkadot-protocol/architecture/parachains/){targe=\\_blank}), shared security through [Nominated Proof of Stake (NPoS)](/reference/glossary/#nominated-proof-of-stake-npos){target=\\_blank}, and cross-chain int", - "outline": [ - { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" + "title": "Install Required Packages and Rust {: #install-required-packages-and-rust-windows-wls }", + "anchor": "install-required-packages-and-rust-install-required-packages-and-rust-windows-wls" }, { "depth": 2, - "title": "Polkadot 1.0", - "anchor": "polkadot-10" - }, - { - "depth": 3, - "title": "High-Level Architecture", - "anchor": "high-level-architecture" + "title": "Build the Polkadot SDK", + "anchor": "build-the-polkadot-sdk" }, { "depth": 3, - "title": "Polkadot's Additional Functionalities", - "anchor": "polkadots-additional-functionalities" + "title": "Clone the Polkadot SDK", + "anchor": "clone-the-polkadot-sdk" }, { "depth": 3, - "title": "Polkadot's Resilience", - "anchor": "polkadots-resilience" + "title": "Compile the Polkadot SDK", + "anchor": "compile-the-polkadot-sdk" }, { "depth": 3, - "title": "Polkadot's Blockspace", - "anchor": "polkadots-blockspace" + "title": "Verify the Build", + "anchor": "verify-the-build" }, { "depth": 2, - "title": "DOT Token", - "anchor": "dot-token" - }, - { - "depth": 3, - "title": "Redenomination of DOT", - "anchor": "redenomination-of-dot" + "title": "Optional: Run the Kitchensink Node", + "anchor": "optional-run-the-kitchensink-node" }, { "depth": 3, - "title": "The Planck Unit", - "anchor": "the-planck-unit" + "title": "Run the Kitchensink Node in Development Mode", + "anchor": "run-the-kitchensink-node-in-development-mode" }, { "depth": 3, - "title": "Uses for DOT", - "anchor": "uses-for-dot" + "title": "Interact with the Kitchensink Node", + "anchor": "interact-with-the-kitchensink-node" }, { "depth": 2, - "title": "JAM and the Road Ahead", - "anchor": "jam-and-the-road-ahead" + "title": "Where to Go Next", + "anchor": "where-to-go-next" } ], "stats": { - "chars": 12458, - "words": 1774, - "headings": 11, - "estimated_token_count_total": 2580 + "chars": 16051, + "words": 2312, + "headings": 20, + "estimated_token_count_total": 3345 }, - "hash": "sha256:60f5ac9f67fb9f2188121219830538d334028b3b9e85d42bd1e7279043654e39", + "hash": "sha256:a52c05b623f3780f14be3a5f36b3d79a6c1965c2fbfd6864b512a9a70c47cd60", "token_estimator": "heuristic-v1" }, { - "id": "reference-polkadot-hub-people-and-identity", - "title": "People Chain", - "slug": "reference-polkadot-hub-people-and-identity", + "id": "parachains-integrations-indexers", + "title": "Indexers", + "slug": "parachains-integrations-indexers", "categories": [ - "Polkadot Protocol" + "Tooling", + "Dapps" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-people-and-identity.md", - "html_url": "https://docs.polkadot.com/reference/polkadot-hub/people-and-identity/", - "preview": "People chain is a specialized parachain within the Polkadot ecosystem dedicated to secure, decentralized identity management.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-indexers.md", + "html_url": "https://docs.polkadot.com/parachains/integrations/indexers/", + "preview": "Blockchain data is inherently sequential and distributed, with information stored chronologically across numerous blocks. While retrieving data from a single block through JSON-RPC API calls is straightforward, more complex queries that span multiple blocks present significant challenges:", "outline": [ { "depth": 2, - "title": "Introduction", - "anchor": "introduction" - }, - { - "depth": 2, - "title": "Identity Management System", - "anchor": "identity-management-system" - }, - { - "depth": 3, - "title": "Sub-Identities", - "anchor": "sub-identities" + "title": "The Challenge of Blockchain Data Access", + "anchor": "the-challenge-of-blockchain-data-access" }, { "depth": 2, - "title": "Verification Process", - "anchor": "verification-process" - }, - { - "depth": 3, - "title": "Judgment Requests", - "anchor": "judgment-requests" - }, - { - "depth": 3, - "title": "Judgment Classifications", - "anchor": "judgment-classifications" - }, - { - "depth": 3, - "title": "Registrars", - "anchor": "registrars" + "title": "What is a Blockchain Indexer?", + "anchor": "what-is-a-blockchain-indexer" }, { "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" + "title": "Indexer Implementations", + "anchor": "indexer-implementations" } ], "stats": { - "chars": 4750, - "words": 606, - "headings": 8, - "estimated_token_count_total": 876 + "chars": 2230, + "words": 302, + "headings": 3, + "estimated_token_count_total": 428 }, - "hash": "sha256:8239d1e8d8642cb7c10e9e5f971c99b999e9e4a87373b50bf4a691225c1e4702", + "hash": "sha256:cfcc76bb24779c9b613f2c046b6f99a0f2529c25fd82287d804f6b945b936227", "token_estimator": "heuristic-v1" }, { - "id": "reference-polkadot-hub", - "title": "reference-polkadot-hub", - "slug": "reference-polkadot-hub", + "id": "parachains-integrations-oracles", + "title": "Oracles", + "slug": "parachains-integrations-oracles", "categories": [ - "Uncategorized" + "Tooling", + "Dapps" + ], + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-oracles.md", + "html_url": "https://docs.polkadot.com/parachains/integrations/oracles/", + "preview": "Oracles enable blockchains to access external data sources. Since blockchains operate as isolated networks, they cannot natively interact with external systems - this limitation is known as the \"blockchain oracle problem.\" Oracles solves this by extracting data from external sources (like APIs, IoT devices, or other blockchains), validating it, and submitting it on-chain.", + "outline": [ + { + "depth": 2, + "title": "What is a Blockchain Oracle?", + "anchor": "what-is-a-blockchain-oracle" + }, + { + "depth": 2, + "title": "Oracle Implementations", + "anchor": "oracle-implementations" + } ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub.md", - "html_url": "https://docs.polkadot.com/reference/polkadot-hub/", - "preview": "TODO", - "outline": [], "stats": { - "chars": 5, - "words": 1, - "headings": 0, - "estimated_token_count_total": 0 + "chars": 1343, + "words": 181, + "headings": 2, + "estimated_token_count_total": 245 }, - "hash": "sha256:56ba36249ea8216ad513b13df3de6c0e490ba214897674d30331f1c7e7edbef3", + "hash": "sha256:6d8e01281a5895fd2bc4438b24c170c72a496de0b838626a53e87685aea4aa25", "token_estimator": "heuristic-v1" }, { - "id": "reference-tools-chopsticks", - "title": "reference-tools-chopsticks", - "slug": "reference-tools-chopsticks", + "id": "parachains-integrations-wallets", + "title": "Wallets", + "slug": "parachains-integrations-wallets", "categories": [ - "Uncategorized" + "Tooling", + "Dapps" + ], + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-wallets.md", + "html_url": "https://docs.polkadot.com/parachains/integrations/wallets/", + "preview": "A wallet serves as your gateway to interacting with blockchain networks. Rather than storing funds, wallets secure your private keys, controlling access to your blockchain assets. Your private key provides complete control over all permitted transactions on your blockchain account, making it essential to keep it secure.", + "outline": [ + { + "depth": 2, + "title": "What is a Blockchain Wallet?", + "anchor": "what-is-a-blockchain-wallet" + }, + { + "depth": 2, + "title": "Hot Wallets", + "anchor": "hot-wallets" + }, + { + "depth": 2, + "title": "Cold Wallets", + "anchor": "cold-wallets" + }, + { + "depth": 2, + "title": "Wallet Tools", + "anchor": "wallet-tools" + } ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-chopsticks.md", - "html_url": "https://docs.polkadot.com/reference/tools/chopsticks/", - "preview": "TODO", - "outline": [], "stats": { - "chars": 5, - "words": 1, - "headings": 0, - "estimated_token_count_total": 0 + "chars": 3588, + "words": 489, + "headings": 4, + "estimated_token_count_total": 786 }, - "hash": "sha256:56ba36249ea8216ad513b13df3de6c0e490ba214897674d30331f1c7e7edbef3", + "hash": "sha256:1c65342056983806d639fb8393fdfbdf2ef644ffd41ed749947a16fb3839753d", "token_estimator": "heuristic-v1" }, { - "id": "reference-tools-dedot", - "title": "Dedot", - "slug": "reference-tools-dedot", + "id": "parachains-interoperability-channels-between-parachains", + "title": "Opening HRMP Channels Between Parachains", + "slug": "parachains-interoperability-channels-between-parachains", "categories": [ - "Tooling", - "Dapps" + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-dedot.md", - "html_url": "https://docs.polkadot.com/reference/tools/dedot/", - "preview": "[Dedot](https://github.com/dedotdev/dedot){target=\\_blank} is a next-generation JavaScript client for Polkadot and Polkadot SDK-based blockchains. Designed to elevate the dApp development experience, Dedot is built and optimized to be lightweight and tree-shakable, offering precise types and APIs suggestions for individual Polkadot SDK-based blockchains and [ink! smart contracts](https://use.ink/){target=\\_blank}.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-channels-between-parachains.md", + "html_url": "https://docs.polkadot.com/parachains/interoperability/channels-between-parachains/", + "preview": "For establishing communication channels between parachains on the Polkadot network using the Horizontal Relay-routed Message Passing (HRMP) protocol, the following steps are required:", "outline": [ { "depth": 2, @@ -5628,66 +2154,70 @@ "anchor": "introduction" }, { - "depth": 3, - "title": "Key Features", - "anchor": "key-features" + "depth": 2, + "title": "Prerequisites", + "anchor": "prerequisites" }, { "depth": 2, - "title": "Installation", - "anchor": "installation" + "title": "Procedure to Initiate an HRMP Channel", + "anchor": "procedure-to-initiate-an-hrmp-channel" }, { - "depth": 2, - "title": "Get Started", - "anchor": "get-started" + "depth": 3, + "title": "Fund Sender Sovereign Account", + "anchor": "fund-sender-sovereign-account" }, { "depth": 3, - "title": "Initialize a Client Instance", - "anchor": "initialize-a-client-instance" + "title": "Create Channel Opening Extrinsic", + "anchor": "create-channel-opening-extrinsic" }, { "depth": 3, - "title": "Enable Type and API Suggestions", - "anchor": "enable-type-and-api-suggestions" + "title": "Craft and Submit the XCM Message from the Sender", + "anchor": "craft-and-submit-the-xcm-message-from-the-sender" + }, + { + "depth": 2, + "title": "Procedure to Accept an HRMP Channel", + "anchor": "procedure-to-accept-an-hrmp-channel" }, { "depth": 3, - "title": "Read On-Chain Data", - "anchor": "read-on-chain-data" + "title": "Fund Receiver Sovereign Account", + "anchor": "fund-receiver-sovereign-account" }, { "depth": 3, - "title": "Sign and Send Transactions", - "anchor": "sign-and-send-transactions" + "title": "Create Channel Accepting Extrinsic", + "anchor": "create-channel-accepting-extrinsic" }, { - "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" + "depth": 3, + "title": "Craft and Submit the XCM Message from the Receiver", + "anchor": "craft-and-submit-the-xcm-message-from-the-receiver" } ], "stats": { - "chars": 8855, - "words": 1100, - "headings": 9, - "estimated_token_count_total": 2300 + "chars": 10934, + "words": 1549, + "headings": 10, + "estimated_token_count_total": 2285 }, - "hash": "sha256:ba24e31e2ad94fbf1d73f1878da92dd2e1476db00170780bbdf0e65ab18bc961", + "hash": "sha256:b8de1228b9976765accd18ff724038bed6f2449367f500bc3177ab2a053abe63", "token_estimator": "heuristic-v1" }, { - "id": "reference-tools-light-clients", - "title": "Light Clients", - "slug": "reference-tools-light-clients", + "id": "parachains-interoperability-channels-with-system-parachains", + "title": "Opening HRMP Channels with System Parachains", + "slug": "parachains-interoperability-channels-with-system-parachains", "categories": [ - "Parachains", - "Tooling" + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-light-clients.md", - "html_url": "https://docs.polkadot.com/reference/tools/light-clients/", - "preview": "Light clients enable secure and efficient blockchain interaction without running a full node. They provide a trust-minimized alternative to JSON-RPC by verifying data through cryptographic proofs rather than blindly trusting remote nodes.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-channels-with-system-parachains.md", + "html_url": "https://docs.polkadot.com/parachains/interoperability/channels-with-system-parachains/", + "preview": "While establishing Horizontal Relay-routed Message Passing (HRMP) channels between regular parachains involves a two-step request and acceptance procedure, opening channels with system parachains follows a more straightforward approach.", "outline": [ { "depth": 2, @@ -5696,55 +2226,50 @@ }, { "depth": 2, - "title": "Light Clients Workflow", - "anchor": "light-clients-workflow" - }, - { - "depth": 2, - "title": "JSON-RPC and Light Client Comparison", - "anchor": "json-rpc-and-light-client-comparison" + "title": "Prerequisites", + "anchor": "prerequisites" }, { "depth": 2, - "title": "Using Light Clients", - "anchor": "using-light-clients" + "title": "Procedure to Establish an HRMP Channel", + "anchor": "procedure-to-establish-an-hrmp-channel" }, { "depth": 3, - "title": "PAPI Light Client Support", - "anchor": "papi-light-client-support" + "title": "Fund Parachain Sovereign Account", + "anchor": "fund-parachain-sovereign-account" }, { "depth": 3, - "title": "Substrate Connect - Browser Extension", - "anchor": "substrate-connect-browser-extension" + "title": "Create Establish Channel with System Extrinsic", + "anchor": "create-establish-channel-with-system-extrinsic" }, { - "depth": 2, - "title": "Resources", - "anchor": "resources" + "depth": 3, + "title": "Craft and Submit the XCM Message", + "anchor": "craft-and-submit-the-xcm-message" } ], "stats": { - "chars": 6490, - "words": 870, - "headings": 7, - "estimated_token_count_total": 1430 + "chars": 7203, + "words": 889, + "headings": 6, + "estimated_token_count_total": 1427 }, - "hash": "sha256:1284c42be692167e01bcc44e2e134ec20615402675fac26df246c00aa1588d80", + "hash": "sha256:b501d99c464fb049d46676827b6a325a195c90617becc4a7db305441c115350a", "token_estimator": "heuristic-v1" }, { - "id": "reference-tools-moonwall", - "title": "E2E Testing with Moonwall", - "slug": "reference-tools-moonwall", + "id": "parachains-interoperability-get-started", + "title": "Get Started with XCM", + "slug": "parachains-interoperability-get-started", "categories": [ - "Parachains", - "Tooling" + "Basics", + "Polkadot Protocol" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-moonwall.md", - "html_url": "https://docs.polkadot.com/reference/tools/moonwall/", - "preview": "Moonwall is an end-to-end testing framework designed explicitly for Polkadot SDK-based blockchain networks. It addresses one of the most significant challenges in blockchain development: managing complex test environments and network configurations.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md", + "html_url": "https://docs.polkadot.com/parachains/interoperability/get-started/", + "preview": "Polkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems.", "outline": [ { "depth": 2, @@ -5753,65 +2278,54 @@ }, { "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" + "title": "Messaging Format", + "anchor": "messaging-format" }, { "depth": 2, - "title": "Install Moonwall", - "anchor": "install-moonwall" - }, - { - "depth": 3, - "title": "Global Installation", - "anchor": "global-installation" - }, - { - "depth": 3, - "title": "Local Installation", - "anchor": "local-installation" + "title": "The Four Principles of XCM", + "anchor": "the-four-principles-of-xcm" }, { "depth": 2, - "title": "Initialize Moonwall", - "anchor": "initialize-moonwall" + "title": "The XCM Tech Stack", + "anchor": "the-xcm-tech-stack" }, { "depth": 2, - "title": "Writing Tests", - "anchor": "writing-tests" + "title": "Core Functionalities of XCM", + "anchor": "core-functionalities-of-xcm" }, { "depth": 2, - "title": "Running the Tests", - "anchor": "running-the-tests" + "title": "XCM Example", + "anchor": "xcm-example" }, { "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" + "title": "Overview", + "anchor": "overview" } ], "stats": { - "chars": 10240, - "words": 1295, - "headings": 9, - "estimated_token_count_total": 2453 + "chars": 7451, + "words": 975, + "headings": 7, + "estimated_token_count_total": 1501 }, - "hash": "sha256:2c77cfb38bb2e466a8f56dabbb706fcd2e90cf1634fc9beb7f0ee95a75735653", + "hash": "sha256:71ec75e18ea13b80d5955f96c10edd86ba679379d508a16c77e638f57a19361d", "token_estimator": "heuristic-v1" }, { - "id": "reference-tools-omninode", - "title": "Polkadot Omni Node", - "slug": "reference-tools-omninode", + "id": "parachains-launch-a-parachain-deploy-to-polkadot", + "title": "Deploy on Polkadot", + "slug": "parachains-launch-a-parachain-deploy-to-polkadot", "categories": [ - "Parachains", - "Tooling" + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-omninode.md", - "html_url": "https://docs.polkadot.com/reference/tools/omninode/", - "preview": "The [`polkadot-omni-node`](https://crates.io/crates/polkadot-omni-node/0.7.0){target=\\_blank} crate is a versatile, pre-built binary designed to simplify running parachains in the Polkadot ecosystem. Unlike traditional node binaries that are tightly coupled to specific runtime code, the `polkadot-omni-node` operates using an external [chain specification](/polkadot-protocol/glossary#chain-specification){target=\\_blank} file, allowing it to adapt dynamically to different parachains.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-launch-a-parachain-deploy-to-polkadot.md", + "html_url": "https://docs.polkadot.com/parachains/launch-a-parachain/deploy-to-polkadot/", + "preview": "Previously, you learned how to [choose and set up a parachain template](/parachains/launch-a-parachain/choose-a-template/){target=\\_blank}. Now, you'll take the next step towards a production-like environment by deploying your parachain to the Polkadot TestNet. Deploying to a TestNet is a crucial step for validating your parachain's functionality and preparing it for eventual MainNet deployment.", "outline": [ { "depth": 2, @@ -5820,65 +2334,64 @@ }, { "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" + "title": "Get Started with an Account and Tokens", + "anchor": "get-started-with-an-account-and-tokens" }, { "depth": 2, - "title": "Install Polkadot Omni Node", - "anchor": "install-polkadot-omni-node" + "title": "Reserve a Parachain Identifier", + "anchor": "reserve-a-parachain-identifier" }, { "depth": 2, - "title": "Obtain Chain Specifications", - "anchor": "obtain-chain-specifications" + "title": "Generate Custom Keys for Your Collators", + "anchor": "generate-custom-keys-for-your-collators" }, { "depth": 2, - "title": "Run a Parachain Full Node", - "anchor": "run-a-parachain-full-node" + "title": "Generate the Chain Specification", + "anchor": "generate-the-chain-specification" }, { "depth": 2, - "title": "Interact with the Node", - "anchor": "interact-with-the-node" + "title": "Export Required Files", + "anchor": "export-required-files" }, { "depth": 2, - "title": "Parachain Compatibility", - "anchor": "parachain-compatibility" + "title": "Register a Parathread", + "anchor": "register-a-parathread" }, { - "depth": 3, - "title": "Required Runtime APIs", - "anchor": "required-runtime-apis" + "depth": 2, + "title": "Start the Collator Node", + "anchor": "start-the-collator-node" }, { - "depth": 3, - "title": "Required Pallets", - "anchor": "required-pallets" + "depth": 2, + "title": "Producing Blocks", + "anchor": "producing-blocks" } ], "stats": { - "chars": 8913, - "words": 1164, + "chars": 20252, + "words": 2357, "headings": 9, - "estimated_token_count_total": 2017 + "estimated_token_count_total": 4129 }, - "hash": "sha256:7db2d31ba37abad20b026c875f632b89739b45707e58809e2e8b32a09715c6f9", + "hash": "sha256:7309d3487c653951bf264013eb3402a72a1cbb5e0b6f89ae4e678f239cd63b80", "token_estimator": "heuristic-v1" }, { - "id": "reference-tools-papi", - "title": "Polkadot-API", - "slug": "reference-tools-papi", + "id": "parachains-launch-a-parachain-obtain-coretime", + "title": "Obtain Coretime", + "slug": "parachains-launch-a-parachain-obtain-coretime", "categories": [ - "Tooling", - "Dapps" + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-papi.md", - "html_url": "https://docs.polkadot.com/reference/tools/papi/", - "preview": "[Polkadot-API](https://github.com/polkadot-api/polkadot-api){target=\\_blank} (PAPI) is a set of libraries built to be modular, composable, and grounded in a “light-client first” approach. Its primary aim is to equip dApp developers with an extensive toolkit for building fully decentralized applications.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-launch-a-parachain-obtain-coretime.md", + "html_url": "https://docs.polkadot.com/parachains/launch-a-parachain/obtain-coretime/", + "preview": "After deploying a parachain to Paseo in the [Deploy on Polkadot](/parachains/launch-a-parachain/deploy-to-polkadot/){target=\\_blank} tutorial, the next critical step is obtaining coretime. Coretime is the mechanism through which validation resources are allocated from the relay chain to your parachain. Your parachain can only produce and finalize blocks on the relay chain by obtaining coretime.", "outline": [ { "depth": 2, @@ -5887,136 +2400,130 @@ }, { "depth": 2, - "title": "Get Started", - "anchor": "get-started" + "title": "Prerequisites", + "anchor": "prerequisites" }, { - "depth": 3, - "title": "API Instantiation", - "anchor": "api-instantiation" + "depth": 2, + "title": "Order On-Demand Coretime", + "anchor": "order-on-demand-coretime" }, { "depth": 3, - "title": "Reading Chain Data", - "anchor": "reading-chain-data" + "title": "On-Demand Extrinsics", + "anchor": "on-demand-extrinsics" }, { "depth": 3, - "title": "Sending Transactions", - "anchor": "sending-transactions" + "title": "Place an On-Demand Order", + "anchor": "place-an-on-demand-order" }, { "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" - } - ], - "stats": { - "chars": 8957, - "words": 1156, - "headings": 6, - "estimated_token_count_total": 1987 - }, - "hash": "sha256:2ca93b09d3bb9159bbf53816886a9b242bb3c13b996c51fd52962e049e2d5477", - "token_estimator": "heuristic-v1" - }, - { - "id": "reference-tools-paraspell", - "title": "ParaSpell XCM SDK", - "slug": "reference-tools-paraspell", - "categories": [ - "Uncategorized" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-paraspell.md", - "html_url": "https://docs.polkadot.com/reference/tools/paraspell/", - "preview": "[ParaSpell](https://paraspell.github.io/docs/){target=\\_blank} is a comprehensive suite of open-source tools designed to simplify cross-chain interactions within the Polkadot ecosystem. At its core, ParaSpell is dedicated to enhancing the functionality of the [XCM (Cross-Consensus Messaging)](/parachains/interoperability/get-started/){target=\\_blank} protocol by providing developers with a unified and streamlined experience for building interoperable decentralized applications (dApps).", - "outline": [ + "title": "Purchase Bulk Coretime", + "anchor": "purchase-bulk-coretime" + }, { - "depth": 2, - "title": "Introduction", - "anchor": "introduction" + "depth": 3, + "title": "Connect Your Wallet to RegionX", + "anchor": "connect-your-wallet-to-regionx" }, { "depth": 3, - "title": "ParaSpell XCM SDK", - "anchor": "paraspell-xcm-sdk" + "title": "Obtain Coretime Chain Funds", + "anchor": "obtain-coretime-chain-funds" }, { - "depth": 2, - "title": "Install ParaSpell", - "anchor": "install-paraspell" + "depth": 3, + "title": "Purchase a Core", + "anchor": "purchase-a-core" + }, + { + "depth": 3, + "title": "Verify Your Purchase", + "anchor": "verify-your-purchase" + }, + { + "depth": 3, + "title": "Assign Your Parachain to the Core", + "anchor": "assign-your-parachain-to-the-core" }, { "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" + "title": "Next Steps", + "anchor": "next-steps" } ], "stats": { - "chars": 4043, - "words": 562, - "headings": 4, - "estimated_token_count_total": 888 + "chars": 9049, + "words": 1345, + "headings": 12, + "estimated_token_count_total": 2103 }, - "hash": "sha256:c8741954ea656680aa3322c825e3f6acbaac369baaa42232b06af9e5e482f74f", + "hash": "sha256:15154f211753665d9af70dc81d15ceb3f0954e3febf9282c68c0074881d620c6", "token_estimator": "heuristic-v1" }, { - "id": "reference-tools-polkadart", - "title": "Polkadart", - "slug": "reference-tools-polkadart", + "id": "parachains-launch-a-parachain-set-up-the-parachain-template", + "title": "Set Up the Polkadot SDK Parachain Template", + "slug": "parachains-launch-a-parachain-set-up-the-parachain-template", "categories": [ - "Tooling", - "Dapps" + "Basics", + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-polkadart.md", - "html_url": "https://docs.polkadot.com/reference/tools/polkadart/", - "preview": "Polkadart is the most comprehensive Dart/Flutter SDK for interacting with Polkadot, Substrate, and other compatible blockchain networks. Designed with a Dart-first approach and type-safe APIs, it provides everything developers need to build powerful decentralized applications.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-launch-a-parachain-set-up-the-parachain-template.md", + "html_url": "https://docs.polkadot.com/parachains/launch-a-parachain/set-up-the-parachain-template/", + "preview": "The [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\\_blank} includes several [templates](/parachains/customize-runtime/#starting-templates){target=\\_blank} designed to help you quickly start building your own blockchain. Each template offers a different level of configuration, from minimal setups to feature-rich environments, allowing you to choose the foundation that best fits your project's needs.", "outline": [ { "depth": 2, - "title": "Installation", - "anchor": "installation" + "title": "Introduction", + "anchor": "introduction" + }, + { + "depth": 2, + "title": "Prerequisites", + "anchor": "prerequisites" }, { "depth": 2, - "title": "Get Started", - "anchor": "get-started" + "title": "Polkadot SDK Utility Tools", + "anchor": "polkadot-sdk-utility-tools" }, { - "depth": 3, - "title": "Type Generation", - "anchor": "type-generation" + "depth": 2, + "title": "Clone the Template", + "anchor": "clone-the-template" }, { - "depth": 3, - "title": "Run Generator", - "anchor": "run-generator" + "depth": 2, + "title": "Explore the Project Structure", + "anchor": "explore-the-project-structure" }, { - "depth": 3, - "title": "Use Generated Types", - "anchor": "use-generated-types" + "depth": 2, + "title": "Compile the Runtime", + "anchor": "compile-the-runtime" }, { - "depth": 3, - "title": "Creating an API Instance", - "anchor": "creating-an-api-instance" + "depth": 2, + "title": "Verify the Build", + "anchor": "verify-the-build" }, { - "depth": 3, - "title": "Reading Chain Data", - "anchor": "reading-chain-data" + "depth": 2, + "title": "Run the Node Locally", + "anchor": "run-the-node-locally" }, { - "depth": 3, - "title": "Subscribe to New Blocks", - "anchor": "subscribe-to-new-blocks" + "depth": 2, + "title": "Interact with the Node", + "anchor": "interact-with-the-node" }, { - "depth": 3, - "title": "Send a Transaction", - "anchor": "send-a-transaction" + "depth": 2, + "title": "Stop the Node", + "anchor": "stop-the-node" }, { "depth": 2, @@ -6025,92 +2532,70 @@ } ], "stats": { - "chars": 5178, - "words": 624, - "headings": 10, - "estimated_token_count_total": 1084 + "chars": 10588, + "words": 1510, + "headings": 11, + "estimated_token_count_total": 2375 }, - "hash": "sha256:7f533abe61586af8438e350c41b741d74a8edb839f9dc4139bc4619ba3748258", + "hash": "sha256:380063fe7c00ae8bde05fa76688b8ae4902e6566147f1cfe0e0260ad1aa05aa6", "token_estimator": "heuristic-v1" }, { - "id": "reference-tools-polkadot-js-api", - "title": "Polkadot.js API", - "slug": "reference-tools-polkadot-js-api", + "id": "parachains-runtime-maintenance-runtime-upgrades", + "title": "Runtime Upgrades", + "slug": "parachains-runtime-maintenance-runtime-upgrades", "categories": [ - "Tooling", - "Dapps" + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-polkadot-js-api.md", - "html_url": "https://docs.polkadot.com/reference/tools/polkadot-js-api/", - "preview": "!!! warning \"Maintenance Mode Only\" The Polkadot.js API is now in maintenance mode and is no longer actively developed. New projects should use [Dedot](/develop/toolkit/api-libraries/dedot){target=\\_blank} (TypeScript-first API) or [Polkadot API](/develop/toolkit/api-libraries/papi){target=\\_blank} (modern, type-safe API) as actively maintained alternatives.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-runtime-maintenance-runtime-upgrades.md", + "html_url": "https://docs.polkadot.com/parachains/runtime-maintenance/runtime-upgrades/", + "preview": "One of the defining features of Polkadot SDK-based blockchains is the ability to perform forkless runtime upgrades. Unlike traditional blockchains, which require hard forks and node coordination for upgrades, Polkadot networks enable seamless updates without network disruption.", "outline": [ { "depth": 2, "title": "Introduction", "anchor": "introduction" }, - { - "depth": 3, - "title": "Dynamic API Generation", - "anchor": "dynamic-api-generation" - }, - { - "depth": 3, - "title": "Available API Categories", - "anchor": "available-api-categories" - }, - { - "depth": 2, - "title": "Installation", - "anchor": "installation" - }, { "depth": 2, - "title": "Get Started", - "anchor": "get-started" - }, - { - "depth": 3, - "title": "Creating an API Instance", - "anchor": "creating-an-api-instance" + "title": "How Runtime Upgrades Work", + "anchor": "how-runtime-upgrades-work" }, { "depth": 3, - "title": "Reading Chain Data", - "anchor": "reading-chain-data" + "title": "Runtime Versioning", + "anchor": "runtime-versioning" }, { "depth": 3, - "title": "Sending Transactions", - "anchor": "sending-transactions" + "title": "Accessing the Runtime Version", + "anchor": "accessing-the-runtime-version" }, { "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" + "title": "Storage Migrations", + "anchor": "storage-migrations" } ], "stats": { - "chars": 5042, - "words": 684, - "headings": 9, - "estimated_token_count_total": 1166 + "chars": 5837, + "words": 811, + "headings": 5, + "estimated_token_count_total": 1161 }, - "hash": "sha256:ed3986f30880fefca5975fcdc847c68b4aca65862c63e3002b25391b0521781d", + "hash": "sha256:ec31270001a6cd9d0a8ecb7974ad161d5c1ef4d3023d5a6af9fbc5a6ca46cbca", "token_estimator": "heuristic-v1" }, { - "id": "reference-tools-py-substrate-interface", - "title": "Python Substrate Interface", - "slug": "reference-tools-py-substrate-interface", + "id": "parachains-runtime-maintenance-storage-migrations", + "title": "Storage Migrations", + "slug": "parachains-runtime-maintenance-storage-migrations", "categories": [ - "Tooling", - "Dapps" + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-py-substrate-interface.md", - "html_url": "https://docs.polkadot.com/reference/tools/py-substrate-interface/", - "preview": "The [Python Substrate Interface](https://github.com/polkascan/py-substrate-interface){target=\\_blank} is a powerful library that enables interaction with Polkadot SDK-based chains. It provides essential functionality for:", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-runtime-maintenance-storage-migrations.md", + "html_url": "https://docs.polkadot.com/parachains/runtime-maintenance/storage-migrations/", + "preview": "Storage migrations are a crucial part of the runtime upgrade process. They allow you to update the [storage items](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/attr.storage.html){target=\\_blank} of your blockchain, adapting to changes in the runtime. Whenever you change the encoding or data types used to represent data in storage, you'll need to provide a storage migration to ensure the runtime can correctly interpret the existing stored values in the new runtime", "outline": [ { "depth": 2, @@ -6119,55 +2604,69 @@ }, { "depth": 2, - "title": "Installation", - "anchor": "installation" + "title": "Storage Migration Scenarios", + "anchor": "storage-migration-scenarios" }, { "depth": 2, - "title": "Get Started", - "anchor": "get-started" + "title": "Implement Storage Migrations", + "anchor": "implement-storage-migrations" + }, + { + "depth": 3, + "title": "Core Migration Function", + "anchor": "core-migration-function" + }, + { + "depth": 3, + "title": "Migration Testing Hooks", + "anchor": "migration-testing-hooks" }, { "depth": 3, - "title": "Establishing Connection", - "anchor": "establishing-connection" + "title": "Migration Structure", + "anchor": "migration-structure" }, { "depth": 3, - "title": "Reading Chain State", - "anchor": "reading-chain-state" + "title": "Migration Organization", + "anchor": "migration-organization" }, { "depth": 3, - "title": "Submitting Transactions", - "anchor": "submitting-transactions" + "title": "Scheduling Migrations", + "anchor": "scheduling-migrations" }, { "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" + "title": "Single-Block Migrations", + "anchor": "single-block-migrations" + }, + { + "depth": 2, + "title": "Multi Block Migrations", + "anchor": "multi-block-migrations" } ], "stats": { - "chars": 4302, - "words": 541, - "headings": 7, - "estimated_token_count_total": 942 + "chars": 18500, + "words": 2363, + "headings": 10, + "estimated_token_count_total": 4014 }, - "hash": "sha256:8987fc35cd28602054ee018031f773e2e3837425107c51d0e2ac68a94b86e9c0", + "hash": "sha256:55dc252fdecf1590048ce8d009b822e90231442abe81e9593cf1635944a31336", "token_estimator": "heuristic-v1" }, { - "id": "reference-tools-sidecar", - "title": "Sidecar REST API", - "slug": "reference-tools-sidecar", + "id": "parachains-runtime-maintenance-unlock-parachains", + "title": "Unlock a Parachain", + "slug": "parachains-runtime-maintenance-unlock-parachains", "categories": [ - "Tooling", - "Dapps" + "Parachains" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-sidecar.md", - "html_url": "https://docs.polkadot.com/reference/tools/sidecar/", - "preview": "The [Sidecar REST API](https://github.com/paritytech/substrate-api-sidecar){target=\\_blank} is a service that provides a REST interface for interacting with Polkadot SDK-based blockchains. With this API, developers can easily access a broad range of endpoints for nodes, accounts, transactions, parachains, and more.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-runtime-maintenance-unlock-parachains.md", + "html_url": "https://docs.polkadot.com/parachains/runtime-maintenance/unlock-parachains/", + "preview": "Parachain locks are a critical security mechanism in the Polkadot ecosystem designed to maintain decentralization during the parachain lifecycle. These locks prevent potential centralization risks that could emerge during the early stages of parachain operation.", "outline": [ { "depth": 2, @@ -6176,50 +2675,50 @@ }, { "depth": 2, - "title": "Prerequisites", - "anchor": "prerequisites" + "title": "Check If the Parachain Is Locked", + "anchor": "check-if-the-parachain-is-locked" }, { "depth": 2, - "title": "Installation", - "anchor": "installation" + "title": "How to Unlock a Parachain", + "anchor": "how-to-unlock-a-parachain" }, { - "depth": 2, - "title": "Usage", - "anchor": "usage" + "depth": 3, + "title": "Prepare the Unlock Call", + "anchor": "prepare-the-unlock-call" }, { "depth": 3, - "title": "Endpoints", - "anchor": "endpoints" + "title": "Fund the Sovereign Account", + "anchor": "fund-the-sovereign-account" }, { - "depth": 2, - "title": "Where to Go Next", - "anchor": "where-to-go-next" + "depth": 3, + "title": "Craft and Submit the XCM", + "anchor": "craft-and-submit-the-xcm" } ], "stats": { - "chars": 7309, - "words": 1033, + "chars": 9232, + "words": 1276, "headings": 6, - "estimated_token_count_total": 1945 + "estimated_token_count_total": 2028 }, - "hash": "sha256:0795462182cb97256bb5c2acb035855fe0d6557185de8ac99482725ecb4f94c1", + "hash": "sha256:e408d05199cc184fc6fe8bb212efb3c9aa6cb79258977e07566692176c912def", "token_estimator": "heuristic-v1" }, { - "id": "reference-tools-subxt", - "title": "Subxt Rust API", - "slug": "reference-tools-subxt", + "id": "parachains-testing-fork-a-parachain", + "title": "Fork a Parachain Using Chopsticks", + "slug": "parachains-testing-fork-a-parachain", "categories": [ - "Tooling", - "Dapps" + "Parachains", + "Tooling" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-subxt.md", - "html_url": "https://docs.polkadot.com/reference/tools/subxt/", - "preview": "Subxt is a Rust library designed to interact with Polkadot SDK-based blockchains. It provides a type-safe interface for submitting transactions, querying on-chain state, and performing other blockchain interactions. By leveraging Rust's strong type system, subxt ensures that your code is validated at compile time, reducing runtime errors and improving reliability.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-fork-a-parachain.md", + "html_url": "https://docs.polkadot.com/parachains/testing/fork-a-parachain/", + "preview": "[Chopsticks](https://github.com/AcalaNetwork/chopsticks/){target=\\_blank}, developed by the [Acala Foundation](https://github.com/AcalaNetwork){target=\\_blank}, is a versatile tool tailored for developers working on Polkadot SDK-based blockchains. With Chopsticks, you can fork live chains locally, replay blocks to analyze extrinsics, and simulate complex scenarios like XCM interactions all without deploying to a live network.", "outline": [ { "depth": 2, @@ -6233,38 +2732,38 @@ }, { "depth": 2, - "title": "Installation", - "anchor": "installation" + "title": "Install Chopsticks", + "anchor": "install-chopsticks" }, { - "depth": 2, - "title": "Get Started", - "anchor": "get-started" + "depth": 3, + "title": "Global Installation", + "anchor": "global-installation" }, { "depth": 3, - "title": "Download Chain Metadata", - "anchor": "download-chain-metadata" + "title": "Local Installation", + "anchor": "local-installation" }, { - "depth": 3, - "title": "Generate Type-Safe Interfaces", - "anchor": "generate-type-safe-interfaces" + "depth": 2, + "title": "Configure Chopsticks", + "anchor": "configure-chopsticks" }, { "depth": 3, - "title": "Initialize the Subxt Client", - "anchor": "initialize-the-subxt-client" + "title": "Configuration File", + "anchor": "configuration-file" }, { "depth": 3, - "title": "Read Chain Data", - "anchor": "read-chain-data" + "title": "CLI Flags", + "anchor": "cli-flags" }, { - "depth": 3, - "title": "Submit Transactions", - "anchor": "submit-transactions" + "depth": 2, + "title": "WebSocket Commands", + "anchor": "websocket-commands" }, { "depth": 2, @@ -6273,26 +2772,25 @@ } ], "stats": { - "chars": 9174, - "words": 1175, + "chars": 10916, + "words": 1333, "headings": 10, - "estimated_token_count_total": 2187 + "estimated_token_count_total": 2614 }, - "hash": "sha256:56269d9ea47f5b4e92cd7d5a1e65ab06d181a9c380f90bb3ef285529b12299f7", + "hash": "sha256:2079ef331bde286e281ca1b4bffc6c7c86844bad08c728131d1787dbe977d56e", "token_estimator": "heuristic-v1" }, { - "id": "reference-tools-xcm-tools", - "title": "XCM Tools", - "slug": "reference-tools-xcm-tools", + "id": "parachains-testing-run-a-parachain-network", + "title": "Run a Parachain Network", + "slug": "parachains-testing-run-a-parachain-network", "categories": [ - "Basics", - "Tooling", - "Dapps" + "Parachains", + "Tooling" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-xcm-tools.md", - "html_url": "https://docs.polkadot.com/reference/tools/xcm-tools/", - "preview": "As described in the [Interoperability](/develop/interoperability){target=\\_blank} section, XCM (Cross-Consensus Messaging) is a protocol used in the Polkadot and Kusama ecosystems to enable communication and interaction between chains. It facilitates cross-chain communication, allowing assets, data, and messages to flow seamlessly across the ecosystem.", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-run-a-parachain-network.md", + "html_url": "https://docs.polkadot.com/parachains/testing/run-a-parachain-network/", + "preview": "Zombienet is a robust testing framework designed for Polkadot SDK-based blockchain networks. It enables developers to efficiently deploy and test ephemeral blockchain environments on platforms like Kubernetes, Podman, and native setups. With its simple and versatile CLI, Zombienet provides an all-in-one solution for spawning networks, running tests, and validating performance.", "outline": [ { "depth": 2, @@ -6301,106 +2799,63 @@ }, { "depth": 2, - "title": "Popular XCM Tools", - "anchor": "popular-xcm-tools" + "title": "Install Zombienet", + "anchor": "install-zombienet" }, { - "depth": 3, - "title": "Moonsong Labs XCM Tools", - "anchor": "moonsong-labs-xcm-tools" + "depth": 2, + "title": "Providers", + "anchor": "providers" }, { "depth": 3, - "title": "ParaSpell", - "anchor": "paraspell" + "title": "Kubernetes", + "anchor": "kubernetes" }, { "depth": 3, - "title": "Astar XCM Tools", - "anchor": "astar-xcm-tools" + "title": "Podman", + "anchor": "podman" }, { "depth": 3, - "title": "Chopsticks", - "anchor": "chopsticks" + "title": "Local Provider", + "anchor": "local-provider" }, - { - "depth": 3, - "title": "Moonbeam XCM SDK", - "anchor": "moonbeam-xcm-sdk" - } - ], - "stats": { - "chars": 6146, - "words": 852, - "headings": 7, - "estimated_token_count_total": 1377 - }, - "hash": "sha256:674e4f60c82fc7544c7af8e09f1e0f677c9907cdff88b107f6c8489e97a43487", - "token_estimator": "heuristic-v1" - }, - { - "id": "reference-tools-zombienet", - "title": "reference-tools-zombienet", - "slug": "reference-tools-zombienet", - "categories": [ - "Uncategorized" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-zombienet.md", - "html_url": "https://docs.polkadot.com/reference/tools/zombienet/", - "preview": "TODO", - "outline": [], - "stats": { - "chars": 5, - "words": 1, - "headings": 0, - "estimated_token_count_total": 0 - }, - "hash": "sha256:56ba36249ea8216ad513b13df3de6c0e490ba214897674d30331f1c7e7edbef3", - "token_estimator": "heuristic-v1" - }, - { - "id": "reference", - "title": "Technical Reference Overview", - "slug": "reference", - "categories": [ - "Basics", - "Polkadot Protocol", - "Reference" - ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference.md", - "html_url": "https://docs.polkadot.com/reference/", - "preview": "The Technical Reference section provides comprehensive documentation of Polkadot's architecture, core concepts, and development tooling. Whether you're exploring how Polkadot's relay chain coordinates parachains, understanding governance mechanisms, or building applications on the network, this reference covers the technical foundations you need.", - "outline": [ { "depth": 2, - "title": "Introduction", - "anchor": "introduction" + "title": "Configure Zombienet", + "anchor": "configure-zombienet" }, { - "depth": 2, - "title": "Polkadot Hub", - "anchor": "polkadot-hub" + "depth": 3, + "title": "Configuration Files", + "anchor": "configuration-files" }, { - "depth": 2, - "title": "Parachains", - "anchor": "parachains" + "depth": 3, + "title": "CLI Usage", + "anchor": "cli-usage" }, { - "depth": 2, - "title": "On-Chain Governance", - "anchor": "on-chain-governance" + "depth": 3, + "title": "Settings", + "anchor": "settings" }, { - "depth": 2, - "title": "Glossary", - "anchor": "glossary" + "depth": 3, + "title": "Relay Chain Configuration", + "anchor": "relay-chain-configuration" }, { - "depth": 2, - "title": "Tools", - "anchor": "tools" + "depth": 3, + "title": "Parachain Configuration", + "anchor": "parachain-configuration" + }, + { + "depth": 3, + "title": "XCM Configuration", + "anchor": "xcm-configuration" }, { "depth": 2, @@ -6409,12 +2864,12 @@ } ], "stats": { - "chars": 7648, - "words": 937, - "headings": 7, - "estimated_token_count_total": 1682 + "chars": 41664, + "words": 4603, + "headings": 14, + "estimated_token_count_total": 9871 }, - "hash": "sha256:9f71f3b4018f7a9e127cff51fab7cfe1168adcde2553cd1fc5dc8c25fb97a30d", + "hash": "sha256:2007d6d01c9b915f613eba0aae53c80e61898bc61b5033c82a5c20324065b81f", "token_estimator": "heuristic-v1" }, { @@ -6512,7 +2967,7 @@ }, { "depth": 2, - "title": "Set Up the dApp Project", + "title": "Set Up the DApp Project", "anchor": "set-up-the-dapp-project" }, { @@ -6582,7 +3037,7 @@ "headings": 22, "estimated_token_count_total": 6967 }, - "hash": "sha256:b200f93a9179f0b2588ba722dd4c118536136faf3c39eabccf4abf5c346f78a8", + "hash": "sha256:59084ceaad3ff22227c58d4fe3af81ee968ca33fb5bffd256bdc92a1ffe7a0c4", "token_estimator": "heuristic-v1" }, { @@ -7717,7 +4172,7 @@ }, { "id": "smart-contracts-faucet", - "title": "Faucet", + "title": "Get Tokens from the Official Faucet", "slug": "smart-contracts-faucet", "categories": [ "Smart Contracts" @@ -8032,8 +4487,8 @@ "outline": [ { "depth": 2, - "title": "Overview", - "anchor": "overview" + "title": "Introduction", + "anchor": "introduction" }, { "depth": 2, @@ -8067,12 +4522,12 @@ } ], "stats": { - "chars": 5234, + "chars": 5238, "words": 751, "headings": 7, "estimated_token_count_total": 1046 }, - "hash": "sha256:dd29fab6e3c00d720b10effa4e50373a6fe9ab4b7bfd3aea892c7fa9c84318a2", + "hash": "sha256:e7ec7e9746d9314405d09c78db4da888054871eb48cd4881a0bade00e9b05edc", "token_estimator": "heuristic-v1" }, { @@ -8410,14 +4865,14 @@ "token_estimator": "heuristic-v1" }, { - "id": "smart-contracts-integrations-indexers", - "title": "smart-contracts-integrations-indexers", - "slug": "smart-contracts-integrations-indexers", + "id": "smart-contracts-integrations-.indexers", + "title": "smart-contracts-integrations-.indexers", + "slug": "smart-contracts-integrations-.indexers", "categories": [ "Uncategorized" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-integrations-indexers.md", - "html_url": "https://docs.polkadot.com/smart-contracts/integrations/indexers/", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-integrations-.indexers.md", + "html_url": "https://docs.polkadot.com/smart-contracts/integrations/.indexers/", "preview": "TODO", "outline": [], "stats": { @@ -8430,14 +4885,14 @@ "token_estimator": "heuristic-v1" }, { - "id": "smart-contracts-integrations-oracles", - "title": "smart-contracts-integrations-oracles", - "slug": "smart-contracts-integrations-oracles", + "id": "smart-contracts-integrations-.oracles", + "title": "smart-contracts-integrations-.oracles", + "slug": "smart-contracts-integrations-.oracles", "categories": [ "Uncategorized" ], - "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-integrations-oracles.md", - "html_url": "https://docs.polkadot.com/smart-contracts/integrations/oracles/", + "raw_md_url": "https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-integrations-.oracles.md", + "html_url": "https://docs.polkadot.com/smart-contracts/integrations/.oracles/", "preview": "TODO", "outline": [], "stats": { diff --git a/chain-interactions/.nav.yml b/.chain-interactions/.nav.yml similarity index 100% rename from chain-interactions/.nav.yml rename to .chain-interactions/.nav.yml diff --git a/chain-interactions/accounts/.nav.yml b/.chain-interactions/accounts/.nav.yml similarity index 100% rename from chain-interactions/accounts/.nav.yml rename to .chain-interactions/accounts/.nav.yml diff --git a/chain-interactions/accounts/create-account.md b/.chain-interactions/accounts/create-account.md similarity index 100% rename from chain-interactions/accounts/create-account.md rename to .chain-interactions/accounts/create-account.md diff --git a/chain-interactions/accounts/query-accounts.md b/.chain-interactions/accounts/query-accounts.md similarity index 100% rename from chain-interactions/accounts/query-accounts.md rename to .chain-interactions/accounts/query-accounts.md diff --git a/chain-interactions/index.md b/.chain-interactions/index.md similarity index 100% rename from chain-interactions/index.md rename to .chain-interactions/index.md diff --git a/chain-interactions/query-data/.nav.yml b/.chain-interactions/query-data/.nav.yml similarity index 100% rename from chain-interactions/query-data/.nav.yml rename to .chain-interactions/query-data/.nav.yml diff --git a/chain-interactions/query-data/query-rest.md b/.chain-interactions/query-data/query-rest.md similarity index 100% rename from chain-interactions/query-data/query-rest.md rename to .chain-interactions/query-data/query-rest.md diff --git a/chain-interactions/query-data/query-sdks.md b/.chain-interactions/query-data/query-sdks.md similarity index 100% rename from chain-interactions/query-data/query-sdks.md rename to .chain-interactions/query-data/query-sdks.md diff --git a/chain-interactions/query-data/runtime-api-calls.md b/.chain-interactions/query-data/runtime-api-calls.md similarity index 100% rename from chain-interactions/query-data/runtime-api-calls.md rename to .chain-interactions/query-data/runtime-api-calls.md diff --git a/chain-interactions/send-transactions/.nav.yml b/.chain-interactions/send-transactions/.nav.yml similarity index 100% rename from chain-interactions/send-transactions/.nav.yml rename to .chain-interactions/send-transactions/.nav.yml diff --git a/chain-interactions/send-transactions/calculate-transaction-fees.md b/.chain-interactions/send-transactions/calculate-transaction-fees.md similarity index 100% rename from chain-interactions/send-transactions/calculate-transaction-fees.md rename to .chain-interactions/send-transactions/calculate-transaction-fees.md diff --git a/chain-interactions/send-transactions/interoperability/.nav.yml b/.chain-interactions/send-transactions/interoperability/.nav.yml similarity index 100% rename from chain-interactions/send-transactions/interoperability/.nav.yml rename to .chain-interactions/send-transactions/interoperability/.nav.yml diff --git a/chain-interactions/send-transactions/interoperability/debug-and-preview-xcms.md b/.chain-interactions/send-transactions/interoperability/debug-and-preview-xcms.md similarity index 100% rename from chain-interactions/send-transactions/interoperability/debug-and-preview-xcms.md rename to .chain-interactions/send-transactions/interoperability/debug-and-preview-xcms.md diff --git a/chain-interactions/send-transactions/interoperability/estimate-xcm-fees.md b/.chain-interactions/send-transactions/interoperability/estimate-xcm-fees.md similarity index 100% rename from chain-interactions/send-transactions/interoperability/estimate-xcm-fees.md rename to .chain-interactions/send-transactions/interoperability/estimate-xcm-fees.md diff --git a/chain-interactions/send-transactions/interoperability/transfer-assets-out-of-polkadot.md b/.chain-interactions/send-transactions/interoperability/transfer-assets-out-of-polkadot.md similarity index 100% rename from chain-interactions/send-transactions/interoperability/transfer-assets-out-of-polkadot.md rename to .chain-interactions/send-transactions/interoperability/transfer-assets-out-of-polkadot.md diff --git a/chain-interactions/send-transactions/interoperability/transfer-assets-parachains.md b/.chain-interactions/send-transactions/interoperability/transfer-assets-parachains.md similarity index 96% rename from chain-interactions/send-transactions/interoperability/transfer-assets-parachains.md rename to .chain-interactions/send-transactions/interoperability/transfer-assets-parachains.md index e0113ee03..9d6f20176 100644 --- a/chain-interactions/send-transactions/interoperability/transfer-assets-parachains.md +++ b/.chain-interactions/send-transactions/interoperability/transfer-assets-parachains.md @@ -184,6 +184,6 @@ You have now successfully created and sent a cross-chain transfer using the Para ## Next Steps -- Read the Docs: Dive deeper into the features of the [ParaSpell XCM SDK](https://paraspell.github.io/docs/sdk/getting-started.html){target=\_blank} documentation. +- **Read the docs**: Dive deeper into the features of the [ParaSpell XCM SDK](https://paraspell.github.io/docs/sdk/getting-started.html){target=\_blank} documentation. -- Learn about XCM: Understand the underlying protocol by visiting the [Introduction to XCM page](/parachains/interoperability/get-started/) in the Polkadot Docs. \ No newline at end of file +- **Learn about XCM**: Understand the underlying protocol by visiting the [Get Started with XCM](/parachains/interoperability/get-started/) guide. \ No newline at end of file diff --git a/chain-interactions/send-transactions/pay-fees-with-different-tokens.md b/.chain-interactions/send-transactions/pay-fees-with-different-tokens.md similarity index 100% rename from chain-interactions/send-transactions/pay-fees-with-different-tokens.md rename to .chain-interactions/send-transactions/pay-fees-with-different-tokens.md diff --git a/chain-interactions/send-transactions/with-sdks.md b/.chain-interactions/send-transactions/with-sdks.md similarity index 100% rename from chain-interactions/send-transactions/with-sdks.md rename to .chain-interactions/send-transactions/with-sdks.md diff --git a/chain-interactions/token-operations/.nav.yml b/.chain-interactions/token-operations/.nav.yml similarity index 100% rename from chain-interactions/token-operations/.nav.yml rename to .chain-interactions/token-operations/.nav.yml diff --git a/chain-interactions/token-operations/convert-assets.md b/.chain-interactions/token-operations/convert-assets.md similarity index 100% rename from chain-interactions/token-operations/convert-assets.md rename to .chain-interactions/token-operations/convert-assets.md diff --git a/chain-interactions/token-operations/register-foreign-asset.md b/.chain-interactions/token-operations/register-foreign-asset.md similarity index 100% rename from chain-interactions/token-operations/register-foreign-asset.md rename to .chain-interactions/token-operations/register-foreign-asset.md diff --git a/chain-interactions/token-operations/register-local-asset.md b/.chain-interactions/token-operations/register-local-asset.md similarity index 100% rename from chain-interactions/token-operations/register-local-asset.md rename to .chain-interactions/token-operations/register-local-asset.md diff --git a/.nav.yml b/.nav.yml index ce7cd8449..17e5ccd0e 100644 --- a/.nav.yml +++ b/.nav.yml @@ -2,7 +2,7 @@ nav: - 'Home': index.md - 'Smart Contracts': smart-contracts - 'Parachains': parachains - - 'Chain Interactions': chain-interactions + # - 'Chain Interactions': chain-interactions # 'Get Support': get-support - 'Nodes and Validators': nodes-and-validators - - 'Technical Reference': reference + # - 'Technical Reference': reference diff --git a/reference/.nav.yml b/.reference/.nav.yml similarity index 100% rename from reference/.nav.yml rename to .reference/.nav.yml diff --git a/reference/glossary.md b/.reference/glossary.md similarity index 100% rename from reference/glossary.md rename to .reference/glossary.md diff --git a/reference/governance/index.md b/.reference/governance/index.md similarity index 100% rename from reference/governance/index.md rename to .reference/governance/index.md diff --git a/reference/governance/origins-tracks.md b/.reference/governance/origins-tracks.md similarity index 100% rename from reference/governance/origins-tracks.md rename to .reference/governance/origins-tracks.md diff --git a/reference/index.md b/.reference/index.md similarity index 100% rename from reference/index.md rename to .reference/index.md diff --git a/reference/parachains/.nav.yml b/.reference/parachains/.nav.yml similarity index 100% rename from reference/parachains/.nav.yml rename to .reference/parachains/.nav.yml diff --git a/reference/parachains/accounts.md b/.reference/parachains/accounts.md similarity index 100% rename from reference/parachains/accounts.md rename to .reference/parachains/accounts.md diff --git a/reference/parachains/blocks-transactions-fees/.nav.yml b/.reference/parachains/blocks-transactions-fees/.nav.yml similarity index 100% rename from reference/parachains/blocks-transactions-fees/.nav.yml rename to .reference/parachains/blocks-transactions-fees/.nav.yml diff --git a/reference/parachains/blocks-transactions-fees/blocks.md b/.reference/parachains/blocks-transactions-fees/blocks.md similarity index 100% rename from reference/parachains/blocks-transactions-fees/blocks.md rename to .reference/parachains/blocks-transactions-fees/blocks.md diff --git a/reference/parachains/blocks-transactions-fees/fees.md b/.reference/parachains/blocks-transactions-fees/fees.md similarity index 100% rename from reference/parachains/blocks-transactions-fees/fees.md rename to .reference/parachains/blocks-transactions-fees/fees.md diff --git a/reference/parachains/blocks-transactions-fees/transactions.md b/.reference/parachains/blocks-transactions-fees/transactions.md similarity index 100% rename from reference/parachains/blocks-transactions-fees/transactions.md rename to .reference/parachains/blocks-transactions-fees/transactions.md diff --git a/reference/parachains/chain-data.md b/.reference/parachains/chain-data.md similarity index 100% rename from reference/parachains/chain-data.md rename to .reference/parachains/chain-data.md diff --git a/reference/parachains/consensus/.nav.yml b/.reference/parachains/consensus/.nav.yml similarity index 100% rename from reference/parachains/consensus/.nav.yml rename to .reference/parachains/consensus/.nav.yml diff --git a/reference/parachains/consensus/async-backing.md b/.reference/parachains/consensus/async-backing.md similarity index 100% rename from reference/parachains/consensus/async-backing.md rename to .reference/parachains/consensus/async-backing.md diff --git a/reference/parachains/consensus/elastic-scaling.md b/.reference/parachains/consensus/elastic-scaling.md similarity index 100% rename from reference/parachains/consensus/elastic-scaling.md rename to .reference/parachains/consensus/elastic-scaling.md diff --git a/reference/parachains/consensus/index.md b/.reference/parachains/consensus/index.md similarity index 100% rename from reference/parachains/consensus/index.md rename to .reference/parachains/consensus/index.md diff --git a/reference/parachains/cryptography.md b/.reference/parachains/cryptography.md similarity index 100% rename from reference/parachains/cryptography.md rename to .reference/parachains/cryptography.md diff --git a/reference/parachains/data-encoding.md b/.reference/parachains/data-encoding.md similarity index 100% rename from reference/parachains/data-encoding.md rename to .reference/parachains/data-encoding.md diff --git a/reference/parachains/index.md b/.reference/parachains/index.md similarity index 100% rename from reference/parachains/index.md rename to .reference/parachains/index.md diff --git a/reference/parachains/interoperability.md b/.reference/parachains/interoperability.md similarity index 97% rename from reference/parachains/interoperability.md rename to .reference/parachains/interoperability.md index 3901c6928..3e071734b 100644 --- a/reference/parachains/interoperability.md +++ b/.reference/parachains/interoperability.md @@ -39,7 +39,7 @@ Through XCM, decentralized applications can: - Enable seamless user experiences where underlying blockchain differences are invisible. - XCM exemplifies Polkadot’s commitment to creating a robust and interoperable ecosystem. -For further information about XCM, check the [Introduction to XCM](/parachains/interoperability/get-started/){target=\_blank} article. +For further information about XCM, check the [Get Started with XCM](/parachains/interoperability/get-started/){target=\_blank} article. ### Bridges: Connecting External Networks diff --git a/reference/parachains/networks.md b/.reference/parachains/networks.md similarity index 100% rename from reference/parachains/networks.md rename to .reference/parachains/networks.md diff --git a/reference/parachains/node-and-runtime.md b/.reference/parachains/node-and-runtime.md similarity index 100% rename from reference/parachains/node-and-runtime.md rename to .reference/parachains/node-and-runtime.md diff --git a/reference/parachains/randomness.md b/.reference/parachains/randomness.md similarity index 100% rename from reference/parachains/randomness.md rename to .reference/parachains/randomness.md diff --git a/reference/polkadot-hub/.nav.yml b/.reference/polkadot-hub/.nav.yml similarity index 100% rename from reference/polkadot-hub/.nav.yml rename to .reference/polkadot-hub/.nav.yml diff --git a/reference/polkadot-hub/assets-and-smart-contracts.md b/.reference/polkadot-hub/assets-and-smart-contracts.md similarity index 100% rename from reference/polkadot-hub/assets-and-smart-contracts.md rename to .reference/polkadot-hub/assets-and-smart-contracts.md diff --git a/reference/polkadot-hub/bridging.md b/.reference/polkadot-hub/bridging.md similarity index 100% rename from reference/polkadot-hub/bridging.md rename to .reference/polkadot-hub/bridging.md diff --git a/reference/polkadot-hub/collectives-and-daos.md b/.reference/polkadot-hub/collectives-and-daos.md similarity index 100% rename from reference/polkadot-hub/collectives-and-daos.md rename to .reference/polkadot-hub/collectives-and-daos.md diff --git a/reference/polkadot-hub/consensus-and-security/.nav.yml b/.reference/polkadot-hub/consensus-and-security/.nav.yml similarity index 100% rename from reference/polkadot-hub/consensus-and-security/.nav.yml rename to .reference/polkadot-hub/consensus-and-security/.nav.yml diff --git a/reference/polkadot-hub/consensus-and-security/agile-coretime.md b/.reference/polkadot-hub/consensus-and-security/agile-coretime.md similarity index 100% rename from reference/polkadot-hub/consensus-and-security/agile-coretime.md rename to .reference/polkadot-hub/consensus-and-security/agile-coretime.md diff --git a/reference/polkadot-hub/consensus-and-security/pos-consensus.md b/.reference/polkadot-hub/consensus-and-security/pos-consensus.md similarity index 100% rename from reference/polkadot-hub/consensus-and-security/pos-consensus.md rename to .reference/polkadot-hub/consensus-and-security/pos-consensus.md diff --git a/reference/polkadot-hub/consensus-and-security/relay-chain.md b/.reference/polkadot-hub/consensus-and-security/relay-chain.md similarity index 100% rename from reference/polkadot-hub/consensus-and-security/relay-chain.md rename to .reference/polkadot-hub/consensus-and-security/relay-chain.md diff --git a/reference/polkadot-hub/index.md b/.reference/polkadot-hub/index.md similarity index 100% rename from reference/polkadot-hub/index.md rename to .reference/polkadot-hub/index.md diff --git a/reference/polkadot-hub/people-and-identity.md b/.reference/polkadot-hub/people-and-identity.md similarity index 100% rename from reference/polkadot-hub/people-and-identity.md rename to .reference/polkadot-hub/people-and-identity.md diff --git a/reference/tools/.nav.yml b/.reference/tools/.nav.yml similarity index 100% rename from reference/tools/.nav.yml rename to .reference/tools/.nav.yml diff --git a/reference/tools/chopsticks.md b/.reference/tools/chopsticks.md similarity index 100% rename from reference/tools/chopsticks.md rename to .reference/tools/chopsticks.md diff --git a/reference/tools/dedot.md b/.reference/tools/dedot.md similarity index 100% rename from reference/tools/dedot.md rename to .reference/tools/dedot.md diff --git a/reference/tools/light-clients.md b/.reference/tools/light-clients.md similarity index 100% rename from reference/tools/light-clients.md rename to .reference/tools/light-clients.md diff --git a/reference/tools/moonwall.md b/.reference/tools/moonwall.md similarity index 100% rename from reference/tools/moonwall.md rename to .reference/tools/moonwall.md diff --git a/reference/tools/omninode.md b/.reference/tools/omninode.md similarity index 100% rename from reference/tools/omninode.md rename to .reference/tools/omninode.md diff --git a/reference/tools/papi.md b/.reference/tools/papi.md similarity index 100% rename from reference/tools/papi.md rename to .reference/tools/papi.md diff --git a/reference/tools/paraspell.md b/.reference/tools/paraspell.md similarity index 100% rename from reference/tools/paraspell.md rename to .reference/tools/paraspell.md diff --git a/reference/tools/polkadart.md b/.reference/tools/polkadart.md similarity index 100% rename from reference/tools/polkadart.md rename to .reference/tools/polkadart.md diff --git a/reference/tools/polkadot-js-api.md b/.reference/tools/polkadot-js-api.md similarity index 100% rename from reference/tools/polkadot-js-api.md rename to .reference/tools/polkadot-js-api.md diff --git a/reference/tools/py-substrate-interface.md b/.reference/tools/py-substrate-interface.md similarity index 100% rename from reference/tools/py-substrate-interface.md rename to .reference/tools/py-substrate-interface.md diff --git a/reference/tools/sidecar.md b/.reference/tools/sidecar.md similarity index 100% rename from reference/tools/sidecar.md rename to .reference/tools/sidecar.md diff --git a/reference/tools/subxt.md b/.reference/tools/subxt.md similarity index 100% rename from reference/tools/subxt.md rename to .reference/tools/subxt.md diff --git a/reference/tools/xcm-tools.md b/.reference/tools/xcm-tools.md similarity index 100% rename from reference/tools/xcm-tools.md rename to .reference/tools/xcm-tools.md diff --git a/reference/tools/zombienet.md b/.reference/tools/zombienet.md similarity index 100% rename from reference/tools/zombienet.md rename to .reference/tools/zombienet.md diff --git a/llms-full.jsonl b/llms-full.jsonl index a4e285837..f9c65dae8 100644 --- a/llms-full.jsonl +++ b/llms-full.jsonl @@ -1,83 +1,3 @@ -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 44, "end_char": 709, "estimated_token_count": 144, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nIn this tutorial, you'll learn how to replay and dry-run XCMs using [Chopsticks](/parachains/testing/fork-a-parachain/){target=\\_blank}, a powerful tool for forking live Polkadot SDK-based chains in your local environment. These techniques are essential for:\n\n- Debugging cross-chain message failures.\n- Tracing execution across relay chains and parachains.\n- Analyzing weight usage, error types, and message flow.\n- Safely simulating XCMs without committing state changes.\n\nBy the end of this guide, you'll be able to set up a local fork, capture and replay real XCMs, and use dry-run features to diagnose and resolve complex cross-chain issues."} -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 1, "depth": 2, "title": "Prerequisites", "anchor": "prerequisites", "start_char": 709, "end_char": 1426, "estimated_token_count": 193, "token_estimator": "heuristic-v1", "text": "## Prerequisites\n\nBefore you begin, make sure you have:\n\n- [Chopsticks](/parachains/testing/fork-a-parachain/){target=\\_blank} installed (`npm i -g @acala-network/chopsticks`).\n- Access to the endpoint or genesis file of the parachain you want to fork.\n- The block number or hash where the XCM was sent.\n- (Optional) A Chopsticks config file for repeated setups.\n\nIf you haven't forked a chain before, see the [Fork a Chain with Chopsticks guide](/tutorials/polkadot-sdk/testing/fork-live-chains/){target=\\_blank} or [Fork a Network Locally using Chopsticks](https://wiki.polkadot.com/learn/learn-guides-test-opengov-proposals/#fork-a-network-locally-using-chopsticks){target=\\_blank} for step-by-step instructions."} -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 2, "depth": 2, "title": "Set Up Your Project", "anchor": "set-up-your-project", "start_char": 1426, "end_char": 2258, "estimated_token_count": 194, "token_estimator": "heuristic-v1", "text": "## Set Up Your Project\n\nLet's start by creating a dedicated workspace for your XCM replay and dry-run experiments.\n\n1. Create a new directory and navigate into it:\n\n ```bash\n mkdir -p replay-xcm-tests\n cd replay-xcm-tests\n ```\n\n2. Initialize a new Node project:\n\n ```bash\n npm init -y\n ```\n\n3. Install Chopsticks globally (recommended to avoid conflicts with local installs):\n\n ```bash\n npm install -g @acala-network/chopsticks@latest\n ```\n\n4. Install TypeScript and related tooling for local development:\n\n ```bash\n npm install --save-dev typescript @types/node tsx\n ```\n\n5. Install the required Polkadot packages:\n\n ```bash\n npm install polkadot-api @polkadot-labs/hdkd @polkadot-labs/hdkd-helpers\n ```\n\n6. Initialize the TypeScript config:\n\n ```bash\n npx tsc --init\n ```"} -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 3, "depth": 2, "title": "Capture the XCM to Replay", "anchor": "capture-the-xcm-to-replay", "start_char": 2258, "end_char": 2834, "estimated_token_count": 151, "token_estimator": "heuristic-v1", "text": "## Capture the XCM to Replay\n\nTo replay a specific XCM, identify:\n\n- The source and destination chains involved.\n- The block number or height where the XCM was sent.\n- Optionally, the call payload (if you plan to simulate it manually via development commands).\n\nYou can use [Polkadot.js Apps](/tutorials/polkadot-sdk/testing/fork-live-chains/#use-polkadotjs-apps){target=\\_blank}, [papi console](https://dev.papi.how/){target=\\_blank}, or indexers such as [Subscan](https://polkadot.subscan.io/xcm_dashboard){target=\\_blank} to locate and inspect the original XCM execution."} -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 4, "depth": 2, "title": "Fork the Relevant Chains", "anchor": "fork-the-relevant-chains", "start_char": 2834, "end_char": 3022, "estimated_token_count": 48, "token_estimator": "heuristic-v1", "text": "## Fork the Relevant Chains\n\nUse Chopsticks to [fork the required chains](/tutorials/polkadot-sdk/testing/fork-live-chains/#xcm-testing){target=\\_blank} at the appropriate block heights."} -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 5, "depth": 3, "title": "Set the Block Numbers", "anchor": "set-the-block-numbers", "start_char": 3022, "end_char": 3307, "estimated_token_count": 61, "token_estimator": "heuristic-v1", "text": "### Set the Block Numbers\n\nCreate/edit a `.env` file with the block heights for each chain. These should be just before the XCM is sent to allow a full replay:\n\n```text title=\".env\"\nPOLKADOT_BLOCK_NUMBER=26481107\nPOLKADOT_ASSET_HUB_BLOCK_NUMBER=9079591\nACALA_BLOCK_NUMBER=8826385\n```"} -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 6, "depth": 3, "title": "Enable Logging and Wasm Override", "anchor": "enable-logging-and-wasm-override", "start_char": 3307, "end_char": 7168, "estimated_token_count": 1021, "token_estimator": "heuristic-v1", "text": "### Enable Logging and Wasm Override\n\nFull execution logs only work if the runtime was compiled with logging enabled. Most live chains are built using the `production` profile, which disables logs. To enable logging, you'll need to override the Wasm with a locally built `release` or `debug` version. The `release` profile is faster to load in Chopsticks. \n\n1. Clone the `polkadot-fellows/runtimes` repository:\n\n ```bash\n git clone git@github.com:polkadot-fellows/runtimes.git\n ```\n\n2. Build the Polkadot Asset Hub runtime:\n\n ```bash\n cd runtimes\n # Build with the `debug` profile (default): \n # cargo build -p asset-hub-polkadot-runtime\n\n # Build with the `release` profile (faster to load in Chopsticks)\n cargo build --release -p asset-hub-polkadot-runtime\n ```\n\n3. Copy the compiled Wasm to your working directory:\n\n ```bash\n # Assuming you're still in the `runtimes` directory\n mkdir -p ../wasms # or your /wasms path\n\n # Copy the compiled Wasm to your working directory:\n\n # If built with the `debug` profile:\n # cp target/debug/wbuild/asset-hub-polkadot-runtime/asset_hub_polkadot_runtime.wasm ../wasms\n\n # If built with the `release` profile:\n cp target/release/wbuild/asset-hub-polkadot-runtime/asset_hub_polkadot_runtime.compact.compressed.wasm ../wasms\n ```\n\n4. Download and modify a config file:\n\n ```bash\n # Still in the `runtimes` directory\n cd .. # Return to your replay-xcm-tests root\n mkdir -p configs\n wget https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/polkadot-asset-hub.yml -O configs/polkadot-asset-hub-override.yaml\n ```\n\n5. Edit `configs/polkadot-asset-hub-override.yaml` to include:\n\n {% raw %}\n ```yaml title=\"configs/polkadot-asset-hub-override.yaml\"\n ...\n runtime-log-level: 5\n # wasm-override: wasms/asset_hub_polkadot_runtime.wasm # Uncomment if using the `debug` build\n wasm-override: wasms/asset_hub_polkadot_runtime.compact.compressed.wasm # Use this if you built with `release`\n ...\n ```\n {% endraw %}\n\n6. Start the forked chains using your custom config:\n\n ```bash\n npx @acala-network/chopsticks xcm \\\n -r polkadot \\\n -p configs/polkadot-asset-hub-override.yaml \\\n -p acala\n ```\n\n This command starts the relay chain and parachains locally, with full runtime execution logs enabled. Once the chains are running, you should see output indicating that the following RPC endpoints are available:\n\n - Polkadot Asset Hub RPC on `http://localhost:8000`\n - Acala RPC on `http://localhost:8001`\n - Polkadot RPC on `http://localhost:8002`\n\n You'll also see runtime logs such as:\n\n
\n npx @acala-network/chopsticks xcm \\ -r polkadot \\ -p configs/polkadot-asset-hub-override.yaml \\ -p acala\n [09:29:14.988] INFO: Polkadot Asset Hub RPC listening on http://[::]:8000 and ws://[::]:8000\n [09:29:14.988] INFO: Loading config file https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/acala.yml\n [09:29:15.984] INFO: Acala RPC listening on http://[::]:8001 and ws://[::]:8001\n [09:29:15.990] INFO (xcm): Connected parachains [1000,2000]\n [09:29:15.990] INFO: Loading config file https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/polkadot.yml\n [09:29:16.927] INFO: Polkadot RPC listening on http://[::]:8002 and ws://[::]:8002\n [09:29:16.984] INFO (xcm): Connected relaychain 'Polkadot' with parachain 'Polkadot Asset Hub'\n [09:29:17.028] INFO (xcm): Connected relaychain 'Polkadot' with parachain 'Acala'\n
"} -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 7, "depth": 2, "title": "Identify and Extract the XCM", "anchor": "identify-and-extract-the-xcm", "start_char": 7168, "end_char": 8791, "estimated_token_count": 333, "token_estimator": "heuristic-v1", "text": "## Identify and Extract the XCM\n\nTo replay an XCM, you'll first need to identify the exact extrinsic that triggered it. In this example, we'll use block 9079592 on the Polkadot Asset Hub.\n\n1. Find and open the block on Subscan to inspect its extrinsics and events. In this case, the block is [9079592](https://assethub-polkadot.subscan.io/block/9079592){target=\\_blank}.\n\n2. Copy the black hash. Look for the block hash at the top of the page. For block 9079592, the hash is:\n\n ```bash title=\"Block Hash\"\n 0xeb5a5737d47367dc1c02b978232283cdb096eb7e51d2eb22366a106a011347f6\n ```\n\n3. Explore and view the block in [Polkadot.Js Apps](https://polkadot.js.org/apps){target=\\_blank} using this direct link: [Block Hash Explorer](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fpolkadot-asset-hub-rpc.polkadot.io#/explorer/query/0xeb5a5737d47367dc1c02b978232283cdb096eb7e51d2eb22366a106a011347f6){target=\\_blank}.\n\n4. Locate and decode the XCM extrinsic. Once you've found the extrinsic (e.g., 9079592-2), extract and decode its call data. For example, the call data is:\n \n ```bash title=\"Call Data\"\n 0xad028400fc39fcf04a8071b7409823b7c82427ce67910c6ed80aa0e5093aff234624c820016a30461702adc48213e5c9ee4d15c5a481c578cb5cbc935f0bd11fe8aee489082a745ffbbe94282f91b67daa6cb44920d77c30849c1d25f5f6c3e59015a3e383440055040000011f0803010100411f0300010100fc39fcf04a8071b7409823b7c82427ce67910c6ed80aa0e5093aff234624c8200304000002043205011f0092e81d790000000000\n ```\n\n5. From the decoded view, copy the **hex-encoded call** (e.g. `0x1f08...0000`). You'll pass this into `api.txFromCallData(...)` to replay the XCM locally."} -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 8, "depth": 2, "title": "Replay the XCM", "anchor": "replay-the-xcm", "start_char": 8791, "end_char": 9045, "estimated_token_count": 50, "token_estimator": "heuristic-v1", "text": "## Replay the XCM\n\nOnce your project is set up, you're ready to replay the XCM locally.\n\nThis is useful for:\n\n- Diagnosing execution failures or weight limits.\n- Inspecting all emitted events.\n- Verifying behaviour before submitting a real transaction."} -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 9, "depth": 3, "title": "Add the Asset Hub Descriptor", "anchor": "add-the-asset-hub-descriptor", "start_char": 9045, "end_char": 9478, "estimated_token_count": 105, "token_estimator": "heuristic-v1", "text": "### Add the Asset Hub Descriptor\n\nThis will let you use type-safe APIs with PAPI:\n\n```bash\nnpx papi add assetHub -w ws://localhost:8000\n```\n\nThe script assumes the Polkadot Asset Hub is served on `ws://localhost:8000`. If you're using a different port or config, update the WebSocket endpoint in the script or descriptor. You can confirm the port by checking your terminal logs or by seeing [Launch Chopsticks](#launch-chopsticks)."} -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 10, "depth": 3, "title": "Create a Replay Script", "anchor": "create-a-replay-script", "start_char": 9478, "end_char": 12356, "estimated_token_count": 667, "token_estimator": "heuristic-v1", "text": "### Create a Replay Script\n\nCreate a file named `replay-xcm.ts` and copy the following code into it:\n\n```ts\nimport { Binary, createClient, Transaction } from 'polkadot-api';\nimport { withPolkadotSdkCompat } from 'polkadot-api/polkadot-sdk-compat';\nimport { getPolkadotSigner } from 'polkadot-api/signer';\nimport { getWsProvider } from 'polkadot-api/ws-provider/web';\nimport { assetHub } from '@polkadot-api/descriptors';\nimport { sr25519CreateDerive } from '@polkadot-labs/hdkd';\nimport {\n DEV_PHRASE,\n entropyToMiniSecret,\n mnemonicToEntropy,\n} from '@polkadot-labs/hdkd-helpers';\n\nconst toHuman = (_key: any, value: any) => {\n if (typeof value === 'bigint') {\n return Number(value);\n }\n\n if (value && typeof value === 'object' && typeof value.asHex === 'function') {\n return value.asHex();\n }\n\n return value;\n};\n\nfunction getSigner() {\n const entropy = mnemonicToEntropy(DEV_PHRASE);\n const miniSecret = entropyToMiniSecret(entropy);\n const derive = sr25519CreateDerive(miniSecret);\n const alice = derive('//Alice');\n\n return getPolkadotSigner(alice.publicKey, 'Sr25519', alice.sign);\n}\n\nasync function main() {\n const provider = withPolkadotSdkCompat(getWsProvider('ws://localhost:8000'));\n const client = createClient(provider);\n const api = client.getTypedApi(assetHub);\n const aliceSigner = getSigner();\n\n const callData = Binary.fromHex(\n '0x1f0803010100411f0300010100fc39fcf04a8071b7409823b7c82427ce67910c6ed80aa0e5093aff234624c8200304000002043205011f0092e81d790000000000',\n );\n const tx: Transaction =\n await api.txFromCallData(callData);\n console.log('👀 Executing XCM:', JSON.stringify(tx.decodedCall, toHuman, 2));\n\n await new Promise((resolve) => {\n const subscription = tx.signSubmitAndWatch(aliceSigner).subscribe((ev) => {\n if (\n ev.type === 'finalized' ||\n (ev.type === 'txBestBlocksState' && ev.found)\n ) {\n console.log(\n `📦 Included in block #${ev.block.number}: ${ev.block.hash}`,\n );\n\n if (!ev.ok) {\n const dispatchError = ev.dispatchError;\n if (dispatchError.type === 'Module') {\n const modErr: any = dispatchError.value;\n console.error(\n `❌ Dispatch error in module: ${modErr.type} → ${modErr.value?.type}`,\n );\n } else {\n console.error(\n '❌ Dispatch error:',\n JSON.stringify(dispatchError, toHuman, 2),\n );\n }\n }\n\n for (const event of ev.events) {\n console.log(\n '📣 Event:',\n event.type,\n JSON.stringify(event.value, toHuman, 2),\n );\n }\n\n console.log('✅ Process completed, exiting...');\n subscription.unsubscribe();\n resolve();\n }\n });\n });\n\n client.destroy();\n}\n\nmain().catch(console.error);\n\n```"} -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 11, "depth": 3, "title": "Execute the Replay Script", "anchor": "execute-the-replay-script", "start_char": 12356, "end_char": 12545, "estimated_token_count": 48, "token_estimator": "heuristic-v1", "text": "### Execute the Replay Script\n\nEnsure Chopsticks is running and serving a chain that includes `pallet-xcm`, such as a Polkadot Asset Hub fork. Then run:\n\n```bash\nnpx tsx replay-xcm.ts\n```"} -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 12, "depth": 3, "title": "Expected Output", "anchor": "expected-output", "start_char": 12545, "end_char": 14451, "estimated_token_count": 674, "token_estimator": "heuristic-v1", "text": "### Expected Output\n\nIf everything is working, you'll see logs like:\n\n
\n npx tsx replay-xcm.ts\n
\nexecuting xcm: {\n  \"type\": \"polkadotxcm\",\n  \"value\": {\n    \"type\": \"limited_reserve_transfer_assets\",\n    \"value\": {\n      \"dest\": { \"parents\": 0, \"interior\": { \"X1\": [{ \"Parachain\": 2006 }] } },\n      \"beneficiary\": { \"parents\": 0, \"interior\": { \"X1\": [{ \"AccountId32\": { \"network\": null, \"id\": \"0x...\" } }] } },\n      \"assets\": [{ \"id\": { \"Concrete\": { \"parents\": 0, \"interior\": \"Here\" } }, \"fun\": { \"Fungible\": 120000000000 } }],\n      \"fee_asset_item\": 0,\n      \"weight_limit\": { \"type\": \"Unlimited\" }\n    }\n  }\n}\n  
\n 📦 Included in block #9079592: 0x227a11c64f6051ba2e090a13abd17e5f7581640a80f6c03fc2d43fac66ab7949\n 📣 Event: Balances { \"type\": \"Upgraded\", \"value\": { ... } }\n 📣 Event: Balances { \"type\": \"Withdraw\", \"value\": { ... } }\n 📣 Event: Assets { \"type\": \"Transferred\", \"value\": { ... } }\n 📣 Event: PolkadotXcm { \"type\": \"Attempted\", \"value\": { ... } }\n 📣 Event: Balances { \"type\": \"Burned\", \"value\": { ... } }\n 📣 Event: Balances { \"type\": \"Minted\", \"value\": { ... } }\n 📣 Event: PolkadotXcm { \"type\": \"FeesPaid\", \"value\": { ... } }\n 📣 Event: XcmpQueue { \"type\": \"XcmpMessageSent\", \"value\": { ... } }\n 📣 Event: PolkadotXcm { \"type\": \"Sent\", \"value\": { ... } }\n 📣 Event: Balances { \"type\": \"Deposit\", \"value\": { ... } }\n 📣 Event: TransactionPayment { \"type\": \"TransactionFeePaid\", \"value\": { ... } }\n 📣 Event: System { \"type\": \"ExtrinsicSuccess\", \"value\": { ... } }\n ✅ Process completed, exiting...\n
"} -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 13, "depth": 2, "title": "Dry Run the XCM", "anchor": "dry-run-the-xcm", "start_char": 14451, "end_char": 14639, "estimated_token_count": 38, "token_estimator": "heuristic-v1", "text": "## Dry Run the XCM\n\nTo simulate the XCM without actually sending it, you can use the `dry_run_call` method. This lets you check whether the XCM would succeed without modifying any state."} -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 14, "depth": 3, "title": "Create a Dry Run Script", "anchor": "create-a-dry-run-script", "start_char": 14639, "end_char": 16321, "estimated_token_count": 366, "token_estimator": "heuristic-v1", "text": "### Create a Dry Run Script\n\nAssuming you've the `tx` transaction from the previous step, you can create a new script, `dry-run-call.ts`, then paste in the following code:\n\n```ts\nimport { Binary, createClient, Enum } from 'polkadot-api';\nimport { withPolkadotSdkCompat } from 'polkadot-api/polkadot-sdk-compat';\nimport { getWsProvider } from 'polkadot-api/ws-provider/web';\nimport { assetHub } from '@polkadot-api/descriptors';\nimport { sr25519CreateDerive } from '@polkadot-labs/hdkd';\nimport {\n DEV_PHRASE,\n entropyToMiniSecret,\n mnemonicToEntropy,\n ss58Address,\n} from '@polkadot-labs/hdkd-helpers';\n\nconst XCM_VERSION = 5;\n\nasync function main() {\n const provider = withPolkadotSdkCompat(getWsProvider('ws://localhost:8000'));\n const client = createClient(provider);\n const api = client.getTypedApi(assetHub);\n\n const entropy = mnemonicToEntropy(DEV_PHRASE);\n const miniSecret = entropyToMiniSecret(entropy);\n const derive = sr25519CreateDerive(miniSecret);\n const alice = derive('//Alice');\n const aliceAddress = ss58Address(alice.publicKey);\n\n const callData = Binary.fromHex(\n '0x1f0803010100411f0300010100fc39fcf04a8071b7409823b7c82427ce67910c6ed80aa0e5093aff234624c8200304000002043205011f0092e81d790000000000',\n );\n const tx: any = await api.txFromCallData(callData);\n const origin = Enum('system', Enum('Signed', aliceAddress));\n const dryRunResult: any = await api.apis.DryRunApi.dry_run_call(\n origin,\n tx.decodedCall,\n XCM_VERSION,\n );\n console.dir(dryRunResult.value, { depth: null });\n\n client.destroy();\n}\n\nmain().catch(console.error);\n\n```\n\nEnsure your local Chopsticks fork is running and the ports match those used in the script."} -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 15, "depth": 3, "title": "Execute the Dry Run Script", "anchor": "execute-the-dry-run-script", "start_char": 16321, "end_char": 17894, "estimated_token_count": 496, "token_estimator": "heuristic-v1", "text": "### Execute the Dry Run Script\n\n```bash\nnpx tsx dry-run-call.ts\n```\n\nIf successful, the dry run confirms that the XCM would execute correctly:\n\n
\n npx tsx dry-run-call.ts\n
\nexecution_result: {\n  \"success\": true,\n  \"value\": {\n    \"post_info\": { \"actual_weight\": 123456, \"pays_fee\": \"Yes\" },\n    \"result\": \"Ok\"\n  }\n}\nemitted_events: [ { \"section\": \"Balances\", \"method\": \"Transfer\", \"data\": { \"from\": \"0x...\", \"to\": \"0x...\", \"amount\": 1000000000 } } ]\nlocal_xcm: { \"type\": \"SomeType\", \"value\": { ... } }\nforwarded_xcms: []\n  
\n ✅ Dry run succeeded\n ✅ Process completed, exiting...\n
\n\nIf it fails, you'll receive detailed error information:\n\n
\n npx tsx dry-run-call.ts\n
\nexecution_result: {\n  \"success\": false,\n  \"value\": {\n    \"post_info\": { \"actual_weight\": 123456, \"pays_fee\": \"Yes\" },\n    \"error\": {\n      \"type\": \"Module\",\n      \"value\": {\n        \"type\": \"PolkadotXcm\",\n        \"value\": { \"type\": \"LocalExecutionIncomplete\", \"value\": null }\n      }\n    }\n  }\n}\n  
\n ❌ Dry run failed: LocalExecutionIncomplete\n ✅ Process completed, exiting...\n
\n\nFor more information, see:\n\n- [Dry Run Call](/develop/interoperability/xcm-runtime-apis/#dry-run-call){target=\\_blank} to simulate a full extrinsic\n- [Dry Run XCM](/develop/interoperability/xcm-runtime-apis/#dry-run-xcm){target=\\_blank} to simulate a raw XCM"} -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 16, "depth": 2, "title": "Review and Debug", "anchor": "review-and-debug", "start_char": 17894, "end_char": 18239, "estimated_token_count": 60, "token_estimator": "heuristic-v1", "text": "## Review and Debug\n\nReplaying XCMs with full logging provides fine-grained control and visibility into cross-chain message behaviour. Chopsticks makes this possible in a safe, local environment – empowering developers to:\n\n- Debug complex message flows.\n- Identify root causes of XCM failures.\n- Improve observability for future integrations."} -{"page_id": "chain-interactions-send-transactions-interoperability-debug-and-preview-xcms", "page_title": "Replay and Dry Run XCMs", "index": 17, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 18239, "end_char": 18942, "estimated_token_count": 181, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\n
\n\n- External __Chopsticks Repository__\n\n ---\n\n View the official Chopsticks GitHub repository.\n\n [:octicons-arrow-right-24: Get Started](https://github.com/AcalaNetwork/chopsticks/)\n\n- Guide __Polkadot XCM Docs__\n\n ---\n\n Learn how to use XCM effectively.\n\n [:octicons-arrow-right-24: Get Started](/parachains/interoperability/get-started/)\n\n- Tutorial __XCM Runtime APIs__\n\n ---\n\n Learn how to use XCM Runtime APIs.\n\n [:octicons-arrow-right-24: Get Started](/develop/interoperability/xcm-runtime-apis/)\n\n
"} -{"page_id": "chain-interactions-send-transactions-interoperability-estimate-xcm-fees", "page_title": "XCM Fee Estimation", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 22, "end_char": 450, "estimated_token_count": 76, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nWhen sending cross-chain messages, ensure that the transaction will be successful not only in the local chain but also in the destination chain and any intermediate chains.\n\nSending cross-chain messages requires estimating the fees for the operation. \n\nThis tutorial will demonstrate how to dry-run and estimate the fees for teleporting assets from the Paseo Asset Hub parachain to the Paseo Bridge Hub chain."} -{"page_id": "chain-interactions-send-transactions-interoperability-estimate-xcm-fees", "page_title": "XCM Fee Estimation", "index": 1, "depth": 2, "title": "Fee Mechanism", "anchor": "fee-mechanism", "start_char": 450, "end_char": 1437, "estimated_token_count": 222, "token_estimator": "heuristic-v1", "text": "## Fee Mechanism\n\nThere are three types of fees that can be charged when sending a cross-chain message:\n\n- **Local execution fees**: Fees charged in the local chain for executing the message.\n- **Delivery fees**: Fees charged for delivering the message to the destination chain.\n- **Remote execution fees**: Fees charged in the destination chain for executing the message.\n\nIf there are multiple intermediate chains, delivery fees and remote execution fees will be charged for each one.\n\nIn this example, you will estimate the fees for teleporting assets from the Paseo Asset Hub parachain to the Paseo Bridge Hub chain. The fee structure will be as follows:\n\n```mermaid\nflowchart LR\n AssetHub[Paseo Asset Hub] -->|Delivery Fees| BridgeHub[Paseo Bridge Hub]\n AssetHub -->|
Local
Execution
Fees| AssetHub\n BridgeHub -->|
Remote
Execution
Fees| BridgeHub\n```\n\nThe overall fees are `local_execution_fees` + `delivery_fees` + `remote_execution_fees`."} -{"page_id": "chain-interactions-send-transactions-interoperability-estimate-xcm-fees", "page_title": "XCM Fee Estimation", "index": 2, "depth": 2, "title": "Environment Setup", "anchor": "environment-setup", "start_char": 1437, "end_char": 3989, "estimated_token_count": 588, "token_estimator": "heuristic-v1", "text": "## Environment Setup\n\nFirst, you need to set up your environment:\n\n1. Create a new directory and initialize the project:\n\n ```bash\n mkdir xcm-fee-estimation && \\\n cd xcm-fee-estimation\n ```\n\n2. Initialize the project:\n\n ```bash\n npm init -y\n ```\n\n3. Install dev dependencies:\n\n ```bash\n npm install --save-dev @types/node@^22.12.0 ts-node@^10.9.2 typescript@^5.7.3\n ```\n\n4. Install dependencies:\n\n ```bash\n npm install --save @polkadot-labs/hdkd@^0.0.13 @polkadot-labs/hdkd-helpers@^0.0.13 polkadot-api@1.9.5\n ```\n\n5. Create TypeScript configuration:\n\n ```bash\n npx tsc --init\n ```\n\n6. Generate the types for the Polkadot API for Paseo Bridge Hub and Paseo Asset Hub:\n\n ```bash\n npx papi add paseoAssetHub -n paseo_asset_hub && \\\n npx papi add paseoBridgeHub -w wss://bridge-hub-paseo.dotters.network\n ```\n\n7. Create a new file called `teleport-ah-to-bridge-hub.ts`:\n\n ```bash\n touch teleport-ah-to-bridge-hub.ts\n ```\n\n8. Import the necessary modules. Add the following code to the `teleport-ah-to-bridge-hub.ts` file:\n\n ```typescript title=\"teleport-ah-to-bridge-hub.ts\"\n import { paseoAssetHub, paseoBridgeHub } from '@polkadot-api/descriptors';\n import { createClient, FixedSizeBinary, Enum } from 'polkadot-api';\n import { getWsProvider } from 'polkadot-api/ws-provider/node';\n import { withPolkadotSdkCompat } from 'polkadot-api/polkadot-sdk-compat';\n import {\n XcmVersionedLocation,\n XcmVersionedAssetId,\n XcmV3Junctions,\n XcmV3MultiassetFungibility,\n XcmVersionedXcm,\n XcmV5Instruction,\n XcmV5Junctions,\n XcmV5Junction,\n XcmV5AssetFilter,\n XcmV5WildAsset,\n } from '@polkadot-api/descriptors';\n ```\n\n9. Define constants and a `main` function where you will implement all the logic:\n\n ```typescript title=\"teleport-ah-to-bridge-hub.ts\"\n // 1 PAS = 10^10 units\n const PAS_UNITS = 10_000_000_000n; // 1 PAS\n const PAS_CENTS = 100_000_000n; // 0.01 PAS\n\n // Paseo Asset Hub constants\n const PASEO_ASSET_HUB_RPC_ENDPOINT = 'ws://localhost:8001';\n const ASSET_HUB_ACCOUNT = '15oF4uVJwmo4TdGW7VfQxNLavjCXviqxT9S1MgbjMNHr6Sp5'; // Alice (Paseo Asset Hub)\n\n // Bridge Hub destination\n const BRIDGE_HUB_RPC_ENDPOINT = 'ws://localhost:8000';\n const BRIDGE_HUB_PARA_ID = 1002;\n const BRIDGE_HUB_BENEFICIARY =\n async function main() {\n // Code will go here\n }\n ```\n\nAll the following code explained in the subsequent sections must be added inside the `main` function."} -{"page_id": "chain-interactions-send-transactions-interoperability-estimate-xcm-fees", "page_title": "XCM Fee Estimation", "index": 3, "depth": 2, "title": "Client and API Setup", "anchor": "client-and-api-setup", "start_char": 3989, "end_char": 4866, "estimated_token_count": 172, "token_estimator": "heuristic-v1", "text": "## Client and API Setup\n\nNow you are ready to start implementing the logic for the fee estimation for the teleport you want to perform. In this step, you will create the client for the Paseo Asset Hub parachain and generate the typed API to interact with the chain. Follow the steps below:\n\nCreate the API client. You will need to create a client for the Paseo Asset Hub parachain:\n\n```typescript title=\"teleport-ah-to-bridge-hub.ts\"\n // Connect to the Asset Hub parachain\n const assetHubClient = createClient(\n withPolkadotSdkCompat(getWsProvider(PASEO_ASSET_HUB_RPC_ENDPOINT)),\n );\n\n // Get the typed API for Asset Hub\n const assetHubApi = assetHubClient.getTypedApi(paseoAssetHub);\n```\n\nEnsure that you replace the endpoint URLs with the actual WebSocket endpoints. This example uses local chopsticks endpoints, but you can use public endpoints or run local nodes."} -{"page_id": "chain-interactions-send-transactions-interoperability-estimate-xcm-fees", "page_title": "XCM Fee Estimation", "index": 4, "depth": 2, "title": "Create the XCM Message", "anchor": "create-the-xcm-message", "start_char": 4866, "end_char": 6826, "estimated_token_count": 395, "token_estimator": "heuristic-v1", "text": "## Create the XCM Message\n\nNow, you can construct a proper XCM message using the new XCM V5 instructions for teleporting from Asset Hub to the Bridge Hub Chain:\n\n```typescript title=\"teleport-ah-to-bridge-hub.ts\"\nfunction createTeleportXcmToBridgeHub(paraId: number) {\n return XcmVersionedXcm.V5([\n // Withdraw PAS from Asset Hub (PAS on parachains is parents:1, interior: Here)\n XcmV5Instruction.WithdrawAsset([\n {\n id: { parents: 1, interior: XcmV5Junctions.Here() },\n fun: XcmV3MultiassetFungibility.Fungible(1n * PAS_UNITS), // 1 PAS\n },\n ]),\n // Pay local fees on Asset Hub in PAS\n XcmV5Instruction.PayFees({\n asset: {\n id: { parents: 1, interior: XcmV5Junctions.Here() },\n fun: XcmV3MultiassetFungibility.Fungible(10n * PAS_CENTS), // 0.01 PAS\n },\n }),\n // Send to Bridge Hub parachain (parents:1, interior: X1(Parachain(paraId)))\n XcmV5Instruction.InitiateTransfer({\n destination: {\n parents: 1,\n interior: XcmV5Junctions.X1(XcmV5Junction.Parachain(paraId)),\n },\n remote_fees: Enum(\n 'Teleport',\n XcmV5AssetFilter.Definite([\n {\n id: { parents: 1, interior: XcmV5Junctions.Here() },\n fun: XcmV3MultiassetFungibility.Fungible(10n * PAS_CENTS), // 0.01 PAS\n },\n ]),\n ),\n preserve_origin: false,\n remote_xcm: [\n XcmV5Instruction.DepositAsset({\n assets: XcmV5AssetFilter.Wild(XcmV5WildAsset.AllCounted(1)),\n beneficiary: {\n parents: 0,\n interior: XcmV5Junctions.X1(\n XcmV5Junction.AccountId32({\n network: undefined,\n id: FixedSizeBinary.fromAccountId32(BRIDGE_HUB_BENEFICIARY),\n }),\n ),\n },\n }),\n ],\n assets: [\n Enum('Teleport', XcmV5AssetFilter.Wild(XcmV5WildAsset.AllCounted(1))), // Send everything.\n ],\n }),\n ]);\n}\n```"} -{"page_id": "chain-interactions-send-transactions-interoperability-estimate-xcm-fees", "page_title": "XCM Fee Estimation", "index": 5, "depth": 2, "title": "Fee Estimation Function", "anchor": "fee-estimation-function", "start_char": 6826, "end_char": 20688, "estimated_token_count": 2699, "token_estimator": "heuristic-v1", "text": "## Fee Estimation Function\n\nBelow is a four-step breakdown of the logic needed to estimate the fees for the teleport.\n\nFirst, you need to create the function that will estimate the fees for the teleport:\n\n```typescript title=\"teleport-ah-to-bridge-hub.ts\"\nasync function estimateXcmFeesFromAssetHubToBridgeHub(\n xcm: any,\n assetHubApi: any,\n) {\n // Code will go here\n}\n```\n\n1. **Local execution fees on Asset Hub**: Compute the XCM weight locally, then convert that weight to PAS using Asset Hub's view of PAS (`parents: 1, interior: Here`). Add the code to the function:\n\n ```typescript title=\"teleport-ah-to-bridge-hub.ts\"\n console.log('=== Fee Estimation Process (Asset Hub → Bridge Hub) ===');\n\n // 1. LOCAL EXECUTION FEES on Asset Hub\n console.log('1. Calculating local execution fees on Asset Hub...');\n let localExecutionFees = 0n;\n\n const weightResult =\n await assetHubApi.apis.XcmPaymentApi.query_xcm_weight(xcm);\n if (weightResult.success) {\n console.log('✓ XCM weight (Asset Hub):', weightResult.value);\n\n // Convert weight to PAS fees from Asset Hub's perspective (parents:1, Here)\n const executionFeesResult =\n await assetHubApi.apis.XcmPaymentApi.query_weight_to_asset_fee(\n weightResult.value,\n XcmVersionedAssetId.V4({\n parents: 1,\n interior: XcmV3Junctions.Here(),\n }),\n );\n\n if (executionFeesResult.success) {\n localExecutionFees = executionFeesResult.value;\n console.log(\n '✓ Local execution fees (Asset Hub):',\n localExecutionFees.toString(),\n 'PAS units',\n );\n } else {\n console.log(\n '✗ Failed to calculate local execution fees:',\n executionFeesResult.value,\n );\n }\n } else {\n console.log(\n '✗ Failed to query XCM weight on Asset Hub:',\n weightResult.value,\n );\n }\n ```\n\n2. **Dry-run and delivery fees to Bridge Hub**: Dry-run the XCM on Asset Hub to capture forwarded messages, locate the one targeting Bridge Hub (`parents: 1, interior: Here`), and ask for delivery fees. Add the code to the function:\n\n ```typescript title=\"teleport-ah-to-bridge-hub.ts\"\n // 2. DELIVERY FEES + REMOTE EXECUTION FEES\n console.log('\\n2. Calculating delivery and remote execution fees...');\n let deliveryFees = 0n;\n let remoteExecutionFees = 0n; // Skipped (Bridge Hub descriptor not available)\n\n // Origin from Asset Hub perspective\n const origin = XcmVersionedLocation.V5({\n parents: 0,\n interior: XcmV5Junctions.X1(\n XcmV5Junction.AccountId32({\n id: FixedSizeBinary.fromAccountId32(ASSET_HUB_ACCOUNT),\n network: undefined,\n }),\n ),\n });\n\n // Dry run the XCM locally on Asset Hub\n const dryRunResult = await assetHubApi.apis.DryRunApi.dry_run_xcm(\n origin,\n xcm,\n );\n\n if (\n dryRunResult.success &&\n dryRunResult.value.execution_result.type === 'Complete'\n ) {\n console.log('✓ Local dry run on Asset Hub successful');\n\n const { forwarded_xcms: forwardedXcms } = dryRunResult.value;\n\n // Find the XCM message sent to Bridge Hub (parents:1, interior: X1(Parachain(1002)))\n const bridgeHubXcmEntry = forwardedXcms.find(\n ([location, _]: [any, any]) =>\n (location.type === 'V4' || location.type === 'V5') &&\n location.value.parents === 1 &&\n location.value.interior?.type === 'X1' &&\n location.value.interior.value?.type === 'Parachain' &&\n location.value.interior.value.value === BRIDGE_HUB_PARA_ID,\n );\n\n if (bridgeHubXcmEntry) {\n const [destination, messages] = bridgeHubXcmEntry;\n const remoteXcm = messages[0];\n\n console.log('✓ Found XCM message to Bridge Hub');\n\n // Calculate delivery fees from Asset Hub to Bridge Hub\n const deliveryFeesResult =\n await assetHubApi.apis.XcmPaymentApi.query_delivery_fees(\n destination,\n remoteXcm,\n );\n\n if (\n deliveryFeesResult.success &&\n deliveryFeesResult.value.type === 'V5' &&\n deliveryFeesResult.value.value[0]?.fun?.type === 'Fungible'\n ) {\n deliveryFees = deliveryFeesResult.value.value[0].fun.value;\n console.log('✓ Delivery fees:', deliveryFees.toString(), 'PAS units');\n } else {\n console.log('✗ Failed to calculate delivery fees:', deliveryFeesResult);\n }\n ```\n\n3. **Remote execution fees on Bridge Hub**: Connect to Bridge Hub, recompute the forwarded XCM weight there, and convert weight to PAS (`parents: 0, interior: Here`). Add the code to the function:\n\n ```typescript title=\"teleport-ah-to-bridge-hub.ts\"\n // 3. REMOTE EXECUTION FEES on Bridge Hub\n console.log('\\n3. Calculating remote execution fees on Bridge Hub');\n try {\n const bridgeHubClient = createClient(\n withPolkadotSdkCompat(getWsProvider(BRIDGE_HUB_RPC_ENDPOINT)),\n );\n const bridgeHubApi = bridgeHubClient.getTypedApi(paseoBridgeHub);\n const remoteWeightResult =\n await bridgeHubApi.apis.XcmPaymentApi.query_xcm_weight(remoteXcm);\n const remoteFeesResult =\n await bridgeHubApi.apis.XcmPaymentApi.query_weight_to_asset_fee(\n remoteWeightResult.value as {\n ref_time: bigint;\n proof_size: bigint;\n },\n XcmVersionedAssetId.V4({\n parents: 1,\n interior: XcmV3Junctions.Here(),\n }),\n );\n bridgeHubClient.destroy();\n remoteExecutionFees = remoteFeesResult.value as bigint;\n console.log(\n '✓ Remote execution fees:',\n remoteExecutionFees.toString(),\n 'PAS units',\n );\n } catch (error) {\n console.error(\n 'Error calculating remote execution fees on Bridge Hub:',\n error,\n );\n }\n } else {\n console.log('✗ No XCM message found to Bridge Hub');\n }\n } else {\n console.log('✗ Local dry run failed on Asset Hub:', dryRunResult.value);\n }\n ```\n\n4. **Sum and return totals**: Aggregate all parts, print a short summary, and return a structured result. Add the code to the function:\n\n ```typescript title=\"teleport-ah-to-bridge-hub.ts\"\n // 4. TOTAL FEES\n const totalFees = localExecutionFees + deliveryFees + remoteExecutionFees;\n\n console.log('\\n=== Fee Summary (Asset Hub → Bridge Hub) ===');\n console.log(\n 'Local execution fees:',\n localExecutionFees.toString(),\n 'PAS units',\n );\n console.log('Delivery fees:', deliveryFees.toString(), 'PAS units');\n console.log(\n 'Remote execution fees:',\n remoteExecutionFees.toString(),\n 'PAS units',\n );\n console.log('TOTAL FEES:', totalFees.toString(), 'PAS units');\n console.log(\n 'TOTAL FEES:',\n (Number(totalFees) / Number(PAS_UNITS)).toFixed(4),\n 'PAS',\n );\n\n return {\n localExecutionFees,\n deliveryFees,\n remoteExecutionFees,\n totalFees,\n };\n }\n ```\n\nThe full code for the fee estimation function is the following:\n\n??? code \"Fee Estimation Function\"\n\n ```typescript title=\"teleport-ah-to-bridge-hub.ts\"\n async function estimateXcmFeesFromAssetHubToBridgeHub(\n xcm: any,\n assetHubApi: any,\n ) {\n console.log('=== Fee Estimation Process (Asset Hub → Bridge Hub) ===');\n\n // 1. LOCAL EXECUTION FEES on Asset Hub\n console.log('1. Calculating local execution fees on Asset Hub...');\n let localExecutionFees = 0n;\n\n const weightResult =\n await assetHubApi.apis.XcmPaymentApi.query_xcm_weight(xcm);\n if (weightResult.success) {\n console.log('✓ XCM weight (Asset Hub):', weightResult.value);\n\n // Convert weight to PAS fees from Asset Hub's perspective (parents:1, Here)\n const executionFeesResult =\n await assetHubApi.apis.XcmPaymentApi.query_weight_to_asset_fee(\n weightResult.value,\n XcmVersionedAssetId.V4({\n parents: 1,\n interior: XcmV3Junctions.Here(),\n }),\n );\n\n if (executionFeesResult.success) {\n localExecutionFees = executionFeesResult.value;\n console.log(\n '✓ Local execution fees (Asset Hub):',\n localExecutionFees.toString(),\n 'PAS units',\n );\n } else {\n console.log(\n '✗ Failed to calculate local execution fees:',\n executionFeesResult.value,\n );\n }\n } else {\n console.log(\n '✗ Failed to query XCM weight on Asset Hub:',\n weightResult.value,\n );\n }\n\n // 2. DELIVERY FEES + REMOTE EXECUTION FEES\n console.log('\\n2. Calculating delivery and remote execution fees...');\n let deliveryFees = 0n;\n let remoteExecutionFees = 0n; // Skipped (Bridge Hub descriptor not available)\n\n // Origin from Asset Hub perspective\n const origin = XcmVersionedLocation.V5({\n parents: 0,\n interior: XcmV5Junctions.X1(\n XcmV5Junction.AccountId32({\n id: FixedSizeBinary.fromAccountId32(ASSET_HUB_ACCOUNT),\n network: undefined,\n }),\n ),\n });\n\n // Dry run the XCM locally on Asset Hub\n const dryRunResult = await assetHubApi.apis.DryRunApi.dry_run_xcm(\n origin,\n xcm,\n );\n\n if (\n dryRunResult.success &&\n dryRunResult.value.execution_result.type === 'Complete'\n ) {\n console.log('✓ Local dry run on Asset Hub successful');\n\n const { forwarded_xcms: forwardedXcms } = dryRunResult.value;\n\n // Find the XCM message sent to Bridge Hub (parents:1, interior: X1(Parachain(1002)))\n const bridgeHubXcmEntry = forwardedXcms.find(\n ([location, _]: [any, any]) =>\n (location.type === 'V4' || location.type === 'V5') &&\n location.value.parents === 1 &&\n location.value.interior?.type === 'X1' &&\n location.value.interior.value?.type === 'Parachain' &&\n location.value.interior.value.value === BRIDGE_HUB_PARA_ID,\n );\n\n if (bridgeHubXcmEntry) {\n const [destination, messages] = bridgeHubXcmEntry;\n const remoteXcm = messages[0];\n\n console.log('✓ Found XCM message to Bridge Hub');\n\n // Calculate delivery fees from Asset Hub to Bridge Hub\n const deliveryFeesResult =\n await assetHubApi.apis.XcmPaymentApi.query_delivery_fees(\n destination,\n remoteXcm,\n );\n\n if (\n deliveryFeesResult.success &&\n deliveryFeesResult.value.type === 'V5' &&\n deliveryFeesResult.value.value[0]?.fun?.type === 'Fungible'\n ) {\n deliveryFees = deliveryFeesResult.value.value[0].fun.value;\n console.log('✓ Delivery fees:', deliveryFees.toString(), 'PAS units');\n } else {\n console.log('✗ Failed to calculate delivery fees:', deliveryFeesResult);\n }\n\n // 3. REMOTE EXECUTION FEES on Bridge Hub\n console.log('\\n3. Calculating remote execution fees on Bridge Hub');\n try {\n const bridgeHubClient = createClient(\n withPolkadotSdkCompat(getWsProvider(BRIDGE_HUB_RPC_ENDPOINT)),\n );\n const bridgeHubApi = bridgeHubClient.getTypedApi(paseoBridgeHub);\n const remoteWeightResult =\n await bridgeHubApi.apis.XcmPaymentApi.query_xcm_weight(remoteXcm);\n const remoteFeesResult =\n await bridgeHubApi.apis.XcmPaymentApi.query_weight_to_asset_fee(\n remoteWeightResult.value as {\n ref_time: bigint;\n proof_size: bigint;\n },\n XcmVersionedAssetId.V4({\n parents: 1,\n interior: XcmV3Junctions.Here(),\n }),\n );\n bridgeHubClient.destroy();\n remoteExecutionFees = remoteFeesResult.value as bigint;\n console.log(\n '✓ Remote execution fees:',\n remoteExecutionFees.toString(),\n 'PAS units',\n );\n } catch (error) {\n console.error(\n 'Error calculating remote execution fees on Bridge Hub:',\n error,\n );\n }\n } else {\n console.log('✗ No XCM message found to Bridge Hub');\n }\n } else {\n console.log('✗ Local dry run failed on Asset Hub:', dryRunResult.value);\n }\n\n // 4. TOTAL FEES\n const totalFees = localExecutionFees + deliveryFees + remoteExecutionFees;\n\n console.log('\\n=== Fee Summary (Asset Hub → Bridge Hub) ===');\n console.log(\n 'Local execution fees:',\n localExecutionFees.toString(),\n 'PAS units',\n );\n console.log('Delivery fees:', deliveryFees.toString(), 'PAS units');\n console.log(\n 'Remote execution fees:',\n remoteExecutionFees.toString(),\n 'PAS units',\n );\n console.log('TOTAL FEES:', totalFees.toString(), 'PAS units');\n console.log(\n 'TOTAL FEES:',\n (Number(totalFees) / Number(PAS_UNITS)).toFixed(4),\n 'PAS',\n );\n\n return {\n localExecutionFees,\n deliveryFees,\n remoteExecutionFees,\n totalFees,\n };\n }\n ```"} -{"page_id": "chain-interactions-send-transactions-interoperability-estimate-xcm-fees", "page_title": "XCM Fee Estimation", "index": 6, "depth": 2, "title": "Complete Implementation", "anchor": "complete-implementation", "start_char": 20688, "end_char": 22403, "estimated_token_count": 411, "token_estimator": "heuristic-v1", "text": "## Complete Implementation\n\nNow put it all together in the main function:\n\n```typescript title=\"teleport-ah-to-bridge-hub.ts\"\nasync function main() {\n // Connect to the Asset Hub parachain\n const assetHubClient = createClient(\n withPolkadotSdkCompat(getWsProvider(PASEO_ASSET_HUB_RPC_ENDPOINT)),\n );\n\n // Get the typed API for Asset Hub\n const assetHubApi = assetHubClient.getTypedApi(paseoAssetHub);\n\n try {\n // Create the XCM message for teleport (Asset Hub → Bridge Hub)\n const xcm = createTeleportXcmToBridgeHub(BRIDGE_HUB_PARA_ID);\n\n console.log('=== XCM Teleport: Paseo Asset Hub → Bridge Hub ===');\n console.log('From:', ASSET_HUB_ACCOUNT, '(Alice on Asset Hub)');\n console.log('To:', BRIDGE_HUB_BENEFICIARY, '(Beneficiary on Bridge Hub)');\n console.log('Amount:', '1 PAS');\n console.log('');\n\n // Estimate all fees\n const fees = await estimateXcmFeesFromAssetHubToBridgeHub(xcm, assetHubApi);\n void fees; // prevent unused var under isolatedModules\n\n // Create the execute transaction on Asset Hub\n const tx = assetHubApi.tx.PolkadotXcm.execute({\n message: xcm,\n max_weight: {\n ref_time: 6000000000n,\n proof_size: 65536n,\n },\n });\n\n console.log('\\n=== Transaction Details ===');\n console.log('Transaction hex:', (await tx.getEncodedData()).asHex());\n console.log('Ready to submit!');\n } catch (error) {\n console.log('Error stack:', (error as Error).stack);\n console.error('Error occurred:', (error as Error).message);\n if ((error as Error).cause) {\n console.dir((error as Error).cause, { depth: null });\n }\n } finally {\n // Ensure client is always destroyed\n assetHubClient.destroy();\n }\n}\n```"} -{"page_id": "chain-interactions-send-transactions-interoperability-estimate-xcm-fees", "page_title": "XCM Fee Estimation", "index": 7, "depth": 2, "title": "Full Code", "anchor": "full-code", "start_char": 22403, "end_char": 33766, "estimated_token_count": 2142, "token_estimator": "heuristic-v1", "text": "## Full Code\n\nThe full code for the complete implementation is the following:\n\n??? code \"Teleport from Asset Hub to Bridge Hub\"\n\n ```typescript title=\"teleport-ah-to-bridge-hub.ts\"\n import { paseoAssetHub, paseoBridgeHub } from '@polkadot-api/descriptors';\n import { createClient, FixedSizeBinary, Enum } from 'polkadot-api';\n import { getWsProvider } from 'polkadot-api/ws-provider/node';\n import { withPolkadotSdkCompat } from 'polkadot-api/polkadot-sdk-compat';\n import {\n XcmVersionedLocation,\n XcmVersionedAssetId,\n XcmV3Junctions,\n XcmV3MultiassetFungibility,\n XcmVersionedXcm,\n XcmV5Instruction,\n XcmV5Junctions,\n XcmV5Junction,\n XcmV5AssetFilter,\n XcmV5WildAsset,\n } from '@polkadot-api/descriptors';\n\n // 1 PAS = 10^10 units\n const PAS_UNITS = 10_000_000_000n; // 1 PAS\n const PAS_CENTS = 100_000_000n; // 0.01 PAS\n\n // Paseo Asset Hub constants\n const PASEO_ASSET_HUB_RPC_ENDPOINT = 'ws://localhost:8001';\n const ASSET_HUB_ACCOUNT = '15oF4uVJwmo4TdGW7VfQxNLavjCXviqxT9S1MgbjMNHr6Sp5'; // Alice (Paseo Asset Hub)\n\n // Bridge Hub destination\n const BRIDGE_HUB_RPC_ENDPOINT = 'ws://localhost:8000';\n const BRIDGE_HUB_PARA_ID = 1002;\n const BRIDGE_HUB_BENEFICIARY =\n '14E5nqKAp3oAJcmzgZhUD2RcptBeUBScxKHgJKU4HPNcKVf3'; // Bob (Bridge Hub)\n\n // Create the XCM message for teleport (Asset Hub → Bridge Hub)\n function createTeleportXcmToBridgeHub(paraId: number) {\n return XcmVersionedXcm.V5([\n // Withdraw PAS from Asset Hub (PAS on parachains is parents:1, interior: Here)\n XcmV5Instruction.WithdrawAsset([\n {\n id: { parents: 1, interior: XcmV5Junctions.Here() },\n fun: XcmV3MultiassetFungibility.Fungible(1n * PAS_UNITS), // 1 PAS\n },\n ]),\n // Pay local fees on Asset Hub in PAS\n XcmV5Instruction.PayFees({\n asset: {\n id: { parents: 1, interior: XcmV5Junctions.Here() },\n fun: XcmV3MultiassetFungibility.Fungible(10n * PAS_CENTS), // 0.01 PAS\n },\n }),\n // Send to Bridge Hub parachain (parents:1, interior: X1(Parachain(paraId)))\n XcmV5Instruction.InitiateTransfer({\n destination: {\n parents: 1,\n interior: XcmV5Junctions.X1(XcmV5Junction.Parachain(paraId)),\n },\n remote_fees: Enum(\n 'Teleport',\n XcmV5AssetFilter.Definite([\n {\n id: { parents: 1, interior: XcmV5Junctions.Here() },\n fun: XcmV3MultiassetFungibility.Fungible(10n * PAS_CENTS), // 0.01 PAS\n },\n ]),\n ),\n preserve_origin: false,\n remote_xcm: [\n XcmV5Instruction.DepositAsset({\n assets: XcmV5AssetFilter.Wild(XcmV5WildAsset.AllCounted(1)),\n beneficiary: {\n parents: 0,\n interior: XcmV5Junctions.X1(\n XcmV5Junction.AccountId32({\n network: undefined,\n id: FixedSizeBinary.fromAccountId32(BRIDGE_HUB_BENEFICIARY),\n }),\n ),\n },\n }),\n ],\n assets: [\n Enum('Teleport', XcmV5AssetFilter.Wild(XcmV5WildAsset.AllCounted(1))), // Send everything.\n ],\n }),\n ]);\n }\n\n async function estimateXcmFeesFromAssetHubToBridgeHub(\n xcm: any,\n assetHubApi: any,\n ) {\n console.log('=== Fee Estimation Process (Asset Hub → Bridge Hub) ===');\n\n // 1. LOCAL EXECUTION FEES on Asset Hub\n console.log('1. Calculating local execution fees on Asset Hub...');\n let localExecutionFees = 0n;\n\n const weightResult =\n await assetHubApi.apis.XcmPaymentApi.query_xcm_weight(xcm);\n if (weightResult.success) {\n console.log('✓ XCM weight (Asset Hub):', weightResult.value);\n\n // Convert weight to PAS fees from Asset Hub's perspective (parents:1, Here)\n const executionFeesResult =\n await assetHubApi.apis.XcmPaymentApi.query_weight_to_asset_fee(\n weightResult.value,\n XcmVersionedAssetId.V4({\n parents: 1,\n interior: XcmV3Junctions.Here(),\n }),\n );\n\n if (executionFeesResult.success) {\n localExecutionFees = executionFeesResult.value;\n console.log(\n '✓ Local execution fees (Asset Hub):',\n localExecutionFees.toString(),\n 'PAS units',\n );\n } else {\n console.log(\n '✗ Failed to calculate local execution fees:',\n executionFeesResult.value,\n );\n }\n } else {\n console.log(\n '✗ Failed to query XCM weight on Asset Hub:',\n weightResult.value,\n );\n }\n\n // 2. DELIVERY FEES + REMOTE EXECUTION FEES\n console.log('\\n2. Calculating delivery and remote execution fees...');\n let deliveryFees = 0n;\n let remoteExecutionFees = 0n; // Skipped (Bridge Hub descriptor not available)\n\n // Origin from Asset Hub perspective\n const origin = XcmVersionedLocation.V5({\n parents: 0,\n interior: XcmV5Junctions.X1(\n XcmV5Junction.AccountId32({\n id: FixedSizeBinary.fromAccountId32(ASSET_HUB_ACCOUNT),\n network: undefined,\n }),\n ),\n });\n\n // Dry run the XCM locally on Asset Hub\n const dryRunResult = await assetHubApi.apis.DryRunApi.dry_run_xcm(\n origin,\n xcm,\n );\n\n if (\n dryRunResult.success &&\n dryRunResult.value.execution_result.type === 'Complete'\n ) {\n console.log('✓ Local dry run on Asset Hub successful');\n\n const { forwarded_xcms: forwardedXcms } = dryRunResult.value;\n\n // Find the XCM message sent to Bridge Hub (parents:1, interior: X1(Parachain(1002)))\n const bridgeHubXcmEntry = forwardedXcms.find(\n ([location, _]: [any, any]) =>\n (location.type === 'V4' || location.type === 'V5') &&\n location.value.parents === 1 &&\n location.value.interior?.type === 'X1' &&\n location.value.interior.value?.type === 'Parachain' &&\n location.value.interior.value.value === BRIDGE_HUB_PARA_ID,\n );\n\n if (bridgeHubXcmEntry) {\n const [destination, messages] = bridgeHubXcmEntry;\n const remoteXcm = messages[0];\n\n console.log('✓ Found XCM message to Bridge Hub');\n\n // Calculate delivery fees from Asset Hub to Bridge Hub\n const deliveryFeesResult =\n await assetHubApi.apis.XcmPaymentApi.query_delivery_fees(\n destination,\n remoteXcm,\n );\n\n if (\n deliveryFeesResult.success &&\n deliveryFeesResult.value.type === 'V5' &&\n deliveryFeesResult.value.value[0]?.fun?.type === 'Fungible'\n ) {\n deliveryFees = deliveryFeesResult.value.value[0].fun.value;\n console.log('✓ Delivery fees:', deliveryFees.toString(), 'PAS units');\n } else {\n console.log('✗ Failed to calculate delivery fees:', deliveryFeesResult);\n }\n\n // 3. REMOTE EXECUTION FEES on Bridge Hub\n console.log('\\n3. Calculating remote execution fees on Bridge Hub');\n try {\n const bridgeHubClient = createClient(\n withPolkadotSdkCompat(getWsProvider(BRIDGE_HUB_RPC_ENDPOINT)),\n );\n const bridgeHubApi = bridgeHubClient.getTypedApi(paseoBridgeHub);\n const remoteWeightResult =\n await bridgeHubApi.apis.XcmPaymentApi.query_xcm_weight(remoteXcm);\n const remoteFeesResult =\n await bridgeHubApi.apis.XcmPaymentApi.query_weight_to_asset_fee(\n remoteWeightResult.value as {\n ref_time: bigint;\n proof_size: bigint;\n },\n XcmVersionedAssetId.V4({\n parents: 1,\n interior: XcmV3Junctions.Here(),\n }),\n );\n bridgeHubClient.destroy();\n remoteExecutionFees = remoteFeesResult.value as bigint;\n console.log(\n '✓ Remote execution fees:',\n remoteExecutionFees.toString(),\n 'PAS units',\n );\n } catch (error) {\n console.error(\n 'Error calculating remote execution fees on Bridge Hub:',\n error,\n );\n }\n } else {\n console.log('✗ No XCM message found to Bridge Hub');\n }\n } else {\n console.log('✗ Local dry run failed on Asset Hub:', dryRunResult.value);\n }\n\n // 4. TOTAL FEES\n const totalFees = localExecutionFees + deliveryFees + remoteExecutionFees;\n\n console.log('\\n=== Fee Summary (Asset Hub → Bridge Hub) ===');\n console.log(\n 'Local execution fees:',\n localExecutionFees.toString(),\n 'PAS units',\n );\n console.log('Delivery fees:', deliveryFees.toString(), 'PAS units');\n console.log(\n 'Remote execution fees:',\n remoteExecutionFees.toString(),\n 'PAS units',\n );\n console.log('TOTAL FEES:', totalFees.toString(), 'PAS units');\n console.log(\n 'TOTAL FEES:',\n (Number(totalFees) / Number(PAS_UNITS)).toFixed(4),\n 'PAS',\n );\n\n return {\n localExecutionFees,\n deliveryFees,\n remoteExecutionFees,\n totalFees,\n };\n }\n\n async function main() {\n // Connect to the Asset Hub parachain\n const assetHubClient = createClient(\n withPolkadotSdkCompat(getWsProvider(PASEO_ASSET_HUB_RPC_ENDPOINT)),\n );\n\n // Get the typed API for Asset Hub\n const assetHubApi = assetHubClient.getTypedApi(paseoAssetHub);\n\n try {\n // Create the XCM message for teleport (Asset Hub → Bridge Hub)\n const xcm = createTeleportXcmToBridgeHub(BRIDGE_HUB_PARA_ID);\n\n console.log('=== XCM Teleport: Paseo Asset Hub → Bridge Hub ===');\n console.log('From:', ASSET_HUB_ACCOUNT, '(Alice on Asset Hub)');\n console.log('To:', BRIDGE_HUB_BENEFICIARY, '(Beneficiary on Bridge Hub)');\n console.log('Amount:', '1 PAS');\n console.log('');\n\n // Estimate all fees\n const fees = await estimateXcmFeesFromAssetHubToBridgeHub(xcm, assetHubApi);\n void fees; // prevent unused var under isolatedModules\n\n // Create the execute transaction on Asset Hub\n const tx = assetHubApi.tx.PolkadotXcm.execute({\n message: xcm,\n max_weight: {\n ref_time: 6000000000n,\n proof_size: 65536n,\n },\n });\n\n console.log('\\n=== Transaction Details ===');\n console.log('Transaction hex:', (await tx.getEncodedData()).asHex());\n console.log('Ready to submit!');\n } catch (error) {\n console.log('Error stack:', (error as Error).stack);\n console.error('Error occurred:', (error as Error).message);\n if ((error as Error).cause) {\n console.dir((error as Error).cause, { depth: null });\n }\n } finally {\n // Ensure client is always destroyed\n assetHubClient.destroy();\n }\n }\n\n main().catch(console.error);\n\n ```"} -{"page_id": "chain-interactions-send-transactions-interoperability-estimate-xcm-fees", "page_title": "XCM Fee Estimation", "index": 8, "depth": 2, "title": "Running the Script", "anchor": "running-the-script", "start_char": 33766, "end_char": 38015, "estimated_token_count": 950, "token_estimator": "heuristic-v1", "text": "## Running the Script\n\nBefore running the script, you can use chopsticks to fork the Paseo Asset Hub and Paseo Bridge Hub chains locally. To do so, you can use the following files and commands:\n\n1. Create a new directory called `.chopsticks` and add the files:\n\n ??? code \"paseo-bridge-hub.yml\"\n\n {% raw %}\n ```yaml title=\".chopsticks/paseo-bridge-hub.yml\"\n endpoint: wss://bridge-hub-paseo.dotters.network\n mock-signature-host: true\n block: ${env.PASEO_BRIDGE_HUB_BLOCK_NUMBER}\n db: ./db.sqlite\n\n import-storage:\n Sudo:\n Key: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY # Alice\n System:\n Account:\n -\n -\n - 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY\n - providers: 1\n data:\n free: '10000000000000000000'\n ```\n {% endraw %}\n \n ??? code \"paseo-asset-hub.yml\"\n\n {% raw %}\n ```yaml title=\".chopsticks/paseo-asset-hub.yml\"\n endpoint: wss://asset-hub-paseo-rpc.n.dwellir.com\n mock-signature-host: true\n block: ${env.PASEO_ASSET_HUB_BLOCK_NUMBER}\n db: ./db.sqlite\n\n import-storage:\n Sudo:\n Key: 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY # Alice\n System:\n Account:\n -\n -\n - 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY\n - providers: 1\n data:\n free: '10000000000000000000'\n ```\n {% endraw %}\n\n2. Run the following command to fork the Paseo Bridge Hub chain:\n\n ```bash\n chopsticks --config=.chopsticks/paseo-bridge-hub.yml\n ```\n\n After running the command, you will see the following output:\n\n
\n chopsticks --config=.chopsticks/paseo-bridge-hub.yml\n [15:55:22.770] INFO: Paseo Bridge Hub RPC listening on http://[::]:8000 and ws://[::]:8000\n app: \"chopsticks\"\n
\n\n3. Run the following command to fork the Paseo Asset Hub chain:\n\n ```bash\n chopsticks --config=.chopsticks/paseo-asset-hub.yml\n ```\n\n After running the commands, you will see the following output:\n\n
\n chopsticks --config=.chopsticks/paseo-asset-hub.yml\n [15:55:22.770] INFO: Paseo Asset Hub Testnet RPC listening on http://[::]:8001 and ws://[::]:8001\n app: \"chopsticks\"\n
\n\n4. Run the script:\n\n ```bash\n npx ts-node teleport-ah-to-bridge-hub.ts\n ```\n\nAfter running the script, you will see the following output:\n\n
\n npx ts-node teleport-ah-to-bridge-hub.ts\n
\n=== XCM Teleport: Paseo Asset Hub → Bridge Hub ===\nFrom: 15oF4uVJwmo4TdGW7VfQxNLavjCXviqxT9S1MgbjMNHr6Sp5 (Alice on Asset Hub)\nTo: 14E5nqKAp3oAJcmzgZhUD2RcptBeUBScxKHgJKU4HPNcKVf3 (Beneficiary on Bridge Hub)\nAmount: 1 PAS\n\n=== Fee Estimation Process (Asset Hub → Bridge Hub) ===\n1. Calculating local execution fees on Asset Hub...\n✓ XCM weight (Asset Hub): { ref_time: 1462082000n, proof_size: 19578n }\n✓ Local execution fees (Asset Hub): 97890000 PAS units\n\n2. Calculating delivery and remote execution fees...\n✓ Local dry run on Asset Hub successful\n✓ Found XCM message to Bridge Hub\n✓ Delivery fees: 305150000 PAS units\n\n3. Calculating remote execution fees on Bridge Hub\n✓ Remote execution fees: 17965000 PAS units\n\n=== Fee Summary (Asset Hub → Bridge Hub) ===\nLocal execution fees: 97890000 PAS units\nDelivery fees: 305150000 PAS units\nRemote execution fees: 17965000 PAS units\nTOTAL FEES: 421005000 PAS units\nTOTAL FEES: 0.0421 PAS\n\n=== Transaction Details ===\nTransaction hex: 0x1f03050c00040100000700e40b54023001000002286bee31010100a90f0100000401000002286bee000400010204040d010204000101008eaf04151687736326c9fea17e25fc5287613693c912909cb226aa4794f26a480700bca0650102000400\nReady to submit!\n\n\n
"} -{"page_id": "chain-interactions-send-transactions-interoperability-estimate-xcm-fees", "page_title": "XCM Fee Estimation", "index": 9, "depth": 2, "title": "Conclusion", "anchor": "conclusion", "start_char": 38015, "end_char": 38625, "estimated_token_count": 100, "token_estimator": "heuristic-v1", "text": "## Conclusion\n\nThis approach provides accurate fee estimation for XCM teleports from Asset Hub to Bridge Hub Chain by properly simulating execution on both chains and utilizing dedicated runtime APIs for fee calculation. The fee breakdown helps you understand the cost structure of reverse cross-chain operations (parachain → bridge hub chain) and ensures your transactions have sufficient funds to complete successfully.\n\nThe key insight is understanding how asset references change based on the perspective of each chain in the XCM ecosystem, which is crucial for proper fee estimation and XCM construction."} -{"page_id": "chain-interactions-send-transactions-interoperability-transfer-assets-parachains", "page_title": "Transfer Assets Between Parachains", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 38, "end_char": 1008, "estimated_token_count": 223, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nThis guide walks you through transferring tokens between two parachains using the [ParaSpell XCM SDK](/reference/tools/paraspell/){target=\\_blank}. This example utilizes [Asset Hub](/polkadot-protocol/architecture/system-chains/asset-hub/){target=\\_blank} and the [People Chain](/polkadot-protocol/architecture/system-chains/people/){target=\\_blank}. However, the same approach can be applied to transfers between other parachains.\n\nFor development purposes, this guide will use the [Polkadot TestNet](/develop/networks/#paseo){target=\\_blank}, so the transferred token will be PAS.\n\nIn this guide, you will:\n\n- Build an XCM transfer transaction using ParaSpell XCM SDK.\n- Perform a dry run to validate the transfer.\n- Verify the [Existential Deposit (ED)](/reference/glossary/#existential-deposit){target=\\_blank} requirement on the destination chain.\n- Retrieve information regarding the transfer, along with fee estimates.\n- Submit the transaction."} -{"page_id": "chain-interactions-send-transactions-interoperability-transfer-assets-parachains", "page_title": "Transfer Assets Between Parachains", "index": 1, "depth": 3, "title": "Prerequisites", "anchor": "prerequisites", "start_char": 1008, "end_char": 1456, "estimated_token_count": 116, "token_estimator": "heuristic-v1", "text": "### Prerequisites\n\nBefore you begin, ensure you have the following:\n\n- Knowledge of the [fundamentals of Polkadot](/parachains/get-started/){target=\\_blank}.\n- Basic understanding of [XCM](/parachains/interoperability/get-started/){target=\\_blank}.\n- Basic familiarity with JavaScript or TypeScript.\n- Installed [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm){target=\\_blank}, a JavaScript and TypeScript package manager."} -{"page_id": "chain-interactions-send-transactions-interoperability-transfer-assets-parachains", "page_title": "Transfer Assets Between Parachains", "index": 2, "depth": 2, "title": "Initialize Your Project", "anchor": "initialize-your-project", "start_char": 1456, "end_char": 3282, "estimated_token_count": 438, "token_estimator": "heuristic-v1", "text": "## Initialize Your Project\n\nCreate the project folder:\n\n```bash\nmkdir paraspell-transfer && \\\ncd paraspell-transfer\n```\n\nInitialize the JavaScript project:\n\n```bash\nnpm init -y\n```\n\nInstall dev dependencies:\n\n```bash\nnpm install --save-dev @types/node@^22.12.0 tsx@^4.20.6 typescript@^5.7.3\n```\n\nInstall the required dependencies:\n\n```bash\nnpm install --save @paraspell/sdk@11.12.6 polkadot-api@1.20.0 @polkadot-labs/hdkd-helpers@0.0.26 @polkadot-labs/hdkd@0.0.25\n```\n\nNow add the following setup code to `index.ts`:\n\n```ts title=\"index.ts\"\nimport { Builder, hasDryRunSupport } from '@paraspell/sdk';\nimport {\n entropyToMiniSecret,\n mnemonicToEntropy,\n ss58Address,\n} from '@polkadot-labs/hdkd-helpers';\nimport { getPolkadotSigner } from 'polkadot-api/signer';\nimport { sr25519CreateDerive } from '@polkadot-labs/hdkd';\nimport { inspect } from 'util';\n\n// PAS token has 10 decimals\nconst PAS_UNITS = 10_000_000_000n;\n\nconst SEED_PHRASE =\n 'INSERT_YOUR_SEED_PHRASE';\n\n// Create Sr25519 signer from mnemonic\nfunction getSigner() {\n const entropy = mnemonicToEntropy(SEED_PHRASE);\n const miniSecret = entropyToMiniSecret(entropy);\n const derive = sr25519CreateDerive(miniSecret);\n const keyPair = derive('');\n return getPolkadotSigner(keyPair.publicKey, 'Sr25519', keyPair.sign);\n}\n\nconst RECIPIENT_ADDRESS = ss58Address(getSigner().publicKey);\nconst SENDER_ADDRESS = ss58Address(getSigner().publicKey);\n```\n\nReplace the `INSERT_YOUR_SEED_PHRASE` with the seed phrase from your Polkadot development account.\n\nBe sure to fund this account with some PAS tokens on the Paseo Asset Hub using the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1000){target=_blank}.\n\n!!!warning \"Security Warning\"\n Never commit your mnemonic phrase to production code. Use environment variables or secure key management systems."} -{"page_id": "chain-interactions-send-transactions-interoperability-transfer-assets-parachains", "page_title": "Transfer Assets Between Parachains", "index": 3, "depth": 2, "title": "Build a Token Transfer Transaction", "anchor": "build-a-token-transfer-transaction", "start_char": 3282, "end_char": 4195, "estimated_token_count": 229, "token_estimator": "heuristic-v1", "text": "## Build a Token Transfer Transaction\n\nThe next step is to build the transaction that you intend to execute.\n\nIn this example, you will transfer 10 PAS tokens from Paseo's Asset Hub to Paseo's People Chain system parachain.\n\nAdd the ParaSpell transaction code to your `index.ts` file:\n\n```ts title=\"index.ts\"\nasync function transfer() {\n const signer = getSigner();\n\n const tx = await Builder()\n .from('AssetHubPaseo')\n .to('PeoplePaseo')\n .currency({\n symbol: 'PAS',\n amount: 10n * PAS_UNITS, // 10 PAS\n })\n .address(RECIPIENT_ADDRESS)\n .build();\n\n console.log('Built transaction:', inspect(tx, { colors: true, depth: null }));\n\n const result = await tx.signAndSubmit(signer);\n console.log(inspect(result, { colors: true, depth: null }));\n process.exit(0);\n}\n```\n\nDo not execute it just yet. You will perform a dry run of this transaction first to ensure it works as expected."} -{"page_id": "chain-interactions-send-transactions-interoperability-transfer-assets-parachains", "page_title": "Transfer Assets Between Parachains", "index": 4, "depth": 2, "title": "Perform a Dry Run", "anchor": "perform-a-dry-run", "start_char": 4195, "end_char": 8689, "estimated_token_count": 832, "token_estimator": "heuristic-v1", "text": "## Perform a Dry Run\n\nDry runs simulate the transaction without broadcasting it, allowing you to confirm success in advance.\n\nAdd the following dry run code to your `index.ts` script:\n\n```ts title=\"index.ts\"\nasync function dryRunTransfer() {\n if (!hasDryRunSupport('AssetHubPaseo')) {\n console.log('Dry run is not supported on AssetHubPaseo.');\n return;\n }\n\n const tx = await Builder()\n .from('AssetHubPaseo')\n .to('PeoplePaseo')\n .currency({\n symbol: 'PAS',\n amount: 10n * PAS_UNITS,\n })\n .address(RECIPIENT_ADDRESS)\n .senderAddress(SENDER_ADDRESS)\n .dryRun();\n\n console.log(inspect(tx, { colors: true, depth: null }));\n process.exit(0);\n}\n\ndryRunTransfer();\n```\nRun the script using the following command:\n\n```bash\nnpx tsx index.ts\n```\n\nThe result of the dry run will look similar to the following example output:\n\n
\n npx tsx index.ts\n {\n failureReason: undefined,\n failureChain: undefined,\n origin: {\n success: true,\n fee: 17965000n,\n currency: 'PAS',\n asset: {\n symbol: 'PAS',\n isNative: true,\n decimals: 10,\n existentialDeposit: '100000000',\n location: { parents: 1, interior: { Here: null } },\n isFeeAsset: true,\n amount: 100000000000n\n },\n weight: undefined,\n forwardedXcms: [\n {\n type: 'V3',\n value: {\n parents: 1,\n interior: { type: 'X1', value: { type: 'Parachain', value: 1004 } }\n }\n },\n [\n {\n type: 'V3',\n value: [\n {\n type: 'ReceiveTeleportedAsset',\n value: [\n {\n id: {\n type: 'Concrete',\n value: {\n parents: 1,\n interior: { type: 'Here', value: undefined }\n }\n },\n fun: { type: 'Fungible', value: 100000000000n }\n }\n ]\n },\n { type: 'ClearOrigin', value: undefined },\n {\n type: 'BuyExecution',\n value: {\n fees: {\n id: {\n type: 'Concrete',\n value: {\n parents: 1,\n interior: { type: 'Here', value: undefined }\n }\n },\n fun: { type: 'Fungible', value: 100000000000n }\n },\n weight_limit: { type: 'Unlimited', value: undefined }\n }\n },\n {\n type: 'DepositAsset',\n value: {\n assets: {\n type: 'Wild',\n value: { type: 'AllCounted', value: 1 }\n },\n beneficiary: {\n parents: 0,\n interior: {\n type: 'X1',\n value: {\n type: 'AccountId32',\n value: {\n network: undefined,\n id: FixedSizeBinary {\n asText: [Function (anonymous)],\n asHex: [Function (anonymous)],\n asOpaqueHex: [Function (anonymous)],\n asBytes: [Function (anonymous)],\n asOpaqueBytes: [Function (anonymous)]\n }\n }\n }\n }\n }\n }\n },\n {\n type: 'SetTopic',\n value: FixedSizeBinary {\n asText: [Function (anonymous)],\n asHex: [Function (anonymous)],\n asOpaqueHex: [Function (anonymous)],\n asBytes: [Function (anonymous)],\n asOpaqueBytes: [Function (anonymous)]\n }\n }\n ]\n }\n ]\n ],\n destParaId: 1004\n },\n assetHub: undefined,\n bridgeHub: undefined,\n destination: {\n success: true,\n fee: 817598n,\n currency: 'PAS',\n asset: {\n symbol: 'PAS',\n isNative: true,\n decimals: 10,\n existentialDeposit: '1000000000',\n location: { parents: 1, interior: { Here: null } },\n isFeeAsset: true\n },\n weight: { refTime: 176858000n, proofSize: 0n },\n forwardedXcms: [],\n destParaId: undefined\n },\n hops: []\n}\n
"} -{"page_id": "chain-interactions-send-transactions-interoperability-transfer-assets-parachains", "page_title": "Transfer Assets Between Parachains", "index": 5, "depth": 2, "title": "Verify the Existential Deposit", "anchor": "verify-the-existential-deposit", "start_char": 8689, "end_char": 9871, "estimated_token_count": 316, "token_estimator": "heuristic-v1", "text": "## Verify the Existential Deposit\n\nCheck if the recipient account meets the [Existential Deposit (ED)](/polkadot-protocol/glossary/#existential-deposit){target=\\_blank} requirement before sending by using [`verifyEdOnDestination`](https://paraspell.github.io/docs/sdk/xcmUtils.html#verify-ed-on-destination){target=\\_blank}:\n\n```ts title=\"index.ts\"\nasync function verifyED() {\n const isValid = await Builder()\n .from('AssetHubPaseo')\n .to('PeoplePaseo')\n .currency({\n symbol: 'PAS',\n amount: 10n * PAS_UNITS,\n })\n .address(RECIPIENT_ADDRESS)\n .senderAddress(SENDER_ADDRESS)\n .verifyEdOnDestination();\n\n console.log(`ED verification ${isValid ? 'successful' : 'failed'}.`);\n process.exit(0);\n}\n\nverifyED();\n```\nComment out the `dryRunTransfer()` function so that it is not executed again. Then, execute the `verifyED()` by running the following command:\n\n```bash\nnpx tsx index.ts\n```\n\nAfter that, you will get output confirming the ED which will look similar to the following:\n\n
\n npx tsx index.ts\n ED verification successful.\n
"} -{"page_id": "chain-interactions-send-transactions-interoperability-transfer-assets-parachains", "page_title": "Transfer Assets Between Parachains", "index": 6, "depth": 2, "title": "Get Transfer Info and Fee Estimates", "anchor": "get-transfer-info-and-fee-estimates", "start_char": 9871, "end_char": 26422, "estimated_token_count": 3019, "token_estimator": "heuristic-v1", "text": "## Get Transfer Info and Fee Estimates\n\nBefore sending an XCM transaction, it is helpful to estimate the fees associated with executing and delivering the cross-chain message.\n\nParaSpell has a helpful function for this: [`getTransferInfo()`](https://paraspell.github.io/docs/sdk/xcmUtils.html#xcm-transfer-info){target=\\_blank}. This function returns an estimate of the associated XCM fees, along with the account's balance before and after the fees are paid.\n\n```ts title=\"index.ts\"\nasync function XcmTransferInfo() {\n const info = await Builder()\n .from('AssetHubPaseo')\n .to('PeoplePaseo')\n .currency({\n symbol: 'PAS',\n amount: 10n * PAS_UNITS,\n })\n .address(RECIPIENT_ADDRESS)\n .senderAddress(SENDER_ADDRESS)\n .getTransferInfo();\n\n console.log('Transfer Info:', info);\n process.exit(0);\n}\n\nXcmTransferInfo();\n```\n\nComment out the `verifyED()` function so it doesn't execute again. Then, execute the `XcmTransferInfo()` function by running the following command:\n\n```bash\nnpx tsx index.ts\n```\n\nYou will see all the information for your transfer similar to the following example:\n\n
\n npx tsx index.ts\n Transfer Info: {\n chain: {\n origin: \"AssetHubPaseo\",\n destination: \"PeoplePaseo\",\n ecosystem: \"PAS\",\n },\n origin: {\n selectedCurrency: {\n sufficient: true,\n balance: 9799197260420n,\n balanceAfter: 9699197260420n,\n currencySymbol: \"PAS\",\n asset: [Object ...],\n existentialDeposit: 100000000n,\n },\n xcmFee: {\n sufficient: true,\n fee: 17965000n,\n balance: 9799197260420n,\n balanceAfter: 9799179295420n,\n currencySymbol: \"PAS\",\n asset: [Object ...],\n },\n },\n assetHub: undefined,\n bridgeHub: undefined,\n hops: [],\n destination: {\n receivedCurrency: {\n sufficient: true,\n receivedAmount: 99999182402n,\n balance: 199998364804n,\n balanceAfter: 299997547206n,\n currencySymbol: \"PAS\",\n asset: [Object ...],\n existentialDeposit: 1000000000n,\n },\n xcmFee: {\n fee: 817598n,\n balance: 199998364804n,\n balanceAfter: 299997547206n,\n currencySymbol: \"PAS\",\n asset: [Object ...],\n },\n },\n}\n
\nNow that you have:\n\n- Completed a successful dry run of the transaction.\n- Verified the existential deposit on the recipient account.\n- Obtained an estimate of the associated XCM fees.\n\nYou can execute the transfer function by adding the following function call:\n\n```typescript title=\"index.ts\"\ntransfer();\n```\n\nComment out the `XcmTransferInfo()` function so it doesn't execute again. Then, execute the transfer by running the following command: \n\n```bash\nnpx tsx index.ts\n```\n\nYour `transfer` function will submit the transaction, and you will get the following output:\n\n
\n npx tsx index.ts\n ...\n Built transaction: {\n getPaymentInfo: [AsyncFunction: getPaymentInfo],\n getEstimatedFees: [AsyncFunction: getEstimatedFees],\n decodedCall: {\n type: 'PolkadotXcm',\n value: {\n type: 'limited_teleport_assets',\n value: {\n dest: {\n type: 'V5',\n value: {\n parents: 1,\n interior: { type: 'X1', value: { type: 'Parachain', value: 1004 } }\n }\n },\n beneficiary: {\n type: 'V5',\n value: {\n parents: 0,\n interior: {\n type: 'X1',\n value: {\n type: 'AccountId32',\n value: {\n network: undefined,\n id: FixedSizeBinary {\n asText: [Function (anonymous)],\n asHex: [Function (anonymous)],\n asOpaqueHex: [Function (anonymous)],\n asBytes: [Function (anonymous)],\n asOpaqueBytes: [Function (anonymous)]\n }\n }\n }\n }\n }\n },\n assets: {\n type: 'V5',\n value: [\n {\n id: { parents: 1, interior: { type: 'Here', value: null } },\n fun: { type: 'Fungible', value: 100000000000n }\n }\n ]\n },\n fee_asset_item: 0,\n weight_limit: { type: 'Unlimited' }\n }\n }\n },\n getEncodedData: [Function: getEncodedData],\n sign: [Function: sign],\n signSubmitAndWatch: [Function: signSubmitAndWatch],\n signAndSubmit: [Function: signAndSubmit]\n}\n
\nOnce the transaction is successfully included in a block, you will see the recipient's account balance updated, and you will receive output similar to the following.\n\n???- code \"Successful Transaction Submission\"\n This output will be returned once the transaction has been successfully included in a block.\n\n
\n ...\n {\n txHash: '0x6fbecc0b284adcff46ab39872659c2567395c865adef5f8cbea72f25b6042609',\n block: {\n index: 2,\n number: 2524809,\n hash: '0xa39a96d5921402c6e8f67e48b8395d6b21382c72d4d30f8497a0e9f890bc0d4c'\n },\n ok: true,\n events: [\n {\n type: 'Balances',\n value: {\n type: 'Withdraw',\n value: {\n who: '15DMtB5BDCJqw4uZtByTWXGqViAVx7XjRsxWbTH5tfrHLe8j',\n amount: 15668864n\n }\n },\n topics: []\n },\n {\n type: 'Balances',\n value: {\n type: 'Burned',\n value: {\n who: '15DMtB5BDCJqw4uZtByTWXGqViAVx7XjRsxWbTH5tfrHLe8j',\n amount: 100000000000n\n }\n },\n topics: []\n },\n {\n type: 'PolkadotXcm',\n value: {\n type: 'Attempted',\n value: {\n outcome: {\n type: 'Complete',\n value: { used: { ref_time: 190990000n, proof_size: 3593n } }\n }\n }\n },\n topics: []\n },\n {\n type: 'Balances',\n value: {\n type: 'Burned',\n value: {\n who: '15DMtB5BDCJqw4uZtByTWXGqViAVx7XjRsxWbTH5tfrHLe8j',\n amount: 304850000n\n }\n },\n topics: []\n },\n {\n type: 'Balances',\n value: {\n type: 'Minted',\n value: {\n who: '14xmwinmCEz6oRrFdczHKqHgWNMiCysE2KrA4jXXAAM1Eogk',\n amount: 304850000n\n }\n },\n topics: []\n },\n {\n type: 'PolkadotXcm',\n value: {\n type: 'FeesPaid',\n value: {\n paying: {\n parents: 0,\n interior: {\n type: 'X1',\n value: {\n type: 'AccountId32',\n value: {\n network: { type: 'Polkadot', value: undefined },\n id: FixedSizeBinary {\n asText: [Function (anonymous)],\n asHex: [Function (anonymous)],\n asOpaqueHex: [Function (anonymous)],\n asBytes: [Function (anonymous)],\n asOpaqueBytes: [Function (anonymous)]\n }\n }\n }\n }\n },\n fees: [\n {\n id: {\n parents: 1,\n interior: { type: 'Here', value: undefined }\n },\n fun: { type: 'Fungible', value: 304850000n }\n }\n ]\n }\n },\n topics: []\n },\n {\n type: 'XcmpQueue',\n value: {\n type: 'XcmpMessageSent',\n value: {\n message_hash: FixedSizeBinary {\n asText: [Function (anonymous)],\n asHex: [Function (anonymous)],\n asOpaqueHex: [Function (anonymous)],\n asBytes: [Function (anonymous)],\n asOpaqueBytes: [Function (anonymous)]\n }\n }\n },\n topics: []\n },\n {\n type: 'PolkadotXcm',\n value: {\n type: 'Sent',\n value: {\n origin: {\n parents: 0,\n interior: {\n type: 'X1',\n value: {\n type: 'AccountId32',\n value: {\n network: { type: 'Polkadot', value: undefined },\n id: FixedSizeBinary {\n asText: [Function (anonymous)],\n asHex: [Function (anonymous)],\n asOpaqueHex: [Function (anonymous)],\n asBytes: [Function (anonymous)],\n asOpaqueBytes: [Function (anonymous)]\n }\n }\n }\n }\n },\n destination: {\n parents: 1,\n interior: { type: 'X1', value: { type: 'Parachain', value: 1002 } }\n },\n message: [\n {\n type: 'ReceiveTeleportedAsset',\n value: [\n {\n id: {\n parents: 1,\n interior: { type: 'Here', value: undefined }\n },\n fun: { type: 'Fungible', value: 100000000000n }\n }\n ]\n },\n { type: 'ClearOrigin', value: undefined },\n {\n type: 'BuyExecution',\n value: {\n fees: {\n id: {\n parents: 1,\n interior: { type: 'Here', value: undefined }\n },\n fun: { type: 'Fungible', value: 100000000000n }\n },\n weight_limit: { type: 'Unlimited', value: undefined }\n }\n },\n {\n type: 'DepositAsset',\n value: {\n assets: {\n type: 'Wild',\n value: { type: 'AllCounted', value: 1 }\n },\n beneficiary: {\n parents: 0,\n interior: {\n type: 'X1',\n value: {\n type: 'AccountId32',\n value: {\n network: undefined,\n id: FixedSizeBinary {\n asText: [Function (anonymous)],\n asHex: [Function (anonymous)],\n asOpaqueHex: [Function (anonymous)],\n asBytes: [Function (anonymous)],\n asOpaqueBytes: [Function (anonymous)]\n }\n }\n }\n }\n }\n }\n }\n ],\n message_id: FixedSizeBinary {\n asText: [Function (anonymous)],\n asHex: [Function (anonymous)],\n asOpaqueHex: [Function (anonymous)],\n asBytes: [Function (anonymous)],\n asOpaqueBytes: [Function (anonymous)]\n }\n }\n },\n topics: []\n },\n {\n type: 'Balances',\n value: {\n type: 'Deposit',\n value: {\n who: '13UVJyLgBASGhE2ok3TvxUfaQBGUt88JCcdYjHvUhvQkFTTx',\n amount: 15668864n\n }\n },\n topics: []\n },\n {\n type: 'TransactionPayment',\n value: {\n type: 'TransactionFeePaid',\n value: {\n who: '15DMtB5BDCJqw4uZtByTWXGqViAVx7XjRsxWbTH5tfrHLe8j',\n actual_fee: 15668864n,\n tip: 0n\n }\n },\n topics: []\n },\n {\n type: 'System',\n value: {\n type: 'ExtrinsicSuccess',\n value: {\n dispatch_info: {\n weight: { ref_time: 952851000n, proof_size: 13382n },\n class: { type: 'Normal', value: undefined },\n pays_fee: { type: 'Yes', value: undefined }\n }\n }\n },\n topics: []\n }\n ]\n }\n
\nAfter executing the transfer, check the account balance on [Polkadot.js Apps](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fsys.turboflakes.io%2Fasset-hub-paseo){target=\\_blank} for [Paseo's Asset Hub](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fsys.turboflakes.io%2Fasset-hub-paseo#/accounts){target=\\_blank} and [Paseo's People Chain](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fsys.ibp.network%2Fpeople-paseo#/accounts){target=\\_blank}.\n\nYou should see:\n\n- The recipient account now has 10 more PAS tokens.\n- The sender account has the transfer amount (10 PAS) + the fees amount debited from their account balance.\n\nYou have now successfully created and sent a cross-chain transfer using the ParaSpell XCM SDK!\n\n???- code \"Full Code\"\n\n ```typescript title=\"index.ts\"\n import { Builder, hasDryRunSupport } from '@paraspell/sdk';\n import {\n entropyToMiniSecret,\n mnemonicToEntropy,\n ss58Address,\n } from '@polkadot-labs/hdkd-helpers';\n import { getPolkadotSigner } from 'polkadot-api/signer';\n import { sr25519CreateDerive } from '@polkadot-labs/hdkd';\n import { inspect } from 'util';\n\n // PAS token has 10 decimals\n const PAS_UNITS = 10_000_000_000n;\n\n const SEED_PHRASE =\n 'INSERT_YOUR_SEED_PHRASE';\n\n // Create Sr25519 signer from mnemonic\n function getSigner() {\n const entropy = mnemonicToEntropy(SEED_PHRASE);\n const miniSecret = entropyToMiniSecret(entropy);\n const derive = sr25519CreateDerive(miniSecret);\n const keyPair = derive('');\n return getPolkadotSigner(keyPair.publicKey, 'Sr25519', keyPair.sign);\n }\n\n const RECIPIENT_ADDRESS = ss58Address(getSigner().publicKey);\n const SENDER_ADDRESS = ss58Address(getSigner().publicKey);\n\n async function transfer() {\n const signer = getSigner();\n\n const tx = await Builder()\n .from('AssetHubPaseo')\n .to('PeoplePaseo')\n .currency({\n symbol: 'PAS',\n amount: 10n * PAS_UNITS, // 10 PAS\n })\n .address(RECIPIENT_ADDRESS)\n .build();\n\n console.log('Built transaction:', inspect(tx, { colors: true, depth: null }));\n\n const result = await tx.signAndSubmit(signer);\n console.log(inspect(result, { colors: true, depth: null }));\n process.exit(0);\n }\n\n async function dryRunTransfer() {\n if (!hasDryRunSupport('AssetHubPaseo')) {\n console.log('Dry run is not supported on AssetHubPaseo.');\n return;\n }\n\n const tx = await Builder()\n .from('AssetHubPaseo')\n .to('PeoplePaseo')\n .currency({\n symbol: 'PAS',\n amount: 10n * PAS_UNITS,\n })\n .address(RECIPIENT_ADDRESS)\n .senderAddress(SENDER_ADDRESS)\n .dryRun();\n\n console.log(inspect(tx, { colors: true, depth: null }));\n process.exit(0);\n }\n\n dryRunTransfer();\n\n async function verifyED() {\n const isValid = await Builder()\n .from('AssetHubPaseo')\n .to('PeoplePaseo')\n .currency({\n symbol: 'PAS',\n amount: 10n * PAS_UNITS,\n })\n .address(RECIPIENT_ADDRESS)\n .senderAddress(SENDER_ADDRESS)\n .verifyEdOnDestination();\n\n console.log(`ED verification ${isValid ? 'successful' : 'failed'}.`);\n process.exit(0);\n }\n\n verifyED();\n\n async function XcmTransferInfo() {\n const info = await Builder()\n .from('AssetHubPaseo')\n .to('PeoplePaseo')\n .currency({\n symbol: 'PAS',\n amount: 10n * PAS_UNITS,\n })\n .address(RECIPIENT_ADDRESS)\n .senderAddress(SENDER_ADDRESS)\n .getTransferInfo();\n\n console.log('Transfer Info:', info);\n process.exit(0);\n }\n\n XcmTransferInfo();\n\n transfer();\n\n ```"} -{"page_id": "chain-interactions-send-transactions-interoperability-transfer-assets-parachains", "page_title": "Transfer Assets Between Parachains", "index": 7, "depth": 2, "title": "Next Steps", "anchor": "next-steps", "start_char": 26422, "end_char": 26764, "estimated_token_count": 84, "token_estimator": "heuristic-v1", "text": "## Next Steps\n\n- Read the Docs: Dive deeper into the features of the [ParaSpell XCM SDK](https://paraspell.github.io/docs/sdk/getting-started.html){target=\\_blank} documentation.\n\n- Learn about XCM: Understand the underlying protocol by visiting the [Introduction to XCM page](/parachains/interoperability/get-started/) in the Polkadot Docs."} -{"page_id": "chain-interactions-send-transactions-pay-fees-with-different-tokens", "page_title": "Send a Transaction While Paying the Fee with a Different Token", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 66, "end_char": 389, "estimated_token_count": 58, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nThe Asset Hub provides a powerful feature that allows users to pay transaction fees using alternative tokens instead of the native token of the chain.\n\nThis tutorial demonstrates how to send a DOT transfer transaction while paying the fees using a different token (USDT in this example) on the Asset Hub."} -{"page_id": "chain-interactions-send-transactions-pay-fees-with-different-tokens", "page_title": "Send a Transaction While Paying the Fee with a Different Token", "index": 1, "depth": 2, "title": "Environment Setup", "anchor": "environment-setup", "start_char": 389, "end_char": 1465, "estimated_token_count": 288, "token_estimator": "heuristic-v1", "text": "## Environment Setup\n\nLet's set up the development environment for this tutorial:\n\n1. Create a new directory and initialize the project:\n\n ```bash\n mkdir fee-payment-tutorial && \\\n cd fee-payment-tutorial\n ```\n\n2. Initialize the project:\n\n ```bash\n npm init -y\n ```\n\n3. Install dev dependencies:\n\n ```bash\n npm install --save-dev @types/node@^22.12.0 ts-node@^10.9.2 typescript@^5.7.3\n ```\n\n4. Install dependencies:\n\n ```bash\n npm install --save @polkadot-labs/hdkd@^0.0.13 @polkadot-labs/hdkd-helpers@^0.0.13 polkadot-api@1.9.5\n ```\n\n5. Create TypeScript configuration:\n\n ```bash\n npx tsc --init && npm pkg set type=module\n ```\n\n The command `npm pkg set type=module` is used to set the type of the project to module. This is necessary to use the `import` statement in the TypeScript code.\n\n6. Generate Polkadot API types for Asset Hub:\n\n ```bash\n npx papi add assetHub -n polkadot_asset_hub\n ```\n\n7. Create a new file called `fee-payment-transaction.ts`:\n\n ```bash\n touch fee-payment-transaction.ts\n ```"} -{"page_id": "chain-interactions-send-transactions-pay-fees-with-different-tokens", "page_title": "Send a Transaction While Paying the Fee with a Different Token", "index": 2, "depth": 2, "title": "Local Asset Hub Setup", "anchor": "local-asset-hub-setup", "start_char": 1465, "end_char": 2109, "estimated_token_count": 162, "token_estimator": "heuristic-v1", "text": "## Local Asset Hub Setup\n\nBefore running the script, you'll need to fork the Asset Hub locally using Chopsticks:\n\n```bash\nchopsticks -c polkadot-asset-hub\n```\n\nThis command forks the Asset Hub chain, making it available at `ws://localhost:8000`. By running `polkadot-asset-hub`, you're using the Asset Hub fork with the configuration specified in the [`polkadot-asset-hub.yml`](https://github.com/AcalaNetwork/chopsticks/blob/master/configs/polkadot-asset-hub.yml){target=_blank} file. This configuration defines Alice's account with USDT assets. If you want to use a different chain, ensure the account you're using has the necessary assets."} -{"page_id": "chain-interactions-send-transactions-pay-fees-with-different-tokens", "page_title": "Send a Transaction While Paying the Fee with a Different Token", "index": 3, "depth": 2, "title": "Implementation", "anchor": "implementation", "start_char": 2109, "end_char": 2377, "estimated_token_count": 55, "token_estimator": "heuristic-v1", "text": "## Implementation\n\nIn the following sections, you'll set up imports and constants, create a transaction signer, and connect to the Polkadot Asset Hub chain. Then, you'll create and send a DOT transfer transaction, requesting that fees be paid in USDT instead of DOT."} -{"page_id": "chain-interactions-send-transactions-pay-fees-with-different-tokens", "page_title": "Send a Transaction While Paying the Fee with a Different Token", "index": 4, "depth": 3, "title": "Import Dependencies", "anchor": "import-dependencies", "start_char": 2377, "end_char": 3041, "estimated_token_count": 161, "token_estimator": "heuristic-v1", "text": "### Import Dependencies\n\nAdd the following imports to your `fee-payment-transaction.ts` file:\n\n```typescript title=\"fee-payment-transaction.ts\"\nimport { sr25519CreateDerive } from \"@polkadot-labs/hdkd\";\nimport {\n DEV_PHRASE,\n entropyToMiniSecret,\n mnemonicToEntropy,\n} from \"@polkadot-labs/hdkd-helpers\";\nimport { getPolkadotSigner } from \"polkadot-api/signer\";\nimport { createClient } from \"polkadot-api\";\nimport { assetHub } from \"@polkadot-api/descriptors\";\nimport { withPolkadotSdkCompat } from \"polkadot-api/polkadot-sdk-compat\";\nimport { getWsProvider } from \"polkadot-api/ws-provider/node\";\nimport { MultiAddress } from \"@polkadot-api/descriptors\";\n```"} -{"page_id": "chain-interactions-send-transactions-pay-fees-with-different-tokens", "page_title": "Send a Transaction While Paying the Fee with a Different Token", "index": 5, "depth": 3, "title": "Define Constants", "anchor": "define-constants", "start_char": 3041, "end_char": 3329, "estimated_token_count": 57, "token_estimator": "heuristic-v1", "text": "### Define Constants\n\nDefine the constants for your transaction:\n\n```typescript title=\"fee-payment-transaction.ts\"\nconst TARGET_ADDRESS = \"14E5nqKAp3oAJcmzgZhUD2RcptBeUBScxKHgJKU4HPNcKVf3\"; // Bob's address\nconst TRANSFER_AMOUNT = 3_000_000_000n; // 3 DOT\nconst USD_ASSET_ID = 1337;\n```"} -{"page_id": "chain-interactions-send-transactions-pay-fees-with-different-tokens", "page_title": "Send a Transaction While Paying the Fee with a Different Token", "index": 6, "depth": 3, "title": "Create a Signer", "anchor": "create-a-signer", "start_char": 3329, "end_char": 3900, "estimated_token_count": 117, "token_estimator": "heuristic-v1", "text": "### Create a Signer\n\nCreate a signer using Alice's development account:\n\n```typescript title=\"fee-payment-transaction.ts\"\nconst createSigner = async () => {\n const entropy = mnemonicToEntropy(DEV_PHRASE);\n const miniSecret = entropyToMiniSecret(entropy);\n const derive = sr25519CreateDerive(miniSecret);\n const hdkdKeyPair = derive(\"//Alice\");\n const polkadotSigner = getPolkadotSigner(\n hdkdKeyPair.publicKey,\n \"Sr25519\",\n hdkdKeyPair.sign\n );\n return polkadotSigner;\n};\n```\n\nThis function will return a signer that can be used to sign the transaction."} -{"page_id": "chain-interactions-send-transactions-pay-fees-with-different-tokens", "page_title": "Send a Transaction While Paying the Fee with a Different Token", "index": 7, "depth": 3, "title": "Setup the Client and API", "anchor": "setup-the-client-and-api", "start_char": 3900, "end_char": 4207, "estimated_token_count": 73, "token_estimator": "heuristic-v1", "text": "### Setup the Client and API\n\nCreate the client connection to the local Asset Hub:\n\n```typescript title=\"fee-payment-transaction.ts\"\nconst client = createClient(\n withPolkadotSdkCompat(\n getWsProvider(\"ws://localhost:8000\") // Chopsticks Asset Hub\n )\n);\n\nconst api = client.getTypedApi(assetHub);\n```"} -{"page_id": "chain-interactions-send-transactions-pay-fees-with-different-tokens", "page_title": "Send a Transaction While Paying the Fee with a Different Token", "index": 8, "depth": 3, "title": "Create the Transaction", "anchor": "create-the-transaction", "start_char": 4207, "end_char": 4565, "estimated_token_count": 83, "token_estimator": "heuristic-v1", "text": "### Create the Transaction\n\nCreate a standard DOT transfer transaction:\n\n```typescript title=\"fee-payment-transaction.ts\"\nconst tx = api.tx.Balances.transfer_keep_alive({\n dest: MultiAddress.Id(TARGET_ADDRESS),\n value: BigInt(TRANSFER_AMOUNT),\n});\n```\n\nThis creates a transaction that transfers 3 DOT to Bob's address while keeping Alice's account alive."} -{"page_id": "chain-interactions-send-transactions-pay-fees-with-different-tokens", "page_title": "Send a Transaction While Paying the Fee with a Different Token", "index": 9, "depth": 3, "title": "Sign and Submit with Alternative Fee Payment", "anchor": "sign-and-submit-with-alternative-fee-payment", "start_char": 4565, "end_char": 5515, "estimated_token_count": 270, "token_estimator": "heuristic-v1", "text": "### Sign and Submit with Alternative Fee Payment\n\nThe key part of this tutorial is specifying an alternative asset for fee payment. This is done through the `asset` parameter in the `signAndSubmit` options:\n\n```typescript title=\"fee-payment-transaction.ts\"\nconst signer = await createSigner();\n\nconst result = await tx.signAndSubmit(signer, {\n asset: {\n parents: 0,\n interior: {\n type: \"X2\",\n value: [\n { type: \"PalletInstance\", value: 50 },\n { type: \"GeneralIndex\", value: BigInt(USD_ASSET_ID) },\n ],\n },\n },\n});\n\nconst { txHash, ok, block, events } = result;\nconsole.log(`Tx finalized: ${txHash} (ok=${ok})`);\nconsole.log(`Block: #${block.number} ${block.hash} [tx index ${block.index}]`);\n\nconsole.log(\"Events:\");\nfor (const ev of events) {\n const type = (ev as any).type ?? \"unknown\";\n console.log(`- ${type}`);\n}\n\nprocess.exit(0);\n```\n\nThis specifies that the fees should be paid using the USDT asset."} -{"page_id": "chain-interactions-send-transactions-pay-fees-with-different-tokens", "page_title": "Send a Transaction While Paying the Fee with a Different Token", "index": 10, "depth": 2, "title": "Full Code", "anchor": "full-code", "start_char": 5515, "end_char": 7890, "estimated_token_count": 523, "token_estimator": "heuristic-v1", "text": "## Full Code\n\nThe full code for the complete implementation is the following:\n\n??? code \"Complete Code\"\n\n ```typescript title=\"fee-payment-transaction.ts\"\n import { sr25519CreateDerive } from \"@polkadot-labs/hdkd\";\n import {\n DEV_PHRASE,\n entropyToMiniSecret,\n mnemonicToEntropy,\n } from \"@polkadot-labs/hdkd-helpers\";\n import { getPolkadotSigner } from \"polkadot-api/signer\";\n import { createClient } from \"polkadot-api\";\n import { assetHub } from \"@polkadot-api/descriptors\";\n import { withPolkadotSdkCompat } from \"polkadot-api/polkadot-sdk-compat\";\n import { getWsProvider } from \"polkadot-api/ws-provider/node\";\n import { MultiAddress } from \"@polkadot-api/descriptors\";\n\n const TARGET_ADDRESS = \"14E5nqKAp3oAJcmzgZhUD2RcptBeUBScxKHgJKU4HPNcKVf3\"; // Bob's address\n const TRANSFER_AMOUNT = 3_000_000_000n; // 3 DOT\n const USD_ASSET_ID = 1337;\n\n const createSigner = async () => {\n const entropy = mnemonicToEntropy(DEV_PHRASE);\n const miniSecret = entropyToMiniSecret(entropy);\n const derive = sr25519CreateDerive(miniSecret);\n const hdkdKeyPair = derive(\"//Alice\");\n const polkadotSigner = getPolkadotSigner(\n hdkdKeyPair.publicKey,\n \"Sr25519\",\n hdkdKeyPair.sign\n );\n return polkadotSigner;\n };\n\n const client = createClient(\n withPolkadotSdkCompat(\n getWsProvider(\"ws://localhost:8000\") // Chopsticks Asset Hub\n )\n );\n\n const api = client.getTypedApi(assetHub);\n\n const tx = api.tx.Balances.transfer_keep_alive({\n dest: MultiAddress.Id(TARGET_ADDRESS),\n value: BigInt(TRANSFER_AMOUNT),\n });\n\n const signer = await createSigner();\n\n const result = await tx.signAndSubmit(signer, {\n asset: {\n parents: 0,\n interior: {\n type: \"X2\",\n value: [\n { type: \"PalletInstance\", value: 50 },\n { type: \"GeneralIndex\", value: BigInt(USD_ASSET_ID) },\n ],\n },\n },\n });\n\n const { txHash, ok, block, events } = result;\n console.log(`Tx finalized: ${txHash} (ok=${ok})`);\n console.log(`Block: #${block.number} ${block.hash} [tx index ${block.index}]`);\n\n console.log(\"Events:\");\n for (const ev of events) {\n const type = (ev as any).type ?? \"unknown\";\n console.log(`- ${type}`);\n }\n\n process.exit(0);\n ```"} -{"page_id": "chain-interactions-send-transactions-pay-fees-with-different-tokens", "page_title": "Send a Transaction While Paying the Fee with a Different Token", "index": 11, "depth": 2, "title": "Running the Script", "anchor": "running-the-script", "start_char": 7890, "end_char": 7985, "estimated_token_count": 28, "token_estimator": "heuristic-v1", "text": "## Running the Script\n\nTo run the script:\n\n```bash\nnpx ts-node fee-payment-transaction.ts\n```"} -{"page_id": "chain-interactions-send-transactions-pay-fees-with-different-tokens", "page_title": "Send a Transaction While Paying the Fee with a Different Token", "index": 12, "depth": 2, "title": "Expected Output", "anchor": "expected-output", "start_char": 7985, "end_char": 8853, "estimated_token_count": 196, "token_estimator": "heuristic-v1", "text": "## Expected Output\n\nWhen you run the script successfully, you should see output similar to:\n\n
\n npx ts-node fee-payment-transaction.ts\n
\nTx finalized: 0x771956fdf40b3741bdc3c1e981a6daacbe5521877ad1915542e7413bb4a820bc (ok=true)\nBlock: #9645060 0x57710514f168b5c444c8e47b1e1a31dd9e7bc7e9a51d8d25ccdbc6053e159f6b [tx index 2]\nEvents:\n- Assets\n- Balances\n- Assets\n- AssetConversion\n- Balances\n- Balances\n- AssetTxPayment\n- System\n
\n
\nThe key events to look for are:\n\n- **Assets**: The asset was transferred.\n- **Balances**: The fees were paid using the alternative asset.\n- **AssetConversion**: The fees were converted to the alternative asset.\n- **AssetTxPayment**: The fees were paid using the alternative asset.\n- **System**: The transaction was successful."} -{"page_id": "chain-interactions-send-transactions-pay-fees-with-different-tokens", "page_title": "Send a Transaction While Paying the Fee with a Different Token", "index": 13, "depth": 2, "title": "Conclusion", "anchor": "conclusion", "start_char": 8853, "end_char": 9257, "estimated_token_count": 61, "token_estimator": "heuristic-v1", "text": "## Conclusion\n\nPaying transaction fees with alternative tokens on Asset Hub provides significant flexibility for users and applications.\n\nThe key takeaway is understanding how to specify alternative assets using the XCM location format, which opens up possibilities for building applications that can operate entirely using specific token ecosystems while still leveraging the full power of the network."} -{"page_id": "chain-interactions-token-operations-convert-assets", "page_title": "Convert Assets on Asset Hub", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 31, "end_char": 613, "estimated_token_count": 137, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nAsset Conversion is an Automated Market Maker (AMM) utilizing [Uniswap V2](https://github.com/Uniswap/v2-core){target=\\_blank} logic and implemented as a pallet on Polkadot's Asset Hub.\n\nThis guide will provide detailed information about the key functionalities offered by the [Asset Conversion](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/asset-conversion){target=\\_blank} pallet on Asset Hub, including:\n\n- Creating a liquidity pool.\n- Adding liquidity to a pool.\n- Swapping assets.\n- Withdrawing liquidity from a pool."} -{"page_id": "chain-interactions-token-operations-convert-assets", "page_title": "Convert Assets on Asset Hub", "index": 1, "depth": 2, "title": "Prerequisites", "anchor": "prerequisites", "start_char": 613, "end_char": 1321, "estimated_token_count": 169, "token_estimator": "heuristic-v1", "text": "## Prerequisites\n\nBefore converting assets on Asset Hub, you must ensure you have:\n\n- Access to the [Polkadot.js Apps](https://polkadot.js.org/apps){target=\\_blank} interface and a connection with the intended blockchain.\n- A funded wallet containing the assets you wish to convert and enough available funds to cover the transaction fees.\n- An asset registered on Asset Hub that you want to convert. If you haven't created an asset on Asset Hub yet, refer to the [Register a Local Asset](/chain-interactions/token-operations/register-local-asset/){target=\\_blank} or [Register a Foreign Asset](/chain-interactions/token-operations/register-foreign-asset/){target=\\_blank} documentation to create an asset."} -{"page_id": "chain-interactions-token-operations-convert-assets", "page_title": "Convert Assets on Asset Hub", "index": 2, "depth": 2, "title": "Create a Liquidity Pool", "anchor": "create-a-liquidity-pool", "start_char": 1321, "end_char": 4337, "estimated_token_count": 687, "token_estimator": "heuristic-v1", "text": "## Create a Liquidity Pool\n\nIf an asset on Asset Hub does not have an existing liquidity pool, the first step is to create one.\n\nThe asset conversion pallet provides the `createPool` extrinsic to create a new liquidity pool, creating an empty liquidity pool and a new `LP token` asset.\n\n!!! tip\n A testing token with the asset ID `1112` and the name `PPM` was created for this example.\n\nAs stated in the [Test Environment Setup](#test-environment-setup) section, this tutorial is based on the assumption that you have an instance of Polkadot Asset Hub running locally. Therefore, the demo liquidity pool will be created between DOT and PPM tokens. However, the same steps can be applied to any other asset on Asset Hub.\n\nFrom the Asset Hub perspective, the Multilocation that identifies the PPM token is the following:\n\n```javascript\n{\n parents: 0,\n interior: {\n X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }]\n }\n}\n```\n\nThe `PalletInstance` value of `50` represents the Assets pallet on Asset Hub. The `GeneralIndex` value of `1112` is the PPM asset's asset ID.\n\nTo create the liquidity pool, you can follow these steps:\n\n1. Navigate to the **Extrinsics** section on the Polkadot.js Apps interface:\n\n 1. Select **Developer** from the top menu.\n 2. Click on **Extrinsics** from the dropdown menu.\n\n ![Extrinsics Section](/images/chain-interactions/token-operations/convert-assets/convert-assets-01.webp)\n\n2. Select extrinsic to create the pool:\n\n 1. Select the **`AssetConversion`** pallet.\n 2. Choose the **`createPool`** extrinsic from the list of available extrinsics.\n\n ![Create Pool Extrinsic](/images/chain-interactions/token-operations/convert-assets/convert-assets-02.webp)\n\n3. Fill in the required fields:\n\n 1. **`asset1`**: The Multilocation of the first asset in the pool. In this case, it is the DOT token, which the following Multilocation represents.\n\n ```javascript\n {\n parents: 0,\n interior: 'Here'\n }\n ```\n\n 2. **`asset2`**: The second asset's Multilocation within the pool. This refers to the PPM token, which the following Multilocation identifies.\n\n ```javascript\n {\n parents: 0,\n interior: {\n X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }]\n }\n }\n ```\n\n 3. Click on **Submit Transaction** to create the liquidity pool.\n\n ![Create Pool Fields](/images/chain-interactions/token-operations/convert-assets/convert-assets-03.webp)\n\nSigning and submitting the transaction triggers the creation of the liquidity pool. To verify the new pool's creation, check the **Explorer** section on the Polkadot.js Apps interface and ensure that the **`PoolCreated`** event was emitted.\n\n![Pool Created Event](/images/chain-interactions/token-operations/convert-assets/convert-assets-04.webp)\n\nAs the preceding image shows, the **`lpToken`** ID created for this pool is 19. This ID is essential to identify the liquidity pool and associated LP tokens."} -{"page_id": "chain-interactions-token-operations-convert-assets", "page_title": "Convert Assets on Asset Hub", "index": 3, "depth": 2, "title": "Add Liquidity to a Pool", "anchor": "add-liquidity-to-a-pool", "start_char": 4337, "end_char": 7492, "estimated_token_count": 690, "token_estimator": "heuristic-v1", "text": "## Add Liquidity to a Pool\n\nThe `addLiquidity` extrinsic allows users to provide liquidity to a pool of two assets. Users specify their preferred amounts for both assets and minimum acceptable quantities. The function determines the best asset contribution, which may vary from the amounts desired but won't fall below the specified minimums. Providers receive liquidity tokens representing their pool portion in return for their contribution.\n\nTo add liquidity to a pool, follow these steps:\n\n1. Navigate to the **Extrinsics** section on the Polkadot.js Apps interface:\n\n 1. Select **Developer** from the top menu.\n 2. Click on **Extrinsics** from the dropdown menu.\n\n ![Extrinsics Section](/images/chain-interactions/token-operations/convert-assets/convert-assets-01.webp)\n\n2. Select extrinsic to add liqudity:\n\n 1. Select the **`assetConversion`** pallet.\n 2. Choose the **`addLiquidity`** extrinsic from the list of available extrinsics.\n\n ![Add Liquidity Extrinsic](/images/chain-interactions/token-operations/convert-assets/convert-assets-05.webp)\n\n3. Fill in the required fields:\n\n 1. **`asset1`**: The Multilocation of the first asset in the pool. In this case, it is the DOT token, which the following Multilocation represents.\n\n ```javascript\n {\n parents: 0,\n interior: 'Here'\n }\n ```\n\n 2. **`asset2`**: The second asset's Multilocation within the pool. This refers to the PPM token, which the following Multilocation identifies.\n\n ```javascript\n {\n parents: 0,\n interior: {\n X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }]\n }\n }\n ```\n\n 3. **`amount1Desired`**: The amount of the first asset that will be contributed to the pool.\n 4. **`amount2Desired`**: The quantity of the second asset intended for pool contribution.\n 5. **`amount1Min`**: The minimum amount of the first asset that will be contributed.\n 6. **`amount2Min`**: The lowest acceptable quantity of the second asset for contribution.\n 7. **`mintTo`**: The account to which the liquidity tokens will be minted.\n 8. Click on **Submit Transaction** to add liquidity to the pool.\n\n ![Add Liquidity Fields](/images/chain-interactions/token-operations/convert-assets/convert-assets-06.webp)\n\n !!! warning\n Ensure that the appropriate amount of tokens provided has been minted previously and is available in your account before adding liquidity to the pool.\n\n In this case, the liquidity provided to the pool is between DOT tokens and PPM tokens with the asset ID 1112 on Polkadot Asset Hub. The intention is to provide liquidity for 1 DOT token (`u128` value of 1000000000000 as it has 10 decimals) and 1 PPM token (`u128` value of 1000000000000 as it also has 10 decimals).\n\nSigning and submitting the transaction adds liquidity to the pool. To verify the liquidity addition, check the **Explorer** section on the Polkadot.js Apps interface and ensure that the **`LiquidityAdded`** event was emitted.\n\n![Liquidity Added Event](/images/chain-interactions/token-operations/convert-assets/convert-assets-07.webp)"} -{"page_id": "chain-interactions-token-operations-convert-assets", "page_title": "Convert Assets on Asset Hub", "index": 4, "depth": 2, "title": "Swap Assets", "anchor": "swap-assets", "start_char": 7492, "end_char": 7508, "estimated_token_count": 4, "token_estimator": "heuristic-v1", "text": "## Swap Assets"} -{"page_id": "chain-interactions-token-operations-convert-assets", "page_title": "Convert Assets on Asset Hub", "index": 5, "depth": 3, "title": "Swap from an Exact Amount of Tokens", "anchor": "swap-from-an-exact-amount-of-tokens", "start_char": 7508, "end_char": 10879, "estimated_token_count": 722, "token_estimator": "heuristic-v1", "text": "### Swap from an Exact Amount of Tokens\n\nThe asset conversion pallet enables users to exchange a specific quantity of one asset for another in a designated liquidity pool by swapping them for an exact amount of tokens. It guarantees the user will receive at least a predetermined minimum amount of the second asset. This function increases trading predictability and allows users to conduct asset exchanges with confidence that they are assured a minimum return.\n\nTo swap assets for an exact amount of tokens, follow these steps:\n\n1. Navigate to the **Extrinsics** section on the Polkadot.js Apps interface:\n\n 1. Select **Developer** from the top menu.\n 2. Click on **Extrinsics** from the dropdown menu.\n\n ![Extrinsics Section](/images/chain-interactions/token-operations/convert-assets/convert-assets-01.webp)\n\n2. Select extrinsic to swap assets:\n\n 1. Select the **`AssetConversion`** pallet.\n 2. Choose the **`swapExactTokensForTokens`** extrinsic from the list of available extrinsics.\n\n ![Swap From Exact Tokens Extrinsic](/images/chain-interactions/token-operations/convert-assets/convert-assets-08.webp)\n\n3. Fill in the required fields:\n\n 1. **`path: Vec`**: An array of Multilocations representing the path of the swap. The first and last elements of the array are the input and output assets, respectively. In this case, the path consists of two elements:\n\n - **`0: StagingXcmV3MultiLocation`**: The Multilocation of the first asset in the pool. In this case, it is the DOT token, which the following Multilocation represents.\n\n ```javascript\n {\n parents: 0,\n interior: 'Here'\n }\n ```\n\n - **`1: StagingXcmV3MultiLocation`**: The second asset's Multilocation within the pool. This refers to the PPM token, which the following Multilocation identifies.\n\n ```javascript\n {\n parents: 0,\n interior: {\n X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }]\n }\n }\n ```\n\n 2. **`amountOut`**: The exact amount of the second asset that the user wants to receive.\n 3. **`amountInMax`**: The maximum amount of the first asset that the user is willing to swap.\n 4. **`sendTo`**: The account to which the swapped assets will be sent.\n 5. **`keepAlive`**: A boolean value that determines whether the pool should be kept alive after the swap.\n 6. Click on **Submit Transaction** to swap assets for an exact amount of tokens.\n\n ![Swap For Exact Tokens Fields](/images/chain-interactions/token-operations/convert-assets/convert-assets-09.webp)\n\n !!! warning\n Ensure that the appropriate amount of tokens provided has been minted previously and is available in your account before adding liquidity to the pool.\n\n In this case, the intention is to swap 0.01 DOT token (u128 value of 100000000000 as it has 10 decimals) for 0.04 PPM token (u128 value of 400000000000 as it also has 10 decimals).\n\nSigning and submitting the transaction will execute the swap. To verify execution, check the **Explorer** section on the Polkadot.js Apps interface and make sure that the **`SwapExecuted`** event was emitted.\n\n![Swap From Exact Tokens Event](/images/chain-interactions/token-operations/convert-assets/convert-assets-10.webp)"} -{"page_id": "chain-interactions-token-operations-convert-assets", "page_title": "Convert Assets on Asset Hub", "index": 6, "depth": 3, "title": "Swap to an Exact Amount of Tokens", "anchor": "swap-to-an-exact-amount-of-tokens", "start_char": 10879, "end_char": 14189, "estimated_token_count": 721, "token_estimator": "heuristic-v1", "text": "### Swap to an Exact Amount of Tokens\n\nConversely, the Asset Conversion pallet comes with a function that allows users to trade a variable amount of one asset to acquire a precise quantity of another. It ensures that users stay within a set maximum of the initial asset to obtain the desired amount of the second asset. This provides a method to control transaction costs while achieving the intended result.\n\nTo swap assets for an exact amount of tokens, follow these steps:\n\n1. Navigate to the **Extrinsics** section on the Polkadot.js Apps interface:\n\n 1. Select **Developer** from the top menu.\n 2. Click on **Extrinsics** from the dropdown menu.\n\n ![Extrinsics Section](/images/chain-interactions/token-operations/convert-assets/convert-assets-01.webp)\n\n2. Select extrinsic to swap tokens:\n\n 1. Select the **`AssetConversion`** pallet.\n 2. Choose the **`swapTokensForExactTokens`** extrinsic from the list of available extrinsics.\n\n ![Swap Tokens For Exact Tokens Extrinsic](/images/chain-interactions/token-operations/convert-assets/convert-assets-11.webp)\n\n3. Fill in the required fields:\n\n 1. **`path: Vec`**: An array of Multilocations representing the path of the swap. The first and last elements of the array are the input and output assets, respectively. In this case, the path consists of two elements:\n - **`0: StagingXcmV3MultiLocation`**: The Multilocation of the first asset in the pool. In this case, it is the PPM token, which the following Multilocation represents.\n\n ```javascript\n {\n parents: 0,\n interior: {\n X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }]\n }\n }\n ```\n\n - **`1: StagingXcmV3MultiLocation`**: The second asset's Multilocation within the pool. This refers to the DOT token, which the following Multilocation identifies.\n\n ```javascript\n {\n parents: 0,\n interior: 'Here'\n }\n ```\n\n 2. **`amountOut`**: The exact amount of the second asset that the user wants to receive.\n 3. **`amountInMax`**: The maximum amount of the first asset that the user is willing to swap.\n 4. **`sendTo`**: The account to which the swapped assets will be sent.\n 5. **`keepAlive`**: A boolean value that determines whether the pool should be kept alive after the swap.\n 6. Click on **Submit Transaction** to swap assets for an exact amount of tokens.\n\n ![Swap Tokens For Exact Tokens Fields](/images/chain-interactions/token-operations/convert-assets/convert-assets-12.webp)\n\n !!! warning\n Before swapping assets, ensure that the tokens provided have been minted previously and are available in your account.\n\n In this case, the intention is to swap 0.01 DOT token (`u128` value of 100000000000 as it has ten decimals) for 0.04 PPM token (`u128` value of 400000000000 as it also has ten decimals).\n\nSigning and submitting the transaction will execute the swap. To verify execution, check the **Explorer** section on the Polkadot.js Apps interface and make sure that the **`SwapExecuted`** event was emitted.\n\n![Swap Tokens For Exact Tokens Event](/images/chain-interactions/token-operations/convert-assets/convert-assets-13.webp)"} -{"page_id": "chain-interactions-token-operations-convert-assets", "page_title": "Convert Assets on Asset Hub", "index": 7, "depth": 2, "title": "Withdraw Liquidity from a Pool", "anchor": "withdraw-liquidity-from-a-pool", "start_char": 14189, "end_char": 17403, "estimated_token_count": 691, "token_estimator": "heuristic-v1", "text": "## Withdraw Liquidity from a Pool\n\nThe Asset Conversion pallet provides the `removeLiquidity` extrinsic to remove liquidity from a pool. This function allows users to withdraw the liquidity they offered from a pool, returning the original assets. When calling this function, users specify the number of liquidity tokens (representing their share in the pool) they wish to burn. They also set minimum acceptable amounts for the assets they expect to receive back. This mechanism ensures that users can control the minimum value they receive, protecting against unfavorable price movements during the withdrawal process.\n\nTo withdraw liquidity from a pool, follow these steps:\n\n1. Navigate to the **Extrinsics** section on the Polkadot.js Apps interface:\n\n 1. Select **Developer** from the top menu.\n 2. Click on **Extrinsics** from the dropdown menu.\n\n ![Extrinsics Section](/images/chain-interactions/token-operations/convert-assets/convert-assets-01.webp)\n\n2. Select extrinsic to withdraw liqudity from a pool:\n\n 1. Select the **`AssetConversion`** pallet.\n 2. Choose the **`removeLiquidity`** extrinsic from the list of available extrinsics.\n\n ![Remove Liquidity Extrinsic](/images/chain-interactions/token-operations/convert-assets/convert-assets-14.webp)\n\n3. Fill in the required fields:\n\n 1. **`asset1`**: The Multilocation of the first asset in the pool. In this case, it is the DOT token, which the following Multilocation represents.\n\n ```javascript\n {\n parents: 0,\n interior: 'Here'\n }\n ```\n\n 2. **`asset2`**: The second asset's Multilocation within the pool. This refers to the PPM token, which the following Multilocation identifies.\n\n ```javascript\n {\n parents: 0,\n interior: {\n X2: [{ PalletInstance: 50 }, { GeneralIndex: 1112 }]\n }\n }\n ```\n\n 3. **`lpTokenBurn`**: The number of liquidity tokens to burn.\n 4. **`amount1MinReceived`**: The minimum amount of the first asset that the user expects to receive.\n 5. **`amount2MinReceived`**: The minimum quantity of the second asset the user expects to receive.\n 6. **`withdrawTo`**: The account to which the withdrawn assets will be sent.\n 7. Click on **Submit Transaction** to withdraw liquidity from the pool.\n\n ![Remove Liquidity Fields](/images/chain-interactions/token-operations/convert-assets/convert-assets-15.webp)\n\n !!! warning\n Ensure that the tokens provided have been minted previously and are available in your account before withdrawing liquidity from the pool.\n\n In this case, the intention is to withdraw 0.05 liquidity tokens from the pool, expecting to receive 0.004 DOT token (`u128` value of 40000000000 as it has 10 decimals) and 0.04 PPM token (`u128` value of 400000000000 as it also has 10 decimals).\n\nSigning and submitting the transaction will initiate the withdrawal of liquidity from the pool. To verify the withdrawal, check the **Explorer** section on the Polkadot.js Apps interface and ensure that the **`LiquidityRemoved`** event was emitted.\n\n![Remove Liquidity Event](/images/chain-interactions/token-operations/convert-assets/convert-assets-16.webp)"} -{"page_id": "chain-interactions-token-operations-convert-assets", "page_title": "Convert Assets on Asset Hub", "index": 8, "depth": 2, "title": "Test Environment Setup", "anchor": "test-environment-setup", "start_char": 17403, "end_char": 18507, "estimated_token_count": 242, "token_estimator": "heuristic-v1", "text": "## Test Environment Setup\n\nTo test the Asset Conversion pallet, you can set up a local test environment to simulate different scenarios. This guide uses Chopsticks to spin up an instance of Polkadot Asset Hub. For further details on using Chopsticks, please refer to the [Chopsticks documentation](/develop/toolkit/parachains/fork-chains/chopsticks/get-started){target=\\_blank}.\n\nTo set up a local test environment, execute the following command:\n\n```bash\nnpx @acala-network/chopsticks \\\n--config=https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/polkadot-asset-hub.yml\n```\n\nThis command initiates a lazy fork of Polkadot Asset Hub, including the most recent block information from the network. For Kusama Asset Hub testing, simply switch out `polkadot-asset-hub.yml` with `kusama-asset-hub.yml` in the command.\n\nYou now have a local Asset Hub instance up and running, ready for you to test various asset conversion procedures. The process here mirrors what you'd do on MainNet. After completing a transaction on TestNet, you can apply the same steps to convert assets on MainNet."} -{"page_id": "chain-interactions-token-operations-register-foreign-asset", "page_title": "Register a Foreign Asset on Asset Hub", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 41, "end_char": 1111, "estimated_token_count": 234, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nAs outlined in the [Asset Hub Overview](/polkadot-protocol/architecture/system-chains/asset-hub){target=\\_blank}, Asset Hub supports two categories of assets: local and foreign. Local assets are created on the Asset Hub system parachain and are identified by integer IDs. On the other hand, foreign assets, which originate outside of Asset Hub, are recognized by [Multilocations](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#7-universal-consensus-location-identifiers){target=\\_blank}.\n\nWhen registering a foreign asset on Asset Hub, it's essential to notice that the process involves communication between two parachains. The Asset Hub parachain will be the destination of the foreign asset, while the source parachain will be the origin of the asset. The communication between the two parachains is facilitated by the [Cross-Chain Message Passing (XCMP)](/parachains/interoperability/get-started/){target=\\_blank} protocol.\n\nThis guide will take you through the process of registering a foreign asset on the Asset Hub parachain."} -{"page_id": "chain-interactions-token-operations-register-foreign-asset", "page_title": "Register a Foreign Asset on Asset Hub", "index": 1, "depth": 2, "title": "Prerequisites", "anchor": "prerequisites", "start_char": 1111, "end_char": 2805, "estimated_token_count": 472, "token_estimator": "heuristic-v1", "text": "## Prerequisites\n\nThe Asset Hub parachain is one of the system parachains on a relay chain, such as [Polkadot](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fpolkadot.api.onfinality.io%2Fpublic-ws#/explorer){target=\\_blank} or [Kusama](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fkusama.api.onfinality.io%2Fpublic-ws#/explorer){target=\\_blank}. To interact with these parachains, you can use the [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\\_blank} interface for:\n\n- [Polkadot Asset Hub](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fasset-hub-polkadot-rpc.dwellir.com#/explorer){target=\\_blank}\n- [Kusama Asset Hub](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fsys.ibp.network%2Fstatemine#/explorer){target=\\_blank}\n\nFor testing purposes, you can also interact with the Asset Hub instance on the following test networks:\n\n- [Paseo Asset Hub](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fpas-rpc.stakeworld.io%2Fassethub#/explorer){target=\\_blank}\n\nBefore you start, ensure that you have: \n\n- Access to the Polkadot.js Apps interface, and you are connected to the desired chain.\n- A parachain that supports the XCMP protocol to interact with the Asset Hub parachain.\n- A funded wallet to pay for the transaction fees and subsequent registration of the foreign asset.\n\nThis guide will use Polkadot, its local Asset Hub instance, and the [Astar](https://astar.network/){target=\\_blank} parachain (`ID` 2006), as stated in the [Test Environment Setup](#test-environment-setup) section. However, the process is the same for other relay chains and their respective Asset Hub parachain, regardless of the network you are using and the parachain owner of the foreign asset."} -{"page_id": "chain-interactions-token-operations-register-foreign-asset", "page_title": "Register a Foreign Asset on Asset Hub", "index": 2, "depth": 2, "title": "Steps to Register a Foreign Asset", "anchor": "steps-to-register-a-foreign-asset", "start_char": 2805, "end_char": 2843, "estimated_token_count": 8, "token_estimator": "heuristic-v1", "text": "## Steps to Register a Foreign Asset"} -{"page_id": "chain-interactions-token-operations-register-foreign-asset", "page_title": "Register a Foreign Asset on Asset Hub", "index": 3, "depth": 3, "title": "Asset Hub", "anchor": "asset-hub", "start_char": 2843, "end_char": 5911, "estimated_token_count": 701, "token_estimator": "heuristic-v1", "text": "### Asset Hub\n\n1. Open the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\\_blank} interface and connect to the Asset Hub parachain using the network selector in the top left corner.\n\n - Testing foreign asset registration is recommended on TestNet before proceeding to MainNet. If you haven't set up a local testing environment yet, consult the [Environment setup](#test-environment-setup) guide. After setting up, connect to the Local Node (Chopsticks) at `ws://127.0.0.1:8000`.\n - For live network operations, connect to the Asset Hub parachain. You can choose either Polkadot or Kusama Asset Hub from the dropdown menu, selecting your preferred RPC provider.\n\n2. Navigate to the **Extrinsics** page:\n\n 1. Click on the **Developer** tab from the top navigation bar.\n 2. Select **Extrinsics** from the dropdown.\n\n ![Access to Developer Extrinsics section](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-01.webp)\n\n3. Select the Foreign Assets pallet:\n\n 3. Select the **`foreignAssets`** pallet from the dropdown list.\n 4. Choose the **`create`** extrinsic.\n\n ![Select the Foreign Asset pallet](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-02.webp)\n\n3. Fill out the required fields and click on the copy icon to copy the **encoded call data** to your clipboard. The fields to be filled are:\n\n - **id**: As this is a foreign asset, the ID will be represented by a Multilocation that reflects its origin. For this case, the Multilocation of the asset will be from the source parachain perspective.\n \n ```javascript\n { parents: 1, interior: { X1: [{ Parachain: 2006 }] } }\n ```\n\n - **admin**: Refers to the account that will be the admin of this asset. This account will be able to manage the asset, including updating its metadata. As the registered asset corresponds to a native asset of the source parachain, the admin account should be the sovereign account of the source parachain.\n \n The sovereign account can be obtained through [Substrate Utilities](https://www.shawntabrizi.com/substrate-js-utilities/){target=\\_blank}.\n\n Ensure that **Sibling** is selected and that the **Para ID** corresponds to the source parachain. In this case, since the guide follows the test setup stated in the [Test Environment Setup](#test-environment-setup) section, the **Para ID** is `2006`.\n\n ![Get parachain sovereign account](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-03.webp)\n\n\n - **`minBalance`**: The minimum balance required to hold this asset.\n\n ![Fill out the required fields](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-04.webp)\n\n !!! tip \n If you need an example of the encoded call data, you can copy the following:\n ```\n 0x3500010100591f007369626cd6070000000000000000000000000000000000000000000000000000a0860100000000000000000000000000\n ```"} -{"page_id": "chain-interactions-token-operations-register-foreign-asset", "page_title": "Register a Foreign Asset on Asset Hub", "index": 4, "depth": 3, "title": "Source Parachain", "anchor": "source-parachain", "start_char": 5911, "end_char": 7553, "estimated_token_count": 297, "token_estimator": "heuristic-v1", "text": "### Source Parachain\n\n1. Navigate to the **Developer > Extrinsics** section.\n2. Create the extrinsic to register the foreign asset through XCM:\n\n 1. Paste the **encoded call data** copied in the previous step.\n 2. Click the **Submit Transaction** button.\n\n ![Register foreign asset through XCM](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-05.webp)\n\n This XCM call involves withdrawing DOT from the sibling account of the parachain, using it to initiate an execution. The transaction will be carried out with XCM as the origin kind, and will be a hex-encoded call to create a foreign asset on Asset Hub for the specified parachain asset multilocation. Any surplus will be refunded, and the asset will be deposited into the sibling account.\n\n !!! warning\n Note that the sovereign account on the Asset Hub parachain must have a sufficient balance to cover the XCM `BuyExecution` instruction. If the account does not have enough balance, the transaction will fail.\n\n If you want to have the whole XCM call ready to be copied, go to the **Developer > Extrinsics > Decode** section and paste the following hex-encoded call data:\n\n ```text\n 0x6300330003010100a10f030c000400010000070010a5d4e81300010000070010a5d4e80006030700b4f13501419ce03500010100591f007369626cd607000000000000000000000000000000000000000000000000000000000000000000000000000000000000\n ```\n\n Be sure to replace the encoded call data with the one you copied in the previous step.\n\nAfter the transaction is successfully executed, the foreign asset will be registered on the Asset Hub parachain."} -{"page_id": "chain-interactions-token-operations-register-foreign-asset", "page_title": "Register a Foreign Asset on Asset Hub", "index": 5, "depth": 2, "title": "Asset Registration Verification", "anchor": "asset-registration-verification", "start_char": 7553, "end_char": 8100, "estimated_token_count": 115, "token_estimator": "heuristic-v1", "text": "## Asset Registration Verification\n\nTo confirm that a foreign asset has been successfully accepted and registered on the Asset Hub parachain, you can navigate to the `Network > Explorer` section of the Polkadot.js Apps interface for Asset Hub. You should be able to see an event that includes the following details:\n\n![Asset registration event](/images/chain-interactions/token-operations/register-foreign-asset/register-a-foreign-asset-06.webp)\n\nIn the image above, the **success** field indicates whether the asset registration was successful."} -{"page_id": "chain-interactions-token-operations-register-foreign-asset", "page_title": "Register a Foreign Asset on Asset Hub", "index": 6, "depth": 2, "title": "Test Environment Setup", "anchor": "test-environment-setup", "start_char": 8100, "end_char": 9757, "estimated_token_count": 398, "token_estimator": "heuristic-v1", "text": "## Test Environment Setup\n\nTo test the foreign asset registration process before deploying it on a live network, you can set up a local parachain environment. This guide uses Chopsticks to simulate that process. For more information on using Chopsticks, please refer to the [Chopsticks documentation](/develop/toolkit/parachains/fork-chains/chopsticks/get-started){target=\\_blank}.\n\nTo set up a test environment, run the following command:\n\n```bash\nnpx @acala-network/chopsticks xcm \\\n--r polkadot \\\n--p polkadot-asset-hub \\\n--p astar\n```\n\nThe preceding command will create a lazy fork of Polkadot as the relay chain, its Asset Hub instance, and the Astar parachain. The `xcm` parameter enables communication through the XCMP protocol between the relay chain and the parachains, allowing the registration of foreign assets on Asset Hub. For further information on the chopsticks usage of the XCMP protocol, refer to the [XCM Testing](/tutorials/polkadot-sdk/testing/fork-live-chains/#xcm-testing){target=\\_blank} section of the Chopsticks documentation.\n\nAfter executing the command, the terminal will display output indicating the Polkadot relay chain, the Polkadot Asset Hub, and the Astar parachain are running locally and connected through XCM. You can access them individually via the Polkadot.js Apps interface.\n\n- [Polkadot Relay Chain](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Flocalhost%3A8002#/explorer){target=\\_blank}\n- [Polkadot Asset Hub](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Flocalhost%3A8000#/explorer){target=\\_blank}\n- [Astar Parachain](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Flocalhost%3A8001#/explorer){target=\\_blank}"} -{"page_id": "chain-interactions-token-operations-register-local-asset", "page_title": "Register a Local Asset", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 39, "end_char": 541, "estimated_token_count": 104, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nAs detailed in the [Asset Hub Overview](/polkadot-protocol/architecture/system-chains/asset-hub){target=\\_blank} page, Asset Hub accommodates two types of assets: local and foreign. Local assets are those that were created in Asset Hub and are identifiable by an integer ID. On the other hand, foreign assets originate from a sibling parachain and are identified by a Multilocation.\n\nThis guide will take you through the steps of registering a local asset on the Asset Hub parachain."} -{"page_id": "chain-interactions-token-operations-register-local-asset", "page_title": "Register a Local Asset", "index": 1, "depth": 2, "title": "Prerequisites", "anchor": "prerequisites", "start_char": 541, "end_char": 1097, "estimated_token_count": 130, "token_estimator": "heuristic-v1", "text": "## Prerequisites\n\nBefore you begin, ensure you have access to the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\\_blank} interface and a funded wallet with DOT or KSM.\n\n- For Polkadot Asset Hub, you would need a deposit of 10 DOT and around 0.201 DOT for the metadata.\n- For Kusama Asset Hub, the deposit is 0.1 KSM and around 0.000669 KSM for the metadata.\n\nYou need to ensure that your Asset Hub account balance is a bit more than the sum of those two deposits, which should seamlessly account for the required deposits and transaction fees."} -{"page_id": "chain-interactions-token-operations-register-local-asset", "page_title": "Register a Local Asset", "index": 2, "depth": 2, "title": "Steps to Register a Local Asset", "anchor": "steps-to-register-a-local-asset", "start_char": 1097, "end_char": 4321, "estimated_token_count": 802, "token_estimator": "heuristic-v1", "text": "## Steps to Register a Local Asset\n\nTo register a local asset on the Asset Hub parachain, follow these steps:\n\n1. Open the [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\\_blank} interface and connect to the Asset Hub parachain using the network selector in the top left corner.\n\n - You may prefer to test local asset registration on TestNet before registering the asset on a MainNet hub. If you still need to set up a local testing environment, review the [Environment setup](#test-setup-environment) section for instructions. Once the local environment is set up, connect to the Local Node (Chopsticks) available on `ws://127.0.0.1:8000`.\n - For the live network, connect to the **Asset Hub** parachain. Either Polkadot or Kusama Asset Hub can be selected from the dropdown list, choosing the desired RPC provider.\n\n2. Click on the **Network** tab on the top navigation bar and select **Assets** from the dropdown list.\n\n ![Access to Asset Hub through Polkadot.JS](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-01.webp)\n\n3. Now, you need to examine all the registered asset IDs. This step is crucial to ensure that the asset ID you are about to register is unique. Asset IDs are displayed in the **assets** column.\n\n ![Asset IDs on Asset Hub](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-02.webp)\n\n4. Once you have confirmed that the asset ID is unique, click on the **Create** button on the top right corner of the page.\n\n ![Create a new asset](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-03.webp)\n\n5. Fill in the required fields in the **Create Asset** form:\n\n 1. **creator account**: The account to be used for creating this asset and setting up the initial metadata.\n 2. **asset name**: The descriptive name of the asset you are registering.\n 3. **asset symbol**: The symbol that will be used to represent the asset.\n 4. **asset decimals**: The number of decimal places for this token, with a maximum of 20 allowed through the user interface.\n 5. **minimum balance**: The minimum balance for the asset. This is specified in the units and decimals as requested.\n 6. **asset ID**: The selected id for the asset. This should not match an already-existing asset id.\n 7. Click on the **Next** button.\n \n ![Create Asset Form](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-04.webp)\n\n6. Choose the accounts for the roles listed below:\n\n 1. **admin account**: The account designated for continuous administration of the token.\n 2. **issuer account**: The account that will be used for issuing this token.\n 3. **freezer account**: The account that will be used for performing token freezing operations.\n 4. Click on the **Create** button.\n\n ![Admin, Issuer, Freezer accounts](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-05.webp)\n\n7. Click on the **Sign and Submit** button to complete the asset registration process.\n\n ![Sign and Submit](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-06.webp)"} -{"page_id": "chain-interactions-token-operations-register-local-asset", "page_title": "Register a Local Asset", "index": 3, "depth": 2, "title": "Verify Asset Registration", "anchor": "verify-asset-registration", "start_char": 4321, "end_char": 5247, "estimated_token_count": 247, "token_estimator": "heuristic-v1", "text": "## Verify Asset Registration\n\nAfter completing these steps, the asset will be successfully registered. You can now view your asset listed on the [**Assets**](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fasset-hub-polkadot-rpc.dwellir.com#/assets){target=\\_blank} section of the Polkadot.js Apps interface.\n\n![Asset listed on Polkadot.js Apps](/images/chain-interactions/token-operations/register-local-asset/register-a-local-asset-07.webp)\n\n!!! tip\n Take into consideration that the **Assets** section’s link may differ depending on the network you are using. For the local environment, enter `ws://127.0.0.1:8000` into the **Custom Endpoint** field.\n\nIn this way, you have successfully registered a local asset on the Asset Hub parachain.\n\nFor an in-depth explanation about Asset Hub and its features, see the [Asset Hub](/chain-interactions/token-operations/convert-assets/){target=\\_blank} entry in the Polkadot Wiki."} -{"page_id": "chain-interactions-token-operations-register-local-asset", "page_title": "Register a Local Asset", "index": 4, "depth": 2, "title": "Test Setup Environment", "anchor": "test-setup-environment", "start_char": 5247, "end_char": 6355, "estimated_token_count": 240, "token_estimator": "heuristic-v1", "text": "## Test Setup Environment\n\nYou can set up a local parachain environment to test the asset registration process before deploying it on the live network. This guide uses Chopsticks to simulate that process. For further information on chopsticks usage, refer to the [Chopsticks](/develop/toolkit/parachains/fork-chains/chopsticks/get-started){target=\\_blank} documentation.\n\nTo set up a test environment, execute the following command:\n\n```bash\nnpx @acala-network/chopsticks \\\n--config=https://raw.githubusercontent.com/AcalaNetwork/chopsticks/master/configs/polkadot-asset-hub.yml\n```\n\nThe above command will spawn a lazy fork of Polkadot Asset Hub with the latest block data from the network. If you need to test Kusama Asset Hub, replace `polkadot-asset-hub.yml` with `kusama-asset-hub.yml` in the command.\n\nAn Asset Hub instance is now running locally, and you can proceed with the asset registration process. Note that the local registration process does not differ from the live network process. Once you have a successful TestNet transaction, you can use the same steps to register the asset on MainNet."} -{"page_id": "chain-interactions", "page_title": "Chain Interactions Overview", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 22, "end_char": 995, "estimated_token_count": 166, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nChain interactions form the foundation of building applications on Polkadot. Whether you're querying on-chain data, executing transactions, enabling cross-chain communication, or managing accounts, understanding how to interact with Polkadot-based chains is essential for application developers.\n\nThis section provides comprehensive guidance on the various ways to interact with Polkadot chains, from basic queries to complex cross-chain operations. You'll learn how to:\n\n- Query on-chain state and subscribe to blockchain events.\n- Send transactions and manage their lifecycle.\n- Enable interoperability between parachains through XCM.\n- Manage tokens and perform token operations.\n- Create and manage accounts programmatically.\n\nWhether you're building a frontend application, a backend service, or integrating with the Polkadot ecosystem, these guides will equip you with the knowledge and tools to effectively interact with chains across the network."} -{"page_id": "chain-interactions", "page_title": "Chain Interactions Overview", "index": 1, "depth": 2, "title": "Core Interaction Patterns", "anchor": "core-interaction-patterns", "start_char": 995, "end_char": 1025, "estimated_token_count": 5, "token_estimator": "heuristic-v1", "text": "## Core Interaction Patterns"} -{"page_id": "chain-interactions", "page_title": "Chain Interactions Overview", "index": 2, "depth": 3, "title": "Query On-Chain Data", "anchor": "query-on-chain-data", "start_char": 1025, "end_char": 1898, "estimated_token_count": 223, "token_estimator": "heuristic-v1", "text": "### Query On-Chain Data\n\nAccessing blockchain state is fundamental to building responsive applications. Polkadot offers several methods to query on-chain data, each suited for different use cases.\n\n- **[SDK integration](/chain-interactions/query-data/query-sdks/)**: Programmatically read blockchain state using:\n\n - [Polkadot API (PAPI)](/reference/tools/papi/)\n - [Polkadot.js](/reference/tools/polkadot-js-api/)\n - [Dedot](/reference/tools/dedot/)\n - [Python Substrate Interface](/reference/tools/py-substrate-interface/)\n - [Subxt](/reference/tools/subxt/)\n\n- **[REST API access](/chain-interactions/query-data/query-rest/)**: Query chain data through standardized REST endpoints for simpler integration.\n- **[Runtime API calls](/chain-interactions/query-data/runtime-api-calls/)**: Execute runtime APIs directly for specialized queries and operations."} -{"page_id": "chain-interactions", "page_title": "Chain Interactions Overview", "index": 3, "depth": 3, "title": "Send Transactions", "anchor": "send-transactions", "start_char": 1898, "end_char": 2608, "estimated_token_count": 150, "token_estimator": "heuristic-v1", "text": "### Send Transactions\n\nTransactions are the primary mechanism for modifying blockchain state. Understanding transaction construction, signing, and submission is crucial for building interactive applications.\n\n- **[Transaction construction](/chain-interactions/send-transactions/with-sdks/)**: Build transactions using various SDKs with proper encoding and formatting.\n- **[Fee estimation](/chain-interactions/send-transactions/calculate-transaction-fees/)**: Calculate transaction fees to ensure sufficient balance and optimize costs.\n- **[Multi-token fees](/chain-interactions/send-transactions/pay-fees-with-different-tokens/)**: Learn how to pay transaction fees with different tokens on supported chains."} -{"page_id": "chain-interactions", "page_title": "Chain Interactions Overview", "index": 4, "depth": 3, "title": "Send Cross-Chain Transactions", "anchor": "send-cross-chain-transactions", "start_char": 2608, "end_char": 3431, "estimated_token_count": 196, "token_estimator": "heuristic-v1", "text": "### Send Cross-Chain Transactions\n\nPolkadot enables native cross-chain capabilities through Cross-Consensus Messaging (XCM), allowing chains to securely communicate and transfer assets across the ecosystem.\n\n- **[Transfer assets between parachains](/chain-interactions/send-transactions/interoperability/transfer-assets-parachains/)**: Understand how to construct and send XCM messages using [ParaSpell XCM SDK](/reference/tools/paraspell/){target=\\_blank} and [Polkadot API (PAPI)](/reference/tools/papi/){target=\\_blank}.\n- **[Transfer assets out of Polkadot](/chain-interactions/send-transactions/interoperability/transfer-assets-out-of-polkadot/)**: Connect to blockchains outside the Polkadot ecosystem using [Snowbridge](https://wiki.polkadot.com/learn/learn-snowbridge/){target=\\_blank} and other bridge solutions."} -{"page_id": "chain-interactions", "page_title": "Chain Interactions Overview", "index": 5, "depth": 3, "title": "Manage Tokens", "anchor": "manage-tokens", "start_char": 3431, "end_char": 4284, "estimated_token_count": 203, "token_estimator": "heuristic-v1", "text": "### Manage Tokens\n\nPolkadot Hub provides a unified platform for managing assets across the ecosystem. Understanding token operations is essential for DeFi applications and multi-chain asset management.\n\n- **[Local asset registration](/chain-interactions/token-operations/register-local-asset/)**: Learn how assets created in Asset Hub are registered on the network.\n- **[Foregin asset registration](/chain-interactions/token-operations/register-foreign-asset/)**: Learn how assets created outside of Asset Hub are registered on the network.\n- **[Convert assets](/chain-interactions/token-operations/convert-assets/)**: Convert, swap, and manage assets on-chain using the Asset Conversion pallet.\n- **Asset Hub integration**: Interact with Polkadot's central asset management hub using [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\\_blank}."} -{"page_id": "chain-interactions", "page_title": "Chain Interactions Overview", "index": 6, "depth": 3, "title": "Manage Accounts", "anchor": "manage-accounts", "start_char": 4284, "end_char": 4756, "estimated_token_count": 101, "token_estimator": "heuristic-v1", "text": "### Manage Accounts\n\nAccount management forms the basis of user identity and authentication in blockchain applications. Learn how to create, manage, and query accounts programmatically.\n\n- **[Account creation](/chain-interactions/accounts/create-account/)**: Generate accounts using various SDKs in Rust, Python, and JavaScript.\n- **[Account queries](/chain-interactions/accounts/query-accounts/)**: Retrieve account information including balances, nonces, and metadata."} -{"page_id": "chain-interactions", "page_title": "Chain Interactions Overview", "index": 7, "depth": 2, "title": "Development Tools and SDKs", "anchor": "development-tools-and-sdks", "start_char": 4756, "end_char": 5737, "estimated_token_count": 235, "token_estimator": "heuristic-v1", "text": "## Development Tools and SDKs\n\nThe Polkadot ecosystem offers a rich set of tools and libraries to facilitate chain interactions:\n\n- **[Polkadot API (PAPI)](/reference/tools/papi/)**: Modern, type-safe TypeScript library with full metadata support.\n- **[Polkadot.js](/reference/tools/polkadot-js-api/)**: Comprehensive JavaScript library with extensive ecosystem support.\n- **[Dedot](/reference/tools/dedot/)**: Lightweight TypeScript library optimized for performance.\n- **[Python Substrate Interface](/reference/tools/py-substrate-interface/)**: Polkadot Substrate Interface for streamlined development.\n- **[Subxt](/reference/tools/subxt/)**: Rust library for building robust substrate-based applications.\n- **[Polkadot.js Apps](https://polkadot.js.org/apps/)**: Web-based interface for exploring and interacting with chains.\n\nEach tool has its strengths, and choosing the right one depends on your project requirements, programming language preference, and specific use cases."} -{"page_id": "chain-interactions", "page_title": "Chain Interactions Overview", "index": 8, "depth": 2, "title": "Next Steps", "anchor": "next-steps", "start_char": 5737, "end_char": 6632, "estimated_token_count": 209, "token_estimator": "heuristic-v1", "text": "## Next Steps\n\nExplore the sections below to dive deeper into specific chain interaction patterns:\n\n- **[Query On-Chain Data](/chain-interactions/query-data/query-sdks/)**: Learn to read blockchain state efficiently.\n- **[Send Transactions](/chain-interactions/send-transactions/with-sdks/)**: Master transaction construction and submission.\n- **[Send Cross-Chain Transactions](/chain-interactions/send-transactions/interoperability/transfer-assets-parachains/)**: Enable cross-chain communication with XCM.\n- **[Manage Tokens](/chain-interactions/token-operations/register-local-asset/)**: Manage assets across the Polkadot ecosystem.\n- **[Manage Accounts](/chain-interactions/accounts/create-account/)**: Create and query accounts programmatically.\n\nEach section provides practical examples, code snippets, and comprehensive guides to help you build production-ready applications on Polkadot."} {"page_id": "get-support-ai-ready-docs", "page_title": "AI Ready Docs", "index": 0, "depth": 2, "title": "How to Use These Files", "anchor": "how-to-use-these-files", "start_char": 286, "end_char": 952, "estimated_token_count": 164, "token_estimator": "heuristic-v1", "text": "## How to Use These Files\n\n- **Quick navigation**: Use `llms.txt` to give models a high-level map of the site.\n- **Lightweight context**: Use `site-index.json` for smaller context windows or when you only need targeted retrieval.\n- **Full content**: Use `llms-full.jsonl` for large-context models or preparing data for RAG pipelines.\n- **Focused bundles**: Use category files (e.g., `basics.md`, `parachains.md`) to limit content to a specific theme or task for more focused responses.\n\nThese AI-ready files do not include any persona or system prompts. They are purely informational and can be used without conflicting with your existing agent or tool prompting."} {"page_id": "get-support-ai-ready-docs", "page_title": "AI Ready Docs", "index": 1, "depth": 2, "title": "Download LLM Files", "anchor": "download-llm-files", "start_char": 952, "end_char": 7998, "estimated_token_count": 2068, "token_estimator": "heuristic-v1", "text": "## Download LLM Files\n\n| Category | Description | File | Actions |\n|----------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| Index | Markdown URL index for documentation pages, links to essential repos, and additional resources in the llms.txt standard format. | llms.txt |
[:octicons-copy-16:](){ .llms-copy data-path=\"/llms.txt\" } [:octicons-download-16:](){ .llms-dl data-path=\"/llms.txt\" data-filename=\"llms.txt\" }
|\n| Site index (JSON) | Lightweight site index of JSON objects (one per page) with metadata and content previews. | site-index.json |
[:octicons-copy-16:](){ .llms-copy data-path=\"/ai/site-index.json\" } [:octicons-download-16:](){ .llms-dl data-path=\"/ai/site-index.json\" data-filename=\"site-index.json\" }
|\n| Full site contents (JSONL) | Full content of documentation site enhanced with metadata. | llms-full.jsonl |
[:octicons-copy-16:](){ .llms-copy data-path=\"/llms-full.jsonl\" } [:octicons-download-16:](){ .llms-dl data-path=\"/llms-full.jsonl\" data-filename=\"llms-full.jsonl\" }
|\n| Basics | Polkadot general knowledge base to provide context around overview and beginner-level content. | basics.md |
[:octicons-copy-16:](){ .llms-copy data-path=\"/ai/categories/basics.md\" } [:octicons-download-16:](){ .llms-dl data-path=\"/ai/categories/basics.md\" data-filename=\"basics.md\" }
|\n| Reference | Reference material including key functions and glossary. | reference.md |
[:octicons-copy-16:](){ .llms-copy data-path=\"/ai/categories/reference.md\" } [:octicons-download-16:](){ .llms-dl data-path=\"/ai/categories/reference.md\" data-filename=\"reference.md\" }
|\n| Smart Contracts | How to develop and deploy Solidity smart contracts on Polkadot Hub. | smart-contracts.md |
[:octicons-copy-16:](){ .llms-copy data-path=\"/ai/categories/smart-contracts.md\" } [:octicons-download-16:](){ .llms-dl data-path=\"/ai/categories/smart-contracts.md\" data-filename=\"smart-contracts.md\" }
|\n| Parachains | How-to guides related to building, customizing, deploying, and maintaining a parachain. | parachains.md |
[:octicons-copy-16:](){ .llms-copy data-path=\"/ai/categories/parachains.md\" } [:octicons-download-16:](){ .llms-dl data-path=\"/ai/categories/parachains.md\" data-filename=\"parachains.md\" }
|\n| DApps | Information and tutorials for application developers. | dapps.md |
[:octicons-copy-16:](){ .llms-copy data-path=\"/ai/categories/dapps.md\" } [:octicons-download-16:](){ .llms-dl data-path=\"/ai/categories/dapps.md\" data-filename=\"dapps.md\" }
|\n| Networks | Information about the various Polkadot networks (Polkadot, Kusama, Westend, Paseo), their purposes, and how they fit into the development workflow. | networks.md |
[:octicons-copy-16:](){ .llms-copy data-path=\"/ai/categories/networks.md\" } [:octicons-download-16:](){ .llms-dl data-path=\"/ai/categories/networks.md\" data-filename=\"networks.md\" }
|\n| Polkadot Protocol | Polkadot's core architecture, including the relay chain, parachains, system chains, interoperability, and main actors. | polkadot-protocol.md |
[:octicons-copy-16:](){ .llms-copy data-path=\"/ai/categories/polkadot-protocol.md\" } [:octicons-download-16:](){ .llms-dl data-path=\"/ai/categories/polkadot-protocol.md\" data-filename=\"polkadot-protocol.md\" }
|\n| Infrastructure | Operational aspects of supporting the Polkadot network, including how to run a node or validator and staking mechanics. | infrastructure.md |
[:octicons-copy-16:](){ .llms-copy data-path=\"/ai/categories/infrastructure.md\" } [:octicons-download-16:](){ .llms-dl data-path=\"/ai/categories/infrastructure.md\" data-filename=\"infrastructure.md\" }
|\n| Tooling | An overview of various development tools available for Polkadot development. | tooling.md |
[:octicons-copy-16:](){ .llms-copy data-path=\"/ai/categories/tooling.md\" } [:octicons-download-16:](){ .llms-dl data-path=\"/ai/categories/tooling.md\" data-filename=\"tooling.md\" }
|\n\n!!! note\n The `llms-full.jsonl` file may exceed the input limits of some language models due to its size. If you encounter limitations, consider using the smaller `site-index.json` or category bundle files instead."} {"page_id": "get-support-explore-resources", "page_title": "Subscribe to Updates", "index": 0, "depth": 2, "title": "🧠 Stack Exchange", "anchor": "stack-exchange", "start_char": 178, "end_char": 403, "estimated_token_count": 53, "token_estimator": "heuristic-v1", "text": "## 🧠 Stack Exchange\n\n- Browse commonly asked technical questions.\n- Ask your own and get detailed responses from experienced devs.\n\n👉 **[Visit Polkadot Stack Exchange](https://substrate.stackexchange.com/){target=\\_blank}**"} @@ -386,13 +306,13 @@ {"page_id": "parachains-interoperability-channels-with-system-parachains", "page_title": "Opening HRMP Channels with System Parachains", "index": 3, "depth": 3, "title": "Fund Parachain Sovereign Account", "anchor": "fund-parachain-sovereign-account", "start_char": 1338, "end_char": 2961, "estimated_token_count": 357, "token_estimator": "heuristic-v1", "text": "### Fund Parachain Sovereign Account\n\nThe [sovereign account](https://github.com/polkadot-fellows/xcm-format/blob/10726875bd3016c5e528c85ed6e82415e4b847d7/README.md?plain=1#L50){target=_blank} for parachain 2500 on the relay chain must be funded so it can take care of any XCM transact fees.\n\nUse [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\\_blank} UI to connect to the relay chain and transfer funds from your account to the parachain 2500 sovereign account.\n\n![](/images/parachains/interoperability/channels-common/channels-01.webp)\n\n??? note \"Calculating Parachain Sovereign Account\"\n To generate the sovereign account address for a parachain, you'll need to follow these steps:\n\n 1. Determine if the parachain is an \"up/down\" chain (parent or child) or a \"sibling\" chain:\n\n - Up/down chains use the prefix `0x70617261` (which decodes to `b\"para\"`).\n - Sibling chains use the prefix `0x7369626c` (which decodes to `b\"sibl\"`).\n\n 2. Calculate the u32 scale encoded value of the parachain ID:\n\n - Parachain 2500 would be encoded as `c4090000`.\n\n 3. Combine the prefix and parachain ID encoding to form the full sovereign account address:\n\n The sovereign account of parachain 2500 in relay chain will be `0x70617261c4090000000000000000000000000000000000000000000000000000`\n and the SS58 format of this address is `5Ec4AhPSY2GEE4VoHUVheqv5wwq2C1HMKa7c9fVJ1WKivX1Y`.\n \n To perform this conversion, you can also use the **\"Para ID\" to Address** section in [Substrate Utilities](https://www.shawntabrizi.com/substrate-js-utilities/){target=\\_blank}."} {"page_id": "parachains-interoperability-channels-with-system-parachains", "page_title": "Opening HRMP Channels with System Parachains", "index": 4, "depth": 3, "title": "Create Establish Channel with System Extrinsic", "anchor": "create-establish-channel-with-system-extrinsic", "start_char": 2961, "end_char": 3767, "estimated_token_count": 183, "token_estimator": "heuristic-v1", "text": "### Create Establish Channel with System Extrinsic\n\n1. In Polkadot.js Apps, connect to the relay chain, navigate to the **Developer** dropdown and select the **Extrinsics** option.\n\n ![](/images/parachains/interoperability/channels-common/channels-02.webp)\n\n2. Construct an `establish_channel_with_system` extrinsic call:\n\n 1. Select the **`hrmp`** pallet.\n 2. Choose the **`establish_channel_with_system`** extrinsic.\n 3. Fill in the parameters:\n - **`target_system_chain`**: Parachain ID of the target system chain (in this case, 1000).\n 4. Copy the encoded call data.\n ![](/images/parachains/interoperability/channels-with-system-parachains/system-parachains-01.webp)\n\n The encoded call data for establishing a channel with system parachain 1000 should be `0x3c0ae8030000`."} {"page_id": "parachains-interoperability-channels-with-system-parachains", "page_title": "Opening HRMP Channels with System Parachains", "index": 5, "depth": 3, "title": "Craft and Submit the XCM Message", "anchor": "craft-and-submit-the-xcm-message", "start_char": 3767, "end_char": 7203, "estimated_token_count": 671, "token_estimator": "heuristic-v1", "text": "### Craft and Submit the XCM Message\n\nConnect to parachain 2500 using Polkadot.js Apps to send the XCM message to the relay chain. Input the necessary parameters as illustrated in the image below. Make sure to:\n\n1. Insert your previously encoded `establish_channel_with_system` call data into the **`call`** field.\n2. Provide beneficiary details.\n3. Dispatch the XCM message to the relay chain by clicking the **Submit Transaction** button.\n\n![](/images/parachains/interoperability/channels-with-system-parachains/system-parachains-02.webp)\n\n!!! note\n The exact process and parameters for submitting this XCM message may vary depending on your specific parachain and relay chain configurations. Always refer to the most current documentation for your particular network setup.\n\nAfter successfully submitting the XCM message to the relay chain, two [`HrmpSystemChannelOpened`](https://paritytech.github.io/polkadot-sdk/master/polkadot_runtime_parachains/hrmp/pallet/enum.Event.html#variant.HrmpSystemChannelOpened){target=\\_blank} events are emitted, indicating that the channels are now present in storage under [`HrmpOpenChannelRequests`](https://paritytech.github.io/polkadot-sdk/master/polkadot_runtime_parachains/hrmp/pallet/storage_types/struct.HrmpOpenChannelRequests.html){target=\\_blank}. However, the channels are not actually set up until the start of the next session, at which point bidirectional communication between parachain 2500 and system chain 1000 is established.\n\nTo verify this, wait for the next session and then follow these steps:\n\n1. Using Polkadot.js Apps, connect to the relay chain and navigate to the **Developer** dropdown, then select **Chain state**.\n\n ![](/images/parachains/interoperability/channels-common/channels-03.webp)\n\n2. Query the HRMP channels:\n\n 1. Select **`hrmp`** from the options.\n 2. Choose the **`hrmpChannels`** call.\n 3. Click the **+** button to execute the query.\n\n ![](/images/parachains/interoperability/channels-with-system-parachains/system-parachains-03.webp)\n \n3. Examine the query results. You should see output similar to the following:\n\n ```json\n [\n [\n [\n {\n \"sender\": 1000,\n \"recipient\": 2500\n }\n ],\n {\n \"maxCapacity\": 8,\n \"maxTotalSize\": 8192,\n \"maxMessageSize\": 1048576,\n \"msgCount\": 0,\n \"totalSize\": 0,\n \"mqcHead\": null,\n \"senderDeposit\": 0,\n \"recipientDeposit\": 0\n }\n ],\n [\n [\n {\n \"sender\": 2500,\n \"recipient\": 1000\n }\n ],\n {\n \"maxCapacity\": 8,\n \"maxTotalSize\": 8192,\n \"maxMessageSize\": 1048576,\n \"msgCount\": 0,\n \"totalSize\": 0,\n \"mqcHead\": null,\n \"senderDeposit\": 0,\n \"recipientDeposit\": 0\n }\n ]\n ]\n\n ```\n\nThe output confirms the successful establishment of two HRMP channels:\n\n- From chain 1000 (system chain) to chain 2500 (parachain).\n- From chain 2500 (parachain) to chain 1000 (system chain).\n\nThis bidirectional channel enables direct communication between the system chain and the parachain, allowing for cross-chain message passing."} -{"page_id": "parachains-interoperability-get-started", "page_title": "Introduction to XCM", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 23, "end_char": 695, "estimated_token_count": 113, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nPolkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems.\n\nWith XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation."} -{"page_id": "parachains-interoperability-get-started", "page_title": "Introduction to XCM", "index": 1, "depth": 2, "title": "Messaging Format", "anchor": "messaging-format", "start_char": 695, "end_char": 1569, "estimated_token_count": 153, "token_estimator": "heuristic-v1", "text": "## Messaging Format\n\nXCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics.\n\nXCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing."} -{"page_id": "parachains-interoperability-get-started", "page_title": "Introduction to XCM", "index": 2, "depth": 2, "title": "The Four Principles of XCM", "anchor": "the-four-principles-of-xcm", "start_char": 1569, "end_char": 2505, "estimated_token_count": 174, "token_estimator": "heuristic-v1", "text": "## The Four Principles of XCM\n\nXCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems:\n\n- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes.\n- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended.\n- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin.\n- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems.\n\nThese principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments."} -{"page_id": "parachains-interoperability-get-started", "page_title": "Introduction to XCM", "index": 3, "depth": 2, "title": "The XCM Tech Stack", "anchor": "the-xcm-tech-stack", "start_char": 2505, "end_char": 2869, "estimated_token_count": 75, "token_estimator": "heuristic-v1", "text": "## The XCM Tech Stack\n\n![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp)\n\nThe XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels."} -{"page_id": "parachains-interoperability-get-started", "page_title": "Introduction to XCM", "index": 4, "depth": 2, "title": "Core Functionalities of XCM", "anchor": "core-functionalities-of-xcm", "start_char": 2869, "end_char": 3865, "estimated_token_count": 165, "token_estimator": "heuristic-v1", "text": "## Core Functionalities of XCM\n\nXCM enhances cross-consensus communication by introducing several powerful features:\n\n- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management.\n- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification.\n- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location.\n\nThe standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications."} -{"page_id": "parachains-interoperability-get-started", "page_title": "Introduction to XCM", "index": 5, "depth": 2, "title": "XCM Example", "anchor": "xcm-example", "start_char": 3865, "end_char": 6877, "estimated_token_count": 704, "token_estimator": "heuristic-v1", "text": "## XCM Example\n\nThe following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA).\n\n```rust\nlet message = Xcm(vec![\n WithdrawAsset((Here, amount).into()),\n BuyExecution { \n fees: (Here, amount).into(), \n weight_limit: WeightLimit::Unlimited \n },\n DepositAsset {\n assets: All.into(),\n beneficiary: MultiLocation {\n parents: 0,\n interior: Junction::AccountId32 {\n network: None,\n id: BOB.clone().into()\n }.into(),\n }.into()\n }\n]);\n```\n\nThe message consists of three instructions described as follows:\n\n- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register.\n\n ```rust\n WithdrawAsset((Here, amount).into()),\n ```\n\n - **`Here`**: The native parachain token.\n - **`amount`**: The number of tokens that are transferred.\n\n The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register.\n\n- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\\_blank} of the XCM instructions.\n\n ```rust\n BuyExecution { \n fees: (Here, amount).into(), \n weight_limit: WeightLimit::Unlimited \n },\n ```\n\n - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight.\n - **`weight_limit`**: Defines the maximum fees that can be used to buy weight.\n\n- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\\_blank}**: Moves the remaining tokens from the holding register to Bob’s account.\n\n ```rust\n DepositAsset {\n assets: All.into(),\n beneficiary: MultiLocation {\n parents: 0,\n interior: Junction::AccountId32 {\n network: None,\n id: BOB.clone().into()\n }.into(),\n }.into()\n }\n ```\n\n - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited.\n \nThis step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\\_blank}."} -{"page_id": "parachains-interoperability-get-started", "page_title": "Introduction to XCM", "index": 6, "depth": 2, "title": "Overview", "anchor": "overview", "start_char": 6877, "end_char": 7450, "estimated_token_count": 117, "token_estimator": "heuristic-v1", "text": "## Overview\n\nXCM revolutionizes cross-chain communication by enabling use cases such as:\n\n- Token transfers between blockchains.\n- Asset locking for cross-chain smart contract interactions.\n- Remote execution of functions on other blockchains.\n\nThese functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\\_blank}."} +{"page_id": "parachains-interoperability-get-started", "page_title": "Get Started with XCM", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 24, "end_char": 696, "estimated_token_count": 113, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nPolkadot’s unique value lies in its ability to enable interoperability between parachains and other blockchain systems. At the core of this capability is XCM (Cross-Consensus Messaging)—a flexible messaging format that facilitates communication and collaboration between independent consensus systems.\n\nWith XCM, one chain can send intents to another one, fostering a more interconnected ecosystem. Although it was developed specifically for Polkadot, XCM is a universal format, usable in any blockchain environment. This guide provides an overview of XCM’s core principles, design, and functionality, alongside practical examples of its implementation."} +{"page_id": "parachains-interoperability-get-started", "page_title": "Get Started with XCM", "index": 1, "depth": 2, "title": "Messaging Format", "anchor": "messaging-format", "start_char": 696, "end_char": 1570, "estimated_token_count": 153, "token_estimator": "heuristic-v1", "text": "## Messaging Format\n\nXCM is not a protocol but a standardized [messaging format](https://github.com/polkadot-fellows/xcm-format){target=\\_blank}. It defines the structure and behavior of messages but does not handle their delivery. This separation allows developers to focus on crafting instructions for target systems without worrying about transmission mechanics.\n\nXCM messages are intent-driven, outlining desired actions for the receiving blockchain to consider and potentially alter its state. These messages do not directly execute changes; instead, they rely on the host chain's environment to interpret and implement them. By utilizing asynchronous composability, XCM facilitates efficient execution where messages can be processed independently of their original order, similar to how RESTful services handle HTTP requests without requiring sequential processing."} +{"page_id": "parachains-interoperability-get-started", "page_title": "Get Started with XCM", "index": 2, "depth": 2, "title": "The Four Principles of XCM", "anchor": "the-four-principles-of-xcm", "start_char": 1570, "end_char": 2506, "estimated_token_count": 174, "token_estimator": "heuristic-v1", "text": "## The Four Principles of XCM\n\nXCM adheres to four guiding principles that ensure robust and reliable communication across consensus systems:\n\n- **Asynchronous**: XCM messages operate independently of sender acknowledgment, avoiding delays due to blocked processes.\n- **Absolute**: XCM messages are guaranteed to be delivered and interpreted accurately, in order, and timely. Once a message is sent, one can be sure it will be processed as intended.\n- **Asymmetric**: XCM messages follow the 'fire and forget' paradigm meaning no automatic feedback is provided to the sender. Any results must be communicated separately to the sender with an additional message back to the origin.\n- **Agnostic**: XCM operates independently of the specific consensus mechanisms, making it compatible across diverse systems.\n\nThese principles guarantee that XCM provides a reliable framework for cross-chain communication, even in complex environments."} +{"page_id": "parachains-interoperability-get-started", "page_title": "Get Started with XCM", "index": 3, "depth": 2, "title": "The XCM Tech Stack", "anchor": "the-xcm-tech-stack", "start_char": 2506, "end_char": 2870, "estimated_token_count": 75, "token_estimator": "heuristic-v1", "text": "## The XCM Tech Stack\n\n![Diagram of the XCM tech stack](/images/parachains/interoperability/get-started/intro-to-xcm-01.webp)\n\nThe XCM tech stack is designed to facilitate seamless interoperable communication between chains that reside within the Polkadot ecosystem. XCM can be used to express the meaning of the messages over each of the communication channels."} +{"page_id": "parachains-interoperability-get-started", "page_title": "Get Started with XCM", "index": 4, "depth": 2, "title": "Core Functionalities of XCM", "anchor": "core-functionalities-of-xcm", "start_char": 2870, "end_char": 3866, "estimated_token_count": 165, "token_estimator": "heuristic-v1", "text": "## Core Functionalities of XCM\n\nXCM enhances cross-consensus communication by introducing several powerful features:\n\n- **Programmability**: Supports dynamic message handling, allowing for more comprehensive use cases. Includes branching logic, safe dispatches for version checks, and asset operations like NFT management.\n- **Functional Multichain Decomposition**: Enables mechanisms such as remote asset locking, asset namespacing, and inter-chain state referencing, with contextual message identification.\n- **Bridging**: Establishes a universal reference framework for multi-hop setups, connecting disparate systems like Ethereum and Bitcoin with the Polkadot relay chain acting as a universal location.\n\nThe standardized format for messages allows parachains to handle tasks like user balances, governance, and staking, freeing the Polkadot relay chain to focus on shared security. These features make XCM indispensable for implementing scalable and interoperable blockchain applications."} +{"page_id": "parachains-interoperability-get-started", "page_title": "Get Started with XCM", "index": 5, "depth": 2, "title": "XCM Example", "anchor": "xcm-example", "start_char": 3866, "end_char": 6878, "estimated_token_count": 704, "token_estimator": "heuristic-v1", "text": "## XCM Example\n\nThe following is a simplified XCM message demonstrating a token transfer from Alice to Bob on the same chain (ParaA).\n\n```rust\nlet message = Xcm(vec![\n WithdrawAsset((Here, amount).into()),\n BuyExecution { \n fees: (Here, amount).into(), \n weight_limit: WeightLimit::Unlimited \n },\n DepositAsset {\n assets: All.into(),\n beneficiary: MultiLocation {\n parents: 0,\n interior: Junction::AccountId32 {\n network: None,\n id: BOB.clone().into()\n }.into(),\n }.into()\n }\n]);\n```\n\nThe message consists of three instructions described as follows:\n\n- **[WithdrawAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#withdrawasset){target=\\_blank}**: Transfers a specified number of tokens from Alice's account to a holding register.\n\n ```rust\n WithdrawAsset((Here, amount).into()),\n ```\n\n - **`Here`**: The native parachain token.\n - **`amount`**: The number of tokens that are transferred.\n\n The first instruction takes as an input the MultiAsset that should be withdrawn. The MultiAsset describes the native parachain token with the `Here` keyword. The `amount` parameter is the number of tokens that are transferred. The withdrawal account depends on the origin of the message. In this example the origin of the message is Alice. The `WithdrawAsset` instruction moves `amount` number of native tokens from Alice's account into the holding register.\n\n- **[BuyExecution](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#buyexecution){target=\\_blank}**: Allocates fees to cover the execution [weight](/reference/glossary/#weight){target=\\_blank} of the XCM instructions.\n\n ```rust\n BuyExecution { \n fees: (Here, amount).into(), \n weight_limit: WeightLimit::Unlimited \n },\n ```\n\n - **`fees`**: Describes the asset in the holding register that should be used to pay for the weight.\n - **`weight_limit`**: Defines the maximum fees that can be used to buy weight.\n\n- **[DepositAsset](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#depositasset){target=\\_blank}**: Moves the remaining tokens from the holding register to Bob’s account.\n\n ```rust\n DepositAsset {\n assets: All.into(),\n beneficiary: MultiLocation {\n parents: 0,\n interior: Junction::AccountId32 {\n network: None,\n id: BOB.clone().into()\n }.into(),\n }.into()\n }\n ```\n\n - **`All`**: The wildcard for the asset(s) to be deposited. In this case, all assets in the holding register should be deposited.\n \nThis step-by-step process showcases how XCM enables precise state changes within a blockchain system. You can find a complete XCM message example in the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\\_blank}."} +{"page_id": "parachains-interoperability-get-started", "page_title": "Get Started with XCM", "index": 6, "depth": 2, "title": "Overview", "anchor": "overview", "start_char": 6878, "end_char": 7451, "estimated_token_count": 117, "token_estimator": "heuristic-v1", "text": "## Overview\n\nXCM revolutionizes cross-chain communication by enabling use cases such as:\n\n- Token transfers between blockchains.\n- Asset locking for cross-chain smart contract interactions.\n- Remote execution of functions on other blockchains.\n\nThese functionalities empower developers to build innovative, multi-chain applications, leveraging the strengths of various blockchain networks. To stay updated on XCM’s evolving format or contribute, visit the [XCM repository](https://github.com/paritytech/xcm-docs/blob/main/examples/src/0_first_look/mod.rs){target=\\_blank}."} {"page_id": "parachains-launch-a-parachain-deploy-to-polkadot", "page_title": "Deploy on Polkadot", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 22, "end_char": 439, "estimated_token_count": 89, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nPreviously, you learned how to [choose and set up a parachain template](/parachains/launch-a-parachain/choose-a-template/){target=\\_blank}. Now, you'll take the next step towards a production-like environment by deploying your parachain to the Polkadot TestNet. Deploying to a TestNet is a crucial step for validating your parachain's functionality and preparing it for eventual MainNet deployment."} {"page_id": "parachains-launch-a-parachain-deploy-to-polkadot", "page_title": "Deploy on Polkadot", "index": 1, "depth": 2, "title": "Get Started with an Account and Tokens", "anchor": "get-started-with-an-account-and-tokens", "start_char": 439, "end_char": 2420, "estimated_token_count": 540, "token_estimator": "heuristic-v1", "text": "## Get Started with an Account and Tokens\n\nTo perform any action on the Polkadot TestNet, you need PAS tokens, which can be requested from the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=0){target=\\_blank}. To store the tokens, you must have access to a Polkadot-SDK-compatible wallet. Go to the [Polkadot Wallets](https://polkadot.com/get-started/wallets/){target=\\_blank} page to view different options for a Polkadot wallet, or use the [Polkadot.js browser extension](https://polkadot.js.org/extension/){target=\\_blank}, which is suitable for development purposes.\n\n!!!warning \n Development keys and accounts should never hold assets of actual value and should not be used for production.\n\nThe [Polkadot.js Apps](https://polkadot.js.org/apps/){target=\\_blank} interface can be used to get you started for testing purposes.\n\nTo prepare an account, follow these steps:\n\n1. Open the [Polkadot.js Apps: Paseo](https://polkadot.js.org/apps/?rpc=wss://paseo.dotters.network#/explorer){target=\\_blank} interface and connect to the Polkadot TestNet (Paseo).\n\n ![](/images/parachains/launch-a-parachain/deploy-to-polkadot/deploy-to-polkadot-1.webp)\n\n2. Navigate to the **Accounts** section:\n\n 1. Click on the **Accounts** tab in the top menu.\n 2. Select the **Accounts** option from the dropdown menu.\n \n ![](/images/parachains/launch-a-parachain/deploy-to-polkadot/deploy-to-polkadot-2.webp)\n\n3. Copy the address of the account you want to use for the parachain deployment.\n\n ![](/images/parachains/launch-a-parachain/deploy-to-polkadot/deploy-to-polkadot-3.webp)\n\n4. Visit the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=0){target=\\_blank} and paste the copied address in the input field. Ensure that the network is set to Paseo and click on the **Get some PASs** button.\n\n ![](/images/parachains/launch-a-parachain/deploy-to-polkadot/deploy-to-polkadot-4.webp)\n\n After a few seconds, you will receive 5000 PAS tokens in your account."} {"page_id": "parachains-launch-a-parachain-deploy-to-polkadot", "page_title": "Deploy on Polkadot", "index": 2, "depth": 2, "title": "Reserve a Parachain Identifier", "anchor": "reserve-a-parachain-identifier", "start_char": 2420, "end_char": 3577, "estimated_token_count": 303, "token_estimator": "heuristic-v1", "text": "## Reserve a Parachain Identifier\n\nYou must reserve a parachain identifier (ID) before registering your parachain on Paseo. You'll be assigned the next available identifier.\n\nTo reserve a parachain identifier, follow these steps:\n\n1. Navigate to the **Parachains** section:\n\n 1. Click on the **Network** tab in the top menu.\n 2. Select the **Parachains** option from the dropdown menu.\n\n ![](/images/parachains/launch-a-parachain/deploy-to-polkadot/deploy-to-polkadot-5.webp)\n\n2. Register a ParaId:\n\n 1. Select the **Parathreads** tab.\n 2. Click on the **+ ParaId** button.\n\n ![](/images/parachains/launch-a-parachain/deploy-to-polkadot/deploy-to-polkadot-6.webp)\n\n3. Review the transaction and click on the **+ Submit** button.\n\n ![](/images/parachains/launch-a-parachain/deploy-to-polkadot/deploy-to-polkadot-7.webp)\n\n For this case, the next available parachain identifier is `4508`.\n\n4. After submitting the transaction, you can navigate to the **Explorer** tab and check the list of recent events for successful `registrar.Reserved`.\n\n ![](/images/parachains/launch-a-parachain/deploy-to-polkadot/deploy-to-polkadot-8.webp)"} @@ -446,416 +366,30 @@ {"page_id": "parachains-runtime-maintenance-unlock-parachains", "page_title": "Unlock a Parachain", "index": 3, "depth": 3, "title": "Prepare the Unlock Call", "anchor": "prepare-the-unlock-call", "start_char": 2758, "end_char": 4174, "estimated_token_count": 341, "token_estimator": "heuristic-v1", "text": "### Prepare the Unlock Call\n\nBefore sending the XCM, you need to construct the relay chain call that will be executed. Follow these steps to prepare the `registrar.removeLock` extrinsic:\n\n1. In [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\\_blank}, connect to the relay chain, navigate to the **Developer** dropdown and select the **Extrinsics** option.\n\n2. Build the `registrar.removeLock` extrinsic:\n\n 1. Select the **registrar** pallet.\n 2. Choose the **removeLock** extrinsic.\n 3. Fill in the parachain ID parameter (e.g., `2006`).\n 4. Copy the **encoded call data**.\n\n ![](/images/parachains/runtime-maintenance/unlock-parachains/unlock-parachain-2.webp)\n\n To ensure your encoded call data is correct, check this [example](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fdot-rpc.stakeworld.io#/extrinsics/decode/0x4604d6070000){target=\\_blank} of a decoded `removeLock` call for parachain 2006. Your encoded data should follow the same pattern.\n\n3. Determine the transaction weight required for executing the call. You can estimate this by executing the `transactionPaymentCallApi.queryCallInfo` runtime call with the encoded call data previously obtained:\n\n ![](/images/parachains/runtime-maintenance/unlock-parachains/unlock-parachain-3.webp)\n\n This weight information is crucial for properly configuring your XCM message's execution parameters in the next steps."} {"page_id": "parachains-runtime-maintenance-unlock-parachains", "page_title": "Unlock a Parachain", "index": 4, "depth": 3, "title": "Fund the Sovereign Account", "anchor": "fund-the-sovereign-account", "start_char": 4174, "end_char": 6051, "estimated_token_count": 414, "token_estimator": "heuristic-v1", "text": "### Fund the Sovereign Account\n\nFor a successful XCM execution, the [sovereign account](https://github.com/polkadot-fellows/xcm-format/blob/10726875bd3016c5e528c85ed6e82415e4b847d7/README.md?plain=1#L50){target=\\_blank} of your parachain on the relay chain must have sufficient funds to cover transaction fees. The sovereign account is a deterministic address derived from your parachain ID.\n\nYou can identify your parachain's sovereign account using either of these methods:\n\n=== \"Runtime API\"\n\n Execute the `locationToAccountApi.convertLocation` runtime API call to convert your parachain's location into its sovereign account address on the relay chain.\n\n ![](/images/parachains/runtime-maintenance/unlock-parachains/unlock-parachain-7.webp)\n\n=== \"Substrate Utilities\"\n\n Use the **\"Para ID\" to Address** section in [Substrate Utilities](https://www.shawntabrizi.com/substrate-js-utilities/){target=\\_blank} with the **Child** option selected.\n\n=== \"Manual Calculation\"\n\n 1. Identify the appropriate prefix:\n\n - For parent/child chains use the prefix `0x70617261` (which decodes to `b\"para\"`).\n \n 2. Encode your parachain ID as a u32 [SCALE](/polkadot-protocol/parachain-basics/data-encoding#data-types){target=\\_blank} value:\n\n - For parachain 2006, this would be `d6070000`.\n\n 3. Combine the prefix with the encoded ID to form the sovereign account address:\n\n - **Hex**: `0x70617261d6070000000000000000000000000000000000000000000000000000`\n - **SS58 format**: `5Ec4AhPW97z4ZyYkd3mYkJrSeZWcwVv4wiANES2QrJi1x17F`\n\nYou can transfer funds to this account from any account on the relay chain using a standard transfer. To calculate the amount needed, refer to the [XCM Payment API](/develop/interoperability/xcm-runtime-apis/#xcm-payment-api){target=\\_blank}. The calculation will depend on the XCM built in the next step."} {"page_id": "parachains-runtime-maintenance-unlock-parachains", "page_title": "Unlock a Parachain", "index": 5, "depth": 3, "title": "Craft and Submit the XCM", "anchor": "craft-and-submit-the-xcm", "start_char": 6051, "end_char": 9232, "estimated_token_count": 710, "token_estimator": "heuristic-v1", "text": "### Craft and Submit the XCM\n\nWith the call data prepared and the sovereign account funded, you can now construct and send the XCM from your parachain to the relay chain. The XCM will need to perform several operations in sequence:\n\n1. Withdraw DOT from your parachain's sovereign account.\n2. Buy execution to pay for transaction fees.\n3. Execute the `registrar.removeLock` extrinsic.\n4. Return any unused funds to your sovereign account.\n\nHere's how to submit this XCM using Astar (Parachain 2006) as an example:\n\n1. In [Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\\_blank}, connect to the parachain, navigate to the **Developer** dropdown and select the **Extrinsics** option.\n\n2. Create a `sudo.sudo` extrinsic that executes `polkadotXcm.send`:\n\n 1. Use the `sudo.sudo` extrinsic to execute the following call as Root.\n 2. Select the **polkadotXcm** pallet.\n 3. Choose the **send** extrinsic.\n 4. Set the **dest** parameter as the relay chain.\n\n ![](/images/parachains/runtime-maintenance/unlock-parachains/unlock-parachain-4.webp)\n\n3. Construct the XCM and submit it:\n\n 1. Add a **WithdrawAsset** instruction.\n 2. Add a **BuyExecution** instruction.\n - **fees**:\n - **id**: The asset location to use for the fee payment. In this example, the relay chain native asset is used.\n - **fun**: Select `Fungible` and use the same amount you withdrew from the sovereign account in the previous step.\n - **weightLimit**: Use `Unlimited`.\n 3. Add a **Transact** instruction with the following parameters:\n - **originKind**: Use `Native`.\n - **requireWeightAtMost**: Use the weight calculated previously.\n - **call**: Use the encoded call data generated before.\n 4. Add a **RefundSurplus** instruction.\n 5. Add a **DepositAsset** instruction to send the remaining funds to the parachain sovereign account.\n 6. Click the **Submit Transaction** button.\n\n ![](/images/parachains/runtime-maintenance/unlock-parachains/unlock-parachain-5.webp)\n\n If the amount withdrawn in the first instruction is exactly the amount needed to pay the transaction fees, instructions 4 and 5 can be omitted.\n\n To validate your XCM, examine the following reference [extrinsic](https://polkadot.js.org/apps/?rpc=wss%3A%2F%2Fastar.public.curie.radiumblock.co%2Fws#/extrinsics/decode/0x63003300040100041400040000000700e40b5402130000000700e40b540200060042d3c91800184604d6070000140d0100000100591f){target=_blank} showing the proper instruction sequence and parameter formatting. Following this structure will help ensure successful execution of your message.\n\nAfter submitting the transaction, wait for it to be finalized and then verify that your parachain has been successfully unlocked by following the steps described in the [Check if the Parachain is Locked](#check-if-the-parachain-is-locked) section. If the parachain shows as unlocked, your operation has been successful. If it still appears locked, verify that your XCM transaction was processed correctly and consider troubleshooting the XCM built.\n\n![](/images/parachains/runtime-maintenance/unlock-parachains/unlock-parachain-6.webp)"} -{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Get Started", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 15, "end_char": 1193, "estimated_token_count": 242, "token_estimator": "heuristic-v1", "text": "## Introduction\n\n[Chopsticks](https://github.com/AcalaNetwork/chopsticks/){target=\\_blank}, developed by the [Acala Foundation](https://github.com/AcalaNetwork){target=\\_blank}, is a versatile tool tailored for developers working on Polkadot SDK-based blockchains. With Chopsticks, you can fork live chains locally, replay blocks to analyze extrinsics, and simulate complex scenarios like XCM interactions all without deploying to a live network.\n\nThis guide walks you through installing Chopsticks and provides information on configuring a local blockchain fork. By streamlining testing and experimentation, Chopsticks empowers developers to innovate and accelerate their blockchain projects within the Polkadot ecosystem.\n\nFor additional support and information, please reach out through [GitHub Issues](https://github.com/AcalaNetwork/chopsticks/issues){target=_blank}.\n\n!!! warning\n Chopsticks uses [Smoldot](https://github.com/smol-dot/smoldot){target=_blank} light client, which only supports the native Polkadot SDK API. Consequently, a Chopsticks-based fork doesn't support Ethereum JSON-RPC calls, meaning you cannot use it to fork your chain and connect Metamask."} -{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Get Started", "index": 1, "depth": 2, "title": "Prerequisites", "anchor": "prerequisites", "start_char": 1193, "end_char": 1500, "estimated_token_count": 99, "token_estimator": "heuristic-v1", "text": "## Prerequisites\n\nBefore you begin, ensure you have the following installed:\n\n- [Node.js](https://nodejs.org/en/){target=\\_blank}.\n- A package manager such as [npm](https://www.npmjs.com/){target=\\_blank}, which should be installed with Node.js by default, or [Yarn](https://yarnpkg.com/){target=\\_blank}."} -{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Get Started", "index": 2, "depth": 2, "title": "Install Chopsticks", "anchor": "install-chopsticks", "start_char": 1500, "end_char": 1792, "estimated_token_count": 55, "token_estimator": "heuristic-v1", "text": "## Install Chopsticks\n\nYou can install Chopsticks globally or locally in your project. Choose the option that best fits your development workflow. This documentation explains the features of Chopsticks version `1.2.2`. Make sure you're using the correct version to match these instructions."} -{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Get Started", "index": 3, "depth": 3, "title": "Global Installation", "anchor": "global-installation", "start_char": 1792, "end_char": 2035, "estimated_token_count": 61, "token_estimator": "heuristic-v1", "text": "### Global Installation\n\nTo install Chopsticks globally, allowing you to use it across multiple projects, run:\n\n```bash\nnpm i -g @acala-network/chopsticks@1.2.2\n```\n\nNow, you should be able to run the `chopsticks` command from your terminal."} -{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Get Started", "index": 4, "depth": 3, "title": "Local Installation", "anchor": "local-installation", "start_char": 2035, "end_char": 2524, "estimated_token_count": 128, "token_estimator": "heuristic-v1", "text": "### Local Installation\n\nTo use Chopsticks in a specific project, first create a new directory and initialize a Node.js project:\n\n```bash\nmkdir my-chopsticks-project\ncd my-chopsticks-project\nnpm init -y\n```\n\nThen, install Chopsticks as a local dependency:\n\n```bash\nnpm i @acala-network/chopsticks@1.2.2\n```\n\nFinally, you can run Chopsticks using the `npx` command. To see all available options and commands, run it with the `--help` flag:\n\n```bash\nnpx @acala-network/chopsticks --help\n```"} -{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Get Started", "index": 5, "depth": 2, "title": "Configure Chopsticks", "anchor": "configure-chopsticks", "start_char": 2524, "end_char": 3873, "estimated_token_count": 360, "token_estimator": "heuristic-v1", "text": "## Configure Chopsticks\n\nTo run Chopsticks, you need to configure some parameters. This can be set either through using a configuration file or the command line interface (CLI). The parameters that can be configured are as follows:\n\n- **`genesis`**: The link to a parachain's raw genesis file to build the fork from, instead of an endpoint.\n- **`timestamp`**: Timestamp of the block to fork from.\n- **`endpoint`**: The endpoint of the parachain to fork.\n- **`block`**: Use to specify at which block hash or number to replay the fork.\n- **`wasm-override`**: Path of the Wasm to use as the parachain runtime, instead of an endpoint's runtime.\n- **`db`**: Path to the name of the file that stores or will store the parachain's database.\n- **`config`**: Path or URL of the config file.\n- **`port`**: The port to expose an endpoint on.\n- **`build-block-mode`**: How blocks should be built in the fork: batch, manual, instant.\n- **`import-storage`**: A pre-defined JSON/YAML storage path to override in the parachain's storage.\n- **`allow-unresolved-imports`**: Whether to allow Wasm unresolved imports when using a Wasm to build the parachain.\n- **`html`**: Include to generate storage diff preview between blocks.\n- **`mock-signature-host`**: Mock signature host so that any signature starts with `0xdeadbeef` and filled by `0xcd` is considered valid."} -{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Get Started", "index": 6, "depth": 3, "title": "Configuration File", "anchor": "configuration-file", "start_char": 3873, "end_char": 5072, "estimated_token_count": 271, "token_estimator": "heuristic-v1", "text": "### Configuration File\n\nThe Chopsticks source repository includes a collection of [YAML](https://yaml.org/){target=\\_blank} files that can be used to set up various Polkadot SDK chains locally. You can download these configuration files from the [repository's `configs` folder](https://github.com/AcalaNetwork/chopsticks/tree/master/configs){target=\\_blank}.\n\nAn example of a configuration file for Polkadot is as follows:\n\n{% raw %}\n```yaml\nendpoint:\n - wss://rpc.ibp.network/polkadot\n - wss://polkadot-rpc.dwellir.com\nmock-signature-host: true\nblock: ${env.POLKADOT_BLOCK_NUMBER}\ndb: ./db.sqlite\nruntime-log-level: 5\n\nimport-storage:\n System:\n Account:\n - - - 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY\n - providers: 1\n data:\n free: '10000000000000000000'\n ParasDisputes:\n $removePrefix: ['disputes'] # those can makes block building super slow\n\n```\n{% endraw %}\n\nThe configuration file allows you to modify the storage of the forked network by rewriting the pallet, state component and value that you want to change. For example, Polkadot's file rewrites Alice's `system.Account` storage so that the free balance is set to `10000000000000000000`."} -{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Get Started", "index": 7, "depth": 3, "title": "CLI Flags", "anchor": "cli-flags", "start_char": 5072, "end_char": 5253, "estimated_token_count": 35, "token_estimator": "heuristic-v1", "text": "### CLI Flags\n\nAlternatively, all settings (except for genesis and timestamp) can be configured via command-line flags, providing a comprehensive method to set up the environment."} -{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Get Started", "index": 8, "depth": 2, "title": "WebSocket Commands", "anchor": "websocket-commands", "start_char": 5253, "end_char": 10537, "estimated_token_count": 1272, "token_estimator": "heuristic-v1", "text": "## WebSocket Commands\n\nChopstick's internal WebSocket server has special endpoints that allow the manipulation of the local Polkadot SDK chain.\n\nThese are the methods that can be invoked and their parameters:\n\n- **dev_newBlock** (newBlockParams): Generates one or more new blocks.\n\n === \"Parameters\"\n\n - **`newBlockParams` ++\"NewBlockParams\"++**: The parameters to build the new block with. Where the `NewBlockParams` interface includes the following properties.\n\n - **`count` ++\"number\"++**: The number of blocks to build.\n - **`dmp` ++\"{ msg: string, sentAt: number }[]\"++**: The downward messages to include in the block.\n - **`hrmp` ++\"Record\"++**: The horizontal messages to include in the block.\n - **`to` ++\"number\"++**: The block number to build to.\n - **`transactions` ++\"string[]\"++**: The transactions to include in the block.\n - **`ump` ++\"Record\"++**: The upward messages to include in the block.\n - **`unsafeBlockHeight` ++\"number\"++**: Build block using a specific block height (unsafe).\n\n === \"Example\"\n\n ```js\n import { ApiPromise, WsProvider } from '@polkadot/api';\n\n async function main() {\n const wsProvider = new WsProvider('ws://localhost:8000');\n const api = await ApiPromise.create({ provider: wsProvider });\n await api.isReady;\n await api.rpc('dev_newBlock', { count: 1 });\n }\n\n main();\n\n ```\n\n- **dev_setBlockBuildMode** (buildBlockMode): Sets block build mode.\n\n === \"Parameter\"\n \n - **`buildBlockMode` ++\"BuildBlockMode\"++**: The build mode. Can be any of the following modes:\n\n ```ts\n export enum BuildBlockMode {\n Batch = 'Batch', /** One block per batch (default) */\n Instant = 'Instant', /** One block per transaction */\n Manual = 'Manual', /** Only build when triggered */\n }\n ```\n \n === \"Example\"\n\n ```js\n import { ApiPromise, WsProvider } from '@polkadot/api';\n\n async function main() {\n const wsProvider = new WsProvider('ws://localhost:8000');\n const api = await ApiPromise.create({ provider: wsProvider });\n await api.isReady;\n await api.rpc('dev_setBlockBuildMode', 'Instant');\n }\n\n main();\n\n ```\n\n- **dev_setHead** (hashOrNumber): Sets the head of the blockchain to a specific hash or number.\n\n === \"Parameter\"\n\n - **`hashOrNumber` ++\"string | number\"++**: The block hash or number to set as head.\n\n === \"Example\"\n\n ```js\n import { ApiPromise, WsProvider } from '@polkadot/api';\n\n async function main() {\n const wsProvider = new WsProvider('ws://localhost:8000');\n const api = await ApiPromise.create({ provider: wsProvider });\n await api.isReady;\n await api.rpc('dev_setHead', 500);\n }\n\n main();\n\n ```\n\n- **dev_setRuntimeLogLevel** (runtimeLogLevel): Sets the runtime log level.\n\n === \"Parameter\"\n\n - **`runtimeLogLevel` ++\"number\"++**: The runtime log level to set.\n\n === \"Example\"\n\n ```js\n import { ApiPromise, WsProvider } from '@polkadot/api';\n\n async function main() {\n const wsProvider = new WsProvider('ws://localhost:8000');\n const api = await ApiPromise.create({ provider: wsProvider });\n await api.isReady;\n await api.rpc('dev_setRuntimeLogLevel', 1);\n }\n\n main();\n\n ```\n\n- **dev_setStorage** (values, blockHash): Creates or overwrites the value of any storage.\n\n === \"Parameters\"\n\n - **`values` ++\"object\"++**: JSON object resembling the path to a storage value.\n - **`blockHash` ++\"string\"++**: The block hash to set the storage value.\n\n === \"Example\"\n\n ```js\n import { ApiPromise, WsProvider } from '@polkadot/api';\n\n import { Keyring } from '@polkadot/keyring';\n async function main() {\n const wsProvider = new WsProvider('ws://localhost:8000');\n const api = await ApiPromise.create({ provider: wsProvider });\n await api.isReady;\n const keyring = new Keyring({ type: 'ed25519' });\n const bob = keyring.addFromUri('//Bob');\n const storage = {\n System: {\n Account: [[[bob.address], { data: { free: 100000 }, nonce: 1 }]],\n },\n };\n await api.rpc('dev_setStorage', storage);\n }\n\n main();\n\n ```\n\n- **dev_timeTravel** (date): Sets the timestamp of the block to a specific date\".\n\n === \"Parameter\"\n\n - **`date` ++\"string\"++**: Timestamp or date string to set. All future blocks will be sequentially created after this point in time.\n\n === \"Example\"\n\n ```js\n import { ApiPromise, WsProvider } from '@polkadot/api';\n\n async function main() {\n const wsProvider = new WsProvider('ws://localhost:8000');\n const api = await ApiPromise.create({ provider: wsProvider });\n await api.isReady;\n await api.rpc('dev_timeTravel', '2030-08-15T00:00:00');\n }\n\n main();\n\n ```"} -{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Get Started", "index": 9, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 10537, "end_char": 10894, "estimated_token_count": 91, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\n
\n\n- Tutorial __Fork a Chain with Chopsticks__\n\n ---\n\n Visit this guide for step-by-step instructions for configuring and interacting with your forked chain.\n\n [:octicons-arrow-right-24: Reference](/tutorials/polkadot-sdk/testing/fork-live-chains/)\n\n
"} -{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Get Started", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 15, "end_char": 767, "estimated_token_count": 125, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nZombienet is a robust testing framework designed for Polkadot SDK-based blockchain networks. It enables developers to efficiently deploy and test ephemeral blockchain environments on platforms like Kubernetes, Podman, and native setups. With its simple and versatile CLI, Zombienet provides an all-in-one solution for spawning networks, running tests, and validating performance.\n\nThis guide will outline the different installation methods for Zombienet, provide step-by-step instructions for setting up on various platforms, and highlight essential provider-specific features and requirements.\n\nBy following this guide, Zombienet will be up and running quickly, ready to streamline your blockchain testing and development workflows."} -{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Get Started", "index": 1, "depth": 2, "title": "Install Zombienet", "anchor": "install-zombienet", "start_char": 767, "end_char": 5021, "estimated_token_count": 901, "token_estimator": "heuristic-v1", "text": "## Install Zombienet\n\nZombienet releases are available on the [Zombienet repository](https://github.com/paritytech/zombienet){target=\\_blank}.\n\nMultiple options are available for installing Zombienet, depending on the user's preferences and the environment where it will be used. The following section will guide you through the installation process for each option.\n\n=== \"Use the executable\"\n\n Install Zombienet using executables by visiting the [latest release](https://github.com/paritytech/zombienet/releases){target=\\_blank} page and selecting the appropriate asset for your operating system. You can download the executable and move it to a directory in your PATH. \n\n Each release includes executables for Linux and macOS. Executables are generated using [pkg](https://github.com/vercel/pkg){target=\\_blank}, which allows the Zombienet CLI to operate without requiring Node.js to be installed. \n\n Then, ensure the downloaded file is executable:\n\n ```bash\n chmod +x zombienet-macos-arm64\n ```\n\n Finally, you can run the following command to check if the installation was successful. If so, it will display the version of the installed Zombienet:\n\n ```bash\n ./zombienet-macos-arm64 version\n ```\n\n If you want to add the `zombienet` executable to your PATH, you can move it to a directory in your PATH, such as `/usr/local/bin`:\n\n ```bash\n mv zombienet-macos-arm64 /usr/local/bin/zombienet\n ```\n\n Now you can refer to the `zombienet` executable directly.\n\n ```bash\n zombienet version\n ```\n\n=== \"Use Nix\"\n\n For Nix users, the Zombienet repository provides a [`flake.nix`](https://github.com/paritytech/zombienet/blob/main/flake.nix){target=\\_blank} file to install Zombienet making it easy to incorporate Zombienet into Nix-based projects.\n \n To install Zombienet utilizing Nix, users can run the following command, triggering the fetching of the flake and subsequently installing the Zombienet package:\n\n ```bash\n nix run github:paritytech/zombienet/INSERT_ZOMBIENET_VERSION -- \\\n spawn INSERT_ZOMBIENET_CONFIG_FILE_NAME.toml\n ```\n\n Replace the `INSERT_ZOMBIENET_VERSION` with the desired version of Zombienet and the `INSERT_ZOMBIENET_CONFIG_FILE_NAME` with the name of the configuration file you want to use.\n\n To run the command above, you need to have [Flakes](https://nixos.wiki/wiki/Flakes#Enable_flakes){target=\\_blank} enabled.\n\n Alternatively, you can also include the Zombienet binary in the PATH for the current shell using the following command:\n \n ```bash\n nix shell github:paritytech/zombienet/INSERT_ZOMBIENET_VERSION\n ```\n\n=== \"Use Docker\"\n\n Zombienet can also be run using Docker. The Zombienet repository provides a Docker image that can be used to run the Zombienet CLI. To run Zombienet using Docker, you can use the following command:\n\n ```bash\n docker run -it --rm \\\n -v $(pwd):/home/nonroot/zombie-net/host-current-files \\\n paritytech/zombienet\n ```\n\n The command above will run the Zombienet CLI inside a Docker container and mount the current directory to the `/home/nonroot/zombie-net/host-current-files` directory. This allows Zombienet to access the configuration file and other files in the current directory. If you want to mount a different directory, replace `$(pwd)` with the desired directory path.\n\n Inside the Docker container, you can run the Zombienet CLI commands. First, you need to set up Zombienet to download the necessary binaries:\n\n ```bash\n npm run zombie -- setup polkadot polkadot-parachain\n ```\n\n After that, you need to add those binaries to the PATH:\n\n ```bash\n export PATH=/home/nonroot/zombie-net:$PATH\n ```\n\n Finally, you can run the Zombienet CLI commands. For example, to spawn a network using a specific configuration file, you can run the following command:\n\n ```bash\n npm run zombie -- -p native spawn host-current-files/minimal.toml\n ```\n\n The command above mounts the current directory to the `/workspace` directory inside the Docker container, allowing Zombienet to access the configuration file and other files in the current directory. If you want to mount a different directory, replace `$(pwd)` with the desired directory path."} -{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Get Started", "index": 2, "depth": 2, "title": "Providers", "anchor": "providers", "start_char": 5021, "end_char": 5804, "estimated_token_count": 185, "token_estimator": "heuristic-v1", "text": "## Providers\n\nZombienet supports different backend providers for running the nodes. At this moment, [Kubernetes](https://kubernetes.io/){target=\\_blank}, [Podman](https://podman.io/){target=\\_blank}, and local providers are supported, which can be declared as `kubernetes`, `podman`, or `native`, respectively.\n\nTo use a particular provider, you can specify it in the network file or use the `--provider` flag in the CLI:\n\n```bash\nzombienet spawn network.toml --provider INSERT_PROVIDER\n```\n\nAlternatively, you can set the provider in the network file:\n\n```toml\n[settings]\nprovider = \"INSERT_PROVIDER\"\n...\n```\n\nIt's important to note that each provider has specific requirements and associated features. The following sections cover each provider's requirements and added features."} -{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Get Started", "index": 3, "depth": 3, "title": "Kubernetes", "anchor": "kubernetes", "start_char": 5804, "end_char": 7333, "estimated_token_count": 329, "token_estimator": "heuristic-v1", "text": "### Kubernetes\n\nKubernetes is a portable, extensible, open-source platform for managing containerized workloads and services. Zombienet is designed to be compatible with a variety of Kubernetes clusters, including: \n\n- [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine){target=\\_blank}\n- [Docker Desktop](https://docs.docker.com/desktop/features/kubernetes/){target=\\_blank}\n- [kind](https://kind.sigs.k8s.io/){target=\\_blank}\n\n#### Requirements\n \nTo effectively interact with your cluster, you'll need to ensure that [`kubectl`](https://kubernetes.io/docs/reference/kubectl/){target=\\_blank} is installed on your system. This Kubernetes command-line tool allows you to run commands against Kubernetes clusters. If you don't have `kubectl` installed, you can follow the instructions provided in the [Kubernetes documentation](https://kubernetes.io/docs/tasks/tools/#kubectl){target=\\_blank}.\n\nTo create resources such as namespaces, pods, and CronJobs within the target cluster, you must grant your user or service account the appropriate permissions. These permissions are essential for managing and deploying applications effectively within Kubernetes.\n\n#### Features\n \nIf available, Zombienet uses the Prometheus operator to oversee monitoring and visibility. This configuration ensures that only essential networking-related pods are deployed. Using the Prometheus operator, Zombienet improves its ability to monitor and manage network activities within the Kubernetes cluster efficiently."} -{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Get Started", "index": 4, "depth": 3, "title": "Podman", "anchor": "podman", "start_char": 7333, "end_char": 8929, "estimated_token_count": 374, "token_estimator": "heuristic-v1", "text": "### Podman\n\nPodman is a daemonless container engine for developing, managing, and running Open Container Initiative (OCI) containers and container images on Linux-based systems. Zombienet supports Podman rootless as a provider on Linux machines. Although Podman has support for macOS through an internal virtual machine (VM), the Zombienet provider code requires Podman to run natively on Linux.\n\n#### Requirements\n \nTo use Podman as a provider, you need to have Podman installed on your system. You can install Podman by following the instructions provided on the [Podman website](https://podman.io/getting-started/installation){target=\\_blank}.\n\n#### Features\n \nUsing Podman, Zombienet deploys additional pods to enhance the monitoring and visibility of the active network. Specifically, pods for [Prometheus](https://prometheus.io/){target=\\_blank}, [Tempo](https://grafana.com/docs/tempo/latest/operations/monitor/){target=\\_blank}, and [Grafana](https://grafana.com/){target=\\_blank} are included in the deployment. Grafana is configured with Prometheus and Tempo as data sources.\n\nUpon launching Zombienet, access to these monitoring services is facilitated through specific URLs provided in the output:\n\n- **Prometheus**: `http://127.0.0.1:34123`\n- **Tempo**: `http://127.0.0.1:34125`\n- **Grafana**: `http://127.0.0.1:41461`\n\nIt's important to note that Grafana is deployed with default administrator access. \n \nWhen network operations cease, either from halting a running spawn with the `Ctrl+C` command or test completion, Zombienet automatically removes all associated pods."} -{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Get Started", "index": 5, "depth": 3, "title": "Local Provider", "anchor": "local-provider", "start_char": 8929, "end_char": 10889, "estimated_token_count": 420, "token_estimator": "heuristic-v1", "text": "### Local Provider\n\nThe Zombienet local provider, also called native, enables you to run nodes as local processes in your environment.\n\n#### Requirements\n \nYou must have the necessary binaries for your network (such as `polkadot` and `polkadot-parachain`). These binaries should be available in your PATH, allowing Zombienet to spawn the nodes as local processes.\n\nTo install the necessary binaries, you can use the Zombienet CLI command:\n\n```bash\nzombienet setup polkadot polkadot-parachain\n```\n\nThis command will download and prepare the necessary binaries for Zombienet's use.\n\nIf you need to use a custom binary, ensure the binary is available in your PATH. You can also specify the binary path in the network configuration file. The following example uses the custom [OpenZeppelin template](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\\_blank}:\n\nFirst, clone the OpenZeppelin template repository using the following command:\n\n```bash\ngit clone https://github.com/OpenZeppelin/polkadot-runtime-templates \\\n&& cd polkadot-runtime-templates/generic-template\n```\n\nNext, run the command to build the custom binary:\n\n```bash\ncargo build --release\n```\n\nFinally, add the custom binary to your PATH as follows:\n\n```bash\nexport PATH=$PATH:INSERT_PATH_TO_RUNTIME_TEMPLATES/parachain-template-node/target/release\n```\n\nAlternatively, you can specify the binary path in the network configuration file. The local provider exclusively utilizes the command configuration for nodes, which supports both relative and absolute paths. You can employ the `default_command` configuration to specify the binary for spawning all nodes in the relay chain.\n\n```toml\n[relaychain]\nchain = \"rococo-local\"\ndefault_command = \"./bin-v1.6.0/polkadot\"\n\n[parachain]\nid = 1000\n\n [parachain.collators]\n name = \"collator01\"\n command = \"./target/release/parachain-template-node\"\n```\n\n#### Features\n\nThe local provider does not offer any additional features."} -{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Get Started", "index": 6, "depth": 2, "title": "Configure Zombienet", "anchor": "configure-zombienet", "start_char": 10889, "end_char": 11501, "estimated_token_count": 99, "token_estimator": "heuristic-v1", "text": "## Configure Zombienet\n\nEffective network configuration is crucial for deploying and managing blockchain systems. Zombienet simplifies this process by offering versatile configuration options in both JSON and TOML formats. Whether setting up a simple test network or a complex multi-node system, Zombienet's tools provide the flexibility to customize every aspect of your network's setup.\n\nThe following sections will explore the structure and usage of Zombienet configuration files, explain key settings for network customization, and walk through CLI commands and flags to optimize your development workflow."} -{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Get Started", "index": 7, "depth": 3, "title": "Configuration Files", "anchor": "configuration-files", "start_char": 11501, "end_char": 11979, "estimated_token_count": 100, "token_estimator": "heuristic-v1", "text": "### Configuration Files\n\nThe network configuration file can be either JSON or TOML format. The Zombienet repository also provides a collection of [example configuration files](https://github.com/paritytech/zombienet/tree/main/examples){target=\\_blank} that can be used as a reference.\n\nEach section may include provider-specific keys that aren't recognized by other providers. For example, if you use the local provider, any references to images for nodes will be disregarded."} -{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Get Started", "index": 8, "depth": 3, "title": "CLI Usage", "anchor": "cli-usage", "start_char": 11979, "end_char": 13771, "estimated_token_count": 502, "token_estimator": "heuristic-v1", "text": "### CLI Usage\n\nZombienet provides a CLI that allows interaction with the tool. The CLI can receive commands and flags to perform different kinds of operations. These operations use the following syntax:\n\n```bash\nzombienet \n```\n\nThe following sections will guide you through the primary usage of the Zombienet CLI and the available commands and flags.\n\n#### CLI Commands\n\n- **`spawn `**: Spawn the network defined in the [configuration file](#configuration-files).\n- **`test `**: Run tests on the spawned network using the assertions and tests defined in the [test file](/develop/toolkit/parachains/spawn-chains/zombienet/write-tests/#the-test-file){target=\\_blank}.\n- **`setup `**: Set up the Zombienet development environment to download and use the `polkadot` or `polkadot-parachain` executable.\n- **`convert `**: Transforms a [polkadot-launch](https://github.com/paritytech/polkadot-launch){target=\\_blank} configuration file with a `.js` or `.json` extension into a Zombienet configuration file.\n- **`version`**: Prints Zombienet version.\n- **`help`**: Prints help information.\n\n#### CLI Flags\n\nYou can use the following flags to customize the behavior of the CLI:\n\n- **`-p`, `--provider`**: Override the [provider](#providers) to use.\n- **`-d`, `--dir`**: Specify a directory path for placing the network files instead of using the default temporary path.\n- **`-f`, `--force`**: Force override all prompt commands.\n- **`-l`, `--logType`**: Type of logging on the console. Defaults to `table`.\n- **`-m`, `--monitor`**: Start as monitor and don't auto clean up network.\n- **`-c`, `--spawn-concurrency`**: Number of concurrent spawning processes to launch. Defaults to `1`.\n- **`-h`, `--help`**: Display help for command."} -{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Get Started", "index": 9, "depth": 3, "title": "Settings", "anchor": "settings", "start_char": 13771, "end_char": 16964, "estimated_token_count": 866, "token_estimator": "heuristic-v1", "text": "### Settings\n\nThrough the keyword `settings`, it's possible to define the general settings for the network. The available keys are:\n\n- **`global_volumes?`** ++\"GlobalVolume[]\"++: A list of global volumes to use.\n\n ??? child \"`GlobalVolume` interface definition\"\n ```js\n export interface GlobalVolume {\n name: string;\n fs_type: string;\n mount_path: string;\n }\n ```\n\n- **`bootnode`** ++\"boolean\"++: Add bootnode to network. Defaults to `true`.\n- **`bootnode_domain?`** ++\"string\"++: Domain to use for bootnode.\n- **`timeout`** ++\"number\"++: Global timeout to use for spawning the whole network.\n- **`node_spawn_timeout?`** ++\"number\"++: Timeout to spawn pod/process.\n- **`grafana?`** ++\"boolean\"++: Deploy an instance of Grafana.\n- **`prometheus?`** ++\"boolean\"++: Deploy an instance of Prometheus.\n- **`telemetry?`** ++\"boolean\"++: Enable telemetry for the network.\n- **`jaeger_agent?`** ++\"string\"++: The Jaeger agent endpoint passed to the nodes. Only available on Kubernetes.\n- **`tracing_collator_url?`** ++\"string\"++: The URL of the tracing collator used to query by the tracing assertion. Should be tempo query compatible.\n- **`tracing_collator_service_name?`** ++\"string\"++: Service name for tempo query frontend. Only available on Kubernetes. Defaults to `tempo-tempo-distributed-query-frontend`.\n- **`tracing_collator_service_namespace?`** ++\"string\"++: Namespace where tempo is running. Only available on Kubernetes. Defaults to `tempo`.\n- **`tracing_collator_service_port?`** ++\"number\"++: Port of the query instance of tempo. Only available on Kubernetes. Defaults to `3100`.\n- **`enable_tracing?`** ++\"boolean\"++: Enable the tracing system. Only available on Kubernetes. Defaults to `true`.\n- **`provider`** ++\"string\"++: Provider to use. Default is `kubernetes`\".\n- **`polkadot_introspector?`** ++\"boolean\"++: Deploy an instance of polkadot-introspector. Only available on Podman and Kubernetes. Defaults to `false`.\n- **`backchannel?`** ++\"boolean\"++: Deploy an instance of backchannel server. Only available on Kubernetes. Defaults to `false`.\n- **`image_pull_policy?`** ++\"string\"++: Image pull policy to use in the network. Possible values are `Always`, `IfNotPresent`, and `Never`.\n- **`local_ip?`** ++\"string\"++: IP used for exposing local services (rpc/metrics/monitors). Defaults to `\"127.0.0.1\"`.\n- **`global_delay_network_global_settings?`** ++\"number\"++: Delay in seconds to apply to the network.\n- **`node_verifier?`** ++\"string\"++: Specify how to verify node readiness or deactivate by using `None`. Possible values are `None` and `Metric`. Defaults to `Metric`.\n\nFor example, the following configuration file defines a minimal example for the settings:\n\n=== \"TOML\"\n\n ```toml title=\"base-example.toml\"\n [settings]\n timeout = 1000\n bootnode = false\n provider = \"kubernetes\"\n backchannel = false\n # ...\n\n ```\n\n=== \"JSON\"\n\n ```json title=\"base-example.json\"\n {\n \"settings\": {\n \"timeout\": 1000,\n \"bootnode\": false,\n \"provider\": \"kubernetes\",\n \"backchannel\": false,\n \"...\": {}\n },\n \"...\": {}\n }\n\n ```"} -{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Get Started", "index": 10, "depth": 3, "title": "Relay Chain Configuration", "anchor": "relay-chain-configuration", "start_char": 16964, "end_char": 28518, "estimated_token_count": 2794, "token_estimator": "heuristic-v1", "text": "### Relay Chain Configuration\n\nYou can use the `relaychain` keyword to define further parameters for the relay chain at start-up. The available keys are:\n\n- **`default_command?`** ++\"string\"++: The default command to run. Defaults to `polkadot`.\n- **`default_image?`** ++\"string\"++: The default Docker image to use.\n- **`default_resources?`** ++\"Resources\"++: Represents the resource limits/reservations the nodes need by default. Only available on Kubernetes.\n\n ??? child \"`Resources` interface definition\"\n ```js\n export interface Resources {\n resources: {\n requests?: {\n memory?: string;\n cpu?: string;\n };\n limits?: {\n memory?: string;\n cpu?: string;\n };\n };\n }\n ```\n\n- **`default_db_snapshot?`** ++\"string\"++: The default database snapshot to use.\n- **`default_prometheus_prefix`** ++\"string\"++: A parameter for customizing the metric's prefix. Defaults to `substrate`.\n- **`default_substrate_cli_args_version?`** ++\"SubstrateCliArgsVersion\"++: Set the Substrate CLI arguments version.\n\n ??? child \"`SubstrateCliArgsVersion` enum definition\"\n ```js\n export enum SubstrateCliArgsVersion {\n V0 = 0,\n V1 = 1,\n V2 = 2,\n V3 = 3,\n }\n ```\n\n- **`default_keystore_key_types?`** ++\"string[]\"++: Defines which keystore keys should be created.\n- **`chain`** ++\"string\"++: The chain name.\n- **`chain_spec_path?`** ++\"string\"++: Path to the chain spec file. Should be the plain version to allow customizations.\n- **`chain_spec_command?`** ++\"string\"++: Command to generate the chain spec. It can't be used in combination with `chain_spec_path`.\n- **`default_args?`** ++\"string[]\"++: An array of arguments to use as default to pass to the command.\n- **`default_overrides?`** ++\"Override[]\"++: An array of overrides to upload to the node.\n\n ??? child \"`Override` interface definition\"\n ```js\n export interface Override {\n local_path: string;\n remote_name: string;\n } \n ```\n\n- **`random_nominators_count?`** ++\"number\"++: If set and the stacking pallet is enabled, Zombienet will generate the input quantity of nominators and inject them into the genesis.\n- **`max_nominations`** ++\"number\"++: The max number of nominations allowed by a nominator. Should match the value set in the runtime. Defaults to `24`.\n- **`nodes?`** ++\"Node[]\"++: An array of nodes to spawn. It is further defined in the [Node Configuration](#node-configuration) section.\n- **`node_groups?`** ++\"NodeGroup[]\"++: An array of node groups to spawn. It is further defined in the [Node Group Configuration](#node-group-configuration) section.\n- **`total_node_in_group?`** ++\"number\"++: The total number of nodes in the group. Defaults to `1`.\n- **`genesis`** ++\"JSON\"++: The genesis configuration.\n- **`default_delay_network_settings?`** ++\"DelayNetworkSettings\"++: Sets the expected configuration to delay the network.\n\n ??? child \"`DelayNetworkSettings` interface definition\"\n ```js\n export interface DelayNetworkSettings {\n latency: string;\n correlation?: string; // should be parsable as float by k8s\n jitter?: string;\n }\n ```\n\n#### Node Configuration\n\nOne specific key capable of receiving more subkeys is the `nodes` key. This key is used to define further parameters for the nodes. The available keys:\n\n- **`name`** ++\"string\"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`).\n- **`image?`** ++\"string\"++: Override default Docker image to use for this node.\n- **`command?`** ++\"string\"++: Override default command to run.\n- **`command_with_args?`** ++\"string\"++: Override default command and arguments.\n- **`args?`** ++\"string[]\"++: Arguments to be passed to the command.\n- **`env?`** ++\"envVars[]\"++: Environment variables to set in the container.\n\n ??? child \"`envVars` interface definition\"\n ```js\n export interface EnvVars {\n name: string;\n value: string;\n }\n ```\n\n- **`prometheus_prefix?`** ++\"string\"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`.\n- **`db_snapshot?`** ++\"string\"++: Database snapshot to use.\n- **`substrate_cli_args_version?`** ++\"SubstrateCliArgsVersion\"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead.\n\n ??? child \"`SubstrateCliArgsVersion` enum definition\"\n ```js\n export enum SubstrateCliArgsVersion {\n V0 = 0,\n V1 = 1,\n V2 = 2,\n V3 = 3,\n }\n ```\n\n- **`resources?`** ++\"Resources\"++: Represent the resources limits/reservations needed by the node.\n\n ??? child \"`Resources` interface definition\"\n ```js\n export interface Resources {\n resources: {\n requests?: {\n memory?: string;\n cpu?: string;\n };\n limits?: {\n memory?: string;\n cpu?: string;\n };\n };\n }\n ```\n\n- **`keystore_key_types?`** ++\"string[]\"++: Defines which keystore keys should be created.\n- **`validator`** ++\"boolean\"++: Pass the `--validator` flag to the command. Defaults to `true`.\n- **`invulnerable`** ++\"boolean\"++: If true, add the node to invulnerables in the chain spec. Defaults to `false`.\n- **`balance`** ++\"number\"++: Balance to set in balances for node's account. Defaults to `2000000000000`.\n- **`bootnodes?`** ++\"string[]\"++: Array of bootnodes to use.\n- **`add_to_bootnodes?`** ++\"boolean\"++: Add this node to the bootnode list. Defaults to `false`.\n- **`ws_port?`** ++\"number\"++: WS port to use.\n- **`rpc_port?`** ++\"number\"++: RPC port to use.\n- **`prometheus_port?`** ++\"number\"++: Prometheus port to use.\n- **`p2p_cert_hash?`** ++\"string\"++: Libp2p certhash to use with webRTC transport.\n- **`delay_network_settings?`** ++\"DelayNetworkSettings\"++: Sets the expected configuration to delay the network.\n\n ??? child \"`DelayNetworkSettings` interface definition\"\n ```js\n export interface DelayNetworkSettings {\n latency: string;\n correlation?: string; // should be parsable as float by k8s\n jitter?: string;\n }\n ```\n\nThe following configuration file defines a minimal example for the relay chain, including the `nodes` key:\n\n=== \"TOML\"\n\n ```toml title=\"relaychain-example-nodes.toml\"\n [relaychain]\n default_command = \"polkadot\"\n default_image = \"polkadot-debug:master\"\n chain = \"rococo-local\"\n chain_spec_path = \"INSERT_PATH_TO_CHAIN_SPEC\"\n default_args = [\"--chain\", \"rococo-local\"]\n\n [[relaychain.nodes]]\n name = \"alice\"\n validator = true\n balance = 1000000000000\n\n [[relaychain.nodes]]\n name = \"bob\"\n validator = true\n balance = 1000000000000\n # ...\n\n ```\n\n=== \"JSON\"\n\n ```json title=\"relaychain-example-nodes.json\"\n {\n \"relaychain\": {\n \"default_command\": \"polkadot\",\n \"default_image\": \"polkadot-debug:master\",\n \"chain\": \"rococo-local\",\n \"chain_spec_path\": \"INSERT_PATH_TO_CHAIN-SPEC.JSON\",\n \"default_args\": [\"--chain\", \"rococo-local\"],\n \"nodes\": [\n {\n \"name\": \"alice\",\n \"validator\": true,\n \"balance\": 1000000000000\n },\n {\n \"name\": \"bob\",\n \"validator\": true,\n \"balance\": 1000000000000\n }\n ]\n }\n }\n\n ```\n\n#### Node Group Configuration\n\nThe `node_groups` key defines further parameters for the node groups. The available keys are:\n\n- **`name`** ++\"string\"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`).\n- **`image?`** ++\"string\"++: Override default Docker image to use for this node.\n- **`command?`** ++\"string\"++: Override default command to run.\n- **`args?`** ++\"string[]\"++: Arguments to be passed to the command.\n- **`env?`** ++\"envVars[]\"++: Environment variables to set in the container.\n \n ??? child \"`envVars` interface definition\"\n ```js\n export interface EnvVars {\n name: string;\n value: string;\n }\n ```\n\n- **`overrides?`** ++\"Override[]\"++: Array of overrides definitions.\n\n ??? child \"`Override` interface definition\"\n ```js\n export interface Override {\n local_path: string;\n remote_name: string;\n }\n ```\n\n- **`prometheus_prefix?`** ++\"string\"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`.\n- **`db_snapshot?`** ++\"string\"++: Database snapshot to use.\n- **`substrate_cli_args_version?`** ++\"SubstrateCliArgsVersion\"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead.\n\n ??? child \"`SubstrateCliArgsVersion` enum definition\"\n ```js\n export enum SubstrateCliArgsVersion {\n V0 = 0,\n V1 = 1,\n V2 = 2,\n V3 = 3,\n }\n ```\n\n- **`resources?`** ++\"Resources\"++: Represent the resources limits/reservations needed by the node.\n\n ??? child \"`Resources` interface definition\"\n ```js\n export interface Resources {\n resources: {\n requests?: {\n memory?: string;\n cpu?: string;\n };\n limits?: {\n memory?: string;\n cpu?: string;\n };\n };\n }\n ```\n\n- **`keystore_key_types?`** ++\"string[]\"++: Defines which keystore keys should be created.\n- **`count`** ++\"number | string\"++: Number of nodes to launch for this group.\n- **`delay_network_settings?`** ++\"DelayNetworkSettings\"++: Sets the expected configuration to delay the network.\n\n ??? child \"`DelayNetworkSettings` interface definition\"\n ```js\n export interface DelayNetworkSettings {\n latency: string;\n correlation?: string; // should be parsable as float by k8s\n jitter?: string;\n }\n ```\n\nThe following configuration file defines a minimal example for the relay chain, including the `node_groups` key:\n\n=== \"TOML\"\n\n ```toml title=\"relaychain-example-node-groups.toml\"\n [relaychain]\n default_command = \"polkadot\"\n default_image = \"polkadot-debug:master\"\n chain = \"rococo-local\"\n chain_spec_path = \"INSERT_PATH_TO_CHAIN_SPEC\"\n default_args = [\"--chain\", \"rococo-local\"]\n\n [[relaychain.node_groups]]\n name = \"group-1\"\n count = 2\n image = \"polkadot-debug:master\"\n command = \"polkadot\"\n args = [\"--chain\", \"rococo-local\"]\n # ...\n\n ```\n\n=== \"JSON\"\n\n ```json title=\"relaychain-example-node-groups.json\"\n {\n \"relaychain\": {\n \"default_command\": \"polkadot\",\n \"default_image\": \"polkadot-debug:master\",\n \"chain\": \"rococo-local\",\n \"chain_spec_path\": \"INSERT_PATH_TO_CHAIN-SPEC.JSON\",\n \"default_args\": [\"--chain\", \"rococo-local\"],\n \"node_groups\": [\n {\n \"name\": \"group-1\",\n \"count\": 2,\n \"image\": \"polkadot-debug:master\",\n \"command\": \"polkadot\",\n \"args\": [\"--chain\", \"rococo-local\"]\n }\n ],\n \"...\": {}\n },\n \"...\": {}\n }\n\n ```"} -{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Get Started", "index": 11, "depth": 3, "title": "Parachain Configuration", "anchor": "parachain-configuration", "start_char": 28518, "end_char": 39691, "estimated_token_count": 2716, "token_estimator": "heuristic-v1", "text": "### Parachain Configuration\n\nThe `parachain` keyword defines further parameters for the parachain. The available keys are:\n\n- **`id`** ++\"number\"++: The id to assign to this parachain. Must be unique.\n- **`chain?`** ++\"string\"++: The chain name.\n- **`force_decorator?`** ++\"string\"++: Force the use of a specific decorator.\n- **`genesis?`** ++\"JSON\"++: The genesis configuration.\n- **`balance?`** ++\"number\"++: Balance to set in balances for parachain's account.\n- **`delay_network_settings?`** ++\"DelayNetworkSettings\"++: Sets the expected configuration to delay the network.\n\n ??? child \"`DelayNetworkSettings` interface definition\"\n ```js\n export interface DelayNetworkSettings {\n latency: string;\n correlation?: string; // should be parsable as float by k8s\n jitter?: string;\n }\n ```\n\n- **`add_to_genesis?`** ++\"boolean\"++: Flag to add parachain to genesis or register in runtime. Defaults to `true`.\n- **`register_para?`** ++\"boolean\"++: Flag to specify whether the para should be registered. The `add_to_genesis` flag must be set to false for this flag to have any effect. Defaults to `true`.\n- **`onboard_as_parachain?`** ++\"boolean\"++: Flag to specify whether the para should be onboarded as a parachain, rather than remaining a parathread. Defaults to `true`.\n- **`genesis_wasm_path?`** ++\"string\"++: Path to the Wasm file to use.\n- **`genesis_wasm_generator?`** ++\"string\"++: Command to generate the Wasm file.\n- **`genesis_state_path?`** ++\"string\"++: Path to the state file to use.\n- **`genesis_state_generator?`** ++\"string\"++: Command to generate the state file.\n- **`chain_spec_path?`** ++\"string\"++: Path to the chain spec file.\n- **`chain_spec_command?`** ++\"string\"++: Command to generate the chain spec.\n- **`cumulus_based?`** ++\"boolean\"++: Flag to use cumulus command generation. Defaults to `true`.\n- **`bootnodes?`** ++\"string[]\"++: Array of bootnodes to use.\n- **`prometheus_prefix?`** ++\"string\"++: Parameter for customizing the metric's prefix for all parachain nodes/collators. Defaults to `substrate`.\n- **`collator?`** ++\"Collator\"++: Further defined in the [Collator Configuration](#collator-configuration) section.\n- **`collator_groups?`** ++\"CollatorGroup[]\"++: An array of collator groups to spawn. It is further defined in the [Collator Groups Configuration](#collator-groups-configuration) section.\n \nFor example, the following configuration file defines a minimal example for the parachain:\n\n=== \"TOML\"\n\n ```toml title=\"parachain-example.toml\"\n [parachain]\n id = 100\n add_to_genesis = true\n cumulus_based = true\n genesis_wasm_path = \"INSERT_PATH_TO_WASM\"\n genesis_state_path = \"INSERT_PATH_TO_STATE\"\n # ...\n\n ```\n\n=== \"JSON\"\n\n ```json title=\"parachain-example.json\"\n {\n \"parachain\": {\n \"id\": 100,\n \"add_to_genesis\": true,\n \"cumulus_based\": true,\n \"genesis_wasm_path\": \"INSERT_PATH_TO_WASM\",\n \"genesis_state_path\": \"INSERT_PATH_TO_STATE\",\n \"...\": {}\n },\n \"...\": {}\n }\n\n ```\n\n#### Collator Configuration\n\nOne specific key capable of receiving more subkeys is the `collator` key. This key defines further parameters for the nodes. The available keys are:\n\n- **`name`** ++\"string\"++: Name of the collator. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`).\n- **`image?`** ++\"string\"++: Image to use for the collator.\n- **`command_with_args?`** ++\"string\"++: Overrides both command and arguments for the collator.\n- **`validator`** ++\"boolean\"++: Pass the `--validator` flag to the command. Defaults to `true`.\n- **`invulnerable`** ++\"boolean\"++: If true, add the collator to invulnerables in the chain spec. Defaults to `false`.\n- **`balance`** ++\"number\"++: Balance to set in balances for collator's account. Defaults to `2000000000000`.\n- **`bootnodes?`** ++\"string[]\"++: Array of bootnodes to use.\n- **`add_to_bootnodes?`** ++\"boolean\"++: Add this collator to the bootnode list. Defaults to `false`.\n- **`ws_port?`** ++\"number\"++: WS port to use.\n- **`rpc_port?`** ++\"number\"++: RPC port to use.\n- **`prometheus_port?`** ++\"number\"++: Prometheus port to use.\n- **`p2p_port?`** ++\"number\"++: P2P port to use.\n- **`p2p_cert_hash?`** ++\"string\"++: Libp2p certhash to use with webRTC transport.\n- **`delay_network_settings?`** ++\"DelayNetworkSettings\"++: Sets the expected configuration to delay the network.\n\n ??? child \"`DelayNetworkSettings` interface definition\"\n ```js\n export interface DelayNetworkSettings {\n latency: string;\n correlation?: string; // should be parsable as float by k8s\n jitter?: string;\n }\n ```\n\n- **`command?`** ++\"string\"++: Override default command to run.\n- **`args?`** ++\"string[]\"++: Arguments to be passed to the command.\n- **`env?`** ++\"envVars[]\"++: Environment variables to set in the container.\n\n ??? child \"`envVars` interface definition\"\n ```js\n export interface EnvVars {\n name: string;\n value: string;\n }\n ```\n\n- **`overrides?`** ++\"Override[]\"++: Array of overrides definitions.\n\n ??? child \"`Override` interface definition\"\n ```js\n export interface Override {\n local_path: string;\n remote_name: string;\n }\n ```\n\n- **`prometheus_prefix?`** ++\"string\"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`.\n- **`db_snapshot?`** ++\"string\"++: Database snapshot to use.\n- **`substrate_cli_args_version?`** ++\"SubstrateCliArgsVersion\"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead.\n\n ??? child \"`SubstrateCliArgsVersion` enum definition\"\n ```js\n export enum SubstrateCliArgsVersion {\n V0 = 0,\n V1 = 1,\n V2 = 2,\n V3 = 3,\n }\n ```\n\n- **`resources?`** ++\"Resources\"++: Represent the resources limits/reservations needed by the node.\n\n ??? child \"`Resources` interface definition\"\n ```js\n export interface Resources {\n resources: {\n requests?: {\n memory?: string;\n cpu?: string;\n };\n limits?: {\n memory?: string;\n cpu?: string;\n };\n };\n }\n ```\n\n- **`keystore_key_types?`** ++\"string[]\"++: Defines which keystore keys should be created.\n\nThe configuration file below defines a minimal example for the collator:\n\n=== \"TOML\"\n\n ```toml title=\"collator-example.toml\"\n [parachain]\n id = 100\n add_to_genesis = true\n cumulus_based = true\n genesis_wasm_path = \"INSERT_PATH_TO_WASM\"\n genesis_state_path = \"INSERT_PATH_TO_STATE\"\n\n [[parachain.collators]]\n name = \"alice\"\n image = \"polkadot-parachain\"\n command = \"polkadot-parachain\"\n # ...\n\n ```\n\n=== \"JSON\"\n\n ```json title=\"collator-example.json\"\n {\n \"parachain\": {\n \"id\": 100,\n \"add_to_genesis\": true,\n \"cumulus_based\": true,\n \"genesis_wasm_path\": \"INSERT_PATH_TO_WASM\",\n \"genesis_state_path\": \"INSERT_PATH_TO_STATE\",\n \"collators\": [\n {\n \"name\": \"alice\",\n \"image\": \"polkadot-parachain\",\n \"command\": \"polkadot-parachain\",\n \"...\": {}\n }\n ]\n },\n \"...\": {}\n }\n\n ```\n\n#### Collator Groups Configuration\n\nThe `collator_groups` key defines further parameters for the collator groups. The available keys are:\n\n- **`name`** ++\"string\"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`).\n- **`image?`** ++\"string\"++: Override default Docker image to use for this node.\n- **`command?`** ++\"string\"++: Override default command to run.\n- **`args?`** ++\"string[]\"++: Arguments to be passed to the command.\n- **`env?`** ++\"envVars[]\"++: Environment variables to set in the container.\n\n ??? child \"`envVars` interface definition\"\n ```js\n export interface EnvVars {\n name: string;\n value: string;\n }\n ```\n\n- **`overrides?`** ++\"Override[]\"++: Array of overrides definitions.\n\n ??? child \"`Override` interface definition\"\n ```js\n export interface Override {\n local_path: string;\n remote_name: string;\n }\n ```\n\n- **`prometheus_prefix?`** ++\"string\"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`.\n- **`db_snapshot?`** ++\"string\"++: Database snapshot to use.\n- **`substrate_cli_args_version?`** ++\"SubstrateCliArgsVersion\"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead.\n\n ??? child \"`SubstrateCliArgsVersion` enum definition\"\n ```js\n export enum SubstrateCliArgsVersion {\n V0 = 0,\n V1 = 1,\n V2 = 2,\n V3 = 3,\n }\n ```\n\n- **`resources?`** ++\"Resources\"++: Represent the resources limits/reservations needed by the node.\n\n ??? child \"`Resources` interface definition\"\n ```js\n export interface Resources {\n resources: {\n requests?: {\n memory?: string;\n cpu?: string;\n };\n limits?: {\n memory?: string;\n cpu?: string;\n };\n };\n }\n ```\n\n- **`keystore_key_types?`** ++\"string[]\"++: Defines which keystore keys should be created.\n- **`count`** ++\"number | string\"++: Number of nodes to launch for this group.\n- **`delay_network_settings?`** ++\"DelayNetworkSettings\"++: Sets the expected configuration to delay the network.\n\n ??? child \"`DelayNetworkSettings` interface definition\"\n ```js\n export interface DelayNetworkSettings {\n latency: string;\n correlation?: string; // should be parsable as float by k8s\n jitter?: string;\n }\n ```\n\nFor instance, the configuration file below defines a minimal example for the collator groups:\n\n=== \"TOML\"\n\n ```toml title=\"collator-groups-example.toml\"\n [parachain]\n id = 100\n add_to_genesis = true\n cumulus_based = true\n genesis_wasm_path = \"INSERT_PATH_TO_WASM\"\n genesis_state_path = \"INSERT_PATH_TO_STATE\"\n\n [[parachain.collator_groups]]\n name = \"group-1\"\n count = 2\n image = \"polkadot-parachain\"\n command = \"polkadot-parachain\"\n # ...\n\n ```\n\n=== \"JSON\"\n\n ```json title=\"collator-groups-example.json\"\n {\n \"parachain\": {\n \"id\": 100,\n \"add_to_genesis\": true,\n \"cumulus_based\": true,\n \"genesis_wasm_path\": \"INSERT_PATH_TO_WASM\",\n \"genesis_state_path\": \"INSERT_PATH_TO_STATE\",\n \"collator_groups\": [\n {\n \"name\": \"group-1\",\n \"count\": 2,\n \"image\": \"polkadot-parachain\",\n \"command\": \"polkadot-parachain\",\n \"...\": {}\n }\n ]\n },\n \"...\": {}\n }\n\n ```"} -{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Get Started", "index": 12, "depth": 3, "title": "XCM Configuration", "anchor": "xcm-configuration", "start_char": 39691, "end_char": 40622, "estimated_token_count": 206, "token_estimator": "heuristic-v1", "text": "### XCM Configuration\n\nYou can use the `hrmp_channels` keyword to define further parameters for the XCM channels at start-up. The available keys are:\n\n- **`hrmp_channels`** ++\"HrmpChannelsConfig[]\"++: Array of Horizontal Relay-routed Message Passing (HRMP) channel configurations.\n\n ??? child \"`HrmpChannelsConfig` interface definition\"\n ```js\n export interface HrmpChannelsConfig {\n sender: number;\n recipient: number;\n max_capacity: number;\n max_message_size: number;\n }\n ```\n Each of the `HrmpChannelsConfig` keys are defined as follows:\n\n - **`sender` ++\"number\"++**: Parachain ID of the sender.\n - **`recipient` ++\"number\"++**: Parachain ID of the recipient.\n - **`max_capacity` ++\"number\"++**: Maximum capacity of the HRMP channel.\n - **`max_message_size` ++\"number\"++**: Maximum message size allowed in the HRMP channel."} -{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Get Started", "index": 13, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 40622, "end_char": 41636, "estimated_token_count": 254, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\n
\n\n- External __Zombienet Support__\n\n ---\n\n [Parity Technologies](https://www.parity.io/){target=\\_blank} has designed and developed this framework, now maintained by the Zombienet team. \n\n For further support and information, refer to the following contact points:\n\n [:octicons-arrow-right-24: Zombienet repository](https://github.com/paritytech/zombienet){target=\\_blank}\n\n [:octicons-arrow-right-24: Element public channel](https://matrix.to/#/!FWyuEyNvIFygLnWNMh:parity.io?via=parity.io&via=matrix.org&via=web3.foundation){target=\\_blank}\n\n\n- Tutorial __Spawn a Basic Chain with Zombienet__\n\n ---\n\n Learn to spawn, connect to and monitor a basic blockchain network with Zombienet, using customizable configurations for streamlined development and debugging.\n\n [:octicons-arrow-right-24: Reference](/tutorials/polkadot-sdk/testing/spawn-basic-chain/)\n\n
"} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 0, "depth": 2, "title": "Authority", "anchor": "authority", "start_char": 416, "end_char": 897, "estimated_token_count": 119, "token_estimator": "heuristic-v1", "text": "## Authority\n\nThe role in a blockchain that can participate in consensus mechanisms. \n\n- **[GRANDPA](#grandpa)**: The authorities vote on chains they consider final.\n- **[Blind Assignment of Blockchain Extension](#blind-assignment-of-blockchain-extension-babe) (BABE)**: The authorities are also [block authors](#block-author).\n\nAuthority sets can be used as a basis for consensus mechanisms such as the [Nominated Proof of Stake (NPoS)](#nominated-proof-of-stake-npos) protocol."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 1, "depth": 2, "title": "Authority Round (Aura)", "anchor": "authority-round-aura", "start_char": 897, "end_char": 1416, "estimated_token_count": 118, "token_estimator": "heuristic-v1", "text": "## Authority Round (Aura)\n\nA deterministic [consensus](#consensus) protocol where block production is limited to a rotating list of [authorities](#authority) that take turns creating blocks. In authority round (Aura) consensus, most online authorities are assumed to be honest. It is often used in combination with [GRANDPA](#grandpa) as a [hybrid consensus](#hybrid-consensus) protocol.\n\nLearn more by reading the official [Aura consensus algorithm](https://openethereum.github.io/Aura){target=\\_blank} wiki article."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 2, "depth": 2, "title": "Blind Assignment of Blockchain Extension (BABE)", "anchor": "blind-assignment-of-blockchain-extension-babe", "start_char": 1416, "end_char": 1930, "estimated_token_count": 124, "token_estimator": "heuristic-v1", "text": "## Blind Assignment of Blockchain Extension (BABE)\n\nA [block authoring](#block-author) protocol similar to [Aura](#authority-round-aura), except [authorities](#authority) win [slots](#slot) based on a Verifiable Random Function (VRF) instead of the round-robin selection method. The winning authority can select a chain and submit a new block.\n\nLearn more by reading the official Web3 Foundation [BABE research document](https://research.web3.foundation/Polkadot/protocols/block-production/Babe){target=\\_blank}."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 3, "depth": 2, "title": "Block Author", "anchor": "block-author", "start_char": 1930, "end_char": 2099, "estimated_token_count": 35, "token_estimator": "heuristic-v1", "text": "## Block Author\n\nThe node responsible for the creation of a block, also called _block producers_. In a Proof of Work (PoW) blockchain, these nodes are called _miners_."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 4, "depth": 2, "title": "Byzantine Fault Tolerance (BFT)", "anchor": "byzantine-fault-tolerance-bft", "start_char": 2099, "end_char": 2527, "estimated_token_count": 79, "token_estimator": "heuristic-v1", "text": "## Byzantine Fault Tolerance (BFT)\n\nThe ability of a distributed computer network to remain operational if a certain proportion of its nodes or [authorities](#authority) are defective or behaving maliciously. A distributed network is typically considered Byzantine fault tolerant if it can remain functional, with up to one-third of nodes assumed to be defective, offline, actively malicious, and part of a coordinated attack."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 5, "depth": 3, "title": "Byzantine Failure", "anchor": "byzantine-failure", "start_char": 2527, "end_char": 2667, "estimated_token_count": 26, "token_estimator": "heuristic-v1", "text": "### Byzantine Failure\n\nThe loss of a network service due to node failures that exceed the proportion of nodes required to reach consensus."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 6, "depth": 3, "title": "Practical Byzantine Fault Tolerance (pBFT)", "anchor": "practical-byzantine-fault-tolerance-pbft", "start_char": 2667, "end_char": 3007, "estimated_token_count": 71, "token_estimator": "heuristic-v1", "text": "### Practical Byzantine Fault Tolerance (pBFT)\n\nAn early approach to Byzantine fault tolerance (BFT), practical Byzantine fault tolerance (pBFT) systems tolerate Byzantine behavior from up to one-third of participants.\n\nThe communication overhead for such systems is `O(n²)`, where `n` is the number of nodes (participants) in the system."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 7, "depth": 3, "title": "Preimage", "anchor": "preimage", "start_char": 3007, "end_char": 3284, "estimated_token_count": 74, "token_estimator": "heuristic-v1", "text": "### Preimage\n\nA preimage is the data that is input into a hash function to calculate a hash. Since a hash function is a [one-way function](https://en.wikipedia.org/wiki/One-way_function){target=\\_blank}, the output, the hash, cannot be used to reveal the input, the preimage."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 8, "depth": 2, "title": "Call", "anchor": "call", "start_char": 3284, "end_char": 3561, "estimated_token_count": 56, "token_estimator": "heuristic-v1", "text": "## Call\n\nIn the context of pallets containing functions to be dispatched to the runtime, `Call` is an enumeration data type that describes the functions that can be dispatched with one variant per pallet. A `Call` represents a [dispatch](#dispatchable) data structure object."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 9, "depth": 2, "title": "Chain Specification", "anchor": "chain-specification", "start_char": 3561, "end_char": 4014, "estimated_token_count": 84, "token_estimator": "heuristic-v1", "text": "## Chain Specification \n\nA chain specification file defines the properties required to run a node in an active or new Polkadot SDK-built network. It often contains the initial genesis runtime code, network properties (such as the network's name), the initial state for some pallets, and the boot node list. The chain specification file makes it easy to use a single Polkadot SDK codebase as the foundation for multiple independently configured chains."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 10, "depth": 2, "title": "Collator", "anchor": "collator", "start_char": 4014, "end_char": 4353, "estimated_token_count": 98, "token_estimator": "heuristic-v1", "text": "## Collator\n\nAn [author](#block-author) of a [parachain](#parachain) network.\nThey aren't [authorities](#authority) in themselves, as they require a [relay chain](#relay-chain) to coordinate [consensus](#consensus).\n\nMore details are found on the [Polkadot Collator Wiki](https://wiki.polkadot.com/learn/learn-collator/){target=\\_blank}."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 11, "depth": 2, "title": "Collective", "anchor": "collective", "start_char": 4353, "end_char": 4593, "estimated_token_count": 54, "token_estimator": "heuristic-v1", "text": "## Collective\n\nMost often used to refer to an instance of the Collective pallet on Polkadot SDK-based networks such as [Kusama](#kusama) or [Polkadot](#polkadot) if the Collective pallet is part of the FRAME-based runtime for the network."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 12, "depth": 2, "title": "Consensus", "anchor": "consensus", "start_char": 4593, "end_char": 4984, "estimated_token_count": 86, "token_estimator": "heuristic-v1", "text": "## Consensus\n\nConsensus is the process blockchain nodes use to agree on a chain's canonical fork. It is composed of [authorship](#block-author), finality, and [fork-choice rule](#fork-choice-rulestrategy). In the Polkadot ecosystem, these three components are usually separate and the term consensus often refers specifically to authorship.\n\nSee also [hybrid consensus](#hybrid-consensus)."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 13, "depth": 2, "title": "Consensus Algorithm", "anchor": "consensus-algorithm", "start_char": 4984, "end_char": 5546, "estimated_token_count": 120, "token_estimator": "heuristic-v1", "text": "## Consensus Algorithm\n\nEnsures a set of [actors](#authority)—who don't necessarily trust each other—can reach an agreement about the state as the result of some computation. Most consensus algorithms assume that up to one-third of the actors or nodes can be [Byzantine fault tolerant](#byzantine-fault-tolerance-bft).\n\nConsensus algorithms are generally concerned with ensuring two properties:\n\n- **Safety**: Indicating that all honest nodes eventually agreed on the state of the chain.\n- **Liveness**: Indicating the ability of the chain to keep progressing."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 14, "depth": 2, "title": "Consensus Engine", "anchor": "consensus-engine", "start_char": 5546, "end_char": 5885, "estimated_token_count": 77, "token_estimator": "heuristic-v1", "text": "## Consensus Engine\n\nThe node subsystem responsible for consensus tasks.\n\nFor detailed information about the consensus strategies of the [Polkadot](#polkadot) network, see the [Polkadot Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\\_blank} blog series.\n\nSee also [hybrid consensus](#hybrid-consensus)."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 15, "depth": 2, "title": "Coretime", "anchor": "coretime", "start_char": 5885, "end_char": 6685, "estimated_token_count": 177, "token_estimator": "heuristic-v1", "text": "## Coretime\n\nThe time allocated for utilizing a core, measured in relay chain blocks. There are two types of coretime: *on-demand* and *bulk*.\n\nOn-demand coretime refers to coretime acquired through bidding in near real-time for the validation of a single parachain block on one of the cores reserved specifically for on-demand orders. They are available as an on-demand coretime pool. Set of cores that are available on-demand. Cores reserved through bulk coretime could also be made available in the on-demand coretime pool, in parts or in entirety.\n\nBulk coretime is a fixed duration of continuous coretime represented by an NFT that can be split, shared, or resold. It is managed by the [Broker pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_broker/index.html){target=\\_blank}."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 16, "depth": 2, "title": "Development Phrase", "anchor": "development-phrase", "start_char": 6685, "end_char": 7343, "estimated_token_count": 157, "token_estimator": "heuristic-v1", "text": "## Development Phrase\n\nA [mnemonic phrase](https://en.wikipedia.org/wiki/Mnemonic#For_numerical_sequences_and_mathematical_operations){target=\\_blank} that is intentionally made public.\n\nWell-known development accounts, such as Alice, Bob, Charlie, Dave, Eve, and Ferdie, are generated from the same secret phrase:\n\n```\nbottom drive obey lake curtain smoke basket hold race lonely fit walk\n```\n\nMany tools in the Polkadot SDK ecosystem, such as [`subkey`](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/bin/utils/subkey){target=\\_blank}, allow you to implicitly specify an account using a derivation path such as `//Alice`."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 17, "depth": 2, "title": "Digest", "anchor": "digest", "start_char": 7343, "end_char": 7655, "estimated_token_count": 66, "token_estimator": "heuristic-v1", "text": "## Digest\n\nAn extensible field of the [block header](#header) that encodes information needed by several actors in a blockchain network, including:\n\n- [Light clients](#light-client) for chain synchronization.\n- Consensus engines for block verification.\n- The runtime itself, in the case of pre-runtime digests."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 18, "depth": 2, "title": "Dispatchable", "anchor": "dispatchable", "start_char": 7655, "end_char": 7953, "estimated_token_count": 62, "token_estimator": "heuristic-v1", "text": "## Dispatchable\n\nFunction objects that act as the entry points in FRAME [pallets](#pallet). Internal or external entities can call them to interact with the blockchain’s state. They are a core aspect of the runtime logic, handling [transactions](#transaction) and other state-changing operations."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 19, "depth": 2, "title": "Events", "anchor": "events", "start_char": 7953, "end_char": 8385, "estimated_token_count": 90, "token_estimator": "heuristic-v1", "text": "## Events\n\nA means of recording that some particular [state](#state) transition happened.\n\nIn the context of [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities), events are composable data types that each [pallet](#pallet) can individually define. Events in FRAME are implemented as a set of transient storage items inspected immediately after a block has been executed and reset during block initialization."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 20, "depth": 2, "title": "Executor", "anchor": "executor", "start_char": 8385, "end_char": 9021, "estimated_token_count": 134, "token_estimator": "heuristic-v1", "text": "## Executor\n\nA means of executing a function call in a given [runtime](#runtime) with a set of dependencies.\nThere are two orchestration engines in Polkadot SDK, _WebAssembly_ and _native_.\n\n- The _native executor_ uses a natively compiled runtime embedded in the node to execute calls. This is a performance optimization available to up-to-date nodes.\n\n- The _WebAssembly executor_ uses a [Wasm](#webassembly-wasm) binary and a Wasm interpreter to execute calls. The binary is guaranteed to be up-to-date regardless of the version of the blockchain node because it is persisted in the [state](#state) of the Polkadot SDK-based chain."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 21, "depth": 2, "title": "Existential Deposit", "anchor": "existential-deposit", "start_char": 9021, "end_char": 9761, "estimated_token_count": 179, "token_estimator": "heuristic-v1", "text": "## Existential Deposit\n\nThe minimum balance an account is allowed to have in the [Balances pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/index.html){target=\\_blank}. Accounts cannot be created with a balance less than the existential deposit amount. \n\nIf an account balance drops below this amount, the Balances pallet uses [a FRAME System API](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.dec_ref){target=\\_blank} to drop its references to that account.\n\nIf the Balances pallet reference to an account is dropped, the account can be [reaped](https://paritytech.github.io/substrate/master/frame_system/pallet/struct.Pallet.html#method.allow_death){target=\\_blank}."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 22, "depth": 2, "title": "Extrinsic", "anchor": "extrinsic", "start_char": 9761, "end_char": 10377, "estimated_token_count": 130, "token_estimator": "heuristic-v1", "text": "## Extrinsic\n\nA general term for data that originates outside the runtime, is included in a block, and leads to some action. This includes user-initiated transactions and inherent transactions placed into the block by the block builder.\n\nIt is a SCALE-encoded array typically consisting of a version number, signature, and varying data types indicating the resulting runtime function to be called. Extrinsics can take two forms: [inherents](#inherent-transactions) and [transactions](#transaction). \n\nFor more technical details, see the [Polkadot spec](https://spec.polkadot.network/id-extrinsics){target=\\_blank}."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 23, "depth": 2, "title": "Fork Choice Rule/Strategy", "anchor": "fork-choice-rulestrategy", "start_char": 10377, "end_char": 10723, "estimated_token_count": 79, "token_estimator": "heuristic-v1", "text": "## Fork Choice Rule/Strategy\n\nA fork choice rule or strategy helps determine which chain is valid when reconciling several network forks. A common fork choice rule is the [longest chain](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/struct.LongestChain.html){target=\\_blank}, in which the chain with the most blocks is selected."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 24, "depth": 2, "title": "FRAME (Framework for Runtime Aggregation of Modularized Entities)", "anchor": "frame-framework-for-runtime-aggregation-of-modularized-entities", "start_char": 10723, "end_char": 11169, "estimated_token_count": 97, "token_estimator": "heuristic-v1", "text": "## FRAME (Framework for Runtime Aggregation of Modularized Entities)\n\nEnables developers to create blockchain [runtime](#runtime) environments from a modular set of components called [pallets](#pallet). It utilizes a set of procedural macros to construct runtimes.\n\n[Visit the Polkadot SDK docs for more details on FRAME.](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\\_blank}"} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 25, "depth": 2, "title": "Full Node", "anchor": "full-node", "start_char": 11169, "end_char": 11448, "estimated_token_count": 48, "token_estimator": "heuristic-v1", "text": "## Full Node\n\nA node that prunes historical states, keeping only recently finalized block states to reduce storage needs. Full nodes provide current chain state access and allow direct submission and validation of [extrinsics](#extrinsic), maintaining network decentralization."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 26, "depth": 2, "title": "Genesis Configuration", "anchor": "genesis-configuration", "start_char": 11448, "end_char": 11783, "estimated_token_count": 63, "token_estimator": "heuristic-v1", "text": "## Genesis Configuration\n\nA mechanism for specifying the initial state of a blockchain. By convention, this initial state or first block is commonly referred to as the genesis state or genesis block. The genesis configuration for Polkadot SDK-based chains is accomplished by way of a [chain specification](#chain-specification) file."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 27, "depth": 2, "title": "GRANDPA", "anchor": "grandpa", "start_char": 11783, "end_char": 12139, "estimated_token_count": 101, "token_estimator": "heuristic-v1", "text": "## GRANDPA\n\nA deterministic finality mechanism for blockchains that is implemented in the [Rust](https://www.rust-lang.org/){target=\\_blank} programming language.\n\nThe [formal specification](https://github.com/w3f/consensus/blob/master/pdf/grandpa-old.pdf){target=\\_blank} is maintained by the [Web3 Foundation](https://web3.foundation/){target=\\_blank}."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 28, "depth": 2, "title": "Header", "anchor": "header", "start_char": 12139, "end_char": 12379, "estimated_token_count": 44, "token_estimator": "heuristic-v1", "text": "## Header\n\nA structure that aggregates the information used to summarize a block. Primarily, it consists of cryptographic information used by [light clients](#light-client) to get minimally secure but very efficient chain synchronization."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 29, "depth": 2, "title": "Hybrid Consensus", "anchor": "hybrid-consensus", "start_char": 12379, "end_char": 12793, "estimated_token_count": 81, "token_estimator": "heuristic-v1", "text": "## Hybrid Consensus\n\nA blockchain consensus protocol that consists of independent or loosely coupled mechanisms for [block production](#block-author) and finality.\n\nHybrid consensus allows the chain to grow as fast as probabilistic consensus protocols, such as [Aura](#authority-round-aura), while maintaining the same level of security as deterministic finality consensus protocols, such as [GRANDPA](#grandpa)."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 30, "depth": 2, "title": "Inherent Transactions", "anchor": "inherent-transactions", "start_char": 12793, "end_char": 13259, "estimated_token_count": 81, "token_estimator": "heuristic-v1", "text": "## Inherent Transactions\n\nA special type of unsigned transaction, referred to as _inherents_, that enables a block authoring node to insert information that doesn't require validation directly into a block.\n\nOnly the block-authoring node that calls the inherent transaction function can insert data into its block. In general, validators assume the data inserted using an inherent transaction is valid and reasonable even if it can't be deterministically verified."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 31, "depth": 2, "title": "JSON-RPC", "anchor": "json-rpc", "start_char": 13259, "end_char": 13600, "estimated_token_count": 77, "token_estimator": "heuristic-v1", "text": "## JSON-RPC\n\nA stateless, lightweight remote procedure call protocol encoded in JavaScript Object Notation (JSON). JSON-RPC provides a standard way to call functions on a remote system by using JSON.\n\nFor Polkadot SDK, this protocol is implemented through the [Parity JSON-RPC](https://github.com/paritytech/jsonrpc){target=\\_blank} crate."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 32, "depth": 2, "title": "Keystore", "anchor": "keystore", "start_char": 13600, "end_char": 13685, "estimated_token_count": 16, "token_estimator": "heuristic-v1", "text": "## Keystore\n\nA subsystem for managing keys for the purpose of producing new blocks."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 33, "depth": 2, "title": "Kusama", "anchor": "kusama", "start_char": 13685, "end_char": 14379, "estimated_token_count": 174, "token_estimator": "heuristic-v1", "text": "## Kusama\n\n[Kusama](https://kusama.network/){target=\\_blank} is a Polkadot SDK-based blockchain that implements a design similar to the [Polkadot](#polkadot) network.\n\nKusama is a [canary](https://en.wiktionary.org/wiki/canary_in_a_coal_mine){target=\\_blank} network and is referred to as [Polkadot's \"wild cousin.\"](https://wiki.polkadot.com/learn/learn-comparisons-kusama/){target=\\_blank}.\n\nAs a canary network, Kusama is expected to be more stable than a test network like [Westend](#westend) but less stable than a production network like [Polkadot](#polkadot). Kusama is controlled by its network participants and is intended to be stable enough to encourage meaningful experimentation."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 34, "depth": 2, "title": "libp2p", "anchor": "libp2p", "start_char": 14379, "end_char": 14655, "estimated_token_count": 67, "token_estimator": "heuristic-v1", "text": "## libp2p\n\nA peer-to-peer networking stack that allows the use of many transport mechanisms, including WebSockets (usable in a web browser).\n\nPolkadot SDK uses the [Rust implementation](https://github.com/libp2p/rust-libp2p){target=\\_blank} of the `libp2p` networking stack."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 35, "depth": 2, "title": "Light Client", "anchor": "light-client", "start_char": 14655, "end_char": 14993, "estimated_token_count": 77, "token_estimator": "heuristic-v1", "text": "## Light Client\n\nA type of blockchain node that doesn't store the [chain state](#state) or produce blocks.\n\nA light client can verify cryptographic primitives and provides a [remote procedure call (RPC)](https://en.wikipedia.org/wiki/Remote_procedure_call){target=\\_blank} server, enabling blockchain users to interact with the network."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 36, "depth": 2, "title": "Metadata", "anchor": "metadata", "start_char": 14993, "end_char": 15189, "estimated_token_count": 34, "token_estimator": "heuristic-v1", "text": "## Metadata\n\nData that provides information about one or more aspects of a system.\nThe metadata that exposes information about a Polkadot SDK blockchain enables you to interact with that system."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 37, "depth": 2, "title": "Nominated Proof of Stake (NPoS)", "anchor": "nominated-proof-of-stake-npos", "start_char": 15189, "end_char": 15416, "estimated_token_count": 51, "token_estimator": "heuristic-v1", "text": "## Nominated Proof of Stake (NPoS)\n\nA method for determining [validators](#validator) or _[authorities](#authority)_ based on a willingness to commit their stake to the proper functioning of one or more block-producing nodes."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 38, "depth": 2, "title": "Oracle", "anchor": "oracle", "start_char": 15416, "end_char": 15653, "estimated_token_count": 42, "token_estimator": "heuristic-v1", "text": "## Oracle\n\nAn entity that connects a blockchain to a non-blockchain data source. Oracles enable the blockchain to access and act upon information from existing data sources and incorporate data from non-blockchain systems and services."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 39, "depth": 2, "title": "Origin", "anchor": "origin", "start_char": 15653, "end_char": 16143, "estimated_token_count": 126, "token_estimator": "heuristic-v1", "text": "## Origin\n\nA [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitive that identifies the source of a [dispatched](#dispatchable) function call into the [runtime](#runtime). The FRAME System pallet defines three built-in [origins](#origin). As a [pallet](#pallet) developer, you can also define custom origins, such as those defined by the [Collective pallet](https://paritytech.github.io/substrate/master/pallet_collective/enum.RawOrigin.html){target=\\_blank}."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 40, "depth": 2, "title": "Pallet", "anchor": "pallet", "start_char": 16143, "end_char": 16434, "estimated_token_count": 75, "token_estimator": "heuristic-v1", "text": "## Pallet\n\nA module that can be used to extend the capabilities of a [FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities)-based [runtime](#runtime).\nPallets bundle domain-specific logic with runtime primitives like [events](#events) and [storage items](#storage-item)."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 41, "depth": 2, "title": "Parachain", "anchor": "parachain", "start_char": 16434, "end_char": 16690, "estimated_token_count": 66, "token_estimator": "heuristic-v1", "text": "## Parachain\n\nA parachain is a blockchain that derives shared infrastructure and security from a _[relay chain](#relay-chain)_.\nYou can learn more about parachains on the [Polkadot Wiki](https://wiki.polkadot.com/learn/learn-parachains/){target=\\_blank}."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 42, "depth": 2, "title": "Paseo", "anchor": "paseo", "start_char": 16690, "end_char": 17144, "estimated_token_count": 95, "token_estimator": "heuristic-v1", "text": "## Paseo\n\nPaseo TestNet provisions testing on Polkadot's \"production\" runtime, which means less chance of feature or code mismatch when developing parachain apps. Specifically, after the [Polkadot Technical fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\\_blank} proposes a runtime upgrade for Polkadot, this TestNet is updated, giving a period where the TestNet will be ahead of Polkadot to allow for testing."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 43, "depth": 2, "title": "Polkadot", "anchor": "polkadot", "start_char": 17144, "end_char": 17445, "estimated_token_count": 71, "token_estimator": "heuristic-v1", "text": "## Polkadot\n\nThe [Polkadot network](https://polkadot.com/){target=\\_blank} is a blockchain that serves as the central hub of a heterogeneous blockchain network. It serves the role of the [relay chain](#relay-chain) and provides shared infrastructure and security to support [parachains](#parachain)."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 44, "depth": 2, "title": "Polkadot Cloud", "anchor": "polkadot-cloud", "start_char": 17445, "end_char": 18083, "estimated_token_count": 97, "token_estimator": "heuristic-v1", "text": "## Polkadot Cloud\n\nPolkadot Cloud is a platform for deploying resilient, customizable and scalable Web3 applications through Polkadot's functionality. It encompasses the wider Polkadot network infrastructure and security layer where parachains operate. The platform enables users to launch Ethereum-compatible chains, build specialized blockchains, and flexibly manage computing resources through on-demand or bulk coretime purchases. Initially launched with basic parachain functionality, Polkadot Cloud has evolved to offer enhanced flexibility with features like coretime, elastic scaling, and async backing for improved performance."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 45, "depth": 2, "title": "Polkadot Hub", "anchor": "polkadot-hub", "start_char": 18083, "end_char": 18491, "estimated_token_count": 68, "token_estimator": "heuristic-v1", "text": "## Polkadot Hub\n\nPolkadot Hub is a Layer 1 platform that serves as the primary entry point to the Polkadot ecosystem, providing essential functionality without requiring parachain deployment. It offers core services including smart contracts, identity management, staking, governance, and interoperability with other ecosystems, making it simple and fast for both builders and users to get started in Web3."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 46, "depth": 2, "title": "PolkaVM", "anchor": "polkavm", "start_char": 18491, "end_char": 18774, "estimated_token_count": 50, "token_estimator": "heuristic-v1", "text": "## PolkaVM\n\nPolkaVM is a custom virtual machine optimized for performance, leveraging a RISC-V-based architecture to support Solidity and any language that compiles to RISC-V. It is specifically designed for the Polkadot ecosystem, enabling smart contract deployment and execution."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 47, "depth": 2, "title": "Relay Chain", "anchor": "relay-chain", "start_char": 18774, "end_char": 19090, "estimated_token_count": 57, "token_estimator": "heuristic-v1", "text": "## Relay Chain\n\nRelay chains are blockchains that provide shared infrastructure and security to the [parachains](#parachain) in the network. In addition to providing [consensus](#consensus) capabilities, relay chains allow parachains to communicate and exchange digital assets without needing to trust one another."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 48, "depth": 2, "title": "Rococo", "anchor": "rococo", "start_char": 19090, "end_char": 19342, "estimated_token_count": 54, "token_estimator": "heuristic-v1", "text": "## Rococo\n\nA [parachain](#parachain) test network for the Polkadot network. The [Rococo](#rococo) network is a Polkadot SDK-based blockchain with an October 14, 2024 deprecation date. Development teams are encouraged to use the Paseo TestNet instead."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 49, "depth": 2, "title": "Runtime", "anchor": "runtime", "start_char": 19342, "end_char": 19679, "estimated_token_count": 73, "token_estimator": "heuristic-v1", "text": "## Runtime\n\nThe runtime represents the [state transition function](#state-transition-function-stf) for a blockchain. In Polkadot SDK, the runtime is stored as a [Wasm](#webassembly-wasm) binary in the chain state. The Runtime is stored under a unique state key and can be modified during the execution of the state transition function."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 50, "depth": 2, "title": "Slot", "anchor": "slot", "start_char": 19679, "end_char": 19959, "estimated_token_count": 79, "token_estimator": "heuristic-v1", "text": "## Slot\n\nA fixed, equal interval of time used by consensus engines such as [Aura](#authority-round-aura) and [BABE](#blind-assignment-of-blockchain-extension-babe). In each slot, a subset of [authorities](#authority) is permitted, or obliged, to [author](#block-author) a block."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 51, "depth": 2, "title": "Sovereign Account", "anchor": "sovereign-account", "start_char": 19959, "end_char": 20461, "estimated_token_count": 91, "token_estimator": "heuristic-v1", "text": "## Sovereign Account\n\nThe unique account identifier for each chain in the relay chain ecosystem. It is often used in cross-consensus (XCM) interactions to sign XCM messages sent to the relay chain or other chains in the ecosystem.\n\nThe sovereign account for each chain is a root-level account that can only be accessed using the Sudo pallet or through governance. The account identifier is calculated by concatenating the Blake2 hash of a specific text string and the registered parachain identifier."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 52, "depth": 2, "title": "SS58 Address Format", "anchor": "ss58-address-format", "start_char": 20461, "end_char": 21014, "estimated_token_count": 128, "token_estimator": "heuristic-v1", "text": "## SS58 Address Format\n\nA public key address based on the Bitcoin [`Base-58-check`](https://en.bitcoin.it/wiki/Base58Check_encoding){target=\\_blank} encoding. Each Polkadot SDK SS58 address uses a `base-58` encoded value to identify a specific account on a specific Polkadot SDK-based chain\n\nThe [canonical `ss58-registry`](https://github.com/paritytech/ss58-registry){target=\\_blank} provides additional details about the address format used by different Polkadot SDK-based chains, including the network prefix and website used for different networks"} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 53, "depth": 2, "title": "State Transition Function (STF)", "anchor": "state-transition-function-stf", "start_char": 21014, "end_char": 21243, "estimated_token_count": 46, "token_estimator": "heuristic-v1", "text": "## State Transition Function (STF)\n\nThe logic of a blockchain that determines how the state changes when a block is processed. In Polkadot SDK, the state transition function is effectively equivalent to the [runtime](#runtime)."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 54, "depth": 2, "title": "Storage Item", "anchor": "storage-item", "start_char": 21243, "end_char": 21606, "estimated_token_count": 92, "token_estimator": "heuristic-v1", "text": "## Storage Item\n\n[FRAME](#frame-framework-for-runtime-aggregation-of-modularized-entities) primitives that provide type-safe data persistence capabilities to the [runtime](#runtime).\nLearn more in the [storage items](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/index.html){target=\\_blank} reference document in the Polkadot SDK."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 55, "depth": 2, "title": "Substrate", "anchor": "substrate", "start_char": 21606, "end_char": 21888, "estimated_token_count": 73, "token_estimator": "heuristic-v1", "text": "## Substrate\n\nA flexible framework for building modular, efficient, and upgradeable blockchains. Substrate is written in the [Rust](https://www.rust-lang.org/){target=\\_blank} programming language and is maintained by [Parity Technologies](https://www.parity.io/){target=\\_blank}."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 56, "depth": 2, "title": "Transaction", "anchor": "transaction", "start_char": 21888, "end_char": 22179, "estimated_token_count": 66, "token_estimator": "heuristic-v1", "text": "## Transaction\n\nAn [extrinsic](#extrinsic) that includes a signature that can be used to verify the account authorizing it inherently or via [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\\_blank}."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 57, "depth": 2, "title": "Transaction Era", "anchor": "transaction-era", "start_char": 22179, "end_char": 22458, "estimated_token_count": 51, "token_estimator": "heuristic-v1", "text": "## Transaction Era\n\nA definable period expressed as a range of block numbers during which a transaction can be included in a block.\nTransaction eras are used to protect against transaction replay attacks if an account is reaped and its replay-protecting nonce is reset to zero."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 58, "depth": 2, "title": "Trie (Patricia Merkle Tree)", "anchor": "trie-patricia-merkle-tree", "start_char": 22458, "end_char": 23204, "estimated_token_count": 155, "token_estimator": "heuristic-v1", "text": "## Trie (Patricia Merkle Tree)\n\nA data structure used to represent sets of key-value pairs and enables the items in the data set to be stored and retrieved using a cryptographic hash. Because incremental changes to the data set result in a new hash, retrieving data is efficient even if the data set is very large. With this data structure, you can also prove whether the data set includes any particular key-value pair without access to the entire data set.\n\nIn Polkadot SDK-based blockchains, state is stored in a trie data structure that supports the efficient creation of incremental digests. This trie is exposed to the [runtime](#runtime) as [a simple key/value map](#storage-item) where both keys and values can be arbitrary byte arrays."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 59, "depth": 2, "title": "Validator", "anchor": "validator", "start_char": 23204, "end_char": 23407, "estimated_token_count": 34, "token_estimator": "heuristic-v1", "text": "## Validator\n\nA validator is a node that participates in the consensus mechanism of the network. Its roles include block production, transaction validation, network integrity, and security maintenance."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 60, "depth": 2, "title": "WebAssembly (Wasm)", "anchor": "webassembly-wasm", "start_char": 23407, "end_char": 23870, "estimated_token_count": 113, "token_estimator": "heuristic-v1", "text": "## WebAssembly (Wasm)\n\nAn execution architecture that allows for the efficient, platform-neutral expression of\ndeterministic, machine-executable logic.\n\n[Wasm](https://webassembly.org/){target=\\_blank} can be compiled from many languages, including\nthe [Rust](https://www.rust-lang.org/){target=\\_blank} programming language. Polkadot SDK-based chains use a Wasm binary to provide portable [runtimes](#runtime) that can be included as part of the chain's state."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 61, "depth": 2, "title": "Weight", "anchor": "weight", "start_char": 23870, "end_char": 24596, "estimated_token_count": 133, "token_estimator": "heuristic-v1", "text": "## Weight\n\nA convention used in Polkadot SDK-based blockchains to measure and manage the time it takes to validate a block.\nPolkadot SDK defines one unit of weight as one picosecond of execution time on reference hardware.\n\nThe maximum block weight should be equivalent to one-third of the target block time with an allocation of one-third each for:\n\n- Block construction\n- Network propagation\n- Import and verification\n\nBy defining weights, you can trade-off the number of transactions per second and the hardware required to maintain the target block time appropriate for your use case. Weights are defined in the runtime, meaning you can tune them using runtime updates to keep up with hardware and software improvements."} -{"page_id": "reference-glossary", "page_title": "Glossary", "index": 62, "depth": 2, "title": "Westend", "anchor": "westend", "start_char": 24596, "end_char": 24739, "estimated_token_count": 32, "token_estimator": "heuristic-v1", "text": "## Westend\n\nWestend is a Parity-maintained, Polkadot SDK-based blockchain that serves as a test network for the [Polkadot](#polkadot) network."} -{"page_id": "reference-governance-origins-tracks", "page_title": "Origins and Tracks", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 22, "end_char": 833, "estimated_token_count": 128, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nPolkadot's OpenGov system empowers decentralized decision-making and active community participation by tailoring the governance process to the impact of proposed changes. Through a system of origins and tracks, OpenGov ensures that every referendum receives the appropriate scrutiny, balancing security, inclusivity, and efficiency.\n\nThis guide will help you understand the role of origins in classifying proposals by privilege and priority. You will learn how tracks guide proposals through tailored stages like voting, confirmation, and enactment and how to select the correct origin for your referendum to align with community expectations and network governance.\n\nOrigins and tracks are vital in streamlining the governance workflow and maintaining Polkadot's resilience and adaptability."} -{"page_id": "reference-governance-origins-tracks", "page_title": "Origins and Tracks", "index": 1, "depth": 2, "title": "Origins", "anchor": "origins", "start_char": 833, "end_char": 1886, "estimated_token_count": 200, "token_estimator": "heuristic-v1", "text": "## Origins\n\nOrigins are the foundation of Polkadot's OpenGov governance system. They categorize proposals by privilege and define their decision-making rules. Each origin corresponds to a specific level of importance and risk, guiding how referendums progress through the governance process.\n\n- High-privilege origins like Root Origin govern critical network changes, such as core software upgrades.\n- Lower-privilege origins like Small Spender handle minor requests, such as community project funding under 10,000 DOT.\n\nProposers select an origin based on the nature of their referendum. Origins determine parameters like approval thresholds, required deposits, and timeframes for voting and confirmation. Each origin is paired with a track, which acts as a roadmap for the proposal's lifecycle, including preparation, voting, and enactment.\n\nFor a detailed list of origins and their associated parameters, see the [Polkadot OpenGov Origins](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/){target=\\_blank} entry in the Polkadot Wiki."} -{"page_id": "reference-governance-origins-tracks", "page_title": "Origins and Tracks", "index": 2, "depth": 2, "title": "Tracks", "anchor": "tracks", "start_char": 1886, "end_char": 2836, "estimated_token_count": 175, "token_estimator": "heuristic-v1", "text": "## Tracks\n\nTracks define a referendum's journey from submission to enactment, tailoring governance parameters to the impact of proposed changes. Each track operates independently and includes several key stages:\n\n- **Preparation**: Time for community discussion before voting begins.\n- **Voting**: Period for token holders to cast their votes.\n- **Decision**: Finalization of results and determination of the proposal's outcome.\n- **Confirmation**: Period to verify sustained community support before enactment.\n- **Enactment**: Final waiting period before the proposal takes effect.\n\nTracks customize these stages with parameters like decision deposit requirements, voting durations, and approval thresholds, ensuring proposals from each origin receive the required scrutiny and process. For example, a runtime upgrade in the Root Origin track will have longer timeframes and stricter thresholds than a treasury request in the Small Spender track."} -{"page_id": "reference-governance-origins-tracks", "page_title": "Origins and Tracks", "index": 3, "depth": 2, "title": "Additional Resources", "anchor": "additional-resources", "start_char": 2836, "end_char": 3333, "estimated_token_count": 128, "token_estimator": "heuristic-v1", "text": "## Additional Resources\n\n- For a list of origins and tracks for Polkadot and Kusama, including associated parameters, see the [Origins and Tracks Info](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#origins-and-tracks-info){target=\\_blank} entry in the Polkadot Wiki.\n\n- For a deeper dive into the approval and support system, see the [Approval and Support](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#approval-and-support){target=\\_blank} entry of the Polkadot Wiki."} -{"page_id": "reference-governance", "page_title": "On-Chain Governance Overview", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 24, "end_char": 852, "estimated_token_count": 133, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nPolkadot’s governance system exemplifies decentralized decision-making, empowering its community of stakeholders to shape the network’s future through active participation. The latest evolution, OpenGov, builds on Polkadot’s foundation by providing a more inclusive and efficient governance model.\n\nThis guide will explain the principles and structure of OpenGov and walk you through its key components, such as Origins, Tracks, and Delegation. You will learn about improvements over earlier governance systems, including streamlined voting processes and enhanced stakeholder participation.\n\nWith OpenGov, Polkadot achieves a flexible, scalable, and democratic governance framework that allows multiple proposals to proceed simultaneously, ensuring the network evolves in alignment with its community's needs."} -{"page_id": "reference-governance", "page_title": "On-Chain Governance Overview", "index": 1, "depth": 2, "title": "Governance Evolution", "anchor": "governance-evolution", "start_char": 852, "end_char": 1816, "estimated_token_count": 198, "token_estimator": "heuristic-v1", "text": "## Governance Evolution\n\nPolkadot’s governance journey began with [Governance V1](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#governance-summary){target=\\_blank}, a system that proved effective in managing treasury funds and protocol upgrades. However, it faced limitations, such as:\n\n- Slow voting cycles, causing delays in decision-making.\n- Inflexibility in handling multiple referendums, restricting scalability.\n\nTo address these challenges, Polkadot introduced OpenGov, a governance model designed for greater inclusivity, efficiency, and scalability. OpenGov replaces the centralized structures of Governance V1, such as the Council and Technical Committee, with a fully decentralized and dynamic framework.\n\nFor a full comparison of the historic and current governance models, visit the [Gov1 vs. Polkadot OpenGov](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#gov1-vs-polkadot-opengov){target=\\_blank} section of the Polkadot Wiki."} -{"page_id": "reference-governance", "page_title": "On-Chain Governance Overview", "index": 2, "depth": 2, "title": "OpenGov Key Features", "anchor": "opengov-key-features", "start_char": 1816, "end_char": 2574, "estimated_token_count": 139, "token_estimator": "heuristic-v1", "text": "## OpenGov Key Features\n\nOpenGov transforms Polkadot’s governance into a decentralized, stakeholder-driven model, eliminating centralized decision-making bodies like the Council. Key enhancements include:\n\n- **Decentralization**: Shifts all decision-making power to the public, ensuring a more democratic process.\n- **Enhanced delegation**: Allows users to delegate their votes to trusted experts across specific governance tracks.\n- **Simultaneous referendums**: Multiple proposals can progress at once, enabling faster decision-making.\n- **Polkadot Technical Fellowship**: A broad, community-driven group replacing the centralized Technical Committee.\n\nThis new system ensures Polkadot governance remains agile and inclusive, even as the ecosystem grows."} -{"page_id": "reference-governance", "page_title": "On-Chain Governance Overview", "index": 3, "depth": 2, "title": "Origins and Tracks", "anchor": "origins-and-tracks", "start_char": 2574, "end_char": 3654, "estimated_token_count": 248, "token_estimator": "heuristic-v1", "text": "## Origins and Tracks\n\nIn OpenGov, origins and tracks are central to managing proposals and votes.\n\n- **Origin**: Determines the authority level of a proposal (e.g., Treasury, Root) which decides the track of all referendums from that origin.\n- **Track**: Define the procedural flow of a proposal, such as voting duration, approval thresholds, and enactment timelines.\n\nDevelopers must be aware that referendums from different origins and tracks will take varying amounts of time to reach approval and enactment. The [Polkadot Technical Fellowship](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\\_blank} has the option to shorten this timeline by whitelisting a proposal and allowing it to be enacted through the [Whitelist Caller](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#whitelisted-caller){target=\\_blank} origin.\n\nVisit [Origins and Tracks Info](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#origins-and-tracks){target=\\_blank} for details on current origins and tracks, associated terminology, and parameters."} -{"page_id": "reference-governance", "page_title": "On-Chain Governance Overview", "index": 4, "depth": 2, "title": "Referendums", "anchor": "referendums", "start_char": 3654, "end_char": 4505, "estimated_token_count": 178, "token_estimator": "heuristic-v1", "text": "## Referendums\n\nIn OpenGov, anyone can submit a referendum, fostering an open and participatory system. The timeline for a referendum depends on the privilege level of the origin with more significant changes offering more time for community voting and participation before enactment. \n\nThe timeline for an individual referendum includes four distinct periods:\n\n- **Lead-in**: A minimum amount of time to allow for community participation, available room in the origin, and payment of the decision deposit. Voting is open during this period.\n- **Decision**: Voting continues.\n- **Confirmation**: Referendum must meet [approval and support](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#approval-and-support){target=\\_blank} criteria during entire period to avoid rejection.\n- **Enactment**: Changes approved by the referendum are executed."} -{"page_id": "reference-governance", "page_title": "On-Chain Governance Overview", "index": 5, "depth": 3, "title": "Vote on Referendums", "anchor": "vote-on-referendums", "start_char": 4505, "end_char": 5146, "estimated_token_count": 133, "token_estimator": "heuristic-v1", "text": "### Vote on Referendums\n\nVoters can vote with their tokens on each referendum. Polkadot uses a voluntary token locking mechanism, called conviction voting, as a way for voters to increase their voting power. A token holder signals they have a stronger preference for approving a proposal based upon their willingness to lock up tokens. Longer voluntary token locks are seen as a signal of continual approval and translate to increased voting weight.\n\nSee [Voting on a Referendum](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\\_blank} for a deeper look at conviction voting and related token locks."} -{"page_id": "reference-governance", "page_title": "On-Chain Governance Overview", "index": 6, "depth": 3, "title": "Delegate Voting Power", "anchor": "delegate-voting-power", "start_char": 5146, "end_char": 5929, "estimated_token_count": 168, "token_estimator": "heuristic-v1", "text": "### Delegate Voting Power\n\nThe OpenGov system also supports multi-role delegations, allowing token holders to assign their voting power on different tracks to entities with expertise in those areas. \n\nFor example, if a token holder lacks the technical knowledge to evaluate proposals on the [Root track](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#root){target=\\_blank}, they can delegate their voting power for that track to an expert they trust to vote in the best interest of the network. This ensures informed decision-making across tracks while maintaining flexibility for token holders.\n\nVisit [Multirole Delegation](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#multirole-delegation){target=\\_blank} for more details on delegating voting power."} -{"page_id": "reference-governance", "page_title": "On-Chain Governance Overview", "index": 7, "depth": 3, "title": "Cancel a Referendum", "anchor": "cancel-a-referendum", "start_char": 5929, "end_char": 6702, "estimated_token_count": 184, "token_estimator": "heuristic-v1", "text": "### Cancel a Referendum\n\nPolkadot OpenGov has two origins for rejecting ongoing referendums: \n\n- [**Referendum Canceller**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-canceller){target=\\_blank}: Cancels an active referendum when non-malicious errors occur and refunds the deposits to the originators.\n- [**Referendum Killer**](https://wiki.polkadot.com/learn/learn-polkadot-opengov-origins/#referendum-killer){target=\\_blank}: Used for urgent, malicious cases this origin instantly terminates an active referendum and slashes deposits.\n\nSee [Cancelling, Killing, and Blacklisting](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#cancelling-killing--blacklisting){target=\\_blank} for additional information on rejecting referendums."} -{"page_id": "reference-governance", "page_title": "On-Chain Governance Overview", "index": 8, "depth": 2, "title": "Additional Resources", "anchor": "additional-resources", "start_char": 6702, "end_char": 7493, "estimated_token_count": 230, "token_estimator": "heuristic-v1", "text": "## Additional Resources\n\n- **[Democracy pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/democracy/src){target=\\_blank}**: Handles administration of general stakeholder voting.\n- **[Gov2: Polkadot’s Next Generation of Decentralised Governance](https://medium.com/polkadot-network/gov2-polkadots-next-generation-of-decentralised-governance-4d9ef657d11b){target=\\_blank}**: Medium article by Gavin Wood.\n- **[Polkadot Direction](https://matrix.to/#/#Polkadot-Direction:parity.io){target=\\_blank}**: Matrix Element client.\n- **[Polkassembly](https://polkadot.polkassembly.io/){target=\\_blank}**: OpenGov dashboard and UI.\n- **[Polkadot.js Apps Governance](https://polkadot.js.org/apps/#/referenda){target=\\_blank}**: Overview of active referendums."} -{"page_id": "reference-parachains-accounts", "page_title": "Polkadot SDK Accounts", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 12, "end_char": 597, "estimated_token_count": 101, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nAccounts are essential for managing identity, transactions, and governance on the network in the Polkadot SDK. Understanding these components is critical for seamless development and operation on the network, whether you're building or interacting with Polkadot-based chains.\n\nThis page will guide you through the essential aspects of accounts, including their data structure, balance types, reference counters, and address formats. You’ll learn how accounts are managed within the runtime, how balances are categorized, and how addresses are encoded and validated."} -{"page_id": "reference-parachains-accounts", "page_title": "Polkadot SDK Accounts", "index": 1, "depth": 2, "title": "Account Data Structure", "anchor": "account-data-structure", "start_char": 597, "end_char": 862, "estimated_token_count": 42, "token_estimator": "heuristic-v1", "text": "## Account Data Structure\n\nAccounts are foundational to any blockchain, and the Polkadot SDK provides a flexible management system. This section explains how the Polkadot SDK defines accounts and manages their lifecycle through data structures within the runtime."} -{"page_id": "reference-parachains-accounts", "page_title": "Polkadot SDK Accounts", "index": 2, "depth": 3, "title": "Account", "anchor": "account", "start_char": 862, "end_char": 3162, "estimated_token_count": 569, "token_estimator": "heuristic-v1", "text": "### Account\n\nThe [`Account` data type](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/type.Account.html){target=\\_blank} is a storage map within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\\_blank} that links an account ID to its corresponding data. This structure is fundamental for mapping account-related information within the chain.\n\nThe code snippet below shows how accounts are defined:\n\n```rs\n /// The full account information for a particular account ID.\n \t#[pallet::storage]\n \t#[pallet::getter(fn account)]\n \tpub type Account = StorageMap<\n \t\t_,\n \t\tBlake2_128Concat,\n \t\tT::AccountId,\n \t\tAccountInfo,\n \t\tValueQuery,\n \t>;\n```\n\nThe preceding code block defines a storage map named `Account`. The `StorageMap` is a type of on-chain storage that maps keys to values. In the `Account` map, the key is an account ID, and the value is the account's information. Here, `T` represents the generic parameter for the runtime configuration, which is defined by the pallet's configuration trait (`Config`).\n\nThe `StorageMap` consists of the following parameters:\n\n- **`_`**: Used in macro expansion and acts as a placeholder for the storage prefix type. Tells the macro to insert the default prefix during expansion.\n- **`Blake2_128Concat`**: The hashing function applied to keys in the storage map.\n- **`T: :AccountId`**: Represents the key type, which corresponds to the account’s unique ID.\n- **`AccountInfo`**: The value type stored in the map. For each account ID, the map stores an `AccountInfo` struct containing:\n\n - **`T::Nonce`**: A nonce for the account, which is incremented with each transaction to ensure transaction uniqueness.\n - **`T: :AccountData`**: Custom account data defined by the runtime configuration, which could include balances, locked funds, or other relevant information.\n \n- **`ValueQuery`**: Defines how queries to the storage map behave when no value is found; returns a default value instead of `None`.\n\nFor a detailed explanation of storage maps, see the [`StorageMap`](https://paritytech.github.io/polkadot-sdk/master/frame_support/storage/types/struct.StorageMap.html){target=\\_blank} entry in the Rust docs."} -{"page_id": "reference-parachains-accounts", "page_title": "Polkadot SDK Accounts", "index": 3, "depth": 3, "title": "Account Info", "anchor": "account-info", "start_char": 3162, "end_char": 5825, "estimated_token_count": 617, "token_estimator": "heuristic-v1", "text": "### Account Info\n\nThe `AccountInfo` structure is another key element within the [System pallet](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/lib.rs.html){target=\\_blank}, providing more granular details about each account's state. This structure tracks vital data, such as the number of transactions and the account’s relationships with other modules.\n\n```rs\n/// Information of an account.\n#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)]\npub struct AccountInfo {\n\t/// The number of transactions this account has sent.\n\tpub nonce: Nonce,\n\t/// The number of other modules that currently depend on this account's existence. The account\n\t/// cannot be reaped until this is zero.\n\tpub consumers: RefCount,\n\t/// The number of other modules that allow this account to exist. The account may not be reaped\n\t/// until this and `sufficients` are both zero.\n\tpub providers: RefCount,\n\t/// The number of modules that allow this account to exist for their own purposes only. The\n\t/// account may not be reaped until this and `providers` are both zero.\n\tpub sufficients: RefCount,\n\t/// The additional data that belongs to this account. Used to store the balance(s) in a lot of\n\t/// chains.\n\tpub data: AccountData,\n}\n```\n\nThe `AccountInfo` structure includes the following components:\n\n- **`nonce`**: Tracks the number of transactions initiated by the account, which ensures transaction uniqueness and prevents replay attacks.\n- **`consumers`**: Counts how many other modules or pallets rely on this account’s existence. The account cannot be removed from the chain (reaped) until this count reaches zero.\n- **`providers`**: Tracks how many modules permit this account’s existence. An account can only be reaped once both `providers` and `sufficients` are zero.\n- **`sufficients`**: Represents the number of modules that allow the account to exist for internal purposes, independent of any other modules.\n- **`AccountData`**: A flexible data structure that can be customized in the runtime configuration, usually containing balances or other user-specific data.\n\nThis structure helps manage an account's state and prevents its premature removal while it is still referenced by other on-chain data or modules. The [`AccountInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.AccountInfo.html){target=\\_blank} structure can vary as long as it satisfies the trait bounds defined by the `AccountData` associated type in the [`frame-system::pallet::Config`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/trait.Config.html){target=\\_blank} trait."} -{"page_id": "reference-parachains-accounts", "page_title": "Polkadot SDK Accounts", "index": 4, "depth": 3, "title": "Account Reference Counters", "anchor": "account-reference-counters", "start_char": 5825, "end_char": 10918, "estimated_token_count": 1040, "token_estimator": "heuristic-v1", "text": "### Account Reference Counters\n\nPolkadot SDK uses reference counters to track an account’s dependencies across different runtime modules. These counters ensure that accounts remain active while data is associated with them.\n\nThe reference counters include:\n\n- **`consumers`**: Prevents account removal while other pallets still rely on the account.\n- **`providers`**: Ensures an account is active before other pallets store data related to it.\n- **`sufficients`**: Indicates the account’s independence, ensuring it can exist even without a native token balance, such as when holding sufficient alternative assets.\n\n#### Providers Reference Counters\n\nThe `providers` counter ensures that an account is ready to be depended upon by other runtime modules. For example, it is incremented when an account has a balance above the existential deposit, which marks the account as active.\n\nThe system requires this reference counter to be greater than zero for the `consumers` counter to be incremented, ensuring the account is stable before any dependencies are added.\n\n#### Consumers Reference Counters\n\nThe `consumers` counter ensures that the account cannot be reaped until all references to it across the runtime have been removed. This check prevents the accidental deletion of accounts that still have active on-chain data.\n\nIt is the user’s responsibility to clear out any data from other runtime modules if they wish to remove their account and reclaim their existential deposit.\n\n#### Sufficients Reference Counter\n\nThe `sufficients` counter tracks accounts that can exist independently without relying on a native account balance. This is useful for accounts holding other types of assets, like tokens, without needing a minimum balance in the native token.\n\nFor instance, the [Assets pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_assets/index.html){target=\\_blank}, may increment this counter for an account holding sufficient tokens.\n\n#### Account Deactivation\n\nIn Polkadot SDK-based chains, an account is deactivated when its reference counters (such as `providers`, `consumers`, and `sufficient`) reach zero. These counters ensure the account remains active as long as other runtime modules or pallets reference it.\n\nWhen all dependencies are cleared and the counters drop to zero, the account becomes deactivated and may be removed from the chain (reaped). This is particularly important in Polkadot SDK-based blockchains, where accounts with balances below the existential deposit threshold are pruned from storage to conserve state resources.\n\nEach pallet that references an account has cleanup functions that decrement these counters when the pallet no longer depends on the account. Once these counters reach zero, the account is marked for deactivation.\n\n#### Updating Counters\n\nThe Polkadot SDK provides runtime developers with various methods to manage account lifecycle events, such as deactivation or incrementing reference counters. These methods ensure that accounts cannot be reaped while still in use.\n\nThe following helper functions manage these counters:\n\n- **`inc_consumers()`**: Increments the `consumer` reference counter for an account, signaling that another pallet depends on it.\n- **`dec_consumers()`**: Decrements the `consumer` reference counter, signaling that a pallet no longer relies on the account.\n- **`inc_providers()`**: Increments the `provider` reference counter, ensuring the account remains active.\n- **`dec_providers()`**: Decrements the `provider` reference counter, allowing for account deactivation when no longer in use.\n- **`inc_sufficients()`**: Increments the `sufficient` reference counter for accounts that hold sufficient assets.\n- **`dec_sufficients()`**: Decrements the `sufficient` reference counter.\n\nTo ensure proper account cleanup and lifecycle management, a corresponding decrement should be made for each increment action.\n\nThe `System` pallet offers three query functions to assist developers in tracking account states:\n\n- **[`can_inc_consumer()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_inc_consumer){target=\\_blank}**: Checks if the account can safely increment the consumer reference.\n- **[`can_dec_provider()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.can_dec_provider){target=\\_blank}**: Ensures that no consumers exist before allowing the decrement of the provider counter.\n- **[`is_provider_required()`](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html#method.is_provider_required){target=\\_blank}**: Verifies whether the account still has any active consumer references.\n\nThis modular and flexible system of reference counters tightly controls the lifecycle of accounts in Polkadot SDK-based blockchains, preventing the accidental removal or retention of unneeded accounts. You can refer to the [System pallet Rust docs](https://paritytech.github.io/polkadot-sdk/master/frame_system/pallet/struct.Pallet.html){target=\\_blank} for more details."} -{"page_id": "reference-parachains-accounts", "page_title": "Polkadot SDK Accounts", "index": 5, "depth": 2, "title": "Account Balance Types", "anchor": "account-balance-types", "start_char": 10918, "end_char": 12838, "estimated_token_count": 465, "token_estimator": "heuristic-v1", "text": "## Account Balance Types\n\nIn the Polkadot ecosystem, account balances are categorized into different types based on how the funds are utilized and their availability. These balance types determine the actions that can be performed, such as transferring tokens, paying transaction fees, or participating in governance activities. Understanding these balance types helps developers manage user accounts and implement balance-dependent logic.\n\n!!! note \"A more efficient distribution of account balance types is in development\"\n Soon, pallets in the Polkadot SDK will implement the [`Fungible` trait](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\\_blank} (see the [tracking issue](https://github.com/paritytech/polkadot-sdk/issues/226){target=\\_blank} for more details). For example, the [`transaction-storage`](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_storage/index.html){target=\\_blank} pallet changed the implementation of the [`Currency`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/currency/index.html){target=\\_blank} trait (see the [Refactor transaction storage pallet to use fungible traits](https://github.com/paritytech/polkadot-sdk/pull/1800){target=\\_blank} PR for further details):\n\n ```rust\n type BalanceOf = <::Currency as Currency<::AccountId>>::Balance;\n ```\n \n To the [`Fungible`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/tokens/fungible/index.html){target=\\_blank} trait:\n\n ```rust\n type BalanceOf = <::Currency as FnInspect<::AccountId>>::Balance;\n ```\n \n This update will enable more efficient use of account balances, allowing the free balance to be utilized for on-chain activities such as setting proxies and managing identities."} -{"page_id": "reference-parachains-accounts", "page_title": "Polkadot SDK Accounts", "index": 6, "depth": 3, "title": "Balance Types", "anchor": "balance-types", "start_char": 12838, "end_char": 15313, "estimated_token_count": 601, "token_estimator": "heuristic-v1", "text": "### Balance Types\n\nThe five main balance types are:\n\n- **Free balance**: Represents the total tokens available to the account for any on-chain activity, including staking, governance, and voting. However, it may not be fully spendable or transferrable if portions of it are locked or reserved.\n- **Locked balance**: Portions of the free balance that cannot be spent or transferred because they are tied up in specific activities like [staking](https://wiki.polkadot.com/learn/learn-staking/#nominating-validators){target=\\_blank}, [vesting](https://wiki.polkadot.com/learn/learn-guides-transfers/#vested-transfers-with-the-polkadot-js-ui){target=\\_blank}, or participating in [governance](https://wiki.polkadot.com/learn/learn-polkadot-opengov/#voting-on-a-referendum){target=\\_blank}. While the tokens remain part of the free balance, they are non-transferable for the duration of the lock.\n- **Reserved balance**: Funds locked by specific system actions, such as setting up an [identity](https://wiki.polkadot.com/learn/learn-identity/){target=\\_blank}, creating [proxies](https://wiki.polkadot.com/learn/learn-proxies/){target=\\_blank}, or submitting [deposits for governance proposals](https://wiki.polkadot.com/learn/learn-guides-polkadot-opengov/#claiming-opengov-deposits){target=\\_blank}. These tokens are not part of the free balance and cannot be spent unless they are unreserved.\n- **Spendable balance**: The portion of the free balance that is available for immediate spending or transfers. It is calculated by subtracting the maximum of locked or reserved amounts from the free balance, ensuring that existential deposit limits are met.\n- **Untouchable balance**: Funds that cannot be directly spent or transferred but may still be utilized for on-chain activities, such as governance participation or staking. These tokens are typically tied to certain actions or locked for a specific period.\n\nThe spendable balance is calculated as follows:\n\n```text\nspendable = free - max(locked - reserved, ED)\n```\n\nHere, `free`, `locked`, and `reserved` are defined above. The `ED` represents the [existential deposit](https://wiki.polkadot.com/learn/learn-accounts/#existential-deposit-and-reaping){target=\\_blank}, the minimum balance required to keep an account active and prevent it from being reaped. You may find you can't see all balance types when looking at your account via a wallet. Wallet providers often display only spendable, locked, and reserved balances."} -{"page_id": "reference-parachains-accounts", "page_title": "Polkadot SDK Accounts", "index": 7, "depth": 3, "title": "Locks", "anchor": "locks", "start_char": 15313, "end_char": 17490, "estimated_token_count": 458, "token_estimator": "heuristic-v1", "text": "### Locks\n\nLocks are applied to an account's free balance, preventing that portion from being spent or transferred. Locks are automatically placed when an account participates in specific on-chain activities, such as staking or governance. Although multiple locks may be applied simultaneously, they do not stack. Instead, the largest lock determines the total amount of locked tokens.\n\nLocks follow these basic rules:\n\n- If different locks apply to varying amounts, the largest lock amount takes precedence.\n- If multiple locks apply to the same amount, the lock with the longest duration governs when the balance can be unlocked.\n\n#### Locks Example\n\nConsider an example where an account has 80 DOT locked for both staking and governance purposes like so:\n\n- 80 DOT is staked with a 28-day lock period.\n- 24 DOT is locked for governance with a 1x conviction and a 7-day lock period.\n- 4 DOT is locked for governance with a 6x conviction and a 224-day lock period.\n\nIn this case, the total locked amount is 80 DOT because only the largest lock (80 DOT from staking) governs the locked balance. These 80 DOT will be released at different times based on the lock durations. In this example, the 24 DOT locked for governance will be released first since the shortest lock period is seven days. The 80 DOT stake with a 28-day lock period is released next. Now, all that remains locked is the 4 DOT for governance. After 224 days, all 80 DOT (minus the existential deposit) will be free and transferable.\n\n![Illustration of Lock Example](/images/reference/parachains/accounts/accounts-01.webp)\n\n#### Edge Cases for Locks\n\nIn scenarios where multiple convictions and lock periods are active, the lock duration and amount are determined by the longest period and largest amount. For example, if you delegate with different convictions and attempt to undelegate during an active lock period, the lock may be extended for the full amount of tokens. For a detailed discussion on edge case lock behavior, see this [Stack Exchange post](https://substrate.stackexchange.com/questions/5067/delegating-and-undelegating-during-the-lock-period-extends-it-for-the-initial-am){target=\\_blank}."} -{"page_id": "reference-parachains-accounts", "page_title": "Polkadot SDK Accounts", "index": 8, "depth": 3, "title": "Balance Types on Polkadot.js", "anchor": "balance-types-on-polkadotjs", "start_char": 17490, "end_char": 20529, "estimated_token_count": 603, "token_estimator": "heuristic-v1", "text": "### Balance Types on Polkadot.js\n\nPolkadot.js provides a user-friendly interface for managing and visualizing various account balances on Polkadot and Kusama networks. When interacting with Polkadot.js, you will encounter multiple balance types that are critical for understanding how your funds are distributed and restricted. This section explains how different balances are displayed in the Polkadot.js UI and what each type represents.\n\n![](/images/reference/parachains/accounts/accounts-02.webp)\n\nThe most common balance types displayed on Polkadot.js are:\n\n- **Total balance**: The total number of tokens available in the account. This includes all tokens, whether they are transferable, locked, reserved, or vested. However, the total balance does not always reflect what can be spent immediately. In this example, the total balance is 0.6274 KSM.\n\n- **Transferable balance**: Shows how many tokens are immediately available for transfer. It is calculated by subtracting the locked and reserved balances from the total balance. For example, if an account has a total balance of 0.6274 KSM and a transferable balance of 0.0106 KSM, only the latter amount can be sent or spent freely.\n\n- **Vested balance**: Tokens that allocated to the account but released according to a specific schedule. Vested tokens remain locked and cannot be transferred until fully vested. For example, an account with a vested balance of 0.2500 KSM means that this amount is owned but not yet transferable.\n\n- **Locked balance**: Tokens that are temporarily restricted from being transferred or spent. These locks typically result from participating in staking, governance, or vested transfers. In Polkadot.js, locked balances do not stack—only the largest lock is applied. For instance, if an account has 0.5500 KSM locked for governance and staking, the locked balance would display 0.5500 KSM, not the sum of all locked amounts.\n\n- **Reserved balance**: Refers to tokens locked for specific on-chain actions, such as setting an identity, creating a proxy, or making governance deposits. Reserved tokens are not part of the free balance, but can be freed by performing certain actions. For example, removing an identity would unreserve those funds.\n\n- **Bonded balance**: The tokens locked for staking purposes. Bonded tokens are not transferable until they are unbonded after the unbonding period.\n\n- **Redeemable balance**: The number of tokens that have completed the unbonding period and are ready to be unlocked and transferred again. For example, if an account has a redeemable balance of 0.1000 KSM, those tokens are now available for spending.\n\n- **Democracy balance**: Reflects the number of tokens locked for governance activities, such as voting on referenda. These tokens are locked for the duration of the governance action and are only released after the lock period ends.\n\nBy understanding these balance types and their implications, developers and users can better manage their funds and engage with on-chain activities more effectively."} -{"page_id": "reference-parachains-accounts", "page_title": "Polkadot SDK Accounts", "index": 9, "depth": 2, "title": "Address Formats", "anchor": "address-formats", "start_char": 20529, "end_char": 20988, "estimated_token_count": 77, "token_estimator": "heuristic-v1", "text": "## Address Formats\n\nThe SS58 address format is a core component of the Polkadot SDK that enables accounts to be uniquely identified across Polkadot-based networks. This format is a modified version of Bitcoin's Base58Check encoding, specifically designed to accommodate the multi-chain nature of the Polkadot ecosystem. SS58 encoding allows each chain to define its own set of addresses while maintaining compatibility and checksum validation for security."} -{"page_id": "reference-parachains-accounts", "page_title": "Polkadot SDK Accounts", "index": 10, "depth": 3, "title": "Basic Format", "anchor": "basic-format", "start_char": 20988, "end_char": 22230, "estimated_token_count": 295, "token_estimator": "heuristic-v1", "text": "### Basic Format\n\nSS58 addresses consist of three main components:\n\n```text\nbase58encode(concat(,
, ))\n```\n\n- **Address type**: A byte or set of bytes that define the network (or chain) for which the address is intended. This ensures that addresses are unique across different Polkadot SDK-based chains.\n- **Address**: The public key of the account encoded as bytes.\n- **Checksum**: A hash-based checksum which ensures that addresses are valid and unaltered. The checksum is derived from the concatenated address type and address components, ensuring integrity.\n\nThe encoding process transforms the concatenated components into a Base58 string, providing a compact and human-readable format that avoids easily confused characters (e.g., zero '0', capital 'O', lowercase 'l'). This encoding function ([`encode`](https://docs.rs/bs58/latest/bs58/fn.encode.html){target=\\_blank}) is implemented exactly as defined in Bitcoin and IPFS specifications, using the same alphabet as both implementations.\n\nFor more details about the SS58 address format implementation, see the [`Ss58Codec`](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Ss58Codec.html){target=\\_blank} trait in the Rust Docs."} -{"page_id": "reference-parachains-accounts", "page_title": "Polkadot SDK Accounts", "index": 11, "depth": 3, "title": "Address Type", "anchor": "address-type", "start_char": 22230, "end_char": 23165, "estimated_token_count": 203, "token_estimator": "heuristic-v1", "text": "### Address Type\n\nThe address type defines how an address is interpreted and to which network it belongs. Polkadot SDK uses different prefixes to distinguish between various chains and address formats:\n\n- **Address types `0-63`**: Simple addresses, commonly used for network identifiers.\n- **Address types `64-127`**: Full addresses that support a wider range of network identifiers.\n- **Address types `128-255`**: Reserved for future address format extensions.\n\nFor example, Polkadot’s main network uses an address type of 0, while Kusama uses 2. This ensures that addresses can be used without confusion between networks.\n\nThe address type is always encoded as part of the SS58 address, making it easy to quickly identify the network. Refer to the [SS58 registry](https://github.com/paritytech/ss58-registry){target=\\_blank} for the canonical listing of all address type identifiers and how they map to Polkadot SDK-based networks."} -{"page_id": "reference-parachains-accounts", "page_title": "Polkadot SDK Accounts", "index": 12, "depth": 3, "title": "Address Length", "anchor": "address-length", "start_char": 23165, "end_char": 24359, "estimated_token_count": 268, "token_estimator": "heuristic-v1", "text": "### Address Length\n\nSS58 addresses can have different lengths depending on the specific format. Address lengths range from as short as 3 to 35 bytes, depending on the complexity of the address and network requirements. This flexibility allows SS58 addresses to adapt to different chains while providing a secure encoding mechanism.\n\n| Total | Type | Raw account | Checksum |\n|-------|------|-------------|----------|\n| 3 | 1 | 1 | 1 |\n| 4 | 1 | 2 | 1 |\n| 5 | 1 | 2 | 2 |\n| 6 | 1 | 4 | 1 |\n| 7 | 1 | 4 | 2 |\n| 8 | 1 | 4 | 3 |\n| 9 | 1 | 4 | 4 |\n| 10 | 1 | 8 | 1 |\n| 11 | 1 | 8 | 2 |\n| 12 | 1 | 8 | 3 |\n| 13 | 1 | 8 | 4 |\n| 14 | 1 | 8 | 5 |\n| 15 | 1 | 8 | 6 |\n| 16 | 1 | 8 | 7 |\n| 17 | 1 | 8 | 8 |\n| 35 | 1 | 32 | 2 |\n\nSS58 addresses also support different payload sizes, allowing a flexible range of account identifiers."} -{"page_id": "reference-parachains-accounts", "page_title": "Polkadot SDK Accounts", "index": 13, "depth": 3, "title": "Checksum Types", "anchor": "checksum-types", "start_char": 24359, "end_char": 24824, "estimated_token_count": 94, "token_estimator": "heuristic-v1", "text": "### Checksum Types\n\nA checksum is applied to validate SS58 addresses. Polkadot SDK uses a Blake2b-512 hash function to calculate the checksum, which is appended to the address before encoding. The checksum length can vary depending on the address format (e.g., 1-byte, 2-byte, or longer), providing varying levels of validation strength.\n\nThe checksum ensures that an address is not modified or corrupted, adding an extra layer of security for account management."} -{"page_id": "reference-parachains-accounts", "page_title": "Polkadot SDK Accounts", "index": 14, "depth": 3, "title": "Validating Addresses", "anchor": "validating-addresses", "start_char": 24824, "end_char": 29604, "estimated_token_count": 1074, "token_estimator": "heuristic-v1", "text": "### Validating Addresses\n\nSS58 addresses can be validated using the subkey command-line interface or the Polkadot.js API. These tools help ensure an address is correctly formatted and valid for the intended network. The following sections will provide an overview of how validation works with these tools.\n\n#### Using Subkey\n\n[Subkey](https://paritytech.github.io/polkadot-sdk/master/subkey/index.html){target=\\_blank} is a CLI tool provided by Polkadot SDK for generating and managing keys. It can inspect and validate SS58 addresses.\n\nThe `inspect` command gets a public key and an SS58 address from the provided secret URI. The basic syntax for the `subkey inspect` command is:\n\n```bash\nsubkey inspect [flags] [options] uri\n```\n\nFor the `uri` command-line argument, you can specify the secret seed phrase, a hex-encoded private key, or an SS58 address. If the input is a valid address, the `subkey` program displays the corresponding hex-encoded public key, account identifier, and SS58 addresses.\n\nFor example, to inspect the public keys derived from a secret seed phrase, you can run a command similar to the following:\n\n```bash\nsubkey inspect \"caution juice atom organ advance problem want pledge someone senior holiday very\"\n```\n\nThe command displays output similar to the following:\n\n
\n subkey inspect \"caution juice atom organ advance problem want pledge someone senior holiday very\"\n Secret phrase `caution juice atom organ advance problem want pledge someone senior holiday very` is account:\n Secret seed: 0xc8fa03532fb22ee1f7f6908b9c02b4e72483f0dbd66e4cd456b8f34c6230b849\n Public key (hex): 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746\n Public key (SS58): 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR\n Account ID: 0xd6a3105d6768e956e9e5d41050ac29843f98561410d3a47f9dd5b3b227ab8746\n SS58 Address: 5Gv8YYFu8H1btvmrJy9FjjAWfb99wrhV3uhPFoNEr918utyR\n
\n\nThe `subkey` program assumes an address is based on a public/private key pair. If you inspect an address, the command returns the 32-byte account identifier.\n\nHowever, not all addresses in Polkadot SDK-based networks are based on keys.\n\nDepending on the command-line options you specify and the input you provided, the command output might also display the network for which the address has been encoded. For example:\n\n```bash\nsubkey inspect \"12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU\"\n```\n\nThe command displays output similar to the following:\n\n
\n subkey inspect \"12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU\"\n Public Key URI `12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU` is account:\n Network ID/Version: polkadot\n Public key (hex): 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a\n Account ID: 0x46ebddef8cd9bb167dc30878d7113b7e168e6f0646beffd77d69d39bad76b47a\n Public key (SS58): 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU\n SS58 Address: 12bzRJfh7arnnfPPUZHeJUaE62QLEwhK48QnH9LXeK2m1iZU\n
\n\n#### Using Polkadot.js API\n\nTo verify an address in JavaScript or TypeScript projects, you can use the functions built into the [Polkadot.js API](https://polkadot.js.org/docs/){target=\\_blank}. For example:\n\n```js\n// Import Polkadot.js API dependencies\nconst { decodeAddress, encodeAddress } = require('@polkadot/keyring');\nconst { hexToU8a, isHex } = require('@polkadot/util');\n\n// Specify an address to test.\nconst address = 'INSERT_ADDRESS_TO_TEST';\n\n// Check address\nconst isValidSubstrateAddress = () => {\n try {\n encodeAddress(isHex(address) ? hexToU8a(address) : decodeAddress(address));\n\n return true;\n } catch (error) {\n return false;\n }\n};\n\n// Query result\nconst isValid = isValidSubstrateAddress();\nconsole.log(isValid);\n\n```\n\nIf the function returns `true`, the specified address is a valid address.\n\n#### Other SS58 Implementations\n\nSupport for encoding and decoding Polkadot SDK SS58 addresses has been implemented in several other languages and libraries.\n\n- **Crystal**: [`wyhaines/base58.cr`](https://github.com/wyhaines/base58.cr){target=\\_blank}\n- **Go**: [`itering/subscan-plugin`](https://github.com/itering/subscan-plugin){target=\\_blank}\n- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\\_blank}\n- **TypeScript**: [`subsquid/squid-sdk`](https://github.com/subsquid/squid-sdk){target=\\_blank}"} -{"page_id": "reference-parachains-blocks-transactions-fees-blocks", "page_title": "Blocks", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 10, "end_char": 693, "estimated_token_count": 126, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nIn the Polkadot SDK, blocks are fundamental to the functioning of the blockchain, serving as containers for [transactions](/reference/parachains/blocks-transactions-fees/transactions/){target=\\_blank} and changes to the chain's state. Blocks consist of headers and an array of transactions, ensuring the integrity and validity of operations on the network. This guide explores the essential components of a block, the process of block production, and how blocks are validated and imported across the network. By understanding these concepts, developers can better grasp how blockchains maintain security, consistency, and performance within the Polkadot ecosystem."} -{"page_id": "reference-parachains-blocks-transactions-fees-blocks", "page_title": "Blocks", "index": 1, "depth": 2, "title": "What is a Block?", "anchor": "what-is-a-block", "start_char": 693, "end_char": 1830, "estimated_token_count": 226, "token_estimator": "heuristic-v1", "text": "## What is a Block?\n\nIn the Polkadot SDK, a block is a fundamental unit that encapsulates both the header and an array of transactions. The block header includes critical metadata to ensure the integrity and sequence of the blockchain. Here's a breakdown of its components:\n\n- **Block height**: Indicates the number of blocks created in the chain so far.\n- **Parent hash**: The hash of the previous block, providing a link to maintain the blockchain's immutability.\n- **Transaction root**: Cryptographic digest summarizing all transactions in the block.\n- **State root**: A cryptographic digest representing the post-execution state.\n- **Digest**: Additional information that can be attached to a block, such as consensus-related messages.\n\nEach transaction is part of a series that is executed according to the runtime's rules. The transaction root is a cryptographic digest of this series, which prevents alterations and enables succinct verification by light clients. This verification process allows light clients to confirm whether a transaction exists in a block with only the block header, avoiding downloading the entire block."} -{"page_id": "reference-parachains-blocks-transactions-fees-blocks", "page_title": "Blocks", "index": 2, "depth": 2, "title": "Block Production", "anchor": "block-production", "start_char": 1830, "end_char": 2154, "estimated_token_count": 57, "token_estimator": "heuristic-v1", "text": "## Block Production\n\nWhen an authoring node is authorized to create a new block, it selects transactions from the transaction queue based on priority. This step, known as block production, relies heavily on the executive module to manage the initialization and finalization of blocks. The process is summarized as follows:"} -{"page_id": "reference-parachains-blocks-transactions-fees-blocks", "page_title": "Blocks", "index": 3, "depth": 3, "title": "Initialize Block", "anchor": "initialize-block", "start_char": 2154, "end_char": 3023, "estimated_token_count": 199, "token_estimator": "heuristic-v1", "text": "### Initialize Block\n\nThe block initialization process begins with a series of function calls that prepare the block for transaction execution:\n\n1. **Call `on_initialize`**: The executive module calls the [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\\_blank} hook from the system pallet and other runtime pallets to prepare for the block's transactions.\n2. **Coordinate runtime calls**: Coordinates function calls in the order defined by the transaction queue.\n3. **Verify information**: Once [`on_initialize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_initialize){target=\\_blank} functions are executed, the executive module checks the parent hash in the block header and the trie root to verify information is consistent."} -{"page_id": "reference-parachains-blocks-transactions-fees-blocks", "page_title": "Blocks", "index": 4, "depth": 3, "title": "Finalize Block", "anchor": "finalize-block", "start_char": 3023, "end_char": 3897, "estimated_token_count": 209, "token_estimator": "heuristic-v1", "text": "### Finalize Block\n\nOnce transactions are processed, the block must be finalized before being broadcast to the network. The finalization steps are as follows:\n\n1. **Call `on_finalize`**: The executive module calls the [`on_finalize`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_finalize){target=\\_blank} hooks in each pallet to ensure any remaining state updates or checks are completed before the block is sealed and published.\n2. **Verify information**: The block's digest and storage root in the header are checked against the initialized block to ensure consistency.\n3. **Call `on_idle`**: The [`on_idle`](https://paritytech.github.io/polkadot-sdk/master/frame_support/traits/trait.Hooks.html#method.on_idle){target=\\_blank} hook is triggered to process any remaining tasks using the leftover weight from the block."} -{"page_id": "reference-parachains-blocks-transactions-fees-blocks", "page_title": "Blocks", "index": 5, "depth": 2, "title": "Block Authoring and Import", "anchor": "block-authoring-and-import", "start_char": 3897, "end_char": 4399, "estimated_token_count": 113, "token_estimator": "heuristic-v1", "text": "## Block Authoring and Import\n\nOnce the block is finalized, it is gossiped to other nodes in the network. Nodes follow this procedure:\n\n1. **Receive transactions**: The authoring node collects transactions from the network.\n2. **Validate**: Transactions are checked for validity.\n3. **Queue**: Valid transactions are placed in the transaction pool for execution.\n4. **Execute**: State changes are made as the transactions are executed.\n5. **Publish**: The finalized block is broadcast to the network."} -{"page_id": "reference-parachains-blocks-transactions-fees-blocks", "page_title": "Blocks", "index": 6, "depth": 3, "title": "Block Import Queue", "anchor": "block-import-queue", "start_char": 4399, "end_char": 6005, "estimated_token_count": 401, "token_estimator": "heuristic-v1", "text": "### Block Import Queue\n\nAfter a block is published, other nodes on the network can import it into their chain state. The block import queue is part of the outer node in every Polkadot SDK-based node and ensures incoming blocks are valid before adding them to the node's state.\n\nIn most cases, you don't need to know details about how transactions are gossiped or how other nodes on the network import blocks. The following traits are relevant, however, if you plan to write any custom consensus logic or want a deeper dive into the block import queue:\n\n- **[`ImportQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.ImportQueue.html){target=\\_blank}**: The trait that defines the block import queue.\n- **[`Link`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Link.html){target=\\_blank}**: The trait that defines the link between the block import queue and the network.\n- **[`BasicQueue`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/struct.BasicQueue.html){target=\\_blank}**: A basic implementation of the block import queue.\n- **[`Verifier`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/import_queue/trait.Verifier.html){target=\\_blank}**: The trait that defines the block verifier.\n- **[`BlockImport`](https://paritytech.github.io/polkadot-sdk/master/sc_consensus/block_import/trait.BlockImport.html){target=\\_blank}**: The trait that defines the block import process.\n\nThese traits govern how blocks are validated and imported across the network, ensuring consistency and security."} -{"page_id": "reference-parachains-blocks-transactions-fees-blocks", "page_title": "Blocks", "index": 7, "depth": 2, "title": "Additional Resources", "anchor": "additional-resources", "start_char": 6005, "end_char": 6252, "estimated_token_count": 64, "token_estimator": "heuristic-v1", "text": "## Additional Resources\n\nTo learn more about the block structure in the Polkadot SDK runtime, see the [`Block` reference](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.Block.html){target=\\_blank} entry in the Rust Docs."} -{"page_id": "reference-parachains-blocks-transactions-fees-fees", "page_title": "Transactions Weights and Fees", "index": 0, "depth": 2, "title": "Introductions", "anchor": "introductions", "start_char": 33, "end_char": 2267, "estimated_token_count": 408, "token_estimator": "heuristic-v1", "text": "## Introductions\n\nWhen transactions are executed, or data is stored on-chain, the activity changes the chain's state and consumes blockchain resources. Because the resources available to a blockchain are limited, managing how operations on-chain consume them is important. In addition to being limited in practical terms, such as storage capacity, blockchain resources represent a potential attack vector for malicious users. For example, a malicious user might attempt to overload the network with messages to stop the network from producing new blocks. To protect blockchain resources from being drained or overloaded, you need to manage how they are made available and how they are consumed. The resources to be aware of include:\n\n- Memory usage\n- Storage input and output\n- Computation\n- Transaction and block size\n- State database size\n\nThe Polkadot SDK provides block authors with several ways to manage access to resources and to prevent individual components of the chain from consuming too much of any single resource. Two of the most important mechanisms available to block authors are weights and transaction fees.\n\n[Weights](/reference/glossary/#weight){target=\\_blank} manage the time it takes to validate a block and characterize the time it takes to execute the calls in the block's body. By controlling the execution time a block can consume, weights set limits on storage input, output, and computation.\n\nSome of the weight allowed for a block is consumed as part of the block's initialization and finalization. The weight might also be used to execute mandatory inherent extrinsic calls. To help ensure blocks don’t consume too much execution time and prevent malicious users from overloading the system with unnecessary calls, weights are combined with transaction fees.\n\n[Transaction fees](/reference/parachains/blocks-transactions-fees/transactions/#transaction-fees){target=\\_blank} provide an economic incentive to limit execution time, computation, and the number of calls required to perform operations. Transaction fees are also used to make the blockchain economically sustainable because they are typically applied to transactions initiated by users and deducted before a transaction request is executed."} -{"page_id": "reference-parachains-blocks-transactions-fees-fees", "page_title": "Transactions Weights and Fees", "index": 1, "depth": 2, "title": "How Fees are Calculated", "anchor": "how-fees-are-calculated", "start_char": 2267, "end_char": 3592, "estimated_token_count": 287, "token_estimator": "heuristic-v1", "text": "## How Fees are Calculated\n\nThe final fee for a transaction is calculated using the following parameters:\n\n- **`base fee`**: This is the minimum amount a user pays for a transaction. It is declared a base weight in the runtime and converted to a fee using the [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\\_blank} conversion.\n- **`weight fee`**: A fee proportional to the execution time (input and output and computation) that a transaction consumes.\n- **`length fee`**: A fee proportional to the encoded length of the transaction.\n- **`tip`**: An optional tip to increase the transaction’s priority, giving it a higher chance to be included in the transaction queue.\n\nThe base fee and proportional weight and length fees constitute the inclusion fee. The inclusion fee is the minimum fee that must be available for a transaction to be included in a block.\n\n```text\ninclusion fee = base fee + weight fee + length fee\n```\n\nTransaction fees are withdrawn before the transaction is executed. After the transaction is executed, the weight can be adjusted to reflect the resources used. If a transaction uses fewer resources than expected, the transaction fee is corrected, and the adjusted transaction fee is deposited."} -{"page_id": "reference-parachains-blocks-transactions-fees-fees", "page_title": "Transactions Weights and Fees", "index": 2, "depth": 2, "title": "Using the Transaction Payment Pallet", "anchor": "using-the-transaction-payment-pallet", "start_char": 3592, "end_char": 4931, "estimated_token_count": 309, "token_estimator": "heuristic-v1", "text": "## Using the Transaction Payment Pallet\n\nThe [Transaction Payment pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/transaction-payment){target=\\_blank} provides the basic logic for calculating the inclusion fee. You can also use the Transaction Payment pallet to:\n\n- Convert a weight value into a deductible fee based on a currency type using [`Config::WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\\_blank}.\n- Update the fee for the next block by defining a multiplier based on the chain’s final state at the end of the previous block using [`Config::FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\\_blank}.\n- Manage the withdrawal, refund, and deposit of transaction fees using [`Config::OnChargeTransaction`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.OnChargeTransaction){target=\\_blank}.\n\nYou can learn more about these configuration traits in the [Transaction Payment documentation](https://paritytech.github.io/polkadot-sdk/master/pallet_transaction_payment/index.html){target=\\_blank}."} -{"page_id": "reference-parachains-blocks-transactions-fees-fees", "page_title": "Transactions Weights and Fees", "index": 3, "depth": 3, "title": "Understanding the Inclusion Fee", "anchor": "understanding-the-inclusion-fee", "start_char": 4931, "end_char": 6255, "estimated_token_count": 278, "token_estimator": "heuristic-v1", "text": "### Understanding the Inclusion Fee\n\nThe formula for calculating the inclusion fee is as follows:\n\n```text\ninclusion_fee = base_fee + length_fee + [targeted_fee_adjustment * weight_fee]\n```\n\nAnd then, for calculating the final fee:\n\n```text\nfinal_fee = inclusion_fee + tip\n```\n\nIn the first formula, the `targeted_fee_adjustment` is a multiplier that can tune the final fee based on the network’s congestion.\n\n- The `base_fee` derived from the base weight covers inclusion overhead like signature verification.\n- The `length_fee` is a per-byte fee that is multiplied by the length of the encoded extrinsic.\n- The `weight_fee` fee is calculated using two parameters:\n - The `ExtrinsicBaseWeight` that is declared in the runtime and applies to all extrinsics.\n - The `#[pallet::weight]` annotation that accounts for an extrinsic's complexity.\n\nTo convert the weight to `Currency`, the runtime must define a `WeightToFee` struct that implements a conversion function, [`Convert`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/struct.Pallet.html#method.weight_to_fee){target=\\_blank}.\n\nNote that the extrinsic sender is charged the inclusion fee before the extrinsic is invoked. The fee is deducted from the sender's balance even if the transaction fails upon execution."} -{"page_id": "reference-parachains-blocks-transactions-fees-fees", "page_title": "Transactions Weights and Fees", "index": 4, "depth": 3, "title": "Accounts with an Insufficient Balance", "anchor": "accounts-with-an-insufficient-balance", "start_char": 6255, "end_char": 6816, "estimated_token_count": 104, "token_estimator": "heuristic-v1", "text": "### Accounts with an Insufficient Balance\n\nIf an account does not have a sufficient balance to pay the inclusion fee and remain alive—that is, enough to pay the inclusion fee and maintain the minimum existential deposit—then you should ensure the transaction is canceled so that no fee is deducted and the transaction does not begin execution.\n\nThe Polkadot SDK doesn't enforce this rollback behavior. However, this scenario would be rare because the transaction queue and block-making logic perform checks to prevent it before adding an extrinsic to a block."} -{"page_id": "reference-parachains-blocks-transactions-fees-fees", "page_title": "Transactions Weights and Fees", "index": 5, "depth": 3, "title": "Fee Multipliers", "anchor": "fee-multipliers", "start_char": 6816, "end_char": 8034, "estimated_token_count": 260, "token_estimator": "heuristic-v1", "text": "### Fee Multipliers\n\nThe inclusion fee formula always results in the same fee for the same input. However, weight can be dynamic and—based on how [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\\_blank} is defined—the final fee can include some degree of variability.\nThe Transaction Payment pallet provides the [`FeeMultiplierUpdate`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.FeeMultiplierUpdate){target=\\_blank} configurable parameter to account for this variability.\n\nThe Polkadot network inspires the default update function and implements a targeted adjustment in which a target saturation level of block weight is defined. If the previous block is more saturated, the fees increase slightly. Similarly, if the last block has fewer transactions than the target, fees are decreased by a small amount. For more information about fee multiplier adjustments, see the [Web3 Research Page](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\\_blank}."} -{"page_id": "reference-parachains-blocks-transactions-fees-fees", "page_title": "Transactions Weights and Fees", "index": 6, "depth": 2, "title": "Transactions with Special Requirements", "anchor": "transactions-with-special-requirements", "start_char": 8034, "end_char": 9446, "estimated_token_count": 277, "token_estimator": "heuristic-v1", "text": "## Transactions with Special Requirements\n\nInclusion fees must be computable before execution and can only represent fixed logic. Some transactions warrant limiting resources with other strategies. For example:\n\n- Bonds are a type of fee that might be returned or slashed after some on-chain event. For example, you might want to require users to place a bond to participate in a vote. The bond might then be returned at the end of the referendum or slashed if the voter attempted malicious behavior.\n- Deposits are fees that might be returned later. For example, you might require users to pay a deposit to execute an operation that uses storage. The user’s deposit could be returned if a subsequent operation frees up storage.\n- Burn operations are used to pay for a transaction based on its internal logic. For example, a transaction might burn funds from the sender if the transaction creates new storage items to pay for the increased state size.\n- Limits enable you to enforce constant or configurable limits on specific operations. For example, the default [Staking pallet](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/substrate/frame/staking){target=\\_blank} only allows nominators to nominate 16 validators to limit the complexity of the validator election process.\n\nIt is important to note that if you query the chain for a transaction fee, it only returns the inclusion fee."} -{"page_id": "reference-parachains-blocks-transactions-fees-fees", "page_title": "Transactions Weights and Fees", "index": 7, "depth": 2, "title": "Default Weight Annotations", "anchor": "default-weight-annotations", "start_char": 9446, "end_char": 10104, "estimated_token_count": 146, "token_estimator": "heuristic-v1", "text": "## Default Weight Annotations\n\nAll dispatchable functions in the Polkadot SDK must specify a weight. The way of doing that is using the annotation-based system that lets you combine fixed values for database read/write weight and/or fixed values based on benchmarks. The most basic example would look like this:\n\n```rust\n#[pallet::weight(100_000)]\nfn my_dispatchable() {\n // ...\n}\n```\n\nNote that the [`ExtrinsicBaseWeight`](https://crates.parity.io/frame_support/weights/constants/struct.ExtrinsicBaseWeight.html){target=\\_blank} is automatically added to the declared weight to account for the costs of simply including an empty extrinsic into a block."} -{"page_id": "reference-parachains-blocks-transactions-fees-fees", "page_title": "Transactions Weights and Fees", "index": 8, "depth": 3, "title": "Weights and Database Read/Write Operations", "anchor": "weights-and-database-readwrite-operations", "start_char": 10104, "end_char": 11244, "estimated_token_count": 264, "token_estimator": "heuristic-v1", "text": "### Weights and Database Read/Write Operations\n\nTo make weight annotations independent of the deployed database backend, they are defined as a constant and then used in the annotations when expressing database accesses performed by the dispatchable:\n\n```rust\n#[pallet::weight(T::DbWeight::get().reads_writes(1, 2) + 20_000)]\nfn my_dispatchable() {\n // ...\n}\n```\n\nThis dispatchable allows one database to read and two to write, in addition to other things that add the additional 20,000. Database access is generally every time a value declared inside the [`#[pallet::storage]`](https://paritytech.github.io/polkadot-sdk/master/frame_support/pallet_macros/attr.storage.html){target=\\_blank} block is accessed. However, unique accesses are counted because after a value is accessed, it is cached, and reaccessing it does not result in a database operation. That is:\n\n- Multiple reads of the exact value count as one read.\n- Multiple writes of the exact value count as one write.\n- Multiple reads of the same value, followed by a write to that value, count as one read and one write.\n- A write followed by a read-only counts as one write."} -{"page_id": "reference-parachains-blocks-transactions-fees-fees", "page_title": "Transactions Weights and Fees", "index": 9, "depth": 3, "title": "Dispatch Classes", "anchor": "dispatch-classes", "start_char": 11244, "end_char": 13982, "estimated_token_count": 571, "token_estimator": "heuristic-v1", "text": "### Dispatch Classes\n\nDispatches are broken into three classes:\n\n- Normal\n- Operational\n- Mandatory\n\nIf a dispatch is not defined as `Operational` or `Mandatory` in the weight annotation, the dispatch is identified as `Normal` by default. You can specify that the dispatchable uses another class like this:\n\n```rust\n#[pallet::dispatch((DispatchClass::Operational))]\nfn my_dispatchable() {\n // ...\n}\n```\n\nThis tuple notation also allows you to specify a final argument determining whether the user is charged based on the annotated weight. If you don't specify otherwise, `Pays::Yes` is assumed:\n\n```rust\n#[pallet::dispatch(DispatchClass::Normal, Pays::No)]\nfn my_dispatchable() {\n // ...\n}\n```\n\n#### Normal Dispatches\n\nDispatches in this class represent normal user-triggered transactions. These types of dispatches only consume a portion of a block's total weight limit. For information about the maximum portion of a block that can be consumed for normal dispatches, see [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\\_blank}. Normal dispatches are sent to the transaction pool.\n\n#### Operational Dispatches\n\nUnlike normal dispatches, which represent the usage of network capabilities, operational dispatches are those that provide network capabilities. Operational dispatches can consume the entire weight limit of a block. They are not bound by the [`AvailableBlockRatio`](https://paritytech.github.io/polkadot-sdk/master/frame_system/limits/struct.BlockLength.html){target=\\_blank}. Dispatches in this class are given maximum priority and are exempt from paying the [`length_fee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/){target=\\_blank}.\n\n#### Mandatory Dispatches\n\nMandatory dispatches are included in a block even if they cause the block to surpass its weight limit. You can only use the mandatory dispatch class for inherent transactions that the block author submits. This dispatch class is intended to represent functions in the block validation process. Because these dispatches are always included in a block regardless of the function weight, the validation process must prevent malicious nodes from abusing the function to craft valid but impossibly heavy blocks. You can typically accomplish this by ensuring that:\n\n- The operation performed is always light.\n- The operation can only be included in a block once.\n\nTo make it more difficult for malicious nodes to abuse mandatory dispatches, they cannot be included in blocks that return errors. This dispatch class serves the assumption that it is better to allow an overweight block to be created than not to allow any block to be created at all."} -{"page_id": "reference-parachains-blocks-transactions-fees-fees", "page_title": "Transactions Weights and Fees", "index": 10, "depth": 3, "title": "Dynamic Weights", "anchor": "dynamic-weights", "start_char": 13982, "end_char": 14529, "estimated_token_count": 132, "token_estimator": "heuristic-v1", "text": "### Dynamic Weights\n\nIn addition to purely fixed weights and constants, the weight calculation can consider the input arguments of a dispatchable. The weight should be trivially computable from the input arguments with some basic arithmetic:\n\n```rust\nuse frame_support:: {\n dispatch:: {\n DispatchClass::Normal,\n Pays::Yes,\n },\n weights::Weight,\n};\n\n#[pallet::weight(FunctionOf(\n |args: (&Vec,)| args.0.len().saturating_mul(10_000),\n )\n]\nfn handle_users(origin, calls: Vec) {\n // Do something per user\n}\n```"} -{"page_id": "reference-parachains-blocks-transactions-fees-fees", "page_title": "Transactions Weights and Fees", "index": 11, "depth": 2, "title": "Post Dispatch Weight Correction", "anchor": "post-dispatch-weight-correction", "start_char": 14529, "end_char": 15153, "estimated_token_count": 131, "token_estimator": "heuristic-v1", "text": "## Post Dispatch Weight Correction\n\nDepending on the execution logic, a dispatchable function might consume less weight than was prescribed pre-dispatch. To correct weight, the function declares a different return type and returns its actual weight:\n\n```rust\n#[pallet::weight(10_000 + 500_000_000)]\nfn expensive_or_cheap(input: u64) -> DispatchResultWithPostInfo {\n let was_heavy = do_calculation(input);\n\n if (was_heavy) {\n // None means \"no correction\" from the weight annotation.\n Ok(None.into())\n } else {\n // Return the actual weight consumed.\n Ok(Some(10_000).into())\n }\n}\n```"} -{"page_id": "reference-parachains-blocks-transactions-fees-fees", "page_title": "Transactions Weights and Fees", "index": 12, "depth": 2, "title": "Custom Fees", "anchor": "custom-fees", "start_char": 15153, "end_char": 15269, "estimated_token_count": 20, "token_estimator": "heuristic-v1", "text": "## Custom Fees\n\nYou can also define custom fee systems through custom weight functions or inclusion fee functions."} -{"page_id": "reference-parachains-blocks-transactions-fees-fees", "page_title": "Transactions Weights and Fees", "index": 13, "depth": 3, "title": "Custom Weights", "anchor": "custom-weights", "start_char": 15269, "end_char": 19797, "estimated_token_count": 1044, "token_estimator": "heuristic-v1", "text": "### Custom Weights\n\nInstead of using the default weight annotations, you can create a custom weight calculation type using the weights module. The custom weight calculation type must implement the following traits:\n\n- [`WeighData`](https://crates.parity.io/frame_support/weights/trait.WeighData.html){target=\\_blank} to determine the weight of the dispatch.\n- [`ClassifyDispatch`](https://crates.parity.io/frame_support/weights/trait.ClassifyDispatch.html){target=\\_blank} to determine the class of the dispatch.\n- [`PaysFee`](https://crates.parity.io/frame_support/weights/trait.PaysFee.html){target=\\_blank} to determine whether the sender of the dispatch pays fees.\n \nThe Polkadot SDK then bundles the output information of the three traits into the [`DispatchInfo`](https://paritytech.github.io/polkadot-sdk/master/frame_support/dispatch/struct.DispatchInfo.html){target=\\_blank} struct and provides it by implementing the [`GetDispatchInfo`](https://docs.rs/frame-support/latest/frame_support/dispatch/trait.GetDispatchInfo.html){target=\\_blank} for all `Call` variants and opaque extrinsic types. This is used internally by the System and Executive modules.\n\n`ClassifyDispatch`, `WeighData`, and `PaysFee` are generic over T, which gets resolved into the tuple of all dispatch arguments except for the origin. The following example illustrates a struct that calculates the weight as `m * len(args)`, where `m` is a given multiplier and args is the concatenated tuple of all dispatch arguments. In this example, the dispatch class is `Operational` if the transaction has more than 100 bytes of length in arguments and will pay fees if the encoded length exceeds 10 bytes.\n\n```rust\nstruct LenWeight(u32);\nimpl WeighData for LenWeight {\n fn weigh_data(&self, target: T) -> Weight {\n let multiplier = self.0;\n let encoded_len = target.encode().len() as u32;\n multiplier * encoded_len\n }\n}\n\nimpl ClassifyDispatch for LenWeight {\n fn classify_dispatch(&self, target: T) -> DispatchClass {\n let encoded_len = target.encode().len() as u32;\n if encoded_len > 100 {\n DispatchClass::Operational\n } else {\n DispatchClass::Normal\n }\n }\n}\n\nimpl PaysFee {\n fn pays_fee(&self, target: T) -> Pays {\n let encoded_len = target.encode().len() as u32;\n if encoded_len > 10 {\n Pays::Yes\n } else {\n Pays::No\n }\n }\n}\n```\n\nA weight calculator function can also be coerced to the final type of the argument instead of defining it as a vague type that can be encoded. The code would roughly look like this:\n\n```rust\nstruct CustomWeight;\nimpl WeighData<(&u32, &u64)> for CustomWeight {\n fn weigh_data(&self, target: (&u32, &u64)) -> Weight {\n ...\n }\n}\n\n// given a dispatch:\n#[pallet::call]\nimpl, I: 'static> Pallet {\n #[pallet::weight(CustomWeight)]\n fn foo(a: u32, b: u64) { ... }\n}\n```\n\nIn this example, the `CustomWeight` can only be used in conjunction with a dispatch with a particular signature `(u32, u64)`, as opposed to `LenWeight`, which can be used with anything because there aren't any assumptions about ``.\n\n#### Custom Inclusion Fee\n\nThe following example illustrates how to customize your inclusion fee. You must configure the appropriate associated types in the respective module.\n\n```rust\n// Assume this is the balance type\ntype Balance = u64;\n\n// Assume we want all the weights to have a `100 + 2 * w` conversion to fees\nstruct CustomWeightToFee;\nimpl WeightToFee for CustomWeightToFee {\n fn convert(w: Weight) -> Balance {\n let a = Balance::from(100);\n let b = Balance::from(2);\n let w = Balance::from(w);\n a + b * w\n }\n}\n\nparameter_types! {\n pub const ExtrinsicBaseWeight: Weight = 10_000_000;\n}\n\nimpl frame_system::Config for Runtime {\n type ExtrinsicBaseWeight = ExtrinsicBaseWeight;\n}\n\nparameter_types! {\n pub const TransactionByteFee: Balance = 10;\n}\n\nimpl transaction_payment::Config {\n type TransactionByteFee = TransactionByteFee;\n type WeightToFee = CustomWeightToFee;\n type FeeMultiplierUpdate = TargetedFeeAdjustment;\n}\n\nstruct TargetedFeeAdjustment(sp_std::marker::PhantomData);\nimpl> WeightToFee for TargetedFeeAdjustment {\n fn convert(multiplier: Fixed128) -> Fixed128 {\n // Don't change anything. Put any fee update info here.\n multiplier\n }\n}\n```"} -{"page_id": "reference-parachains-blocks-transactions-fees-fees", "page_title": "Transactions Weights and Fees", "index": 14, "depth": 2, "title": "Additional Resources", "anchor": "additional-resources", "start_char": 19797, "end_char": 20800, "estimated_token_count": 233, "token_estimator": "heuristic-v1", "text": "## Additional Resources\n\nYou now know the weight system, how it affects transaction fee computation, and how to specify weights for your dispatchable calls. The next step is determining the correct weight for your dispatchable operations. You can use Substrate benchmarking functions and frame-benchmarking calls to test your functions with different parameters and empirically determine the proper weight in their worst-case scenarios.\n\n- [Benchmark](/parachains/customize-runtime/pallet-development/benchmark-pallet/)\n- [`SignedExtension`](https://paritytech.github.io/polkadot-sdk/master/sp_runtime/traits/trait.SignedExtension.html){target=\\_blank}\n- [Custom weights for the Example pallet](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/substrate/frame/examples/basic/src/weights.rs){target=\\_blank}\n- [Web3 Foundation Research](https://research.web3.foundation/Polkadot/overview/token-economics#relay-chain-transaction-fees-and-per-block-transaction-limits){target=\\_blank}"} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 16, "end_char": 655, "estimated_token_count": 108, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nTransactions are essential components of blockchain networks, enabling state changes and the execution of key operations. In the Polkadot SDK, transactions, often called extrinsics, come in multiple forms, including signed, unsigned, and inherent transactions.\n\nThis guide walks you through the different transaction types and how they're formatted, validated, and processed within the Polkadot ecosystem. You'll also learn how to customize transaction formats and construct transactions for FRAME-based runtimes, ensuring a complete understanding of how transactions are built and executed in Polkadot SDK-based chains."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 1, "depth": 2, "title": "What Is a Transaction?", "anchor": "what-is-a-transaction", "start_char": 655, "end_char": 1674, "estimated_token_count": 193, "token_estimator": "heuristic-v1", "text": "## What Is a Transaction?\n\nIn the Polkadot SDK, transactions represent operations that modify the chain's state, bundled into blocks for execution. The term extrinsic is often used to refer to any data that originates outside the runtime and is included in the chain. While other blockchain systems typically refer to these operations as \"transactions,\" the Polkadot SDK adopts the broader term \"extrinsic\" to capture the wide variety of data types that can be added to a block.\n\nThere are three primary types of transactions (extrinsics) in the Polkadot SDK:\n\n- **Signed transactions**: Signed by the submitting account, often carrying transaction fees.\n- **Unsigned transactions**: Submitted without a signature, often requiring custom validation logic.\n- **Inherent transactions**: Typically inserted directly into blocks by block authoring nodes, without gossiping between peers.\n\nEach type serves a distinct purpose, and understanding when and how to use each is key to efficiently working with the Polkadot SDK."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 2, "depth": 3, "title": "Signed Transactions", "anchor": "signed-transactions", "start_char": 1674, "end_char": 2838, "estimated_token_count": 221, "token_estimator": "heuristic-v1", "text": "### Signed Transactions\n\nSigned transactions require an account's signature and typically involve submitting a request to execute a runtime call. The signature serves as a form of cryptographic proof that the sender has authorized the action, using their private key. These transactions often involve a transaction fee to cover the cost of execution and incentivize block producers.\n\nSigned transactions are the most common type of transaction and are integral to user-driven actions, such as token transfers. For instance, when you transfer tokens from one account to another, the sending account must sign the transaction to authorize the operation.\n\nFor example, the [`pallet_balances::Call::transfer_allow_death`](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/pallet/struct.Pallet.html#method.transfer_allow_death){target=\\_blank} extrinsic in the Balances pallet allows you to transfer tokens. Since your account initiates this transaction, your account key is used to sign it. You'll also be responsible for paying the associated transaction fee, with the option to include an additional tip to incentivize faster inclusion in the block."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 3, "depth": 3, "title": "Unsigned Transactions", "anchor": "unsigned-transactions", "start_char": 2838, "end_char": 4091, "estimated_token_count": 235, "token_estimator": "heuristic-v1", "text": "### Unsigned Transactions\n\nUnsigned transactions do not require a signature or account-specific data from the sender. Unlike signed transactions, they do not come with any form of economic deterrent, such as fees, which makes them susceptible to spam or replay attacks. Custom validation logic must be implemented to mitigate these risks and ensure these transactions are secure.\n\nUnsigned transactions typically involve scenarios where including a fee or signature is unnecessary or counterproductive. However, due to the absence of fees, they require careful validation to protect the network. For example, [`pallet_im_online::Call::heartbeat`](https://paritytech.github.io/polkadot-sdk/master/pallet_im_online/pallet/struct.Pallet.html#method.heartbeat){target=\\_blank} extrinsic allows validators to send a heartbeat signal, indicating they are active. Since only validators can make this call, the logic embedded in the transaction ensures that the sender is a validator, making the need for a signature or fee redundant.\n\nUnsigned transactions are more resource-intensive than signed ones because custom validation is required, but they play a crucial role in certain operational scenarios, especially when regular user accounts aren't involved."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 4, "depth": 3, "title": "Inherent Transactions", "anchor": "inherent-transactions", "start_char": 4091, "end_char": 5815, "estimated_token_count": 327, "token_estimator": "heuristic-v1", "text": "### Inherent Transactions\n\nInherent transactions are a specialized type of unsigned transaction that is used primarily for block authoring. Unlike signed or other unsigned transactions, inherent transactions are added directly by block producers and are not broadcasted to the network or stored in the transaction queue. They don't require signatures or the usual validation steps and are generally used to insert system-critical data directly into blocks.\n\nA key example of an inherent transaction is inserting a timestamp into each block. The [`pallet_timestamp::Call::now`](https://paritytech.github.io/polkadot-sdk/master/pallet_timestamp/pallet/struct.Pallet.html#method.now-1){target=\\_blank} extrinsic allows block authors to include the current time in the block they are producing. Since the block producer adds this information, there is no need for transaction validation, like signature verification. The validation in this case is done indirectly by the validators, who check whether the timestamp is within an acceptable range before finalizing the block.\n\nAnother example is the [`paras_inherent::Call::enter`](https://paritytech.github.io/polkadot-sdk/master/polkadot_runtime_parachains/paras_inherent/pallet/struct.Pallet.html#method.enter){target=\\_blank} extrinsic, which enables parachain collator nodes to send validation data to the relay chain. This inherent transaction ensures that the necessary parachain data is included in each block without the overhead of gossiped transactions.\n\nInherent transactions serve a critical role in block authoring by allowing important operational data to be added directly to the chain without needing the validation processes required for standard transactions."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 5, "depth": 2, "title": "Transaction Formats", "anchor": "transaction-formats", "start_char": 5815, "end_char": 6164, "estimated_token_count": 58, "token_estimator": "heuristic-v1", "text": "## Transaction Formats\n\nUnderstanding the structure of signed and unsigned transactions is crucial for developers building on Polkadot SDK-based chains. Whether you're optimizing transaction processing, customizing formats, or interacting with the transaction pool, knowing the format of extrinsics, Polkadot's term for transactions, is essential."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 6, "depth": 3, "title": "Types of Transaction Formats", "anchor": "types-of-transaction-formats", "start_char": 6164, "end_char": 7058, "estimated_token_count": 163, "token_estimator": "heuristic-v1", "text": "### Types of Transaction Formats\n\nIn Polkadot SDK-based chains, extrinsics can fall into three main categories:\n\n- **Unchecked extrinsics**: Typically used for signed transactions that require validation. They contain a signature and additional data, such as a nonce and information for fee calculation. Unchecked extrinsics are named as such because they require validation checks before being accepted into the transaction pool.\n- **Checked extrinsics**: Typically used for inherent extrinsics (unsigned transactions); these don't require signature verification. Instead, they carry information such as where the extrinsic originates and any additional data required for the block authoring process.\n- **Opaque extrinsics**: Used when the format of an extrinsic is not yet fully committed or finalized. They are still decodable, but their structure can be flexible depending on the context."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 7, "depth": 3, "title": "Signed Transaction Data Structure", "anchor": "signed-transaction-data-structure", "start_char": 7058, "end_char": 8020, "estimated_token_count": 195, "token_estimator": "heuristic-v1", "text": "### Signed Transaction Data Structure\n\nA signed transaction typically includes the following components:\n\n- **Signature**: Verifies the authenticity of the transaction sender.\n- **Call**: The actual function or method call the transaction is requesting (for example, transferring funds).\n- **Nonce**: Tracks the number of prior transactions sent from the account, helping to prevent replay attacks.\n- **Tip**: An optional incentive to prioritize the transaction in block inclusion.\n- **Additional data**: Includes details such as spec version, block hash, and genesis hash to ensure the transaction is valid within the correct runtime and chain context.\n\nHere's a simplified breakdown of how signed transactions are typically constructed in a Polkadot SDK runtime:\n\n``` code\n + + \n```\n\nEach part of the signed transaction has a purpose, ensuring the transaction's authenticity and context within the blockchain."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 8, "depth": 3, "title": "Signed Extensions", "anchor": "signed-extensions", "start_char": 8020, "end_char": 10654, "estimated_token_count": 610, "token_estimator": "heuristic-v1", "text": "### Signed Extensions\n\nPolkadot SDK also provides the concept of [signed extensions](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/signed_extensions/index.html){target=\\_blank}, which allow developers to extend extrinsics with additional data or validation logic before they are included in a block. The [`SignedExtension`](https://paritytech.github.io/try-runtime-cli/sp_runtime/traits/trait.SignedExtension.html){target=\\_blank} set helps enforce custom rules or protections, such as ensuring the transaction's validity or calculating priority.\n\nThe transaction queue regularly calls signed extensions to verify a transaction's validity before placing it in the ready queue. This safeguard ensures transactions won't fail in a block. Signed extensions are commonly used to enforce validation logic and protect the transaction pool from spam and replay attacks.\n\nIn FRAME, a signed extension can hold any of the following types by default:\n\n- **[`AccountId`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/runtime/types_common/type.AccountId.html){target=\\_blank}**: To encode the sender's identity.\n- **[`Call`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Call){target=\\_blank}**: To encode the pallet call to be dispatched. This data is used to calculate transaction fees.\n- **[`AdditionalSigned`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.AdditionalSigned){target=\\_blank}**: To handle any additional data to go into the signed payload allowing you to attach any custom logic prior to dispatching a transaction.\n- **[`Pre`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/traits/trait.SignedExtension.html#associatedtype.Pre){target=\\_blank}**: To encode the information that can be passed from before a call is dispatched to after it gets dispatched.\n\nSigned extensions can enforce checks like:\n\n- **[`CheckSpecVersion`](https://paritytech.github.io/polkadot-sdk/master/src/frame_system/extensions/check_spec_version.rs.html){target=\\_blank}**: Ensures the transaction is compatible with the runtime's current version.\n- **[`CheckWeight`](https://paritytech.github.io/polkadot-sdk/master/frame_system/struct.CheckWeight.html){target=\\_blank}**: Calculates the weight (or computational cost) of the transaction, ensuring the block doesn't exceed the maximum allowed weight.\n\nThese extensions are critical in the transaction lifecycle, ensuring that only valid and prioritized transactions are processed."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 9, "depth": 2, "title": "Transaction Construction", "anchor": "transaction-construction", "start_char": 10654, "end_char": 10991, "estimated_token_count": 56, "token_estimator": "heuristic-v1", "text": "## Transaction Construction\n\nBuilding transactions in the Polkadot SDK involves constructing a payload that can be verified, signed, and submitted for inclusion in a block. Each runtime in the Polkadot SDK has its own rules for validating and executing transactions, but there are common patterns for constructing a signed transaction."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 10, "depth": 3, "title": "Construct a Signed Transaction", "anchor": "construct-a-signed-transaction", "start_char": 10991, "end_char": 12900, "estimated_token_count": 404, "token_estimator": "heuristic-v1", "text": "### Construct a Signed Transaction\n\nA signed transaction in the Polkadot SDK includes various pieces of data to ensure security, prevent replay attacks, and prioritize processing. Here's an overview of how to construct one:\n\n1. **Construct the unsigned payload**: Gather the necessary information for the call, including:\n\n - **Pallet index**: Identifies the pallet where the runtime function resides.\n - **Function index**: Specifies the particular function to call in the pallet.\n - **Parameters**: Any additional arguments required by the function call.\n\n2. **Create a signing payload**: Once the unsigned payload is ready, additional data must be included:\n\n - **Transaction nonce**: Unique identifier to prevent replay attacks.\n - **Era information**: Defines how long the transaction is valid before it's dropped from the pool.\n - **Block hash**: Ensures the transaction doesn't execute on the wrong chain or fork.\n\n3. **Sign the payload**: Using the sender's private key, sign the payload to ensure that the transaction can only be executed by the account holder.\n4. **Serialize the signed payload**: Once signed, the transaction must be serialized into a binary format, ensuring the data is compact and easy to transmit over the network.\n5. **Submit the serialized transaction**: Finally, submit the serialized transaction to the network, where it will enter the transaction pool and wait for processing by an authoring node.\n\nThe following is an example of how a signed transaction might look:\n\n``` rust\nnode_runtime::UncheckedExtrinsic::new_signed(\n function.clone(), // some call\n sp_runtime::AccountId32::from(sender.public()).into(), // some sending account\n node_runtime::Signature::Sr25519(signature.clone()), // the account's signature\n extra.clone(), // the signed extensions\n)\n```"} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 11, "depth": 3, "title": "Transaction Encoding", "anchor": "transaction-encoding", "start_char": 12900, "end_char": 13898, "estimated_token_count": 225, "token_estimator": "heuristic-v1", "text": "### Transaction Encoding\n\nBefore a transaction is sent to the network, it is serialized and encoded using a structured encoding process that ensures consistency and prevents tampering:\n\n- **`[1]`**: Compact encoded length in bytes of the entire transaction.\n- **`[2]`**: A u8 containing 1 byte to indicate whether the transaction is signed or unsigned (1 bit) and the encoded transaction version ID (7 bits).\n- **`[3]`**: If signed, this field contains an account ID, an SR25519 signature, and some extra data.\n- **`[4]`**: Encoded call data, including pallet and function indices and any required arguments.\n\nThis encoded format ensures consistency and efficiency in processing transactions across the network. By adhering to this format, applications can construct valid transactions and pass them to the network for execution.\n\nTo learn more about how compact encoding works using SCALE, see the [SCALE Codec](https://github.com/paritytech/parity-scale-codec){target=\\_blank} README on GitHub."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 12, "depth": 3, "title": "Customize Transaction Construction", "anchor": "customize-transaction-construction", "start_char": 13898, "end_char": 14538, "estimated_token_count": 112, "token_estimator": "heuristic-v1", "text": "### Customize Transaction Construction\n\nAlthough the basic steps for constructing transactions are consistent across Polkadot SDK-based chains, developers can customize transaction formats and validation rules. For example:\n\n- **Custom pallets**: You can define new pallets with custom function calls, each with its own parameters and validation logic.\n- **Signed extensions**: Developers can implement custom extensions that modify how transactions are prioritized, validated, or included in blocks.\n\nBy leveraging Polkadot SDK's modular design, developers can create highly specialized transaction logic tailored to their chain's needs."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 13, "depth": 2, "title": "Lifecycle of a Transaction", "anchor": "lifecycle-of-a-transaction", "start_char": 14538, "end_char": 15016, "estimated_token_count": 81, "token_estimator": "heuristic-v1", "text": "## Lifecycle of a Transaction\n\nIn the Polkadot SDK, transactions are often referred to as extrinsics because the data in transactions originates outside of the runtime. These transactions contain data that initiates changes to the chain state. The most common type of extrinsic is a signed transaction, which is cryptographically verified and typically incurs a fee. This section focuses on how signed transactions are processed, validated, and ultimately included in a block."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 14, "depth": 3, "title": "Define Transaction Properties", "anchor": "define-transaction-properties", "start_char": 15016, "end_char": 15747, "estimated_token_count": 146, "token_estimator": "heuristic-v1", "text": "### Define Transaction Properties\n\nThe Polkadot SDK runtime defines key transaction properties, such as:\n\n- **Transaction validity**: Ensures the transaction meets all runtime requirements.\n- **Signed or unsigned**: Identifies whether a transaction needs to be signed by an account.\n- **State changes**: Determines how the transaction modifies the state of the chain.\n\nPallets, which compose the runtime's logic, define the specific transactions that your chain supports. When a user submits a transaction, such as a token transfer, it becomes a signed transaction, verified by the user's account signature. If the account has enough funds to cover fees, the transaction is executed, and the chain's state is updated accordingly."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 15, "depth": 3, "title": "Process on a Block Authoring Node", "anchor": "process-on-a-block-authoring-node", "start_char": 15747, "end_char": 16444, "estimated_token_count": 135, "token_estimator": "heuristic-v1", "text": "### Process on a Block Authoring Node\n\nIn Polkadot SDK-based networks, some nodes are authorized to author blocks. These nodes validate and process transactions. When a transaction is sent to a node that can produce blocks, it undergoes a lifecycle that involves several stages, including validation and execution. Non-authoring nodes gossip the transaction across the network until an authoring node receives it. The following diagram illustrates the lifecycle of a transaction that's submitted to a network and processed by an authoring node.\n\n![Transaction lifecycle diagram](/images/reference/parachains/blocks-transactions-fees/transactions/transactions-01.webp){ style=\"background:white\" }"} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 16, "depth": 3, "title": "Validate and Queue", "anchor": "validate-and-queue", "start_char": 16444, "end_char": 18688, "estimated_token_count": 436, "token_estimator": "heuristic-v1", "text": "### Validate and Queue\n\nOnce a transaction reaches an authoring node, it undergoes an initial validation process to ensure it meets specific conditions defined in the runtime. This validation includes checks for:\n\n- **Correct nonce**: Ensures the transaction is sequentially valid for the account.\n- **Sufficient funds**: Confirms the account can cover any associated transaction fees.\n- **Signature validity**: Verifies that the sender's signature matches the transaction data.\n\nAfter these checks, valid transactions are placed in the transaction pool, where they are queued for inclusion in a block. The transaction pool regularly re-validates queued transactions to ensure they remain valid before being processed. To reach consensus, two-thirds of the nodes must agree on the order of the transactions executed and the resulting state change. Transactions are validated and queued on the local node in a transaction pool to prepare for consensus.\n\n#### Transaction Pool\n\nThe transaction pool is responsible for managing valid transactions. It ensures that only transactions that pass initial validity checks are queued. Transactions that fail validation, expire, or become invalid for other reasons are removed from the pool.\n\nThe transaction pool organizes transactions into two queues:\n\n- **Ready queue**: Transactions that are valid and ready to be included in a block.\n- **Future queue**: Transactions that are not yet valid but could be in the future, such as transactions with a nonce too high for the current state.\n\nDetails on how the transaction pool validates transactions, including fee and signature handling, can be found in the [`validate_transaction`](https://paritytech.github.io/polkadot-sdk/master/sp_transaction_pool/runtime_api/trait.TaggedTransactionQueue.html#method.validate_transaction){target=\\_blank} method.\n\n#### Invalid Transactions\n\nIf a transaction is invalid, for example, due to an invalid signature or insufficient funds, it is rejected and won't be added to the block. Invalid transactions might be rejected for reasons such as:\n\n- The transaction has already been included in a block.\n- The transaction's signature does not match the sender.\n- The transaction is too large to fit in the current block."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 17, "depth": 3, "title": "Transaction Ordering and Priority", "anchor": "transaction-ordering-and-priority", "start_char": 18688, "end_char": 19326, "estimated_token_count": 128, "token_estimator": "heuristic-v1", "text": "### Transaction Ordering and Priority\n\nWhen a node is selected as the next block author, it prioritizes transactions based on weight, length, and tip amount. The goal is to fill the block with high-priority transactions without exceeding its maximum size or computational limits. Transactions are ordered as follows:\n\n- **Inherents first**: Inherent transactions, such as block timestamp updates, are always placed first.\n- **Nonce-based ordering**: Transactions from the same account are ordered by their nonce.\n- **Fee-based ordering**: Among transactions with the same nonce or priority level, those with higher fees are prioritized."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 18, "depth": 3, "title": "Transaction Execution", "anchor": "transaction-execution", "start_char": 19326, "end_char": 19943, "estimated_token_count": 114, "token_estimator": "heuristic-v1", "text": "### Transaction Execution\n\nOnce a block author selects transactions from the pool, the transactions are executed in priority order. As each transaction is processed, the state changes are written directly to the chain's storage. It's important to note that these changes are not cached, meaning a failed transaction won't revert earlier state changes, which could leave the block in an inconsistent state.\n\nEvents are also written to storage. Runtime logic should not emit an event before performing the associated actions. If the associated transaction fails after the event was emitted, the event will not revert."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 19, "depth": 2, "title": "Transaction Mortality", "anchor": "transaction-mortality", "start_char": 19943, "end_char": 21474, "estimated_token_count": 279, "token_estimator": "heuristic-v1", "text": "## Transaction Mortality\n\nTransactions in the network can be configured as either mortal (with expiration) or immortal (without expiration). Every transaction payload contains a block checkpoint (reference block number and hash) and an era/validity period that determines how many blocks after the checkpoint the transaction remains valid.\n\nWhen a transaction is submitted, the network validates it against these parameters. If the transaction is not included in a block within the specified validity window, it is automatically removed from the transaction queue.\n\n- **Mortal transactions**: Have a finite lifespan and will expire after a specified number of blocks. For example, a transaction with a block checkpoint of 1000 and a validity period of 64 blocks will be valid from blocks 1000 to 1064.\n\n- **Immortal transactions**: Never expire and remain valid indefinitely. To create an immortal transaction, set the block checkpoint to 0 (genesis block), use the genesis hash as a reference, and set the validity period to 0.\n\nHowever, immortal transactions pose significant security risks through replay attacks. If an account is reaped (balance drops to zero, account removed) and later re-funded, malicious actors can replay old immortal transactions.\n\nThe blockchain maintains only a limited number of prior block hashes for reference validation, called `BlockHashCount`. If your validity period exceeds `BlockHashCount`, the effective validity period becomes the minimum of your specified period and the block hash count."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 20, "depth": 2, "title": "Unique Identifiers for Extrinsics", "anchor": "unique-identifiers-for-extrinsics", "start_char": 21474, "end_char": 23370, "estimated_token_count": 427, "token_estimator": "heuristic-v1", "text": "## Unique Identifiers for Extrinsics\n\nTransaction hashes are **not unique identifiers** in Polkadot SDK-based chains.\n\nKey differences from traditional blockchains:\n\n- Transaction hashes serve only as fingerprints of transaction information.\n- Multiple valid transactions can share the same hash.\n- Hash uniqueness assumptions lead to serious issues.\n\nFor example, when an account is reaped (removed due to insufficient balance) and later recreated, it resets to nonce 0, allowing identical transactions to be valid at different points:\n\n| Block | Extrinsic Index | Hash | Origin | Nonce | Call | Result |\n|-------|----------------|------|-----------|-------|---------------------|-------------------------------|\n| 100 | 0 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Account A reaped |\n| 150 | 5 | 0x02 | Account B | 4 | Transfer 7 DOT to A | Account A created (nonce = 0) |\n| 200 | 2 | 0x01 | Account A | 0 | Transfer 5 DOT to B | Successful transaction |\n\nNotice that blocks 100 and 200 contain transactions with identical hashes (0x01) but are completely different, valid operations occurring at different times.\n\nAdditional complexity comes from Polkadot SDK's origin abstraction. Origins can represent collectives, governance bodies, or other non-account entities that don't maintain nonces like regular accounts and might dispatch identical calls multiple times with the same hash values. Each execution occurs in different chain states with different results.\n\nThe correct way to uniquely identify an extrinsic on a Polkadot SDK-based chain is to use the block ID (height or hash) and the extrinsic index. Since the Polkadot SDK defines blocks as headers plus ordered arrays of extrinsics, the index position within a canonical block provides guaranteed uniqueness."} -{"page_id": "reference-parachains-blocks-transactions-fees-transactions", "page_title": "Transactions", "index": 21, "depth": 2, "title": "Additional Resources", "anchor": "additional-resources", "start_char": 23370, "end_char": 23610, "estimated_token_count": 55, "token_estimator": "heuristic-v1", "text": "## Additional Resources\n\nFor a video overview of the lifecycle of transactions and the types of transactions that exist, see the [Transaction lifecycle](https://www.youtube.com/watch?v=3pfM0GOp02c){target=\\_blank} seminar from Parity Tech."} -{"page_id": "reference-parachains-chain-data", "page_title": "Chain Data", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 14, "end_char": 612, "estimated_token_count": 94, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nUnderstanding and leveraging on-chain data is a fundamental aspect of blockchain development. Whether you're building frontend applications or backend systems, accessing and decoding runtime metadata is vital to interacting with the blockchain. This guide introduces you to the tools and processes for generating and retrieving metadata, explains its role in application development, and outlines the additional APIs available for interacting with a Polkadot node. By mastering these components, you can ensure seamless communication between your applications and the blockchain."} -{"page_id": "reference-parachains-chain-data", "page_title": "Chain Data", "index": 1, "depth": 2, "title": "Application Development", "anchor": "application-development", "start_char": 612, "end_char": 1674, "estimated_token_count": 195, "token_estimator": "heuristic-v1", "text": "## Application Development\n\nYou might not be directly involved in building frontend applications as a blockchain developer. However, most applications that run on a blockchain require some form of frontend or user-facing client to enable users or other programs to access and modify the data that the blockchain stores. For example, you might develop a browser-based, mobile, or desktop application that allows users to submit transactions, post articles, view their assets, or track previous activity. The backend for that application is configured in the runtime logic for your blockchain, but the frontend client makes the runtime features accessible to your users.\n\nFor your custom chain to be useful to others, you'll need to provide a client application that allows users to view, interact with, or update information that the blockchain keeps track of. In this article, you'll learn how to expose information about your runtime so that client applications can use it, see examples of the information exposed, and explore tools and libraries that use it."} -{"page_id": "reference-parachains-chain-data", "page_title": "Chain Data", "index": 2, "depth": 2, "title": "Understand Metadata", "anchor": "understand-metadata", "start_char": 1674, "end_char": 2274, "estimated_token_count": 112, "token_estimator": "heuristic-v1", "text": "## Understand Metadata\n\nPolkadot SDK-based blockchain networks are designed to expose their runtime information, allowing developers to learn granular details regarding pallets, RPC calls, and runtime APIs. The metadata also exposes their related documentation. The chain's metadata is [SCALE-encoded](/reference/parachains/data-encoding/){target=\\_blank}, allowing for the development of browser-based, mobile, or desktop applications to support the chain's runtime upgrades seamlessly. It is also possible to develop applications compatible with multiple Polkadot SDK-based chains simultaneously."} -{"page_id": "reference-parachains-chain-data", "page_title": "Chain Data", "index": 3, "depth": 2, "title": "Expose Runtime Information as Metadata", "anchor": "expose-runtime-information-as-metadata", "start_char": 2274, "end_char": 3873, "estimated_token_count": 282, "token_estimator": "heuristic-v1", "text": "## Expose Runtime Information as Metadata\n\nTo interact with a node or the state of the blockchain, you need to know how to connect to the chain and access the exposed runtime features. This interaction involves a Remote Procedure Call (RPC) through a node endpoint address, commonly through a secure web socket connection.\n\nAn application developer typically needs to know the contents of the runtime logic, including the following details:\n\n- Version of the runtime the application is connecting to.\n- Supported APIs.\n- Implemented pallets.\n- Defined functions and corresponding type signatures.\n- Defined custom types.\n- Exposed parameters users can set.\n\nAs the Polkadot SDK is modular and provides a composable framework for building blockchains, there are limitless opportunities to customize the schema of properties. Each runtime can be configured with its properties, including function calls and types, which can be changed over time with runtime upgrades.\n\nThe Polkadot SDK enables you to generate the runtime metadata schema to capture information unique to a runtime. The metadata for a runtime describes the pallets in use and types defined for a specific runtime version. The metadata includes information about each pallet's storage items, functions, events, errors, and constants. The metadata also provides type definitions for any custom types included in the runtime.\n\nMetadata provides a complete inventory of a chain's runtime. It is key to enabling client applications to interact with the node, parse responses, and correctly format message payloads sent back to that chain."} -{"page_id": "reference-parachains-chain-data", "page_title": "Chain Data", "index": 4, "depth": 2, "title": "Generate Metadata", "anchor": "generate-metadata", "start_char": 3873, "end_char": 5179, "estimated_token_count": 297, "token_estimator": "heuristic-v1", "text": "## Generate Metadata\n\nTo efficiently use the blockchain's networking resources and minimize the data transmitted over the network, the metadata schema is encoded using the [Parity SCALE Codec](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\\_blank}. This encoding is done automatically through the [`scale-info`](https://docs.rs/scale-info/latest/scale_info/){target=\\_blank}crate.\n\nAt a high level, generating the metadata involves the following steps:\n\n1. The pallets in the runtime logic expose callable functions, types, parameters, and documentation that need to be encoded in the metadata.\n2. The `scale-info` crate collects type information for the pallets in the runtime, builds a registry of the pallets that exist in a particular runtime, and the relevant types for each pallet in the registry. The type information is detailed enough to enable encoding and decoding for every type.\n3. The [`frame-metadata`](https://github.com/paritytech/frame-metadata){target=\\_blank} crate describes the structure of the runtime based on the registry provided by the `scale-info` crate.\n4. Nodes provide the RPC method `state_getMetadata` to return a complete description of all the types in the current runtime as a hex-encoded vector of SCALE-encoded bytes."} -{"page_id": "reference-parachains-chain-data", "page_title": "Chain Data", "index": 5, "depth": 2, "title": "Retrieve Runtime Metadata", "anchor": "retrieve-runtime-metadata", "start_char": 5179, "end_char": 5695, "estimated_token_count": 98, "token_estimator": "heuristic-v1", "text": "## Retrieve Runtime Metadata\n\nThe type information provided by the metadata enables applications to communicate with nodes using different runtime versions and across chains that expose different calls, events, types, and storage items. The metadata also allows libraries to generate a substantial portion of the code needed to communicate with a given node, enabling libraries like [`subxt`](https://github.com/paritytech/subxt){target=\\_blank} to generate frontend interfaces that are specific to a target chain."} -{"page_id": "reference-parachains-chain-data", "page_title": "Chain Data", "index": 6, "depth": 3, "title": "Use Polkadot.js", "anchor": "use-polkadotjs", "start_char": 5695, "end_char": 6146, "estimated_token_count": 131, "token_estimator": "heuristic-v1", "text": "### Use Polkadot.js\n\nVisit the [Polkadot.js Portal](https://polkadot.js.org/apps/#/rpc){target=\\_blank} and select the **Developer** dropdown in the top banner. Select **RPC Calls** to make the call to request metadata. Follow these steps to make the RPC call:\n\n1. Select **state** as the endpoint to call.\n2. Select **`getMetadata(at)`** as the method to call.\n3. Click **Submit RPC call** to submit the call and return the metadata in JSON format."} -{"page_id": "reference-parachains-chain-data", "page_title": "Chain Data", "index": 7, "depth": 3, "title": "Use Curl", "anchor": "use-curl", "start_char": 6146, "end_char": 6460, "estimated_token_count": 95, "token_estimator": "heuristic-v1", "text": "### Use Curl \n\nYou can fetch the metadata for the network by calling the node's RPC endpoint. This request returns the metadata in bytes rather than human-readable JSON:\n\n```sh\ncurl -H \"Content-Type: application/json\" \\\n-d '{\"id\":1, \"jsonrpc\":\"2.0\", \"method\": \"state_getMetadata\"}' \\\nhttps://rpc.polkadot.io\n\n```"} -{"page_id": "reference-parachains-chain-data", "page_title": "Chain Data", "index": 8, "depth": 3, "title": "Use Subxt", "anchor": "use-subxt", "start_char": 6460, "end_char": 6826, "estimated_token_count": 116, "token_estimator": "heuristic-v1", "text": "### Use Subxt\n\n[`subxt`](https://github.com/paritytech/subxt){target=\\_blank} may also be used to fetch the metadata of any data in a human-readable JSON format: \n\n```sh\nsubxt metadata --url wss://rpc.polkadot.io --format json > spec.json\n```\n\nAnother option is to use the [`subxt` explorer web UI](https://paritytech.github.io/subxt-explorer/#/){target=\\_blank}."} -{"page_id": "reference-parachains-chain-data", "page_title": "Chain Data", "index": 9, "depth": 2, "title": "Client Applications and Metadata", "anchor": "client-applications-and-metadata", "start_char": 6826, "end_char": 7379, "estimated_token_count": 115, "token_estimator": "heuristic-v1", "text": "## Client Applications and Metadata\n\nThe metadata exposes the expected way to decode each type, meaning applications can send, retrieve, and process application information without manual encoding and decoding. Client applications must use the [SCALE codec library](https://github.com/paritytech/parity-scale-codec?tab=readme-ov-file#parity-scale-codec){target=\\_blank} to encode and decode RPC payloads to use the metadata. Client applications use the metadata to interact with the node, parse responses, and format message payloads sent to the node."} -{"page_id": "reference-parachains-chain-data", "page_title": "Chain Data", "index": 10, "depth": 2, "title": "Metadata Format", "anchor": "metadata-format", "start_char": 7379, "end_char": 9561, "estimated_token_count": 466, "token_estimator": "heuristic-v1", "text": "## Metadata Format\n\nAlthough the SCALE-encoded bytes can be decoded using the `frame-metadata` and [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\\_blank} libraries, there are other tools, such as `subxt` and the Polkadot-JS API, that can convert the raw data to human-readable JSON format.\n\nThe types and type definitions included in the metadata returned by the `state_getMetadata` RPC call depend on the runtime's metadata version.\n\nIn general, the metadata includes the following information:\n\n- A constant identifying the file as containing metadata.\n- The version of the metadata format used in the runtime.\n- Type definitions for all types used in the runtime and generated by the `scale-info` crate.\n- Pallet information for the pallets included in the runtime in the order that they are defined in the `construct_runtime` macro.\n\n!!!tip \n Depending on the frontend library used (such as the [Polkadot API](https://papi.how/){target=\\_blank}), they may format the metadata differently than the raw format shown.\n\nThe following example illustrates a condensed and annotated section of metadata decoded and converted to JSON:\n\n```json\n[\n 1635018093,\n {\n \"V14\": {\n \"types\": {\n \"types\": [{}]\n },\n \"pallets\": [{}],\n \"extrinsic\": {\n \"ty\": 126,\n \"version\": 4,\n \"signed_extensions\": [{}]\n },\n \"ty\": 141\n }\n }\n]\n\n```\n\nThe constant `1635018093` is a magic number that identifies the file as a metadata file. The rest of the metadata is divided into the `types`, `pallets`, and `extrinsic` sections:\n\n- The `types` section contains an index of the types and information about each type's type signature.\n- The `pallets` section contains information about each pallet in the runtime.\n- The `extrinsic` section describes the type identifier and transaction format version that the runtime uses.\n\nDifferent extrinsic versions can have varying formats, especially when considering [signed transactions](/reference/parachains/blocks-transactions-fees/transactions/#signed-transactions){target=\\_blank}."} -{"page_id": "reference-parachains-chain-data", "page_title": "Chain Data", "index": 11, "depth": 3, "title": "Pallets", "anchor": "pallets", "start_char": 9561, "end_char": 15081, "estimated_token_count": 986, "token_estimator": "heuristic-v1", "text": "### Pallets\n\nThe following is a condensed and annotated example of metadata for a single element in the `pallets` array (the [`sudo`](https://paritytech.github.io/polkadot-sdk/master/pallet_sudo/index.html){target=\\_blank} pallet):\n\n```json\n{\n \"name\": \"Sudo\",\n \"storage\": {\n \"prefix\": \"Sudo\",\n \"entries\": [\n {\n \"name\": \"Key\",\n \"modifier\": \"Optional\",\n \"ty\": {\n \"Plain\": 0\n },\n \"default\": [0],\n \"docs\": [\"The `AccountId` of the sudo key.\"]\n }\n ]\n },\n \"calls\": {\n \"ty\": 117\n },\n \"event\": {\n \"ty\": 42\n },\n \"constants\": [],\n \"error\": {\n \"ty\": 124\n },\n \"index\": 8\n}\n\n```\n\nEvery element metadata contains the name of the pallet it represents and information about its storage, calls, events, and errors. You can look up details about the definition of the calls, events, and errors by viewing the type index identifier. The type index identifier is the `u32` integer used to access the type information for that item. For example, the type index identifier for calls in the Sudo pallet is 117. If you view information for that type identifier in the `types` section of the metadata, it provides information about the available calls, including the documentation for each call.\n\nFor example, the following is a condensed excerpt of the calls for the Sudo pallet:\n\n```json\n{\n \"id\": 117,\n \"type\": {\n \"path\": [\"pallet_sudo\", \"pallet\", \"Call\"],\n \"params\": [\n {\n \"name\": \"T\",\n \"type\": null\n }\n ],\n \"def\": {\n \"variant\": {\n \"variants\": [\n {\n \"name\": \"sudo\",\n \"fields\": [\n {\n \"name\": \"call\",\n \"type\": 114,\n \"typeName\": \"Box<::RuntimeCall>\"\n }\n ],\n \"index\": 0,\n \"docs\": [\n \"Authenticates sudo key, dispatches a function call with `Root` origin\"\n ]\n },\n {\n \"name\": \"sudo_unchecked_weight\",\n \"fields\": [\n {\n \"name\": \"call\",\n \"type\": 114,\n \"typeName\": \"Box<::RuntimeCall>\"\n },\n {\n \"name\": \"weight\",\n \"type\": 8,\n \"typeName\": \"Weight\"\n }\n ],\n \"index\": 1,\n \"docs\": [\n \"Authenticates sudo key, dispatches a function call with `Root` origin\"\n ]\n },\n {\n \"name\": \"set_key\",\n \"fields\": [\n {\n \"name\": \"new\",\n \"type\": 103,\n \"typeName\": \"AccountIdLookupOf\"\n }\n ],\n \"index\": 2,\n \"docs\": [\n \"Authenticates current sudo key, sets the given AccountId (`new`) as the new sudo\"\n ]\n },\n {\n \"name\": \"sudo_as\",\n \"fields\": [\n {\n \"name\": \"who\",\n \"type\": 103,\n \"typeName\": \"AccountIdLookupOf\"\n },\n {\n \"name\": \"call\",\n \"type\": 114,\n \"typeName\": \"Box<::RuntimeCall>\"\n }\n ],\n \"index\": 3,\n \"docs\": [\n \"Authenticates sudo key, dispatches a function call with `Signed` origin from a given account\"\n ]\n }\n ]\n }\n }\n }\n}\n\n```\n\nFor each field, you can access type information and metadata for the following:\n\n- **Storage metadata**: Provides the information required to enable applications to get information for specific storage items.\n- **Call metadata**: Includes information about the runtime calls defined by the `#[pallet]` macro including call names, arguments and documentation.\n- **Event metadata**: Provides the metadata generated by the `#[pallet::event]` macro, including the name, arguments, and documentation for each pallet event.\n- **Constants metadata**: Provides metadata generated by the `#[pallet::constant]` macro, including the name, type, and hex-encoded value of the constant.\n- **Error metadata**: Provides metadata generated by the `#[pallet::error]` macro, including the name and documentation for each pallet error.\n\n!!!tip\n Type identifiers change from time to time, so you should avoid relying on specific type identifiers in your applications."} -{"page_id": "reference-parachains-chain-data", "page_title": "Chain Data", "index": 12, "depth": 3, "title": "Extrinsic", "anchor": "extrinsic", "start_char": 15081, "end_char": 17205, "estimated_token_count": 384, "token_estimator": "heuristic-v1", "text": "### Extrinsic\n\nThe runtime generates extrinsic metadata and provides useful information about transaction format. When decoded, the metadata contains the transaction version and the list of signed extensions.\n\nFor example:\n\n```json\n{\n \"extrinsic\": {\n \"ty\": 126,\n \"version\": 4,\n \"signed_extensions\": [\n {\n \"identifier\": \"CheckNonZeroSender\",\n \"ty\": 132,\n \"additional_signed\": 41\n },\n {\n \"identifier\": \"CheckSpecVersion\",\n \"ty\": 133,\n \"additional_signed\": 4\n },\n {\n \"identifier\": \"CheckTxVersion\",\n \"ty\": 134,\n \"additional_signed\": 4\n },\n {\n \"identifier\": \"CheckGenesis\",\n \"ty\": 135,\n \"additional_signed\": 11\n },\n {\n \"identifier\": \"CheckMortality\",\n \"ty\": 136,\n \"additional_signed\": 11\n },\n {\n \"identifier\": \"CheckNonce\",\n \"ty\": 138,\n \"additional_signed\": 41\n },\n {\n \"identifier\": \"CheckWeight\",\n \"ty\": 139,\n \"additional_signed\": 41\n },\n {\n \"identifier\": \"ChargeTransactionPayment\",\n \"ty\": 140,\n \"additional_signed\": 41\n }\n ]\n },\n \"ty\": 141\n}\n\n```\n\nThe type system is [composite](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/frame_runtime_types/index.html){target=\\_blank}, meaning each type identifier contains a reference to a specific type or to another type identifier that provides information about the associated primitive types.\n\nFor example, you can encode the `BitVec` type, but to decode it properly, you must know the types used for the `Order` and `Store` types. To find type information for `Order` and `Store`, you can use the path in the decoded JSON to locate their type identifiers."} -{"page_id": "reference-parachains-chain-data", "page_title": "Chain Data", "index": 13, "depth": 2, "title": "Included RPC APIs", "anchor": "included-rpc-apis", "start_char": 17205, "end_char": 18317, "estimated_token_count": 302, "token_estimator": "heuristic-v1", "text": "## Included RPC APIs\n\nA standard node comes with the following APIs to interact with a node:\n\n- **[`AuthorApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/author/trait.AuthorApiServer.html){target=\\_blank}**: Make calls into a full node, including authoring extrinsics and verifying session keys.\n- **[`ChainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/chain/trait.ChainApiServer.html){target=\\_blank}**: Retrieve block header and finality information.\n- **[`OffchainApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/offchain/trait.OffchainApiServer.html){target=\\_blank}**: Make RPC calls for off-chain workers.\n- **[`StateApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/state/trait.StateApiServer.html){target=\\_blank}**: Query information about on-chain state such as runtime version, storage items, and proofs.\n- **[`SystemApiServer`](https://paritytech.github.io/polkadot-sdk/master/sc_rpc/system/trait.SystemApiServer.html){target=\\_blank}**: Retrieve information about network state, such as connected peers and node roles."} -{"page_id": "reference-parachains-chain-data", "page_title": "Chain Data", "index": 14, "depth": 2, "title": "Additional Resources", "anchor": "additional-resources", "start_char": 18317, "end_char": 18650, "estimated_token_count": 101, "token_estimator": "heuristic-v1", "text": "## Additional Resources\n\nThe following tools can help you locate and decode metadata:\n\n- [Subxt Explorer](https://paritytech.github.io/subxt-explorer/#/){target=\\_blank}\n- [Metadata Portal 🌗](https://github.com/paritytech/metadata-portal){target=\\_blank}\n- [De[code] Sub[strate]](https://github.com/paritytech/desub){target=\\_blank}"} -{"page_id": "reference-parachains-consensus-elastic-scaling", "page_title": "Elastic Scaling", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 19, "end_char": 842, "estimated_token_count": 130, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nPolkadot's architecture delivers scalability and security through its shared security model, where the relay chain coordinates and validates multiple parallel chains. \n\nElastic scaling enhances this architecture by allowing parachains to utilize multiple computational cores simultaneously, breaking the previous 1:1 relationship between parachain and relay chain blocks.\n\nThis technical advancement enables parachains to process multiple blocks within a single relay chain block, significantly increasing throughput capabilities. By leveraging [Agile Coretime](/polkadot-protocol/architecture/polkadot-chain/agile-coretime){target=\\_blank}, parachains can dynamically adjust their processing capacity based on demand, creating an efficient and responsive infrastructure for high-throughput applications."} -{"page_id": "reference-parachains-consensus-elastic-scaling", "page_title": "Elastic Scaling", "index": 1, "depth": 2, "title": "How Elastic Scaling Works", "anchor": "how-elastic-scaling-works", "start_char": 842, "end_char": 4212, "estimated_token_count": 710, "token_estimator": "heuristic-v1", "text": "## How Elastic Scaling Works\n\nElastic scaling enables parachains to process multiple blocks in parallel by utilizing additional cores on the relay chain. This section provides a technical analysis of the performance advantages and details of the implementation.\n\nConsider a parachain that needs to process four consecutive parablocks. With traditional single-core allocation, the validation process follows a strictly sequential pattern. Each parablock undergoes a two-phase process on the relay chain:\n\n1. **Backing phase**: Validators create and distribute validity statements.\n2. **Inclusion phase**: The parablock is included in the relay chain after availability verification.\n\nThroughout the following diagrams, specific notation is used to represent different components of the system:\n\n- **R1, R2, ...**: Relay chain blocks (produced at ~6-second intervals).\n- **P1, P2, ...**: Parachain blocks that need validation and inclusion.\n- **C1, C2, ...**: Cores on the relay chain.\n\nIn the single-core scenario (assuming a 6-second relay chain block time), processing four parablocks requires approximately 30 seconds:\n\n```mermaid\nsequenceDiagram\n participant R1 as R1\n participant R2 as R2\n participant R3 as R3\n participant R4 as R4\n participant R5 as R5\n \n Note over R1,R5: Single Core Scenario\n \n rect rgb(200, 220, 240)\n Note right of R1: Core C1\n R1->>R1: Back P1\n R2->>R2: Include P1\n R2->>R2: Back P2\n R3->>R3: Include P2\n R3->>R3: Back P3\n R4->>R4: Include P3\n R4->>R4: Back P4\n R5->>R5: Include P4\n end\n```\n\nWith elastic scaling utilizing two cores simultaneously, the same four parablocks can be processed in approximately 18 seconds:\n\n```mermaid\nsequenceDiagram\n participant R1 as R1\n participant R2 as R2\n participant R3 as R3\n participant R4 as R4\n participant R5 as R5\n \n Note over R1,R3: Multi-Core Scenario\n \n rect rgb(200, 220, 240)\n Note right of R1: Core C1\n R1->>R1: Back P1\n R2->>R2: Include P1\n R2->>R2: Back P2\n R3->>R3: Include P2\n end\n \n rect rgb(220, 200, 240)\n Note right of R1: Core C2\n R1->>R1: Back P3\n R2->>R2: Include P3\n R2->>R2: Back P4\n R3->>R3: Include P4\n end\n```\n\nTo help interpret the sequence diagrams above, note the following key elements:\n\n- The horizontal axis represents time progression through relay chain blocks (R1-R5).\n- Each colored rectangle shows processing on a specific core (C1 or C2).\n- In the single-core scenario, all blocks must be processed sequentially on one core.\n- In the multi-core scenario, blocks are processed in parallel across multiple cores, reducing total time.\n\nThe relay chain processes these multiple parablocks as independent validation units during the backing, availability, and approval phases. However, during inclusion, it verifies that their state roots align properly to maintain chain consistency.\n\nFrom an implementation perspective:\n\n- **Parachain side**: Collators must increase their block production rate to utilize multiple cores fully.\n- **Validation process**: Each core operates independently, but with coordinated state verification.\n- **Resource management**: Cores are dynamically allocated based on parachain requirements.\n- **State consistency**: While backed and processed in parallel, the parablocks maintain sequential state transitions."} -{"page_id": "reference-parachains-consensus-elastic-scaling", "page_title": "Elastic Scaling", "index": 2, "depth": 2, "title": "Benefits of Elastic Scaling", "anchor": "benefits-of-elastic-scaling", "start_char": 4212, "end_char": 6001, "estimated_token_count": 288, "token_estimator": "heuristic-v1", "text": "## Benefits of Elastic Scaling\n\n- **Increased throughput**: Multiple concurrent cores enable parachains to process transactions at multiples of their previous capacity. By allowing multiple parachain blocks to be validated within each relay chain block cycle, applications can achieve significantly higher transaction volumes.\n\n- **Lower latency**: Transaction finality improves substantially with multi-core processing. Parachains currently achieve 2-second latency with three cores, with projected improvements to 500ms using 12 cores, enabling near-real-time application responsiveness.\n\n- **Resource efficiency**: Applications acquire computational resources precisely matched to their needs, eliminating wasteful over-provisioning. Coretime can be purchased at granular intervals (blocks, hours, days), creating cost-effective operations, particularly for applications with variable transaction patterns.\n\n- **Scalable growth**: New applications can launch with minimal initial resource commitment and scale dynamically as adoption increases. This eliminates the traditional paradox of either over-allocating resources (increasing costs) or under-allocating (degrading performance) during growth phases.\n\n- **Workload distribution**: Parachains intelligently distribute workloads across cores during peak demand periods and release resources when traffic subsides. Paired with secondary coretime markets, this ensures maximum resource utilization across the entire network ecosystem.\n\n- **Reliable performance**: End-users experience reliable application performance regardless of network congestion levels. Applications maintain responsiveness even during traffic spikes, eliminating performance degradation that commonly impacts blockchain applications during high-demand periods."} -{"page_id": "reference-parachains-consensus-elastic-scaling", "page_title": "Elastic Scaling", "index": 3, "depth": 2, "title": "Use Cases", "anchor": "use-cases", "start_char": 6001, "end_char": 6369, "estimated_token_count": 54, "token_estimator": "heuristic-v1", "text": "## Use Cases\n\nElastic scaling enables applications to dynamically adjust their resource consumption based on real-time demand. This is especially valuable for decentralized applications where usage patterns can be highly variable. The following examples illustrate common scenarios where elastic scaling delivers significant performance and cost-efficiency benefits."} -{"page_id": "reference-parachains-consensus-elastic-scaling", "page_title": "Elastic Scaling", "index": 4, "depth": 3, "title": "Handling Sudden Traffic Spikes", "anchor": "handling-sudden-traffic-spikes", "start_char": 6369, "end_char": 6786, "estimated_token_count": 64, "token_estimator": "heuristic-v1", "text": "### Handling Sudden Traffic Spikes\n\nMany decentralized applications experience unpredictable, high-volume traffic bursts, especially in gaming, DeFi protocols, NFT auctions, messaging platforms, and social media. Elastic scaling allows these systems to acquire additional coretime during peak usage and release it during quieter periods, ensuring responsiveness without incurring constant high infrastructure costs."} -{"page_id": "reference-parachains-consensus-elastic-scaling", "page_title": "Elastic Scaling", "index": 5, "depth": 3, "title": "Supporting Early-Stage Growth", "anchor": "supporting-early-stage-growth", "start_char": 6786, "end_char": 7168, "estimated_token_count": 69, "token_estimator": "heuristic-v1", "text": "### Supporting Early-Stage Growth\n\nStartups and new projects often begin with uncertain or volatile demand. With elastic scaling, teams can launch with minimal compute resources (e.g., a single core) and gradually scale as adoption increases. This prevents overprovisioning and enables cost-efficient growth until the application is ready for more permanent or horizontal scaling."} -{"page_id": "reference-parachains-consensus-elastic-scaling", "page_title": "Elastic Scaling", "index": 6, "depth": 3, "title": "Scaling Massive IoT Networks", "anchor": "scaling-massive-iot-networks", "start_char": 7168, "end_char": 7556, "estimated_token_count": 67, "token_estimator": "heuristic-v1", "text": "### Scaling Massive IoT Networks\n\nInternet of Things (IoT) applications often involve processing data from millions of devices in real time. Elastic scaling supports this need by enabling high-throughput transaction processing as demand fluctuates. Combined with Polkadot’s shared security model, it provides a reliable and privacy-preserving foundation for large-scale IoT deployments."} -{"page_id": "reference-parachains-consensus-elastic-scaling", "page_title": "Elastic Scaling", "index": 7, "depth": 3, "title": "Powering Real-Time, Low-Latency Systems", "anchor": "powering-real-time-low-latency-systems", "start_char": 7556, "end_char": 7871, "estimated_token_count": 58, "token_estimator": "heuristic-v1", "text": "### Powering Real-Time, Low-Latency Systems\n\nApplications like payment processors, trading platforms, gaming engines, or real-time data feeds require fast, consistent performance. Elastic scaling can reduce execution latency during demand spikes, helping ensure low-latency, reliable service even under heavy load."} -{"page_id": "reference-parachains-cryptography", "page_title": "Cryptography", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 16, "end_char": 525, "estimated_token_count": 73, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nCryptography forms the backbone of blockchain technology, providing the mathematical verifiability crucial for consensus systems, data integrity, and user security. While a deep understanding of the underlying mathematical processes isn't necessary for most blockchain developers, grasping the fundamental applications of cryptography is essential. This page comprehensively overviews cryptographic implementations used across Polkadot SDK-based chains and the broader blockchain ecosystem."} -{"page_id": "reference-parachains-cryptography", "page_title": "Cryptography", "index": 1, "depth": 2, "title": "Hash Functions", "anchor": "hash-functions", "start_char": 525, "end_char": 1170, "estimated_token_count": 130, "token_estimator": "heuristic-v1", "text": "## Hash Functions\n\nHash functions are fundamental to blockchain technology, creating a unique digital fingerprint for any piece of data, including simple text, images, or any other form of file. They map input data of any size to a fixed-size output (typically 32 bytes) using complex mathematical operations. Hashing is used to verify data integrity, create digital signatures, and provide a secure way to store passwords. This form of mapping is known as the [\"pigeonhole principle,\"](https://en.wikipedia.org/wiki/Pigeonhole_principle){target=\\_blank} it is primarily implemented to efficiently and verifiably identify data from large sets."} -{"page_id": "reference-parachains-cryptography", "page_title": "Cryptography", "index": 2, "depth": 3, "title": "Key Properties of Hash Functions", "anchor": "key-properties-of-hash-functions", "start_char": 1170, "end_char": 1720, "estimated_token_count": 138, "token_estimator": "heuristic-v1", "text": "### Key Properties of Hash Functions\n\n- **Deterministic**: The same input always produces the same output.\n- **Quick computation**: It's easy to calculate the hash value for any given input.\n- **Pre-image resistance**: It's infeasible to generate the input data from its hash.\n- **Small changes in input yield large changes in output**: Known as the [\"avalanche effect\"](https://en.wikipedia.org/wiki/Avalanche_effect){target=\\_blank}.\n- **Collision resistance**: The probabilities are extremely low to find two different inputs with the same hash."} -{"page_id": "reference-parachains-cryptography", "page_title": "Cryptography", "index": 3, "depth": 3, "title": "Blake2", "anchor": "blake2", "start_char": 1720, "end_char": 2257, "estimated_token_count": 126, "token_estimator": "heuristic-v1", "text": "### Blake2\n\nThe Polkadot SDK utilizes Blake2, a state-of-the-art hashing method that offers:\n\n- Equal or greater security compared to [SHA-2](https://en.wikipedia.org/wiki/SHA-2){target=\\_blank}.\n- Significantly faster performance than other algorithms.\n\nThese properties make Blake2 ideal for blockchain systems, reducing sync times for new nodes and lowering the resources required for validation. For detailed technical specifications about Blake2, see the [official Blake2 paper](https://www.blake2.net/blake2.pdf){target=\\_blank}."} -{"page_id": "reference-parachains-cryptography", "page_title": "Cryptography", "index": 4, "depth": 2, "title": "Types of Cryptography", "anchor": "types-of-cryptography", "start_char": 2257, "end_char": 2412, "estimated_token_count": 22, "token_estimator": "heuristic-v1", "text": "## Types of Cryptography\n\nThere are two different ways that cryptographic algorithms are implemented: symmetric cryptography and asymmetric cryptography."} -{"page_id": "reference-parachains-cryptography", "page_title": "Cryptography", "index": 5, "depth": 3, "title": "Symmetric Cryptography", "anchor": "symmetric-cryptography", "start_char": 2412, "end_char": 3256, "estimated_token_count": 162, "token_estimator": "heuristic-v1", "text": "### Symmetric Cryptography\n\nSymmetric encryption is a branch of cryptography that isn't based on one-way functions, unlike asymmetric cryptography. It uses the same cryptographic key to encrypt plain text and decrypt the resulting ciphertext.\n\nSymmetric cryptography is a type of encryption that has been used throughout history, such as the Enigma Cipher and the Caesar Cipher. It is still widely used today and can be found in Web2 and Web3 applications alike. There is only one single key, and a recipient must also have access to it to access the contained information.\n\n#### Advantages {: #symmetric-advantages }\n\n- Fast and efficient for large amounts of data.\n- Requires less computational power.\n\n#### Disadvantages {: #symmetric-disadvantages }\n\n- Key distribution can be challenging.\n- Scalability issues in systems with many users."} -{"page_id": "reference-parachains-cryptography", "page_title": "Cryptography", "index": 6, "depth": 3, "title": "Asymmetric Cryptography", "anchor": "asymmetric-cryptography", "start_char": 3256, "end_char": 4221, "estimated_token_count": 182, "token_estimator": "heuristic-v1", "text": "### Asymmetric Cryptography\n\nAsymmetric encryption is a type of cryptography that uses two different keys, known as a keypair: a public key, used to encrypt plain text, and a private counterpart, used to decrypt the ciphertext.\n\nThe public key encrypts a fixed-length message that can only be decrypted with the recipient's private key and, sometimes, a set password. The public key can be used to cryptographically verify that the corresponding private key was used to create a piece of data without compromising the private key, such as with digital signatures. This has obvious implications for identity, ownership, and properties and is used in many different protocols across Web2 and Web3.\n\n#### Advantages {: #asymmetric-advantages }\n\n- Solves the key distribution problem.\n- Enables digital signatures and secure key exchange.\n\n#### Disadvantages {: #asymmetric-disadvantages }\n\n- Slower than symmetric encryption.\n- Requires more computational resources."} -{"page_id": "reference-parachains-cryptography", "page_title": "Cryptography", "index": 7, "depth": 3, "title": "Trade-offs and Compromises", "anchor": "trade-offs-and-compromises", "start_char": 4221, "end_char": 5014, "estimated_token_count": 143, "token_estimator": "heuristic-v1", "text": "### Trade-offs and Compromises\n\nSymmetric cryptography is faster and requires fewer bits in the key to achieve the same level of security that asymmetric cryptography provides. However, it requires a shared secret before communication can occur, which poses issues to its integrity and a potential compromise point. On the other hand, asymmetric cryptography doesn't require the secret to be shared ahead of time, allowing for far better end-user security.\n\nHybrid symmetric and asymmetric cryptography is often used to overcome the engineering issues of asymmetric cryptography, as it is slower and requires more bits in the key to achieve the same level of security. It encrypts a key and then uses the comparatively lightweight symmetric cipher to do the \"heavy lifting\" with the message."} -{"page_id": "reference-parachains-cryptography", "page_title": "Cryptography", "index": 8, "depth": 2, "title": "Digital Signatures", "anchor": "digital-signatures", "start_char": 5014, "end_char": 6403, "estimated_token_count": 266, "token_estimator": "heuristic-v1", "text": "## Digital Signatures\n\nDigital signatures are a way of verifying the authenticity of a document or message using asymmetric keypairs. They are used to ensure that a sender or signer's document or message hasn't been tampered with in transit, and for recipients to verify that the data is accurate and from the expected sender.\n\nSigning digital signatures only requires a low-level understanding of mathematics and cryptography. For a conceptual example -- when signing a check, it is expected that it cannot be cashed multiple times. This isn't a feature of the signature system but rather the check serialization system. The bank will check that the serial number on the check hasn't already been used. Digital signatures essentially combine these two concepts, allowing the signature to provide the serialization via a unique cryptographic fingerprint that cannot be reproduced.\n\nUnlike pen-and-paper signatures, knowledge of a digital signature cannot be used to create other signatures. Digital signatures are often used in bureaucratic processes, as they are more secure than simply scanning in a signature and pasting it onto a document.\n\nPolkadot SDK provides multiple different cryptographic schemes and is generic so that it can support anything that implements the [`Pair` trait](https://paritytech.github.io/polkadot-sdk/master/sp_core/crypto/trait.Pair.html){target=\\_blank}."} -{"page_id": "reference-parachains-cryptography", "page_title": "Cryptography", "index": 9, "depth": 3, "title": "Example of Creating a Digital Signature", "anchor": "example-of-creating-a-digital-signature", "start_char": 6403, "end_char": 6977, "estimated_token_count": 117, "token_estimator": "heuristic-v1", "text": "### Example of Creating a Digital Signature\n\nThe process of creating and verifying a digital signature involves several steps:\n\n1. The sender creates a hash of the message.\n2. The hash is encrypted using the sender's private key, creating the signature.\n3. The message and signature are sent to the recipient.\n4. The recipient decrypts the signature using the sender's public key.\n5. The recipient hashes the received message and compares it to the decrypted hash.\n\nIf the hashes match, the signature is valid, confirming the message's integrity and the sender's identity."} -{"page_id": "reference-parachains-cryptography", "page_title": "Cryptography", "index": 10, "depth": 2, "title": "Elliptic Curve", "anchor": "elliptic-curve", "start_char": 6977, "end_char": 7869, "estimated_token_count": 170, "token_estimator": "heuristic-v1", "text": "## Elliptic Curve\n\nBlockchain technology requires the ability to have multiple keys creating a signature for block proposal and validation. To this end, Elliptic Curve Digital Signature Algorithm (ECDSA) and Schnorr signatures are two of the most commonly used methods. While ECDSA is a far simpler implementation, Schnorr signatures are more efficient when it comes to multi-signatures.\n\nSchnorr signatures bring some noticeable features over the ECDSA/EdDSA schemes:\n\n- It is better for hierarchical deterministic key derivations.\n- It allows for native multi-signature through [signature aggregation](https://bitcoincore.org/en/2017/03/23/schnorr-signature-aggregation/){target=\\_blank}.\n- It is generally more resistant to misuse.\n\nOne sacrifice that is made when using Schnorr signatures over ECDSA is that both require 64 bytes, but only ECDSA signatures communicate their public key."} -{"page_id": "reference-parachains-cryptography", "page_title": "Cryptography", "index": 11, "depth": 3, "title": "Various Implementations", "anchor": "various-implementations", "start_char": 7869, "end_char": 8860, "estimated_token_count": 268, "token_estimator": "heuristic-v1", "text": "### Various Implementations\n\n- **[ECDSA](https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm){target=\\_blank}**: Polkadot SDK provides an ECDSA signature scheme using the [secp256k1](https://en.bitcoin.it/wiki/Secp256k1){target=\\_blank} curve. This is the same cryptographic algorithm used to secure [Bitcoin](https://en.wikipedia.org/wiki/Bitcoin){target=\\_blank} and [Ethereum](https://en.wikipedia.org/wiki/Ethereum){target=\\_blank}.\n\n- **[Ed25519](https://en.wikipedia.org/wiki/EdDSA#Ed25519){target=\\_blank}**: An EdDSA signature scheme using [Curve25519](https://en.wikipedia.org/wiki/Curve25519){target=\\_blank}. It is carefully engineered at several levels of design and implementation to achieve very high speeds without compromising security.\n\n- **[SR25519](https://research.web3.foundation/Polkadot/security/keys/accounts-more){target=\\_blank}**: Based on the same underlying curve as Ed25519. However, it uses Schnorr signatures instead of the EdDSA scheme."} -{"page_id": "reference-parachains-data-encoding", "page_title": "Data Encoding", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 17, "end_char": 1595, "estimated_token_count": 332, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nThe Polkadot SDK uses a lightweight and efficient encoding/decoding mechanism to optimize data transmission across the network. This mechanism, known as the _SCALE_ codec, is used for serializing and deserializing data.\n\nThe SCALE codec enables communication between the runtime and the outer node. This mechanism is designed for high-performance, copy-free data encoding and decoding in resource-constrained environments like the Polkadot SDK [Wasm runtime](/develop/parachains/deployment/build-deterministic-runtime/#introduction){target=\\_blank}.\n\nIt is not self-describing, meaning the decoding context must fully know the encoded data types. \n\nParity's libraries utilize the [`parity-scale-codec`](https://github.com/paritytech/parity-scale-codec){target=\\_blank} crate (a Rust implementation of the SCALE codec) to handle encoding and decoding for interactions between RPCs and the runtime.\n\nThe `codec` mechanism is ideal for Polkadot SDK-based chains because:\n\n- It is lightweight compared to generic serialization frameworks like [`serde`](https://serde.rs/){target=\\_blank}, which add unnecessary bulk to binaries.\n- It doesn’t rely on Rust’s `libstd`, making it compatible with `no_std` environments like Wasm runtime.\n- It integrates seamlessly with Rust, allowing easy derivation of encoding and decoding logic for new types using `#[derive(Encode, Decode)]`.\n\nDefining a custom encoding scheme in the Polkadot SDK-based chains, rather than using an existing Rust codec library, is crucial for enabling cross-platform and multi-language support."} -{"page_id": "reference-parachains-data-encoding", "page_title": "Data Encoding", "index": 1, "depth": 2, "title": "SCALE Codec", "anchor": "scale-codec", "start_char": 1595, "end_char": 1798, "estimated_token_count": 63, "token_estimator": "heuristic-v1", "text": "## SCALE Codec\n\nThe codec is implemented using the following traits:\n\n- [`Encode`](#encode)\n- [`Decode`](#decode)\n- [`CompactAs`](#compactas)\n- [`HasCompact`](#hascompact)\n- [`EncodeLike`](#encodelike)"} -{"page_id": "reference-parachains-data-encoding", "page_title": "Data Encoding", "index": 2, "depth": 3, "title": "Encode", "anchor": "encode", "start_char": 1798, "end_char": 2875, "estimated_token_count": 291, "token_estimator": "heuristic-v1", "text": "### Encode\n\nThe [`Encode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Encode.html){target=\\_blank} trait handles data encoding into SCALE format and includes the following key functions:\n\n- **`size_hint(&self) -> usize`**: Estimates the number of bytes required for encoding to prevent multiple memory allocations. This should be inexpensive and avoid complex operations. Optional if the size isn’t known.\n- **`encode_to(&self, dest: &mut T)`**: Encodes the data, appending it to a destination buffer.\n- **`encode(&self) -> Vec`**: Encodes the data and returns it as a byte vector.\n- **`using_encoded R>(&self, f: F) -> R`**: Encodes the data and passes it to a closure, returning the result.\n- **`encoded_size(&self) -> usize`**: Calculates the encoded size. Should be used when the encoded data isn’t required.\n\n!!!tip\n For best performance, value types should override `using_encoded`, and allocating types should override `encode_to`. It's recommended to implement `size_hint` for all types where possible."} -{"page_id": "reference-parachains-data-encoding", "page_title": "Data Encoding", "index": 3, "depth": 3, "title": "Decode", "anchor": "decode", "start_char": 2875, "end_char": 3216, "estimated_token_count": 98, "token_estimator": "heuristic-v1", "text": "### Decode\n\nThe [`Decode`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.Decode.html){target=\\_blank} trait handles decoding SCALE-encoded data back into the appropriate types:\n\n- **`fn decode(value: &mut I) -> Result`**: Decodes data from the SCALE format, returning an error if decoding fails."} -{"page_id": "reference-parachains-data-encoding", "page_title": "Data Encoding", "index": 4, "depth": 3, "title": "CompactAs", "anchor": "compactas", "start_char": 3216, "end_char": 3566, "estimated_token_count": 109, "token_estimator": "heuristic-v1", "text": "### CompactAs\n\nThe [`CompactAs`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.CompactAs.html){target=\\_blank} trait wraps custom types for compact encoding:\n\n- **`encode_as(&self) -> &Self::As`**: Encodes the type as a compact type.\n- **`decode_from(_: Self::As) -> Result`**: decodes from a compact encoded type."} -{"page_id": "reference-parachains-data-encoding", "page_title": "Data Encoding", "index": 5, "depth": 3, "title": "HasCompact", "anchor": "hascompact", "start_char": 3566, "end_char": 3752, "estimated_token_count": 49, "token_estimator": "heuristic-v1", "text": "### HasCompact\n\nThe [`HasCompact`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.HasCompact.html){target=\\_blank} trait indicates a type supports compact encoding."} -{"page_id": "reference-parachains-data-encoding", "page_title": "Data Encoding", "index": 6, "depth": 3, "title": "EncodeLike", "anchor": "encodelike", "start_char": 3752, "end_char": 4038, "estimated_token_count": 69, "token_estimator": "heuristic-v1", "text": "### EncodeLike\n\nThe [`EncodeLike`](https://docs.rs/parity-scale-codec/latest/parity_scale_codec/trait.EncodeLike.html){target=\\_blank} trait is used to ensure multiple types that encode similarly are accepted by the same function. When using `derive`, it is automatically implemented."} -{"page_id": "reference-parachains-data-encoding", "page_title": "Data Encoding", "index": 7, "depth": 3, "title": "Data Types", "anchor": "data-types", "start_char": 4038, "end_char": 11053, "estimated_token_count": 1201, "token_estimator": "heuristic-v1", "text": "### Data Types\n\nThe table below outlines how the Rust implementation of the Parity SCALE codec encodes different data types.\n\n| Type | Description | Example SCALE Decoded Value | SCALE Encoded Value |\n|-------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------|\n| Boolean | Boolean values are encoded using the least significant bit of a single byte. | `false` / `true` | `0x00` / `0x01` |\n| Compact/general integers | A \"compact\" or general integer encoding is sufficient for encoding large integers (up to 2^536) and is more efficient at encoding most values than the fixed-width version. | `unsigned integer 0` / `unsigned integer 1` / `unsigned integer 42` / `unsigned integer 69` / `unsigned integer 65535` / `BigInt(100000000000000)` | `0x00` / `0x04` / `0xa8` / `0x1501` / `0xfeff0300` / `0x0b00407a10f35a` |\n| Enumerations (tagged-unions) | A fixed number of variants, each mutually exclusive and potentially implying a further value or series of values. Encoded as the first byte identifying the index of the variant that the value is. Any further bytes are used to encode any data that the variant implies. Thus, no more than 256 variants are supported. | `Int(42)` and `Bool(true)` where `enum IntOrBool { Int(u8), Bool(bool) }` | `0x002a` and `0x0101` |\n| Fixed-width integers | Basic integers are encoded using a fixed-width little-endian (LE) format. | `signed 8-bit integer 69` / `unsigned 16-bit integer 42` / `unsigned 32-bit integer 16777215` | `0x45` / `0x2a00` / `0xffffff00` |\n| Options | One or zero values of a particular type. | `Some` / `None` | `0x01` followed by the encoded value / `0x00` |\n| Results | Results are commonly used enumerations which indicate whether certain operations were successful or unsuccessful. | `Ok(42)` / `Err(false)` | `0x002a` / `0x0100` |\n| Strings | Strings are Vectors of bytes (Vec) containing a valid UTF8 sequence. | | |\n| Structs | For structures, the values are named, but that is irrelevant for the encoding (names are ignored - only order matters). | `SortedVecAsc::from([3, 5, 2, 8])` | `[3, 2, 5, 8] ` |\n| Tuples | A fixed-size series of values, each with a possibly different but predetermined and fixed type. This is simply the concatenation of each encoded value. | Tuple of compact unsigned integer and boolean: `(3, false)` | `0x0c00` |\n| Vectors (lists, series, sets) | A collection of same-typed values is encoded, prefixed with a compact encoding of the number of items, followed by each item's encoding concatenated in turn. | Vector of unsigned `16`-bit integers: `[4, 8, 15, 16, 23, 42]` | `0x18040008000f00100017002a00` |"} -{"page_id": "reference-parachains-data-encoding", "page_title": "Data Encoding", "index": 8, "depth": 2, "title": "Encode and Decode Rust Trait Implementations", "anchor": "encode-and-decode-rust-trait-implementations", "start_char": 11053, "end_char": 12105, "estimated_token_count": 444, "token_estimator": "heuristic-v1", "text": "## Encode and Decode Rust Trait Implementations\n\nHere's how the `Encode` and `Decode` traits are implemented:\n\n\n```rust\nuse parity_scale_codec::{Encode, Decode};\n\n[derive(Debug, PartialEq, Encode, Decode)]\nenum EnumType {\n #[codec(index = 15)]\n A,\n B(u32, u64),\n C {\n a: u32,\n b: u64,\n },\n}\n\nlet a = EnumType::A;\nlet b = EnumType::B(1, 2);\nlet c = EnumType::C { a: 1, b: 2 };\n\na.using_encoded(|ref slice| {\n assert_eq!(slice, &b\"\\x0f\");\n});\n\nb.using_encoded(|ref slice| {\n assert_eq!(slice, &b\"\\x01\\x01\\0\\0\\0\\x02\\0\\0\\0\\0\\0\\0\\0\");\n});\n\nc.using_encoded(|ref slice| {\n assert_eq!(slice, &b\"\\x02\\x01\\0\\0\\0\\x02\\0\\0\\0\\0\\0\\0\\0\");\n});\n\nlet mut da: &[u8] = b\"\\x0f\";\nassert_eq!(EnumType::decode(&mut da).ok(), Some(a));\n\nlet mut db: &[u8] = b\"\\x01\\x01\\0\\0\\0\\x02\\0\\0\\0\\0\\0\\0\\0\";\nassert_eq!(EnumType::decode(&mut db).ok(), Some(b));\n\nlet mut dc: &[u8] = b\"\\x02\\x01\\0\\0\\0\\x02\\0\\0\\0\\0\\0\\0\\0\";\nassert_eq!(EnumType::decode(&mut dc).ok(), Some(c));\n\nlet mut dz: &[u8] = &[0];\nassert_eq!(EnumType::decode(&mut dz).ok(), None);\n```"} -{"page_id": "reference-parachains-data-encoding", "page_title": "Data Encoding", "index": 9, "depth": 2, "title": "SCALE Codec Libraries", "anchor": "scale-codec-libraries", "start_char": 12105, "end_char": 13629, "estimated_token_count": 557, "token_estimator": "heuristic-v1", "text": "## SCALE Codec Libraries\n\nSeveral SCALE codec implementations are available in various languages. Here's a list of them:\n\n- **AssemblyScript**: [`LimeChain/as-scale-codec`](https://github.com/LimeChain/as-scale-codec){target=\\_blank}\n- **C**: [`MatthewDarnell/cScale`](https://github.com/MatthewDarnell/cScale){target=\\_blank}\n- **C++**: [`qdrvm/scale-codec-cpp`](https://github.com/qdrvm/scale-codec-cpp){target=\\_blank}\n- **JavaScript**: [`polkadot-js/api`](https://github.com/polkadot-js/api){target=\\_blank}\n- **Dart**: [`leonardocustodio/polkadart`](https://github.com/leonardocustodio/polkadart){target=\\_blank}\n- **Haskell**: [`airalab/hs-web3`](https://github.com/airalab/hs-web3/tree/master/packages/scale){target=\\_blank}\n- **Golang**: [`itering/scale.go`](https://github.com/itering/scale.go){target=\\_blank}\n- **Java**: [`splix/polkaj`](https://github.com/splix/polkaj){target=\\_blank}\n- **Python**: [`polkascan/py-scale-codec`](https://github.com/polkascan/py-scale-codec){target=\\_blank}\n- **Ruby**: [` wuminzhe/scale_rb`](https://github.com/wuminzhe/scale_rb){target=\\_blank}\n- **TypeScript**: [`parity-scale-codec-ts`](https://github.com/tjjfvi/subshape){target=\\_blank}, [`scale-ts`](https://github.com/unstoppablejs/unstoppablejs/tree/main/packages/scale-ts#scale-ts){target=\\_blank}, [`soramitsu/scale-codec-js-library`](https://github.com/soramitsu/scale-codec-js-library){target=\\_blank}, [`subsquid/scale-codec`](https://github.com/subsquid/squid-sdk/tree/master/substrate/scale-codec){target=\\_blank}"} -{"page_id": "reference-parachains-interoperability", "page_title": "Interoperability", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 20, "end_char": 607, "estimated_token_count": 91, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nInteroperability lies at the heart of the Polkadot ecosystem, enabling communication and collaboration across a diverse range of blockchains. By bridging the gaps between parachains, relay chains, and even external networks, Polkadot unlocks the potential for truly decentralized applications, efficient resource sharing, and scalable solutions.\n\nPolkadot’s design ensures that blockchains can transcend their individual limitations by working together as part of a unified system. This cooperative architecture is what sets Polkadot apart in the blockchain landscape."} -{"page_id": "reference-parachains-interoperability", "page_title": "Interoperability", "index": 1, "depth": 2, "title": "Why Interoperability Matters", "anchor": "why-interoperability-matters", "start_char": 607, "end_char": 1641, "estimated_token_count": 169, "token_estimator": "heuristic-v1", "text": "## Why Interoperability Matters\n\nThe blockchain ecosystem is inherently fragmented. Different blockchains excel in specialized domains such as finance, gaming, or supply chain management, but these chains function in isolation without interoperability. This lack of connectivity stifles the broader utility of blockchain technology.\n\nInteroperability solves this problem by enabling blockchains to:\n\n- **Collaborate across networks**: Chains can interact to share assets, functionality, and data, creating synergies that amplify their individual strengths.\n- **Achieve greater scalability**: Specialized chains can offload tasks to others, optimizing performance and resource utilization.\n- **Expand use-case potential**: Cross-chain applications can leverage features from multiple blockchains, unlocking novel user experiences and solutions.\n\nIn the Polkadot ecosystem, interoperability transforms a collection of isolated chains into a cohesive, efficient network, pushing the boundaries of what blockchains can achieve together."} -{"page_id": "reference-parachains-interoperability", "page_title": "Interoperability", "index": 2, "depth": 2, "title": "Key Mechanisms for Interoperability", "anchor": "key-mechanisms-for-interoperability", "start_char": 1641, "end_char": 1921, "estimated_token_count": 45, "token_estimator": "heuristic-v1", "text": "## Key Mechanisms for Interoperability\n\nAt the core of Polkadot's cross-chain collaboration are foundational technologies designed to break down barriers between networks. These mechanisms empower blockchains to communicate, share resources, and operate as a cohesive ecosystem."} -{"page_id": "reference-parachains-interoperability", "page_title": "Interoperability", "index": 3, "depth": 3, "title": "Cross-Consensus Messaging (XCM): The Backbone of Communication", "anchor": "cross-consensus-messaging-xcm-the-backbone-of-communication", "start_char": 1921, "end_char": 2749, "estimated_token_count": 150, "token_estimator": "heuristic-v1", "text": "### Cross-Consensus Messaging (XCM): The Backbone of Communication\n\nPolkadot's Cross-Consensus Messaging (XCM) is the standard framework for interaction between parachains, relay chains, and, eventually, external blockchains. XCM provides a trustless, secure messaging format for exchanging assets, sharing data, and executing cross-chain operations.\n\nThrough XCM, decentralized applications can:\n\n- Transfer tokens and other assets across chains.\n- Coordinate complex workflows that span multiple blockchains.\n- Enable seamless user experiences where underlying blockchain differences are invisible.\n- XCM exemplifies Polkadot’s commitment to creating a robust and interoperable ecosystem.\n\nFor further information about XCM, check the [Introduction to XCM](/parachains/interoperability/get-started/){target=\\_blank} article."} -{"page_id": "reference-parachains-interoperability", "page_title": "Interoperability", "index": 4, "depth": 3, "title": "Bridges: Connecting External Networks", "anchor": "bridges-connecting-external-networks", "start_char": 2749, "end_char": 3529, "estimated_token_count": 138, "token_estimator": "heuristic-v1", "text": "### Bridges: Connecting External Networks\n\nWhile XCM enables interoperability within the Polkadot ecosystem, bridges extend this functionality to external blockchains such as Ethereum and Bitcoin. By connecting these networks, bridges allow Polkadot-based chains to access external liquidity, additional functionalities, and broader user bases.\n\nWith bridges, developers and users gain the ability to:\n\n- Integrate external assets into Polkadot-based applications.\n- Combine the strengths of Polkadot’s scalability with the liquidity of other networks.\n- Facilitate accurate multi-chain applications that transcend ecosystem boundaries.\n\nFor more information about bridges in the Polkadot ecosystem, see the [Bridge Hub](/reference/polkadot-hub/bridging/){target=\\_blank} guide."} -{"page_id": "reference-parachains-interoperability", "page_title": "Interoperability", "index": 5, "depth": 2, "title": "The Polkadot Advantage", "anchor": "the-polkadot-advantage", "start_char": 3529, "end_char": 4247, "estimated_token_count": 121, "token_estimator": "heuristic-v1", "text": "## The Polkadot Advantage\n\nPolkadot was purpose-built for interoperability. Unlike networks that add interoperability as an afterthought, Polkadot integrates it as a fundamental design principle. This approach offers several distinct advantages:\n\n- **Developer empowerment**: Polkadot’s interoperability tools allow developers to build applications that leverage multiple chains’ capabilities without added complexity.\n- **Enhanced ecosystem collaboration**: Chains in Polkadot can focus on their unique strengths while contributing to the ecosystem’s overall growth.\n- **Future-proofing blockchain**: By enabling seamless communication, Polkadot ensures its ecosystem can adapt to evolving demands and technologies."} -{"page_id": "reference-parachains-interoperability", "page_title": "Interoperability", "index": 6, "depth": 2, "title": "Looking Ahead", "anchor": "looking-ahead", "start_char": 4247, "end_char": 4635, "estimated_token_count": 58, "token_estimator": "heuristic-v1", "text": "## Looking Ahead\n\nPolkadot’s vision of interoperability extends beyond technical functionality, representing a shift towards a more collaborative blockchain landscape. By enabling chains to work together, Polkadot fosters innovation, efficiency, and accessibility, paving the way for a decentralized future where blockchains are not isolated competitors but interconnected collaborators."} -{"page_id": "reference-parachains-networks", "page_title": "Networks", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 12, "end_char": 601, "estimated_token_count": 99, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nThe Polkadot ecosystem is built on a robust set of networks designed to enable secure and scalable development. Whether you are testing new features or deploying to live production, Polkadot offers several layers of networks tailored for each stage of the development process. From local environments to experimental networks like Kusama and community-run TestNets such as Paseo, developers can thoroughly test, iterate, and validate their applications. This guide will introduce you to Polkadot's various networks and explain how they fit into the development workflow."} -{"page_id": "reference-parachains-networks", "page_title": "Networks", "index": 1, "depth": 2, "title": "Network Overview", "anchor": "network-overview", "start_char": 601, "end_char": 3131, "estimated_token_count": 484, "token_estimator": "heuristic-v1", "text": "## Network Overview \n\nPolkadot's development process is structured to ensure new features and upgrades are rigorously tested before being deployed on live production networks. The progression follows a well-defined path, starting from local environments and advancing through TestNets, ultimately reaching the Polkadot MainNet. The diagram below outlines the typical progression of the Polkadot development cycle:\n\n``` mermaid\nflowchart LR\n id1[Local] --> id2[Westend] --> id4[Kusama] --> id5[Polkadot] \n id1[Local] --> id3[Paseo] --> id5[Polkadot] \n```\n\nThis flow ensures developers can thoroughly test and iterate without risking real tokens or affecting production networks. Testing tools like [Chopsticks](#chopsticks) and various TestNets make it easier to experiment safely before releasing to production.\n\nA typical journey through the Polkadot core protocol development process might look like this:\n\n1. **Local development node**: Development starts in a local environment, where developers can create, test, and iterate on upgrades or new features using a local development node. This stage allows rapid experimentation in an isolated setup without any external dependencies.\n\n2. **Westend**: After testing locally, upgrades are deployed to [Westend](#westend), Polkadot's primary TestNet. Westend simulates real-world conditions without using real tokens, making it the ideal place for rigorous feature testing before moving on to production networks.\n\n3. **Kusama**: Once features have passed extensive testing on Westend, they move to Kusama, Polkadot's experimental and fast-moving \"canary\" network. Kusama operates as a high-fidelity testing ground with actual economic incentives, giving developers insights into how their features will perform in a real-world environment.\n\n4. **Polkadot**: After passing tests on Westend and Kusama, features are considered ready for deployment to Polkadot, the live production network.\n\n In addition, parachain developers can leverage local TestNets like [Zombienet](#zombienet) and deploy upgrades on parachain TestNets.\n\n5. **Paseo**: For parachain and dApp developers, Paseo serves as a community-run TestNet that mirrors Polkadot's runtime. Like Westend for core protocol development, Paseo provides a testing ground for parachain development without affecting live networks.\n\n!!!note\n The Rococo TestNet deprecation date was October 14, 2024. Teams should use Westend for Polkadot protocol and feature testing and Paseo for chain development-related testing."} -{"page_id": "reference-parachains-networks", "page_title": "Networks", "index": 2, "depth": 2, "title": "Polkadot Development Networks", "anchor": "polkadot-development-networks", "start_char": 3131, "end_char": 3663, "estimated_token_count": 83, "token_estimator": "heuristic-v1", "text": "## Polkadot Development Networks\n\nDevelopment and testing are crucial to building robust dApps and parachains and performing network upgrades within the Polkadot ecosystem. To achieve this, developers can leverage various networks and tools that provide a risk-free environment for experimentation and validation before deploying features to live networks. These networks help avoid the costs and risks associated with real tokens, enabling testing for functionalities like governance, cross-chain messaging, and runtime upgrades."} -{"page_id": "reference-parachains-networks", "page_title": "Networks", "index": 3, "depth": 2, "title": "Kusama Network", "anchor": "kusama-network", "start_char": 3663, "end_char": 4268, "estimated_token_count": 122, "token_estimator": "heuristic-v1", "text": "## Kusama Network\n\nKusama is the experimental version of Polkadot, designed for developers who want to move quickly and test their applications in a real-world environment with economic incentives. Kusama serves as a production-grade testing ground where developers can deploy features and upgrades with the pressure of game theory and economics in mind. It mirrors Polkadot but operates as a more flexible space for innovation.\n\nThe native token for Kusama is KSM. For more information about KSM, visit the [Native Assets](https://wiki.polkadot.com/kusama/kusama-getting-started/){target=\\_blank} page."} -{"page_id": "reference-parachains-networks", "page_title": "Networks", "index": 4, "depth": 2, "title": "Test Networks", "anchor": "test-networks", "start_char": 4268, "end_char": 4488, "estimated_token_count": 47, "token_estimator": "heuristic-v1", "text": "## Test Networks\n\nThe following test networks provide controlled environments for testing upgrades and new features. TestNet tokens are available from the [Polkadot faucet](https://faucet.polkadot.io/){target=\\_blank}."} -{"page_id": "reference-parachains-networks", "page_title": "Networks", "index": 5, "depth": 3, "title": "Westend", "anchor": "westend", "start_char": 4488, "end_char": 5009, "estimated_token_count": 110, "token_estimator": "heuristic-v1", "text": "### Westend\n\nWestend is Polkadot's primary permanent TestNet. Unlike temporary test networks, Westend is not reset to the genesis block, making it an ongoing environment for testing Polkadot core features. Managed by Parity Technologies, Westend ensures that developers can test features in a real-world simulation without using actual tokens.\n\nThe native token for Westend is WND. More details about WND can be found on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_2){target=\\_blank} page."} -{"page_id": "reference-parachains-networks", "page_title": "Networks", "index": 6, "depth": 3, "title": "Paseo", "anchor": "paseo", "start_char": 5009, "end_char": 5579, "estimated_token_count": 127, "token_estimator": "heuristic-v1", "text": "### Paseo\n\n[Paseo](https://github.com/paseo-network){target=\\_blank} is a community-managed TestNet designed for parachain and dApp developers. It mirrors Polkadot's runtime and is maintained by Polkadot community members. Paseo provides a dedicated space for parachain developers to test their applications in a Polkadot-like environment without the risks associated with live networks.\n\nThe native token for Paseo is PAS. Additional information on PAS is available on the [Native Assets](https://wiki.polkadot.com/learn/learn-dot/#__tabbed_2_1){target=\\_blank} page."} -{"page_id": "reference-parachains-networks", "page_title": "Networks", "index": 7, "depth": 2, "title": "Local Test Networks", "anchor": "local-test-networks", "start_char": 5579, "end_char": 6057, "estimated_token_count": 80, "token_estimator": "heuristic-v1", "text": "## Local Test Networks\n\nLocal test networks are an essential part of the development cycle for blockchain developers using the Polkadot SDK. They allow for fast, iterative testing in controlled, private environments without connecting to public TestNets. Developers can quickly spin up local instances to experiment, debug, and validate their code before deploying to larger TestNets like Westend or Paseo. Two key tools for local network testing are Zombienet and Chopsticks."} -{"page_id": "reference-parachains-networks", "page_title": "Networks", "index": 8, "depth": 3, "title": "Zombienet", "anchor": "zombienet", "start_char": 6057, "end_char": 6981, "estimated_token_count": 164, "token_estimator": "heuristic-v1", "text": "### Zombienet\n\n[Zombienet](https://github.com/paritytech/zombienet){target=\\_blank} is a flexible testing framework for Polkadot SDK-based blockchains. It enables developers to create and manage ephemeral, short-lived networks. This feature makes Zombienet particularly useful for quick iterations, as it allows you to run multiple local networks concurrently, mimicking different runtime conditions. Whether you're developing a parachain or testing your custom blockchain logic, Zombienet gives you the tools to automate local testing.\n\nKey features of Zombienet include:\n\n- Creating dynamic, local networks with different configurations.\n- Running parachains and relay chains in a simulated environment.\n- Efficient testing of network components like cross-chain messaging and governance.\n\nZombienet is ideal for developers looking to test quickly and thoroughly before moving to more resource-intensive public TestNets."} -{"page_id": "reference-parachains-networks", "page_title": "Networks", "index": 9, "depth": 3, "title": "Chopsticks", "anchor": "chopsticks", "start_char": 6981, "end_char": 7834, "estimated_token_count": 157, "token_estimator": "heuristic-v1", "text": "### Chopsticks\n\n[Chopsticks](https://github.com/AcalaNetwork/chopsticks){target=\\_blank} is a tool designed to create forks of Polkadot SDK-based blockchains, allowing developers to interact with network forks as part of their testing process. This capability makes Chopsticks a powerful option for testing upgrades, runtime changes, or cross-chain applications in a forked network environment.\n\nKey features of Chopsticks include:\n\n- Forking live Polkadot SDK-based blockchains for isolated testing.\n- Simulating cross-chain messages in a private, controlled setup.\n- Debugging network behavior by interacting with the fork in real-time.\n\nChopsticks provides a controlled environment for developers to safely explore the effects of runtime changes. It ensures that network behavior is tested and verified before upgrades are deployed to live networks."} -{"page_id": "reference-parachains-node-and-runtime", "page_title": "Node and Runtime", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 20, "end_char": 1003, "estimated_token_count": 184, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nEvery blockchain platform relies on a decentralized network of computers, called nodes, that communicate with each other about transactions and blocks. In this context, a node refers to the software running on the connected devices rather than the physical or virtual machines in the network.\n\nPolkadot SDK-based nodes consist of two main components, each with distinct responsibilities: the client (also called node) and the runtime.\n\nIf the system were a monolithic protocol, any modification would require updating the entire system. Instead, Polkadot achieves true upgradeability by defining an immutable meta-protocol (the client) and a protocol (the runtime) that can be upgraded independently.\n\nThis separation gives the [Polkadot Relay Chain](/polkadot-protocol/architecture/polkadot-chain){target=\\_blank} and all connected [parachains](/polkadot-protocol/architecture/parachains){target=\\_blank} an evolutionary advantage over other blockchain platforms."} -{"page_id": "reference-parachains-node-and-runtime", "page_title": "Node and Runtime", "index": 1, "depth": 2, "title": "Architectural Principles", "anchor": "architectural-principles", "start_char": 1003, "end_char": 1725, "estimated_token_count": 123, "token_estimator": "heuristic-v1", "text": "## Architectural Principles\n\nThe Polkadot SDK-based blockchain architecture is fundamentally built on two distinct yet interconnected components:\n\n- Client (Meta-protocol):\n - Handles the foundational infrastructure of the blockchain.\n - Manages runtime execution, networking, consensus, and other off-chain components.\n - Provides an immutable base layer that ensures network stability.\n - Upgradable only through hard forks.\n\n- Runtime (Protocol):\n - Defines the blockchain's state transition logic.\n - Determines the specific rules and behaviors of the blockchain.\n - Compiled to WebAssembly (Wasm) for platform-independent execution.\n - Capable of being upgraded without network-wide forking."} -{"page_id": "reference-parachains-node-and-runtime", "page_title": "Node and Runtime", "index": 2, "depth": 3, "title": "Advantages of this Architecture", "anchor": "advantages-of-this-architecture", "start_char": 1725, "end_char": 2106, "estimated_token_count": 75, "token_estimator": "heuristic-v1", "text": "### Advantages of this Architecture\n\n- **Forkless upgrades**: Runtime can be updated without disrupting the entire network.\n- **Modularity**: Clear separation allows independent development of client and runtime.\n- **Flexibility**: Enables rapid iteration and evolution of blockchain logic.\n- **Performance**: WebAssembly compilation provides efficient, cross-platform execution."} -{"page_id": "reference-parachains-node-and-runtime", "page_title": "Node and Runtime", "index": 3, "depth": 2, "title": "Node (Client)", "anchor": "node-client", "start_char": 2106, "end_char": 2939, "estimated_token_count": 164, "token_estimator": "heuristic-v1", "text": "## Node (Client)\n\nThe node, also known as the client, is the core component responsible for executing the Wasm runtime and orchestrating various essential blockchain components. It ensures the correct execution of the state transition function and manages multiple critical subsystems, including:\n\n- **Wasm execution**: Runs the blockchain runtime, which defines the state transition rules.\n- **Database management**: Stores blockchain data.\n- **Networking**: Facilitates peer-to-peer communication, block propagation, and transaction gossiping.\n- **Transaction pool (Mempool)**: Manages pending transactions before they are included in a block.\n- **Consensus mechanism**: Ensures agreement on the blockchain state across nodes.\n- **RPC services**: Provides external interfaces for applications and users to interact with the node."} -{"page_id": "reference-parachains-node-and-runtime", "page_title": "Node and Runtime", "index": 4, "depth": 2, "title": "Runtime", "anchor": "runtime", "start_char": 2939, "end_char": 3221, "estimated_token_count": 56, "token_estimator": "heuristic-v1", "text": "## Runtime\n\nThe runtime is more than just a set of rules. It's the fundamental logic engine that defines a blockchain's entire behavior. In Polkadot SDK-based blockchains, the runtime represents a complete, self-contained description of the blockchain's state transition function."} -{"page_id": "reference-parachains-node-and-runtime", "page_title": "Node and Runtime", "index": 5, "depth": 3, "title": "Characteristics", "anchor": "characteristics", "start_char": 3221, "end_char": 3555, "estimated_token_count": 68, "token_estimator": "heuristic-v1", "text": "### Characteristics\n\nThe runtime is distinguished by three key characteristics:\n\n- **Business logic**: Defines the complete application-specific blockchain behavior.\n- **WebAssembly compilation**: Ensures platform-independent, secure execution.\n- **On-chain storage**: Stored within the blockchain's state, allowing dynamic updates."} -{"page_id": "reference-parachains-node-and-runtime", "page_title": "Node and Runtime", "index": 6, "depth": 3, "title": "Key Functions", "anchor": "key-functions", "start_char": 3555, "end_char": 3840, "estimated_token_count": 50, "token_estimator": "heuristic-v1", "text": "### Key Functions\n\nThe runtime performs several critical functions, such as:\n\n- Define state transition rules.\n- Implement blockchain-specific logic.\n- Manage account interactions.\n- Control transaction processing.\n- Define governance mechanisms.\n- Handle custom pallets and modules."} -{"page_id": "reference-parachains-node-and-runtime", "page_title": "Node and Runtime", "index": 7, "depth": 2, "title": "Communication Between Node and Runtime", "anchor": "communication-between-node-and-runtime", "start_char": 3840, "end_char": 4112, "estimated_token_count": 53, "token_estimator": "heuristic-v1", "text": "## Communication Between Node and Runtime\n\nThe client and runtime communicate exclusively using [SCALE-encoded](/polkadot-protocol/parachain-basics/data-encoding){target=\\_blank} communication. This ensures efficient and compact data exchange between the two components."} -{"page_id": "reference-parachains-node-and-runtime", "page_title": "Node and Runtime", "index": 8, "depth": 3, "title": "Runtime APIs", "anchor": "runtime-apis", "start_char": 4112, "end_char": 4537, "estimated_token_count": 76, "token_estimator": "heuristic-v1", "text": "### Runtime APIs\n\nThe Runtime API consists of well-defined functions and constants a client assumes are implemented in the Runtime Wasm blob. These APIs enable the client to interact with the runtime to execute blockchain operations and retrieve information. The client invokes these APIs to:\n\n- Build, execute, and finalize blocks.\n- Access metadata.\n- Access consensus related information.\n- Handle transaction execution."} -{"page_id": "reference-parachains-node-and-runtime", "page_title": "Node and Runtime", "index": 9, "depth": 3, "title": "Host Functions", "anchor": "host-functions", "start_char": 4537, "end_char": 4937, "estimated_token_count": 65, "token_estimator": "heuristic-v1", "text": "### Host Functions\n\nDuring execution, the runtime can access certain external client functionalities via host functions. The specific functions the client exposes allow the runtime to perform operations outside the WebAssembly domain. Host functions enable the runtime to:\n\n- Perform cryptographic operations.\n- Access the current blockchain state.\n- Handle storage modifications.\n- Allocate memory."} -{"page_id": "reference-parachains-randomness", "page_title": "Randomness", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 14, "end_char": 1254, "estimated_token_count": 285, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nRandomness is crucial in Proof of Stake (PoS) blockchains to ensure a fair and unpredictable distribution of validator duties. However, computers are inherently deterministic, meaning the same input always produces the same output. What we typically refer to as \"random\" numbers on a computer are actually pseudo-random. These numbers rely on an initial \"seed,\" which can come from external sources like [atmospheric noise](https://www.random.org/randomness/){target=\\_blank}, [heart rates](https://mdpi.altmetric.com/details/47574324){target=\\_blank}, or even [lava lamps](https://en.wikipedia.org/wiki/Lavarand){target=\\_blank}. While this may seem random, given the same \"seed,\" the same sequence of numbers will always be generated.\n\nIn a global blockchain network, relying on real-world entropy for randomness isn’t feasible because these inputs vary by time and location. If nodes use different inputs, blockchains can fork. Hence, real-world randomness isn't suitable for use as a seed in blockchain systems.\n\nCurrently, two primary methods for generating randomness in blockchains are used: [`RANDAO`](#randao) and [`VRF`](#vrf) (Verifiable Random Function). Polkadot adopts the `VRF` approach for its randomness."} -{"page_id": "reference-parachains-randomness", "page_title": "Randomness", "index": 1, "depth": 2, "title": "VRF", "anchor": "vrf", "start_char": 1254, "end_char": 2042, "estimated_token_count": 183, "token_estimator": "heuristic-v1", "text": "## VRF\n\nA Verifiable Random Function (VRF) is a cryptographic function that generates a random number and proof that ensures the submitter produced the number. This proof allows anyone to verify the validity of the random number.\n\nPolkadot's VRF is similar to the one used in [**Ouroboros Praos**](https://eprint.iacr.org/2017/573.pdf){target=\\_blank}, which secures randomness for block production in systems like [BABE](/reference/polkadot-hub/consensus-and-security/pos-consensus/#block-production-babe){target=\\_blank} (Polkadot’s block production mechanism). \n\nThe key difference is that Polkadot's VRF doesn’t rely on a central clock—avoiding the issue of whose clock to trust. Instead, it uses its own past results and slot numbers to simulate time and determine future outcomes."} -{"page_id": "reference-parachains-randomness", "page_title": "Randomness", "index": 2, "depth": 3, "title": "How VRF Works", "anchor": "how-vrf-works", "start_char": 2042, "end_char": 4579, "estimated_token_count": 537, "token_estimator": "heuristic-v1", "text": "### How VRF Works\n\nSlots on Polkadot are discrete units of time, each lasting six seconds, and can potentially hold a block. Multiple slots form an epoch, with 2400 slots making up one four-hour epoch.\n\nIn each slot, validators execute a \"die roll\" using a VRF. The VRF uses three inputs:\n\n1. A \"secret key,\" unique to each validator, is used for the die roll.\n2. An epoch randomness value, derived from the hash of VRF outputs from blocks two epochs ago (N-2), so past randomness influences the current epoch (N).\n3. The current slot number.\n\nThis process helps maintain fair randomness across the network.\n\nHere is a graphical representation:\n\n![](/images/reference/parachains/randomness/randomness-01.webp)\n\nThe VRF produces two outputs: a result (the random number) and a proof (verifying that the number was generated correctly).\n\nThe result is checked by the validator against a protocol threshold. If it's below the threshold, the validator becomes a candidate for block production in that slot. \n\nThe validator then attempts to create a block, submitting it along with the `PROOF` and `RESULT`.\n\nSo, VRF can be expressed like:\n\n`(RESULT, PROOF) = VRF(SECRET, EPOCH_RANDOMNESS_VALUE, CURRENT_SLOT_NUMBER)`\n\nPut simply, performing a \"VRF roll\" generates a random number along with proof that the number was genuinely produced and not arbitrarily chosen.\n\nAfter executing the VRF, the `RESULT` is compared to a protocol-defined `THRESHOLD`. If the `RESULT` is below the `THRESHOLD`, the validator becomes a valid candidate to propose a block for that slot. Otherwise, the validator skips the slot.\n\nAs a result, there may be multiple validators eligible to propose a block for a slot. In this case, the block accepted by other nodes will prevail, provided it is on the chain with the latest finalized block as determined by the GRANDPA finality gadget. It's also possible for no block producers to be available for a slot, in which case the AURA consensus takes over. AURA is a fallback mechanism that randomly selects a validator to produce a block, running in parallel with BABE and only stepping in when no block producers exist for a slot. Otherwise, it remains inactive.\n\nBecause validators roll independently, no block candidates may appear in some slots if all roll numbers are above the threshold. \n\nTo verify resolution of this issue and that Polkadot block times remain near constant-time, see the [PoS Consensus](/reference/polkadot-hub/consensus-and-security/pos-consensus/){target=\\_blank} page of this documentation."} -{"page_id": "reference-parachains-randomness", "page_title": "Randomness", "index": 3, "depth": 2, "title": "RANDAO", "anchor": "randao", "start_char": 4579, "end_char": 5266, "estimated_token_count": 134, "token_estimator": "heuristic-v1", "text": "## RANDAO\n\nAn alternative on-chain randomness method is Ethereum's RANDAO, where validators perform thousands of hashes on a seed and publish the final hash during a round. The collective input from all validators forms the random number, and as long as one honest validator participates, the randomness is secure.\n\nTo enhance security, RANDAO can optionally be combined with a Verifiable Delay Function (VDF), ensuring that randomness can't be predicted or manipulated during computation.\n\nFor more information about RANDAO, see the [Randomness - RANDAO](https://eth2book.info/capella/part2/building_blocks/randomness/){target=\\_blank} section of the Upgrading Ethereum documentation."} -{"page_id": "reference-parachains-randomness", "page_title": "Randomness", "index": 4, "depth": 2, "title": "VDFs", "anchor": "vdfs", "start_char": 5266, "end_char": 5943, "estimated_token_count": 125, "token_estimator": "heuristic-v1", "text": "## VDFs\n\nVerifiable Delay Functions (VDFs) are time-bound computations that, even on parallel computers, take a set amount of time to complete. \n\nThey produce a unique result that can be quickly verified publicly. When combined with RANDAO, feeding RANDAO's output into a VDF introduces a delay that nullifies an attacker's chance to influence the randomness.\n\nHowever, VDF likely requires specialized ASIC devices to run separately from standard nodes.\n\n!!!warning \n While only one is needed to secure the system, and they will be open-source and inexpensive, running VDF devices involves significant costs without direct incentives, adding friction for blockchain users."} -{"page_id": "reference-parachains-randomness", "page_title": "Randomness", "index": 5, "depth": 2, "title": "Additional Resources", "anchor": "additional-resources", "start_char": 5943, "end_char": 6503, "estimated_token_count": 124, "token_estimator": "heuristic-v1", "text": "## Additional Resources\n\nFor more information about the reasoning for choices made along with proofs, see Polkadot's research on blockchain randomness and sortition in the [Block production](https://research.web3.foundation/Polkadot/protocols/block-production){target=\\_blank} entry of the Polkadot Wiki. \n\nFor a discussion with Web3 Foundation researchers about when and under what conditions Polkadot's randomness can be utilized, see the [Discussion on Randomness used in Polkadot](https://github.com/use-ink/ink/issues/57){target=\\_blank} issue on GitHub."} -{"page_id": "reference-parachains", "page_title": "Parachains Overview", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 23, "end_char": 1338, "estimated_token_count": 235, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nA parachain is a specialized blockchain that connects to the Polkadot relay chain, benefiting from shared security, interoperability, and scalability. Parachains are built using the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\\_blank}, a powerful toolkit written in Rust that provides everything needed to create custom blockchain logic while integrating seamlessly with the Polkadot network.\n\nUnlike standalone blockchains that must bootstrap their own validator sets and security, parachains leverage Polkadot's pooled security model. This allows parachain developers to focus on their application-specific functionality rather than consensus and security infrastructure. Parachains can communicate with each other through Cross-Consensus Messaging (XCM), enabling seamless interoperability across the Polkadot ecosystem.\n\nKey capabilities that parachains provide include:\n\n- **Shared security**: Inherit security from Polkadot's validator set without maintaining your own.\n- **Interoperability**: Communicate trustlessly with other parachains via XCM.\n- **Scalability**: Process transactions in parallel with other parachains.\n- **Customization**: Build application-specific logic tailored to your use case.\n- **Upgradeability**: Upgrade runtime logic without hard forks."} -{"page_id": "reference-parachains", "page_title": "Parachains Overview", "index": 1, "depth": 2, "title": "Polkadot SDK: Parachain Architecture", "anchor": "polkadot-sdk-parachain-architecture", "start_char": 1338, "end_char": 2576, "estimated_token_count": 308, "token_estimator": "heuristic-v1", "text": "## Polkadot SDK: Parachain Architecture\n\nBuilding a parachain involves understanding and utilizing several key components of the Polkadot SDK:\n\n![](/images/reference/parachains/index/overview-01.webp)\n\n- **[Substrate](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/substrate/index.html){target=\\_blank}**: The foundation providing core blockchain primitives and libraries.\n- **[FRAME](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html){target=\\_blank}**: A modular framework for building your parachain's runtime logic.\n- **[Cumulus](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/cumulus/index.html){target=\\_blank}**: Essential libraries and pallets that enable parachain functionality.\n- **[XCM (Cross Consensus Messaging)](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/xcm/index.html){target=\\_blank}**: The messaging format for communicating with other parachains and the relay chain.\n- **[Polkadot](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/polkadot/index.html){target=\\_blank}**: The relay chain that provides security and coordination."} -{"page_id": "reference-parachains", "page_title": "Parachains Overview", "index": 2, "depth": 3, "title": "Substrate: The Foundation", "anchor": "substrate-the-foundation", "start_char": 2576, "end_char": 4333, "estimated_token_count": 345, "token_estimator": "heuristic-v1", "text": "### Substrate: The Foundation\n\nSubstrate provides the core infrastructure that every parachain is built upon. It handles the low-level blockchain functionality, allowing you to focus on your application's unique features. Substrate includes implementations for networking, database management, consensus participation, and the execution environment for your runtime.\n\nEvery Polkadot SDK node consists of two main components:\n\n- **Client (Host)**: Handles infrastructure services.\n\n - Native binary that runs on validator and collator nodes.\n - Executes the Wasm-compiled runtime.\n - Manages networking, database, mempool, and block production.\n - Interfaces with the relay chain for validation.\n\n- **Runtime (State Transition Function)**: Contains your business logic.\n\n - Defines how your Polkadot SDK node processes transactions.\n - Compiled to [Wasm](https://webassembly.org/){target=\\_blank} for deterministic execution.\n - Stored on-chain and upgradeable via governance.\n\n```mermaid\n%%{init: {'flowchart': {'padding': 5, 'nodeSpacing': 50, 'rankSpacing': 10}}}%%\ngraph TB\n classDef title font-size:20px,font-weight:bold,stroke-width:0px\n classDef clientStyle font-size:16px,font-weight:bold\n classDef clientSubNodeStyle margin-top:10px\n classDef runtimeCallExecutorStyle padding-top:10px\n\n subgraph sg1[Parachain
Node]\n direction TB\n\n I[RuntimeCall Executor]\n B[Wasm Runtime - STF]\n\n subgraph sg2[Client]\n direction TB\n C[Network and Blockchain
Infrastructure Services
+ Relay Chain Interface]\n end\n\n I --> B\n end\n\n class sg1 title\n class sg2 clientStyle\n class C clientSubNodeStyle\n class I runtimeCallExecutorStyle\n\n```"} -{"page_id": "reference-parachains", "page_title": "Parachains Overview", "index": 3, "depth": 3, "title": "FRAME: Building Blocks for Your Runtime", "anchor": "frame-building-blocks-for-your-runtime", "start_char": 4333, "end_char": 6265, "estimated_token_count": 409, "token_estimator": "heuristic-v1", "text": "### FRAME: Building Blocks for Your Runtime\n\nFRAME provides modular components called [pallets](/reference/glossary#pallet){target=\\_blank} that you can compose to build your parachain's runtime. Each pallet provides specific functionality that you can customize and configure for your needs. This modular approach allows you to quickly assemble complex functionality without writing everything from scratch.\n\n```mermaid\ngraph LR\n subgraph SP[\"Parachain Runtime\"]\n direction LR\n Timestamp ~~~ Aura ~~~ ParachainSystem\n Balances ~~~ TransactionPayment ~~~ Sudo\n subgraph Timestamp[\"Timestamp\"]\n SS1[Custom Config]\n end\n subgraph Aura[\"Aura\"]\n SS2[Custom Config]\n end\n subgraph ParachainSystem[\"Parachain System\"]\n SS3[Custom Config]\n end\n subgraph Balances[\"Balances\"]\n SS4[Custom Config]\n end\n subgraph TransactionPayment[\"Transaction Payment\"]\n SS5[Custom Config]\n end\n subgraph Sudo[\"Sudo\"]\n SS6[Custom Config]\n end\n style Timestamp stroke:#FF69B4\n style Aura stroke:#FF69B4\n style ParachainSystem stroke:#FF69B4\n style Balances stroke:#FF69B4\n style TransactionPayment stroke:#FF69B4\n style Sudo stroke:#FF69B4\n style SS1 stroke-dasharray: 5\n style SS2 stroke-dasharray: 5\n style SS3 stroke-dasharray: 5\n style SS4 stroke-dasharray: 5\n style SS5 stroke-dasharray: 5\n style SS6 stroke-dasharray: 5\n\n end\n subgraph AP[\"Available FRAME Pallets\"]\n direction LR\n A1[Aura]~~~A2[Parachain
System]~~~A3[Transaction
Payment]~~~A4[Sudo]\n B1[Identity]~~~B2[Balances]~~~B3[Assets]~~~B4[EVM]\n C1[Timestamp]~~~C2[Staking]~~~C3[Contracts]~~~C4[and more...]\n end\n AP --> SP\n```"} -{"page_id": "reference-parachains", "page_title": "Parachains Overview", "index": 4, "depth": 3, "title": "Cumulus: Parachain-Specific Functionality", "anchor": "cumulus-parachain-specific-functionality", "start_char": 6265, "end_char": 6970, "estimated_token_count": 133, "token_estimator": "heuristic-v1", "text": "### Cumulus: Parachain-Specific Functionality\n\nCumulus is what transforms a Polkadot SDK-based runtime into a parachain-capable runtime. It provides the essential components for communicating with the relay chain, participating in Polkadot's consensus, and handling parachain-specific operations like block validation and collation.\n\nKey Cumulus components include:\n\n- **Parachain system pallet**: Core parachain functionality and relay chain communication.\n- **Collator consensus**: Block production logic for parachain collators.\n- **Relay chain interface**: APIs for interacting with the Polkadot relay chain.\n- **Validation data**: Handling proof-of-validity data required by relay chain validators."} -{"page_id": "reference-parachains", "page_title": "Parachains Overview", "index": 5, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 6970, "end_char": 8495, "estimated_token_count": 329, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\nBuilding a parachain requires understanding the relationship between your chain and the Polkadot relay chain. The Polkadot SDK provides all the tools needed to design custom runtime logic, enable cross-chain communication, and deploy your parachain to production.\n\nThe following sections provide detailed guidance on each aspect of parachain development, from initial design through deployment and ongoing maintenance.\n\n
\n\n- Guide __Launch a Simple Parachain__\n\n ---\n\n Walk through the complete parachain launch flow: from setup and deployment to obtaining coretime.\n\n [:octicons-arrow-right-24: Deploy](/parachains/launch-a-parachain/set-up-the-parachain-template/)\n\n\n- Guide __Customize Your Runtime__\n\n ---\n\n Design your parachain's runtime logic and choose appropriate pallets for your use case.\n\n [:octicons-arrow-right-24: Get Started](/parachains/customize-runtime/)\n\n- Guide __Interoperability__\n\n ---\n\n Implement XCM for trustless cross-chain communication with other parachains.\n\n [:octicons-arrow-right-24: Learn More](/parachains/interoperability/get-started/)\n\n- Guide __Runtime Upgrades__\n\n ---\n\n Upgrade your parachain's runtime without hard forks using forkless upgrade mechanisms.\n\n [:octicons-arrow-right-24: Maintain](/parachains/runtime-maintenance/runtime-upgrades/)\n\n
"} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 13, "end_char": 682, "estimated_token_count": 131, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nThe Asset Hub is a critical component in the Polkadot ecosystem, enabling the management of fungible and non-fungible assets across the network. Since the relay chain focuses on maintaining security and consensus without direct asset management, Asset Hub provides a streamlined platform for creating, managing, and using on-chain assets in a fee-efficient manner. This guide outlines the core features of Asset Hub, including how it handles asset operations, cross-chain transfers, and asset integration using XCM, as well as essential tools like [API Sidecar](#api-sidecar) and [`TxWrapper`](#txwrapper) for developers working with on-chain assets."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 1, "depth": 2, "title": "Assets Basics", "anchor": "assets-basics", "start_char": 682, "end_char": 3257, "estimated_token_count": 493, "token_estimator": "heuristic-v1", "text": "## Assets Basics\n\nIn the Polkadot ecosystem, the relay chain does not natively support additional assets beyond its native token (DOT for Polkadot, KSM for Kusama). The Asset Hub parachain on Polkadot and Kusama provides a fungible and non-fungible assets framework. Asset Hub allows developers and users to create, manage, and use assets across the ecosystem.\n\nAsset creators can use Asset Hub to track their asset issuance across multiple parachains and manage assets through operations such as minting, burning, and transferring. Projects that need a standardized method of handling on-chain assets will find this particularly useful. The fungible asset interface provided by Asset Hub closely resembles Ethereum's ERC-20 standard but is directly integrated into Polkadot's runtime, making it more efficient in terms of speed and transaction fees.\n\nIntegrating with Asset Hub offers several key benefits, particularly for infrastructure providers and users:\n\n- **Support for non-native on-chain assets**: Asset Hub enables seamless asset creation and management, allowing projects to develop tokens or assets that can interact with the broader ecosystem.\n- **Lower transaction fees**: Asset Hub offers significantly lower transaction costs—approximately one-tenth of the fees on the relay chain, providing cost-efficiency for regular operations.\n- **Reduced deposit requirements**: Depositing assets in Asset Hub is more accessible, with deposit requirements that are around one one-hundredth of those on the relay chain.\n- **Payment of transaction fees with non-native assets**: Users can pay transaction fees in assets other than the native token (DOT or KSM), offering more flexibility for developers and users.\n\nAssets created on the Asset Hub are stored as part of a map, where each asset has a unique ID that links to information about the asset, including details like:\n\n- The management team.\n- The total supply.\n- The number of accounts holding the asset.\n- **Sufficiency for account existence**: Whether the asset alone is enough to maintain an account without a native token balance.\n- The metadata of the asset, including its name, symbol, and the number of decimals for representation.\n\nSome assets can be regarded as sufficient to maintain an account's existence, meaning that users can create accounts on the network without needing a native token balance (i.e., no existential deposit required). Developers can also set minimum balances for their assets. If an account's balance drops below the minimum, the balance is considered dust and may be cleared."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 2, "depth": 2, "title": "Assets Pallet", "anchor": "assets-pallet", "start_char": 3257, "end_char": 3793, "estimated_token_count": 112, "token_estimator": "heuristic-v1", "text": "## Assets Pallet\n\nThe Polkadot SDK's Assets pallet is a powerful module designated for creating and managing fungible asset classes with a fixed supply. It offers a secure and flexible way to issue, transfer, freeze, and destroy assets. The pallet supports various operations and includes permissioned and non-permissioned functions to cater to simple and advanced use cases.\n\nVisit the [Assets Pallet Rust docs](https://paritytech.github.io/polkadot-sdk/master/pallet_assets/index.html){target=\\_blank} for more in-depth information."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 3, "depth": 3, "title": "Key Features", "anchor": "key-features", "start_char": 3793, "end_char": 4454, "estimated_token_count": 140, "token_estimator": "heuristic-v1", "text": "### Key Features\n\nKey features of the Assets pallet include:\n\n- **Asset issuance**: Allows the creation of a new asset, where the total supply is assigned to the creator's account.\n- **Asset transfer**: Enables transferring assets between accounts while maintaining a balance in both accounts.\n- **Asset freezing**: Prevents transfers of a specific asset from one account, locking it from further transactions.\n- **Asset destruction**: Allows accounts to burn or destroy their holdings, removing those assets from circulation.\n- **Non-custodial transfers**: A non-custodial mechanism to enable one account to approve a transfer of assets on behalf of another."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 4, "depth": 3, "title": "Main Functions", "anchor": "main-functions", "start_char": 4454, "end_char": 5397, "estimated_token_count": 235, "token_estimator": "heuristic-v1", "text": "### Main Functions\n\nThe Assets pallet provides a broad interface for managing fungible assets. Some of the main dispatchable functions include:\n\n- **`create()`**: Create a new asset class by placing a deposit, applicable when asset creation is permissionless.\n- **`issue()`**: Mint a fixed supply of a new asset and assign it to the creator's account.\n- **`transfer()`**: Transfer a specified amount of an asset between two accounts.\n- **`approve_transfer()`**: Approve a non-custodial transfer, allowing a third party to move assets between accounts.\n- **`destroy()`**: Destroy an entire asset class, removing it permanently from the chain.\n- **`freeze()` and `thaw()`**: Administrators or privileged users can lock or unlock assets from being transferred.\n\nFor a full list of dispatchable and privileged functions, see the [dispatchables Rust docs](https://docs.rs/pallet-assets/latest/pallet_assets/pallet/enum.Call.html){target=\\_blank}."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 5, "depth": 3, "title": "Querying Functions", "anchor": "querying-functions", "start_char": 5397, "end_char": 6347, "estimated_token_count": 193, "token_estimator": "heuristic-v1", "text": "### Querying Functions\n\nThe Assets pallet exposes several key querying functions that developers can interact with programmatically. These functions allow you to query asset information and perform operations essential for managing assets across accounts. The two main querying functions are:\n\n- **`balance(asset_id, account)`**: Retrieves the balance of a given asset for a specified account. Useful for checking the holdings of an asset class across different accounts.\n\n- **`total_supply(asset_id)`**: Returns the total supply of the asset identified by `asset_id`. Allows users to verify how much of the asset exists on-chain.\n\nIn addition to these basic functions, other utility functions are available for querying asset metadata and performing asset transfers. You can view the complete list of querying functions in the [Struct Pallet Rust docs](https://docs.rs/pallet-assets/latest/pallet_assets/pallet/struct.Pallet.html){target=\\_blank}."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 6, "depth": 3, "title": "Permission Models and Roles", "anchor": "permission-models-and-roles", "start_char": 6347, "end_char": 7634, "estimated_token_count": 239, "token_estimator": "heuristic-v1", "text": "### Permission Models and Roles\n\nThe Assets pallet incorporates a robust permission model, enabling control over who can perform specific operations like minting, transferring, or freezing assets. The key roles within the permission model are:\n\n- **Admin**: Can freeze (preventing transfers) and forcibly transfer assets between accounts. Admins also have the power to reduce the balance of an asset class across arbitrary accounts. They manage the more sensitive and administrative aspects of the asset class.\n- **Issuer**: Responsible for minting new tokens. When new assets are created, the Issuer is the account that controls their distribution to other accounts.\n- **Freezer**: Can lock the transfer of assets from an account, preventing the account holder from moving their balance. This function is useful for freezing accounts involved in disputes or fraud.\n- **Owner**: Has overarching control, including destroying an entire asset class. Owners can also set or update the Issuer, Freezer, and Admin roles.\n\nThese permissions provide fine-grained control over assets, enabling developers and asset managers to ensure secure, controlled operations. Each of these roles is crucial for managing asset lifecycles and ensuring that assets are used appropriately across the network."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 7, "depth": 3, "title": "Asset Freezing", "anchor": "asset-freezing", "start_char": 7634, "end_char": 8552, "estimated_token_count": 172, "token_estimator": "heuristic-v1", "text": "### Asset Freezing\n\nThe Assets pallet allows you to freeze assets. This feature prevents transfers or spending from a specific account, effectively locking the balance of an asset class until it is explicitly unfrozen. Asset freezing is beneficial when assets are restricted due to security concerns or disputes.\n\nFreezing assets is controlled by the Freezer role, as mentioned earlier. Only the account with the Freezer privilege can perform these operations. Here are the key freezing functions:\n\n- **`freeze(asset_id, account)`**: Locks the specified asset of the account. While the asset is frozen, no transfers can be made from the frozen account.\n- **`thaw(asset_id, account)`**: Corresponding function for unfreezing, allowing the asset to be transferred again.\n\nThis approach enables secure and flexible asset management, providing administrators the tools to control asset movement in special circumstances."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 8, "depth": 3, "title": "Non-Custodial Transfers (Approval API)", "anchor": "non-custodial-transfers-approval-api", "start_char": 8552, "end_char": 9746, "estimated_token_count": 232, "token_estimator": "heuristic-v1", "text": "### Non-Custodial Transfers (Approval API)\n\nThe Assets pallet also supports non-custodial transfers through the Approval API. This feature allows one account to approve another account to transfer a specific amount of its assets to a third-party recipient without granting full control over the account's balance. Non-custodial transfers enable secure transactions where trust is required between multiple parties.\n\nHere's a brief overview of the key functions for non-custodial asset transfers:\n\n- **`approve_transfer(asset_id, delegate, amount)`**: Approves a delegate to transfer up to a certain amount of the asset on behalf of the original account holder.\n- **`cancel_approval(asset_id, delegate)`**: Cancels a previous approval for the delegate. Once canceled, the delegate no longer has permission to transfer the approved amount.\n- **`transfer_approved(asset_id, owner, recipient, amount)`**: Executes the approved asset transfer from the owner’s account to the recipient. The delegate account can call this function once approval is granted.\n\nThese delegated operations make it easier to manage multi-step transactions and dApps that require complex asset flows between participants."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 9, "depth": 2, "title": "Foreign Assets", "anchor": "foreign-assets", "start_char": 9746, "end_char": 10290, "estimated_token_count": 94, "token_estimator": "heuristic-v1", "text": "## Foreign Assets\n\nForeign assets in Asset Hub refer to assets originating from external blockchains or parachains that are registered in the Asset Hub. These assets are typically native tokens from other parachains within the Polkadot ecosystem or bridged tokens from external blockchains such as Ethereum.\n\nOnce a foreign asset is registered in the Asset Hub by its originating blockchain's root origin, users are able to send these tokens to the Asset Hub and interact with them as they would any other asset within the Polkadot ecosystem."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 10, "depth": 3, "title": "Handling Foreign Assets", "anchor": "handling-foreign-assets", "start_char": 10290, "end_char": 11225, "estimated_token_count": 166, "token_estimator": "heuristic-v1", "text": "### Handling Foreign Assets\n\nThe Foreign Assets pallet, an instance of the Assets pallet, manages these assets. Since foreign assets are integrated into the same interface as native assets, developers can use the same functionalities, such as transferring and querying balances. However, there are important distinctions when dealing with foreign assets.\n\n- **Asset identifier**: Unlike native assets, foreign assets are identified using an XCM Multilocation rather than a simple numeric `AssetId`. This multilocation identifier represents the cross-chain location of the asset and provides a standardized way to reference it across different parachains and relay chains.\n\n- **Transfers**: Once registered in the Asset Hub, foreign assets can be transferred between accounts, just like native assets. Users can also send these assets back to their originating blockchain if supported by the relevant cross-chain messaging mechanisms."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 11, "depth": 2, "title": "Integration", "anchor": "integration", "start_char": 11225, "end_char": 11668, "estimated_token_count": 71, "token_estimator": "heuristic-v1", "text": "## Integration\n\nAsset Hub supports a variety of integration tools that make it easy for developers to manage assets and interact with the blockchain in their applications. The tools and libraries provided by Parity Technologies enable streamlined operations, such as querying asset information, building transactions, and monitoring cross-chain asset transfers.\n\nDevelopers can integrate Asset Hub into their projects using these core tools:"} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 12, "depth": 3, "title": "API Sidecar", "anchor": "api-sidecar", "start_char": 11668, "end_char": 12511, "estimated_token_count": 211, "token_estimator": "heuristic-v1", "text": "### API Sidecar\n\n[API Sidecar](https://github.com/paritytech/substrate-api-sidecar){target=\\_blank} is a RESTful service that can be deployed alongside Polkadot and Kusama nodes. It provides endpoints to retrieve real-time blockchain data, including asset information. When used with Asset Hub, Sidecar allows querying:\n\n- **Asset look-ups**: Retrieve specific assets using `AssetId`.\n- **Asset balances**: View the balance of a particular asset on Asset Hub.\n\nPublic instances of API Sidecar connected to Asset Hub are available, such as:\n\n- [Polkadot Asset Hub Sidecar](https://polkadot-asset-hub-public-sidecar.parity-chains.parity.io/){target=\\_blank}\n- [Kusama Asset Hub Sidecar](https://kusama-asset-hub-public-sidecar.parity-chains.parity.io/){target=\\_blank}\n\nThese public instances are primarily for ad-hoc testing and quick checks."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 13, "depth": 3, "title": "TxWrapper", "anchor": "txwrapper", "start_char": 12511, "end_char": 13113, "estimated_token_count": 113, "token_estimator": "heuristic-v1", "text": "### TxWrapper\n\n[`TxWrapper`](https://github.com/paritytech/txwrapper-core){target=\\_blank} is a library that simplifies constructing and signing transactions for Polkadot SDK-based chains, including Polkadot and Kusama. This tool includes support for working with Asset Hub, enabling developers to:\n\n- Construct offline transactions.\n- Leverage asset-specific functions such as minting, burning, and transferring assets.\n\n`TxWrapper` provides the flexibility needed to integrate asset operations into custom applications while maintaining the security and efficiency of Polkadot's transaction model."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 14, "depth": 3, "title": "Parachain Node", "anchor": "parachain-node", "start_char": 13113, "end_char": 13766, "estimated_token_count": 131, "token_estimator": "heuristic-v1", "text": "### Parachain Node\n\nTo fully leverage the Asset Hub's functionality, developers will need to run a system parachain node. Setting up an Asset Hub node allows users to interact with the parachain in real time, syncing data and participating in the broader Polkadot ecosystem. Guidelines for setting up an [Asset Hub node](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/cumulus#asset-hub-){target=\\_blank} are available in the Parity documentation.\n\nUsing these integration tools, developers can manage assets seamlessly and integrate Asset Hub functionality into their applications, leveraging Polkadot's powerful infrastructure."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 15, "depth": 2, "title": "XCM Transfer Monitoring", "anchor": "xcm-transfer-monitoring", "start_char": 13766, "end_char": 14109, "estimated_token_count": 56, "token_estimator": "heuristic-v1", "text": "## XCM Transfer Monitoring\n\nSince Asset Hub facilitates cross-chain asset transfers across the Polkadot ecosystem, XCM transfer monitoring becomes an essential practice for developers and infrastructure providers. This section outlines how to monitor the cross-chain movement of assets between parachains, the relay chain, and other systems."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 16, "depth": 3, "title": "Monitor XCM Deposits", "anchor": "monitor-xcm-deposits", "start_char": 14109, "end_char": 14901, "estimated_token_count": 160, "token_estimator": "heuristic-v1", "text": "### Monitor XCM Deposits\n\nAs assets move between chains, tracking the cross-chain transfers in real time is crucial. Whether assets are transferred via a teleport from system parachains or through a reserve-backed transfer from any other parachain, each transfer emits a relevant event (such as the `balances.minted` event).\n\nTo ensure accurate monitoring of these events:\n\n- **Track XCM deposits**: Query every new block created in the relay chain or Asset Hub, loop through the events array, and filter for any `balances.minted` events which confirm the asset was successfully transferred to the account.\n- **Track event origins**: Each `balances.minted` event points to a specific address. By monitoring this, service providers can verify that assets have arrived in the correct account."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 17, "depth": 3, "title": "Track XCM Information Back to the Source", "anchor": "track-xcm-information-back-to-the-source", "start_char": 14901, "end_char": 15568, "estimated_token_count": 146, "token_estimator": "heuristic-v1", "text": "### Track XCM Information Back to the Source\n\nWhile the `balances.minted` event confirms the arrival of assets, there may be instances where you need to trace the origin of the cross-chain message that triggered the event. In such cases, you can:\n\n1. Query the relevant chain at the block where the `balances.minted` event was emitted.\n2. Look for a `messageQueue(Processed)` event within that block's initialization. This event contains a parameter (`Id`) that identifies the cross-chain message received by the relay chain or Asset Hub. You can use this `Id` to trace the message back to its origin chain, offering full visibility of the asset transfer's journey."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 18, "depth": 3, "title": "Practical Monitoring Examples", "anchor": "practical-monitoring-examples", "start_char": 15568, "end_char": 16379, "estimated_token_count": 163, "token_estimator": "heuristic-v1", "text": "### Practical Monitoring Examples\n\nThe preceding sections outline the process of monitoring XCM deposits to specific accounts and then tracing back the origin of these deposits. The process of tracking an XCM transfer and the specific events to monitor may vary based on the direction of the XCM message. Here are some examples to showcase the slight differences:\n\n- **Transfer from parachain to relay chain**: Track `parachainsystem(UpwardMessageSent)` on the parachain and `messagequeue(Processed)` on the relay chain.\n- **Transfer from relay chain to parachain**: Track `xcmPallet(sent)` on the relay chain and `dmpqueue(ExecutedDownward)` on the parachain.\n- **Transfer between parachains**: Track `xcmpqueue(XcmpMessageSent)` on the system parachain and `xcmpqueue(Success)` on the destination parachain."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 19, "depth": 3, "title": "Monitor for Failed XCM Transfers", "anchor": "monitor-for-failed-xcm-transfers", "start_char": 16379, "end_char": 17187, "estimated_token_count": 176, "token_estimator": "heuristic-v1", "text": "### Monitor for Failed XCM Transfers\n\nSometimes, XCM transfers may fail due to liquidity or other errors. Failed transfers emit specific error events, which are key to resolving issues in asset transfers. Monitoring for these failure events helps catch issues before they affect asset balances.\n\n- **Relay chain to system parachain**: Look for the `dmpqueue(ExecutedDownward)` event on the parachain with an `Incomplete` outcome and an error type such as `UntrustedReserveLocation`.\n- **Parachain to parachain**: Monitor for `xcmpqueue(Fail)` on the destination parachain with error types like `TooExpensive`.\n\nFor detailed error management in XCM, see Gavin Wood's blog post on [XCM Execution and Error Management](https://polkadot.com/blog/xcm-part-three-execution-and-error-management/){target=\\_blank}."} -{"page_id": "reference-polkadot-hub-assets-and-smart-contracts", "page_title": "Asset Hub", "index": 20, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 17187, "end_char": 18211, "estimated_token_count": 244, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\n
\n\n- Tutorial __Register a Local Asset__\n\n ---\n\n Comprehensive guide to registering a local asset on the Asset Hub system parachain, including step-by-step instructions.\n\n [:octicons-arrow-right-24: Reference](/chain-interactions/token-operations/register-local-asset/)\n\n- Tutorial __Register a Foreign Asset__\n\n ---\n\n An in-depth guide to registering a foreign asset on the Asset Hub parachain, providing clear, step-by-step instructions.\n\n [:octicons-arrow-right-24: Reference](/chain-interactions/token-operations/register-foreign-asset/)\n\n- Tutorial __Convert Assets__\n\n ---\n\n A guide detailing the step-by-step process of converting assets on Asset Hub, helping users efficiently navigate asset management on the platform.\n\n [:octicons-arrow-right-24: Reference](/chain-interactions/token-operations/convert-assets/)\n\n
"} -{"page_id": "reference-polkadot-hub-bridging", "page_title": "Bridge Hub", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 14, "end_char": 1065, "estimated_token_count": 184, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nThe Bridge Hub system parachain plays a crucial role in facilitating trustless interactions between Polkadot, Kusama, Ethereum, and other blockchain ecosystems. By implementing on-chain light clients and supporting protocols like BEEFY and GRANDPA, Bridge Hub ensures seamless message transmission and state verification across chains. It also provides essential [pallets](/reference/glossary/#pallet){target=\\_blank} for sending and receiving messages, making it a cornerstone of Polkadot’s interoperability framework. With built-in support for XCM (Cross-Consensus Messaging), Bridge Hub enables secure, efficient communication between diverse blockchain networks.\n\nThis guide covers the architecture, components, and deployment of the Bridge Hub system. You'll explore its trustless bridging mechanisms, key pallets for various blockchains, and specific implementations like Snowbridge and the Polkadot <> Kusama bridge. By the end, you'll understand how Bridge Hub enhances connectivity within the Polkadot ecosystem and beyond."} -{"page_id": "reference-polkadot-hub-bridging", "page_title": "Bridge Hub", "index": 1, "depth": 2, "title": "Trustless Bridging", "anchor": "trustless-bridging", "start_char": 1065, "end_char": 2671, "estimated_token_count": 313, "token_estimator": "heuristic-v1", "text": "## Trustless Bridging\n\nBridge Hub provides a mode of trustless bridging through its implementation of on-chain light clients and trustless relayers. Trustless bridges are essentially two one-way bridges, where each chain has a method of verifying the state of the other in a trustless manner through consensus proofs. In this context, \"trustless\" refers to the lack of need to trust a human when interacting with various system components. Trustless systems are based instead on trusting mathematics, cryptography, and code. The target chain and source chain both provide ways of verifying one another's state and actions (such as a transfer) based on the consensus and finality of both chains rather than an external mechanism controlled by a third party.\n\n[BEEFY (Bridge Efficiency Enabling Finality Yielder)](/reference/polkadot-hub/consensus-and-security/pos-consensus/#bridging-beefy){target=\\_blank} is instrumental in this solution. It provides a more efficient way to verify the consensus on the relay chain. It allows the participants in a network to verify finality proofs, meaning a remote chain like Ethereum can verify the state of Polkadot at a given block height. \n\nFor example, the Ethereum and Polkadot bridging solution that [Snowbridge](https://docs.snowbridge.network/){target=\\_blank} implements involves two light clients: one which verifies the state of Polkadot and the other which verifies the state of Ethereum. The light client for Polkadot is implemented in the runtime as a pallet, whereas the light client for Ethereum is implemented as a smart contract on the beacon chain."} -{"page_id": "reference-polkadot-hub-bridging", "page_title": "Bridge Hub", "index": 2, "depth": 2, "title": "Bridging Components", "anchor": "bridging-components", "start_char": 2671, "end_char": 3623, "estimated_token_count": 242, "token_estimator": "heuristic-v1", "text": "## Bridging Components\n\nIn any given Bridge Hub implementation (Kusama, Polkadot, or other relay chains), there are a few primary pallets that are utilized:\n\n- **[Pallet Bridge GRANDPA](https://paritytech.github.io/polkadot-sdk/master/pallet_bridge_grandpa/index.html){target=\\_blank}**: An on-chain GRANDPA light client for Substrate based chains.\n- **[Pallet Bridge Parachains](https://paritytech.github.io/polkadot-sdk/master/pallet_bridge_parachains/index.html){target=\\_blank}**: A finality module for parachains.\n- **[Pallet Bridge Messages](https://paritytech.github.io/polkadot-sdk/master/pallet_bridge_messages/index.html){target=\\_blank}**: A pallet which allows sending, receiving, and tracking of inbound and outbound messages.\n- **[Pallet XCM Bridge](https://paritytech.github.io/polkadot-sdk/master/pallet_xcm_bridge_hub/index.html){target=\\_blank}**: A pallet which, with the Bridge Messages pallet, adds XCM support to bridge pallets."} -{"page_id": "reference-polkadot-hub-bridging", "page_title": "Bridge Hub", "index": 3, "depth": 3, "title": "Ethereum-Specific Support", "anchor": "ethereum-specific-support", "start_char": 3623, "end_char": 4243, "estimated_token_count": 149, "token_estimator": "heuristic-v1", "text": "### Ethereum-Specific Support\n\nBridge Hub also has a set of components and pallets that support a bridge between Polkadot and Ethereum through [Snowbridge](https://github.com/Snowfork/snowbridge){target=\\_blank}.\n\nTo view the complete list of which pallets are included in Bridge Hub, visit the Subscan [Runtime Modules](https://bridgehub-polkadot.subscan.io/runtime){target=\\_blank} page. Alternatively, the source code for those pallets can be found in the Polkadot SDK [Snowbridge Pallets](https://github.com/paritytech/polkadot-sdk/tree/polkadot-stable2506-2/bridges/snowbridge/pallets){target=\\_blank} repository."} -{"page_id": "reference-polkadot-hub-bridging", "page_title": "Bridge Hub", "index": 4, "depth": 2, "title": "Deployed Bridges", "anchor": "deployed-bridges", "start_char": 4243, "end_char": 4840, "estimated_token_count": 160, "token_estimator": "heuristic-v1", "text": "## Deployed Bridges\n\n- [**Snowbridge**](https://wiki.polkadot.com/learn/learn-snowbridge/){target=\\_blank}: A general-purpose, trustless bridge between Polkadot and Ethereum.\n- [**Hyperbridge**](https://wiki.polkadot.com/learn/learn-hyperbridge/){target=\\_blank}: A cross-chain solution built as an interoperability coprocessor, providing state-proof-based interoperability across all blockchains.\n- [**Polkadot <> Kusama Bridge**](https://wiki.polkadot.com/learn/learn-dot-ksm-bridge/){target=\\_blank}: A bridge that utilizes relayers to bridge the Polkadot and Kusama relay chains trustlessly."} -{"page_id": "reference-polkadot-hub-bridging", "page_title": "Bridge Hub", "index": 5, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 4840, "end_char": 5467, "estimated_token_count": 172, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\n- Go over the Bridge Hub README in the Polkadot SDK [Bridge-hub Parachains](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/cumulus/parachains/runtimes/bridge-hubs/README.md){target=\\_blank} repository.\n- Take a deeper dive into bridging architecture in the Polkadot SDK [High-Level Bridge](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/bridges/docs/high-level-overview.md){target=\\_blank} documentation.\n- Read more about [BEEFY and Bridging in the Polkadot Wiki](/reference/polkadot-hub/consensus-and-security/pos-consensus/#bridging-beefy){target=\\_blank}."} -{"page_id": "reference-polkadot-hub-collectives-and-daos", "page_title": "Collectives Chain", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 0, "end_char": 824, "estimated_token_count": 150, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nEstablished through [Referendum 81](https://polkadot-old.polkassembly.io/referendum/81){target=\\_blank}, the Collectives chain operates as a dedicated parachain exclusive to the Polkadot network with no counterpart on Kusama. This specialized infrastructure provides a foundation for various on-chain governance groups essential to Polkadot's ecosystem.\n\nThe architecture enables entire networks to function as unified entities, allowing them to present cohesive positions and participate in cross-network governance through [Bridge Hub](/polkadot-protocol/architecture/system-chains/bridge-hub){target=\\_blank}. This capability represents a fundamental advancement in Web3 principles, eliminating dependencies on traditional third-party intermediaries such as legal systems or jurisdictional authorities."} -{"page_id": "reference-polkadot-hub-collectives-and-daos", "page_title": "Collectives Chain", "index": 1, "depth": 2, "title": "Key Collectives", "anchor": "key-collectives", "start_char": 824, "end_char": 2288, "estimated_token_count": 274, "token_estimator": "heuristic-v1", "text": "## Key Collectives\n\nThe Collectives chain hosts several important governance bodies:\n\n- [**Polkadot Technical Fellowship**](https://wiki.polkadot.com/learn/learn-polkadot-technical-fellowship/){target=\\_blank}: A self-governing assembly of protocol experts and developers who oversee technical aspects of the Polkadot and Kusama networks. The Fellowship operates both on-chain through the collectives system and off-chain via GitHub repositories, public discussion forums, and monthly development calls that are publicly accessible.\n\n- [**Polkadot Alliance**](https://wiki.polkadot.com/general/glossary/#polkadot-alliance){target=\\_blank}: A consortium founded by seven leading parachain projects (Acala, Astar, Interlay, Kilt, Moonbeam, Phala, and Subscan) to establish development standards and ethical guidelines within the ecosystem. This ranked collective, comprised of \"Fellows\" and \"Allies,\" focuses on promoting best practices and identifying potential bad actors. Membership is primarily designed for organizations, projects, and other networks rather than individuals.\n\nThese collectives serve as pillars of Polkadot's decentralized governance model, enabling community-driven decision-making and establishing technical standards that shape the network's evolution. Through structured on-chain representation, they provide transparent mechanisms for ecosystem development while maintaining the core Web3 principles of trustlessness and decentralization."} -{"page_id": "reference-polkadot-hub-consensus-and-security-agile-coretime", "page_title": "Agile Coretime", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 18, "end_char": 1479, "estimated_token_count": 318, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nAgile Coretime is the [scheduling](https://en.wikipedia.org/wiki/Scheduling_(computing)){target=\\_blank} framework on Polkadot that lets parachains efficiently access cores, which comprise an active validator set tasked with parablock validation. As the first blockchain to enable a flexible scheduling system for blockspace production, Polkadot offers unparalleled adaptability for parachains.\n\n``` mermaid\ngraph TB\n A[Cores Designation]\n B[Bulk Coretime]\n C[On-Demand Coretime]\n A --continuous--> B\n A --flexible--> C \n```\n\nCores can be designated to a parachain either continuously through [bulk coretime](#bulk-coretime) or dynamically via [on-demand coretime](#on-demand-coretime). Additionally, Polkadot supports scheduling multiple cores in parallel through [elastic scaling](https://wiki.polkadot.com/learn/learn-elastic-scaling/){target=\\_blank}, which is a feature under active development on Polkadot. This flexibility empowers parachains to optimize their resource usage and block production according to their unique needs.\n\nIn this guide, you'll learn how bulk coretime enables continuous core access with features like interlacing and splitting, and how on-demand coretime provides flexible, pay-per-use scheduling for parachains. For a deep dive on Agile Coretime and its terminology, refer to the [Wiki doc](https://wiki.polkadot.com/learn/learn-agile-coretime/#introduction-to-agile-coretime){target=\\_blank}."} -{"page_id": "reference-polkadot-hub-consensus-and-security-agile-coretime", "page_title": "Agile Coretime", "index": 1, "depth": 2, "title": "Bulk Coretime", "anchor": "bulk-coretime", "start_char": 1479, "end_char": 2179, "estimated_token_count": 148, "token_estimator": "heuristic-v1", "text": "## Bulk Coretime\n\nBulk coretime is a fixed duration of continuous coretime represented by an NFT that can be purchased through [coretime sales](#coretime-sales) in DOT and can be split, shared, or resold. Currently, the duration of bulk coretime is set to 28 days. Coretime purchased in bulk and assigned to a single parachain is eligible for a price-capped renewal, providing a form of rent-controlled access, which is important for predicting the running costs in the near future. Suppose the bulk coretime is [interlaced](#coretime-interlacing) or [split](#coretime-splitting) or is kept idle without assigning it to a parachain. In that case, it will be ineligible for the price-capped renewal."} -{"page_id": "reference-polkadot-hub-consensus-and-security-agile-coretime", "page_title": "Agile Coretime", "index": 2, "depth": 3, "title": "Coretime Interlacing", "anchor": "coretime-interlacing", "start_char": 2179, "end_char": 2550, "estimated_token_count": 62, "token_estimator": "heuristic-v1", "text": "### Coretime Interlacing\n\nIt is the action of dividing bulk coretime across multiple parachains that produce blocks spaced uniformly in time. For example, think of multiple parachains taking turns producing blocks, demonstrating a simple form of interlacing. This feature can be used by parachains with a low transaction volume and need not continuously produce blocks."} -{"page_id": "reference-polkadot-hub-consensus-and-security-agile-coretime", "page_title": "Agile Coretime", "index": 3, "depth": 3, "title": "Coretime Splitting", "anchor": "coretime-splitting", "start_char": 2550, "end_char": 2815, "estimated_token_count": 49, "token_estimator": "heuristic-v1", "text": "### Coretime Splitting\n\nIt is the action of dividing bulk coretime into multiple contiguous regions. This feature can be used by parachains that need to produce blocks continuously but do not require the whole 28 days of bulk coretime and require only part of it."} -{"page_id": "reference-polkadot-hub-consensus-and-security-agile-coretime", "page_title": "Agile Coretime", "index": 4, "depth": 2, "title": "On-Demand Coretime", "anchor": "on-demand-coretime", "start_char": 2815, "end_char": 3028, "estimated_token_count": 42, "token_estimator": "heuristic-v1", "text": "## On-Demand Coretime\n\nPolkadot has dedicated cores assigned to provide core time on demand. These cores are excluded from the coretime sales and are reserved for on-demand parachains, which pay in DOT per block."} -{"page_id": "reference-polkadot-hub-consensus-and-security-pos-consensus", "page_title": "Proof of Stake Consensus", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 28, "end_char": 761, "estimated_token_count": 132, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nPolkadot's Proof of Stake consensus model leverages a unique hybrid approach by design to promote decentralized and secure network operations. In traditional Proof of Stake (PoS) systems, a node's ability to validate transactions is tied to its token holdings, which can lead to centralization risks and limited validator participation. Polkadot addresses these concerns through its [Nominated Proof of Stake (NPoS)](/reference/glossary/#nominated-proof-of-stake-npos){target=\\_blank} model and a combination of advanced consensus mechanisms to ensure efficient block production and strong finality guarantees. This combination enables the Polkadot network to scale while maintaining security and decentralization."} -{"page_id": "reference-polkadot-hub-consensus-and-security-pos-consensus", "page_title": "Proof of Stake Consensus", "index": 1, "depth": 2, "title": "Nominated Proof of Stake", "anchor": "nominated-proof-of-stake", "start_char": 761, "end_char": 1788, "estimated_token_count": 215, "token_estimator": "heuristic-v1", "text": "## Nominated Proof of Stake\n\nPolkadot uses Nominated Proof of Stake (NPoS) to select the validator set and secure the network. This model is designed to maximize decentralization and security by balancing the roles of [validators](https://wiki.polkadot.com/learn/learn-validator/){target=\\_blank} and [nominators](https://wiki.polkadot.com/learn/learn-nominator/){target=\\_blank}.\n\n- **Validators**: Play a key role in maintaining the network's integrity. They produce new blocks, validate parachain blocks, and ensure the finality of transactions across the relay chain.\n- **Nominators**: Support the network by selecting validators to back with their stake. This mechanism allows users who don't want to run a validator node to still participate in securing the network and earn rewards based on the validators they support.\n\nIn Polkadot's NPoS system, nominators can delegate their tokens to trusted validators, giving them voting power in selecting validators while spreading security responsibilities across the network."} -{"page_id": "reference-polkadot-hub-consensus-and-security-pos-consensus", "page_title": "Proof of Stake Consensus", "index": 2, "depth": 2, "title": "Hybrid Consensus", "anchor": "hybrid-consensus", "start_char": 1788, "end_char": 2840, "estimated_token_count": 193, "token_estimator": "heuristic-v1", "text": "## Hybrid Consensus\n\nPolkadot employs a hybrid consensus model that combines two key protocols: a finality gadget called [GRANDPA](#finality-gadget-grandpa) and a block production mechanism known as [BABE](#block-production-babe). This hybrid approach enables the network to benefit from both rapid block production and provable finality, ensuring security and performance.\n\nThe hybrid consensus model has some key advantages:\n\n- **Probabilistic finality**: With BABE constantly producing new blocks, Polkadot ensures that the network continues to make progress, even when a final decision has not yet been reached on which chain is the true canonical chain.\n\n- **Provable finality**: GRANDPA guarantees that once a block is finalized, it can never be reverted, ensuring that all network participants agree on the finalized chain.\n\nBy using separate protocols for block production and finality, Polkadot can achieve rapid block creation and strong guarantees of finality while avoiding the typical trade-offs seen in traditional consensus mechanisms."} -{"page_id": "reference-polkadot-hub-consensus-and-security-pos-consensus", "page_title": "Proof of Stake Consensus", "index": 3, "depth": 2, "title": "Block Production - BABE", "anchor": "block-production-babe", "start_char": 2840, "end_char": 4656, "estimated_token_count": 360, "token_estimator": "heuristic-v1", "text": "## Block Production - BABE\n\nBlind Assignment for Blockchain Extension (BABE) is Polkadot's block production mechanism, working with GRANDPA to ensure blocks are produced consistently across the network. As validators participate in BABE, they are assigned block production slots through a randomness-based lottery system. This helps determine which validator is responsible for producing a block at a given time. BABE shares similarities with [Ouroboros Praos](https://eprint.iacr.org/2017/573.pdf){target=\\_blank} but differs in key aspects like chain selection rules and slot timing.\n\nKey features of BABE include:\n\n- **Epochs and slots**: BABE operates in phases called epochs, each of which is divided into slots (around 6 seconds per slot). Validators are assigned slots at the beginning of each epoch based on stake and randomness.\n\n- **Randomized block production**: Validators enter a lottery to determine which will produce a block in a specific slot. This randomness is sourced from the relay chain's [randomness cycle](/reference/parachains/randomness/){target=\\_blank}.\n\n- **Multiple block producers per slot**: In some cases, more than one validator might win the lottery for the same slot, resulting in multiple blocks being produced. These blocks are broadcasted, and the network's fork choice rule helps decide which chain to follow.\n\n- **Handling empty slots**: If no validators win the lottery for a slot, a secondary selection algorithm ensures that a block is still produced. Validators selected through this method always produce a block, ensuring no slots are skipped.\n\nBABE's combination of randomness and slot allocation creates a secure, decentralized system for consistent block production while also allowing for fork resolution when multiple validators produce blocks for the same slot."} -{"page_id": "reference-polkadot-hub-consensus-and-security-pos-consensus", "page_title": "Proof of Stake Consensus", "index": 4, "depth": 3, "title": "Validator Participation", "anchor": "validator-participation", "start_char": 4656, "end_char": 6311, "estimated_token_count": 331, "token_estimator": "heuristic-v1", "text": "### Validator Participation\n\nIn BABE, validators participate in a lottery for every slot to determine whether they are responsible for producing a block during that slot. This process's randomness ensures a decentralized and unpredictable block production mechanism.\n\nThere are two lottery outcomes for any given slot that initiate additional processes:\n\n- **Multiple validators in a slot**: Due to the randomness, multiple validators can be selected to produce a block for the same slot. When this happens, each validator produces a block and broadcasts it to the network resulting in a race condition. The network's topology and latency then determine which block reaches the majority of nodes first. BABE allows both chains to continue building until the finalization process resolves which one becomes canonical. The [Fork Choice](#fork-choice) rule is then used to decide which chain the network should follow.\n\n- **No validators in a slot**: On occasions when no validator is selected by the lottery, a [secondary validator selection algorithm](https://spec.polkadot.network/sect-block-production#defn-babe-secondary-slots){target=\\_blank} steps in. This backup ensures that a block is still produced, preventing skipped slots. However, if the primary block produced by a verifiable random function [(VRF)-selected](/reference/parachains/randomness/#vrf){target=\\_blank} validator exists for that slot, the secondary block will be ignored. As a result, every slot will have either a primary or a secondary block.\n\nThis design ensures continuous block production, even in cases of multiple competing validators or an absence of selected validators."} -{"page_id": "reference-polkadot-hub-consensus-and-security-pos-consensus", "page_title": "Proof of Stake Consensus", "index": 5, "depth": 3, "title": "Additional Resources", "anchor": "additional-resources", "start_char": 6311, "end_char": 6806, "estimated_token_count": 111, "token_estimator": "heuristic-v1", "text": "### Additional Resources\n\nFor further technical insights about BABE, including cryptographic details and formal proofs, see the [BABE paper](https://research.web3.foundation/Polkadot/protocols/block-production/Babe){target=\\_blank} from Web3 Foundation.\n\nFor BABE technical definitions, constants, and formulas, see the [Block Production Lottery](https://spec.polkadot.network/sect-block-production#sect-block-production-lottery){target=\\_blank} section of the Polkadot Protocol Specification."} -{"page_id": "reference-polkadot-hub-consensus-and-security-pos-consensus", "page_title": "Proof of Stake Consensus", "index": 6, "depth": 2, "title": "Finality Gadget - GRANDPA", "anchor": "finality-gadget-grandpa", "start_char": 6806, "end_char": 8324, "estimated_token_count": 292, "token_estimator": "heuristic-v1", "text": "## Finality Gadget - GRANDPA\n\nGRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) serves as the finality gadget for Polkadot's relay chain. Operating alongside the BABE block production mechanism, it ensures provable finality, giving participants confidence that blocks finalized by GRANDPA cannot be reverted.\n\nKey features of GRANDPA include:\n\n- **Independent finality service**: GRANDPA runs separately from the block production process, operating in parallel to ensure seamless finalization.\n- **Chain-based finalization**: Instead of finalizing one block at a time, GRANDPA finalizes entire chains, speeding up the process significantly.\n- **Batch finalization**: Can finalize multiple blocks in a single round, enhancing efficiency and minimizing delays in the network.\n- **Partial synchrony tolerance**: GRANDPA works effectively in a partially synchronous network environment, managing both asynchronous and synchronous conditions.\n- **Byzantine fault tolerance**: Can handle up to 1/5 Byzantine (malicious) nodes, ensuring the system remains secure even when faced with adversarial behavior.\n\n??? note \"What is GHOST?\"\n [GHOST (Greedy Heaviest-Observed Subtree)](https://eprint.iacr.org/2018/104.pdf){target=\\blank} is a consensus protocol used in blockchain networks to select the heaviest branch in a block tree. Unlike traditional longest-chain rules, GHOST can more efficiently handle high block production rates by considering the weight of subtrees rather than just the chain length."} -{"page_id": "reference-polkadot-hub-consensus-and-security-pos-consensus", "page_title": "Proof of Stake Consensus", "index": 7, "depth": 3, "title": "Probabilistic vs. Provable Finality", "anchor": "probabilistic-vs-provable-finality", "start_char": 8324, "end_char": 9130, "estimated_token_count": 142, "token_estimator": "heuristic-v1", "text": "### Probabilistic vs. Provable Finality\n\nIn traditional Proof of Work (PoW) blockchains, finality is probabilistic. As blocks are added to the chain, the probability that a block is final increases, but it can never be guaranteed. Eventual consensus means that all nodes will agree on a single version of the blockchain over time, but this process can be unpredictable and slow.\n\nConversely, GRANDPA provides provable finality, which means that once a block is finalized, it is irreversible. By using Byzantine fault-tolerant agreements, GRANDPA finalizes blocks more efficiently and securely than probabilistic mechanisms like Nakamoto consensus. Like Ethereum's Casper the Friendly Finality Gadget (FFG), GRANDPA ensures that finalized blocks cannot be reverted, offering stronger consensus guarantees."} -{"page_id": "reference-polkadot-hub-consensus-and-security-pos-consensus", "page_title": "Proof of Stake Consensus", "index": 8, "depth": 3, "title": "Additional Resources", "anchor": "additional-resources-2", "start_char": 9130, "end_char": 9678, "estimated_token_count": 144, "token_estimator": "heuristic-v1", "text": "### Additional Resources\n\nFor technical insights, including formal proofs and detailed algorithms, see the [GRANDPA paper](https://github.com/w3f/consensus/blob/master/pdf/grandpa.pdf){target=\\_blank} from Web3 Foundation.\n\nFor a deeper look at the code behind GRANDPA, see the following GitHub repositories:\n\n- [GRANDPA Rust implementation](https://github.com/paritytech/finality-grandpa){target=\\_blank}\n- [GRANDPA Pallet](https://github.com/paritytech/polkadot-sdk/blob/polkadot-stable2506-2/substrate/frame/grandpa/src/lib.rs){target=\\_blank}"} -{"page_id": "reference-polkadot-hub-consensus-and-security-pos-consensus", "page_title": "Proof of Stake Consensus", "index": 9, "depth": 2, "title": "Fork Choice", "anchor": "fork-choice", "start_char": 9678, "end_char": 10520, "estimated_token_count": 176, "token_estimator": "heuristic-v1", "text": "## Fork Choice\n\nThe fork choice of the relay chain combines BABE and GRANDPA:\n\n1. BABE must always build on the chain that GRANDPA has finalized.\n2. When there are forks after the finalized head, BABE builds on the chain with the most primary blocks to provide probabilistic finality.\n\n![Fork choice diagram](/images/reference/polkadot-hub/consensus-and-security/pos-consensus/consensus-protocols-01.webp)\n\nIn the preceding diagram, finalized blocks are black, and non-finalized blocks are yellow. Primary blocks are labeled '1', and secondary blocks are labeled '2.' The topmost chain is the longest chain originating from the last finalized block, but it is not selected because it only has one primary block at the time of evaluation. In comparison, the one below it originates from the last finalized block and has three primary blocks."} -{"page_id": "reference-polkadot-hub-consensus-and-security-pos-consensus", "page_title": "Proof of Stake Consensus", "index": 10, "depth": 3, "title": "Additional Resources", "anchor": "additional-resources-3", "start_char": 10520, "end_char": 11107, "estimated_token_count": 131, "token_estimator": "heuristic-v1", "text": "### Additional Resources\n\nTo learn more about how BABE and GRANDPA work together to produce and finalize blocks on Kusama, see this [Block Production and Finalization in Polkadot](https://youtu.be/FiEAnVECa8c){target=\\_blank} talk from Web3 Foundation's Bill Laboon. \n\nFor an in-depth academic discussion about Polkadot's hybrid consensus model, see this [Block Production and Finalization in Polkadot: Understanding the BABE and GRANDPA Protocols](https://www.youtube.com/watch?v=1CuTSluL7v4&t=4s){target=\\_blank} MIT Cryptoeconomic Systems 2020 talk by Web3 Foundation's Bill Laboon."} -{"page_id": "reference-polkadot-hub-consensus-and-security-pos-consensus", "page_title": "Proof of Stake Consensus", "index": 11, "depth": 2, "title": "Bridging - BEEFY", "anchor": "bridging-beefy", "start_char": 11107, "end_char": 12509, "estimated_token_count": 241, "token_estimator": "heuristic-v1", "text": "## Bridging - BEEFY\n\nBridge Efficiency Enabling Finality Yielder (BEEFY) is a specialized protocol that extends the finality guarantees provided by GRANDPA. It is specifically designed to facilitate efficient bridging between Polkadot relay chains (such as Polkadot and Kusama) and external blockchains like Ethereum. While GRANDPA is well-suited for finalizing blocks within Polkadot, it has limitations when bridging external chains that weren't built with Polkadot's interoperability features in mind. BEEFY addresses these limitations by ensuring other networks can efficiently verify finality proofs.\n\nKey features of BEEFY include:\n\n- **Efficient finality proof verification**: BEEFY enables external networks to easily verify Polkadot finality proofs, ensuring seamless communication between chains.\n- **Merkle Mountain Ranges (MMR)**: This data structure is used to efficiently store and transmit proofs between chains, optimizing data storage and reducing transmission overhead.\n- **ECDSA signature schemes**: BEEFY uses ECDSA signatures, which are widely supported on Ethereum and other EVM-based chains, making integration with these ecosystems smoother.\n- **Light client optimization**: BEEFY reduces the computational burden on light clients by allowing them to check for a super-majority of validator votes rather than needing to process all validator signatures, improving performance."} -{"page_id": "reference-polkadot-hub-consensus-and-security-pos-consensus", "page_title": "Proof of Stake Consensus", "index": 12, "depth": 3, "title": "Additional Resources", "anchor": "additional-resources-4", "start_char": 12509, "end_char": 12753, "estimated_token_count": 58, "token_estimator": "heuristic-v1", "text": "### Additional Resources\n\nFor BEEFY technical definitions, constants, and formulas, see the [Bridge design (BEEFY)](https://spec.polkadot.network/sect-finality#sect-grandpa-beefy){target=\\_blank} section of the Polkadot Protocol Specification."} -{"page_id": "reference-polkadot-hub-consensus-and-security-relay-chain", "page_title": "Overview of the Polkadot Relay Chain", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 12, "end_char": 876, "estimated_token_count": 184, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nPolkadot is a next-generation blockchain protocol designed to support a multi-chain future by enabling secure communication and interoperability between different blockchains. Built as a Layer-0 protocol, Polkadot introduces innovations like application-specific Layer-1 chains ([parachains](/polkadot-protocol/architecture/parachains/){targe=\\_blank}), shared security through [Nominated Proof of Stake (NPoS)](/reference/glossary/#nominated-proof-of-stake-npos){target=\\_blank}, and cross-chain interactions via its native [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\\_blank}.\n\nThis guide covers key aspects of Polkadot’s architecture, including its high-level protocol structure, blockspace commoditization, and the role of its native token, DOT, in governance, staking, and resource allocation."} -{"page_id": "reference-polkadot-hub-consensus-and-security-relay-chain", "page_title": "Overview of the Polkadot Relay Chain", "index": 1, "depth": 2, "title": "Polkadot 1.0", "anchor": "polkadot-10", "start_char": 876, "end_char": 2903, "estimated_token_count": 458, "token_estimator": "heuristic-v1", "text": "## Polkadot 1.0\n\nPolkadot 1.0 represents the state of Polkadot as of 2023, coinciding with the release of [Polkadot runtime v1.0.0](https://github.com/paritytech/polkadot/releases/tag/v1.0.0){target=\\_blank}. This section will focus on Polkadot 1.0, along with philosophical insights into network resilience and blockspace.\n\nAs a Layer-0 blockchain, Polkadot contributes to the multi-chain vision through several key innovations and initiatives, including:\n\n- **Application-specific Layer-1 blockchains (parachains)**: Polkadot's sharded network allows for parallel transaction processing, with shards that can have unique state transition functions, enabling custom-built L1 chains optimized for specific applications.\n\n- **Shared security and scalability**: L1 chains connected to Polkadot benefit from its [Nominated Proof of Stake (NPoS)](/reference/polkadot-hub/consensus-and-security/pos-consensus/#nominated-proof-of-stake){target=\\_blank} system, providing security out-of-the-box without the need to bootstrap their own.\n\n- **Secure interoperability**: Polkadot's native interoperability enables seamless data and value exchange between parachains. This interoperability can also be used outside of the ecosystem for bridging with external networks.\n\n- **Resilient infrastructure**: Decentralized and scalable, Polkadot ensures ongoing support for development and community initiatives via its on-chain [treasury](https://wiki.polkadot.com/learn/learn-polkadot-opengov-treasury/){target=\\_blank} and governance.\n\n- **Rapid L1 development**: The [Polkadot SDK](/reference/parachains/){target=\\_blank} allows fast, flexible creation and deployment of Layer-1 chains.\n\n- **Cultivating the next generation of Web3 developers**: Polkadot supports the growth of Web3 core developers through initiatives such as.\n\n - [Polkadot Blockchain Academy](https://polkadot.com/blockchain-academy){target=\\_blank}\n - [EdX courses](https://www.edx.org/school/web3x){target=\\_blank}\n - Rust and Substrate courses (coming soon)"} -{"page_id": "reference-polkadot-hub-consensus-and-security-relay-chain", "page_title": "Overview of the Polkadot Relay Chain", "index": 2, "depth": 3, "title": "High-Level Architecture", "anchor": "high-level-architecture", "start_char": 2903, "end_char": 4245, "estimated_token_count": 279, "token_estimator": "heuristic-v1", "text": "### High-Level Architecture\n\nPolkadot features a chain that serves as the central component of the system. This chain is depicted as a ring encircled by several parachains that are connected to it.\n\nAccording to Polkadot's design, any blockchain that can compile to WebAssembly (Wasm) and adheres to the Parachains Protocol becomes a parachain on the Polkadot network.\n\nHere’s a high-level overview of the Polkadot protocol architecture:\n\n![](/images/reference/polkadot-hub/consensus-and-security/relay-chain/relay-chain-01.webp){ style=\"background:white\" }\n\nParachains propose blocks to Polkadot validators, who check for availability and validity before finalizing them. With the relay chain providing security, collators—full nodes of parachains—can focus on their tasks without needing strong incentives.\n\nThe [Cross-Consensus Messaging Format (XCM)](/parachains/interoperability/get-started/){target=\\_blank} allows parachains to exchange messages freely, leveraging the chain's security for trust-free communication.\n\nIn order to interact with chains that want to use their own finalization process (e.g., Bitcoin), Polkadot has [bridges](/reference/parachains/interoperability/#bridges-connecting-external-networks){target=\\_blank} that offer two-way compatibility, meaning that transactions can be made between different parachains."} -{"page_id": "reference-polkadot-hub-consensus-and-security-relay-chain", "page_title": "Overview of the Polkadot Relay Chain", "index": 3, "depth": 3, "title": "Polkadot's Additional Functionalities", "anchor": "polkadots-additional-functionalities", "start_char": 4245, "end_char": 6180, "estimated_token_count": 422, "token_estimator": "heuristic-v1", "text": "### Polkadot's Additional Functionalities\n\nHistorically, obtaining core slots on Polkadot chain relied upon crowdloans and auctions. Chain cores were leased through auctions for three-month periods, up to a maximum of two years. Crowdloans enabled users to securely lend funds to teams for lease deposits in exchange for pre-sale tokens, which is the only way to access slots on Polkadot 1.0. Auctions are now deprecated in favor of [coretime](/polkadot-protocol/architecture/system-chains/coretime/){target=\\_blank}.\n\nAdditionally, the chain handles [staking](https://wiki.polkadot.com/learn/learn-staking/){target=\\_blank}, [accounts](/reference/parachains/accounts/){target=\\_blank}, balances, and [governance](/reference/governance/){target=\\_blank}.\n\n#### Agile Coretime\n\nThe new and more efficient way of obtaining core on Polkadot is to go through the process of purchasing coretime.\n\n[Agile coretime](/reference/polkadot-hub/consensus-and-security/agile-coretime/){target=\\_blank} improves the efficient use of Polkadot's network resources and offers economic flexibility for developers, extending Polkadot's capabilities far beyond the original vision outlined in the [whitepaper](https://polkadot.com/papers/Polkadot-whitepaper.pdf){target=\\_blank}.\n\nIt enables parachains to purchase monthly \"bulk\" allocations of coretime (the time allocated for utilizing a core, measured in Polkadot relay chain blocks), ensuring heavy-duty parachains that can author a block every six seconds with [Asynchronous Backing](https://wiki.polkadot.com/learn/learn-async-backing/#asynchronous-backing){target=\\_blank} can reliably renew their coretime each month. Although six-second block times are now the default, parachains have the option of producing blocks less frequently.\n\nRenewal orders are prioritized over new orders, offering stability against price fluctuations and helping parachains budget more effectively for project costs."} -{"page_id": "reference-polkadot-hub-consensus-and-security-relay-chain", "page_title": "Overview of the Polkadot Relay Chain", "index": 4, "depth": 3, "title": "Polkadot's Resilience", "anchor": "polkadots-resilience", "start_char": 6180, "end_char": 7464, "estimated_token_count": 253, "token_estimator": "heuristic-v1", "text": "### Polkadot's Resilience\n\nDecentralization is a vital component of blockchain networks, but it comes with trade-offs:\n\n- An overly decentralized network may face challenges in reaching consensus and require significant energy to operate.\n- Also, a network that achieves consensus quickly risks centralization, making it easier to manipulate or attack.\n\nA network should be decentralized enough to prevent manipulative or malicious influence. In this sense, decentralization is a tool for achieving resilience.\n\nPolkadot 1.0 currently achieves resilience through several strategies:\n\n- **Nominated Proof of Stake (NPoS)**: Ensures that the stake per validator is maximized and evenly distributed among validators.\n\n- **Decentralized nodes**: Designed to encourage operators to join the network. This program aims to expand and diversify the validators in the ecosystem who aim to become independent of the program during their term. Feel free to explore more about the program on the official [Decentralized Nodes](https://nodes.web3.foundation/){target=\\_blank} page.\n\n- **On-chain treasury and governance**: Known as [OpenGov](/reference/governance/){target=\\_blank}, this system allows every decision to be made through public referenda, enabling any token holder to cast a vote."} -{"page_id": "reference-polkadot-hub-consensus-and-security-relay-chain", "page_title": "Overview of the Polkadot Relay Chain", "index": 5, "depth": 3, "title": "Polkadot's Blockspace", "anchor": "polkadots-blockspace", "start_char": 7464, "end_char": 9276, "estimated_token_count": 363, "token_estimator": "heuristic-v1", "text": "### Polkadot's Blockspace\n\nPolkadot 1.0’s design allows for the commoditization of blockspace.\n\nBlockspace is a blockchain's capacity to finalize and commit operations, encompassing its security, computing, and storage capabilities. Its characteristics can vary across different blockchains, affecting security, flexibility, and availability.\n\n- **Security**: Measures the robustness of blockspace in Proof of Stake (PoS) networks linked to the stake locked on validator nodes, the variance in stake among validators, and the total number of validators. It also considers social centralization (how many validators are owned by single operators) and physical centralization (how many validators run on the same service provider).\n\n- **Flexibility**: Reflects the functionalities and types of data that can be stored, with high-quality data essential to avoid bottlenecks in critical processes.\n\n- **Availability**: Indicates how easily users can access blockspace. It should be easily accessible, allowing diverse business models to thrive, ideally regulated by a marketplace based on demand and supplemented by options for \"second-hand\" blockspace.\n\nPolkadot is built on core blockspace principles, but there's room for improvement. Tasks like balance transfers, staking, and governance are managed on the relay chain.\n\nDelegating these responsibilities to [system chains](/polkadot-protocol/architecture/system-chains/){target=\\_blank} could enhance flexibility and allow the relay chain to concentrate on providing shared security and interoperability.\n\nFor more information about blockspace, watch [Robert Habermeier’s interview](https://www.youtube.com/watch?v=e1vISppPwe4){target=\\_blank} or read his [technical blog post](https://www.rob.tech/blog/polkadot-blockspace-over-blockchains/){target=\\_blank}."} -{"page_id": "reference-polkadot-hub-consensus-and-security-relay-chain", "page_title": "Overview of the Polkadot Relay Chain", "index": 6, "depth": 2, "title": "DOT Token", "anchor": "dot-token", "start_char": 9276, "end_char": 9569, "estimated_token_count": 65, "token_estimator": "heuristic-v1", "text": "## DOT Token\n\nDOT is the native token of the Polkadot network, much like BTC for Bitcoin and Ether for the Ethereum blockchain. DOT has 10 decimals, uses the Planck base unit, and has a balance type of `u128`. The same is true for Kusama's KSM token with the exception of having 12 decimals."} -{"page_id": "reference-polkadot-hub-consensus-and-security-relay-chain", "page_title": "Overview of the Polkadot Relay Chain", "index": 7, "depth": 3, "title": "Redenomination of DOT", "anchor": "redenomination-of-dot", "start_char": 9569, "end_char": 10121, "estimated_token_count": 112, "token_estimator": "heuristic-v1", "text": "### Redenomination of DOT\n \nPolkadot conducted a community poll, which ended on 27 July 2020 at block 888,888, to decide whether to redenominate the DOT token. The stakeholders chose to redenominate the token, changing the value of 1 DOT from 1e12 plancks to 1e10 plancks.\n\nImportantly, this did not affect the network's total number of base units (plancks); it only affects how a single DOT is represented. The redenomination became effective 72 hours after transfers were enabled, occurring at block 1,248,328 on 21 August 2020 around 16:50 UTC."} -{"page_id": "reference-polkadot-hub-consensus-and-security-relay-chain", "page_title": "Overview of the Polkadot Relay Chain", "index": 8, "depth": 3, "title": "The Planck Unit", "anchor": "the-planck-unit", "start_char": 10121, "end_char": 10527, "estimated_token_count": 84, "token_estimator": "heuristic-v1", "text": "### The Planck Unit\n\nThe smallest unit of account balance on Polkadot SDK-based blockchains (such as Polkadot and Kusama) is called _Planck_, named after the Planck length, the smallest measurable distance in the physical universe.\n\nSimilar to how BTC's smallest unit is the Satoshi and ETH's is the Wei, Polkadot's native token DOT equals 1e10 Planck, while Kusama's native token KSM equals 1e12 Planck."} -{"page_id": "reference-polkadot-hub-consensus-and-security-relay-chain", "page_title": "Overview of the Polkadot Relay Chain", "index": 9, "depth": 3, "title": "Uses for DOT", "anchor": "uses-for-dot", "start_char": 10527, "end_char": 11094, "estimated_token_count": 121, "token_estimator": "heuristic-v1", "text": "### Uses for DOT\n\nDOT serves three primary functions within the Polkadot network:\n\n- **Governance**: It is used to participate in the governance of the network.\n- **Staking**: DOT is staked to support the network's operation and security.\n- **Buying coretime**: Used to purchase coretime in-bulk or on-demand and access the chain to benefit from Polkadot's security and interoperability.\n\nAdditionally, DOT can serve as a transferable token. For example, DOT, held in the treasury, can be allocated to teams developing projects that benefit the Polkadot ecosystem."} -{"page_id": "reference-polkadot-hub-consensus-and-security-relay-chain", "page_title": "Overview of the Polkadot Relay Chain", "index": 10, "depth": 2, "title": "JAM and the Road Ahead", "anchor": "jam-and-the-road-ahead", "start_char": 11094, "end_char": 12458, "estimated_token_count": 239, "token_estimator": "heuristic-v1", "text": "## JAM and the Road Ahead\n\nThe Join-Accumulate Machine (JAM) represents a transformative redesign of Polkadot's core architecture, envisioned as the successor to the current relay chain. Unlike traditional blockchain architectures, JAM introduces a unique computational model that processes work through two primary functions:\n\n- **Join**: Handles data integration.\n- **Accumulate**: Folds computations into the chain's state.\n\nJAM removes many of the opinions and constraints of the current relay chain while maintaining its core security properties. Expected improvements include:\n\n- **Permissionless code execution**: JAM is designed to be more generic and flexible, allowing for permissionless code execution through services that can be deployed without governance approval.\n- **More effective block time utilization**: JAM's efficient pipeline processing model places the prior state root in block headers instead of the posterior state root, enabling more effective utilization of block time for computations.\n\nThis architectural evolution promises to enhance Polkadot's scalability and flexibility while maintaining robust security guarantees. JAM is planned to be rolled out to Polkadot as a single, complete upgrade rather than a stream of smaller updates. This approach seeks to minimize the developer overhead required to address any breaking changes."} -{"page_id": "reference-polkadot-hub-people-and-identity", "page_title": "People Chain", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 16, "end_char": 504, "estimated_token_count": 70, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nPeople chain is a specialized parachain within the Polkadot ecosystem dedicated to secure, decentralized identity management. \n\nThis solution empowers users to create, control, and verify their digital identities without reliance on centralized authorities. By prioritizing user sovereignty and data privacy, People chain establishes a foundation for trusted interactions throughout the Polkadot ecosystem while returning control of personal information to individuals."} -{"page_id": "reference-polkadot-hub-people-and-identity", "page_title": "People Chain", "index": 1, "depth": 2, "title": "Identity Management System", "anchor": "identity-management-system", "start_char": 504, "end_char": 953, "estimated_token_count": 77, "token_estimator": "heuristic-v1", "text": "## Identity Management System\n\nPeople chain provides a comprehensive identity framework allowing users to:\n\n- Establish verifiable on-chain identities.\n- Control disclosure of personal information.\n- Receive verification from trusted registrars.\n- Link multiple accounts under a unified identity.\n\nUsers must reserve funds in a bond to store their information on chain. These funds are locked, not spent, and returned when the identity is cleared."} -{"page_id": "reference-polkadot-hub-people-and-identity", "page_title": "People Chain", "index": 2, "depth": 3, "title": "Sub-Identities", "anchor": "sub-identities", "start_char": 953, "end_char": 1224, "estimated_token_count": 52, "token_estimator": "heuristic-v1", "text": "### Sub-Identities\n\nThe platform supports hierarchical identity structures through sub-accounts:\n\n- Primary accounts can establish up to 100 linked sub-accounts.\n- Each sub-account maintains its own distinct identity.\n- All sub-accounts require a separate bond deposit."} -{"page_id": "reference-polkadot-hub-people-and-identity", "page_title": "People Chain", "index": 3, "depth": 2, "title": "Verification Process", "anchor": "verification-process", "start_char": 1224, "end_char": 1249, "estimated_token_count": 4, "token_estimator": "heuristic-v1", "text": "## Verification Process"} -{"page_id": "reference-polkadot-hub-people-and-identity", "page_title": "People Chain", "index": 4, "depth": 3, "title": "Judgment Requests", "anchor": "judgment-requests", "start_char": 1249, "end_char": 1598, "estimated_token_count": 68, "token_estimator": "heuristic-v1", "text": "### Judgment Requests\n\nAfter establishing an on-chain identity, users can request verification from [registrars](#registrars):\n\n1. Users specify the maximum fee they're willing to pay for judgment.\n2. Only registrars whose fees fall below this threshold can provide verification.\n3. Registrars assess the provided information and issue a judgment."} -{"page_id": "reference-polkadot-hub-people-and-identity", "page_title": "People Chain", "index": 5, "depth": 3, "title": "Judgment Classifications", "anchor": "judgment-classifications", "start_char": 1598, "end_char": 2385, "estimated_token_count": 150, "token_estimator": "heuristic-v1", "text": "### Judgment Classifications\n\nRegistrars can assign the following confidence levels to identity information:\n\n- **Unknown**: Default status; no judgment rendered yet.\n- **Reasonable**: Data appears valid but without formal verification (standard for most verified identities).\n- **Known good**: Information certified correct through formal verification (requires documentation; limited to registrars).\n- **Out of date**: Previously verified information that requires updating.\n- **Low quality**: Imprecise information requiring correction.\n- **Erroneous**: Incorrect information, potentially indicating fraudulent intent.\n\nA temporary \"Fee Paid\" status indicates judgment in progress. Both \"Fee Paid\" and \"Erroneous\" statuses lock identity information from modification until resolved."} -{"page_id": "reference-polkadot-hub-people-and-identity", "page_title": "People Chain", "index": 6, "depth": 3, "title": "Registrars", "anchor": "registrars", "start_char": 2385, "end_char": 3680, "estimated_token_count": 198, "token_estimator": "heuristic-v1", "text": "### Registrars\n\nRegistrars serve as trusted verification authorities within the People chain ecosystem. These entities validate user identities and provide attestations that build trust in the network.\n\n- Registrars set specific fees for their verification services.\n- They can specialize in verifying particular identity fields.\n- Verification costs vary based on complexity and thoroughness.\n\nWhen requesting verification, users specify their maximum acceptable fee. Only registrars whose fees fall below this threshold can provide judgment. Upon completing the verification process, the user pays the registrar's fee, and the registrar issues an appropriate confidence level classification based on their assessment.\n\nMultiple registrars operate across the Polkadot and People chain ecosystems, each with unique specializations and fee structures. To request verification:\n\n1. Research available registrars and their verification requirements.\n2. Contact your chosen registrar directly through their specified channels.\n3. Submit required documentation according to their verification process.\n4. Pay the associated verification fee.\n\nYou must contact specific registrars individually to request judgment. Each registrar maintains its own verification procedures and communication channels."} -{"page_id": "reference-polkadot-hub-people-and-identity", "page_title": "People Chain", "index": 7, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 3680, "end_char": 4750, "estimated_token_count": 257, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\n
\n\n- External __Polkadot.js Guides about Identity__\n\n ---\n\n Step-by-step instructions for managing identities through the Polkadot.js interface, with practical examples and visual guides.\n\n [:octicons-arrow-right-24: Reference](https://wiki.polkadot.com/learn/learn-guides-identity/)\n\n- External __How to Set and Clear an Identity__\n\n ---\n\n Practical walkthrough covering identity setup and removal process on People chain.\n\n [:octicons-arrow-right-24: Reference](https://support.polkadot.network/support/solutions/articles/65000181981-how-to-set-and-clear-an-identity)\n\n- External __People Chain Runtime Implementation__\n\n ---\n\n Source code for the People chain runtime, detailing the technical architecture of decentralized identity management.\n\n [:octicons-arrow-right-24: Reference](https://github.com/polkadot-fellows/runtimes/tree/main/system-parachains/people)\n\n
"} -{"page_id": "reference-tools-dedot", "page_title": "Dedot", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 9, "end_char": 445, "estimated_token_count": 99, "token_estimator": "heuristic-v1", "text": "## Introduction\n\n[Dedot](https://github.com/dedotdev/dedot){target=\\_blank} is a next-generation JavaScript client for Polkadot and Polkadot SDK-based blockchains. Designed to elevate the dApp development experience, Dedot is built and optimized to be lightweight and tree-shakable, offering precise types and APIs suggestions for individual Polkadot SDK-based blockchains and [ink! smart contracts](https://use.ink/){target=\\_blank}."} -{"page_id": "reference-tools-dedot", "page_title": "Dedot", "index": 1, "depth": 3, "title": "Key Features", "anchor": "key-features", "start_char": 445, "end_char": 1529, "estimated_token_count": 298, "token_estimator": "heuristic-v1", "text": "### Key Features\n\n- **Lightweight and tree-shakable**: No more bn.js or WebAssembly blobs, optimized for dapps bundle size.\n- **Fully typed API**: Comprehensive TypeScript support for seamless on-chain interaction and ink! smart contract integration.\n- **Multi-version JSON-RPC support**: Compatible with both [legacy](https://github.com/w3f/PSPs/blob/master/PSPs/drafts/psp-6.md){target=\\_blank} and [new](https://paritytech.github.io/json-rpc-interface-spec/introduction.html){target=\\_blank} JSON-RPC APIs for broad ecosystem interoperability.\n- **Light client support**: Designed to work with light clients such as [Smoldot](https://github.com/smol-dot/smoldot){target=\\_blank}.\n- **Native TypeScript for scale codec**: Implements scale codec parsing directly in TypeScript without relying on custom wrappers.\n- **Wallet integration**: Works out-of-the-box with [@polkadot/extension-based](https://github.com/polkadot-js/extension?tab=readme-ov-file#api-interface){target=\\_blank} wallets.\n- **Familiar API design**: Similar API style to Polkadot.js for easy and fast migration."} -{"page_id": "reference-tools-dedot", "page_title": "Dedot", "index": 2, "depth": 2, "title": "Installation", "anchor": "installation", "start_char": 1529, "end_char": 2152, "estimated_token_count": 177, "token_estimator": "heuristic-v1", "text": "## Installation\n\nTo add Dedot to your project, use the following command:\n\n=== \"npm\"\n\n ```bash\n npm i dedot\n ```\n\n=== \"pnpm\"\n\n ```bash\n pnpm add dedot\n ```\n\n=== \"yarn\"\n\n ```bash\n yarn add dedot\n ```\n\nTo enable auto-completion/IntelliSense for individual chains, install the [`@dedot/chaintypes`](https://www.npmjs.com/package/@dedot/chaintypes){target=\\_blank} package as a development dependency:\n\n=== \"npm\"\n\n ```bash\n npm i -D @dedot/chaintypes\n ```\n\n=== \"pnpm\"\n\n ```bash\n pnpm add -D @dedot/chaintypes\n ```\n\n=== \"yarn\"\n\n ```bash\n yarn add -D @dedot/chaintypes\n ```"} -{"page_id": "reference-tools-dedot", "page_title": "Dedot", "index": 3, "depth": 2, "title": "Get Started", "anchor": "get-started", "start_char": 2152, "end_char": 2168, "estimated_token_count": 4, "token_estimator": "heuristic-v1", "text": "## Get Started"} -{"page_id": "reference-tools-dedot", "page_title": "Dedot", "index": 4, "depth": 3, "title": "Initialize a Client Instance", "anchor": "initialize-a-client-instance", "start_char": 2168, "end_char": 4242, "estimated_token_count": 522, "token_estimator": "heuristic-v1", "text": "### Initialize a Client Instance\n\nTo connect to and interact with different networks, Dedot provides two client options depending on your needs:\n\n- **[`DedotClient`](https://docs.dedot.dev/clients-and-providers/clients#dedotclient){target=\\_blank}**: Interacts with chains via the [new JSON-RPC APIs](https://paritytech.github.io/json-rpc-interface-spec/introduction.html){target=\\_blank}.\n- **[`LegacyClient`](https://docs.dedot.dev/clients-and-providers/clients#legacyclient){target=\\_blank}**: Interacts with chains via the [legacy JSON-RPC APIs](https://github.com/w3f/PSPs/blob/master/PSPs/drafts/psp-6.md){target=\\_blank}.\n\nUse the following snippets to connect to Polkadot using `DedotClient`:\n\n=== \"WebSocket\"\n\n ```typescript\n import { DedotClient, WsProvider } from 'dedot';\n import type { PolkadotApi } from '@dedot/chaintypes';\n\n // Initialize providers & clients\n const provider = new WsProvider('wss://rpc.polkadot.io');\n const client = await DedotClient.new(provider);\n\n ```\n\n=== \"Light Client (Smoldot)\"\n\n ```typescript\n import { DedotClient, SmoldotProvider } from 'dedot';\n import type { PolkadotApi } from '@dedot/chaintypes';\n import * as smoldot from 'smoldot';\n\n // import `polkadot` chain spec to connect to Polkadot\n import { polkadot } from '@substrate/connect-known-chains';\n\n // Start smoldot instance & initialize a chain\n const client = smoldot.start();\n const chain = await client.addChain({ chainSpec: polkadot });\n\n // Initialize providers & clients\n const provider = new SmoldotProvider(chain);\n const client = await DedotClient.new(provider);\n\n ```\n\nIf the node doesn't support new JSON-RPC APIs yet, you can connect to the network using the `LegacyClient`, which is built on top of the legacy JSON-RPC APIs.\n\n```typescript\nimport { LegacyClient, WsProvider } from 'dedot';\nimport type { PolkadotApi } from '@dedot/chaintypes';\n\nconst provider = new WsProvider('wss://rpc.polkadot.io');\nconst client = await LegacyClient.new(provider);\n\n```"} -{"page_id": "reference-tools-dedot", "page_title": "Dedot", "index": 5, "depth": 3, "title": "Enable Type and API Suggestions", "anchor": "enable-type-and-api-suggestions", "start_char": 4242, "end_char": 5662, "estimated_token_count": 377, "token_estimator": "heuristic-v1", "text": "### Enable Type and API Suggestions\n\nIt is recommended to specify the `ChainApi` interface (e.g., `PolkadotApi` in the example in the previous section) of the chain you want to interact with. This enables type and API suggestions/autocompletion for that particular chain (via IntelliSense). If you don't specify a `ChainApi` interface, a default `SubstrateApi` interface will be used.\n\n```typescript\nimport { DedotClient, WsProvider } from 'dedot';\nimport type { PolkadotApi, KusamaApi } from '@dedot/chaintypes';\n\nconst polkadotClient = await DedotClient.new(\n new WsProvider('wss://rpc.polkadot.io')\n);\nconst kusamaClient = await DedotClient.new(\n new WsProvider('wss://kusama-rpc.polkadot.io')\n);\nconst genericClient = await DedotClient.new(\n new WsProvider('ws://localhost:9944')\n);\n\n```\n\nIf you don't find the `ChainApi` for the network you're working with in [the list](https://github.com/dedotdev/chaintypes?tab=readme-ov-file#supported-networks){target=\\_blank}, you can generate the `ChainApi` (types and APIs) using the built-in [`dedot` cli](https://docs.dedot.dev/cli){target=\\_blank}.\n\n```bash\n# Generate ChainApi interface for Polkadot network via rpc endpoint: wss://rpc.polkadot.io\nnpx dedot chaintypes -w wss://rpc.polkadot.io\n```\n\nOr open a pull request to add your favorite network to the [`@dedot/chaintypes`](https://github.com/dedotdev/chaintypes){target=\\_blank} repo."} -{"page_id": "reference-tools-dedot", "page_title": "Dedot", "index": 6, "depth": 3, "title": "Read On-Chain Data", "anchor": "read-on-chain-data", "start_char": 5662, "end_char": 6993, "estimated_token_count": 348, "token_estimator": "heuristic-v1", "text": "### Read On-Chain Data\n\nDedot provides several ways to read data from the chain:\n\n- **Access runtime constants**: Use the syntax `client.consts..` to inspect runtime constants (parameter types).\n\n ```typescript\n const ss58Prefix = client.consts.system.ss58Prefix;\n console.log('Polkadot ss58Prefix:', ss58Prefix);\n\n ```\n\n- **Storage queries**: Use the syntax `client.query..` to query on-chain storage.\n\n ```typescript\n const balance = await client.query.system.account('INSERT_ADDRESS');\n console.log('Balance:', balance.data.free);\n\n ```\n\n- **Subscribe to storage changes**:\n\n ```typescript\n const unsub = await client.query.system.number((blockNumber) => {\n console.log(`Current block number: ${blockNumber}`);\n });\n\n ```\n\n- **Call Runtime APIs**: Use the syntax `client.call..` to execute Runtime APIs.\n\n ```typescript\n const metadata = await client.call.metadata.metadataAtVersion(15);\n console.log('Metadata V15', metadata);\n\n ```\n\n- **Watch on-chain events**: Use the syntax `client.events..` to access pallet events.\n \n ```typescript\n const unsub = await client.events.system.NewAccount.watch((events) => {\n console.log('New Account Created', events);\n });\n\n ```"} -{"page_id": "reference-tools-dedot", "page_title": "Dedot", "index": 7, "depth": 3, "title": "Sign and Send Transactions", "anchor": "sign-and-send-transactions", "start_char": 6993, "end_char": 8719, "estimated_token_count": 439, "token_estimator": "heuristic-v1", "text": "### Sign and Send Transactions\n\nSign the transaction using `IKeyringPair` from Keyring ([`@polkadot/keyring`](https://polkadot.js.org/docs/keyring/start/sign-verify/){target=\\_blank}) and send the transaction.\n\n```typescript\nimport { cryptoWaitReady } from '@polkadot/util-crypto';\nimport { Keyring } from '@polkadot/keyring';\n// Setup keyring\nawait cryptoWaitReady();\nconst keyring = new Keyring({ type: 'sr25519' });\nconst alice = keyring.addFromUri('//Alice');\n// Send transaction\nconst unsub = await client.tx.balances\n .transferKeepAlive('INSERT_DEST_ADDRESS', 2_000_000_000_000n)\n .signAndSend(alice, async ({ status }) => {\n console.log('Transaction status', status.type);\n if (status.type === 'BestChainBlockIncluded') {\n console.log(`Transaction is included in best block`);\n }\n if (status.type === 'Finalized') {\n console.log(\n `Transaction completed at block hash ${status.value.blockHash}`\n );\n await unsub();\n }\n });\n\n```\n\nYou can also use `Signer` from wallet extensions:\n\n```typescript\nconst injected = await window.injectedWeb3['polkadot-js'].enable('My dApp');\nconst account = (await injected.accounts.get())[0];\nconst signer = injected.signer;\nconst unsub = await client.tx.balances\n .transferKeepAlive('INSERT_DEST_ADDRESS', 2_000_000_000_000n)\n .signAndSend(account.address, { signer }, async ({ status }) => {\n console.log('Transaction status', status.type);\n if (status.type === 'BestChainBlockIncluded') {\n console.log(`Transaction is included in best block`);\n }\n if (status.type === 'Finalized') {\n console.log(\n `Transaction completed at block hash ${status.value.blockHash}`\n );\n await unsub();\n }\n });\n\n```"} -{"page_id": "reference-tools-dedot", "page_title": "Dedot", "index": 8, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 8719, "end_char": 8855, "estimated_token_count": 36, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\nFor more detailed information about Dedot, check the [official documentation](https://dedot.dev/){target=\\_blank}."} -{"page_id": "reference-tools-light-clients", "page_title": "Light Clients", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 17, "end_char": 994, "estimated_token_count": 167, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nLight clients enable secure and efficient blockchain interaction without running a full node. They provide a trust-minimized alternative to JSON-RPC by verifying data through cryptographic proofs rather than blindly trusting remote nodes.\n\nThis guide covers:\n\n- What light clients are and how they work.\n- Their advantages compared to full nodes and JSON-RPC.\n- Available implementations in the Polkadot ecosystem.\n- How to use light clients in your applications.\n\nLight clients are particularly valuable for resource-constrained environments and applications requiring secure, decentralized blockchain access without the overhead of maintaining full nodes.\n\n!!!note \"Light node or light client?\"\n The terms _light node_ and _light client_ are interchangeable. Both refer to a blockchain client that syncs without downloading the entire blockchain state. All nodes in a blockchain network are fundamentally clients, engaging in peer-to-peer communication."} -{"page_id": "reference-tools-light-clients", "page_title": "Light Clients", "index": 1, "depth": 2, "title": "Light Clients Workflow", "anchor": "light-clients-workflow", "start_char": 994, "end_char": 2625, "estimated_token_count": 359, "token_estimator": "heuristic-v1", "text": "## Light Clients Workflow\n\nUnlike JSON-RPC interfaces, where an application must maintain a list of providers or rely on a single node, light clients are not limited to or dependent on a single node. They use cryptographic proofs to verify the blockchain's state, ensuring it is up-to-date and accurate. By verifying only block headers, light clients avoid syncing the entire state, making them ideal for resource-constrained environments.\n\n```mermaid\nflowchart LR\nDAPP([dApp])-- Query Account Info -->LC([Light Client])\nLC -- Request --> FN(((Full Node)))\nLC -- Response --> DAPP\nFN -- Response (validated via Merkle proof) --> LC\n```\n\nIn the diagram above, the decentralized application queries on-chain account information through the light client. The light client runs as part of the application and requires minimal memory and computational resources. It uses Merkle proofs to verify the state retrieved from a full node in a trust-minimized manner. Polkadot-compatible light clients utilize [warp syncing](https://spec.polkadot.network/sect-lightclient#sect-sync-warp-lightclient){target=\\_blank}, which downloads only block headers.\n\nLight clients can quickly verify the blockchain's state, including [GRANDPA finality](/polkadot-protocol/glossary#grandpa){target=\\_blank} justifications.\n\n!!!note \"What does it mean to be trust-minimized?\"\n _Trust-minimized_ means that the light client does not need to fully trust the full node from which it retrieves the state. This is achieved through the use of Merkle proofs, which allow the light client to verify the correctness of the state by checking the Merkle tree root."} -{"page_id": "reference-tools-light-clients", "page_title": "Light Clients", "index": 2, "depth": 2, "title": "JSON-RPC and Light Client Comparison", "anchor": "json-rpc-and-light-client-comparison", "start_char": 2625, "end_char": 4478, "estimated_token_count": 442, "token_estimator": "heuristic-v1", "text": "## JSON-RPC and Light Client Comparison\n\nAnother common method of communication between a user interface (UI) and a node is through the JSON-RPC protocol. Generally, the UI retrieves information from the node, fetches network or [pallet](/polkadot-protocol/glossary#pallet){target=\\_blank} data, and interacts with the blockchain. This is typically done in one of two ways:\n\n- **User-controlled nodes**: The UI connects to a node client installed on the user's machine.\n - These nodes are secure, but installation and maintenance can be inconvenient.\n- **Publicly accessible nodes**: The UI connects to a third-party-owned publicly accessible node client.\n - These nodes are convenient but centralized and less secure. Applications must maintain a list of backup nodes in case the primary node becomes unavailable.\n\nWhile light clients still communicate with [full nodes](/polkadot-protocol/glossary#full-node), they offer significant advantages for applications requiring a secure alternative to running a full node:\n\n| Full Node | Light Client |\n| :---------------------------------------------------------------------------------------------: | :------------------------------------------------------------: |\n| Fully verifies all blocks of the chain | Verifies only the authenticity of blocks |\n| Stores previous block data and the chain's storage in a database | Does not require a database |\n| Installation, maintenance, and execution are resource-intensive and require technical expertise | No installation is typically included as part of the application |"} -{"page_id": "reference-tools-light-clients", "page_title": "Light Clients", "index": 3, "depth": 2, "title": "Using Light Clients", "anchor": "using-light-clients", "start_char": 4478, "end_char": 4799, "estimated_token_count": 78, "token_estimator": "heuristic-v1", "text": "## Using Light Clients\n\nThe [`smoldot`](https://github.com/smol-dot/smoldot){target=\\_blank} client is the cornerstone of light client implementation for Polkadot SDK-based chains. It provides the primitives needed to build light clients and is also integrated into libraries such as [PAPI](#papi-light-client-support)."} -{"page_id": "reference-tools-light-clients", "page_title": "Light Clients", "index": 4, "depth": 3, "title": "PAPI Light Client Support", "anchor": "papi-light-client-support", "start_char": 4799, "end_char": 5131, "estimated_token_count": 82, "token_estimator": "heuristic-v1", "text": "### PAPI Light Client Support\n\nThe [Polkadot API (PAPI)](/develop/toolkit/api-libraries/papi){target=\\_blank} library natively supports light client configurations powered by [`smoldot`](https://github.com/smol-dot/smoldot){target=\\_blank}. This allows developers to connect to multiple chains simultaneously using a light client."} -{"page_id": "reference-tools-light-clients", "page_title": "Light Clients", "index": 5, "depth": 3, "title": "Substrate Connect - Browser Extension", "anchor": "substrate-connect-browser-extension", "start_char": 5131, "end_char": 5902, "estimated_token_count": 139, "token_estimator": "heuristic-v1", "text": "### Substrate Connect - Browser Extension\n\nThe [Substrate Connect browser extension](https://www.npmjs.com/package/@substrate/connect-extension-protocol){target=\\_blank} enables end-users to interact with applications connected to multiple blockchains or to connect their own blockchains to supported applications.\n\nEstablishing a sufficient number of peers can be challenging due to browser limitations on WebSocket connections from HTTPS pages, as many nodes require TLS. The Substrate Connect browser extension addresses this limitation by keeping chains synced in the background, enabling faster application performance.\n\nSubstrate Connect automatically detects whether the user has the extension installed. If not, an in-page Wasm light client is created for them."} -{"page_id": "reference-tools-light-clients", "page_title": "Light Clients", "index": 6, "depth": 2, "title": "Resources", "anchor": "resources", "start_char": 5902, "end_char": 6490, "estimated_token_count": 163, "token_estimator": "heuristic-v1", "text": "## Resources\n\n- [What is a light client and why you should care?](https://medium.com/paritytech/what-is-a-light-client-and-why-you-should-care-75f813ae2670){target=\\_blank}\n- [Introducing Substrate Connect: Browser-Based Light Clients for Connecting to Substrate Chains](https://www.parity.io/blog/introducing-substrate-connect){target=\\_blank}\n- [Substrate Connect GitHub Repository](https://github.com/paritytech/substrate-connect/tree/master/projects/extension){target=\\_blank}\n- [Light Clients - Polkadot Specification](https://spec.polkadot.network/sect-lightclient){target=\\_blank}"} -{"page_id": "reference-tools-moonwall", "page_title": "E2E Testing with Moonwall", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 29, "end_char": 786, "estimated_token_count": 112, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nMoonwall is an end-to-end testing framework designed explicitly for Polkadot SDK-based blockchain networks. It addresses one of the most significant challenges in blockchain development: managing complex test environments and network configurations.\n\nMoonwall consolidates this complexity by providing the following:\n\n- A centralized configuration management system that explicitly defines all network parameters.\n- A standardized approach to environment setup across different Substrate-based chains.\n- Built-in utilities for common testing scenarios and network interactions.\n\nDevelopers can focus on writing meaningful tests rather than managing infrastructure complexities or searching through documentation for configuration options."} -{"page_id": "reference-tools-moonwall", "page_title": "E2E Testing with Moonwall", "index": 1, "depth": 2, "title": "Prerequisites", "anchor": "prerequisites", "start_char": 786, "end_char": 1110, "estimated_token_count": 116, "token_estimator": "heuristic-v1", "text": "## Prerequisites\n\nBefore you begin, ensure you have the following installed:\n\n- [Node.js](https://nodejs.org/en/){target=\\_blank} (version 20.10 or higher).\n- A package manager such as [npm](https://www.npmjs.com/){target=\\_blank}, [yarn](https://yarnpkg.com/){target=\\_blank}, or [pnpm](https://pnpm.io/){target=\\_blank}."} -{"page_id": "reference-tools-moonwall", "page_title": "E2E Testing with Moonwall", "index": 2, "depth": 2, "title": "Install Moonwall", "anchor": "install-moonwall", "start_char": 1110, "end_char": 1450, "estimated_token_count": 63, "token_estimator": "heuristic-v1", "text": "## Install Moonwall\n\nMoonwall can be installed globally for system-wide access or locally within specific projects. This section covers both installation methods.\n\n!!! tip\n This documentation corresponds to Moonwall version `5.15.0`. To avoid compatibility issues with the documented features, ensure you're using the matching version."} -{"page_id": "reference-tools-moonwall", "page_title": "E2E Testing with Moonwall", "index": 3, "depth": 3, "title": "Global Installation", "anchor": "global-installation", "start_char": 1450, "end_char": 1955, "estimated_token_count": 132, "token_estimator": "heuristic-v1", "text": "### Global Installation\n\nGlobal installation provides system-wide access to the Moonwall CLI, making it ideal for developers working across multiple blockchain projects. Install it by running one of the following commands:\n\n=== \"npm\"\n\n ```bash\n npm install -g @moonwall/cli@5.15.0\n ```\n\n=== \"pnpm\"\n\n ```bash\n pnpm -g install @moonwall/cli@5.15.0\n ```\n\n=== \"yarn\"\n\n ```bash\n yarn global add @moonwall/cli@5.15.0\n ```\n\nNow, you can run the `moonwall` command from your terminal."} -{"page_id": "reference-tools-moonwall", "page_title": "E2E Testing with Moonwall", "index": 4, "depth": 3, "title": "Local Installation", "anchor": "local-installation", "start_char": 1955, "end_char": 2448, "estimated_token_count": 134, "token_estimator": "heuristic-v1", "text": "### Local Installation\n\nLocal installation is recommended for better dependency management and version control within a specific project. First, initialize your project:\n\n```bash\nmkdir my-moonwall-project\ncd my-moonwall-project\nnpm init -y\n```\n\nThen, install it as a local dependency:\n\n=== \"npm\"\n\n ```bash\n npm install @moonwall/cli@5.15.0\n ```\n\n=== \"pnpm\"\n\n ```bash\n pnpm install @moonwall/cli@5.15.0\n ```\n\n=== \"yarn\"\n\n ```bash\n yarn add @moonwall/cli@5.15.0\n ```"} -{"page_id": "reference-tools-moonwall", "page_title": "E2E Testing with Moonwall", "index": 5, "depth": 2, "title": "Initialize Moonwall", "anchor": "initialize-moonwall", "start_char": 2448, "end_char": 5873, "estimated_token_count": 767, "token_estimator": "heuristic-v1", "text": "## Initialize Moonwall\n\nThe `moonwall init` command launches an interactive wizard to create your configuration file:\n\n```bash\nmoonwall init\n```\n\nDuring setup, you will see prompts for the following parameters:\n\n- **`label`**: Identifies your test configuration.\n- **`global timeout`**: Maximum time (ms) for test execution.\n- **`environment name`**: Name for your testing environment.\n- **`network foundation`**: Type of blockchain environment to use.\n- **`tests directory`**: Location of your test files.\n\nSelect `Enter` to accept defaults or input custom values. You should see something like this:\n\n
\n moonwall init\n ✔ Provide a label for the config file moonwall_config\n ✔ Provide a global timeout value 30000\n ✔ Provide a name for this environment default_env\n ✔ What type of network foundation is this? dev\n ✔ Provide the path for where tests for this environment are kept tests/\n ? Would you like to generate this config? (no to restart from beginning) (Y/n)\n
\n\nThe wizard generates a `moonwall.config` file:\n\n```json\n{\n \"label\": \"moonwall_config\",\n \"defaultTestTimeout\": 30000,\n \"environments\": [\n {\n \"name\": \"default_env\",\n \"testFileDir\": [\"tests/\"],\n \"foundation\": {\n \"type\": \"dev\"\n }\n }\n ]\n}\n\n```\n\nThe default configuration requires specific details about your blockchain node and test requirements:\n\n- The `foundation` object defines how your test blockchain node will be launched and managed. The dev foundation, which runs a local node binary, is used for local development.\n\n For more information about available options, check the [Foundations](https://moonsong-labs.github.io/moonwall/guide/intro/foundations.html){target=\\_blank} section.\n\n- The `connections` array specifies how your tests will interact with the blockchain node. This typically includes provider configuration and endpoint details.\n\n A provider is a tool that allows you or your application to connect to a blockchain network and simplifies the low-level details of the process. A provider handles submitting transactions, reading state, and more. For more information on available providers, check the [Providers supported](https://moonsong-labs.github.io/moonwall/guide/intro/providers.html#providers-supported){target=\\_blank} page in the Moonwall documentation.\n\nHere's a complete configuration example for testing a local node using Polkadot.js as a provider:\n\n```json\n{\n \"label\": \"moonwall_config\",\n \"defaultTestTimeout\": 30000,\n \"environments\": [\n {\n \"name\": \"default_env\",\n \"testFileDir\": [\"tests/\"],\n \"foundation\": {\n \"launchSpec\": [\n {\n \"binPath\": \"./node-template\",\n \"newRpcBehaviour\": true,\n \"ports\": { \"rpcPort\": 9944 }\n }\n ],\n \"type\": \"dev\"\n },\n \"connections\": [\n {\n \"name\": \"myconnection\",\n \"type\": \"polkadotJs\",\n \"endpoints\": [\"ws://127.0.0.1:9944\"]\n }\n ]\n }\n ]\n}\n\n```"} -{"page_id": "reference-tools-moonwall", "page_title": "E2E Testing with Moonwall", "index": 6, "depth": 2, "title": "Writing Tests", "anchor": "writing-tests", "start_char": 5873, "end_char": 8602, "estimated_token_count": 649, "token_estimator": "heuristic-v1", "text": "## Writing Tests\n\nMoonwall uses the [`describeSuite`](https://github.com/Moonsong-Labs/moonwall/blob/7568048c52e9f7844f38fb4796ae9e1b9205fdaa/packages/cli/src/lib/runnerContext.ts#L65){target=\\_blank} function to define test suites, like using [Mocha](https://mochajs.org/){target=\\_blank}. Each test suite requires the following:\n\n- **`id`**: Unique identifier for the suite.\n- **`title`**: Descriptive name for the suite.\n- **`foundationMethods`**: Specifies the testing environment (e.g., `dev` for local node testing).\n- **`testCases`**: A callback function that houses the individual test cases of this suite.\n\nThe following example shows how to test a balance transfer between two accounts:\n\n```ts\nimport '@polkadot/api-augment';\nimport { describeSuite, expect } from '@moonwall/cli';\nimport { Keyring } from '@polkadot/api';\n\ndescribeSuite({\n id: 'D1',\n title: 'Demo suite',\n foundationMethods: 'dev',\n testCases: ({ it, context, log }) => {\n it({\n id: 'T1',\n title: 'Test Case',\n test: async () => {\n // Set up polkadot.js API and testing accounts\n let api = context.polkadotJs();\n let alice = new Keyring({ type: 'sr25519' }).addFromUri('//Alice');\n let charlie = new Keyring({ type: 'sr25519' }).addFromUri('//Charlie');\n\n // Query Charlie's account balance before transfer\n const balanceBefore = (await api.query.system.account(charlie.address))\n .data.free;\n\n // Before transfer, Charlie's account balance should be 0\n expect(balanceBefore.toString()).toEqual('0');\n log('Balance before: ' + balanceBefore.toString());\n\n // Transfer from Alice to Charlie\n const amount = 1000000000000000;\n await api.tx.balances\n .transferAllowDeath(charlie.address, amount)\n .signAndSend(alice);\n\n // Wait for the transaction to be included in a block.\n // This is necessary because the balance is not updated immediately.\n // Block time is 6 seconds.\n await new Promise((resolve) => setTimeout(resolve, 6000));\n\n // Query Charlie's account balance after transfer\n const balanceAfter = (await api.query.system.account(charlie.address))\n .data.free;\n\n // After transfer, Charlie's account balance should be 1000000000000000\n expect(balanceAfter.toString()).toEqual(amount.toString());\n log('Balance after: ' + balanceAfter.toString());\n },\n });\n },\n});\n\n```\n\nThis test demonstrates several key concepts:\n\n- Initializing the Polkadot.js API through Moonwall's context and setting up test accounts.\n- Querying on-chain state.\n- Executing transactions.\n- Waiting for block inclusion.\n- Verifying results using assertions."} -{"page_id": "reference-tools-moonwall", "page_title": "E2E Testing with Moonwall", "index": 7, "depth": 2, "title": "Running the Tests", "anchor": "running-the-tests", "start_char": 8602, "end_char": 10012, "estimated_token_count": 426, "token_estimator": "heuristic-v1", "text": "## Running the Tests\n\nExecute your tests using the `test` Moonwall CLI command. For the default environment setup run:\n\n```bash\nmoonwall test default_env -c moonwall.config\n```\n\nThe test runner will output detailed results showing:\n\n- Test suite execution status.\n- Individual test case results.\n- Execution time.\n- Detailed logs and error messages (if any).\n\nExample output:\n
\n moonwall test default_env -c moonwall.config\n stdout | tests/test1.ts > 🗃️ D1 Demo suite > 📁 D1T1 Test Case\n 2025-01-21T19:27:55.624Z test:default_env Balance before: 0\n \n stdout | tests/test1.ts > 🗃️ D1 Demo suite > 📁 D1T1 Test Case\n 2025-01-21T19:28:01.637Z test:default_env Balance after: 1000000000000000\n \n ✓ default_env tests/test1.ts (1 test) 6443ms\n ✓ 🗃️ D1 Demo suite > 📁 D1T1 Test Case 6028ms\n \n Test Files 1 passed (1)\n Tests 1 passed (1)\n Start at 16:27:53\n Duration 7.95s (transform 72ms, setup 0ms, collect 1.31s, tests 6.44s, environment 0ms, prepare 46ms)\n \n ✅ All tests passed\n
"} -{"page_id": "reference-tools-moonwall", "page_title": "E2E Testing with Moonwall", "index": 8, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 10012, "end_char": 10240, "estimated_token_count": 54, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\nFor a comprehensive guide to Moonwall's full capabilities, available configurations, and advanced usage, see the official [Moonwall](https://moonsong-labs.github.io/moonwall/){target=\\_blank} documentation."} -{"page_id": "reference-tools-omninode", "page_title": "Polkadot Omni Node", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 22, "end_char": 985, "estimated_token_count": 205, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nThe [`polkadot-omni-node`](https://crates.io/crates/polkadot-omni-node/0.7.0){target=\\_blank} crate is a versatile, pre-built binary designed to simplify running parachains in the Polkadot ecosystem. Unlike traditional node binaries that are tightly coupled to specific runtime code, the `polkadot-omni-node` operates using an external [chain specification](/polkadot-protocol/glossary#chain-specification){target=\\_blank} file, allowing it to adapt dynamically to different parachains.\n\nThis approach enables it to act as a white-labeled node binary, capable of running most parachains that do not require custom node-level logic or extensions. Developers can leverage this flexibility to test, deploy, or operate parachain nodes without maintaining a dedicated codebase for each network.\n\nThis guide provides step-by-step instructions for installing the `polkadot-omni-node`, obtaining a chain specification, and spinning up a parachain node."} -{"page_id": "reference-tools-omninode", "page_title": "Polkadot Omni Node", "index": 1, "depth": 2, "title": "Prerequisites", "anchor": "prerequisites", "start_char": 985, "end_char": 1307, "estimated_token_count": 87, "token_estimator": "heuristic-v1", "text": "## Prerequisites\n\nBefore getting started, ensure you have the following prerequisites:\n\n- **[Rust](https://rust-lang.org/tools/install/){target=\\_blank}**: Required to build and install the `polkadot-omni-node` binary.\n\nEnsure Rust's `cargo` command is available in your terminal by running:\n\n```bash\ncargo --version\n```"} -{"page_id": "reference-tools-omninode", "page_title": "Polkadot Omni Node", "index": 2, "depth": 2, "title": "Install Polkadot Omni Node", "anchor": "install-polkadot-omni-node", "start_char": 1307, "end_char": 1745, "estimated_token_count": 107, "token_estimator": "heuristic-v1", "text": "## Install Polkadot Omni Node\n\nTo install `polkadot-omni-node` globally using `cargo`, run:\n\n```bash\ncargo install --locked polkadot-omni-node@0.7.0\n```\n\nThis command downloads and installs version 0.7.0 of the binary, making it available system-wide.\n\nTo confirm the installation, run:\n\n```bash\npolkadot-omni-node --version\n```\n\nYou should see the installed version number printed to the terminal, confirming a successful installation."} -{"page_id": "reference-tools-omninode", "page_title": "Polkadot Omni Node", "index": 3, "depth": 2, "title": "Obtain Chain Specifications", "anchor": "obtain-chain-specifications", "start_char": 1745, "end_char": 2581, "estimated_token_count": 202, "token_estimator": "heuristic-v1", "text": "## Obtain Chain Specifications\n\nThe `polkadot-omni-node` binary uses a chain specification file to configure and launch a parachain node. This file defines the parachain's genesis state and network settings.\n\nThe most common source for official chain specifications is the [`paritytech/chainspecs`](https://github.com/paritytech/chainspecs){target=\\_blank} repository. These specifications are also browsable in a user-friendly format via the [Chainspec Collection](https://paritytech.github.io/chainspecs/){target=\\_blank} website.\n\nTo obtain a chain specification:\n\n1. Visit the [Chainspec Collection](https://paritytech.github.io/chainspecs/){target=\\_blank} website.\n2. Find the parachain you want to run.\n3. Click the chain spec to open it.\n4. Copy the JSON content and save it locally as a `.json` file, e.g., `chain_spec.json`."} -{"page_id": "reference-tools-omninode", "page_title": "Polkadot Omni Node", "index": 4, "depth": 2, "title": "Run a Parachain Full Node", "anchor": "run-a-parachain-full-node", "start_char": 2581, "end_char": 3712, "estimated_token_count": 241, "token_estimator": "heuristic-v1", "text": "## Run a Parachain Full Node\n\nOnce you've installed `polkadot-omni-node` and saved the appropriate chain specification file, you can start a full node for your chosen parachain.\n\nTo see all available flags and configuration options, run:\n\n```bash\npolkadot-omni-node --help\n```\n\nTo launch the node, run the following command, replacing `./INSERT_PARACHAIN_CHAIN_SPEC.json` with the actual path to your saved chain spec file.\n\nThis command will:\n\n- Load the chain specification.\n- Initialize the node using the provided network configuration.\n- Begin syncing with the parachain network.\n\n```bash\npolkadot-omni-node --chain ./INSERT_PARACHAIN_CHAIN_SPEC.json --sync warp\n```\n\n- The `--chain` flag tells the `polkadot-omni-node` which parachain to run by pointing to its chain specification file.\n- The `--sync warp` flag enables warp sync, allowing the node to quickly catch up to the latest finalized state. Historical blocks are fetched in the background as the node continues operating.\n\nOnce started, the node will begin connecting to peers and syncing with the network. You’ll see logs in your terminal reflecting its progress."} -{"page_id": "reference-tools-omninode", "page_title": "Polkadot Omni Node", "index": 5, "depth": 2, "title": "Interact with the Node", "anchor": "interact-with-the-node", "start_char": 3712, "end_char": 4274, "estimated_token_count": 144, "token_estimator": "heuristic-v1", "text": "## Interact with the Node\n\nBy default, `polkadot-omni-node` exposes a WebSocket endpoint at `ws://localhost:9944`, which you can use to interact with the running node. You can connect using:\n\n- **[Polkadot.js Apps](https://polkadot.js.org/apps/#/explorer){target=\\_blank}**: A web-based interface for exploring and interacting with Polkadot SDK-based chains.\n- Custom scripts using compatible [libraries](/develop/toolkit/api-libraries/){target=\\_blank}.\n\nOnce connected, you can review blocks, call extrinsics, inspect storage, and interact with the runtime."} -{"page_id": "reference-tools-omninode", "page_title": "Polkadot Omni Node", "index": 6, "depth": 2, "title": "Parachain Compatibility", "anchor": "parachain-compatibility", "start_char": 4274, "end_char": 5088, "estimated_token_count": 170, "token_estimator": "heuristic-v1", "text": "## Parachain Compatibility\n\nThe `polkadot-omni-node` is designed to work with most parachains out of the box; however, your parachain's runtime must meet specific requirements and follow certain conventions to be compatible. This section outlines what your runtime needs to implement and configure to work seamlessly with the `polkadot-omni-node`:\n\n- Your runtime must implement the required runtime APIs (see below).\n- Your runtime must include and configure the required pallets.\n\nThe [`parachain-template`](https://github.com/paritytech/polkadot-sdk-parachain-template/tree/v0.0.4){target=_blank} provides a complete reference implementation that is fully compatible with the `polkadot-omni-node`. You can use it as a starting point or reference for ensuring your runtime meets all compatibility requirements."} -{"page_id": "reference-tools-omninode", "page_title": "Polkadot Omni Node", "index": 7, "depth": 3, "title": "Required Runtime APIs", "anchor": "required-runtime-apis", "start_char": 5088, "end_char": 6424, "estimated_token_count": 295, "token_estimator": "heuristic-v1", "text": "### Required Runtime APIs\n\nYour parachain runtime must implement the following runtime APIs for the `polkadot-omni-node` to function properly:\n\n- **GetParachainInfo Runtime API**: The omni-node requires the [`GetParachainInfo`](https://paritytech.github.io/polkadot-sdk/master/cumulus_primitives_core/trait.GetParachainInfo.html){target=\\_blank} runtime API to identify and configure the parachain correctly. This API provides the parachain ID to the node.\n\n ```rust title=\"runtime/src/apis.rs\"\n impl cumulus_primitives_core::GetParachainInfo for Runtime {\n fn parachain_id() -> cumulus_primitives_core::ParaId {\n // Return your parachain ID\n ParachainInfo::parachain_id()\n }\n }\n ```\n\n- **Aura Runtime API**: For consensus, the `polkadot-omni-node` expects the [Aura runtime API](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/runtime/apis/trait.AuraApi.html){target=\\_blank} to be implemented.\n\n ```rust title=\"runtime/src/apis.rs\"\n impl sp_consensus_aura::AuraApi for Runtime {\n fn slot_duration() -> sp_consensus_aura::SlotDuration {\n sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION)\n }\n\n fn authorities() -> Vec {\n Aura::authorities().into_inner()\n }\n }\n ```"} -{"page_id": "reference-tools-omninode", "page_title": "Polkadot Omni Node", "index": 8, "depth": 3, "title": "Required Pallets", "anchor": "required-pallets", "start_char": 6424, "end_char": 8913, "estimated_token_count": 566, "token_estimator": "heuristic-v1", "text": "### Required Pallets\n\nYour runtime must include and properly configure the following pallets:\n\n- **System Pallet**: The System pallet ([`frame-system`](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_frame/prelude/frame_system/index.html){target=\\_blank}) is fundamental and must be configured with appropriate types.\n\n ```rust title=\"runtime/src/lib.rs\"\n #[frame_support::runtime]\n impl frame_system::Config for Runtime {\n type Block = Block;\n type BlockNumber = BlockNumber;\n // ... other configurations\n }\n\n // Must be named \"System\" for omni-node compatibility\n pub type System = frame_system::Pallet;\n ```\n\n- **ParachainSystem Pallet**: This pallet ([`cumulus-pallet-parachain-system`](https://paritytech.github.io/polkadot-sdk/master/cumulus_pallet_parachain_system/index.html){target=\\_blank}) enables parachain functionality and handles low-level details of being a parachain.\n\n ```rust title=\"runtime/src/lib.rs\"\n impl cumulus_pallet_parachain_system::Config for Runtime {\n type RuntimeEvent = RuntimeEvent;\n type OnSystemEvent = ();\n // ... other configurations\n }\n\n // Must be named \"ParachainSystem\" for omni-node compatibility \n pub type ParachainSystem = cumulus_pallet_parachain_system::Pallet;\n ```\n\n- **Aura Pallet**: For block authoring consensus ([`pallet-aura`](https://paritytech.github.io/polkadot-sdk/master/pallet_aura/index.html){target=\\_blank}).\n\n ```rust title=\"runtime/src/lib.rs\"\n impl pallet_aura::Config for Runtime {\n type AuthorityId = AuraId;\n type DisabledValidators = ();\n type MaxAuthorities = MaxAuthorities;\n type AllowMultipleBlocksPerSlot = ConstBool;\n }\n\n pub type Aura = pallet_aura::Pallet;\n ```\n\n- **ParachainInfo Pallet**: Provides parachain metadata ([`parachain-info`](https://paritytech.github.io/polkadot-sdk/master/staging_parachain_info/index.html){target=\\_blank}).\n\n ```rust title=\"runtime/src/lib.rs\"\n impl parachain_info::Config for Runtime {}\n\n pub type ParachainInfo = parachain_info::Pallet;\n ```\n\nIf you're migrating an existing parachain to use the `polkadot-omni-node`, you may need to perform runtime upgrades to add the required runtime APIs and pallets. Follow the standard parachain [runtime upgrade](/parachains/runtime-maintenance/runtime-upgrades/){target=\\_blank} procedures to implement these changes on your live network."} -{"page_id": "reference-tools-papi", "page_title": "Polkadot-API", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 16, "end_char": 1133, "estimated_token_count": 207, "token_estimator": "heuristic-v1", "text": "## Introduction\n\n[Polkadot-API](https://github.com/polkadot-api/polkadot-api){target=\\_blank} (PAPI) is a set of libraries built to be modular, composable, and grounded in a “light-client first” approach. Its primary aim is to equip dApp developers with an extensive toolkit for building fully decentralized applications.\n\nPAPI is optimized for light-client functionality, using the new JSON-RPC spec to support decentralized interactions fully. It provides strong TypeScript support with types and documentation generated directly from on-chain metadata, and it offers seamless access to storage reads, constants, transactions, events, and runtime calls. Developers can connect to multiple chains simultaneously and prepare for runtime updates through multi-descriptor generation and compatibility checks. PAPI is lightweight and performant, leveraging native BigInt, dynamic imports, and modular subpaths to avoid bundling unnecessary assets. It supports promise-based and observable-based APIs, integrates easily with Polkadot.js extensions, and offers signing options through browser extensions or private keys."} -{"page_id": "reference-tools-papi", "page_title": "Polkadot-API", "index": 1, "depth": 2, "title": "Get Started", "anchor": "get-started", "start_char": 1133, "end_char": 1149, "estimated_token_count": 4, "token_estimator": "heuristic-v1", "text": "## Get Started"} -{"page_id": "reference-tools-papi", "page_title": "Polkadot-API", "index": 2, "depth": 3, "title": "API Instantiation", "anchor": "api-instantiation", "start_char": 1149, "end_char": 6190, "estimated_token_count": 1162, "token_estimator": "heuristic-v1", "text": "### API Instantiation\n\nTo instantiate the API, you can install the package by using the following command:\n\n=== \"npm\"\n\n ```bash\n npm i polkadot-api@1.17.2\n ```\n\n=== \"pnpm\"\n\n ```bash\n pnpm add polkadot-api@1.17.2\n ```\n\n=== \"yarn\"\n\n ```bash\n yarn add polkadot-api@1.17.2\n ```\n\nThen, obtain the latest metadata from the target chain and generate the necessary types:\n\n```bash\n# Add the target chain\nnpx papi add dot -n polkadot\n```\n\nThe `papi add` command initializes the library by generating the corresponding types needed for the chain used. It assigns the chain a custom name and specifies downloading metadata from the Polkadot chain. You can replace `dot` with the name you prefer or with another chain if you want to add a different one. Once the latest metadata is downloaded, generate the required types:\n\n```bash\n# Generate the necessary types\nnpx papi\n```\n\nYou can now set up a [`PolkadotClient`](https://github.com/polkadot-api/polkadot-api/blob/main/packages/client/src/types.ts#L153){target=\\_blank} with your chosen provider to begin interacting with the API. Choose from Smoldot via WebWorker, Node.js, or direct usage, or connect through the WSS provider. The examples below show how to configure each option for your setup.\n\n=== \"Smoldot (WebWorker)\"\n\n ```typescript\n // `dot` is the identifier assigned during `npx papi add`\n import { dot } from '@polkadot-api/descriptors';\n import { createClient } from 'polkadot-api';\n import { getSmProvider } from 'polkadot-api/sm-provider';\n import { chainSpec } from 'polkadot-api/chains/polkadot';\n import { startFromWorker } from 'polkadot-api/smoldot/from-worker';\n import SmWorker from 'polkadot-api/smoldot/worker?worker';\n\n const worker = new SmWorker();\n const smoldot = startFromWorker(worker);\n const chain = await smoldot.addChain({ chainSpec });\n\n // Establish connection to the Polkadot relay chain\n const client = createClient(getSmProvider(chain));\n\n // To interact with the chain, obtain the `TypedApi`, which provides\n // the necessary types for every API call on this chain\n const dotApi = client.getTypedApi(dot);\n\n ```\n\n=== \"Smoldot (Node.js)\"\n\n ```typescript\n // `dot` is the alias assigned during `npx papi add`\n import { dot } from '@polkadot-api/descriptors';\n import { createClient } from 'polkadot-api';\n import { getSmProvider } from 'polkadot-api/sm-provider';\n import { chainSpec } from 'polkadot-api/chains/polkadot';\n import { startFromWorker } from 'polkadot-api/smoldot/from-node-worker';\n import { fileURLToPath } from 'url';\n import { Worker } from 'worker_threads';\n\n // Get the path for the worker file in ESM\n const workerPath = fileURLToPath(\n import.meta.resolve('polkadot-api/smoldot/node-worker'),\n );\n\n const worker = new Worker(workerPath);\n const smoldot = startFromWorker(worker);\n const chain = await smoldot.addChain({ chainSpec });\n\n // Set up a client to connect to the Polkadot relay chain\n const client = createClient(getSmProvider(chain));\n\n // To interact with the chain's API, use `TypedApi` for access to\n // all the necessary types and calls associated with this chain\n const dotApi = client.getTypedApi(dot);\n\n ```\n\n=== \"Smoldot\"\n\n ```typescript\n // `dot` is the alias assigned when running `npx papi add`\n import { dot } from '@polkadot-api/descriptors';\n import { createClient } from 'polkadot-api';\n import { getSmProvider } from 'polkadot-api/sm-provider';\n import { chainSpec } from 'polkadot-api/chains/polkadot';\n import { start } from 'polkadot-api/smoldot';\n\n // Initialize Smoldot client\n const smoldot = start();\n const chain = await smoldot.addChain({ chainSpec });\n\n // Set up a client to connect to the Polkadot relay chain\n const client = createClient(getSmProvider(chain));\n\n // Access the `TypedApi` to interact with all available chain calls and types\n const dotApi = client.getTypedApi(dot);\n\n ```\n\n=== \"WSS\"\n\n ```typescript\n // `dot` is the identifier assigned when executing `npx papi add`\n import { dot } from '@polkadot-api/descriptors';\n import { createClient } from 'polkadot-api';\n // Use this import for Node.js environments\n import { getWsProvider } from 'polkadot-api/ws-provider/web';\n import { withPolkadotSdkCompat } from 'polkadot-api/polkadot-sdk-compat';\n\n // Establish a connection to the Polkadot relay chain\n const client = createClient(\n // The Polkadot SDK nodes may have compatibility issues; using this enhancer is recommended.\n // Refer to the Requirements page for additional details\n withPolkadotSdkCompat(getWsProvider('wss://dot-rpc.stakeworld.io')),\n );\n\n // To interact with the chain, obtain the `TypedApi`, which provides\n // the types for all available calls in that chain\n const dotApi = client.getTypedApi(dot);\n\n ```\n\nNow that you have set up the client, you can interact with the chain by reading and sending transactions."} -{"page_id": "reference-tools-papi", "page_title": "Polkadot-API", "index": 3, "depth": 3, "title": "Reading Chain Data", "anchor": "reading-chain-data", "start_char": 6190, "end_char": 7140, "estimated_token_count": 216, "token_estimator": "heuristic-v1", "text": "### Reading Chain Data\n\nThe `TypedApi` provides a streamlined way to read blockchain data through three main interfaces, each designed for specific data access patterns:\n\n- **Constants**: Access fixed values or configurations on the blockchain using the `constants` interface.\n\n ```typescript\n const version = await typedApi.constants.System.Version();\n ```\n\n- **Storage queries**: Retrieve stored values by querying the blockchain’s storage via the `query` interface.\n\n ```typescript\n const asset = await api.query.ForeignAssets.Asset.getValue(\n token.location,\n { at: 'best' },\n );\n ```\n\n- **Runtime APIs**: Interact directly with runtime APIs using the `apis` interface.\n\n ```typescript\n const metadata = await typedApi.apis.Metadata.metadata();\n ```\n\nTo learn more about the different actions you can perform with the `TypedApi`, refer to the [TypedApi reference](https://papi.how/typed){target=\\_blank}."} -{"page_id": "reference-tools-papi", "page_title": "Polkadot-API", "index": 4, "depth": 3, "title": "Sending Transactions", "anchor": "sending-transactions", "start_char": 7140, "end_char": 8815, "estimated_token_count": 355, "token_estimator": "heuristic-v1", "text": "### Sending Transactions\n\nIn PAPI, the `TypedApi` provides the `tx` and `txFromCallData` methods to send transactions. \n\n- The `tx` method allows you to directly send a transaction with the specified parameters by using the `typedApi.tx.Pallet.Call` pattern:\n\n ```typescript\n const tx: Transaction = typedApi.tx.Pallet.Call({arg1, arg2, arg3});\n ``` \n\n For instance, to execute the `balances.transferKeepAlive` call, you can use the following snippet:\n\n ```typescript\n import { MultiAddress } from '@polkadot-api/descriptors';\n\n const tx: Transaction = typedApi.tx.Balances.transfer_keep_alive({\n dest: MultiAddress.Id('INSERT_DESTINATION_ADDRESS'),\n value: BigInt(INSERT_VALUE),\n });\n\n ```\n\n Ensure you replace `INSERT_DESTINATION_ADDRESS` and `INSERT_VALUE` with the actual destination address and value, respectively.\n\n- The `txFromCallData` method allows you to send a transaction using the call data. This option accepts binary call data and constructs the transaction from it. It validates the input upon creation and will throw an error if invalid data is provided. The pattern is as follows:\n\n ```typescript\n const callData = Binary.fromHex('0x...');\n const tx: Transaction = typedApi.txFromCallData(callData);\n ``` \n\n For instance, to execute a transaction using the call data, you can use the following snippet:\n\n ```typescript\n const callData = Binary.fromHex('0x00002470617065726d6f6f6e');\n const tx: Transaction = typedApi.txFromCallData(callData);\n ```\n\nFor more information about sending transactions, refer to the [Transactions](https://papi.how/typed/tx#transactions){target=\\_blank} page."} -{"page_id": "reference-tools-papi", "page_title": "Polkadot-API", "index": 5, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 8815, "end_char": 8957, "estimated_token_count": 43, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\nFor an in-depth guide on how to use PAPI, refer to the official [PAPI](https://papi.how/){target=\\_blank} documentation."} -{"page_id": "reference-tools-paraspell", "page_title": "ParaSpell XCM SDK", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 21, "end_char": 2383, "estimated_token_count": 522, "token_estimator": "heuristic-v1", "text": "## Introduction\n\n[ParaSpell](https://paraspell.github.io/docs/){target=\\_blank} is a comprehensive suite of open-source tools designed to simplify cross-chain interactions within the Polkadot ecosystem. At its core, ParaSpell is dedicated to enhancing the functionality of the [XCM (Cross-Consensus Messaging)](/parachains/interoperability/get-started/){target=\\_blank} protocol by providing developers with a unified and streamlined experience for building interoperable decentralized applications (dApps).\n\nThe primary goal of ParaSpell is to abstract away the complexities of the XCM protocol. While XCM is a powerful feature of the Polkadot network, its implementation can vary significantly between different parachains. ParaSpell addresses this challenge by providing a standardized set of tools that enable developers to easily integrate cross-chain functionality into their applications, saving valuable time and effort. ParaSpell is a \"common good\" software, meaning it is free, open-source, and dedicated to the growth of the Polkadot ecosystem.\n\nThe ParaSpell suite includes:\n\n- **[XCM SDK](https://paraspell.xyz/#xcm-sdk){target=\\_blank}**: Provides a unified layer to incorporate XCM into decentralized applications, simplifying complex cross-chain interactions.\n- **[XCM API](https://paraspell.xyz/#xcm-api){target=\\_blank}**: Offers an efficient, package-free approach to integrating XCM functionality while offloading heavy computing tasks, minimizing costs and improving application performance.\n- **[XCM Router](https://paraspell.xyz/#xcm-router){target=\\_blank}**: Enables cross-chain asset swaps in a single command, allowing developers to send one asset type (such as DOT on Polkadot) and receive a different asset on another chain (like ASTR on Astar).\n- **[XCM Analyser](https://paraspell.xyz/#xcm-analyser){target=\\_blank}**: Decodes and translates complex XCM multilocation data into readable information, supporting easier troubleshooting and debugging.\n- **[XCM Visualizator](https://paraspell.xyz/#xcm-visualizator){target=\\_blank}**: A tool designed to give developers a clear, interactive view of XCM activity across the Polkadot ecosystem, providing insights into cross-chain communication flow.\n- **[XCM Playground](https://paraspell.xyz/#try-it){target=\\_blank}**: An interactive playground for testing different XCM scenarios."} -{"page_id": "reference-tools-paraspell", "page_title": "ParaSpell XCM SDK", "index": 1, "depth": 3, "title": "ParaSpell XCM SDK", "anchor": "paraspell-xcm-sdk", "start_char": 2383, "end_char": 3290, "estimated_token_count": 171, "token_estimator": "heuristic-v1", "text": "### ParaSpell XCM SDK\n\nThe [ParaSpell XCM SDK](https://paraspell.github.io/docs/sdk/getting-started.html){target=\\_blank} is a core component of the ParaSpell toolset and a foundational library for developers looking to leverage XCM in their applications. It is the first and only XCM SDK in the ecosystem to support both PolkadotJS and Polkadot API, providing developers with flexibility and choice.\n\nThe SDK simplifies the process of creating and sending XCM messages by providing a user-friendly builder pattern. This allows developers to construct complex XCM calls with just a few lines of code, reducing the likelihood of errors and ensuring that messages are constructed correctly.\n\nBy using the ParaSpell XCM SDK, developers can significantly accelerate their development workflow and build powerful, interoperable dApps that take full advantage of the Polkadot network's cross-chain capabilities."} -{"page_id": "reference-tools-paraspell", "page_title": "ParaSpell XCM SDK", "index": 2, "depth": 2, "title": "Install ParaSpell", "anchor": "install-paraspell", "start_char": 3290, "end_char": 3634, "estimated_token_count": 103, "token_estimator": "heuristic-v1", "text": "## Install ParaSpell\n\nIf you want to use ParaSpell in your project you can add it as a dependency with the following command:\n\n=== \"npm\"\n\n ```bash\n npm install --save @paraspell/sdk@11.12.6\n ```\n\n=== \"pnpm\"\n\n ```bash\n pnpm add @paraspell/sdk@11.12.6\n ```\n\n=== \"yarn\"\n\n ```bash\n yarn add @paraspell/sdk@11.12.6\n ```"} -{"page_id": "reference-tools-paraspell", "page_title": "ParaSpell XCM SDK", "index": 3, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 3634, "end_char": 4043, "estimated_token_count": 92, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\nExplore more about ParaSpell through these resources:\n\n
\n\n- Tutorial __Transfer Assets Between Parachains__\n\n ---\n\n Learn how to transfer assets across chains with ParaSpell.\n\n [:octicons-arrow-right-24: Get Started](/chain-interactions/send-transactions/interoperability/transfer-assets-parachains/)\n\n
"} -{"page_id": "reference-tools-polkadart", "page_title": "Polkadart", "index": 0, "depth": 2, "title": "Installation", "anchor": "installation", "start_char": 454, "end_char": 1089, "estimated_token_count": 147, "token_estimator": "heuristic-v1", "text": "## Installation\n\nAdd Polkadart to your `pubspec.yaml`:\n\n=== \"All packages\"\n\n ```bash\n dart pub add polkadart polkadart_cli polkadart_keyring polkadart_scale_codec secp256k1_ecdsa sr25519 ss58 substrate_bip39 substrate_metadata\n ```\n\n=== \"Core only\"\n\n ```bash\n dart pub add polkadart polkadart_cli polkadart_keyring\n ```\n\nFor type-safe API generation, add the following to your `pubspec.yaml`:\n\n{% raw %}\n```yaml title=\"pubspec.yaml\"\npolkadart:\n output_dir: lib/generated\n chains:\n polkadot: wss://rpc.polkadot.io\n kusama: wss://kusama-rpc.polkadot.io\n custom: wss://your-node.example.com\n```\n{% endraw %}"} -{"page_id": "reference-tools-polkadart", "page_title": "Polkadart", "index": 1, "depth": 2, "title": "Get Started", "anchor": "get-started", "start_char": 1089, "end_char": 1105, "estimated_token_count": 4, "token_estimator": "heuristic-v1", "text": "## Get Started"} -{"page_id": "reference-tools-polkadart", "page_title": "Polkadart", "index": 2, "depth": 3, "title": "Type Generation", "anchor": "type-generation", "start_char": 1105, "end_char": 1354, "estimated_token_count": 45, "token_estimator": "heuristic-v1", "text": "### Type Generation\n\nPolkadart provides a CLI tool to generate type definitions from any Polkadot-SDK compatible blockchain network. This allows you to build type-safe Dart applications without dealing with the low-level details of the blockchain."} -{"page_id": "reference-tools-polkadart", "page_title": "Polkadart", "index": 3, "depth": 3, "title": "Run Generator", "anchor": "run-generator", "start_char": 1354, "end_char": 1421, "estimated_token_count": 19, "token_estimator": "heuristic-v1", "text": "### Run Generator\n\n```bash\ndart run polkadart_cli:generate -v\n```"} -{"page_id": "reference-tools-polkadart", "page_title": "Polkadart", "index": 4, "depth": 3, "title": "Use Generated Types", "anchor": "use-generated-types", "start_char": 1421, "end_char": 1964, "estimated_token_count": 138, "token_estimator": "heuristic-v1", "text": "### Use Generated Types\n\n```dart\nimport 'package:your_app/generated/polkadot/polkadot.dart';\nimport 'package:polkadart/polkadart.dart';\nimport 'package:ss58/ss58.dart';\n\nfinal provider = Provider.fromUri(Uri.parse('wss://rpc.polkadot.io'));\nfinal polkadot = Polkadot(provider);\n \n// Account from SS58 address\nfinal account = Address.decode('19t9Q2ay58hMDaeg6eeBhqmHsRnc2jDMV3cYYw9zbc59HLj');\n\n// Retrieve Account Balance\nfinal accountInfo = await polkadot.query.system.account(account.pubkey);\nprint('Balance: ${accountInfo.data.free}')\n```"} -{"page_id": "reference-tools-polkadart", "page_title": "Polkadart", "index": 5, "depth": 3, "title": "Creating an API Instance", "anchor": "creating-an-api-instance", "start_char": 1964, "end_char": 2413, "estimated_token_count": 115, "token_estimator": "heuristic-v1", "text": "### Creating an API Instance\n\nAn API instance is required to interact with the blockchain. Polkadart provides a `Provider` class that allows you to connect to any network.\n\n```dart\nimport 'package:demo/generated/polkadot/polkadot.dart';\nimport 'package:polkadart/provider.dart';\n\nFuture main(List arguments) async {\n final provider = Provider.fromUri(Uri.parse('wss://rpc.polkadot.io'));\n final polkadot = Polkadot(provider);\n}\n```"} -{"page_id": "reference-tools-polkadart", "page_title": "Polkadart", "index": 6, "depth": 3, "title": "Reading Chain Data", "anchor": "reading-chain-data", "start_char": 2413, "end_char": 2909, "estimated_token_count": 111, "token_estimator": "heuristic-v1", "text": "### Reading Chain Data\n\nBesides querying the data using the `query` from the generated API, you can also use the State API for querying storage data, metadata, runtime information, and other chain information.\n\n```dart\nfinal stateApi = StateApi(provider);\n\n// Get current runtime version\nfinal runtimeVersion = await stateApi.getRuntimeVersion();\nprint(runtimeVersion.toJson());\n\n// Get metadata\nfinal metadata = await stateApi.getMetadata();\nprint('Metadata version: ${metadata.version}');\n```"} -{"page_id": "reference-tools-polkadart", "page_title": "Polkadart", "index": 7, "depth": 3, "title": "Subscribe to New Blocks", "anchor": "subscribe-to-new-blocks", "start_char": 2909, "end_char": 3197, "estimated_token_count": 74, "token_estimator": "heuristic-v1", "text": "### Subscribe to New Blocks\n\nYou can subscribe to new blocks on the blockchain using the `subscribe` method.\n\n```dart\nfinal subscription = await provider.subscribe('chain_subscribeNewHeads', []);\n\nsubscription.stream.forEach((response) {\n print('New head: ${response.result}');\n});\n```"} -{"page_id": "reference-tools-polkadart", "page_title": "Polkadart", "index": 8, "depth": 3, "title": "Send a Transaction", "anchor": "send-a-transaction", "start_char": 3197, "end_char": 4956, "estimated_token_count": 380, "token_estimator": "heuristic-v1", "text": "### Send a Transaction\n\nPerhaps the most common operation done in any blockchain is transferring funds. Here you can see how that can be done using Polkadart:\n\n```dart\nfinal wallet = await KeyPair.sr25519.fromUri(\"//Alice\");\nprint('Alice\\' wallet: ${wallet.address}');\n\n// Get information necessary to build a proper extrinsic\nfinal runtimeVersion = await polkadot.rpc.state.getRuntimeVersion();\nfinal currentBlockNumber = (await polkadot.query.system.number()) - 1;\nfinal currentBlockHash = await polkadot.query.system.blockHash(currentBlockNumber);\nfinal genesisHash = await polkadot.query.system.blockHash(0);\nfinal nonce = await polkadot.rpc.system.accountNextIndex(wallet.address);\n\n// Make the encoded call\nfinal multiAddress = $MultiAddress().id(wallet.publicKey.bytes);\nfinal transferCall = polkadot.tx.balances.transferKeepAlive(dest: multiAddress, value: BigInt.one).encode();\n\n// Make the payload\nfinal payload = SigningPayload(\n method: transferCall,\n specVersion: runtimeVersion.specVersion,\n transactionVersion: runtimeVersion.transactionVersion,\n genesisHash: encodeHex(genesisHash),\n blockHash: encodeHex(currentBlockHash),\n blockNumber: currentBlockNumber,\n eraPeriod: 64,\n nonce: nonce,\n tip: 0,\n).encode(polkadot.registry);\n\n// Sign the payload and build the final extrinsic\nfinal signature = wallet.sign(payload);\nfinal extrinsic = ExtrinsicPayload(\n signer: wallet.bytes(),\n method: transferCall,\n signature: signature,\n eraPeriod: 64,\n blockNumber: currentBlockNumber,\n nonce: nonce,\n tip: 0,\n).encode(polkadot.registry, SignatureType.sr25519);\n\n// Send the extrinsic to the blockchain\nfinal author = AuthorApi(provider);\nawait author.submitAndWatchExtrinsic(extrinsic, (data) {\n print(data);\n});\n```"} -{"page_id": "reference-tools-polkadart", "page_title": "Polkadart", "index": 9, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 4956, "end_char": 5178, "estimated_token_count": 51, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\nTo dive deeper into Polkadart, refer to the [official Polkadart documentation](https://polkadart.dev/){target=\\_blank}, where you can find comprehensive guides for common use cases and advanced usage."} -{"page_id": "reference-tools-polkadot-js-api", "page_title": "Polkadot.js API", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 385, "end_char": 669, "estimated_token_count": 68, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nThe [Polkadot.js API](https://github.com/polkadot-js/api){target=\\_blank} uses JavaScript/TypeScript to interact with Polkadot SDK-based chains. It allows you to query nodes, read chain state, and submit transactions through a dynamic, auto-generated API interface."} -{"page_id": "reference-tools-polkadot-js-api", "page_title": "Polkadot.js API", "index": 1, "depth": 3, "title": "Dynamic API Generation", "anchor": "dynamic-api-generation", "start_char": 669, "end_char": 1033, "estimated_token_count": 85, "token_estimator": "heuristic-v1", "text": "### Dynamic API Generation\n\nUnlike traditional static APIs, the Polkadot.js API generates its interfaces automatically when connecting to a node. Here's what happens when you connect:\n\n1. The API connects to your node.\n2. It retrieves the chain's metadata.\n3. Based on this metadata, it creates specific endpoints in this format: `api...
`."} -{"page_id": "reference-tools-polkadot-js-api", "page_title": "Polkadot.js API", "index": 2, "depth": 3, "title": "Available API Categories", "anchor": "available-api-categories", "start_char": 1033, "end_char": 1888, "estimated_token_count": 248, "token_estimator": "heuristic-v1", "text": "### Available API Categories\n\nYou can access three main categories of chain interactions:\n\n- **[Runtime constants](https://polkadot.js.org/docs/api/start/api.consts){target=\\_blank}** (`api.consts`):\n\n - Access runtime constants directly.\n - Returns values immediately without function calls.\n - **Example**: `api.consts.balances.existentialDeposit`\n\n- **[State queries](https://polkadot.js.org/docs/api/start/api.query/){target=\\_blank}** (`api.query`):\n\n - Read chain state.\n - **Example**: `api.query.system.account(accountId)`\n\n- **[Transactions](https://polkadot.js.org/docs/api/start/api.tx/){target=\\_blank}** (`api.tx`):\n - Submit extrinsics (transactions).\n - **Example**: `api.tx.balances.transfer(accountId, value)`\n\nThe available methods and interfaces will automatically reflect what's possible on your connected chain."} -{"page_id": "reference-tools-polkadot-js-api", "page_title": "Polkadot.js API", "index": 3, "depth": 2, "title": "Installation", "anchor": "installation", "start_char": 1888, "end_char": 2441, "estimated_token_count": 161, "token_estimator": "heuristic-v1", "text": "## Installation\n\nTo add the Polkadot.js API to your project, use the following command to install the version `16.4.7` which supports any Polkadot SDK-based chain:\n\n=== \"npm\"\n ```bash\n npm i @polkadot/api@16.4.7\n ```\n\n=== \"pnpm\"\n ```bash\n pnpm add @polkadot/api@16.4.7\n ```\n\n=== \"yarn\"\n ```bash\n yarn add @polkadot/api@16.4.7\n ```\n\nFor more detailed information about installation, see the [Installation](https://polkadot.js.org/docs/api/start/install/){target=\\_blank} section in the official Polkadot.js API documentation."} -{"page_id": "reference-tools-polkadot-js-api", "page_title": "Polkadot.js API", "index": 4, "depth": 2, "title": "Get Started", "anchor": "get-started", "start_char": 2441, "end_char": 2457, "estimated_token_count": 4, "token_estimator": "heuristic-v1", "text": "## Get Started"} -{"page_id": "reference-tools-polkadot-js-api", "page_title": "Polkadot.js API", "index": 5, "depth": 3, "title": "Creating an API Instance", "anchor": "creating-an-api-instance", "start_char": 2457, "end_char": 3226, "estimated_token_count": 175, "token_estimator": "heuristic-v1", "text": "### Creating an API Instance\n\nTo interact with a Polkadot SDK-based chain, you must establish a connection through an API instance. The API provides methods for querying chain state, sending transactions, and subscribing to updates.\n\nTo create an API connection:\n\n```js\nimport { ApiPromise, WsProvider } from '@polkadot/api';\n\n// Create a WebSocket provider\nconst wsProvider = new WsProvider('wss://rpc.polkadot.io');\n\n// Initialize the API\nconst api = await ApiPromise.create({ provider: wsProvider });\n\n// Verify the connection by getting the chain's genesis hash\nconsole.log('Genesis Hash:', api.genesisHash.toHex());\n\n```\n\n!!!warning\n All `await` operations must be wrapped in an async function or block since the API uses promises for asynchronous operations."} -{"page_id": "reference-tools-polkadot-js-api", "page_title": "Polkadot.js API", "index": 6, "depth": 3, "title": "Reading Chain Data", "anchor": "reading-chain-data", "start_char": 3226, "end_char": 4066, "estimated_token_count": 187, "token_estimator": "heuristic-v1", "text": "### Reading Chain Data\n\nThe API provides several ways to read data from the chain. You can access:\n\n- **Constants**: Values that are fixed in the runtime and don't change without a runtime upgrade.\n\n ```js\n // Get the minimum balance required for a new account\n const minBalance = api.consts.balances.existentialDeposit.toNumber();\n\n ```\n\n- **State**: Current chain state that updates with each block.\n\n ```js\n // Example address\n const address = '5DTestUPts3kjeXSTMyerHihn1uwMfLj8vU8sqF7qYrFabHE';\n\n // Get current timestamp\n const timestamp = await api.query.timestamp.now();\n\n // Get account information\n const { nonce, data: balance } = await api.query.system.account(address);\n\n console.log(`\n Timestamp: ${timestamp}\n Free Balance: ${balance.free}\n Nonce: ${nonce}\n `);\n\n ```"} -{"page_id": "reference-tools-polkadot-js-api", "page_title": "Polkadot.js API", "index": 7, "depth": 3, "title": "Sending Transactions", "anchor": "sending-transactions", "start_char": 4066, "end_char": 4881, "estimated_token_count": 194, "token_estimator": "heuristic-v1", "text": "### Sending Transactions\n\nTransactions (also called extrinsics) modify the chain state. Before sending a transaction, you need:\n\n- A funded account with sufficient balance to pay transaction fees.\n- The account's keypair for signing.\n\nTo make a transfer:\n\n```js\n// Assuming you have an `alice` keypair from the Keyring\nconst recipient = 'INSERT_RECIPIENT_ADDRESS';\nconst amount = 'INSERT_VALUE'; // Amount in the smallest unit (e.g., Planck for DOT)\n\n// Sign and send a transfer\nconst txHash = await api.tx.balances\n .transfer(recipient, amount)\n .signAndSend(alice);\n\nconsole.log('Transaction Hash:', txHash);\n\n```\n\nThe `alice` keypair in the example comes from a `Keyring` object. For more details about managing keypairs, see the [Keyring documentation](https://polkadot.js.org/docs/keyring){target=\\_blank}."} -{"page_id": "reference-tools-polkadot-js-api", "page_title": "Polkadot.js API", "index": 8, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 4881, "end_char": 5042, "estimated_token_count": 44, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\nFor more detailed information about the Polkadot.js API, check the [official documentation](https://polkadot.js.org/docs/){target=\\_blank}."} -{"page_id": "reference-tools-py-substrate-interface", "page_title": "Python Substrate Interface", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 30, "end_char": 484, "estimated_token_count": 87, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nThe [Python Substrate Interface](https://github.com/polkascan/py-substrate-interface){target=\\_blank} is a powerful library that enables interaction with Polkadot SDK-based chains. It provides essential functionality for:\n\n- Querying on-chain storage.\n- Composing and submitting extrinsics.\n- SCALE encoding/decoding.\n- Interacting with Substrate runtime metadata.\n- Managing blockchain interactions through convenient utility methods."} -{"page_id": "reference-tools-py-substrate-interface", "page_title": "Python Substrate Interface", "index": 1, "depth": 2, "title": "Installation", "anchor": "installation", "start_char": 484, "end_char": 791, "estimated_token_count": 72, "token_estimator": "heuristic-v1", "text": "## Installation\n\nInstall the library using `pip`:\n\n```py\npip install substrate-interface\n```\n\nFor more installation details, see the [Installation](https://jamdottech.github.io/py-polkadot-sdk/getting-started/installation/){target=\\_blank} section in the official Python Substrate Interface documentation."} -{"page_id": "reference-tools-py-substrate-interface", "page_title": "Python Substrate Interface", "index": 2, "depth": 2, "title": "Get Started", "anchor": "get-started", "start_char": 791, "end_char": 971, "estimated_token_count": 32, "token_estimator": "heuristic-v1", "text": "## Get Started\n\nThis guide will walk you through the basic operations with the Python Substrate Interface: connecting to a node, reading chain state, and submitting transactions."} -{"page_id": "reference-tools-py-substrate-interface", "page_title": "Python Substrate Interface", "index": 3, "depth": 3, "title": "Establishing Connection", "anchor": "establishing-connection", "start_char": 971, "end_char": 1488, "estimated_token_count": 130, "token_estimator": "heuristic-v1", "text": "### Establishing Connection\n\nThe first step is to establish a connection to a Polkadot SDK-based node. You can connect to either a local or remote node:\n\n```py\nfrom substrateinterface import SubstrateInterface\n\n# Connect to a node using websocket\nsubstrate = SubstrateInterface(\n # For local node: \"ws://127.0.0.1:9944\"\n # For Polkadot: \"wss://rpc.polkadot.io\"\n # For Kusama: \"wss://kusama-rpc.polkadot.io\"\n url=\"INSERT_WS_URL\"\n)\n\n# Verify connection\nprint(f\"Connected to chain: {substrate.chain}\")\n\n```"} -{"page_id": "reference-tools-py-substrate-interface", "page_title": "Python Substrate Interface", "index": 4, "depth": 3, "title": "Reading Chain State", "anchor": "reading-chain-state", "start_char": 1488, "end_char": 2506, "estimated_token_count": 242, "token_estimator": "heuristic-v1", "text": "### Reading Chain State\n\nYou can query various on-chain storage items. To retrieve data, you need to specify three key pieces of information:\n\n- **Pallet name**: Module or pallet that contains the storage item you want to access.\n- **Storage item**: Specific storage entry you want to query within the pallet.\n- **Required parameters**: Any parameters needed to retrieve the desired data.\n\nHere's an example of how to check an account's balance and other details:\n\n```py\n# ...\n\n# Query account balance and info\naccount_info = substrate.query(\n module=\"System\", # The pallet name\n storage_function=\"Account\", # The storage item\n params=[\"INSERT_ADDRESS\"], # Account address in SS58 format\n)\n\n# Access account details from the result\nfree_balance = account_info.value[\"data\"][\"free\"]\nreserved = account_info.value[\"data\"][\"reserved\"]\nnonce = account_info.value[\"nonce\"]\n\nprint(\n f\"\"\"\n Account Details:\n - Free Balance: {free_balance}\n - Reserved: {reserved} \n - Nonce: {nonce}\n \"\"\"\n)\n\n```"} -{"page_id": "reference-tools-py-substrate-interface", "page_title": "Python Substrate Interface", "index": 5, "depth": 3, "title": "Submitting Transactions", "anchor": "submitting-transactions", "start_char": 2506, "end_char": 3899, "estimated_token_count": 294, "token_estimator": "heuristic-v1", "text": "### Submitting Transactions\n\nTo modify the chain state, you need to submit transactions (extrinsics). Before proceeding, ensure you have:\n\n- A funded account with sufficient balance to pay transaction fees.\n- Access to the account's keypair.\n\nHere's how to create and submit a balance transfer:\n\n```py\n#...\n\n# Compose the transfer call\ncall = substrate.compose_call(\n call_module=\"Balances\", # The pallet name\n call_function=\"transfer_keep_alive\", # The extrinsic function\n call_params={\n 'dest': 'INSERT_ADDRESS', # Recipient's address\n 'value': 'INSERT_VALUE' # Amount in smallest unit (e.g., Planck for DOT)\n }\n)\n\n# Create a signed extrinsic\nextrinsic = substrate.create_signed_extrinsic(\n call=call, keypair=keypair # Your keypair for signing\n)\n\n# Submit and wait for inclusion\nreceipt = substrate.submit_extrinsic(\n extrinsic, wait_for_inclusion=True # Wait until the transaction is in a block\n)\n\nif receipt.is_success:\n print(\n f\"\"\"\n Transaction successful:\n - Extrinsic Hash: {receipt.extrinsic_hash}\n - Block Hash: {receipt.block_hash}\n \"\"\"\n )\nelse:\n print(f\"Transaction failed: {receipt.error_message}\")\n\n```\n\nThe `keypair` object is essential for signing transactions. See the [Keypair](https://jamdottech.github.io/py-polkadot-sdk/reference/keypair/){target=\\_blank} documentation for more details."} -{"page_id": "reference-tools-py-substrate-interface", "page_title": "Python Substrate Interface", "index": 6, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 3899, "end_char": 4302, "estimated_token_count": 85, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\nNow that you understand the basics, you can:\n\n- Explore more complex queries and transactions.\n- Learn about batch transactions and utility functions.\n- Discover how to work with custom pallets and types.\n\nFor comprehensive reference materials and advanced features, see the [Python Substrate Interface](https://jamdottech.github.io/py-polkadot-sdk/){target=\\_blank} documentation."} -{"page_id": "reference-tools-sidecar", "page_title": "Sidecar REST API", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 15, "end_char": 1185, "estimated_token_count": 228, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nThe [Sidecar REST API](https://github.com/paritytech/substrate-api-sidecar){target=\\_blank} is a service that provides a REST interface for interacting with Polkadot SDK-based blockchains. With this API, developers can easily access a broad range of endpoints for nodes, accounts, transactions, parachains, and more.\n\nSidecar functions as a caching layer between your application and a Polkadot SDK-based node, offering standardized REST endpoints that simplify interactions without requiring complex, direct RPC calls. This approach is especially valuable for developers who prefer REST APIs or build applications in languages with limited WebSocket support.\n\nSome of the key features of the Sidecar API include:\n\n- **REST API interface**: Provides a familiar REST API interface for interacting with Polkadot SDK-based chains.\n- **Standardized endpoints**: Offers consistent endpoint formats across different chain implementations.\n- **Caching layer**: Acts as a caching layer to improve performance and reduce direct node requests.\n- **Multiple chain support**: Works with any Polkadot SDK-based chain, including Polkadot, Kusama, and custom chains."} -{"page_id": "reference-tools-sidecar", "page_title": "Sidecar REST API", "index": 1, "depth": 2, "title": "Prerequisites", "anchor": "prerequisites", "start_char": 1185, "end_char": 1484, "estimated_token_count": 80, "token_estimator": "heuristic-v1", "text": "## Prerequisites\n\nSidecar API requires Node.js version 18.14 LTS or higher. Verify your Node.js version:\n\n```bash\nnode --version\n```\n\nIf you need to install or update Node.js, visit the [official Node.js website](https://nodejs.org/){target=\\_blank} to download and install the latest LTS version."} -{"page_id": "reference-tools-sidecar", "page_title": "Sidecar REST API", "index": 2, "depth": 2, "title": "Installation", "anchor": "installation", "start_char": 1484, "end_char": 2137, "estimated_token_count": 171, "token_estimator": "heuristic-v1", "text": "## Installation\n\nTo install Substrate API Sidecar, use one of the following commands:\n\n=== \"npm\"\n\n ```bash\n npm install -g @substrate/api-sidecar\n ```\n\n=== \"pnpm\"\n\n ```bash\n pnpm install -g @substrate/api-sidecar\n ```\n\n=== \"yarn\"\n\n ```bash\n yarn global add @substrate/api-sidecar\n ```\n\nYou can confirm the installation by running:\n\n```bash\nsubstrate-api-sidecar --version\n```\n\nFor more information about the Sidecar API installation, see the [installation and usage](https://github.com/paritytech/substrate-api-sidecar?tab=readme-ov-file#npm-package-installation-and-usage){target=\\_blank} section of the Sidecar API README."} -{"page_id": "reference-tools-sidecar", "page_title": "Sidecar REST API", "index": 3, "depth": 2, "title": "Usage", "anchor": "usage", "start_char": 2137, "end_char": 5688, "estimated_token_count": 1005, "token_estimator": "heuristic-v1", "text": "## Usage\n\nTo use the Sidecar API, you have two options:\n\n- **Local node**: Run a node locally, which Sidecar will connect to by default, requiring no additional configuration. To start, run the following:\n\n ```bash\n substrate-api-sidecar\n ```\n\n- **Remote node**: Connect Sidecar to a remote node by specifying the RPC endpoint for that chain. For example, to gain access to the Polkadot Asset Hub associated endpoints.\n\n ```bash\n SAS_SUBSTRATE_URL=wss://polkadot-asset-hub-rpc.polkadot.io substrate-api-sidecar\n ```\n\n For more configuration details, see the [Configuration](https://github.com/paritytech/substrate-api-sidecar?tab=readme-ov-file#configuration){target=\\_blank} section of the Sidecar API documentation.\n\nOnce the Sidecar API is running, you’ll see output similar to this:\n\n
\n SAS_SUBSTRATE_URL=wss://polkadot-asset-hub-rpc.polkadot.io substrate-api-sidecar\n
\n SAS:\n 📦 LOG:\n ✅ LEVEL: \"info\"\n ✅ JSON: false\n ✅ FILTER_RPC: false\n ✅ STRIP_ANSI: false\n ✅ WRITE: false\n ✅ WRITE_PATH: \"/opt/homebrew/lib/node_modules/@substrate/api-sidecar/build/src/logs\"\n ✅ WRITE_MAX_FILE_SIZE: 5242880\n ✅ WRITE_MAX_FILES: 5\n 📦 SUBSTRATE:\n ✅ URL: \"wss://polkadot-asset-hub-rpc.polkadot.io\"\n ✅ TYPES_BUNDLE: undefined\n ✅ TYPES_CHAIN: undefined\n ✅ TYPES_SPEC: undefined\n ✅ TYPES: undefined\n ✅ CACHE_CAPACITY: undefined\n 📦 EXPRESS:\n ✅ BIND_HOST: \"127.0.0.1\"\n ✅ PORT: 8080\n ✅ KEEP_ALIVE_TIMEOUT: 5000\n 📦 METRICS:\n ✅ ENABLED: false\n ✅ PROM_HOST: \"127.0.0.1\"\n ✅ PROM_PORT: 9100\n ✅ LOKI_HOST: \"127.0.0.1\"\n ✅ LOKI_PORT: 3100\n ✅ INCLUDE_QUERYPARAMS: false\n
\n 2024-11-06 08:06:01 info: Version: 19.3.0\n 2024-11-06 08:06:02 warn: API/INIT: RPC methods not decorated: chainHead_v1_body, chainHead_v1_call, chainHead_v1_continue, chainHead_v1_follow, chainHead_v1_header, chainHead_v1_stopOperation, chainHead_v1_storage, chainHead_v1_unfollow, chainHead_v1_unpin, chainSpec_v1_chainName, chainSpec_v1_genesisHash, chainSpec_v1_properties, transactionWatch_v1_submitAndWatch, transactionWatch_v1_unwatch, transaction_v1_broadcast, transaction_v1_stop\n 2024-11-06 08:06:02 info: Connected to chain Polkadot Asset Hub on the statemint client at wss://polkadot-asset-hub-rpc.polkadot.io\n 2024-11-06 08:06:02 info: Listening on http://127.0.0.1:8080/\n 2024-11-06 08:06:02 info: Check the root endpoint (http://127.0.0.1:8080/) to see the available endpoints for the current node\n
\nWith Sidecar running, you can access the exposed endpoints via a browser, [`Postman`](https://www.postman.com/){target=\\_blank}, [`curl`](https://curl.se/){target=\\_blank}, or your preferred tool."} -{"page_id": "reference-tools-sidecar", "page_title": "Sidecar REST API", "index": 4, "depth": 3, "title": "Endpoints", "anchor": "endpoints", "start_char": 5688, "end_char": 7028, "estimated_token_count": 394, "token_estimator": "heuristic-v1", "text": "### Endpoints\n\nSidecar API provides a set of REST endpoints that allow you to query different aspects of the chain, including blocks, accounts, and transactions. Each endpoint offers specific insights into the chain’s state and activities.\n\nFor example, to retrieve the version of the node, use the `/node/version` endpoint:\n\n```bash\ncurl -X 'GET' \\\n 'http://127.0.0.1:8080/node/version' \\\n -H 'accept: application/json'\n```\n\nAlternatively, you can access `http://127.0.0.1:8080/node/version` directly in a browser since it’s a `GET` request.\n\nIn response, you’ll see output similar to this (assuming you’re connected to Polkadot Asset Hub):\n\n
\n curl -X 'GET' 'http://127.0.0.1:8080/node/version' -H 'accept: application/json'\n
\n {\n \"clientVersion\": \"1.16.1-835e0767fe8\",\n \"clientImplName\": \"statemint\",\n \"chain\": \"Polkadot Asset Hub\"\n }\n
\nFor a complete list of available endpoints and their documentation, visit the [Sidecar API list endpoints](https://paritytech.github.io/substrate-api-sidecar/dist/){target=\\_blank}. You can learn about the endpoints and how to use them in your applications."} -{"page_id": "reference-tools-sidecar", "page_title": "Sidecar REST API", "index": 5, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 7028, "end_char": 7309, "estimated_token_count": 67, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\nTo dive deeper, refer to the [official Sidecar documentation](https://github.com/paritytech/substrate-api-sidecar?tab=readme-ov-file#substrateapi-sidecar){target=\\_blank}. This provides a comprehensive guide to the available configurations and advanced usage."} -{"page_id": "reference-tools-subxt", "page_title": "Subxt Rust API", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 18, "end_char": 403, "estimated_token_count": 68, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nSubxt is a Rust library designed to interact with Polkadot SDK-based blockchains. It provides a type-safe interface for submitting transactions, querying on-chain state, and performing other blockchain interactions. By leveraging Rust's strong type system, subxt ensures that your code is validated at compile time, reducing runtime errors and improving reliability."} -{"page_id": "reference-tools-subxt", "page_title": "Subxt Rust API", "index": 1, "depth": 2, "title": "Prerequisites", "anchor": "prerequisites", "start_char": 403, "end_char": 734, "estimated_token_count": 80, "token_estimator": "heuristic-v1", "text": "## Prerequisites\n\nBefore using subxt, ensure you have the following requirements:\n\n- Rust and Cargo installed on your system. You can install them using [Rustup](https://rustup.rs/){target=\\_blank}.\n- A Rust project initialized. If you don't have one, create it with:\n ```bash\n cargo new my_project && cd my_project\n ```"} -{"page_id": "reference-tools-subxt", "page_title": "Subxt Rust API", "index": 2, "depth": 2, "title": "Installation", "anchor": "installation", "start_char": 734, "end_char": 2796, "estimated_token_count": 510, "token_estimator": "heuristic-v1", "text": "## Installation\n\nTo use subxt in your project, you must install the necessary dependencies. Each plays a specific role in enabling interaction with the blockchain:\n\n1. **Install the subxt CLI**: [`subxt-cli`](https://crates.io/crates/subxt-cli){target=\\_blank} is a command-line tool that provides utilities for working with Polkadot SDK metadata. In the context of subxt, it is essential to download chain metadata, which is required to generate type-safe Rust interfaces for interacting with the blockchain. Install it using the following:\n\n ```bash\n cargo install subxt-cli@0.44.0\n ```\n\n2. **Add core dependencies**: These dependencies are essential for interacting with the blockchain.\n\n - **[subxt](https://crates.io/crates/subxt){target=\\_blank}**: The main library for communicating with Polkadot SDK nodes. It handles RPC requests, encoding/decoding, and type generation.\n\n ```bash\n cargo add subxt@0.44.0\n ```\n\n - **[subxt-signer](https://crates.io/crates/subxt-signer){target=\\_blank}**: Provides cryptographic functionality for signing transactions. Without this, you can only read data but cannot submit transactions.\n\n ```bash\n cargo add subxt-signer@0.44.0\n ```\n\n - **[tokio](https://crates.io/crates/tokio){target=\\_blank}**: An asynchronous runtime for Rust. Since blockchain operations are async, Tokio enables the efficient handling of network requests. The `rt` feature enables Tokio's runtime, including the current-thread single-threaded scheduler, which is necessary for async execution. The `macros` feature provides procedural macros like `#[tokio::main]` to simplify runtime setup.\n\n ```bash\n cargo add tokio@1.44.2 --features rt,macros\n ```\n\n After adding the dependencies, your `Cargo.toml` should look like this:\n\n ```toml\n [package]\n name = \"my_project\"\n version = \"0.1.0\"\n edition = \"2021\"\n\n [dependencies]\n subxt = \"0.41.0\"\n subxt-signer = \"0.41.0\"\n tokio = { version = \"1.44.2\", features = [\"rt\", \"macros\"] }\n\n ```"} -{"page_id": "reference-tools-subxt", "page_title": "Subxt Rust API", "index": 3, "depth": 2, "title": "Get Started", "anchor": "get-started", "start_char": 2796, "end_char": 2973, "estimated_token_count": 29, "token_estimator": "heuristic-v1", "text": "## Get Started\n\nThis guide will walk you through the fundamental operations of subxt, from setting up your environment to executing transactions and querying blockchain state."} -{"page_id": "reference-tools-subxt", "page_title": "Subxt Rust API", "index": 4, "depth": 3, "title": "Download Chain Metadata", "anchor": "download-chain-metadata", "start_char": 2973, "end_char": 3364, "estimated_token_count": 78, "token_estimator": "heuristic-v1", "text": "### Download Chain Metadata\n\nBefore interacting with a blockchain, you need to retrieve its metadata. This metadata defines storage structures, extrinsics, and other runtime details. Use the `subxt-cli` tool to download the metadata, replacing `INSERT_NODE_URL` with the URL of the node you want to interact with:\n\n```bash\nsubxt metadata --url INSERT_NODE_URL > polkadot_metadata.scale\n```"} -{"page_id": "reference-tools-subxt", "page_title": "Subxt Rust API", "index": 5, "depth": 3, "title": "Generate Type-Safe Interfaces", "anchor": "generate-type-safe-interfaces", "start_char": 3364, "end_char": 5229, "estimated_token_count": 529, "token_estimator": "heuristic-v1", "text": "### Generate Type-Safe Interfaces\n\nUse the `#[subxt::subxt]` macro to generate a type-safe Rust interface from the downloaded metadata:\n\n```rust\n// Generate an interface that we can use from the node's metadata.\n#[subxt::subxt(runtime_metadata_path = \"./polkadot_metadata.scale\")]\npub mod polkadot {}\n```\n\nOnce subxt interfaces are generated, you can interact with your node in the following ways. You can use the links below to view the related subxt documentation:\n\n- **[Transactions](https://docs.rs/subxt/latest/subxt/book/usage/transactions/index.html){target=\\_blank}**: Builds and submits transactions, monitors their inclusion in blocks, and retrieves associated events.\n- **[Storage](https://docs.rs/subxt/latest/subxt/book/usage/storage/index.html){target=\\_blank}**: Enables querying of node storage data.\n- **[Events](https://docs.rs/subxt/latest/subxt/book/usage/events/index.html){target=\\_blank}**: Retrieves events emitted from recent blocks.\n- **[Constants](https://docs.rs/subxt/latest/subxt/book/usage/constants/index.html){target=\\_blank}**: Accesses constant values stored in nodes that remain unchanged across a specific runtime version.\n- **[Blocks](https://docs.rs/subxt/latest/subxt/book/usage/blocks/index.html){target=\\_blank}**: Loads recent blocks or subscribes to new/finalized blocks, allowing examination of extrinsics, events, and storage at those blocks.\n- **[Runtime APIs](https://docs.rs/subxt/latest/subxt/book/usage/runtime_apis/index.html){target=\\_blank}**: Makes calls into pallet runtime APIs to fetch data.\n- **[Custom values](https://docs.rs/subxt/latest/subxt/book/usage/custom_values/index.html){target=\\_blank}**: Accesses \"custom values\" contained within metadata.\n- **[Raw RPC calls](https://docs.rs/subxt/latest/subxt/book/usage/rpc/index.html){target=\\_blank}**: Facilitates raw RPC requests to compatible nodes."} -{"page_id": "reference-tools-subxt", "page_title": "Subxt Rust API", "index": 6, "depth": 3, "title": "Initialize the Subxt Client", "anchor": "initialize-the-subxt-client", "start_char": 5229, "end_char": 6115, "estimated_token_count": 229, "token_estimator": "heuristic-v1", "text": "### Initialize the Subxt Client\n\nTo interact with a blockchain node using subxt, create an asynchronous main function and initialize the client. Replace `INSERT_NODE_URL` with the URL of your target node:\n\n```rust\nuse std::str::FromStr;\nuse subxt::utils::AccountId32;\nuse subxt::{OnlineClient, PolkadotConfig};\nuse subxt_signer::{bip39::Mnemonic,sr25519::Keypair};\n\n// Generate an interface that we can use from the node's metadata.\n#[subxt::subxt(runtime_metadata_path = \"./polkadot_metadata.scale\")]\npub mod polkadot {}\n\n#[tokio::main(flavor = \"current_thread\")]\nasync fn main() -> Result<(), Box> {\n // Define the node URL.\n const NODE_URL: &str = \"INSERT_NODE_URL\";\n\n // Initialize the Subxt client to interact with the blockchain.\n let api = OnlineClient::::from_url(NODE_URL).await?;\n\n // Your code here...\n\n Ok(())\n}\n```"} -{"page_id": "reference-tools-subxt", "page_title": "Subxt Rust API", "index": 7, "depth": 3, "title": "Read Chain Data", "anchor": "read-chain-data", "start_char": 6115, "end_char": 7470, "estimated_token_count": 296, "token_estimator": "heuristic-v1", "text": "### Read Chain Data\n\nsubxt provides multiple ways to access on-chain data:\n\n- **Constants**: Constants are predefined values in the runtime that remain unchanged unless modified by a runtime upgrade.\n\n For example, to retrieve the existential deposit, use:\n \n ```rust\n // A query to obtain some constant.\n let constant_query = polkadot::constants().balances().existential_deposit();\n\n // Obtain the value.\n let value = api.constants().at(&constant_query)?;\n\n println!(\"Existential deposit: {:?}\", value);\n ```\n\n- **State**: State refers to the current chain data, which updates with each block.\n\n To fetch account information, replace `INSERT_ADDRESS` with the address you want to fetch data from and use:\n\n ```rust\n // Define the target account address.\n const ADDRESS: &str = \"INSERT_ADDRESS\";\n let account = AccountId32::from_str(ADDRESS).unwrap();\n\n // Build a storage query to access account information.\n let storage_query = polkadot::storage().system().account(&account.into());\n\n // Fetch the latest state for the account.\n let result = api\n .storage()\n .at_latest()\n .await?\n .fetch(&storage_query)\n .await?\n .unwrap();\n\n println!(\"Account info: {:?}\", result);\n ```"} -{"page_id": "reference-tools-subxt", "page_title": "Subxt Rust API", "index": 8, "depth": 3, "title": "Submit Transactions", "anchor": "submit-transactions", "start_char": 7470, "end_char": 8944, "estimated_token_count": 311, "token_estimator": "heuristic-v1", "text": "### Submit Transactions\n\nTo submit a transaction, you must construct an extrinsic, sign it with your private key, and send it to the blockchain. Replace `INSERT_DEST_ADDRESS` with the recipient's address, `INSERT_AMOUNT` with the amount to transfer, and `INSERT_SECRET_PHRASE` with the sender's mnemonic phrase:\n\n```rust\n // Define the recipient address and transfer amount.\n const DEST_ADDRESS: &str = \"INSERT_DEST_ADDRESS\";\n const AMOUNT: u128 = INSERT_AMOUNT;\n\n // Convert the recipient address into an `AccountId32`.\n let dest = AccountId32::from_str(DEST_ADDRESS).unwrap();\n\n // Build the balance transfer extrinsic.\n let balance_transfer_tx = polkadot::tx()\n .balances()\n .transfer_allow_death(dest.into(), AMOUNT);\n\n // Load the sender's keypair from a mnemonic phrase.\n const SECRET_PHRASE: &str = \"INSERT_SECRET_PHRASE\";\n let mnemonic = Mnemonic::parse(SECRET_PHRASE).unwrap();\n let sender_keypair = Keypair::from_phrase(&mnemonic, None).unwrap();\n\n // Sign and submit the extrinsic, then wait for it to be finalized.\n let events = api\n .tx()\n .sign_and_submit_then_watch_default(&balance_transfer_tx, &sender_keypair)\n .await?\n .wait_for_finalized_success()\n .await?;\n\n // Check for a successful transfer event.\n if let Some(event) = events.find_first::()? {\n println!(\"Balance transfer successful: {:?}\", event);\n }\n```"} -{"page_id": "reference-tools-subxt", "page_title": "Subxt Rust API", "index": 9, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 8944, "end_char": 9174, "estimated_token_count": 57, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\nNow that you've covered the basics dive into the official [subxt documentation](https://docs.rs/subxt/latest/subxt/book/index.html){target=\\_blank} for comprehensive reference materials and advanced features."} -{"page_id": "reference-tools-xcm-tools", "page_title": "XCM Tools", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 13, "end_char": 787, "estimated_token_count": 134, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nAs described in the [Interoperability](/develop/interoperability){target=\\_blank} section, XCM (Cross-Consensus Messaging) is a protocol used in the Polkadot and Kusama ecosystems to enable communication and interaction between chains. It facilitates cross-chain communication, allowing assets, data, and messages to flow seamlessly across the ecosystem.\n\nAs XCM is central to enabling communication between blockchains, developers need robust tools to help interact with, build, and test XCM messages. Several XCM tools simplify working with the protocol by providing libraries, frameworks, and utilities that enhance the development process, ensuring that applications built within the Polkadot ecosystem can efficiently use cross-chain functionalities."} -{"page_id": "reference-tools-xcm-tools", "page_title": "XCM Tools", "index": 1, "depth": 2, "title": "Popular XCM Tools", "anchor": "popular-xcm-tools", "start_char": 787, "end_char": 809, "estimated_token_count": 5, "token_estimator": "heuristic-v1", "text": "## Popular XCM Tools"} -{"page_id": "reference-tools-xcm-tools", "page_title": "XCM Tools", "index": 2, "depth": 3, "title": "Moonsong Labs XCM Tools", "anchor": "moonsong-labs-xcm-tools", "start_char": 809, "end_char": 2190, "estimated_token_count": 333, "token_estimator": "heuristic-v1", "text": "### Moonsong Labs XCM Tools\n\n[Moonsong Labs XCM Tools](https://github.com/Moonsong-Labs/xcm-tools){target=\\_blank} provides a collection of scripts for managing and testing XCM operations between Polkadot SDK-based runtimes. These tools allow performing tasks like asset registration, channel setup, and XCM initialization. Key features include:\n\n- **Asset registration**: Registers assets, setting units per second (up-front fees), and configuring error (revert) codes.\n- **XCM initializer**: Initializes XCM, sets default XCM versions, and configures revert codes for XCM-related precompiles.\n- **HRMP manipulator**: Manages HRMP channel actions, including opening, accepting, or closing channels.\n- **XCM-Transactor-Info-Setter**: Configures transactor information, including extra weight and fee settings.\n- **Decode XCM**: Decodes XCM messages on the relay chain or parachains to help interpret cross-chain communication.\n\nTo get started, clone the repository and install the required dependencies:\n\n```bash\ngit clone https://github.com/Moonsong-Labs/xcm-tools && \ncd xcm-tools &&\nyarn install\n```\n\nFor a full overview of each script, visit the [scripts](https://github.com/Moonsong-Labs/xcm-tools/tree/main/scripts){target=\\_blank} directory or refer to the [official documentation](https://github.com/Moonsong-Labs/xcm-tools/blob/main/README.md){target=\\_blank} on GitHub."} -{"page_id": "reference-tools-xcm-tools", "page_title": "XCM Tools", "index": 3, "depth": 3, "title": "ParaSpell", "anchor": "paraspell", "start_char": 2190, "end_char": 2667, "estimated_token_count": 86, "token_estimator": "heuristic-v1", "text": "### ParaSpell\n\n[ParaSpell](/reference/tools/paraspell/){target=\\_blank} is a collection of open-source XCM tools that streamline cross-chain asset transfers and interactions across the Polkadot and Kusama ecosystems. It provides developers with an intuitive interface to build, test, and deploy interoperable dApps, featuring message composition, decoding, and practical utilities for parachain interactions that simplify debugging and cross-chain communication optimization."} -{"page_id": "reference-tools-xcm-tools", "page_title": "XCM Tools", "index": 4, "depth": 3, "title": "Astar XCM Tools", "anchor": "astar-xcm-tools", "start_char": 2667, "end_char": 4207, "estimated_token_count": 369, "token_estimator": "heuristic-v1", "text": "### Astar XCM Tools\n\nThe [Astar parachain](https://github.com/AstarNetwork/Astar/tree/master){target=\\_blank} offers a crate with a set of utilities for interacting with the XCM protocol. The [xcm-tools](https://github.com/AstarNetwork/Astar/tree/master/bin/xcm-tools){target=\\_blank} crate provides a straightforward method for users to locate a sovereign account or calculate an XC20 asset ID. Some commands included by the xcm-tools crate allow users to perform the following tasks:\n\n- **Sovereign accounts**: Obtain the sovereign account address for any parachain, either on the Relay Chain or for sibling parachains, using a simple command.\n- **XC20 EVM addresses**: Generate XC20-compatible Ethereum addresses for assets by entering the asset ID, making it easy to integrate assets across Ethereum-compatible environments.\n- **Remote accounts**: Retrieve remote account addresses needed for multi-location compatibility, using flexible options to specify account types and parachain IDs.\n\nTo start using these tools, clone the [Astar repository](https://github.com/AstarNetwork/Astar){target=\\_blank} and compile the xcm-tools package:\n\n```bash\ngit clone https://github.com/AstarNetwork/Astar &&\ncd Astar &&\ncargo build --release -p xcm-tools\n```\n\nAfter compiling, verify the setup with the following command:\n\n```bash\n./target/release/xcm-tools --help\n```\nFor more details on using Astar xcm-tools, consult the [official documentation](https://docs.astar.network/docs/learn/interoperability/xcm/integration/tools/){target=\\_blank}."} -{"page_id": "reference-tools-xcm-tools", "page_title": "XCM Tools", "index": 5, "depth": 3, "title": "Chopsticks", "anchor": "chopsticks", "start_char": 4207, "end_char": 4517, "estimated_token_count": 65, "token_estimator": "heuristic-v1", "text": "### Chopsticks\n\nThe Chopsticks library provides XCM functionality for testing XCM messages across networks, enabling you to fork multiple parachains along with a relay chain. For further details, see the [Chopsticks documentation](/tutorials/polkadot-sdk/testing/fork-live-chains/){target=\\_blank} about XCM."} -{"page_id": "reference-tools-xcm-tools", "page_title": "XCM Tools", "index": 6, "depth": 3, "title": "Moonbeam XCM SDK", "anchor": "moonbeam-xcm-sdk", "start_char": 4517, "end_char": 6146, "estimated_token_count": 385, "token_estimator": "heuristic-v1", "text": "### Moonbeam XCM SDK\n\nThe [Moonbeam XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk){target=\\_blank} enables developers to easily transfer assets between chains, either between parachains or between a parachain and the relay chain, within the Polkadot/Kusama ecosystem. With the SDK, you don't need to worry about determining the [Multilocation](https://github.com/polkadot-fellows/xcm-format?tab=readme-ov-file#7-universal-consensus-location-identifiers){target=\\_blank} of the origin or destination assets or which extrinsics are used on which networks.\n\nThe SDK consists of two main packages:\n\n- **[XCM SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/sdk){target=\\_blank}**: Core SDK for executing XCM transfers between chains in the Polkadot/Kusama ecosystem.\n- **[MRL SDK](https://github.com/moonbeam-foundation/xcm-sdk/tree/main/packages/mrl){target=\\_blank}**: Extension of the XCM SDK for transferring liquidity into and across the Polkadot ecosystem from other ecosystems like Ethereum.\n\nKey features include:\n\n- **Simplified asset transfers**: Abstracts away complex multilocation determinations and extrinsic selection.\n- **Cross-ecosystem support**: Enables transfers between Polkadot/Kusama chains and external ecosystems.\n- **Developer-friendly API**: Provides intuitive interfaces for cross-chain functionality.\n- **Comprehensive documentation**: Includes usage guides and API references for both packages.\n\nFor detailed usage examples and API documentation, visit the [official Moonbeam XCM SDK documentation](https://moonbeam-foundation.github.io/xcm-sdk/latest/){target=\\_blank}."} -{"page_id": "reference", "page_title": "Technical Reference Overview", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 0, "end_char": 1097, "estimated_token_count": 199, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nThe Technical Reference section provides comprehensive documentation of Polkadot's architecture, core concepts, and development tooling. Whether you're exploring how Polkadot's relay chain coordinates parachains, understanding governance mechanisms, or building applications on the network, this reference covers the technical foundations you need.\n\nPolkadot is a multi-chain network that enables diverse, interconnected blockchains to share security and communicate seamlessly. Understanding how these components interact from the [relay chain](/polkadot-protocol/glossary#relay-chain){target=\\_blank} that validates [parachains](/polkadot-protocol/glossary#parachain){target=\\_blank} to the [governance](/reference/glossary#governance){target=\\_blank} mechanisms that evolve the protocol is essential for developers, validators, and network participants.\n\nThis guide organizes technical documentation across five core areas: Polkadot Hub, Parachains, On-Chain Governance, Glossary, and Tools, each providing detailed information on different aspects of the Polkadot ecosystem."} -{"page_id": "reference", "page_title": "Technical Reference Overview", "index": 1, "depth": 2, "title": "Polkadot Hub", "anchor": "polkadot-hub", "start_char": 1097, "end_char": 2378, "estimated_token_count": 247, "token_estimator": "heuristic-v1", "text": "## Polkadot Hub\n\n[Polkadot Hub](/reference/polkadot-hub/){target=\\_blank} is the entry point to Polkadot for all users and application developers. It provides access to essential Web3 services, including smart contracts, staking, governance, identity management, and cross-ecosystem interoperability—without requiring you to deploy or manage a parachain.\n\nThe Hub encompasses a set of core functionality that enables developers and users to build and interact with applications on Polkadot. Key capabilities include:\n\n- **Smart contracts**: Deploy Ethereum-compatible smart contracts and build decentralized applications.\n- **Assets and tokens**: Create, manage, and transfer fungible tokens and NFTs across the ecosystem.\n- **Staking**: Participate in network security and earn rewards by staking DOT.\n- **Governance**: Vote on proposals and participate in Polkadot's decentralized decision-making through OpenGov.\n- **Identity services**: Register and manage on-chain identities, enabling access to governance roles and network opportunities.\n- **Cross-chain interoperability**: Leverage XCM messaging to interact securely with other chains in the Polkadot ecosystem.\n- **Collectives and DAOs**: Participate in governance collectives and decentralized autonomous organizations."} -{"page_id": "reference", "page_title": "Technical Reference Overview", "index": 2, "depth": 2, "title": "Parachains", "anchor": "parachains", "start_char": 2378, "end_char": 3697, "estimated_token_count": 293, "token_estimator": "heuristic-v1", "text": "## Parachains\n\n[Parachains](/reference/parachains/){target=\\_blank} are specialized blockchains that connect to the Polkadot relay chain, inheriting its security while maintaining their own application-specific logic. The parachains documentation covers:\n\n- **Accounts**: Deep dive into account types, storage, and management on parachains.\n- **Blocks, transactions and fees**: Understand block production, transaction inclusion, and fee mechanisms.\n- **Consensus**: Learn how parachain blocks are validated and finalized through the relay chain's consensus.\n- **Chain data**: Explore data structures, storage layouts, and state management.\n- **Cryptography**: Study cryptographic primitives used in Polkadot SDK-based chains.\n- **Data encoding**: Understand how data is encoded and decoded for blockchain compatibility.\n- **Networks**: Learn about networking protocols and peer-to-peer communication.\n- **Interoperability**: Discover [Cross-Consensus Messaging (XCM)](/parachains/interoperability/get-started/){target=\\_blank}, the standard for cross-chain communication.\n- **Randomness**: Understand how randomness is generated and used in Polkadot chains.\n- **Node and runtime**: Learn about parachain nodes, runtime environments, and the [Polkadot SDK](https://github.com/paritytech/polkadot-sdk){target=\\_blank}."} -{"page_id": "reference", "page_title": "Technical Reference Overview", "index": 3, "depth": 2, "title": "On-Chain Governance", "anchor": "on-chain-governance", "start_char": 3697, "end_char": 4577, "estimated_token_count": 170, "token_estimator": "heuristic-v1", "text": "## On-Chain Governance\n\n[On-Chain governance](/reference/governance/){target=\\_blank} is the decentralized decision-making mechanism for the Polkadot network. It manages the evolution and modification of the network's runtime logic, enabling community oversight and approval for proposed changes. The governance documentation details:\n\n- **OpenGov framework**: Understand Polkadot's next-generation governance system with enhanced delegation, flexible tracks, and simultaneous referendums.\n- **Origins and tracks**: Learn how governance proposals are categorized, prioritized, and executed based on their privilege level and complexity.\n- **Voting and delegation**: Explore conviction voting, vote delegation, and how token holders participate in governance.\n- **Governance evolution**: See how Polkadot's governance has evolved from Governance V1 to the current OpenGov system."} -{"page_id": "reference", "page_title": "Technical Reference Overview", "index": 4, "depth": 2, "title": "Glossary", "anchor": "glossary", "start_char": 4577, "end_char": 5018, "estimated_token_count": 90, "token_estimator": "heuristic-v1", "text": "## Glossary\n\nThe [Glossary](/reference/glossary/){target=\\_blank} provides quick-reference definitions for Polkadot-specific terminology. Essential terms include:\n\n- Blockchain concepts (blocks, transactions, state)\n- Consensus mechanisms (validators, collators, finality)\n- Polkadot-specific terms (relay chain, parachain, XCM, FRAME)\n- Network components (nodes, runtimes, storage)\n- Governance terminology (origins, tracks, referendums)"} -{"page_id": "reference", "page_title": "Technical Reference Overview", "index": 5, "depth": 2, "title": "Tools", "anchor": "tools", "start_char": 5018, "end_char": 6285, "estimated_token_count": 349, "token_estimator": "heuristic-v1", "text": "## Tools\n\nThe [Tools](/reference/tools/){target=\\_blank} section documents essential development and interaction tools for the Polkadot ecosystem:\n\n- **Light clients**: Lightweight solutions for interacting with the network without running full nodes.\n- **JavaScript/TypeScript tools**: Libraries like [Polkadot.js API](/reference/tools/polkadot-js-api/){target=\\_blank} and [PAPI](/reference/tools/papi/){target=\\_blank} for building applications.\n- **Rust tools**: [Polkadart](/reference/tools/polkadart/){target=\\_blank} and other Rust-based libraries for SDK development.\n- **Python tools**: [py-substrate-interface](/reference/tools/py-substrate-interface/){target=\\_blank} for Python developers.\n- **Testing and development**: Tools like [Moonwall](/reference/tools/moonwall/){target=\\_blank}, [Chopsticks](/reference/tools/chopsticks/){target=\\_blank}, and [Omninode](/reference/tools/omninode/){target=\\_blank} for smart contract and parachain testing.\n- **Indexing and monitoring**: [Sidecar](/reference/tools/sidecar/){target=\\_blank} for data indexing and [Dedot](/reference/tools/dedot/){target=\\_blank} for substrate interaction.\n- **Cross-chain tools**: [ParaSpell](/reference/tools/paraspell/){target=\\_blank} for XCM integration and asset transfers."} -{"page_id": "reference", "page_title": "Technical Reference Overview", "index": 6, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 6285, "end_char": 7648, "estimated_token_count": 334, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\nFor detailed exploration of specific areas, proceed to any of the main sections:\n\n
\n\n- Learn **Polkadot Hub**\n\n ---\n\n Understand the relay chain's role in coordinating parachains, providing shared security, and enabling governance.\n\n [:octicons-arrow-right-24: Reference](/reference/polkadot-hub/)\n\n- Learn **Parachains**\n\n ---\n\n Deep dive into parachain architecture, consensus, data structures, and building application-specific blockchains.\n\n [:octicons-arrow-right-24: Reference](/reference/parachains/)\n\n- Learn **On-Chain Governance**\n\n ---\n\n Explore Polkadot's decentralized governance framework and how to participate in network decision-making.\n\n [:octicons-arrow-right-24: Reference](/reference/governance/)\n\n- Guide **Glossary**\n\n ---\n\n Quick reference for Polkadot-specific terminology and concepts used throughout the documentation.\n\n [:octicons-arrow-right-24: Reference](/reference/glossary/)\n\n- Guide **Tools**\n\n ---\n\n Discover development tools, libraries, and frameworks for building and interacting with Polkadot.\n\n [:octicons-arrow-right-24: Reference](/reference/tools/)\n\n
"} +{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Fork a Parachain Using Chopsticks", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 37, "end_char": 1215, "estimated_token_count": 242, "token_estimator": "heuristic-v1", "text": "## Introduction\n\n[Chopsticks](https://github.com/AcalaNetwork/chopsticks/){target=\\_blank}, developed by the [Acala Foundation](https://github.com/AcalaNetwork){target=\\_blank}, is a versatile tool tailored for developers working on Polkadot SDK-based blockchains. With Chopsticks, you can fork live chains locally, replay blocks to analyze extrinsics, and simulate complex scenarios like XCM interactions all without deploying to a live network.\n\nThis guide walks you through installing Chopsticks and provides information on configuring a local blockchain fork. By streamlining testing and experimentation, Chopsticks empowers developers to innovate and accelerate their blockchain projects within the Polkadot ecosystem.\n\nFor additional support and information, please reach out through [GitHub Issues](https://github.com/AcalaNetwork/chopsticks/issues){target=_blank}.\n\n!!! warning\n Chopsticks uses [Smoldot](https://github.com/smol-dot/smoldot){target=_blank} light client, which only supports the native Polkadot SDK API. Consequently, a Chopsticks-based fork doesn't support Ethereum JSON-RPC calls, meaning you cannot use it to fork your chain and connect Metamask."} +{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Fork a Parachain Using Chopsticks", "index": 1, "depth": 2, "title": "Prerequisites", "anchor": "prerequisites", "start_char": 1215, "end_char": 1522, "estimated_token_count": 99, "token_estimator": "heuristic-v1", "text": "## Prerequisites\n\nBefore you begin, ensure you have the following installed:\n\n- [Node.js](https://nodejs.org/en/){target=\\_blank}.\n- A package manager such as [npm](https://www.npmjs.com/){target=\\_blank}, which should be installed with Node.js by default, or [Yarn](https://yarnpkg.com/){target=\\_blank}."} +{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Fork a Parachain Using Chopsticks", "index": 2, "depth": 2, "title": "Install Chopsticks", "anchor": "install-chopsticks", "start_char": 1522, "end_char": 1814, "estimated_token_count": 55, "token_estimator": "heuristic-v1", "text": "## Install Chopsticks\n\nYou can install Chopsticks globally or locally in your project. Choose the option that best fits your development workflow. This documentation explains the features of Chopsticks version `1.2.2`. Make sure you're using the correct version to match these instructions."} +{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Fork a Parachain Using Chopsticks", "index": 3, "depth": 3, "title": "Global Installation", "anchor": "global-installation", "start_char": 1814, "end_char": 2057, "estimated_token_count": 61, "token_estimator": "heuristic-v1", "text": "### Global Installation\n\nTo install Chopsticks globally, allowing you to use it across multiple projects, run:\n\n```bash\nnpm i -g @acala-network/chopsticks@1.2.2\n```\n\nNow, you should be able to run the `chopsticks` command from your terminal."} +{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Fork a Parachain Using Chopsticks", "index": 4, "depth": 3, "title": "Local Installation", "anchor": "local-installation", "start_char": 2057, "end_char": 2546, "estimated_token_count": 128, "token_estimator": "heuristic-v1", "text": "### Local Installation\n\nTo use Chopsticks in a specific project, first create a new directory and initialize a Node.js project:\n\n```bash\nmkdir my-chopsticks-project\ncd my-chopsticks-project\nnpm init -y\n```\n\nThen, install Chopsticks as a local dependency:\n\n```bash\nnpm i @acala-network/chopsticks@1.2.2\n```\n\nFinally, you can run Chopsticks using the `npx` command. To see all available options and commands, run it with the `--help` flag:\n\n```bash\nnpx @acala-network/chopsticks --help\n```"} +{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Fork a Parachain Using Chopsticks", "index": 5, "depth": 2, "title": "Configure Chopsticks", "anchor": "configure-chopsticks", "start_char": 2546, "end_char": 3895, "estimated_token_count": 360, "token_estimator": "heuristic-v1", "text": "## Configure Chopsticks\n\nTo run Chopsticks, you need to configure some parameters. This can be set either through using a configuration file or the command line interface (CLI). The parameters that can be configured are as follows:\n\n- **`genesis`**: The link to a parachain's raw genesis file to build the fork from, instead of an endpoint.\n- **`timestamp`**: Timestamp of the block to fork from.\n- **`endpoint`**: The endpoint of the parachain to fork.\n- **`block`**: Use to specify at which block hash or number to replay the fork.\n- **`wasm-override`**: Path of the Wasm to use as the parachain runtime, instead of an endpoint's runtime.\n- **`db`**: Path to the name of the file that stores or will store the parachain's database.\n- **`config`**: Path or URL of the config file.\n- **`port`**: The port to expose an endpoint on.\n- **`build-block-mode`**: How blocks should be built in the fork: batch, manual, instant.\n- **`import-storage`**: A pre-defined JSON/YAML storage path to override in the parachain's storage.\n- **`allow-unresolved-imports`**: Whether to allow Wasm unresolved imports when using a Wasm to build the parachain.\n- **`html`**: Include to generate storage diff preview between blocks.\n- **`mock-signature-host`**: Mock signature host so that any signature starts with `0xdeadbeef` and filled by `0xcd` is considered valid."} +{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Fork a Parachain Using Chopsticks", "index": 6, "depth": 3, "title": "Configuration File", "anchor": "configuration-file", "start_char": 3895, "end_char": 5094, "estimated_token_count": 271, "token_estimator": "heuristic-v1", "text": "### Configuration File\n\nThe Chopsticks source repository includes a collection of [YAML](https://yaml.org/){target=\\_blank} files that can be used to set up various Polkadot SDK chains locally. You can download these configuration files from the [repository's `configs` folder](https://github.com/AcalaNetwork/chopsticks/tree/master/configs){target=\\_blank}.\n\nAn example of a configuration file for Polkadot is as follows:\n\n{% raw %}\n```yaml\nendpoint:\n - wss://rpc.ibp.network/polkadot\n - wss://polkadot-rpc.dwellir.com\nmock-signature-host: true\nblock: ${env.POLKADOT_BLOCK_NUMBER}\ndb: ./db.sqlite\nruntime-log-level: 5\n\nimport-storage:\n System:\n Account:\n - - - 5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY\n - providers: 1\n data:\n free: '10000000000000000000'\n ParasDisputes:\n $removePrefix: ['disputes'] # those can makes block building super slow\n\n```\n{% endraw %}\n\nThe configuration file allows you to modify the storage of the forked network by rewriting the pallet, state component and value that you want to change. For example, Polkadot's file rewrites Alice's `system.Account` storage so that the free balance is set to `10000000000000000000`."} +{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Fork a Parachain Using Chopsticks", "index": 7, "depth": 3, "title": "CLI Flags", "anchor": "cli-flags", "start_char": 5094, "end_char": 5275, "estimated_token_count": 35, "token_estimator": "heuristic-v1", "text": "### CLI Flags\n\nAlternatively, all settings (except for genesis and timestamp) can be configured via command-line flags, providing a comprehensive method to set up the environment."} +{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Fork a Parachain Using Chopsticks", "index": 8, "depth": 2, "title": "WebSocket Commands", "anchor": "websocket-commands", "start_char": 5275, "end_char": 10559, "estimated_token_count": 1272, "token_estimator": "heuristic-v1", "text": "## WebSocket Commands\n\nChopstick's internal WebSocket server has special endpoints that allow the manipulation of the local Polkadot SDK chain.\n\nThese are the methods that can be invoked and their parameters:\n\n- **dev_newBlock** (newBlockParams): Generates one or more new blocks.\n\n === \"Parameters\"\n\n - **`newBlockParams` ++\"NewBlockParams\"++**: The parameters to build the new block with. Where the `NewBlockParams` interface includes the following properties.\n\n - **`count` ++\"number\"++**: The number of blocks to build.\n - **`dmp` ++\"{ msg: string, sentAt: number }[]\"++**: The downward messages to include in the block.\n - **`hrmp` ++\"Record\"++**: The horizontal messages to include in the block.\n - **`to` ++\"number\"++**: The block number to build to.\n - **`transactions` ++\"string[]\"++**: The transactions to include in the block.\n - **`ump` ++\"Record\"++**: The upward messages to include in the block.\n - **`unsafeBlockHeight` ++\"number\"++**: Build block using a specific block height (unsafe).\n\n === \"Example\"\n\n ```js\n import { ApiPromise, WsProvider } from '@polkadot/api';\n\n async function main() {\n const wsProvider = new WsProvider('ws://localhost:8000');\n const api = await ApiPromise.create({ provider: wsProvider });\n await api.isReady;\n await api.rpc('dev_newBlock', { count: 1 });\n }\n\n main();\n\n ```\n\n- **dev_setBlockBuildMode** (buildBlockMode): Sets block build mode.\n\n === \"Parameter\"\n \n - **`buildBlockMode` ++\"BuildBlockMode\"++**: The build mode. Can be any of the following modes:\n\n ```ts\n export enum BuildBlockMode {\n Batch = 'Batch', /** One block per batch (default) */\n Instant = 'Instant', /** One block per transaction */\n Manual = 'Manual', /** Only build when triggered */\n }\n ```\n \n === \"Example\"\n\n ```js\n import { ApiPromise, WsProvider } from '@polkadot/api';\n\n async function main() {\n const wsProvider = new WsProvider('ws://localhost:8000');\n const api = await ApiPromise.create({ provider: wsProvider });\n await api.isReady;\n await api.rpc('dev_setBlockBuildMode', 'Instant');\n }\n\n main();\n\n ```\n\n- **dev_setHead** (hashOrNumber): Sets the head of the blockchain to a specific hash or number.\n\n === \"Parameter\"\n\n - **`hashOrNumber` ++\"string | number\"++**: The block hash or number to set as head.\n\n === \"Example\"\n\n ```js\n import { ApiPromise, WsProvider } from '@polkadot/api';\n\n async function main() {\n const wsProvider = new WsProvider('ws://localhost:8000');\n const api = await ApiPromise.create({ provider: wsProvider });\n await api.isReady;\n await api.rpc('dev_setHead', 500);\n }\n\n main();\n\n ```\n\n- **dev_setRuntimeLogLevel** (runtimeLogLevel): Sets the runtime log level.\n\n === \"Parameter\"\n\n - **`runtimeLogLevel` ++\"number\"++**: The runtime log level to set.\n\n === \"Example\"\n\n ```js\n import { ApiPromise, WsProvider } from '@polkadot/api';\n\n async function main() {\n const wsProvider = new WsProvider('ws://localhost:8000');\n const api = await ApiPromise.create({ provider: wsProvider });\n await api.isReady;\n await api.rpc('dev_setRuntimeLogLevel', 1);\n }\n\n main();\n\n ```\n\n- **dev_setStorage** (values, blockHash): Creates or overwrites the value of any storage.\n\n === \"Parameters\"\n\n - **`values` ++\"object\"++**: JSON object resembling the path to a storage value.\n - **`blockHash` ++\"string\"++**: The block hash to set the storage value.\n\n === \"Example\"\n\n ```js\n import { ApiPromise, WsProvider } from '@polkadot/api';\n\n import { Keyring } from '@polkadot/keyring';\n async function main() {\n const wsProvider = new WsProvider('ws://localhost:8000');\n const api = await ApiPromise.create({ provider: wsProvider });\n await api.isReady;\n const keyring = new Keyring({ type: 'ed25519' });\n const bob = keyring.addFromUri('//Bob');\n const storage = {\n System: {\n Account: [[[bob.address], { data: { free: 100000 }, nonce: 1 }]],\n },\n };\n await api.rpc('dev_setStorage', storage);\n }\n\n main();\n\n ```\n\n- **dev_timeTravel** (date): Sets the timestamp of the block to a specific date\".\n\n === \"Parameter\"\n\n - **`date` ++\"string\"++**: Timestamp or date string to set. All future blocks will be sequentially created after this point in time.\n\n === \"Example\"\n\n ```js\n import { ApiPromise, WsProvider } from '@polkadot/api';\n\n async function main() {\n const wsProvider = new WsProvider('ws://localhost:8000');\n const api = await ApiPromise.create({ provider: wsProvider });\n await api.isReady;\n await api.rpc('dev_timeTravel', '2030-08-15T00:00:00');\n }\n\n main();\n\n ```"} +{"page_id": "parachains-testing-fork-a-parachain", "page_title": "Fork a Parachain Using Chopsticks", "index": 9, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 10559, "end_char": 10916, "estimated_token_count": 91, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\n
\n\n- Tutorial __Fork a Chain with Chopsticks__\n\n ---\n\n Visit this guide for step-by-step instructions for configuring and interacting with your forked chain.\n\n [:octicons-arrow-right-24: Reference](/tutorials/polkadot-sdk/testing/fork-live-chains/)\n\n
"} +{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Run a Parachain Network", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 43, "end_char": 795, "estimated_token_count": 125, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nZombienet is a robust testing framework designed for Polkadot SDK-based blockchain networks. It enables developers to efficiently deploy and test ephemeral blockchain environments on platforms like Kubernetes, Podman, and native setups. With its simple and versatile CLI, Zombienet provides an all-in-one solution for spawning networks, running tests, and validating performance.\n\nThis guide will outline the different installation methods for Zombienet, provide step-by-step instructions for setting up on various platforms, and highlight essential provider-specific features and requirements.\n\nBy following this guide, Zombienet will be up and running quickly, ready to streamline your blockchain testing and development workflows."} +{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Run a Parachain Network", "index": 1, "depth": 2, "title": "Install Zombienet", "anchor": "install-zombienet", "start_char": 795, "end_char": 5049, "estimated_token_count": 901, "token_estimator": "heuristic-v1", "text": "## Install Zombienet\n\nZombienet releases are available on the [Zombienet repository](https://github.com/paritytech/zombienet){target=\\_blank}.\n\nMultiple options are available for installing Zombienet, depending on the user's preferences and the environment where it will be used. The following section will guide you through the installation process for each option.\n\n=== \"Use the executable\"\n\n Install Zombienet using executables by visiting the [latest release](https://github.com/paritytech/zombienet/releases){target=\\_blank} page and selecting the appropriate asset for your operating system. You can download the executable and move it to a directory in your PATH. \n\n Each release includes executables for Linux and macOS. Executables are generated using [pkg](https://github.com/vercel/pkg){target=\\_blank}, which allows the Zombienet CLI to operate without requiring Node.js to be installed. \n\n Then, ensure the downloaded file is executable:\n\n ```bash\n chmod +x zombienet-macos-arm64\n ```\n\n Finally, you can run the following command to check if the installation was successful. If so, it will display the version of the installed Zombienet:\n\n ```bash\n ./zombienet-macos-arm64 version\n ```\n\n If you want to add the `zombienet` executable to your PATH, you can move it to a directory in your PATH, such as `/usr/local/bin`:\n\n ```bash\n mv zombienet-macos-arm64 /usr/local/bin/zombienet\n ```\n\n Now you can refer to the `zombienet` executable directly.\n\n ```bash\n zombienet version\n ```\n\n=== \"Use Nix\"\n\n For Nix users, the Zombienet repository provides a [`flake.nix`](https://github.com/paritytech/zombienet/blob/main/flake.nix){target=\\_blank} file to install Zombienet making it easy to incorporate Zombienet into Nix-based projects.\n \n To install Zombienet utilizing Nix, users can run the following command, triggering the fetching of the flake and subsequently installing the Zombienet package:\n\n ```bash\n nix run github:paritytech/zombienet/INSERT_ZOMBIENET_VERSION -- \\\n spawn INSERT_ZOMBIENET_CONFIG_FILE_NAME.toml\n ```\n\n Replace the `INSERT_ZOMBIENET_VERSION` with the desired version of Zombienet and the `INSERT_ZOMBIENET_CONFIG_FILE_NAME` with the name of the configuration file you want to use.\n\n To run the command above, you need to have [Flakes](https://nixos.wiki/wiki/Flakes#Enable_flakes){target=\\_blank} enabled.\n\n Alternatively, you can also include the Zombienet binary in the PATH for the current shell using the following command:\n \n ```bash\n nix shell github:paritytech/zombienet/INSERT_ZOMBIENET_VERSION\n ```\n\n=== \"Use Docker\"\n\n Zombienet can also be run using Docker. The Zombienet repository provides a Docker image that can be used to run the Zombienet CLI. To run Zombienet using Docker, you can use the following command:\n\n ```bash\n docker run -it --rm \\\n -v $(pwd):/home/nonroot/zombie-net/host-current-files \\\n paritytech/zombienet\n ```\n\n The command above will run the Zombienet CLI inside a Docker container and mount the current directory to the `/home/nonroot/zombie-net/host-current-files` directory. This allows Zombienet to access the configuration file and other files in the current directory. If you want to mount a different directory, replace `$(pwd)` with the desired directory path.\n\n Inside the Docker container, you can run the Zombienet CLI commands. First, you need to set up Zombienet to download the necessary binaries:\n\n ```bash\n npm run zombie -- setup polkadot polkadot-parachain\n ```\n\n After that, you need to add those binaries to the PATH:\n\n ```bash\n export PATH=/home/nonroot/zombie-net:$PATH\n ```\n\n Finally, you can run the Zombienet CLI commands. For example, to spawn a network using a specific configuration file, you can run the following command:\n\n ```bash\n npm run zombie -- -p native spawn host-current-files/minimal.toml\n ```\n\n The command above mounts the current directory to the `/workspace` directory inside the Docker container, allowing Zombienet to access the configuration file and other files in the current directory. If you want to mount a different directory, replace `$(pwd)` with the desired directory path."} +{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Run a Parachain Network", "index": 2, "depth": 2, "title": "Providers", "anchor": "providers", "start_char": 5049, "end_char": 5832, "estimated_token_count": 185, "token_estimator": "heuristic-v1", "text": "## Providers\n\nZombienet supports different backend providers for running the nodes. At this moment, [Kubernetes](https://kubernetes.io/){target=\\_blank}, [Podman](https://podman.io/){target=\\_blank}, and local providers are supported, which can be declared as `kubernetes`, `podman`, or `native`, respectively.\n\nTo use a particular provider, you can specify it in the network file or use the `--provider` flag in the CLI:\n\n```bash\nzombienet spawn network.toml --provider INSERT_PROVIDER\n```\n\nAlternatively, you can set the provider in the network file:\n\n```toml\n[settings]\nprovider = \"INSERT_PROVIDER\"\n...\n```\n\nIt's important to note that each provider has specific requirements and associated features. The following sections cover each provider's requirements and added features."} +{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Run a Parachain Network", "index": 3, "depth": 3, "title": "Kubernetes", "anchor": "kubernetes", "start_char": 5832, "end_char": 7361, "estimated_token_count": 329, "token_estimator": "heuristic-v1", "text": "### Kubernetes\n\nKubernetes is a portable, extensible, open-source platform for managing containerized workloads and services. Zombienet is designed to be compatible with a variety of Kubernetes clusters, including: \n\n- [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine){target=\\_blank}\n- [Docker Desktop](https://docs.docker.com/desktop/features/kubernetes/){target=\\_blank}\n- [kind](https://kind.sigs.k8s.io/){target=\\_blank}\n\n#### Requirements\n \nTo effectively interact with your cluster, you'll need to ensure that [`kubectl`](https://kubernetes.io/docs/reference/kubectl/){target=\\_blank} is installed on your system. This Kubernetes command-line tool allows you to run commands against Kubernetes clusters. If you don't have `kubectl` installed, you can follow the instructions provided in the [Kubernetes documentation](https://kubernetes.io/docs/tasks/tools/#kubectl){target=\\_blank}.\n\nTo create resources such as namespaces, pods, and CronJobs within the target cluster, you must grant your user or service account the appropriate permissions. These permissions are essential for managing and deploying applications effectively within Kubernetes.\n\n#### Features\n \nIf available, Zombienet uses the Prometheus operator to oversee monitoring and visibility. This configuration ensures that only essential networking-related pods are deployed. Using the Prometheus operator, Zombienet improves its ability to monitor and manage network activities within the Kubernetes cluster efficiently."} +{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Run a Parachain Network", "index": 4, "depth": 3, "title": "Podman", "anchor": "podman", "start_char": 7361, "end_char": 8957, "estimated_token_count": 374, "token_estimator": "heuristic-v1", "text": "### Podman\n\nPodman is a daemonless container engine for developing, managing, and running Open Container Initiative (OCI) containers and container images on Linux-based systems. Zombienet supports Podman rootless as a provider on Linux machines. Although Podman has support for macOS through an internal virtual machine (VM), the Zombienet provider code requires Podman to run natively on Linux.\n\n#### Requirements\n \nTo use Podman as a provider, you need to have Podman installed on your system. You can install Podman by following the instructions provided on the [Podman website](https://podman.io/getting-started/installation){target=\\_blank}.\n\n#### Features\n \nUsing Podman, Zombienet deploys additional pods to enhance the monitoring and visibility of the active network. Specifically, pods for [Prometheus](https://prometheus.io/){target=\\_blank}, [Tempo](https://grafana.com/docs/tempo/latest/operations/monitor/){target=\\_blank}, and [Grafana](https://grafana.com/){target=\\_blank} are included in the deployment. Grafana is configured with Prometheus and Tempo as data sources.\n\nUpon launching Zombienet, access to these monitoring services is facilitated through specific URLs provided in the output:\n\n- **Prometheus**: `http://127.0.0.1:34123`\n- **Tempo**: `http://127.0.0.1:34125`\n- **Grafana**: `http://127.0.0.1:41461`\n\nIt's important to note that Grafana is deployed with default administrator access. \n \nWhen network operations cease, either from halting a running spawn with the `Ctrl+C` command or test completion, Zombienet automatically removes all associated pods."} +{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Run a Parachain Network", "index": 5, "depth": 3, "title": "Local Provider", "anchor": "local-provider", "start_char": 8957, "end_char": 10917, "estimated_token_count": 420, "token_estimator": "heuristic-v1", "text": "### Local Provider\n\nThe Zombienet local provider, also called native, enables you to run nodes as local processes in your environment.\n\n#### Requirements\n \nYou must have the necessary binaries for your network (such as `polkadot` and `polkadot-parachain`). These binaries should be available in your PATH, allowing Zombienet to spawn the nodes as local processes.\n\nTo install the necessary binaries, you can use the Zombienet CLI command:\n\n```bash\nzombienet setup polkadot polkadot-parachain\n```\n\nThis command will download and prepare the necessary binaries for Zombienet's use.\n\nIf you need to use a custom binary, ensure the binary is available in your PATH. You can also specify the binary path in the network configuration file. The following example uses the custom [OpenZeppelin template](https://github.com/OpenZeppelin/polkadot-runtime-templates){target=\\_blank}:\n\nFirst, clone the OpenZeppelin template repository using the following command:\n\n```bash\ngit clone https://github.com/OpenZeppelin/polkadot-runtime-templates \\\n&& cd polkadot-runtime-templates/generic-template\n```\n\nNext, run the command to build the custom binary:\n\n```bash\ncargo build --release\n```\n\nFinally, add the custom binary to your PATH as follows:\n\n```bash\nexport PATH=$PATH:INSERT_PATH_TO_RUNTIME_TEMPLATES/parachain-template-node/target/release\n```\n\nAlternatively, you can specify the binary path in the network configuration file. The local provider exclusively utilizes the command configuration for nodes, which supports both relative and absolute paths. You can employ the `default_command` configuration to specify the binary for spawning all nodes in the relay chain.\n\n```toml\n[relaychain]\nchain = \"rococo-local\"\ndefault_command = \"./bin-v1.6.0/polkadot\"\n\n[parachain]\nid = 1000\n\n [parachain.collators]\n name = \"collator01\"\n command = \"./target/release/parachain-template-node\"\n```\n\n#### Features\n\nThe local provider does not offer any additional features."} +{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Run a Parachain Network", "index": 6, "depth": 2, "title": "Configure Zombienet", "anchor": "configure-zombienet", "start_char": 10917, "end_char": 11529, "estimated_token_count": 99, "token_estimator": "heuristic-v1", "text": "## Configure Zombienet\n\nEffective network configuration is crucial for deploying and managing blockchain systems. Zombienet simplifies this process by offering versatile configuration options in both JSON and TOML formats. Whether setting up a simple test network or a complex multi-node system, Zombienet's tools provide the flexibility to customize every aspect of your network's setup.\n\nThe following sections will explore the structure and usage of Zombienet configuration files, explain key settings for network customization, and walk through CLI commands and flags to optimize your development workflow."} +{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Run a Parachain Network", "index": 7, "depth": 3, "title": "Configuration Files", "anchor": "configuration-files", "start_char": 11529, "end_char": 12007, "estimated_token_count": 100, "token_estimator": "heuristic-v1", "text": "### Configuration Files\n\nThe network configuration file can be either JSON or TOML format. The Zombienet repository also provides a collection of [example configuration files](https://github.com/paritytech/zombienet/tree/main/examples){target=\\_blank} that can be used as a reference.\n\nEach section may include provider-specific keys that aren't recognized by other providers. For example, if you use the local provider, any references to images for nodes will be disregarded."} +{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Run a Parachain Network", "index": 8, "depth": 3, "title": "CLI Usage", "anchor": "cli-usage", "start_char": 12007, "end_char": 13799, "estimated_token_count": 502, "token_estimator": "heuristic-v1", "text": "### CLI Usage\n\nZombienet provides a CLI that allows interaction with the tool. The CLI can receive commands and flags to perform different kinds of operations. These operations use the following syntax:\n\n```bash\nzombienet \n```\n\nThe following sections will guide you through the primary usage of the Zombienet CLI and the available commands and flags.\n\n#### CLI Commands\n\n- **`spawn `**: Spawn the network defined in the [configuration file](#configuration-files).\n- **`test `**: Run tests on the spawned network using the assertions and tests defined in the [test file](/develop/toolkit/parachains/spawn-chains/zombienet/write-tests/#the-test-file){target=\\_blank}.\n- **`setup `**: Set up the Zombienet development environment to download and use the `polkadot` or `polkadot-parachain` executable.\n- **`convert `**: Transforms a [polkadot-launch](https://github.com/paritytech/polkadot-launch){target=\\_blank} configuration file with a `.js` or `.json` extension into a Zombienet configuration file.\n- **`version`**: Prints Zombienet version.\n- **`help`**: Prints help information.\n\n#### CLI Flags\n\nYou can use the following flags to customize the behavior of the CLI:\n\n- **`-p`, `--provider`**: Override the [provider](#providers) to use.\n- **`-d`, `--dir`**: Specify a directory path for placing the network files instead of using the default temporary path.\n- **`-f`, `--force`**: Force override all prompt commands.\n- **`-l`, `--logType`**: Type of logging on the console. Defaults to `table`.\n- **`-m`, `--monitor`**: Start as monitor and don't auto clean up network.\n- **`-c`, `--spawn-concurrency`**: Number of concurrent spawning processes to launch. Defaults to `1`.\n- **`-h`, `--help`**: Display help for command."} +{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Run a Parachain Network", "index": 9, "depth": 3, "title": "Settings", "anchor": "settings", "start_char": 13799, "end_char": 16992, "estimated_token_count": 866, "token_estimator": "heuristic-v1", "text": "### Settings\n\nThrough the keyword `settings`, it's possible to define the general settings for the network. The available keys are:\n\n- **`global_volumes?`** ++\"GlobalVolume[]\"++: A list of global volumes to use.\n\n ??? child \"`GlobalVolume` interface definition\"\n ```js\n export interface GlobalVolume {\n name: string;\n fs_type: string;\n mount_path: string;\n }\n ```\n\n- **`bootnode`** ++\"boolean\"++: Add bootnode to network. Defaults to `true`.\n- **`bootnode_domain?`** ++\"string\"++: Domain to use for bootnode.\n- **`timeout`** ++\"number\"++: Global timeout to use for spawning the whole network.\n- **`node_spawn_timeout?`** ++\"number\"++: Timeout to spawn pod/process.\n- **`grafana?`** ++\"boolean\"++: Deploy an instance of Grafana.\n- **`prometheus?`** ++\"boolean\"++: Deploy an instance of Prometheus.\n- **`telemetry?`** ++\"boolean\"++: Enable telemetry for the network.\n- **`jaeger_agent?`** ++\"string\"++: The Jaeger agent endpoint passed to the nodes. Only available on Kubernetes.\n- **`tracing_collator_url?`** ++\"string\"++: The URL of the tracing collator used to query by the tracing assertion. Should be tempo query compatible.\n- **`tracing_collator_service_name?`** ++\"string\"++: Service name for tempo query frontend. Only available on Kubernetes. Defaults to `tempo-tempo-distributed-query-frontend`.\n- **`tracing_collator_service_namespace?`** ++\"string\"++: Namespace where tempo is running. Only available on Kubernetes. Defaults to `tempo`.\n- **`tracing_collator_service_port?`** ++\"number\"++: Port of the query instance of tempo. Only available on Kubernetes. Defaults to `3100`.\n- **`enable_tracing?`** ++\"boolean\"++: Enable the tracing system. Only available on Kubernetes. Defaults to `true`.\n- **`provider`** ++\"string\"++: Provider to use. Default is `kubernetes`\".\n- **`polkadot_introspector?`** ++\"boolean\"++: Deploy an instance of polkadot-introspector. Only available on Podman and Kubernetes. Defaults to `false`.\n- **`backchannel?`** ++\"boolean\"++: Deploy an instance of backchannel server. Only available on Kubernetes. Defaults to `false`.\n- **`image_pull_policy?`** ++\"string\"++: Image pull policy to use in the network. Possible values are `Always`, `IfNotPresent`, and `Never`.\n- **`local_ip?`** ++\"string\"++: IP used for exposing local services (rpc/metrics/monitors). Defaults to `\"127.0.0.1\"`.\n- **`global_delay_network_global_settings?`** ++\"number\"++: Delay in seconds to apply to the network.\n- **`node_verifier?`** ++\"string\"++: Specify how to verify node readiness or deactivate by using `None`. Possible values are `None` and `Metric`. Defaults to `Metric`.\n\nFor example, the following configuration file defines a minimal example for the settings:\n\n=== \"TOML\"\n\n ```toml title=\"base-example.toml\"\n [settings]\n timeout = 1000\n bootnode = false\n provider = \"kubernetes\"\n backchannel = false\n # ...\n\n ```\n\n=== \"JSON\"\n\n ```json title=\"base-example.json\"\n {\n \"settings\": {\n \"timeout\": 1000,\n \"bootnode\": false,\n \"provider\": \"kubernetes\",\n \"backchannel\": false,\n \"...\": {}\n },\n \"...\": {}\n }\n\n ```"} +{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Run a Parachain Network", "index": 10, "depth": 3, "title": "Relay Chain Configuration", "anchor": "relay-chain-configuration", "start_char": 16992, "end_char": 28546, "estimated_token_count": 2794, "token_estimator": "heuristic-v1", "text": "### Relay Chain Configuration\n\nYou can use the `relaychain` keyword to define further parameters for the relay chain at start-up. The available keys are:\n\n- **`default_command?`** ++\"string\"++: The default command to run. Defaults to `polkadot`.\n- **`default_image?`** ++\"string\"++: The default Docker image to use.\n- **`default_resources?`** ++\"Resources\"++: Represents the resource limits/reservations the nodes need by default. Only available on Kubernetes.\n\n ??? child \"`Resources` interface definition\"\n ```js\n export interface Resources {\n resources: {\n requests?: {\n memory?: string;\n cpu?: string;\n };\n limits?: {\n memory?: string;\n cpu?: string;\n };\n };\n }\n ```\n\n- **`default_db_snapshot?`** ++\"string\"++: The default database snapshot to use.\n- **`default_prometheus_prefix`** ++\"string\"++: A parameter for customizing the metric's prefix. Defaults to `substrate`.\n- **`default_substrate_cli_args_version?`** ++\"SubstrateCliArgsVersion\"++: Set the Substrate CLI arguments version.\n\n ??? child \"`SubstrateCliArgsVersion` enum definition\"\n ```js\n export enum SubstrateCliArgsVersion {\n V0 = 0,\n V1 = 1,\n V2 = 2,\n V3 = 3,\n }\n ```\n\n- **`default_keystore_key_types?`** ++\"string[]\"++: Defines which keystore keys should be created.\n- **`chain`** ++\"string\"++: The chain name.\n- **`chain_spec_path?`** ++\"string\"++: Path to the chain spec file. Should be the plain version to allow customizations.\n- **`chain_spec_command?`** ++\"string\"++: Command to generate the chain spec. It can't be used in combination with `chain_spec_path`.\n- **`default_args?`** ++\"string[]\"++: An array of arguments to use as default to pass to the command.\n- **`default_overrides?`** ++\"Override[]\"++: An array of overrides to upload to the node.\n\n ??? child \"`Override` interface definition\"\n ```js\n export interface Override {\n local_path: string;\n remote_name: string;\n } \n ```\n\n- **`random_nominators_count?`** ++\"number\"++: If set and the stacking pallet is enabled, Zombienet will generate the input quantity of nominators and inject them into the genesis.\n- **`max_nominations`** ++\"number\"++: The max number of nominations allowed by a nominator. Should match the value set in the runtime. Defaults to `24`.\n- **`nodes?`** ++\"Node[]\"++: An array of nodes to spawn. It is further defined in the [Node Configuration](#node-configuration) section.\n- **`node_groups?`** ++\"NodeGroup[]\"++: An array of node groups to spawn. It is further defined in the [Node Group Configuration](#node-group-configuration) section.\n- **`total_node_in_group?`** ++\"number\"++: The total number of nodes in the group. Defaults to `1`.\n- **`genesis`** ++\"JSON\"++: The genesis configuration.\n- **`default_delay_network_settings?`** ++\"DelayNetworkSettings\"++: Sets the expected configuration to delay the network.\n\n ??? child \"`DelayNetworkSettings` interface definition\"\n ```js\n export interface DelayNetworkSettings {\n latency: string;\n correlation?: string; // should be parsable as float by k8s\n jitter?: string;\n }\n ```\n\n#### Node Configuration\n\nOne specific key capable of receiving more subkeys is the `nodes` key. This key is used to define further parameters for the nodes. The available keys:\n\n- **`name`** ++\"string\"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`).\n- **`image?`** ++\"string\"++: Override default Docker image to use for this node.\n- **`command?`** ++\"string\"++: Override default command to run.\n- **`command_with_args?`** ++\"string\"++: Override default command and arguments.\n- **`args?`** ++\"string[]\"++: Arguments to be passed to the command.\n- **`env?`** ++\"envVars[]\"++: Environment variables to set in the container.\n\n ??? child \"`envVars` interface definition\"\n ```js\n export interface EnvVars {\n name: string;\n value: string;\n }\n ```\n\n- **`prometheus_prefix?`** ++\"string\"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`.\n- **`db_snapshot?`** ++\"string\"++: Database snapshot to use.\n- **`substrate_cli_args_version?`** ++\"SubstrateCliArgsVersion\"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead.\n\n ??? child \"`SubstrateCliArgsVersion` enum definition\"\n ```js\n export enum SubstrateCliArgsVersion {\n V0 = 0,\n V1 = 1,\n V2 = 2,\n V3 = 3,\n }\n ```\n\n- **`resources?`** ++\"Resources\"++: Represent the resources limits/reservations needed by the node.\n\n ??? child \"`Resources` interface definition\"\n ```js\n export interface Resources {\n resources: {\n requests?: {\n memory?: string;\n cpu?: string;\n };\n limits?: {\n memory?: string;\n cpu?: string;\n };\n };\n }\n ```\n\n- **`keystore_key_types?`** ++\"string[]\"++: Defines which keystore keys should be created.\n- **`validator`** ++\"boolean\"++: Pass the `--validator` flag to the command. Defaults to `true`.\n- **`invulnerable`** ++\"boolean\"++: If true, add the node to invulnerables in the chain spec. Defaults to `false`.\n- **`balance`** ++\"number\"++: Balance to set in balances for node's account. Defaults to `2000000000000`.\n- **`bootnodes?`** ++\"string[]\"++: Array of bootnodes to use.\n- **`add_to_bootnodes?`** ++\"boolean\"++: Add this node to the bootnode list. Defaults to `false`.\n- **`ws_port?`** ++\"number\"++: WS port to use.\n- **`rpc_port?`** ++\"number\"++: RPC port to use.\n- **`prometheus_port?`** ++\"number\"++: Prometheus port to use.\n- **`p2p_cert_hash?`** ++\"string\"++: Libp2p certhash to use with webRTC transport.\n- **`delay_network_settings?`** ++\"DelayNetworkSettings\"++: Sets the expected configuration to delay the network.\n\n ??? child \"`DelayNetworkSettings` interface definition\"\n ```js\n export interface DelayNetworkSettings {\n latency: string;\n correlation?: string; // should be parsable as float by k8s\n jitter?: string;\n }\n ```\n\nThe following configuration file defines a minimal example for the relay chain, including the `nodes` key:\n\n=== \"TOML\"\n\n ```toml title=\"relaychain-example-nodes.toml\"\n [relaychain]\n default_command = \"polkadot\"\n default_image = \"polkadot-debug:master\"\n chain = \"rococo-local\"\n chain_spec_path = \"INSERT_PATH_TO_CHAIN_SPEC\"\n default_args = [\"--chain\", \"rococo-local\"]\n\n [[relaychain.nodes]]\n name = \"alice\"\n validator = true\n balance = 1000000000000\n\n [[relaychain.nodes]]\n name = \"bob\"\n validator = true\n balance = 1000000000000\n # ...\n\n ```\n\n=== \"JSON\"\n\n ```json title=\"relaychain-example-nodes.json\"\n {\n \"relaychain\": {\n \"default_command\": \"polkadot\",\n \"default_image\": \"polkadot-debug:master\",\n \"chain\": \"rococo-local\",\n \"chain_spec_path\": \"INSERT_PATH_TO_CHAIN-SPEC.JSON\",\n \"default_args\": [\"--chain\", \"rococo-local\"],\n \"nodes\": [\n {\n \"name\": \"alice\",\n \"validator\": true,\n \"balance\": 1000000000000\n },\n {\n \"name\": \"bob\",\n \"validator\": true,\n \"balance\": 1000000000000\n }\n ]\n }\n }\n\n ```\n\n#### Node Group Configuration\n\nThe `node_groups` key defines further parameters for the node groups. The available keys are:\n\n- **`name`** ++\"string\"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`).\n- **`image?`** ++\"string\"++: Override default Docker image to use for this node.\n- **`command?`** ++\"string\"++: Override default command to run.\n- **`args?`** ++\"string[]\"++: Arguments to be passed to the command.\n- **`env?`** ++\"envVars[]\"++: Environment variables to set in the container.\n \n ??? child \"`envVars` interface definition\"\n ```js\n export interface EnvVars {\n name: string;\n value: string;\n }\n ```\n\n- **`overrides?`** ++\"Override[]\"++: Array of overrides definitions.\n\n ??? child \"`Override` interface definition\"\n ```js\n export interface Override {\n local_path: string;\n remote_name: string;\n }\n ```\n\n- **`prometheus_prefix?`** ++\"string\"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`.\n- **`db_snapshot?`** ++\"string\"++: Database snapshot to use.\n- **`substrate_cli_args_version?`** ++\"SubstrateCliArgsVersion\"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead.\n\n ??? child \"`SubstrateCliArgsVersion` enum definition\"\n ```js\n export enum SubstrateCliArgsVersion {\n V0 = 0,\n V1 = 1,\n V2 = 2,\n V3 = 3,\n }\n ```\n\n- **`resources?`** ++\"Resources\"++: Represent the resources limits/reservations needed by the node.\n\n ??? child \"`Resources` interface definition\"\n ```js\n export interface Resources {\n resources: {\n requests?: {\n memory?: string;\n cpu?: string;\n };\n limits?: {\n memory?: string;\n cpu?: string;\n };\n };\n }\n ```\n\n- **`keystore_key_types?`** ++\"string[]\"++: Defines which keystore keys should be created.\n- **`count`** ++\"number | string\"++: Number of nodes to launch for this group.\n- **`delay_network_settings?`** ++\"DelayNetworkSettings\"++: Sets the expected configuration to delay the network.\n\n ??? child \"`DelayNetworkSettings` interface definition\"\n ```js\n export interface DelayNetworkSettings {\n latency: string;\n correlation?: string; // should be parsable as float by k8s\n jitter?: string;\n }\n ```\n\nThe following configuration file defines a minimal example for the relay chain, including the `node_groups` key:\n\n=== \"TOML\"\n\n ```toml title=\"relaychain-example-node-groups.toml\"\n [relaychain]\n default_command = \"polkadot\"\n default_image = \"polkadot-debug:master\"\n chain = \"rococo-local\"\n chain_spec_path = \"INSERT_PATH_TO_CHAIN_SPEC\"\n default_args = [\"--chain\", \"rococo-local\"]\n\n [[relaychain.node_groups]]\n name = \"group-1\"\n count = 2\n image = \"polkadot-debug:master\"\n command = \"polkadot\"\n args = [\"--chain\", \"rococo-local\"]\n # ...\n\n ```\n\n=== \"JSON\"\n\n ```json title=\"relaychain-example-node-groups.json\"\n {\n \"relaychain\": {\n \"default_command\": \"polkadot\",\n \"default_image\": \"polkadot-debug:master\",\n \"chain\": \"rococo-local\",\n \"chain_spec_path\": \"INSERT_PATH_TO_CHAIN-SPEC.JSON\",\n \"default_args\": [\"--chain\", \"rococo-local\"],\n \"node_groups\": [\n {\n \"name\": \"group-1\",\n \"count\": 2,\n \"image\": \"polkadot-debug:master\",\n \"command\": \"polkadot\",\n \"args\": [\"--chain\", \"rococo-local\"]\n }\n ],\n \"...\": {}\n },\n \"...\": {}\n }\n\n ```"} +{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Run a Parachain Network", "index": 11, "depth": 3, "title": "Parachain Configuration", "anchor": "parachain-configuration", "start_char": 28546, "end_char": 39719, "estimated_token_count": 2716, "token_estimator": "heuristic-v1", "text": "### Parachain Configuration\n\nThe `parachain` keyword defines further parameters for the parachain. The available keys are:\n\n- **`id`** ++\"number\"++: The id to assign to this parachain. Must be unique.\n- **`chain?`** ++\"string\"++: The chain name.\n- **`force_decorator?`** ++\"string\"++: Force the use of a specific decorator.\n- **`genesis?`** ++\"JSON\"++: The genesis configuration.\n- **`balance?`** ++\"number\"++: Balance to set in balances for parachain's account.\n- **`delay_network_settings?`** ++\"DelayNetworkSettings\"++: Sets the expected configuration to delay the network.\n\n ??? child \"`DelayNetworkSettings` interface definition\"\n ```js\n export interface DelayNetworkSettings {\n latency: string;\n correlation?: string; // should be parsable as float by k8s\n jitter?: string;\n }\n ```\n\n- **`add_to_genesis?`** ++\"boolean\"++: Flag to add parachain to genesis or register in runtime. Defaults to `true`.\n- **`register_para?`** ++\"boolean\"++: Flag to specify whether the para should be registered. The `add_to_genesis` flag must be set to false for this flag to have any effect. Defaults to `true`.\n- **`onboard_as_parachain?`** ++\"boolean\"++: Flag to specify whether the para should be onboarded as a parachain, rather than remaining a parathread. Defaults to `true`.\n- **`genesis_wasm_path?`** ++\"string\"++: Path to the Wasm file to use.\n- **`genesis_wasm_generator?`** ++\"string\"++: Command to generate the Wasm file.\n- **`genesis_state_path?`** ++\"string\"++: Path to the state file to use.\n- **`genesis_state_generator?`** ++\"string\"++: Command to generate the state file.\n- **`chain_spec_path?`** ++\"string\"++: Path to the chain spec file.\n- **`chain_spec_command?`** ++\"string\"++: Command to generate the chain spec.\n- **`cumulus_based?`** ++\"boolean\"++: Flag to use cumulus command generation. Defaults to `true`.\n- **`bootnodes?`** ++\"string[]\"++: Array of bootnodes to use.\n- **`prometheus_prefix?`** ++\"string\"++: Parameter for customizing the metric's prefix for all parachain nodes/collators. Defaults to `substrate`.\n- **`collator?`** ++\"Collator\"++: Further defined in the [Collator Configuration](#collator-configuration) section.\n- **`collator_groups?`** ++\"CollatorGroup[]\"++: An array of collator groups to spawn. It is further defined in the [Collator Groups Configuration](#collator-groups-configuration) section.\n \nFor example, the following configuration file defines a minimal example for the parachain:\n\n=== \"TOML\"\n\n ```toml title=\"parachain-example.toml\"\n [parachain]\n id = 100\n add_to_genesis = true\n cumulus_based = true\n genesis_wasm_path = \"INSERT_PATH_TO_WASM\"\n genesis_state_path = \"INSERT_PATH_TO_STATE\"\n # ...\n\n ```\n\n=== \"JSON\"\n\n ```json title=\"parachain-example.json\"\n {\n \"parachain\": {\n \"id\": 100,\n \"add_to_genesis\": true,\n \"cumulus_based\": true,\n \"genesis_wasm_path\": \"INSERT_PATH_TO_WASM\",\n \"genesis_state_path\": \"INSERT_PATH_TO_STATE\",\n \"...\": {}\n },\n \"...\": {}\n }\n\n ```\n\n#### Collator Configuration\n\nOne specific key capable of receiving more subkeys is the `collator` key. This key defines further parameters for the nodes. The available keys are:\n\n- **`name`** ++\"string\"++: Name of the collator. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`).\n- **`image?`** ++\"string\"++: Image to use for the collator.\n- **`command_with_args?`** ++\"string\"++: Overrides both command and arguments for the collator.\n- **`validator`** ++\"boolean\"++: Pass the `--validator` flag to the command. Defaults to `true`.\n- **`invulnerable`** ++\"boolean\"++: If true, add the collator to invulnerables in the chain spec. Defaults to `false`.\n- **`balance`** ++\"number\"++: Balance to set in balances for collator's account. Defaults to `2000000000000`.\n- **`bootnodes?`** ++\"string[]\"++: Array of bootnodes to use.\n- **`add_to_bootnodes?`** ++\"boolean\"++: Add this collator to the bootnode list. Defaults to `false`.\n- **`ws_port?`** ++\"number\"++: WS port to use.\n- **`rpc_port?`** ++\"number\"++: RPC port to use.\n- **`prometheus_port?`** ++\"number\"++: Prometheus port to use.\n- **`p2p_port?`** ++\"number\"++: P2P port to use.\n- **`p2p_cert_hash?`** ++\"string\"++: Libp2p certhash to use with webRTC transport.\n- **`delay_network_settings?`** ++\"DelayNetworkSettings\"++: Sets the expected configuration to delay the network.\n\n ??? child \"`DelayNetworkSettings` interface definition\"\n ```js\n export interface DelayNetworkSettings {\n latency: string;\n correlation?: string; // should be parsable as float by k8s\n jitter?: string;\n }\n ```\n\n- **`command?`** ++\"string\"++: Override default command to run.\n- **`args?`** ++\"string[]\"++: Arguments to be passed to the command.\n- **`env?`** ++\"envVars[]\"++: Environment variables to set in the container.\n\n ??? child \"`envVars` interface definition\"\n ```js\n export interface EnvVars {\n name: string;\n value: string;\n }\n ```\n\n- **`overrides?`** ++\"Override[]\"++: Array of overrides definitions.\n\n ??? child \"`Override` interface definition\"\n ```js\n export interface Override {\n local_path: string;\n remote_name: string;\n }\n ```\n\n- **`prometheus_prefix?`** ++\"string\"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`.\n- **`db_snapshot?`** ++\"string\"++: Database snapshot to use.\n- **`substrate_cli_args_version?`** ++\"SubstrateCliArgsVersion\"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead.\n\n ??? child \"`SubstrateCliArgsVersion` enum definition\"\n ```js\n export enum SubstrateCliArgsVersion {\n V0 = 0,\n V1 = 1,\n V2 = 2,\n V3 = 3,\n }\n ```\n\n- **`resources?`** ++\"Resources\"++: Represent the resources limits/reservations needed by the node.\n\n ??? child \"`Resources` interface definition\"\n ```js\n export interface Resources {\n resources: {\n requests?: {\n memory?: string;\n cpu?: string;\n };\n limits?: {\n memory?: string;\n cpu?: string;\n };\n };\n }\n ```\n\n- **`keystore_key_types?`** ++\"string[]\"++: Defines which keystore keys should be created.\n\nThe configuration file below defines a minimal example for the collator:\n\n=== \"TOML\"\n\n ```toml title=\"collator-example.toml\"\n [parachain]\n id = 100\n add_to_genesis = true\n cumulus_based = true\n genesis_wasm_path = \"INSERT_PATH_TO_WASM\"\n genesis_state_path = \"INSERT_PATH_TO_STATE\"\n\n [[parachain.collators]]\n name = \"alice\"\n image = \"polkadot-parachain\"\n command = \"polkadot-parachain\"\n # ...\n\n ```\n\n=== \"JSON\"\n\n ```json title=\"collator-example.json\"\n {\n \"parachain\": {\n \"id\": 100,\n \"add_to_genesis\": true,\n \"cumulus_based\": true,\n \"genesis_wasm_path\": \"INSERT_PATH_TO_WASM\",\n \"genesis_state_path\": \"INSERT_PATH_TO_STATE\",\n \"collators\": [\n {\n \"name\": \"alice\",\n \"image\": \"polkadot-parachain\",\n \"command\": \"polkadot-parachain\",\n \"...\": {}\n }\n ]\n },\n \"...\": {}\n }\n\n ```\n\n#### Collator Groups Configuration\n\nThe `collator_groups` key defines further parameters for the collator groups. The available keys are:\n\n- **`name`** ++\"string\"++: Name of the node. Any whitespace will be replaced with a dash (for example, `new alice` will be converted to `new-alice`).\n- **`image?`** ++\"string\"++: Override default Docker image to use for this node.\n- **`command?`** ++\"string\"++: Override default command to run.\n- **`args?`** ++\"string[]\"++: Arguments to be passed to the command.\n- **`env?`** ++\"envVars[]\"++: Environment variables to set in the container.\n\n ??? child \"`envVars` interface definition\"\n ```js\n export interface EnvVars {\n name: string;\n value: string;\n }\n ```\n\n- **`overrides?`** ++\"Override[]\"++: Array of overrides definitions.\n\n ??? child \"`Override` interface definition\"\n ```js\n export interface Override {\n local_path: string;\n remote_name: string;\n }\n ```\n\n- **`prometheus_prefix?`** ++\"string\"++: Customizes the metric's prefix for the specific node. Defaults to `substrate`.\n- **`db_snapshot?`** ++\"string\"++: Database snapshot to use.\n- **`substrate_cli_args_version?`** ++\"SubstrateCliArgsVersion\"++: Set the Substrate CLI arguments version directly to skip binary evaluation overhead.\n\n ??? child \"`SubstrateCliArgsVersion` enum definition\"\n ```js\n export enum SubstrateCliArgsVersion {\n V0 = 0,\n V1 = 1,\n V2 = 2,\n V3 = 3,\n }\n ```\n\n- **`resources?`** ++\"Resources\"++: Represent the resources limits/reservations needed by the node.\n\n ??? child \"`Resources` interface definition\"\n ```js\n export interface Resources {\n resources: {\n requests?: {\n memory?: string;\n cpu?: string;\n };\n limits?: {\n memory?: string;\n cpu?: string;\n };\n };\n }\n ```\n\n- **`keystore_key_types?`** ++\"string[]\"++: Defines which keystore keys should be created.\n- **`count`** ++\"number | string\"++: Number of nodes to launch for this group.\n- **`delay_network_settings?`** ++\"DelayNetworkSettings\"++: Sets the expected configuration to delay the network.\n\n ??? child \"`DelayNetworkSettings` interface definition\"\n ```js\n export interface DelayNetworkSettings {\n latency: string;\n correlation?: string; // should be parsable as float by k8s\n jitter?: string;\n }\n ```\n\nFor instance, the configuration file below defines a minimal example for the collator groups:\n\n=== \"TOML\"\n\n ```toml title=\"collator-groups-example.toml\"\n [parachain]\n id = 100\n add_to_genesis = true\n cumulus_based = true\n genesis_wasm_path = \"INSERT_PATH_TO_WASM\"\n genesis_state_path = \"INSERT_PATH_TO_STATE\"\n\n [[parachain.collator_groups]]\n name = \"group-1\"\n count = 2\n image = \"polkadot-parachain\"\n command = \"polkadot-parachain\"\n # ...\n\n ```\n\n=== \"JSON\"\n\n ```json title=\"collator-groups-example.json\"\n {\n \"parachain\": {\n \"id\": 100,\n \"add_to_genesis\": true,\n \"cumulus_based\": true,\n \"genesis_wasm_path\": \"INSERT_PATH_TO_WASM\",\n \"genesis_state_path\": \"INSERT_PATH_TO_STATE\",\n \"collator_groups\": [\n {\n \"name\": \"group-1\",\n \"count\": 2,\n \"image\": \"polkadot-parachain\",\n \"command\": \"polkadot-parachain\",\n \"...\": {}\n }\n ]\n },\n \"...\": {}\n }\n\n ```"} +{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Run a Parachain Network", "index": 12, "depth": 3, "title": "XCM Configuration", "anchor": "xcm-configuration", "start_char": 39719, "end_char": 40650, "estimated_token_count": 206, "token_estimator": "heuristic-v1", "text": "### XCM Configuration\n\nYou can use the `hrmp_channels` keyword to define further parameters for the XCM channels at start-up. The available keys are:\n\n- **`hrmp_channels`** ++\"HrmpChannelsConfig[]\"++: Array of Horizontal Relay-routed Message Passing (HRMP) channel configurations.\n\n ??? child \"`HrmpChannelsConfig` interface definition\"\n ```js\n export interface HrmpChannelsConfig {\n sender: number;\n recipient: number;\n max_capacity: number;\n max_message_size: number;\n }\n ```\n Each of the `HrmpChannelsConfig` keys are defined as follows:\n\n - **`sender` ++\"number\"++**: Parachain ID of the sender.\n - **`recipient` ++\"number\"++**: Parachain ID of the recipient.\n - **`max_capacity` ++\"number\"++**: Maximum capacity of the HRMP channel.\n - **`max_message_size` ++\"number\"++**: Maximum message size allowed in the HRMP channel."} +{"page_id": "parachains-testing-run-a-parachain-network", "page_title": "Run a Parachain Network", "index": 13, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 40650, "end_char": 41664, "estimated_token_count": 254, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\n
\n\n- External __Zombienet Support__\n\n ---\n\n [Parity Technologies](https://www.parity.io/){target=\\_blank} has designed and developed this framework, now maintained by the Zombienet team. \n\n For further support and information, refer to the following contact points:\n\n [:octicons-arrow-right-24: Zombienet repository](https://github.com/paritytech/zombienet){target=\\_blank}\n\n [:octicons-arrow-right-24: Element public channel](https://matrix.to/#/!FWyuEyNvIFygLnWNMh:parity.io?via=parity.io&via=matrix.org&via=web3.foundation){target=\\_blank}\n\n\n- Tutorial __Spawn a Basic Chain with Zombienet__\n\n ---\n\n Learn to spawn, connect to and monitor a basic blockchain network with Zombienet, using customizable configurations for streamlined development and debugging.\n\n [:octicons-arrow-right-24: Reference](/tutorials/polkadot-sdk/testing/spawn-basic-chain/)\n\n
"} {"page_id": "smart-contracts-connect", "page_title": "Connect to Polkadot", "index": 0, "depth": 2, "title": "Networks Details", "anchor": "networks-details", "start_char": 951, "end_char": 1604, "estimated_token_count": 137, "token_estimator": "heuristic-v1", "text": "## Networks Details\n\nDevelopers can leverage smart contracts across diverse networks, from TestNets to MainNet. This section outlines the network specifications and connection details for each environment.\n\n=== \"Polkadot Hub TestNet\"\n\n Network name\n\n ```text\n Polkadot Hub TestNet\n ```\n\n ---\n\n Currency symbol\n \n ```text\n PAS\n ```\n\n ---\n \n Chain ID\n \n ```text\n 420420422\n ```\n\n ---\n \n RPC URL\n \n ```text\n https://testnet-passet-hub-eth-rpc.polkadot.io\n ```\n\n ---\n \n Block explorer URL\n \n ```text\n https://blockscout-passet-hub.parity-testnet.parity.io/\n ```"} {"page_id": "smart-contracts-connect", "page_title": "Connect to Polkadot", "index": 1, "depth": 2, "title": "Test Tokens", "anchor": "test-tokens", "start_char": 1604, "end_char": 2618, "estimated_token_count": 233, "token_estimator": "heuristic-v1", "text": "## Test Tokens\n\nYou will need testnet tokens to perform transactions and engage with smart contracts on any chain. Here's how to obtain Paseo (PAS) tokens for testing purposes:\n\n1. Navigate to the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\\_blank}. If the desired network is not already selected, choose it from the Network drop-down.\n\n2. Copy your address linked to the TestNet and paste it into the designated field.\n\n ![](/images/smart-contracts/connect/connect-to-polkadot-01.webp)\n\n3. Click the **Get Some PASs** button to request free test PAS tokens. These tokens will be sent to your wallet shortly.\n\n ![](/images/smart-contracts/connect/connect-to-polkadot-02.webp)\n\nNow that you have obtained PAS tokens in your wallet, you’re ready to deploy and interact with smart contracts on Polkadot Hub TestNet! These tokens will allow you to pay for gas fees when executing transactions, deploying contracts, and testing your dApp functionality in a secure testnet environment."} {"page_id": "smart-contracts-connect", "page_title": "Connect to Polkadot", "index": 2, "depth": 2, "title": "Where to Go Next", "anchor": "where-to-go-next", "start_char": 2618, "end_char": 3459, "estimated_token_count": 188, "token_estimator": "heuristic-v1", "text": "## Where to Go Next\n\nFor your next steps, explore the various smart contract guides demonstrating how to use and integrate different tools and development environments into your workflow.\n\n
\n\n- Guide __Deploy your first contract with Remix__\n\n ---\n\n Explore the smart contract development and deployment process on Polkadot Hub using the Remix IDE.\n\n [:octicons-arrow-right-24: Build with Remix IDE](/smart-contracts/dev-environments/remix/get-started/)\n\n- Guide __Interact with the blockchain with viem__\n\n ---\n\n Use viem for interacting with Ethereum-compatible chains, to deploy and interact with smart contracts on Polkadot Hub.\n\n [:octicons-arrow-right-24: Build with viem](/smart-contracts/libraries/viem/)\n\n
"} @@ -868,7 +402,7 @@ {"page_id": "smart-contracts-cookbook-dapps-zero-to-hero", "page_title": "Zero to Hero Smart Contract DApp", "index": 6, "depth": 3, "title": "Compile the Contract", "anchor": "compile-the-contract", "start_char": 5430, "end_char": 5579, "estimated_token_count": 29, "token_estimator": "heuristic-v1", "text": "### Compile the Contract\n\nCompile your Storage contract:\n\n```bash\nnpx hardhat compile\n```\n\nYou should see output indicating successful compilation."} {"page_id": "smart-contracts-cookbook-dapps-zero-to-hero", "page_title": "Zero to Hero Smart Contract DApp", "index": 7, "depth": 3, "title": "Deploy the Contract", "anchor": "deploy-the-contract", "start_char": 5579, "end_char": 7216, "estimated_token_count": 416, "token_estimator": "heuristic-v1", "text": "### Deploy the Contract\n\nCreate a deployment script in the `ignition/modules` directory called `Storage.ts`:\n\n```typescript title=\"Storage.ts\"\nimport { buildModule } from \"@nomicfoundation/hardhat-ignition/modules\";\n\nexport default buildModule(\"StorageModule\", (m) => {\n const storage = m.contract(\"Storage\");\n\n return { storage };\n});\n```\n\nDeploy the contract to Polkadot Hub TestNet:\n\n```bash\nnpx hardhat ignition deploy ./ignition/modules/Storage.ts --network polkadotTestNet\n```\n\nYou should see output similar to:\n\n
\n npx hardhat ignition deploy ./ignition/modules/Storage.ts --network polkadotTestNet\n WARNING: You are using Node.js 23.11.0 which is not supported by Hardhat.\n Please upgrade to 22.10.0 or a later LTS version (even major version number)\n ✔ Confirm deploy to network polkadotTestNet (420420420)? … yes\n Hardhat Ignition 🚀\n Deploying [ StorageModule ]\n Batch #1\n Executed StorageModule#Storage\n [ StorageModule ] successfully deployed 🚀\n Deployed Addresses\n StorageModule#Storage - 0xc01Ee7f10EA4aF4673cFff62710E1D7792aBa8f3\n
\n\n!!! note\n Save the deployed contract address - you'll need it when building your dApp. In the following sections, we'll reference a pre-deployed contract at `0xc01Ee7f10EA4aF4673cFff62710E1D7792aBa8f3`, but you can use your own deployed contract address instead."} {"page_id": "smart-contracts-cookbook-dapps-zero-to-hero", "page_title": "Zero to Hero Smart Contract DApp", "index": 8, "depth": 3, "title": "Export the Contract ABI", "anchor": "export-the-contract-abi", "start_char": 7216, "end_char": 7603, "estimated_token_count": 89, "token_estimator": "heuristic-v1", "text": "### Export the Contract ABI\n\nAfter deployment, you'll need the contract's Application Binary Interface (ABI) for your dApp. You can find it in the `artifacts/contracts/Storage.sol/Storage.json` file generated by Hardhat. You'll use this in the next section when setting up your dApp.\n\nNow that you have your contract deployed, you're ready to build the dApp that will interact with it!"} -{"page_id": "smart-contracts-cookbook-dapps-zero-to-hero", "page_title": "Zero to Hero Smart Contract DApp", "index": 9, "depth": 2, "title": "Set Up the dApp Project", "anchor": "set-up-the-dapp-project", "start_char": 7603, "end_char": 7800, "estimated_token_count": 59, "token_estimator": "heuristic-v1", "text": "## Set Up the dApp Project\n\nNavigate to the root of the project, and create a new Next.js project called `dapp`:\n\n```bash\nnpx create-next-app dapp --ts --eslint --tailwind --app --yes\ncd dapp\n```"} +{"page_id": "smart-contracts-cookbook-dapps-zero-to-hero", "page_title": "Zero to Hero Smart Contract DApp", "index": 9, "depth": 2, "title": "Set Up the DApp Project", "anchor": "set-up-the-dapp-project", "start_char": 7603, "end_char": 7800, "estimated_token_count": 59, "token_estimator": "heuristic-v1", "text": "## Set Up the DApp Project\n\nNavigate to the root of the project, and create a new Next.js project called `dapp`:\n\n```bash\nnpx create-next-app dapp --ts --eslint --tailwind --app --yes\ncd dapp\n```"} {"page_id": "smart-contracts-cookbook-dapps-zero-to-hero", "page_title": "Zero to Hero Smart Contract DApp", "index": 10, "depth": 2, "title": "Install Dependencies", "anchor": "install-dependencies", "start_char": 7800, "end_char": 7959, "estimated_token_count": 50, "token_estimator": "heuristic-v1", "text": "## Install Dependencies\n\nInstall viem and related packages:\n\n```bash\nnpm install viem@2.38.5\nnpm install --save-dev typescript@5.9.3 @types/node@22.19.24\n```"} {"page_id": "smart-contracts-cookbook-dapps-zero-to-hero", "page_title": "Zero to Hero Smart Contract DApp", "index": 11, "depth": 2, "title": "Connect to Polkadot Hub", "anchor": "connect-to-polkadot-hub", "start_char": 7959, "end_char": 10056, "estimated_token_count": 509, "token_estimator": "heuristic-v1", "text": "## Connect to Polkadot Hub\n\nTo interact with Polkadot Hub, you need to set up a [Public Client](https://viem.sh/docs/clients/public#public-client){target=\\_blank} that connects to the blockchain. In this example, you will interact with the Polkadot Hub TestNet, to experiment safely. Start by creating a new file called `utils/viem.ts` and add the following code:\n\n```typescript title=\"viem.ts\"\nimport { createPublicClient, http, createWalletClient, custom } from 'viem'\nimport 'viem/window';\n\nconst transport = http('http://127.0.0.1:8545') // TODO: change to the paseo asset hub RPC URL when it's available\n\n// Configure the Polkadot Testnet Hub chain\nexport const polkadotTestnet = {\n id: 420420420,\n name: 'Polkadot Testnet',\n network: 'polkadot-testnet',\n nativeCurrency: {\n decimals: 18,\n name: 'PAS',\n symbol: 'PAS',\n },\n rpcUrls: {\n default: {\n http: ['http://127.0.0.1:8545'], // TODO: change to the paseo asset hub RPC URL\n },\n },\n} as const\n\n// Create a public client for reading data\nexport const publicClient = createPublicClient({\n chain: polkadotTestnet,\n transport\n})\n\n// Create a wallet client for signing transactions\nexport const getWalletClient = async () => {\n if (typeof window !== 'undefined' && window.ethereum) {\n const [account] = await window.ethereum.request({ method: 'eth_requestAccounts' });\n return createWalletClient({\n chain: polkadotTestnet,\n transport: custom(window.ethereum),\n account,\n });\n }\n throw new Error('No Ethereum browser provider detected');\n};\n```\n\nThis file initializes a viem client, providing helper functions for obtaining a Public Client and a [Wallet Client](https://viem.sh/docs/clients/wallet#wallet-client){target=\\_blank}. The Public Client enables reading blockchain data, while the Wallet Client allows users to sign and send transactions. Also, note that by importing `viem/window` the global `window.ethereum` will be typed as an `EIP1193Provider`, check the [`window` Polyfill](https://viem.sh/docs/typescript#window-polyfill){target=\\_blank} reference for more information."} {"page_id": "smart-contracts-cookbook-dapps-zero-to-hero", "page_title": "Zero to Hero Smart Contract DApp", "index": 12, "depth": 2, "title": "Set Up the Smart Contract Interface", "anchor": "set-up-the-smart-contract-interface", "start_char": 10056, "end_char": 11947, "estimated_token_count": 415, "token_estimator": "heuristic-v1", "text": "## Set Up the Smart Contract Interface\n\nFor this dApp, you'll use a simple [Storage contract](/tutorials/smart-contracts/launch-your-first-project/create-contracts){target=\\_blank} that's already deployed in the Polkadot Hub TestNet: `0xc01Ee7f10EA4aF4673cFff62710E1D7792aBa8f3`. To interact with it, you need to define the contract interface.\n\nCreate a folder called `abis` at the root of your project, then create a file named `Storage.json` and paste the corresponding ABI of the Storage contract. You can copy and paste the following:\n\n```bash\ncp ./storage-contract/artifacts/contracts/Storage.sol/Storage.json ./dapp/abis/Storage.json\n```\n\nNext, create a file called `utils/contract.ts`:\n\n```typescript title=\"contract.ts\"\nimport { getContract } from 'viem';\nimport { publicClient, getWalletClient } from './viem';\nimport StorageABI from '../abis/Storage.json';\n\nexport const CONTRACT_ADDRESS = '0xc01Ee7f10EA4aF4673cFff62710E1D7792aBa8f3'; // TODO: change when the paseo asset hub RPC URL is available, and the contract is redeployed\nexport const CONTRACT_ABI = StorageABI.abi;\n\n// Create a function to get a contract instance for reading\nexport const getContractInstance = () => {\n return getContract({\n address: CONTRACT_ADDRESS,\n abi: CONTRACT_ABI,\n client: publicClient,\n });\n};\n\n// Create a function to get a contract instance with a signer for writing\nexport const getSignedContract = async () => {\n const walletClient = await getWalletClient();\n return getContract({\n address: CONTRACT_ADDRESS,\n abi: CONTRACT_ABI,\n client: walletClient,\n });\n};\n```\n\nThis file defines the contract address, ABI, and functions to create a viem [contract instance](https://viem.sh/docs/contract/getContract#contract-instances){target=\\_blank} for reading and writing operations. viem's contract utilities enable more efficient, type-safe interaction with smart contracts."} @@ -1013,9 +547,9 @@ {"page_id": "smart-contracts-explorers", "page_title": "Block Explorers", "index": 1, "depth": 2, "title": "Core Functionality", "anchor": "core-functionality", "start_char": 497, "end_char": 1187, "estimated_token_count": 139, "token_estimator": "heuristic-v1", "text": "## Core Functionality\n\nThese block explorers provide essential capabilities for interacting with smart contracts in Polkadot Hub:\n\n- **Transaction tracking**: Monitor transaction status, confirmations, fees, and metadata.\n- **Address analysis**: View account balances, transaction history, and associated contracts.\n- **Block information**: Examine block contents.\n- **Smart contract interaction**: Review contract code, verification status, and interaction history.\n- **Token tracking**: Monitor ERC-20, ERC-721, and other token standards with transfer history and holder analytics.\n- **Network statistics**: Access metrics on transaction volume, gas usage, and other network parameters."} {"page_id": "smart-contracts-explorers", "page_title": "Block Explorers", "index": 2, "depth": 2, "title": "Available Block Explorers", "anchor": "available-block-explorers", "start_char": 1187, "end_char": 1399, "estimated_token_count": 30, "token_estimator": "heuristic-v1", "text": "## Available Block Explorers\n\nThe following block explorers are available for PolkaVM smart contracts, providing specialized tools for monitoring and analyzing contract activity within the Polkadot ecosystem:"} {"page_id": "smart-contracts-explorers", "page_title": "Block Explorers", "index": 3, "depth": 3, "title": "BlockScout", "anchor": "blockscout", "start_char": 1399, "end_char": 1793, "estimated_token_count": 91, "token_estimator": "heuristic-v1", "text": "### BlockScout\n\nBlockScout is an open-source explorer platform with a user-friendly interface adapted for PolkaVM contracts. It excels at detailed contract analytics and provides developers with comprehensive API access.\n\n- [Polkadot Hub TestNet BlockScout](https://blockscout-passet-hub.parity-testnet.parity.io/){target=\\_blank}\n\n![](/images/smart-contracts/explorers/block-explorers-2.webp)"} -{"page_id": "smart-contracts-faucet", "page_title": "Faucet", "index": 0, "depth": 2, "title": "Get Test Tokens", "anchor": "get-test-tokens", "start_char": 473, "end_char": 1160, "estimated_token_count": 182, "token_estimator": "heuristic-v1", "text": "## Get Test Tokens\n\nFor Polkadot Hub TestNet, you can use the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\\_blank} to obtain test tokens. Here's how to do it:\n\n1. Navigate to the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\\_blank}. If the desired network is not already selected, choose it from the **Network** drop-down. This example uses the Polkadot Hub TestNet.\n2. Copy your address linked to the TestNet and paste it into the designated field.\n3. Click the **Get Some PASs** button to request free test PAS tokens. These tokens will be sent to your wallet shortly.\n\n![Polkadot Faucet](/images/smart-contracts/faucet/faucet-1.gif)"} -{"page_id": "smart-contracts-faucet", "page_title": "Faucet", "index": 1, "depth": 2, "title": "Things to Consider", "anchor": "things-to-consider", "start_char": 1160, "end_char": 1584, "estimated_token_count": 79, "token_estimator": "heuristic-v1", "text": "## Things to Consider\n\n!!! info \"Rate Limiting\"\n Faucets typically implement rate limiting to prevent abuse. You may need to wait between requests if you've recently obtained tokens from the same faucet.\n\n!!! warning \"Network Compatibility\"\n Ensure your wallet is connected to the correct network (Polkadot Hub TestNet) before requesting tokens. Tokens sent to addresses on different networks will not be accessible."} -{"page_id": "smart-contracts-faucet", "page_title": "Faucet", "index": 2, "depth": 2, "title": "Using Your Test Tokens", "anchor": "using-your-test-tokens", "start_char": 1584, "end_char": 1890, "estimated_token_count": 52, "token_estimator": "heuristic-v1", "text": "## Using Your Test Tokens\n\nGetting started with test tokens is the first step in your Polkadot development journey. These free resources enable you to build, experiment with, and refine your applications without financial constraints, ensuring your projects are robust and ready for deployment on MainNet."} +{"page_id": "smart-contracts-faucet", "page_title": "Get Tokens from the Official Faucet", "index": 0, "depth": 2, "title": "Get Test Tokens", "anchor": "get-test-tokens", "start_char": 473, "end_char": 1160, "estimated_token_count": 182, "token_estimator": "heuristic-v1", "text": "## Get Test Tokens\n\nFor Polkadot Hub TestNet, you can use the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\\_blank} to obtain test tokens. Here's how to do it:\n\n1. Navigate to the [Polkadot Faucet](https://faucet.polkadot.io/?parachain=1111){target=\\_blank}. If the desired network is not already selected, choose it from the **Network** drop-down. This example uses the Polkadot Hub TestNet.\n2. Copy your address linked to the TestNet and paste it into the designated field.\n3. Click the **Get Some PASs** button to request free test PAS tokens. These tokens will be sent to your wallet shortly.\n\n![Polkadot Faucet](/images/smart-contracts/faucet/faucet-1.gif)"} +{"page_id": "smart-contracts-faucet", "page_title": "Get Tokens from the Official Faucet", "index": 1, "depth": 2, "title": "Things to Consider", "anchor": "things-to-consider", "start_char": 1160, "end_char": 1584, "estimated_token_count": 79, "token_estimator": "heuristic-v1", "text": "## Things to Consider\n\n!!! info \"Rate Limiting\"\n Faucets typically implement rate limiting to prevent abuse. You may need to wait between requests if you've recently obtained tokens from the same faucet.\n\n!!! warning \"Network Compatibility\"\n Ensure your wallet is connected to the correct network (Polkadot Hub TestNet) before requesting tokens. Tokens sent to addresses on different networks will not be accessible."} +{"page_id": "smart-contracts-faucet", "page_title": "Get Tokens from the Official Faucet", "index": 2, "depth": 2, "title": "Using Your Test Tokens", "anchor": "using-your-test-tokens", "start_char": 1584, "end_char": 1890, "estimated_token_count": 52, "token_estimator": "heuristic-v1", "text": "## Using Your Test Tokens\n\nGetting started with test tokens is the first step in your Polkadot development journey. These free resources enable you to build, experiment with, and refine your applications without financial constraints, ensuring your projects are robust and ready for deployment on MainNet."} {"page_id": "smart-contracts-for-eth-devs-accounts", "page_title": "Accounts in Asset Hub Smart Contracts", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 211, "end_char": 1055, "estimated_token_count": 149, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nAsset Hub natively utilizes Polkadot's 32-byte account system while providing interoperability with Ethereum's 20-byte addresses through an automatic conversion system. When interacting with smart contracts:\n\n- Ethereum-compatible wallets (like MetaMask) can use their familiar 20-byte addresses.\n- Polkadot accounts continue using their native 32-byte format.\n- The Asset Hub chain automatically handles conversion between the two formats behind the scenes:\n\n - 20-byte Ethereum addresses are padded with `0xEE` bytes to create valid 32-byte Polkadot accounts.\n - 32-byte Polkadot accounts can optionally register a mapping to a 20-byte address for Ethereum compatibility.\n\nThis dual-format approach enables Asset Hub to maintain compatibility with Ethereum tooling while fully integrating with the Polkadot ecosystem."} {"page_id": "smart-contracts-for-eth-devs-accounts", "page_title": "Accounts in Asset Hub Smart Contracts", "index": 1, "depth": 2, "title": "Address Types and Mappings", "anchor": "address-types-and-mappings", "start_char": 1055, "end_char": 1352, "estimated_token_count": 77, "token_estimator": "heuristic-v1", "text": "## Address Types and Mappings\n\nThe platform handles two distinct address formats:\n\n- [Ethereum-style addresses (20 bytes)](https://ethereum.org/developers/docs/accounts/#account-creation){target=\\_blank}\n- [Polkadot native account IDs (32 bytes)](/reference/parachains/accounts/){target=\\_blank}"} {"page_id": "smart-contracts-for-eth-devs-accounts", "page_title": "Accounts in Asset Hub Smart Contracts", "index": 2, "depth": 3, "title": "Ethereum to Polkadot Mapping", "anchor": "ethereum-to-polkadot-mapping", "start_char": 1352, "end_char": 2397, "estimated_token_count": 237, "token_estimator": "heuristic-v1", "text": "### Ethereum to Polkadot Mapping\n\nThe [`AccountId32Mapper`](https://paritytech.github.io/polkadot-sdk/master/pallet_revive/struct.AccountId32Mapper.html){target=\\_blank} implementation in [`pallet_revive`](https://paritytech.github.io/polkadot-sdk/master/pallet_revive/index.html){target=\\_blank} handles the core address conversion logic. For converting a 20-byte Ethereum address to a 32-byte Polkadot address, the pallet uses a simple concatenation approach:\n\n- [**Core mechanism**](https://paritytech.github.io/polkadot-sdk/master/pallet_revive/trait.AddressMapper.html#tymethod.to_fallback_account_id){target=\\_blank}: Takes a 20-byte Ethereum address and extends it to 32 bytes by adding twelve `0xEE` bytes at the end. The key benefits of this approach are:\n - Able to fully revert, allowing a smooth transition back to the Ethereum format.\n - Provides clear identification of Ethereum-controlled accounts through the `0xEE` suffix pattern.\n - Maintains cryptographic security with a `2^96` difficulty for pattern reproduction."} @@ -1052,13 +586,13 @@ {"page_id": "smart-contracts-for-eth-devs-dual-vm-stack", "page_title": "Dual Virtual Machine Stack", "index": 4, "depth": 3, "title": "Revive Pallet", "anchor": "revive-pallet", "start_char": 2844, "end_char": 4123, "estimated_token_count": 232, "token_estimator": "heuristic-v1", "text": "### Revive Pallet\n\n[**`pallet_revive`**](https://paritytech.github.io/polkadot-sdk/master/pallet_revive/index.html){target=\\_blank} is a runtime module that executes smart contracts by adding extrinsics, runtime APIs, and logic to convert Ethereum-style transactions into formats compatible with Polkadot SDK-based blockchains. It processes Ethereum-style transactions through the following workflow:\n\n```mermaid\nsequenceDiagram\n participant User as User/dApp\n participant Proxy as Ethereum JSON RPC Proxy\n participant Chain as Blockchain Node\n participant Pallet as pallet_revive\n \n User->>Proxy: Submit Ethereum Transaction\n Proxy->>Chain: Repackage as Polkadot Compatible Transaction\n Chain->>Pallet: Process Transaction\n Pallet->>Pallet: Decode Ethereum Transaction\n Pallet->>Pallet: Execute Contract via PolkaVM\n Pallet->>Chain: Return Results\n Chain->>Proxy: Forward Results\n Proxy->>User: Return Ethereum-compatible Response\n```\n\nThis proxy-based approach eliminates the need for node binary modifications, maintaining compatibility across different client implementations. Preserving the original Ethereum transaction payload simplifies the adaptation of existing tools, which can continue processing familiar transaction formats."} {"page_id": "smart-contracts-for-eth-devs-dual-vm-stack", "page_title": "Dual Virtual Machine Stack", "index": 5, "depth": 3, "title": "PolkaVM Design Fundamentals", "anchor": "polkavm-design-fundamentals", "start_char": 4123, "end_char": 5067, "estimated_token_count": 185, "token_estimator": "heuristic-v1", "text": "### PolkaVM Design Fundamentals\n\nPolkaVM differs from the EVM in two key ways that make it faster, more hardware-efficient, and easier to extend:\n\n- **Register-based design**: Instead of a stack machine, PolkaVM uses a RISC-V–style register model. This design:\n\n - Uses a fixed set of registers to pass arguments, not an infinite stack.\n - Maps cleanly to real hardware like x86-64.\n - Simplifies compilation and boosts runtime efficiency.\n - Enables tighter control over register allocation and performance tuning.\n\n- **64-bit word size**: PolkaVM runs on a native 64-bit word size, aligning directly with modern CPUs. This design:\n\n - Executes arithmetic operations with direct hardware support.\n - Maintains compatibility with Solidity’s 256-bit types via YUL translation.\n - Accelerates computation-heavy workloads through native word alignment.\n - Integrates easily with low-level, performance-focused components."} {"page_id": "smart-contracts-for-eth-devs-dual-vm-stack", "page_title": "Dual Virtual Machine Stack", "index": 6, "depth": 2, "title": "Where To Go Next", "anchor": "where-to-go-next", "start_char": 5067, "end_char": 5383, "estimated_token_count": 82, "token_estimator": "heuristic-v1", "text": "## Where To Go Next\n\n
\n\n- Learn __Contract Deployment__\n\n ---\n\n Learn how REVM and PVM compare for compiling and deploying smart contracts.\n\n [:octicons-arrow-right-24: Reference](/smart-contracts/for-eth-devs/contract-deployment/)\n\n
"} -{"page_id": "smart-contracts-for-eth-devs-gas-model", "page_title": "Gas Model on the Polkadot Hub", "index": 0, "depth": 2, "title": "Overview", "anchor": "overview", "start_char": 13, "end_char": 290, "estimated_token_count": 49, "token_estimator": "heuristic-v1", "text": "## Overview\n\nThe Polkadot Hub implements a gas model that bridges Ethereum's familiar gas concept with Polkadot's more sophisticated resource metering system. This page explains how gas works in the Polkadot Hub and what developers need to know when building smart contracts."} -{"page_id": "smart-contracts-for-eth-devs-gas-model", "page_title": "Gas Model on the Polkadot Hub", "index": 1, "depth": 2, "title": "Understanding Resources in the Polkadot Hub", "anchor": "understanding-resources-in-the-polkadot-hub", "start_char": 290, "end_char": 1290, "estimated_token_count": 189, "token_estimator": "heuristic-v1", "text": "## Understanding Resources in the Polkadot Hub\n\nUnlike Ethereum, which uses a single gas value to measure everything, the Polkadot Hub tracks three separate resources:\n\n- **`ref_time`**: Measures computational time. It is the closest equivalent to traditional gas and represents the amount of CPU time your contract execution consumes.\n- **`proof_size`**: Measures the amount of state data that validators need to verify. When your contract reads from storage or makes state queries, this metric tracks the size of the proofs needed to validate those operations.\n- **`storage_deposit`**: Is a native balance that gets temporarily locked when your contract creates new storage entries. This prevents state bloat by requiring contracts to pay for the storage they use. The deposit is returned when the storage is freed.\n\nFor Ethereum wallet compatibility, the Polkadot Hub's RPC layer automatically maps these three dimensions into a single gas value that wallets can understand and display to users."} -{"page_id": "smart-contracts-for-eth-devs-gas-model", "page_title": "Gas Model on the Polkadot Hub", "index": 2, "depth": 2, "title": "Gas vs Weight", "anchor": "gas-vs-weight", "start_char": 1290, "end_char": 1706, "estimated_token_count": 80, "token_estimator": "heuristic-v1", "text": "## Gas vs Weight\n\nWhen you interact with the Polkadot Hub through an Ethereum wallet, you see familiar gas values. Under the hood, the runtime works with `weight` - a two-dimensional metric that combines `ref_time` and `proof_size`.\n\nThe system continuously translates between these representations: converting `weight` to gas when estimating costs, and converting gas back to `weight` when executing transactions."} -{"page_id": "smart-contracts-for-eth-devs-gas-model", "page_title": "Gas Model on the Polkadot Hub", "index": 3, "depth": 2, "title": "How Gas Estimation Works", "anchor": "how-gas-estimation-works", "start_char": 1706, "end_char": 2547, "estimated_token_count": 163, "token_estimator": "heuristic-v1", "text": "## How Gas Estimation Works\n\nWhen your wallet requests a gas estimate (`eth_estimateGas`), the Polkadot Hub performs a dry-run of your transaction. This test execution discovers:\n\n- How much computational time the contract will consume (`ref_time`).\n- How much state data needs to be verified (`proof_size`).\n- Whether any storage deposits are required (`storage_deposit`).\n\nThe system then calculates a gas estimate that covers all these costs, including:\n\n- Base transaction overhead (intrinsic costs like signature verification, nonce/account checks, and dispatch setup).\n- Transaction length fees (charges for the transaction size in bytes).\n- The actual contract execution costs.\n- Any storage deposits.\n\nThe gas estimate also includes a small safety buffer to account for slight differences between the test run and actual execution."} -{"page_id": "smart-contracts-for-eth-devs-gas-model", "page_title": "Gas Model on the Polkadot Hub", "index": 4, "depth": 2, "title": "Dynamic Gas Pricing", "anchor": "dynamic-gas-pricing", "start_char": 2547, "end_char": 3440, "estimated_token_count": 161, "token_estimator": "heuristic-v1", "text": "## Dynamic Gas Pricing\n\nPallet revive uses dynamic pricing through a \"fee multiplier\" that adjusts based on network congestion:\n\n- When blocks are full, the multiplier increases, making transactions more expensive.\n- When blocks are empty, the multiplier decreases, making transactions cheaper.\n- The multiplier updates after every block based on utilization.\n\nThis creates a market-based pricing mechanism similar to Ethereum's base fee, helping to manage network resources efficiently.\n\nThe gas price returned during estimation is simply the current fee multiplier value.\n\n!!! warning \"Important for Users\"\n Because the fee multiplier can change between when you estimate gas and when your transaction executes, you can add a safety buffer (10-20%) to both your gas limit and gas price. This ensures your transaction will execute successfully even if network conditions change slightly."} -{"page_id": "smart-contracts-for-eth-devs-gas-model", "page_title": "Gas Model on the Polkadot Hub", "index": 5, "depth": 2, "title": "Transaction Execution Flow", "anchor": "transaction-execution-flow", "start_char": 3440, "end_char": 4936, "estimated_token_count": 353, "token_estimator": "heuristic-v1", "text": "## Transaction Execution Flow\n\nThe following diagram illustrates the complete lifecycle of a transaction from submission to settlement:\n\n```mermaid\ngraph TD\n U[User/Wallet] --> M[Transaction pool]\n M --> P[Pre-dispatch convert gas to weight and create hold]\n P --> C{Sufficient funds}\n C -->|No| R[Rejected]\n C -->|Yes| X[Execute contract within limits]\n X --> S[Settle fee from actual weight and length; refund]\n S --> B[Included in block]\n```\n\nThe transaction execution flow is as follows:\n\n- **Pool and pre-dispatch**: The transaction enters the pool, `gas` is mapped to `weight`, and a temporary hold is created for the maximum fee exposure. Weight is a two-dimensional tuple (`ref_time`, `proof_size`). Each dimension is tracked independently. The [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\\_blank} conversion takes the maximum of the two dimensions (after applying their respective coefficients) to determine the fee.\n- **Funds check**: If the hold is insufficient, the transaction is rejected before any execution.\n- **Execution**: If sufficient, the contract runs within the derived weight limits; a `storage_deposit` may be reserved when new storage is created.\n- **Settlement**: Fees are charged from the actual `weight` used plus the length fee; any unused hold is refunded.\n- **Inclusion**: After settlement, the transaction is included in the block."} -{"page_id": "smart-contracts-for-eth-devs-gas-model", "page_title": "Gas Model on the Polkadot Hub", "index": 6, "depth": 2, "title": "Conclusion", "anchor": "conclusion", "start_char": 4936, "end_char": 5234, "estimated_token_count": 51, "token_estimator": "heuristic-v1", "text": "## Conclusion\n\nThe Polkadot Hub's gas model is designed to be Ethereum-compatible while providing the flexibility and efficiency of Polkadot's resource metering system. Developers can build on Ethereum tooling while leveraging Polkadot's advanced features like multi-dimensional resource tracking."} +{"page_id": "smart-contracts-for-eth-devs-gas-model", "page_title": "Gas Model on the Polkadot Hub", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 13, "end_char": 294, "estimated_token_count": 49, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nThe Polkadot Hub implements a gas model that bridges Ethereum's familiar gas concept with Polkadot's more sophisticated resource metering system. This page explains how gas works in the Polkadot Hub and what developers need to know when building smart contracts."} +{"page_id": "smart-contracts-for-eth-devs-gas-model", "page_title": "Gas Model on the Polkadot Hub", "index": 1, "depth": 2, "title": "Understanding Resources in the Polkadot Hub", "anchor": "understanding-resources-in-the-polkadot-hub", "start_char": 294, "end_char": 1294, "estimated_token_count": 189, "token_estimator": "heuristic-v1", "text": "## Understanding Resources in the Polkadot Hub\n\nUnlike Ethereum, which uses a single gas value to measure everything, the Polkadot Hub tracks three separate resources:\n\n- **`ref_time`**: Measures computational time. It is the closest equivalent to traditional gas and represents the amount of CPU time your contract execution consumes.\n- **`proof_size`**: Measures the amount of state data that validators need to verify. When your contract reads from storage or makes state queries, this metric tracks the size of the proofs needed to validate those operations.\n- **`storage_deposit`**: Is a native balance that gets temporarily locked when your contract creates new storage entries. This prevents state bloat by requiring contracts to pay for the storage they use. The deposit is returned when the storage is freed.\n\nFor Ethereum wallet compatibility, the Polkadot Hub's RPC layer automatically maps these three dimensions into a single gas value that wallets can understand and display to users."} +{"page_id": "smart-contracts-for-eth-devs-gas-model", "page_title": "Gas Model on the Polkadot Hub", "index": 2, "depth": 2, "title": "Gas vs Weight", "anchor": "gas-vs-weight", "start_char": 1294, "end_char": 1710, "estimated_token_count": 80, "token_estimator": "heuristic-v1", "text": "## Gas vs Weight\n\nWhen you interact with the Polkadot Hub through an Ethereum wallet, you see familiar gas values. Under the hood, the runtime works with `weight` - a two-dimensional metric that combines `ref_time` and `proof_size`.\n\nThe system continuously translates between these representations: converting `weight` to gas when estimating costs, and converting gas back to `weight` when executing transactions."} +{"page_id": "smart-contracts-for-eth-devs-gas-model", "page_title": "Gas Model on the Polkadot Hub", "index": 3, "depth": 2, "title": "How Gas Estimation Works", "anchor": "how-gas-estimation-works", "start_char": 1710, "end_char": 2551, "estimated_token_count": 163, "token_estimator": "heuristic-v1", "text": "## How Gas Estimation Works\n\nWhen your wallet requests a gas estimate (`eth_estimateGas`), the Polkadot Hub performs a dry-run of your transaction. This test execution discovers:\n\n- How much computational time the contract will consume (`ref_time`).\n- How much state data needs to be verified (`proof_size`).\n- Whether any storage deposits are required (`storage_deposit`).\n\nThe system then calculates a gas estimate that covers all these costs, including:\n\n- Base transaction overhead (intrinsic costs like signature verification, nonce/account checks, and dispatch setup).\n- Transaction length fees (charges for the transaction size in bytes).\n- The actual contract execution costs.\n- Any storage deposits.\n\nThe gas estimate also includes a small safety buffer to account for slight differences between the test run and actual execution."} +{"page_id": "smart-contracts-for-eth-devs-gas-model", "page_title": "Gas Model on the Polkadot Hub", "index": 4, "depth": 2, "title": "Dynamic Gas Pricing", "anchor": "dynamic-gas-pricing", "start_char": 2551, "end_char": 3444, "estimated_token_count": 161, "token_estimator": "heuristic-v1", "text": "## Dynamic Gas Pricing\n\nPallet revive uses dynamic pricing through a \"fee multiplier\" that adjusts based on network congestion:\n\n- When blocks are full, the multiplier increases, making transactions more expensive.\n- When blocks are empty, the multiplier decreases, making transactions cheaper.\n- The multiplier updates after every block based on utilization.\n\nThis creates a market-based pricing mechanism similar to Ethereum's base fee, helping to manage network resources efficiently.\n\nThe gas price returned during estimation is simply the current fee multiplier value.\n\n!!! warning \"Important for Users\"\n Because the fee multiplier can change between when you estimate gas and when your transaction executes, you can add a safety buffer (10-20%) to both your gas limit and gas price. This ensures your transaction will execute successfully even if network conditions change slightly."} +{"page_id": "smart-contracts-for-eth-devs-gas-model", "page_title": "Gas Model on the Polkadot Hub", "index": 5, "depth": 2, "title": "Transaction Execution Flow", "anchor": "transaction-execution-flow", "start_char": 3444, "end_char": 4940, "estimated_token_count": 353, "token_estimator": "heuristic-v1", "text": "## Transaction Execution Flow\n\nThe following diagram illustrates the complete lifecycle of a transaction from submission to settlement:\n\n```mermaid\ngraph TD\n U[User/Wallet] --> M[Transaction pool]\n M --> P[Pre-dispatch convert gas to weight and create hold]\n P --> C{Sufficient funds}\n C -->|No| R[Rejected]\n C -->|Yes| X[Execute contract within limits]\n X --> S[Settle fee from actual weight and length; refund]\n S --> B[Included in block]\n```\n\nThe transaction execution flow is as follows:\n\n- **Pool and pre-dispatch**: The transaction enters the pool, `gas` is mapped to `weight`, and a temporary hold is created for the maximum fee exposure. Weight is a two-dimensional tuple (`ref_time`, `proof_size`). Each dimension is tracked independently. The [`WeightToFee`](https://docs.rs/pallet-transaction-payment/latest/pallet_transaction_payment/pallet/trait.Config.html#associatedtype.WeightToFee){target=\\_blank} conversion takes the maximum of the two dimensions (after applying their respective coefficients) to determine the fee.\n- **Funds check**: If the hold is insufficient, the transaction is rejected before any execution.\n- **Execution**: If sufficient, the contract runs within the derived weight limits; a `storage_deposit` may be reserved when new storage is created.\n- **Settlement**: Fees are charged from the actual `weight` used plus the length fee; any unused hold is refunded.\n- **Inclusion**: After settlement, the transaction is included in the block."} +{"page_id": "smart-contracts-for-eth-devs-gas-model", "page_title": "Gas Model on the Polkadot Hub", "index": 6, "depth": 2, "title": "Conclusion", "anchor": "conclusion", "start_char": 4940, "end_char": 5238, "estimated_token_count": 51, "token_estimator": "heuristic-v1", "text": "## Conclusion\n\nThe Polkadot Hub's gas model is designed to be Ethereum-compatible while providing the flexibility and efficiency of Polkadot's resource metering system. Developers can build on Ethereum tooling while leveraging Polkadot's advanced features like multi-dimensional resource tracking."} {"page_id": "smart-contracts-for-eth-devs-json-rpc-apis", "page_title": "JSON-RPC APIs", "index": 0, "depth": 2, "title": "Introduction", "anchor": "introduction", "start_char": 187, "end_char": 679, "estimated_token_count": 115, "token_estimator": "heuristic-v1", "text": "## Introduction\n\nPolkadot Hub provides Ethereum compatibility through its JSON-RPC interface, allowing developers to interact with the chain using familiar Ethereum tooling and methods. This document outlines the supported [Ethereum JSON-RPC methods](https://ethereum.org/developers/docs/apis/json-rpc/#json-rpc-methods){target=\\_blank} and provides examples of how to use them.\n\nThis guide uses the Polkadot Hub TestNet endpoint:\n\n```text\nhttps://testnet-passet-hub-eth-rpc.polkadot.io\n```"} {"page_id": "smart-contracts-for-eth-devs-json-rpc-apis", "page_title": "JSON-RPC APIs", "index": 1, "depth": 2, "title": "Available Methods", "anchor": "available-methods", "start_char": 679, "end_char": 701, "estimated_token_count": 4, "token_estimator": "heuristic-v1", "text": "## Available Methods"} {"page_id": "smart-contracts-for-eth-devs-json-rpc-apis", "page_title": "JSON-RPC APIs", "index": 2, "depth": 3, "title": "eth_accounts", "anchor": "eth_accounts", "start_char": 701, "end_char": 1132, "estimated_token_count": 146, "token_estimator": "heuristic-v1", "text": "### eth_accounts\n\nReturns a list of addresses owned by the client. [Reference](https://ethereum.org/developers/docs/apis/json-rpc/#eth_accounts){target=\\_blank}.\n\n**Parameters**:\n\nNone.\n\n**Example**:\n\n```bash title=\"eth_accounts\"\ncurl -X POST https://testnet-passet-hub-eth-rpc.polkadot.io \\\n-H \"Content-Type: application/json\" \\\n--data '{\n \"jsonrpc\":\"2.0\",\n \"method\":\"eth_accounts\",\n \"params\":[],\n \"id\":1\n}'\n```\n\n---"} diff --git a/llms.txt b/llms.txt index 485efb239..79e3f1ff7 100644 --- a/llms.txt +++ b/llms.txt @@ -6,36 +6,19 @@ This directory lists URLs for raw Markdown pages that complement the rendered pages on the documentation site. Use these Markdown files to retain semantic context when prompting models while avoiding passing HTML elements. ## Metadata -- Documentation pages: 145 -- Categories: 13 +- Documentation pages: 88 +- Categories: 11 ## Docs This section lists documentation pages by category. Each entry links to a raw markdown version of the page and includes a short description. A page may appear in multiple categories. Docs: Basics -- [Register a Local Asset](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-token-operations-register-local-asset.md): Comprehensive guide to registering a local asset on the Asset Hub system parachain, including step-by-step instructions. - [Add Pallets to the Runtime](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime-pallet-development-add-pallet-to-runtime.md): Add pallets to your runtime for custom functionality. Learn to configure and integrate pallets in Polkadot SDK-based blockchains. - [Overview of FRAME](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-customize-runtime.md): Learn how Polkadot SDK’s FRAME framework simplifies blockchain development with modular pallets and support libraries for efficient runtime design. - [Get Started with Parachain Development](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-get-started.md): Practical examples and tutorials for building and deploying Polkadot parachains, covering everything from launch to customization and cross-chain messaging. - [Install Polkadot SDK](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-install-polkadot-sdk.md): Install all required Polkadot SDK dependencies, set up the SDK itself, and verify that it runs correctly on your machine. -- [Introduction to XCM](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md): Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. +- [Get Started with XCM](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md): Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. - [Set Up the Polkadot SDK Parachain Template](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-launch-a-parachain-set-up-the-parachain-template.md): Learn how to set up and run the Polkadot SDK Parachain Template locally, creating a ready-to-customize foundation for your parachain. -- [On-Chain Governance Overview](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-governance.md): Discover Polkadot’s cutting-edge OpenGov system, enabling transparent, decentralized decision-making through direct democracy and flexible governance tracks. -- [Polkadot SDK Accounts](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-accounts.md): Learn about account structures, balances, and address formats in the Polkadot SDK, including how to manage lifecycle, references, and balances. -- [Blocks](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-blocks.md): Understand how blocks are produced, validated, and imported in Polkadot SDK-based blockchains, covering initialization, finalization, and authoring processes. -- [Transactions Weights and Fees](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-fees.md): Overview of transaction weights and fees in Polkadot SDK chains, detailing how fees are calculated using a defined formula and runtime specifics. -- [Transactions](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-transactions.md): Learn how to construct, submit, and validate transactions in the Polkadot SDK, covering signed, unsigned, and inherent types of transactions. -- [Chain Data](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-chain-data.md): Learn how to expose and utilize chain data for blockchain applications. Discover runtime metadata, RPC APIs, and tools for efficient development. -- [Cryptography](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-cryptography.md): A concise guide to cryptography in blockchain, covering hash functions, encryption types, digital signatures, and elliptic curve applications. -- [Data Encoding](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-data-encoding.md): SCALE codec enables fast, efficient data encoding, ideal for resource-constrained environments like Wasm, supporting custom types and compact encoding. -- [Interoperability](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-interoperability.md): Explore the importance of interoperability in the Polkadot ecosystem, covering XCM, bridges, and cross-chain communication. -- [Networks](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-networks.md): Explore Polkadot's testing and production networks, including Westend, Kusama, and Paseo, for efficient development, deployment, and testing. -- [Node and Runtime](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-node-and-runtime.md): Learn how Polkadot SDK-based nodes function, how the client and runtime are separated, and how they communicate using SCALE-encoded data. -- [Randomness](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-randomness.md): Explore the importance of randomness in PoS blockchains, focusing on Polkadot’s VRF-based approach to ensure fairness and security in validator selection. -- [Parachains Overview](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains.md): Learn about parachains, specialized blockchains on Polkadot that gain shared security and interoperability. Discover how they work and the tools to build them. -- [Overview of the Polkadot Relay Chain](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-relay-chain.md): Explore Polkadot's core architecture, including its multi-chain vision, shared security, and the DOT token's governance and staking roles. -- [XCM Tools](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-xcm-tools.md): Explore essential XCM tools across Polkadot, crafted to enhance cross-chain functionality and integration within the ecosystem. -- [Technical Reference Overview](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference.md): Learn about Polkadot's technical architecture, governance framework, parachain ecosystem, and the tools you need to build and interact with the network. - [Deploy an ERC-20 to Polkadot Hub](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-erc20-erc20-hardhat.md): Deploy an ERC-20 token on Polkadot Hub using PolkaVM. This guide covers contract creation, compilation, deployment, and interaction via Hardhat. - [Deploy an ERC-20 to Polkadot Hub](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-erc20-erc20-remix.md): Deploy an ERC-20 token contract on Polkadot Hub. This guide covers contract creation, compilation, deployment, and interaction via the Remix IDE. - [Deploy an NFT to Polkadot Hub with Foundry](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-smart-contracts-deploy-nft-.foundry.md): Learn how to deploy an ERC-721 NFT contract to Polkadot Hub using Foundry, a Rust toolkit with high-performance compilation. @@ -67,7 +50,7 @@ Docs: Smart Contracts - [Use the Remix IDE on Polkadot Hub](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-remix-get-started.md): Explore the smart contract development and deployment process on Polkadot Hub using Remix IDE, a visual IDE for blockchain developers. - [Troubleshooting Remix IDE](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-remix-troubleshooting-faq.md): Common issues related to developing, compiling, and deploying smart contracts using Remix IDE on Polkadot Hub paired with troubleshooting suggestions. - [Block Explorers](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-explorers.md): Access PolkaVM explorers like Subscan, BlockScout, and Routescan to track transactions, analyze contracts, and view on-chain data from smart contracts. -- [Faucet](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-faucet.md): Learn how to obtain test tokens from Polkadot faucets for development and testing purposes across different networks. +- [Get Tokens from the Official Faucet](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-faucet.md): Learn how to obtain test tokens from Polkadot faucets for development and testing purposes across different networks. - [Contract Deployment](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-contract-deployment.md): Compare deployment flows for REVM and PVM-based smart contracts on the Polkadot Hub. Includes single-step REVM flows and PVM’s two-step deployment model. - [Migration FAQs and Considerations](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-migration.md): Learn how to migrate your existing Ethereum contracts to the Polkadot Hub using REVM and PolkaVM by following these considerations. - [Get Started with Smart Contracts](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-get-started.md): Practical examples for building and deploying smart contracts on Polkadot Hub, from connecting and tooling to deployment, integrations, and precompiles. @@ -100,48 +83,15 @@ Docs: Parachains - [Runtime Upgrades](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-runtime-maintenance-runtime-upgrades.md): This page covers how runtime versioning and storage migration support forkless upgrades for Polkadot SDK-based networks and how they factor into chain upgrades. - [Storage Migrations](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-runtime-maintenance-storage-migrations.md): Ensure smooth runtime upgrades with storage migrations, update data formats, and prevent errors. Learn when and how to implement migrations efficiently. - [Unlock a Parachain](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-runtime-maintenance-unlock-parachains.md): Learn how to unlock your parachain. This step-by-step guide covers verifying lock status, preparing calls, and executing the unlock process. -- [Get Started](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-fork-a-parachain.md): Simplify Polkadot SDK development with Chopsticks. Learn essential features, how to install Chopsticks, and how to configure local blockchain forks. -- [Get Started](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-run-a-parachain-network.md): Quickly install and configure Zombienet to deploy and test Polkadot-based blockchain networks with this comprehensive getting-started guide. -- [Parachains Overview](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains.md): Learn about parachains, specialized blockchains on Polkadot that gain shared security and interoperability. Discover how they work and the tools to build them. -- [Overview of the Polkadot Relay Chain](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-relay-chain.md): Explore Polkadot's core architecture, including its multi-chain vision, shared security, and the DOT token's governance and staking roles. -- [Light Clients](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-light-clients.md): Light clients enable secure and efficient blockchain interaction without running a full node. Learn everything you need to know about light clients on Polkadot. -- [E2E Testing with Moonwall](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-moonwall.md): Enhance blockchain end-to-end testing with Moonwall's standardized environment setup, comprehensive configuration management, and simple network interactions. -- [Polkadot Omni Node](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-omninode.md): Run parachain nodes easily with the polkadot-omni-node, a white-labeled binary that can run parachain nodes using a single pre-built solution. +- [Fork a Parachain Using Chopsticks](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-fork-a-parachain.md): Simplify Polkadot SDK development with Chopsticks. Learn essential features, how to install Chopsticks, and how to configure local blockchain forks. +- [Run a Parachain Network](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-run-a-parachain-network.md): Quickly install and configure Zombienet to deploy and test Polkadot-based blockchain networks with this comprehensive getting-started guide. Docs: dApps -- [Convert Assets on Asset Hub](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-token-operations-convert-assets.md): A guide detailing the step-by-step process of converting assets on Asset Hub, helping users efficiently navigate asset management on the platform. -- [Register a Foreign Asset on Asset Hub](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-token-operations-register-foreign-asset.md): An in-depth guide to registering a foreign asset on the Asset Hub parachain, providing clear, step-by-step instructions. -- [Register a Local Asset](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-token-operations-register-local-asset.md): Comprehensive guide to registering a local asset on the Asset Hub system parachain, including step-by-step instructions. - [Deploying Uniswap V2 on Polkadot](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-eth-dapps-uniswap-v2.md): Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. - [Smart Contracts Cookbook Index](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook.md): Explore our full collection of tutorials and guides to learn step-by-step how to build, deploy, and work with smart contracts on Polkadot. -Docs: Networks -- [Networks](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-networks.md): Explore Polkadot's testing and production networks, including Westend, Kusama, and Paseo, for efficient development, deployment, and testing. - Docs: Polkadot Protocol -- [Introduction to XCM](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md): Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. -- [Origins and Tracks](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-governance-origins-tracks.md): Explore Polkadot's OpenGov origins and tracks system, defining privilege levels, decision processes, and tailored pathways for network proposals. -- [On-Chain Governance Overview](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-governance.md): Discover Polkadot’s cutting-edge OpenGov system, enabling transparent, decentralized decision-making through direct democracy and flexible governance tracks. -- [Polkadot SDK Accounts](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-accounts.md): Learn about account structures, balances, and address formats in the Polkadot SDK, including how to manage lifecycle, references, and balances. -- [Blocks](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-blocks.md): Understand how blocks are produced, validated, and imported in Polkadot SDK-based blockchains, covering initialization, finalization, and authoring processes. -- [Transactions Weights and Fees](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-fees.md): Overview of transaction weights and fees in Polkadot SDK chains, detailing how fees are calculated using a defined formula and runtime specifics. -- [Transactions](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-blocks-transactions-fees-transactions.md): Learn how to construct, submit, and validate transactions in the Polkadot SDK, covering signed, unsigned, and inherent types of transactions. -- [Chain Data](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-chain-data.md): Learn how to expose and utilize chain data for blockchain applications. Discover runtime metadata, RPC APIs, and tools for efficient development. -- [Elastic Scaling](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-consensus-elastic-scaling.md): Learn how elastic scaling in Polkadot boosts parachain throughput, reduces latency, and supports dynamic, cost-efficient resource allocation. -- [Cryptography](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-cryptography.md): A concise guide to cryptography in blockchain, covering hash functions, encryption types, digital signatures, and elliptic curve applications. -- [Data Encoding](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-data-encoding.md): SCALE codec enables fast, efficient data encoding, ideal for resource-constrained environments like Wasm, supporting custom types and compact encoding. -- [Interoperability](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-interoperability.md): Explore the importance of interoperability in the Polkadot ecosystem, covering XCM, bridges, and cross-chain communication. -- [Networks](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-networks.md): Explore Polkadot's testing and production networks, including Westend, Kusama, and Paseo, for efficient development, deployment, and testing. -- [Node and Runtime](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-node-and-runtime.md): Learn how Polkadot SDK-based nodes function, how the client and runtime are separated, and how they communicate using SCALE-encoded data. -- [Randomness](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-randomness.md): Explore the importance of randomness in PoS blockchains, focusing on Polkadot’s VRF-based approach to ensure fairness and security in validator selection. -- [Asset Hub](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-assets-and-smart-contracts.md): Learn about Asset Hub in Polkadot, managing on-chain assets, foreign asset integration, and using XCM for cross-chain asset transfers. -- [Bridge Hub](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-bridging.md): Learn about the Bridge Hub system parachain, a parachain that facilitates the interactions from Polkadot to the rest of Web3. -- [Collectives Chain](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-collectives-and-daos.md): Learn how the Collectives chain provides infrastructure for governance organizations, enabling decentralized network stewardship and decision-making. -- [Agile Coretime](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-agile-coretime.md): Explore the efficient scheduling mechanisms to access Polkadot cores to produce blockspace continuously or on-demand. -- [Proof of Stake Consensus](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-pos-consensus.md): Explore Polkadot's consensus protocols for secure, scalable, and decentralized network operation, including NPoS, BABE, GRANDPA, and BEEFY. -- [Overview of the Polkadot Relay Chain](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-consensus-and-security-relay-chain.md): Explore Polkadot's core architecture, including its multi-chain vision, shared security, and the DOT token's governance and staking roles. -- [People Chain](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub-people-and-identity.md): Learn how People chain secures decentralized identity management, empowering users to control and verify digital identities without central authorities. -- [Technical Reference Overview](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference.md): Learn about Polkadot's technical architecture, governance framework, parachain ecosystem, and the tools you need to build and interact with the network. +- [Get Started with XCM](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-interoperability-get-started.md): Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. - [Accounts in Asset Hub Smart Contracts](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-accounts.md): Bridges Ethereum's 20-byte addresses with Polkadot's 32-byte accounts, enabling seamless interaction while maintaining compatibility with Ethereum tooling. - [Transactions and Fees on Asset Hub](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-blocks-transactions-fees.md): Explore how Asset Hub smart contracts handle blocks, transactions, and fees with EVM compatibility, supporting various Ethereum transaction types. - [Dual Virtual Machine Stack](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-dual-vm-stack.md): Compare Polkadot’s dual smart contract VMs—REVM for EVM compatibility and PolkaVM for RISC-V performance, flexibility, and efficiency. @@ -166,19 +116,8 @@ Docs: Tooling - [Indexers](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-indexers.md): Discover blockchain indexers. Enhance data access, enable fast and complex queries, and optimize blockchain data for seamless app performance. - [Oracles](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-oracles.md): Learn about blockchain oracles, the essential bridges connecting blockchains with real-world data for decentralized applications in the Polkadot ecosystem. - [Wallets](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-wallets.md): Explore blockchain wallets. Securely manage digital assets with hot wallets for online access or cold wallets for offline, enhanced security. -- [Get Started](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-fork-a-parachain.md): Simplify Polkadot SDK development with Chopsticks. Learn essential features, how to install Chopsticks, and how to configure local blockchain forks. -- [Get Started](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-run-a-parachain-network.md): Quickly install and configure Zombienet to deploy and test Polkadot-based blockchain networks with this comprehensive getting-started guide. -- [Dedot](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-dedot.md): Dedot is a next-gen JavaScript client for Polkadot and Polkadot SDK-based blockchains, offering lightweight, tree-shakable APIs with strong TypeScript support. -- [Light Clients](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-light-clients.md): Light clients enable secure and efficient blockchain interaction without running a full node. Learn everything you need to know about light clients on Polkadot. -- [E2E Testing with Moonwall](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-moonwall.md): Enhance blockchain end-to-end testing with Moonwall's standardized environment setup, comprehensive configuration management, and simple network interactions. -- [Polkadot Omni Node](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-omninode.md): Run parachain nodes easily with the polkadot-omni-node, a white-labeled binary that can run parachain nodes using a single pre-built solution. -- [Polkadot-API](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-papi.md): Polkadot-API (PAPI) is a modular, composable library set designed for efficient interaction with Polkadot chains, prioritizing a "light-client first" approach. -- [Polkadart](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-polkadart.md): Polkadart is a type-safe, native Dart, SDK for Polkadot and any compatible Polkadot-SDK blockchain network. -- [Polkadot.js API](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-polkadot-js-api.md): Interact with Polkadot SDK-based chains easily using the Polkadot.js API. Query chain data, submit transactions, and more via JavaScript or Typescript. -- [Python Substrate Interface](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-py-substrate-interface.md): Learn how to connect to Polkadot SDK-based nodes, query data, submit transactions, and manage blockchain interactions using the Python Substrate Interface. -- [Sidecar REST API](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-sidecar.md): Learn about Substrate API Sidecar, a REST service that provides endpoints for interacting with Polkadot SDK-based chains and simplifies blockchain interactions. -- [Subxt Rust API](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-subxt.md): Subxt is a Rust library for type-safe interaction with Polkadot SDK blockchains, enabling transactions, state queries, runtime API access, and more. -- [XCM Tools](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-xcm-tools.md): Explore essential XCM tools across Polkadot, crafted to enhance cross-chain functionality and integration within the ecosystem. +- [Fork a Parachain Using Chopsticks](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-fork-a-parachain.md): Simplify Polkadot SDK development with Chopsticks. Learn essential features, how to install Chopsticks, and how to configure local blockchain forks. +- [Run a Parachain Network](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-testing-run-a-parachain-network.md): Quickly install and configure Zombienet to deploy and test Polkadot-based blockchain networks with this comprehensive getting-started guide. - [Zero to Hero Smart Contract DApp](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-dapps-zero-to-hero.md): Learn how to build a decentralized application on Polkadot Hub using Viem and Next.js by creating a simple dApp that interacts with a smart contract. - [Deploying Uniswap V2 on Polkadot](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-cookbook-eth-dapps-uniswap-v2.md): Learn how to deploy and test Uniswap V2 on Polkadot Hub using Hardhat, bringing AMM-based token swaps to the Polkadot ecosystem. - [Use Hardhat with Polkadot Hub](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-hardhat-get-started.md): Overview of Hardhat, a powerful development environment for creating, compiling, testing, and deploying smart contracts on Polkadot Hub. @@ -194,58 +133,27 @@ Docs: Tooling - [Web3.py](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-libraries-web3-py.md): Learn how to interact with Polkadot Hub using the Web3 python library, deploying Solidity contracts, and interacting with deployed smart contracts. Docs: Reference -- [Glossary](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-glossary.md): Glossary of terms used within the Polkadot ecosystem, Polkadot SDK, its subsequent libraries, and other relevant Web3 terminology. -- [Technical Reference Overview](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference.md): Learn about Polkadot's technical architecture, governance framework, parachain ecosystem, and the tools you need to build and interact with the network. - [JSON-RPC APIs](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-json-rpc-apis.md): JSON-RPC APIs guide for Polkadot Hub, covering supported methods, parameters, and examples for interacting with the chain. -Docs: Chain Interactions -- [Chain Interactions Overview](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions.md): Learn how to query data, send transactions, enable cross-chain communication, and manage accounts across the Polkadot ecosystem. - Docs: Dapps - [Indexers](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-indexers.md): Discover blockchain indexers. Enhance data access, enable fast and complex queries, and optimize blockchain data for seamless app performance. - [Oracles](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-oracles.md): Learn about blockchain oracles, the essential bridges connecting blockchains with real-world data for decentralized applications in the Polkadot ecosystem. - [Wallets](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/parachains-integrations-wallets.md): Explore blockchain wallets. Securely manage digital assets with hot wallets for online access or cold wallets for offline, enhanced security. -- [Dedot](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-dedot.md): Dedot is a next-gen JavaScript client for Polkadot and Polkadot SDK-based blockchains, offering lightweight, tree-shakable APIs with strong TypeScript support. -- [Polkadot-API](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-papi.md): Polkadot-API (PAPI) is a modular, composable library set designed for efficient interaction with Polkadot chains, prioritizing a "light-client first" approach. -- [Polkadart](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-polkadart.md): Polkadart is a type-safe, native Dart, SDK for Polkadot and any compatible Polkadot-SDK blockchain network. -- [Polkadot.js API](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-polkadot-js-api.md): Interact with Polkadot SDK-based chains easily using the Polkadot.js API. Query chain data, submit transactions, and more via JavaScript or Typescript. -- [Python Substrate Interface](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-py-substrate-interface.md): Learn how to connect to Polkadot SDK-based nodes, query data, submit transactions, and manage blockchain interactions using the Python Substrate Interface. -- [Sidecar REST API](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-sidecar.md): Learn about Substrate API Sidecar, a REST service that provides endpoints for interacting with Polkadot SDK-based chains and simplifies blockchain interactions. -- [Subxt Rust API](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-subxt.md): Subxt is a Rust library for type-safe interaction with Polkadot SDK blockchains, enabling transactions, state queries, runtime API access, and more. -- [XCM Tools](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-xcm-tools.md): Explore essential XCM tools across Polkadot, crafted to enhance cross-chain functionality and integration within the ecosystem. Docs: Uncategorized -- [chain-interactions-accounts-create-account](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-accounts-create-account.md): No description available. -- [chain-interactions-accounts-query-accounts](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-accounts-query-accounts.md): No description available. -- [chain-interactions-query-data-query-rest](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-query-data-query-rest.md): No description available. -- [chain-interactions-query-data-query-sdks](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-query-data-query-sdks.md): No description available. -- [chain-interactions-query-data-runtime-api-calls](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-query-data-runtime-api-calls.md): No description available. -- [chain-interactions-send-transactions-calculate-transaction-fees](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-send-transactions-calculate-transaction-fees.md): No description available. -- [Replay and Dry Run XCMs](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-send-transactions-interoperability-debug-and-preview-xcms.md): Replay and dry-run XCMs using Chopsticks with full logging enabled. Diagnose issues, trace message flow, and debug complex cross-chain interactions. -- [XCM Fee Estimation](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-send-transactions-interoperability-estimate-xcm-fees.md): This tutorial demonstrates how to estimate the fees for teleporting assets from the Paseo Asset Hub parachain to the Paseo Bridge Hub chain. -- [chain-interactions-send-transactions-interoperability-transfer-assets-out-of-polkadot](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-send-transactions-interoperability-transfer-assets-out-of-polkadot.md): No description available. -- [Transfer Assets Between Parachains](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-send-transactions-interoperability-transfer-assets-parachains.md): A step-by-step guide to using the ParaSpell XCM SDK to build, verify, and execute a transfer from one Parachain to another. -- [Send a Transaction While Paying the Fee with a Different Token](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-send-transactions-pay-fees-with-different-tokens.md): This tutorial demonstrates how to send a DOT transfer transaction while paying the fees using a different token on the Asset Hub. -- [chain-interactions-send-transactions-with-sdks](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/chain-interactions-send-transactions-with-sdks.md): No description available. - [AI Ready Docs](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/get-support-ai-ready-docs.md): Download LLM-optimized files of the Polkadot documentation, including full content and category-specific resources for AI agents. - [Subscribe to Updates](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/get-support-explore-resources.md): Find Polkadot developer resources, tutorials, forums, governance proposals, and community platforms like StackExchange, Reddit, and YouTube. - [Get in Touch](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/get-support-get-in-touch.md): Developer support for Polkadot via Telegram, Matrix, and Discord. Get help with parachains, smart contracts, nodes, and ecosystem tools. - [Support](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/get-support.md): Start here to get developer support for Polkadot. Connect with the team, find help, and explore resources beyond the documentation. - [Polkadot Developer Docs](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/index.md): Explore everything you need to start building on top of Polkadot, a protocol that provides parachains with shared security and interoperability using XCM. -- [reference-parachains-consensus-async-backing](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-consensus-async-backing.md): No description available. -- [reference-parachains-consensus](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-parachains-consensus.md): No description available. -- [reference-polkadot-hub](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-polkadot-hub.md): No description available. -- [reference-tools-chopsticks](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-chopsticks.md): No description available. -- [ParaSpell XCM SDK](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-paraspell.md): A powerful open-source library that simplifies XCM integration, enabling developers to easily build interoperable dApps on Polkadot. -- [reference-tools-zombienet](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/reference-tools-zombienet.md): No description available. - [smart-contracts-dev-environments-hardhat-compile-and-test](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-hardhat-compile-and-test.md): No description available. - [smart-contracts-dev-environments-hardhat-deploy-a-contract](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-hardhat-deploy-a-contract.md): No description available. - [smart-contracts-dev-environments-hardhat-install-and-config](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-hardhat-install-and-config.md): No description available. - [smart-contracts-dev-environments-hardhat-troubleshooting](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-hardhat-troubleshooting.md): No description available. - [smart-contracts-dev-environments-hardhat-verify-a-contract](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-dev-environments-hardhat-verify-a-contract.md): No description available. - [Gas Model on the Polkadot Hub](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-for-eth-devs-gas-model.md): Learn how gas estimation, pricing, and weight mapping work in the Polkadot Hub. -- [smart-contracts-integrations-indexers](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-integrations-indexers.md): No description available. -- [smart-contracts-integrations-oracles](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-integrations-oracles.md): No description available. +- [smart-contracts-integrations-.indexers](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-integrations-.indexers.md): No description available. +- [smart-contracts-integrations-.oracles](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-integrations-.oracles.md): No description available. - [Advanced Functionalities via Precompiles](https://raw.githubusercontent.com/polkadot-developers/polkadot-docs/master/.ai/pages/smart-contracts-precompiles.md): Explores how Polkadot integrates precompiles to run essential functions natively, improving the speed and efficiency of smart contracts on the Hub. Docs: dApp diff --git a/nodes-and-validators/run-a-validator/operational-tasks/general-management.md b/nodes-and-validators/run-a-validator/operational-tasks/general-management.md index dd8a19c29..a6752aaa1 100644 --- a/nodes-and-validators/run-a-validator/operational-tasks/general-management.md +++ b/nodes-and-validators/run-a-validator/operational-tasks/general-management.md @@ -3,6 +3,7 @@ title: General Management description: Optimize your Polkadot validator setup with advanced configuration techniques. Learn how to boost performance, enhance security, and ensure seamless operations. categories: Infrastructure --- + # General Management ## Introduction diff --git a/parachains/.nav.yml b/parachains/.nav.yml index a1683dede..63e728a05 100644 --- a/parachains/.nav.yml +++ b/parachains/.nav.yml @@ -3,7 +3,7 @@ nav: - 'Install Polkadot SDK': install-polkadot-sdk.md - 'Launch a Simple Parachain': launch-a-parachain - 'Customize Your Runtime': customize-runtime - - 'Testing': testing - - 'Runtime Upgrades and Maintenance': runtime-maintenance - - 'Interoperability': interoperability + - 'Test Your Runtime': testing + - 'Maintain and Upgrade Your Runtime': runtime-maintenance + - 'Enable Interoperability': interoperability - 'Integrations': integrations diff --git a/parachains/interoperability/get-started.md b/parachains/interoperability/get-started.md index e328f42df..17543f304 100644 --- a/parachains/interoperability/get-started.md +++ b/parachains/interoperability/get-started.md @@ -1,10 +1,10 @@ --- -title: Introduction to XCM +title: Get Started with XCM description: Unlock blockchain interoperability with XCM — Polkadot's Cross-Consensus Messaging format for cross-chain interactions. categories: Basics, Polkadot Protocol --- -# Introduction to XCM +# Get Started with XCM ## Introduction diff --git a/parachains/testing/fork-a-parachain.md b/parachains/testing/fork-a-parachain.md index 7fd1920d4..2a85b81a5 100644 --- a/parachains/testing/fork-a-parachain.md +++ b/parachains/testing/fork-a-parachain.md @@ -1,10 +1,10 @@ --- -title: Get Started +title: Fork a Parachain Using Chopsticks description: Simplify Polkadot SDK development with Chopsticks. Learn essential features, how to install Chopsticks, and how to configure local blockchain forks. categories: Parachains, Tooling --- -# Get Started +# Fork a Parachain Using Chopsticks ## Introduction diff --git a/parachains/testing/run-a-parachain-network.md b/parachains/testing/run-a-parachain-network.md index ff0fc207c..0c1a2a72b 100644 --- a/parachains/testing/run-a-parachain-network.md +++ b/parachains/testing/run-a-parachain-network.md @@ -1,10 +1,10 @@ --- -title: Get Started +title: Run a Parachain Network description: Quickly install and configure Zombienet to deploy and test Polkadot-based blockchain networks with this comprehensive getting-started guide. categories: Parachains, Tooling --- -# Get Started +# Run a Parachain Network Using Zombienet ## Introduction diff --git a/scripts/llms_config.json b/scripts/llms_config.json index 27bee59c4..4b885cd73 100644 --- a/scripts/llms_config.json +++ b/scripts/llms_config.json @@ -42,7 +42,7 @@ "terms-of-use.md", "privacy-policy.md" ], - "skip_paths": [".snippets", ".github", ".ai", ".venv", "venv"] + "skip_paths": [".snippets", ".github", ".ai", ".venv", "venv", ".reference", ".chain-interactions"] } }, diff --git a/smart-contracts/cookbook/.nav.yml b/smart-contracts/cookbook/.nav.yml index 967a352ff..9f8545e2e 100644 --- a/smart-contracts/cookbook/.nav.yml +++ b/smart-contracts/cookbook/.nav.yml @@ -1,6 +1,6 @@ nav: - 'Overview': index.md # TODO: Update name of page - 'Get Tokens from the Faucet': /smart-contracts/faucet/ -- 'EVM Smart Contracts': smart-contracts +- 'Build Smart Contracts': smart-contracts - 'Create a DApp': dapps - 'Port Ethereum DApps': eth-dapps diff --git a/smart-contracts/cookbook/dapps/zero-to-hero.md b/smart-contracts/cookbook/dapps/zero-to-hero.md index d45dc3a05..e1dd0c582 100644 --- a/smart-contracts/cookbook/dapps/zero-to-hero.md +++ b/smart-contracts/cookbook/dapps/zero-to-hero.md @@ -241,7 +241,7 @@ After deployment, you'll need the contract's Application Binary Interface (ABI) Now that you have your contract deployed, you're ready to build the dApp that will interact with it! -## Set Up the dApp Project +## Set Up the DApp Project Navigate to the root of the project, and create a new Next.js project called `dapp`: diff --git a/smart-contracts/faucet.md b/smart-contracts/faucet.md index 11e0eb3d6..39e70f6d2 100644 --- a/smart-contracts/faucet.md +++ b/smart-contracts/faucet.md @@ -1,5 +1,5 @@ --- -title: Faucet +title: Get Tokens from the Official Faucet description: Learn how to obtain test tokens from Polkadot faucets for development and testing purposes across different networks. tutorial_badge: Beginner categories: Smart Contracts diff --git a/smart-contracts/for-eth-devs/gas-model.md b/smart-contracts/for-eth-devs/gas-model.md index acf8a1d5c..a8df19acb 100644 --- a/smart-contracts/for-eth-devs/gas-model.md +++ b/smart-contracts/for-eth-devs/gas-model.md @@ -5,7 +5,7 @@ description: Learn how gas estimation, pricing, and weight mapping work in the P # Gas Model -## Overview +## Introduction The Polkadot Hub implements a gas model that bridges Ethereum's familiar gas concept with Polkadot's more sophisticated resource metering system. This page explains how gas works in the Polkadot Hub and what developers need to know when building smart contracts. diff --git a/smart-contracts/integrations/indexers.md b/smart-contracts/integrations/.indexers.md similarity index 100% rename from smart-contracts/integrations/indexers.md rename to smart-contracts/integrations/.indexers.md diff --git a/smart-contracts/integrations/.nav.yml b/smart-contracts/integrations/.nav.yml index fdae86b87..8e54f1c2c 100644 --- a/smart-contracts/integrations/.nav.yml +++ b/smart-contracts/integrations/.nav.yml @@ -1,4 +1,4 @@ nav: - 'Wallets': wallets.md - - 'Oracles': oracles.md - - 'Indexers': indexers.md +# - 'Oracles': oracles.md +# - 'Indexers': indexers.md diff --git a/smart-contracts/integrations/oracles.md b/smart-contracts/integrations/.oracles.md similarity index 100% rename from smart-contracts/integrations/oracles.md rename to smart-contracts/integrations/.oracles.md