diff --git a/assets/images/Engine State Machine Diagram.png b/assets/images/Engine State Machine Diagram.png deleted file mode 100644 index 8348dd50..00000000 Binary files a/assets/images/Engine State Machine Diagram.png and /dev/null differ diff --git a/assets/images/Engine Timing Diagram.png b/assets/images/Engine Timing Diagram.png deleted file mode 100644 index 00650336..00000000 Binary files a/assets/images/Engine Timing Diagram.png and /dev/null differ diff --git a/assets/images/Project Logo.png b/assets/images/Project Logo.png deleted file mode 100644 index 69d94304..00000000 Binary files a/assets/images/Project Logo.png and /dev/null differ diff --git a/assets/images/explorer.png b/assets/images/explorer.png deleted file mode 100644 index d8970f50..00000000 Binary files a/assets/images/explorer.png and /dev/null differ diff --git a/assets/pdf/HotStuff paper.pdf b/assets/pdf/HotStuff paper.pdf deleted file mode 100644 index 39f0e251..00000000 Binary files a/assets/pdf/HotStuff paper.pdf and /dev/null differ diff --git a/assets/pdf/LibraBFT paper.pdf b/assets/pdf/LibraBFT paper.pdf deleted file mode 100644 index 658dca06..00000000 Binary files a/assets/pdf/LibraBFT paper.pdf and /dev/null differ diff --git a/docs/concepts/account.md b/docs/concepts/account.md deleted file mode 100644 index f5519674..00000000 --- a/docs/concepts/account.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -tags: - - Account - - EOA - - Network Account ---- - -# Accounts - -**Account** is the basic identity of an agent on the blockchain. An account is identified by its address. - -In Parallelchain Mainnet, accounts are divided into two types: - -- __Externally Owned Accounts (EOA)__: The address of an EOA is the public key of the keypair that is compatible with `ed25519_dalek`. -- __Contract Accounts__: A contract account is created from contract deployment. The address is the hash of the concatenation of a contract's bytecode and the nonce of the EOA that deploys the contract. - -Elements inside an account include: - -- **Nonce**: The number of transactions made to the blockchain under this account. -- **Balance**: The balance of the account. - -The followings are elements that only apply to Contract Accounts: - -- **Contract Code**: The binary of the contract that was deployed to the blockchain (applies to Contract Accounts). -- **CBI Version**: The version of the Contract Binary Interface. -- **Storage Hash**: The 32-byte SHA256 root hash of its Storage Trie. This is empty for an External. - -> **Notes**: -> These accounts cannot be distinguished from each other just by looking at the address format. - ---- - -A **Network Account** is a single identified network-wide account that maintains the state of ParallelChain Mainnet. This account is not associated with Ed25519 material. The network-significant data that the Network Account stores are composed of various fields: - -- **Previous Validator Set**: The set of pools that form the validator set in the previous epoch. The stake in this validator set is locked until the next epoch. -- **Current Validator Set**: The set of pools that form the validator set in the current epoch. -- **Next Validator Set**: The limited-size pools with the largest powers. These will become the validator set in the next epoch. -- **Pools**: The set of pools that are accepting stakes and currently competing to become part of the next validator set. -- **Deposits**: The locked balance used to determine the amount of stake that can be contributed to a pool. -- **Current Epoch**: The current epoch number. - diff --git a/docs/concepts/block.md b/docs/concepts/block.md deleted file mode 100644 index 59ccddb5..00000000 --- a/docs/concepts/block.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -tags: - - Block Header ---- - -# Block - -**Block** is a data structure that describes and authorizes the execution of a batch of transactions (state transitions) on the blockchain. - -Elements inside a block include: - -- `Hash` - the unique identifier for the block -- `Height` - a number that represents the position of the block on the blockchain -- `Justify` - a certificate that proves the block was authorized by the network - -- `Chain ID` - a number that identifies a particular Parallelchain Mainnet-based blockchain -- `Proposer` - the public address of the block producer -- `Timestamp` - the time the block was created, measured in seconds since 1970-01-01 -- `Base Fee Per Gas` - the minimum number of grays that a transaction must pay for every gas used to be included in the block -- `Gas Used` - the amount of gas used in a block, which is the total sum of the gas used in executing the included transactions -- `Transactions Hash` - the root hash of the Merkle Tree that contains the transactions included in the block -- `Receipt Hash` - the root hash of the Merkle Tree that contains the execution results of the transactions included in the block -- `State Hash` - the root hash of the Merkle Tree that represents the current world state -- `Log Bloom` - a 256-byte block-level Bloom Filter that combines all the Bloom Filters of each Log topic from the block's receipts -- `Transactions` - the transactions that are included in the block -- `Receipts` - the execution results of the transactions that are included in the block - ---- - -A block is a fundamental data structure in a blockchain system that serves as a container for a batch of transactions. It plays a critical role in maintaining the integrity and immutability of the blockchain. - -Each block contains a unique identifier known as the `block hash`, which is calculated based on the contents of the block. The block hash acts as a fingerprint for the block, making it tamper-evident. Any change to the block's contents would alter its hash, making it easily detectable by network participants. - -The block header contains important metadata about the block, including the block's `height`, `timestamp`, and the `address of the block producer`, among others. It also includes Merkle tree root hashes for transactions, receipts, and the current state of the blockchain. - -Transactions contained within the block are executed by the blockchain system, with the results recorded in `receipts`. These receipts contain information about the execution status of each transaction and are stored in a Merkle tree, with the root hash included in the block header. - -In addition to transactions and receipts, the block also contains a Bloom filter, which is a probabilistic data structure used to efficiently query logs associated with the transactions contained in the block. - -Overall, block is an essential component of a blockchain system, providing a secure and reliable means of recording and validating transactions while ensuring the immutability and integrity of the blockchain. \ No newline at end of file diff --git a/docs/concepts/epoch.md b/docs/concepts/epoch.md deleted file mode 100644 index 30d194dc..00000000 --- a/docs/concepts/epoch.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -tags: - - Epoch - - Epoch Transition ---- - -# Epoch - -**Epoch** is a protocol-defined period for measuring the performance of operators on the blockchain network. - -The primary purpose of epochs in a blockchain is to facilitate various network functionalities and maintain consensus among network participants by defining a common reference point, which could be utilized to validate transactions. During one epoch, there would be block creation and block addition to the blockchain. - -In the ParallelChain Mainnet ecosystem, an `epoch` is defined by a predetermined block height or the number of blocks added to the blockchain, which is 8640. When a specific block height is reached or another 8640 blocks are added to the blockchain, the blockchain network would move from the current epoch to the next. The epoch transition could trigger critical events: - -- Reward stakes in Current Validator Set - - *Increase deposits* of owner and operator - - *Update stakes* if auto-stake-rewards is enabled - -- Replacing Previous Validator Set with Current Validator Set -- Replacing Current Validator Set with Next Validator Set -- Returning Next Validator Set for the next leader selection - -Epoch transition ensures that only one set of validators is active on the blockchain network at any given time, which makes the information on the blockchain tamper-proof. - diff --git a/docs/concepts/explorer.md b/docs/concepts/explorer.md deleted file mode 100644 index 6fc66618..00000000 --- a/docs/concepts/explorer.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -tags: - - Explorer ---- - -# ParallelChain Explorer - - -## What is ParallelChain Explorer ---- -**ParallelChain Explorer** is a web-based tool integrated with the ParallelChain Mainnet ecosystem, which allows users to visualize and interact with the Mainnet. By using the explorer, users can search for real-time and historical information about the blockchain. - -## ParallelChain Explorer Features ---- -- **Search and Navigation**: Find specific blocks, transactions, and accounts easily by using block hash, transaction hash, and account address. -- **Block Details**: Explore details of specific blocks, including block height, timestamp, transaction information, etc. -- **Transaction Details**: Explore details of specific transactions, including signer/recipient account information, timestamp, consumed gas, etc. -- **Account Details**: Explore details of specific accounts, including nonce, contract count, transaction history, etc. -- **Staking Details**: Explore details of staking information for each pool, including operator, pool power, and commission rate, etc. -- **Network Statistics**: Gain insights into network-wide statistics, including gas consumption, block production time, reward issuance, etc. -- **Wallet Extension**: Seamlessly create a ParallelChain wallet account and make transactions. - -**Check out our [ParallelChain Explorer](https://explorer.parallelchain.io/explorer)!** - - - - - - - diff --git a/docs/concepts/mainnet.md b/docs/concepts/mainnet.md deleted file mode 100644 index adc80463..00000000 --- a/docs/concepts/mainnet.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -tags: - - ParallelChain Mainnet ---- - -# ParallelChain Mainnet - -## What is Mainnet ---- - -**ParallelChain Mainnet** is a high-performance blockchain designed for enterprise-level use cases. It provides a platform for developers to build decentralised applications (dApps) with its efficient smart contract execution engine. - -It is designed to balance high performance and genuine decentralization. It is protected by the ParallelBFT consensus protocol, which adopts a sophisticated class-based node system to ensure fast and accountable consensus. - -For more information about the consensus protocol, please read the section [Consensus](./consensus.md). \ No newline at end of file diff --git a/docs/concepts/mempool.md b/docs/concepts/mempool.md deleted file mode 100644 index 316e1f8a..00000000 --- a/docs/concepts/mempool.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -tags: - - mempool - - MaxBaseFeePerGas ---- - -# Mempool - -## What is Mempool? ---- - -A **mempool** is a component of the blockchain network that keeps transactions that have not yet been added to a block. It can refer to two things: - -- The mempool of validating nodes and fullnodes, which accepts pending transactions for future inclusion in a block. (Only validating nodes can create new blocks.) -- The set of not-yet-confirmed transactions that are stored in the individual mempools of nodes in the network. This set can vary between nodes due to network delays and partitions. - -## How does Mempool Work? ---- - -When a transaction is submitted to the blockchain network, it is first sent to the mempool where it waits to be executed. The mempool acts like a queue, storing the pending transactions and arranging them to be executed by block producers. Transactions are prioritized based on how much the sender is willing to pay for network resources, which is indicated in a field called `Max Base Fee Per Gas` within the transaction. The higher the fee, the higher the priority of the transaction. - -## Max Base Fee Per Gas and EIP-1559 in Ethereum ---- - -The priority ranking method based on the `Max Base Fee Per Gas` is a crucial component of the EIP-1559 model for transaction processing in Ethereum. - -In the EIP-1559 model, each transaction specifies two fees: the `base fee` and the `priority fee`. The `base fee` is dynamically determined by the network based on the current demand for block space and adjusts itself to keep block utilization at a target level. The `priority fee` is the amount that the user is willing to pay in addition to the base fee to prioritize their transaction. - -When a transaction is submitted to the network, it is placed in the mempool, and the `priority fee` value of the transaction is used to rank it. Transactions with higher priority fees are placed higher in the mempool, making them more likely to be included in the next block. However, unlike the traditional method of simply sorting transactions by the fee amount, EIP-1559 allows for more efficient use of block space by dynamically adjusting the `base fee`, which incentivizes users to pay only what they need to get their transaction included. This helps to prevent congestion and ensures that transactions are processed in an efficient and timely manner. - -## Base Fee Per Gas in ParallelChain Mainnet ---- - -In ParallelChain Mainnet, the `base fee per gas` is calculated according to the [Base fee formula](https://github.com/parallelchain-io/parallelchain-protocol/blob/master/Blockchain.md#base-fee-formula). This is nearly identical to Ethereum's EIP-1559 and shares the same purpose: *adjust the cost of a transaction based on how busy the network is*. - -> **Note:** Validator nodes in ParallelChain Mainnet provided at the initial Launch do not take `priority fee` into the ranking calculation. \ No newline at end of file diff --git a/docs/concepts/smartcontract.md b/docs/concepts/smartcontract.md deleted file mode 100644 index f3bdbe78..00000000 --- a/docs/concepts/smartcontract.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -tags: - - Smart Contract ---- - -# Smart Contract - -## What is Smart Contract? ---- - -A **smart contract** is a way to run computer programs on a decentralised network that is secure and fault-tolerant. With smart contracts, users can write code to support their most critical business applications, all on a global, decentralised network. - -To use smart contracts on ParallelChain Mainnet, developers can write a Contract Binary Interface (CBI) Subprotocol that is implemented using a WebAssembly (WASM) module. However, for most developers, it's easier to use the `pchain-sdk` types and macros to write a Contract in **Rust**, and then use the `pchain-compile` commands to compile the Rust source code into WASM bytecode. - - -## Smart Contract Programming Model ---- - -The Smart Contract Programming Model is based on Object-Oriented Programming (OOP). In this model, a contract is like a `Rust` `struct` that controls access to persistent storage. Accounts can interact with contracts by submitting transactions that include a call command to invoke methods of the contract. These methods are sometimes called just "methods" for short. - -See section [Smart Contract Development](../developer_guides/smart_contract_sdk/introduction.md) for more information of `pchain-sdk`. - -## Why Rust and WebAssembly (WASM)? ---- - -Writing smart contracts in Rust and executing them as WebAssembly (WASM) bytecode on a blockchain has several benefits: - -1. **Efficiency and Security**: Rust is a systems programming language that provides a balance between performance and safety. It is designed to prevent common programming errors such as null pointer dereferencing and buffer overflows, which can cause security vulnerabilities. Rust's ownership model and borrow checker also help prevent memory leaks and race conditions. When compiled to WASM, Rust code can run efficiently and securely on a blockchain. - -2. **Interoperability**: WASM is a binary format that can be executed in different environments, such as web browsers and servers. This means that smart contracts written in programming languages and compiled to WASM can be executed on the blockchain that supports the WASM execution context. This provides more options for developers to choose from and promotes interoperability between different blockchain ecosystems. - -2. **Tooling and Ecosystem**: Rust has a rich ecosystem of libraries and tools for building systems and applications. This includes the mentioned `pchain-sdk`, which provides types and macros for writing smart contracts in Rust for the ParallelChain Mainnet blockchain. Rust's cargo package manager also makes it easy to manage dependencies and build projects. By leveraging the Rust ecosystem, developers can build smart contracts faster and with less effort. - -3. **Community Support**: Rust has a growing community of developers and contributors who are passionate about the language and its ecosystem. This means that there are resources available for learning Rust and getting help when needed. It also means that the language and ecosystem are constantly evolving and improving. - -Overall, writing smart contracts in Rust and executing them as WASM bytecode on a blockchain provides a secure, efficient, interoperability, and well-supported programming environment for developers. \ No newline at end of file diff --git a/docs/concepts/staking/block_reward.md b/docs/concepts/staking/block_reward.md deleted file mode 100644 index 7a50a283..00000000 --- a/docs/concepts/staking/block_reward.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -tags: - - block reward - - Staking ---- - - -# Staking - -## Block Reward - -Block rewards in a blockchain serve as an incentive for validators who actively contribute to the creation of new blocks within the blockchain network. - -In DPoS blockchains, validators are selected to validate transactions and generate new blocks based on the quantity of XPLL they have staked within the network. As a reward for their contributions, validators receive two kinds of rewards: -1. **Priority Fees**: an amount of *existing* XPLL that transaction signers *transfer* to block proposers to reward them for including their transaction. -2. **Block Rewards**: an amount of *new* XPLL created ("issued") at the end of every epoch according to a function of the total amount of XPLL staked. - -Block rewards play a crucial role in blockchain networks by serving multiple purposes. They incentivize miners and validators' participation in the network's consensus process, thereby upholding the security and integrity of the network. Additionally, block rewards facilitate the introduction of new XPLL into circulation, ensuring the long-term sustainability of the network. - -This document provides a rough overview of the calculation of block rewards. The exact formulas that Fullnodes use to calculate rewards are specified near the end of the ["next epoch" section](https://github.com/parallelchain-io/parallelchain-protocol/blob/master/Runtime.md#next-epoch) of the Runtime chapter of the ParallelChain Protocol specification. - - -### Reward Rate - -The block reward amount gradually decreases as additional blocks are incorporated into the blockchain over time. This process, which is known as the **block reward reduction**, is a characteristic found in various blockchain networks, such as Bitcoin (where it is popularly called "halving"). By implementing the block reward reduction, the supply of cryptocurrency is regulated, effectively curbing inflationary pressures. - -Block rewards in ParallelChain Mainnet gradually reduce according to the following formula: - -- First year: 8% per annum -- Reduce 15% per annum -- After 10 year (3650 days): keep at 1.5% per annum - -The **total amount of rewards (issuance)** introduced to the network is calculated as follows: - -$$ -\text{Total amount of stake} \times \text{Issuance rate} -$$ - -For example, if the *total amount of stake* of a validator is `100,000 XPLL` currently, and the *issuance rate* is `0.001`, then the *total amount of XPLL to be issued* to that validator in the next epoch will be `100,000 * 0.001 = 100 XPLL`. - - -The **issuance rate** is calculated as follows: - -$$ -\text{Issuance rate at n-th epoch} = 0.0835 \times \frac{0.85^{\frac{n}{365}}}{365} -$$ - -after 10 years (or equivalently, after $n >= 3650$), the issuance rate will become a constant: - -$$ -\text{Issuance rate per epoch after 10 years} = \frac{0.0150}{365} -$$ - -### Delegator Reward - -Delegators receive a portion of the newly issued rewards based on the amount they have staked with the validator. However, it's important to note that the delegator rewards will be reduced by a commission fee, which is determined by the validator and can be adjusted in their settings. - -Let's assume that in the upcoming epoch, the validator `V` will receive a *total reward* of `100 XPLL`. `V` has set a *commission fee* of `1%`. Additionally, one of its delegators, `D`, has contributed `10%` of the total staked amount to `V`. Then in the next epoch, `D` will be rewarded: - -$$ -\text{Reward} = 100 \text{ XPLL} \times 10\% \times (100\% - 1\%) = 9.99 \text{ XPLL} -$$ - ---- - -Note: - -- The values provided in the examples are approximate estimates and may not be exact. The accuracy of calculated values can be influenced by factors such as decimal truncation in integer division and the order of arithmetic operations. -- The above formulas are valid as of protocol version v0.4 but are subject to change in future protocol versions. \ No newline at end of file diff --git a/docs/concepts/staking/delegator.md b/docs/concepts/staking/delegator.md deleted file mode 100644 index 21795133..00000000 --- a/docs/concepts/staking/delegator.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -tags: - - Delegator - - Staking - - Pool ---- - -# Delegator - -In a delegated proof-of-stake (DPoS) blockchain network, a delegator is a participant who delegates their tokens holdings to a staking pool to participate in the network's consensus process. Delegators do not validate transactions or create new blocks themselves, but they can participate in the network's consensus process by proxy through a pool. - -Delegating tokens to a pool allows the delegator to participate in the network's consensus process and earn rewards for doing so, without having to run a pool node themselves. Delegators typically choose a pool based on their reputation, track record, and the rewards they offer. - -Delegators are responsible for selecting a pool to delegate their tokens to and must be careful to choose a reputable and trustworthy one. Delegators can also switch pools at any time, which allows them to take advantage of new opportunities or switch to a different pool if their current pool is underperforming. - -Delegators typically earn rewards for participating in the network's consensus process, which is shared between the delegators and the pool operator they delegate to. The exact amount of rewards earned may depend on various factors, such as the number of tokens staked, the length of time the tokens are staked for, and the network's overall performance. - -Overall, delegation allows more participants to participate in the network's consensus process, which can help to increase the network's security and decentralization. \ No newline at end of file diff --git a/docs/concepts/staking/faq.md b/docs/concepts/staking/faq.md deleted file mode 100644 index d98ffaab..00000000 --- a/docs/concepts/staking/faq.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -tags: - - Staking ---- - -# Staking - -## FAQ ---- - -#### Why am I not able to stake XPLL tokens? -You will need to retain a certain amount of XPLL in your account balance to pay for transaction fees. Ensure that you have reserved a small amount of XPLL tokens to pay for the gas fee of your deposit, stake, or unstake XPLL tokens. - ---- - -#### How do I know which validator to stake with? -The validators securing the ParallelChain Mainnet are trusted participants who are required to stake a significant number of XPLL. You may check the yield and commission fee of each validator by tapping on the drop-down arrow of the ‘Operator’ field. - ---- - -#### How long is the unstaking period? -The staking duration is measured by epochs. If you stake and unstake within the same epoch, the waiting time is considerably shorter. If the staking and unstaking are not within the same epoch, you will need to wait for at least another two epochs before unstaking. - ---- - -#### How long is an Epoch? -One full epoch lasts approximately one day before it enters the next epoch. The epoch itself is a protocol-defined period for measuring the performance of operators on the network. - ---- - -#### How do I withdraw my staking rewards? -You can withdraw the rewards you have earned from staking by unstaking them to your Token Deposit. Additionally, you may toggle the ‘AUTO STAKE REWARDS’ to avoid the process of unstaking your rewards. From there, you can then withdraw the amount to your wallet. Please refer to the section on Unstaking Your XPLL and Withdrawing Your Staking Rewards for the required steps. - ---- - -#### Can I move my staked XPLL to another validator? -Yes, you can. You will need to unstake your XPLL tokens, withdraw them to the Token Deposit, and then back to your wallet. You can then transfer those tokens to a Token Deposit with another validator before staking your tokens with them. Please refer to the sections above to move your XPLL to another validator. - ---- - -#### Can I stake to more than one node? -Yes, you can. To do so, you will need to create a Token Deposit on the validator node you wish to stake with. Once done, you can stake tokens with the validator node. To stake XPLL with more than one validator, repeat the same process of creating a Token Deposit with the other validator node, deposit tokens from your account to the Token Deposit, and you can stake with the second validator. Repeat this process with other validator nodes you wish to stake with. - ---- - -#### The status is still showing ‘PENDING’. Why is my transaction not confirmed yet? -Transactions are prioritized by the amount of Priority Fee per Gas paid, and lower priority transactions may need more time to be confirmed. You may choose to pay a higher Priority Fee during peak periods for a faster transaction, or you may check your wallet address on the blockchain explorer to monitor its transaction status. - ---- - -#### Are the rewards automatically staked? -Depends on the setting of your stake. Your staking rewards will not be automatically staked unless the **AUTO STAKE REWARDS** field is toggled on. You can toggle it on or off anytime you want. - ---- - -#### Is there any locking period? -There is no locking period to stake your XPLL tokens, but the staking duration is measured by epochs. If you stake and unstake within the same epoch, the waiting time is considerably shorter. If the staking and unstaking are not within the same epoch, you will need to wait for at least another two epochs before unstaking. - diff --git a/docs/concepts/staking/how_does_staking_work.md b/docs/concepts/staking/how_does_staking_work.md deleted file mode 100644 index 02a32f4a..00000000 --- a/docs/concepts/staking/how_does_staking_work.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -tags: - - Staking ---- - - -# Staking - - -## How does Staking Work? ---- - -In this staking process, there are two main actors: **pool operators** and **owner**. A pool operator can create, update, and destroy pools. An owner can deposit their cryptocurrency into a pool, top-up their deposit, withdraw their deposit, and set the amount they want to stake in the pool. However, they cannot stake more than the amount they have deposited. - -If a pool has enough power (determined by the amount of cryptocurrency staked), it can join as a validator in the next epoch. In each epoch, rewards are distributed to owners' deposits, and the validator set is updated according to the validators' power, which will determine the validators in consensus for the current epoch. - -An owner can withdraw their deposit from a pool, but the amount they withdraw cannot make their deposit less than the maximum stake amount in the current and previous epoch. - -Overall, the process allows operators to create and manage pools, owners to deposit and withdraw their funds while setting a stake amount, and rewards to be distributed to owners' deposits. The process also ensures the validator set is updated each epoch, which is important for the security and consensus of the network. Additionally, the restriction on withdrawals ensures that the pool always has enough stake to participate in the consensus process and maintains the security of the network. \ No newline at end of file diff --git a/docs/concepts/staking/validator.md b/docs/concepts/staking/validator.md deleted file mode 100644 index 1885cd10..00000000 --- a/docs/concepts/staking/validator.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -tags: - - Validator - - Staking - - Pool ---- - -# Validator -In a delegated proof-of-stake (DPoS) blockchain network, a `validator` is a participant in the network who is responsible for validating transactions and creating new blocks. Validators are selected based on the amount of tokens they hold and their **stake** in the network. This stake serves as collateral and incentivizes validators to act honestly and maintain the security of the network. - -Validators in a DPoS network are responsible for two key functions: proposing new blocks and validating transactions. Validators propose new blocks by creating a block with a set of new transactions and adding it to the blockchain. To validate transactions, validators must check that the transaction is valid, that the sender has enough tokens to complete the transaction, and that the transaction is not a double spend. - -Validators in a DPoS network are chosen according to the amount they staked in the network. The more tokens a user stakes, the greater their chances of being selected to be one of the validators in the next epoch. \ No newline at end of file diff --git a/docs/concepts/staking/what_is_staking.md b/docs/concepts/staking/what_is_staking.md deleted file mode 100644 index e8a8f9a9..00000000 --- a/docs/concepts/staking/what_is_staking.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -tags: - - Staking ---- - - -# Staking - -## What is Staking? ---- - -**Staking** is a process of holding a cryptocurrency or token as a way to support the operations of a blockchain network. It involves locking up a certain amount of tokens for a period of time to participate in the process of validating transactions, adding new blocks to the chain, and maintaining the security and integrity of the network. - -In return for staking, users may receive rewards in the form of additional tokens issued by the network. In Parallelchain Mainnet, Staking is used in delegated proof-of-stake (DPoS) consensus algorithms, where validators are chosen based on the number of tokens they have staked, rather than the computational power they can provide, as in proof-of-work (PoW) algorithms. - -Elements inside a staking process include: - -- **Pool**: a group of validators and delegators who combine their staking resources to increase their chances of being chosen to validate blocks and earn rewards. -- **Stake**: the cryptocurrency tokens that a participant locks up as collateral to become a validator or delegator. -- **Deposit**: the locked balance used to determine the amount of stake that can be contributed to a pool. - diff --git a/docs/concepts/storage.md b/docs/concepts/storage.md deleted file mode 100644 index 601153eb..00000000 --- a/docs/concepts/storage.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -tags: - - Storage - - World State ---- - -# Storage - -**Storage** is a decentralised database to store all necessary information to maintain a node and support data query of the blockchain. Unlike traditional decentralised databases which split data into chunks on different peers, each node instead broadcast the transactions that it received to other peer nodes. Once other nodes receive the transactions, they would execute transactions, verify the changes and update their database locally. - -Elements inside storage include: - -- `Blocks` - the full history of blocks from genesis. -- `World State` - a singular user-visible state maintained by the blockchain. -- `System state` - system data for running the node. - -## Blocks ---- -A block is a data structure in a blockchain system. Except for the first block (a.k.a genesis), each block contains the block hash of the previous block in the header. The whole chain of blocks is stored in the database and can be retrieved using block hash or block height easily. - -See section [Block](block.md) for more information. - -## World State ---- -The world state is a singular user-visible state maintained by the blockchain stored inside a Merkle Patricia Trie (MPT). Each account is associated with some states, representing in the set of key-value pairs, and which can trigger state changes in specific ways. - -There are three kinds of accounts, and they differ in how they trigger state changes: - -- **Externally Owned Accounts**, which trigger state changes by digitally signing transactions -- **Contract Accounts**, which trigger state changes when called according to the logic in its code. -- **Network Accounts**, which triggers state changes by the next epoch transaction. - -See section [Account](account.md) for more information about different types of accounts. - -## System State ---- -The system state stores system-level information to sync and communicate with other nodes in the blockchain. This part is non-accessible to the public and triggers state changes by consensus protocol. \ No newline at end of file diff --git a/docs/concepts/testnet.md b/docs/concepts/testnet.md deleted file mode 100644 index 6bc5d30d..00000000 --- a/docs/concepts/testnet.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -tags: - - ParallelChain Testnet - - Testnet 4 ---- - -# ParallelChain Testnet - -## What is Testnet ---- -To ensure the new features in ParallelChain Mainnet have what it takes to survive decentralised deployment, they must first be battle-tested. This is where ParallelChain Testnet comes into play by allowing developers, or simply users, to develop and run smart contracts or transactions on ParallelChain and experiment with the blockchain, at no cost. - -The current testnet iteration delivers on Byzantine Fault Tolerant (BFT) consensus, the cornerstone of security in ParallelChain's proof-of-stake network. Besides this, Testnet 4 delivers big leaps in the contract SDK and developer experience, as well as a web Wallet. -Both Mainnet and Testnet are accessible through Explorer. \ No newline at end of file diff --git a/docs/concepts/wallet.md b/docs/concepts/wallet.md deleted file mode 100644 index bea0ba5c..00000000 --- a/docs/concepts/wallet.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -tags: - - Wallet - - XPLL ---- - -# Wallet - -A crypto wallet is a software program that stores private and public keys. It enable users to interact with blockchain networks by sending and receiving digital currency, as well as monitoring their balance. Crypto wallets can be used to manage different types of digital assets, including cryptocurrencies and non-fungible tokens (NFTs). There are different types of crypto wallets, like software wallets, hardware wallets, and paper wallets, each with its own set of features and benefits. - -A crypto wallet is important for keeping your keypairs safe. A **keypair** consists of two related cryptographic keys, a public key, and a private key. - -A **public key** is a cryptographic key that can be freely shared with anyone. This is used as an address to identify your account and receive funds, while a **private key** is used to sign transactions and should be kept confidential by the owner. When a user sends cryptocurrency to another user, they use the recipient's public key to encrypt the transaction, which can only be decrypted by the recipient with their private key. - -It is important to keep the private key secure, as anyone who has access to it can sign transactions and transfer funds out of the wallet. \ No newline at end of file diff --git a/docs/developer_guides/pchain_cli/contract_publish.md b/docs/developer_guides/pchain_cli/contract_publish.md deleted file mode 100644 index 13c62280..00000000 --- a/docs/developer_guides/pchain_cli/contract_publish.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -tags: - - pchain-compile - - Contract Publishing Service ---- - -# Contract Publishing Service - -## What is contract publishing service? ---- - -The Contract Publishing Service is a platform that allows smart contract developers to **verify** their deployed source code on ParallelChain Mainnet. - -## How does it work? ---- - -The Contract Publishing Service follows these three steps: - -1. The service generates identity verification bytes using the contract address and transaction hash provided by the user. -2. The user signs the ID bytes with the help of the ParallelChain client using the instructions provided on the front end, which generates a signature. -3. The backend accepts the signature, GitHub link, and commit SHA of the source code. It builds the source code using `pchain_compile` and verifies the generated binary against the existing code on ParallelChain Mainnet. If the contract is successfully verified, the service returns a success status code to the user. - -## About the word "Verify" ---- - -The contract publishing service in ParallelChain Mainnet relies on the user to provide a correct Github link and commit SHA of the source code. If the user provides incorrect information, the verification process may fail or result in a false positive. Additionally, the service only *verifies* the **binary code** generated from the source code, and does *not verify* the **actual logic and functionality** of the smart contract. Therefore, it is still important for smart contract developers to thoroughly test and audit their code before deployment to ensure its correctness and security. \ No newline at end of file diff --git a/docs/developer_guides/pchain_cli/introduction.md b/docs/developer_guides/pchain_cli/introduction.md deleted file mode 100644 index 8fbdf018..00000000 --- a/docs/developer_guides/pchain_cli/introduction.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -tags: - - Tools - - CLI - - pchain-cli-rust ---- - -# ParallelChain Client CLI (pchain-client) - -`pchain_client` is an easy-to-use, fully-featured CLI for interacting with ParallelChain. -For a detailed description of all available commands, execute `pchain_client --help`. - -## Usage ---- - -```terminal -ParallelChain Client CLI 0.4.3 - -ParallelChain client (`pchain_client`) is a command-line tool for you to connect and interact with -the ParallelChain Mainnet/Testnet. - -USAGE: - pchain_client - -OPTIONS: - -h, --help Print help information - -V, --version Print version information - -SUBCOMMANDS: - transaction Construct and submit Transactions to ParallelChain network - query Query blockchain and world state information for ParallelChain network - keys Locally stores and manage account keypairs you created. (Password required) - parse Utilities functions to deserialize return values in CommandReceipt, and - compute contract address - config Get and set Fullnode RPC url to interact with ParallelChain - help Print this message or the help of the given subcommand(s) -``` - -## Why pchain_client ---- - -`pchain_client` allows you to query data from the ParallelChain, submit transactions, and more, all at the comfort of your command line. -Check out the examples below for details or see the full list of commands. The following document walks through the CLI's essential workflows. - -New users can begin either by - -1. [Install and Setup](./install_and_setup.md) or, -2. [Prepare Environment](./install_and_setup.md#prepare-environment) or, -3. [Setting up New Account](./manage_account.md) - - -If you are lost at any step, you can always type `pchain_client --help`. - - - - -## Content List ---- - -- [Install and Setup](install_and_setup.md#install-and-setup) - - [Installation](install_and_setup.md#installation) - - [Running pchain_client](install_and_setup.md#running-pchain_client) - - [Prepare Environment](install_and_setup.md#prepare-environment) -- [Manage Account](./manage_account.md#manage-account) - - [Generate new keypair](./manage_account.md#generate-new-keypair) - - [Import existing keypair](./manage_account.md#import-existing-keypair) - - [List accounts](./manage_account.md#list-accounts) -- [Transaction](./transaction.md#transaction) - - [Prepare Transaction file](./transaction.md#prepare-transaction-file) - - [Create new Transaction file](./transaction.md#create-new-transaction-file) - - [Append Command to existing file](./transaction.md#append-command-to-existing-file) - - [Submit Transaction to ParallelChain](./transaction.md#submit-transaction-to-parallelchain) -- [Query](./query.md#query) - - [Check Account related information](./query.md#check-account-related-information) - - [Get Transaction with receipt](./query.md#get-transaction-with-receipt) - - [Get Deposit and Stake](./query.md#get-deposit-and-stake) -- [Smart Contract](./smart_contract.md#smart-contract) - - [Retrieve contract address](./smart_contract.md#retrieve-contract-address) - - [Prepare contract method arguments file](./smart_contract.md#prepare-contract-method-arguments-file) - -## Opening an Issue ---- - -Open an issue in [GitHub](https://github.com/parallelchain-io/pchain-client-cli/issues) if you: - -1. Have a feature request / feature idea, -2. Have any questions (particularly software related questions), -3. Think you may have discovered a bug. - -Please try to label your issues appropriately. \ No newline at end of file diff --git a/docs/developer_guides/pchain_client_rust.md b/docs/developer_guides/pchain_client_rust.md deleted file mode 100644 index bbc038a7..00000000 --- a/docs/developer_guides/pchain_client_rust.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -tags: - - Tools - - CLI - - pchain-cli-rust ---- - -# pchain-cli-rust - -**pchain-cli-rust** is a Rust client library for the ParallelChain Protocol fullnode [RPC API](https://github.com/parallelchain-io/parallelchain-protocol/blob/master/RPC.md). - -It is designed to be user-friendly and accessible to developers and non-developers alike. It is intended to provide a simple and intuitive way to interact with the blockchain network, without requiring extensive technical knowledge or expertise. - -## Getting started - -Get started by creating an instance of client. - -```rust -use pchain_client::Client; - -let client = Client::new("https://rpc_base_url.xyz"); -``` - -You will then be able to access each RPC through a corresponding method of the same name. - -```rust -client.submit_transaction(txn); -client.block(block_request); -client.state(state_request); -``` diff --git a/docs/developer_guides/rpc/block_rpc.md b/docs/developer_guides/rpc/block_rpc.md deleted file mode 100644 index f42a3cd0..00000000 --- a/docs/developer_guides/rpc/block_rpc.md +++ /dev/null @@ -1,117 +0,0 @@ ---- -tags: - - Tools - - ParallelChain RPC API ---- - -# ParallelChain RPC API - -## Block RPCs - ---- - -### block - -Get a block by its block hash. - -#### Request - -```rust -struct BlockRequest { - block_hash: CryptoHash, -} -``` - -#### Response - -```rust -struct BlockResponse { - block: Option, -} -``` - ---- - -### block_header - -Get a block header by its block hash. - -#### Request - -```rust -struct BlockHeaderRequest { - block_hash: CryptoHash, -} -``` - -#### Response - -```rust -struct BlockHeaderResponse { - block_header: Option, -} -``` - ---- - -### block_height_by_hash - -Get the height of the block with a given block hash. - -#### Request - -```rust -struct BlockHeightByHashRequest { - block_hash: CryptoHash, -} -``` - -#### Response - -```rust -struct BlockHeightByHashResponse { - block_hash: CryptoHash, - block_height: Option, -} -``` - ---- - -### block_hash_by_height - -Get the hash of a block at a given height. - -#### Request - -```rust -struct BlockHashByHeightRequest { - block_height: BlockHeight, -} -``` - -#### Response - -```rust -struct BlockHashByHeightResponse { - block_height: BlockHeight, - block_hash: Option, -} -``` - ---- - -### highest_committed_block - -Get the hash of the highest committed block. - -#### Request - -None. - -#### Response - -```rust -struct HighestCommittedBlockResponse { - block_hash: Option, -} -``` diff --git a/docs/developer_guides/rpc/introduction.md b/docs/developer_guides/rpc/introduction.md deleted file mode 100644 index 0cf9550e..00000000 --- a/docs/developer_guides/rpc/introduction.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -tags: - - Tools - - ParallelChain RPC API ---- - -# ParallelChain RPC API - -This document specifies the ParallelChain RPC API, an HTTP API that Fullnodes make available to clients. - -We spell out the general properties of the API, and then list the available RPCs. With each RPC, we define a request structure and a response structure. - -For readability, we categorize RPCs into [transaction-related RPCs](./transaction_rpc.md), [block-related RPCs](./block_rpc.md), and [state-related RPCs](./state_rpc.md). - - -## General Properties ---- - -1. Procedures are reachable over HTTP at a URL suffixed by the procedure’s name. -2. All HTTP requests should be **POST**. -3. Request and response structures are serialized using **Borsh** and carried in **HTTP message bodies**. -4. Procedures are “strongly typed”. If a procedure receives a request that cannot be deserialized, it will send back a response with an empty body and a **Bad Request (400)** status code. -5. Conversely, if a procedure receives a request that can be deserialized, the response it sends back must have an **OK (200)** status code. This is even if, for example, something was “not found” (e.g., a block was not found with a specified hash), or a transaction was not added to the mempool. Error statuses are reported in response structures. -6. All requests and OK responses should have a content-type of "application/octet-stream". This is so that we can easily extend the RPC API in the future to support other serialization schemes, e.g., JSON using "application/json". \ No newline at end of file diff --git a/docs/developer_guides/rpc/state_rpc.md b/docs/developer_guides/rpc/state_rpc.md deleted file mode 100644 index 8c5f025a..00000000 --- a/docs/developer_guides/rpc/state_rpc.md +++ /dev/null @@ -1,238 +0,0 @@ ---- -tags: - - Tools - - ParallelChain RPC API ---- - -# ParallelChain RPC API - -## State RPCs ---- - -State RPCs return multiple entities in the world state in a single response. This allows clients to get a consistent snapshot of the world state in a single call. - -Every response structure includes the hash of the highest committed block when the snapshot is taken. - -Some of the following RPCs' response structures reference types unique to this document. These are specified in [types referenced in state RPC responses](#types-referenced-in-state-rpc-responses). - ---- - -### state - -Get the state of a set of accounts (optionally including their contract code), and/or a set of storage tuples. - -#### Request - -```rust -struct StateRequest { - accounts: HashSet, - include_contracts: bool, - storage_keys: HashMap>>, -} -``` - -#### Response - -```rust -struct StateResponse { - accounts: HashMap, - storage_tuples: HashMap, Vec>>, - block_hash: CryptoHash, -} -``` - ---- - -### validator_sets - -Get the previous, current, and next validator sets, optionally including the stakes delegated to them. - -#### Request - -```rust -struct ValidatorSetsRequest { - include_prev: bool, - include_prev_delegators: bool, - include_curr: bool, - include_curr_delegators: bool, - include_next: bool, - include_next_delegators: bool, -} -``` - -#### Response - -```rust -struct ValidatorSetsResponse { - // The inner Option is None if we are at Epoch 0. - prev_validator_set: Option>, - curr_validator_set: Option, - next_validator_set: Option, - block_hash: CryptoHash, -} -``` - ---- - -### pools - -Get a set of pools. - -#### Request - -```rust -struct PoolsRequest { - operators: HashSet, - include_stakes: bool, -} -``` - -#### Response - -```rust -struct PoolsResponse { - pools: HashMap>, - block_hash: CryptoHash, -} -``` - ---- - -### deposits - -Get a set of deposits. - -#### Request - -```rust -struct DepositsRequest { - stakes: HashSet<(Operator, Owner)>, -} -``` - -#### Response - -```rust -struct DepositsResponse { - deposits: HashMap<(Operator, Owner), Option>, - block_hash: CryptoHash, -} -``` - ---- - -### stakes - -Get a set of deposits. - -#### Request - -```rust -struct StakesRequest { - stakes: HashSet<(Operator, Owner)>, -} -``` - -#### Response - -```rust -struct StakesResponse { - stakes: HashMap<(Operator, Owner), Option>, - block_hash: CryptoHash, -} -``` - ---- - -### view - -Call a method in a contract in a read-only way. - -#### Request - -```rust -struct ViewRequest { - target: PublicAddress, - method: Vec, - arguments: Option>>, -} -``` - -#### Response - -```rust -struct ViewResponse { - receipt: CommandReceipt, -} -``` - ---- - -## Types Referenced in State RPC Responses ---- - -### Account-related types -```rust -enum Account { - WithContract(AccountWithContract), - WithoutContract(AccountWithoutContract), -} - -struct AccountWithContract { - nonce: Nonce, - balance: Balance, - contract: Option>, - cbi_version: Option, - storage_hash: Option, -} - -struct AccountWithoutContract { - nonce: Nonce, - balance: Balance, - cbi_version: Option, - storage_hash: Option, -} -``` - -### Staking-related types - -```rust -enum ValidatorSet { - WithDelegators(Vec), - WithoutDelegators(Vec), -} - -type Operator = PublicAddress; -type Owner = PublicAddress; - -struct PoolWithDelegators { - operator: PublicAddress, - power: Balance, - commission_rate: u8, - operator_stake: Option, - delegated_stakes: Vec, -} - -struct PoolWithoutDelegators { - operator: PublicAddress, - power: Balance, - commission_rate: u8, - operator_stake: Stake, -} - -struct Deposit { - owner: PublicAddress, - balance: u64, - auto_stake_rewards: bool, -} - -struct Stake { - owner: PublicAddress, - power: Balance, -} - -enum Pool { - WithStakes(PoolWithStakes), - WithoutStakes(PoolWithoutStakes), -} -``` \ No newline at end of file diff --git a/docs/developer_guides/rpc/transaction_rpc.md b/docs/developer_guides/rpc/transaction_rpc.md deleted file mode 100644 index c4d8cb4c..00000000 --- a/docs/developer_guides/rpc/transaction_rpc.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -tags: - - Tools - - ParallelChain RPC API ---- - -# ParallelChain RPC API - - -## Transaction RPCs ---- -### submit_transaction - -Submit a transaction to the mempool. - -#### Request - -```rust -struct SubmitTransactionRequest { - transaction: Transaction, -} -``` - -#### Response - -```rust -struct SubmitTransactionResponse { - error: Option, -} -``` - -Where `SubmitTransactionError`: -```rust -enum SubmitTransactionError { - UnacceptableNonce, - MempoolFull, - Other, -} -``` - ---- - -### transaction - -Get a transaction and optionally its receipt. - -#### Request - -```rust -struct TransactionRequest { - transaction_hash: CryptoHash, - include_receipt: bool, -} -``` - -#### Response - -```rust -struct TransactionResponse { - transaction: Option, - receipt: Option, - block_hash: Option, - position: Option, -} -``` - ---- - -### transaction_position - -Find out where a transaction is in the blockchain. - -#### Request - -```rust -struct TransactionPositionRequest { - transaction_hash: CryptoHash, -} -``` - -#### Response - -```rust -struct TransactionPositionResponse { - transaction_hash: Option, - block_hash: Option, - position: Option, -} -``` - ---- - -### receipt - -Get a transaction's receipt. - -#### Request - -```rust -struct ReceiptRequest { - transaction_hash: CryptoHash, -} -``` - -#### Response - -```rust -struct ReceiptResponse { - transaction_hash: CryptoHash, - receipt: Option, - block_hash: Option, - position: Option, -} -``` \ No newline at end of file diff --git a/docs/developer_guides/smart_contract_sdk/advance/cross_contract.md b/docs/developer_guides/smart_contract_sdk/advance/cross_contract.md deleted file mode 100644 index e12d6df6..00000000 --- a/docs/developer_guides/smart_contract_sdk/advance/cross_contract.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -tags: - - pchain-sdk - - Smart Contract - - Cross Contract Call ---- - -# Cross Contract Call - -The SDK includes two functions to make Contract-to-Contract calls: `call` and `call_untyped`, the former calls a method in a specified Contract with the given arguments. Here is to illustrate the details by example of smart contract "ContractProxy". - - -## Call Contract by Using Trait ---- - -SDK provides developer-friendly ways to call another contract by using macro `use_contract`. The address of the contract is specified inside the attribute list in the macro. - -```rust -/// ### Lesson 1: -/// Use macro `use_contract` to specify the contract action entrypoint methods in a trait. -/// The address is hard-coded when using the macro `use_contract`. -/// It is recommended to remove/comment out the methods that are not intended to be used. -#[use_contract("-jUt6jrEfMRD1JM9n6_yAASl2cwsc4tg1Bqp07gvQpU")] -pub trait MyLittlePony { - //fn self_introduction() -> String; - fn grow_up(); - //fn change_person(name :String, age :u32, gender_name :String, description :String); -} -``` - -In the example above, module `my_little_pony` is generated which name which is the trait name in a snake case format. Associate methods are generated inside the module for being used to make cross-contract calls. - -```rust -/// ### Lesson 2: -/// The trait will be transformed to mod by using macro `use_contract`. -/// Calling the contract `MyLittlePony` can be simply calling associate methods according to the defined method in the trait. -/// Value and Gas will be needed in cross contract call -#[call] -fn grow_up() { - my_little_pony::grow_up(0, 120000); -} -``` - -## Call Contract by Using Function ---- - -Cross-contract calls can also be simply made by using the function `pchain_sdk::call` or `pchain_sdk::call_untyped`. - -```rust -/// ### Lesson 3: -/// It is also possible to use call_untyped() instead of macro `use_contract` to make a cross contract call. -/// Address can also be passed as an argument so that the contract address is not necessarily hard-coded. -#[call] -fn grow_up_2() { - let contract_address = Base64URL::decode("-jUt6jrEfMRD1JM9n6_yAASl2cwsc4tg1Bqp07gvQpU").unwrap().try_into().unwrap(); - pchain_sdk::call_untyped( - contract_address, - "grow_up", - Vec::new(), - 0); -} -``` - -Different from using [Trait](#call-contract-by-using-trait), it no longer requires the address to be hard coded as it can be passed from method arguments. \ No newline at end of file diff --git a/docs/developer_guides/smart_contract_sdk/advance/entrypoints.md b/docs/developer_guides/smart_contract_sdk/advance/entrypoints.md deleted file mode 100644 index ce24e5ec..00000000 --- a/docs/developer_guides/smart_contract_sdk/advance/entrypoints.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -tags: - - pchain-sdk - - Smart Contract - - Contract Methods ---- - -In ParallelChain Smart Contract Programming Model, a contract is like a `Rust` `struct` that controls access to persistent storage. Accounts can interact with contracts by submitting transactions that include a call command to invoke methods of the contract. These methods are sometimes called just "methods" for short. - -## Methods ---- - -The model defines Contract Methods as methods with the `#[call]` macro. Each of these corresponds to a method that can be called via a Call Command in the CBI Subprotocol. To allow methods to be called from the outside world, you must write method definitions within an `impl Contract` statement marked with the `#[contract_methods]` macro. The following example illustrates this: - -```rust -#[contract_methods] -impl PrinceTheDog { - - #[call] - pub fn eat_food(&mut self, food: DogFood) -> Poop { - // ... - } -} -``` - -Methods can change Contract Storage. However, mutations made in a Call Transaction only apply if the transaction is successful. This means that the transaction must have enough gas, not have panicked during execution, and so on. - -A function can be called an Action Method only if: - -The `#[call]` macro is added above the function declaration. -Its arguments (if any) implement `BorshDeserialize`. -Its return value (if any) implements `BorshSerialize`. - -## Accepting Parameters and Returning Values ---- - -Some of the code snippets provided in this document show Contract Methods that accept arguments (in addition to borrow of the Contract struct) and/or return a value. To enable a contract to receive arguments from and return values to callers, both the contract and the caller need to agree on a serialization format. - -The `pchain-sdk` expects callers to serialize method arguments using the Borsh serialization standard. It generates code to serialize values into borsh for inclusion in a Transaction's Receipt. To be precise, a Call Transaction specifies the Contract Method to call and provide the arguments for the call by including a borsh-serialized data structure `Option>` in its `arguments` field, and then returning a borsh-serialized value (if any). \ No newline at end of file diff --git a/docs/developer_guides/smart_contract_sdk/build_contract.md b/docs/developer_guides/smart_contract_sdk/build_contract.md deleted file mode 100644 index 4d0fa391..00000000 --- a/docs/developer_guides/smart_contract_sdk/build_contract.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -tags: - - pchain-sdk - - pchain-compile - - Smart Contract ---- - -# Building the Contract with pchain_compile - -**pchain_compile** is a CLI build tool for smart contract developers to build their source code to WASM binaries for deployment on -ParallelChain Mainnet. - -The WASM binary generated from a generic cargo build process has the following disadvantages: - - - The build process is not toolchain version agnostic i.e. it does not guarantee uniform WASM binaries with different versions of compiler and - rust crate dependencies. This will make it difficult for smart contract developers to verify their source code on the blockchain. - - - The build process generates a large file size, which leads to higher gas costs for deployment and contract calls. - -**pchain_compile** solves these shortcomings by: - - - Executing the build process in a docker environment with pre-defined toolchain versioning. - - - Optimizing and compressing the size of the WASM binary with the help of `wasm-snip` and `wasm-opt` packages. - - -## Downloading **pchain_compile** ---- - -`pchain_compile` supports Linux, macOS and Windows. Depending on the operating system, they can be downloaded from Assets of ParallelChain Lab's Git Hub [release page](https://github.com/parallelchain-io/pchain-compile/releases). - -The binary can also be installed and built by executing the following commands: -``` -cargo install pchain_compile -``` - -!!! Pre-Requisites - `pchain_compile` builds the source code in a docker environment. To know more about Docker and install it, refer to the [official instructions](https://docs.docker.com/engine/install/). - - - -## Build WASM Binary ---- - -In order to build a `WASM` binary of the smart contract, run the following command: - -=== "Linux / macOS" - ```bash - ./pchain_compile build --source - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_compile.exe build --source - ``` - -If you installed `pchain_compile` with `cargo install`, you can simply run: - -``` -pchain_compile build --source -``` - -A `.wasm` file will be generated in the current directory. It will be needed for the [next section](./deploy_contract.md). \ No newline at end of file diff --git a/docs/developer_guides/smart_contract_sdk/call_contract.md b/docs/developer_guides/smart_contract_sdk/call_contract.md deleted file mode 100644 index 4227809f..00000000 --- a/docs/developer_guides/smart_contract_sdk/call_contract.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -tags: - - pchain-client - - Call - - Smart Contract ---- - - -## Preparing Contract Method Arguments ---- - -Suppose you have already deployed a contract that contains a `call` method as follows: - -```rust - #[call] - fn hello_from(name: String) -> u32 { - pchain_sdk::log( - "topic: Hello From".as_bytes(), - format!("Hello, Contract. From: {}", name).as_bytes() - ); - name.len() as u32 - } -``` - -To invoke this contract in the blockchain by using `pchain_client`, you can prepare a JSON file that contains a list of arguments and matches with the `call` method. For example, this `call` method takes a string argument. Then, the content of the JSON file should be as follows: - -```json -{ - "arguments": [ - {"argument_type":"String", "argument_value": "\"Alice\""} - ] -} -``` - -This JSON file will be used in the subcommand `call` as mentioned in the subsequent sections on this page. - -## Calling Contract ---- - -To call a smart contract, submit a transaction with your account nonce and contract address using the `pchain_client`. - -Here is the command to call a contract: - -=== "Linux / macOS" - ```bash - ./pchain_client transaction create \ - --nonce \ - --gas-limit \ - --max-base-fee-per-gas \ - --priority-fee-per-gas \ - call \ - --target \ - --method \ - --arguments - --amount \ - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe transaction create ` - --nonce ` - --gas-limit ` - --max-base-fee-per-gas ` - --priority-fee-per-gas ` - call ` - --target ` - --method ` - --arguments ` - --amount - ``` - -The gas limit required for the transaction depends on the complexity of the smart contract. For safety reasons, you can always set a higher gas limit. You can also test contract calls on testnet to reassure. - -You can follow the instruction in [Create Transaction](../developer_guides/pchain_cli/transaction.md) about submiting a transaction through `pchain-client`. - -To query the resulting receipt of the transaction, - -=== "Linux / macOS" - ```bash - ./pchain_client query tx --hash - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe query tx --hash - ``` - -The commands stored in `transaction` and command receipts in `receipt` are following the same order. That means you can always find the corresponding transaction from a command receipt. - -## Parse Call Result ---- - -To parse the response from the contract method, represented in the field named `return value` , which is in `CallResult` format, you can use the `parse call-result` command in ParallelChain Client. - -For example, if the contract method returns a u32 integer, the `return value` is "BAAAAAUAAAA" you can parse the `CallResult` data structure using the `--data-type u32` flag: - -=== "Linux / macOS" - ```bash - pchain_client parse call-result --value BAAAAAUAAAA --data-type u32 - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe parse call-result --value BAAAAAUAAAA --data-type u32 - ``` - -The output will be the parsed value of the `CallResult`, which in this case is `4`. For more details, you can use the `help` command to see the usage of the tool or take a look at the example `argument,json`. \ No newline at end of file diff --git a/docs/developer_guides/smart_contract_sdk/deploy_contract.md b/docs/developer_guides/smart_contract_sdk/deploy_contract.md deleted file mode 100644 index 2b0d71a9..00000000 --- a/docs/developer_guides/smart_contract_sdk/deploy_contract.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -tags: - - Smart Contract - - pchain-client ---- - -This guide will walk you through the process of deploying your smart contract on ParallelChain Mainnet. - -## Deploying a Smart Contract ---- - -You can deploy the contract using the pchain_client command line tool. You should make sure to obtain your latest account nonce before submitting the transaction. - -=== "Linux / macOS" - ```bash - ./pchain_client transaction create - --nonce \ - --gas-limit \ - --max-base-fee-per-gas \ - --priority-fee-per-gas \ - deploy \ - --contract-code \ - --cbi-version - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe transaction create ` - --nonce ` - --gas-limit ` - --max-base-fee-per-gas ` - --priority-fee-per-gas ` - deploy ` - --contract-code ` - --cbi-version - ``` - -You can follow the instruction in [Create Transaction](../developer_guides/pchain_cli/transaction.md) about submiting a transaction through `pchain-client`. - -## Checking Contract in State ---- - -To verify that the smart contract is deployed correctly, you can run the command `query` with the flag `contract`. It queries the state of the blockchain and saves the wasm code as `code.wasm` in the current directory. -If you want to store the contract file in your preferred location, you need to provide the flag `destination` to specify the path with your preferred file extension: - -=== "Linux / macOS" - ```bash - ./pchain_client query contract --address - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe query contract --address - ``` \ No newline at end of file diff --git a/docs/developer_guides/smart_contract_sdk/develop_contract.md b/docs/developer_guides/smart_contract_sdk/develop_contract.md deleted file mode 100644 index 589533b8..00000000 --- a/docs/developer_guides/smart_contract_sdk/develop_contract.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -tags: - - pchain-sdk - - Smart Contract - - Rust ---- - -Before we dive deep into the structure of a contract and the SDK's semantics, we require some background information about the semantics enforced by ParallelChain Mainnet. The full capabilities of ParallelChain Mainnet continue to grow with active developers -and a growing community. Let's see how smart contracts are called and processed by a node in the form of transactions. - -First, the ParallelChain Client (`pchain_client`) will submit a transaction when making a smart contract call to the validating node using a serialization crate [pchain-types](https://github.com/parallelchain-io/pchain-types-rust). The node's RPC service and mempool will process the list of transactions and check for validity and correctness. - -Transactions that fail the validation check may not be included in a block. The transactions are then packed in a block and sent to the execution engine in the node to execute the transactions. - -The executor will call `wasmer` (Web Assembly Engine) which provides an isolated context to perform the execution. This enables the smart contract code to read the current state of the blockchain and interact with it. However, the execution results are temporarily stored and subject to further checks before the block may be committed or rolled back on error. - -`wasmer` also computes the gas fees through a metering module, which is responsible for limiting the execution to the amount of gas paid. Each transaction returns a result in the form of receipts along with logs. The receipts (with or without log), transactions and block itself will contain its hash (or Merkle proof) and will be all included in the same block. - - -## Smart Contract Development Kit ---- - -Smart Contract can be created by using [ParallelChain SDK](https://github.com/parallelchain-io/pchain-sdk). Example contracts can be found in [example-smart-contracts](https://github.com/parallelchain-io/example-smart-contracts). - -A ParallelChain Smart Contract is a rust crate that imports the SDK. It uses the SDK's features to interact with the blockchain. The folder structure of a typical ParallelChain -Mainnet Smart Contract looks like this: -```bash -my_first_contract -├── src/ -│ └── lib.rs # The main source code of your smart contract. -└── Cargo.toml # You import your packages and the SDK here -``` - -For more information on Rust's crate system, see [Rust Book Chapter 7: Packages and Crates](https://doc.rust-lang.org/stable/book/ch07-01-packages-and-crates.html?highlight=crate#packages-and-crates) - -Please specify the dependency in `Cargo.toml` for using SDK by fetching from [crates.io](https://crates.io/) or repository in Github. - -=== "Crates.io" - ```rust - [dependencies] - pchain-sdk = "0.4" - ``` - -=== "Github" - ```rust - [dependencies] - pchain-sdk = { git = "https://github.com/parallelchain-io/pchain-sdk" } - ``` \ No newline at end of file diff --git a/docs/developer_guides/smart_contract_sdk/introduction.md b/docs/developer_guides/smart_contract_sdk/introduction.md deleted file mode 100644 index 72195bf8..00000000 --- a/docs/developer_guides/smart_contract_sdk/introduction.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -tags: - - Tools - - pchain-sdk - - Smart Contract ---- - -# SDK - -The **ParallelChain Mainnet Contract SDK (pchain-sdk)** is an open-source Rust crate that helps to build smart contracts. It provides Rust structs, functions, types, and macros that aid with the development of smart contracts executable in **WebAssembly (WASM)** engines, implementing the **ParallelChain Mainnet Contract Binary Interface (CBI) Subprotocol.** - - -Contracts are the run-time programmability mechanism of ParallelChain Mainnet networks. They allow users (Account owners) to implement arbitrary logic in a global, decentralised, and Byzantine Fault Tolerant replicated state machine to support their most business-critical applications. - - -Theoretically, any WebAssembly (WASM) module that implements the CBI Subprotocol can be deployed onto a ParallelChain Mainnet blockchain. Practically, however, all developers (except perhaps those who like to experiment, or that would like to stretch the limits of the system) will want to use the types and macros provided in this pchain-sdk to write a Contract and the commands in pchain-compile to compile the Rust source code into WASM bytecode that can be included in a Deploy Transaction. - - -This documentation is for both novice and advanced users alike. We hope to guide you to the success of your first smart contract creation in ParallelChain. - -For sharing the smart contract code, address, or any help with creating smart contracts, please go to [GitHub Discussions](https://github.com/parallelchain-io/parallelchain-sdk/discussions). - -If you have any issues related to the SDK or smart contract, please go to [GitHub issues](https://github.com/parallelchain-io/parallelchain-sdk/issues). diff --git a/docs/developer_guides/smart_contract_sdk/prepare_env.md b/docs/developer_guides/smart_contract_sdk/prepare_env.md deleted file mode 100644 index 73d94e79..00000000 --- a/docs/developer_guides/smart_contract_sdk/prepare_env.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -tags: - - mainnet - - testnet - - explorer ---- - -# Prepare Environment - -In this section, you need the tools and environment to develop and run smart contracts. You can utilize our Mainnet to deploy and make contract calls. You may consider testing your transaction on Testnet before doing it on Mainnet. - -## Checking the Network ---- - -You can check the **mainnet** network by viewing the Explorer website: - -* [ParallelChain Mainnet Explorer](https://explorer.parallelchain.io/explorer) - -The explorer can explore transactions, addresses, information about the network, and blocks. - -To verify that **testnet node** is alive: - -* [https://pchain-test-rpc02.parallelchain.io](https://pchain-test-rpc02.parallelchain.io) - -You can use ParallelChain Client (called `pchain_client`) to interact with the `testnet` node. - -## Set Up ParallelChain Client ---- -Before we start developing the smart contracts, the `pchain_client` executable needs to be configured. - -If you are not yet familiar with `pchain_client`, See [Install and Setup](../developer_guides/pchain_cli/install_and_setup.md) to install `pchain_client` and learn about the basic functionalities before proceeding with smart contract development. diff --git a/docs/developer_guides/wallet_browser_extension/intro.md b/docs/developer_guides/wallet_browser_extension/intro.md deleted file mode 100644 index f1f194cf..00000000 --- a/docs/developer_guides/wallet_browser_extension/intro.md +++ /dev/null @@ -1,62 +0,0 @@ -# ParallelChain Wallet Extension - -ParallelChain Wallet Extension is a browser extension that allows you to integrate your [dapp](./definition.md#provider) with [ParallelChain Wallet](../../concepts/wallet.md). - -This enables your dapp to interact with your dapp users' XPLL accounts, to: - -- Send [transactions](../../concepts/transaction.md#transaction) - - [Stake](../../concepts/staking/what_is_staking.md) XPLL -- Trigger confirmation for [smart contract](../../concepts/smartcontract.md) calls - -Start by reading about the [ParallelChain Wallet Provider API](./provider/intro.md). - -## Supported Platforms - -- Chrome browser (Minimum version: Chrome 57) - - -## Getting Started - -### Prerequisites - -- Chrome browser installed (Refer to above for supported versions) - -### Extension Installation - -#### Chrome - -##### Chrome Web Store - -Chrome users can install the extension via the Chrome Web Store. - -##### Manual Installation - -1. Download `xperience_browser_extension-1.0.2-chromium.zip`. -2. Unzip the file into a folder. -3. Follow the [instructions here][1] to load the extension. Load the folder when prompted. - -[1]: https://developer.chrome.com/docs/extensions/mv3/getstarted/development-basics/#load-unpacked - - - -## FAQ - -### After installing the extension, I am still not able to access `window.xpll` in my browser or dapp. - -Try refreshing the webpage and make sure the website is a valid http or https website. Restricted sites like `chrome://extensions/` or `about:debugging` will not be able to access the injected API. - -### After clicking the extension icon, nothing happens. - -If this is your first time setting up the wallet, a separate notification window will appear. If you are using multiple screens, check if the notification window has appeared on another screen. diff --git a/docs/developer_guides/wallet_browser_extension/provider/intro.md b/docs/developer_guides/wallet_browser_extension/provider/intro.md deleted file mode 100644 index 9bfbffb3..00000000 --- a/docs/developer_guides/wallet_browser_extension/provider/intro.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -tags: - - wallet - - browser extension - - provider API ---- - -# ParallelChain Wallet Provider API - -The ParallelChain Wallet Provider API is a Javascript API designed to deliver a friendly developer experience and consistency across clients and applications. - -ParallelChain Wallet Extension injects a global Javascript API into the browser using the `#!js window.xpll` [provider][1] object. - -This API is specified by [EIP-1193][2], which promotes wallet interoperability by preventing conflicting interfaces and behaviours between wallets. - -ParallelChain Wallet Provider API is designed to be minimal, event-driven, and agnostic of transport and [RPC][3] protocols. Its functionality is easily extended by defining new RPC methods and message event types. - -[1]: ../definition.md#provider -[2]: https://eips.ethereum.org/EIPS/eip-1193 -[3]: ../definition.md#remote-procedure-call-(rpc) diff --git a/docs/for_developers/parallelchain_client_apis/javascript_apis.md b/docs/for_developers/parallelchain_client_apis/javascript_apis.md new file mode 100644 index 00000000..bea090cb --- /dev/null +++ b/docs/for_developers/parallelchain_client_apis/javascript_apis.md @@ -0,0 +1,626 @@ +--- +tags: + - Tools + - ParallelChain RPC API + - Javascript + - Client +--- + +ParallelChain RPC APIs are the HTTP APIs that Fullnodes make available to clients. + +In the section [ParallelChain Client Library](#parallelchain-client-library-javascript), we introduce the Javascript Library to make RPC calls programatically. + +The Client Library allows you to easily submit RPC requests and parse RPC responses without the need to understand the details of HTTP URL, request format or response format. The formation of HTTP APIs is specified in [ParallelChain Protocol](https://github.com/parallelchain-io/parallelchain-protocol/blob/master/RPC.md). + +## ParallelChain Client Library (Javascript) + +[ParallelChain Client Library](https://github.com/parallelchain-io/pchain-client-js) is a Javascript package providing a HTTP client for interacting with the ParallelChain RPC APIs. We will show how to use the library by example code that runs in [Node.js](https://nodejs.org/). To use the library, install the [npm](https://www.npmjs.com) package [pchain-client-js](https://www.npmjs.com/pchain-client-js). You will also need the package [pchain-types-js](https://www.npmjs.com/package/pchain-types-js) for necessary basic types. + +```sh +npm install pchain-client-js +npm install pchain-types-js +``` + +You can instantiate the object `Client` by providing the link to a ParallelChain RPC endpoint. Let's start with a simple Node.js script as below. + +```js +const Client = require("pchain-client-js").Client; + +(async () => { + /// Connect to Testnet RPC endpoint + const client = new Client('https://pchain-test-rpc02.parallelchain.io'); + /// ... +})(); +``` + +!!! Note + RPC endpoints for [Mainnet](../../fundamentals/networks.md#parallelchain-mainnet) and [Testnet](../../fundamentals/networks.md#parallelchain-testnet) are `https://pchain-main-rpc02.parallelchain.io` and `https://pchain-test-rpc02.parallelchain.io` respectively. + +## Understanding Basic Types + +Throughout the API Reference, basic types provided by [pchain-type-js](https://www.npmjs.com/package/pchain-types-js) are often being used in the RPC requests and responses. For better understanding their data, Let's go through them. + +First, the integer types `u16`, `u32` and `u64` are [type-alias](https://www.w3schools.com/typescript/typescript_aliases_and_interfaces.php) to types `number`, `number` and [BN](https://www.npmjs.com/package/bn.js) in typescript respectively. + +The class `Option` contains a value with type `T` or value of [null](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#null-and-undefined). + +The classes `Sha256Hash` and `PublicAddress` store a data `Buffer`. They are similar in the way that they can be instantiated from a Base64URL encoded string. + +```ts +// Instantiates a PublicAddress Object by passing the 32-byte address in base64url encoded string. +const public_address = new PublicAddress('oK8Kvd-2cWYloQaPNlGtG3Q5dV6JFKzVrXOAhBRt5hs'); +// Instantiates a Sha256Hash Object by passing the Sha256 hash in base64url encoded string. +const sha256_hash = new Sha256Hash('x96G2mLXgaCNaAABXNICWHh_DH33khSg_T7UawTGnGg'); +``` + +The abstract class `Enum` functions as the [enum](https://doc.rust-lang.org/book/ch06-01-defining-an-enum.html) in Rust Programming Language so that the inherited class can be used and serialized as requred by ParallelChain RPC API. An example is [ValidatorSet](#staking-related-types). + +The class extends the `Enum` and provides two variants. +```ts +class ValidatorSet extends Enum { + poolsWithDelegator?: PoolWithDelegator[]; + poolsWithoutDelegator?: PoolWithoutDelegator[]; +} +``` + +Example to get the object of `PoolWithoutDelegator`: + +```ts +const validatorSet = // an object of ValidaterSet +const poolsWithoutDelegator = validatorSet?.poolsWithoutDelegator || []; +``` + +## Transaction Related RPCs + +### submit_transaction + +Submit a transaction to the mempool. + +```js +const transaction = await new Transaction({ + signer: keypair.public_key, + // nonce, commands, ... +}) +.toSignedTx(keypair); + +const response = await client.submit_transaction( + new SubmitTransactionRequest({ transaction }) +); +``` +!!! Note + Types such as `Keypair` and `SubmitTransactionRequest` can be imported by the package `pchain-types-js`. E.g. + ```js + const { Keypair, SubmitTransactionRequest } = require("pchain-types-js"); + ``` + + In case you need free tokens for submitting transactions to Testnet, check out the [Faucet Service](../../fundamentals/networks.md#faucet-service) for details. + +**Request** + +```ts +class SubmitTransactionRequest { + transaction: Transaction, +} +``` + +**Response** + +```ts +class SubmitTransactionResponse { + error: Option, +} +``` + +Where `SubmitTransactionError`: +```ts +enum SubmitTransactionError { + UnacceptableNonce = 0, + MempoolFull = 1, + Other = 2 +} +``` + +--- + +### transaction + +Get a transaction and optionally its receipt. + + +```js +const response = await client.transaction( + new TransactionRequest({ transaction_hash, include_receipt }) +); +``` + +**Request** + +```ts +class TransactionRequest { + transaction_hash: Sha256Hash; + include_receipt: boolean; +} +``` + +**Response** + +```ts +class TransactionResponse { + transaction: Option; + receipt: Option; + block_hash: Option; + position: Option; +} +``` + +--- + + +### transaction_position + +Find out where a transaction is in the blockchain. + +```js +const response = await client.transaction_position( + new TransactionPositionRequest({ transaction_hash }) +); +``` + +**Request** + +```ts +class TransactionPositionRequest { + transaction_hash: Sha256Hash, +} +``` + +**Response** + +```ts +class TransactionPositionResponse { + transaction_hash: Option; + block: Option; + position: Option; +} +``` + +--- + + +### receipt + +Get a transaction's receipt. + +```js +const response = await client.receipt( + new ReceiptRequest({ transaction_hash }) +); +``` + +**Request** + +```ts +class ReceiptRequest { + transaction_hash: Sha256Hash; +} +``` + +**Response** + +```ts +class ReceiptResponse { + transaction_hash: Sha256Hash; + receipt: Option; + block_hash: Option; + position: Option; +} +``` + +## Block Related RPCs + +### block + +Get a block by its block hash. + +```js +const response = await client.block( + new BlockRequest({ block_hash }) +); +``` + +**Request** + +```ts +class BlockRequest { + block_hash: Sha256Hash; +} +``` + +**Response** + +```rust +struct BlockResponse { + block: Option, +} +``` + +--- + +### block_header + +Get a block header by its block hash. + +```js +const response = await client.block_header( + new BlockHeaderRequest({ block_hash }) +); +``` + +**Request** + +```ts +class BlockHeaderRequest { + block_hash: Sha256Hash; +} +``` + +**Response** + +```ts +class BlockHeaderResponse { + block_header: Option, +} +``` + +--- + +### block_height_by_hash + +Get the height of the block with a given block hash. + +```js +const response = await client.block_height_by_hash( + new BlockHeightByHashRequest({ block_hash }) +); +``` + +**Request** + +```ts +class BlockHeightByHashRequest { + block_hash: Sha256Hash; +} +``` + +**Response** + +```ts +class BlockHeightByHashResponse { + block_hash: Sha256Hash; + block_height: Option; +} +``` + +--- + +### block_hash_by_height + +Get the hash of a block at a given height. + +```js +const response = await client.block_hash_by_height( + new BlockHashByHeightRequest({ block_height }) +); +``` + +**Request** + +```ts +class BlockHashByHeightRequest { + block_height: u64; +} +``` + +**Response** + +```ts +class BlockHashByHeightResponse { + block_height: u64; + block_hash: Option; +} +``` + +--- + +### highest_committed_block + +Get the hash of the highest committed block. + +```js +const response = await client.highest_committed_block(); +``` + +**Request** + +None. + +**Response** + +```ts +class HighestCommittedBlockResponse { + block_hash: Option; +} +``` + +## State Related RPCs + +State RPCs return multiple entities in the world state in a single response. This allows clients to get a consistent snapshot of the world state in a single call. + +Every response structure includes the hash of the highest committed block when the snapshot is taken. + +Some of the following RPCs' response structures reference types unique to this document. These are specified in [types referenced in state RPC responses](#types-referenced-in-state-rpc-responses). + +--- + +### state + +Get the state of a set of accounts (optionally including their contract code), and/or a set of storage tuples. + +```js +const response = await client.state( + new StateRequest({ accounts, include_contract, storage_keys }) +); +``` + +**Request** + +```ts +class StateRequest { + accounts: Set; + include_contract: boolean; + storage_keys: Map>; +} +``` + +**Response** + +```ts +class StateResponse { + accounts: Map; + storage_tuples: Map>; + block_hash: Sha256Hash; +} +``` + +--- + +### validator_sets + +Get the previous, current, and next validator sets, optionally including the stakes delegated to them. + +```js +const response = await client.validator_sets( + new ValidatorSetsRequest({ + include_prev, + include_prev_delegators, + include_curr, + include_curr_delegators, + include_next, + include_next_delegators + }) +); +``` + +**Request** + +```ts +class ValidatorSetsRequest { + include_prev: boolean; + include_prev_delegators: boolean; + include_curr: boolean; + include_curr_delegators: boolean; + include_next: boolean; + include_next_delegators: boolean; +} +``` + +**Response** + +```ts +class ValidatorSetsResponse { + // The inner Option is None if we are at Epoch 0. + prev_validator_set: Option>; + curr_validator_set: Option; + next_validator_set: Option; + block_hash: Sha256Hash; +} +``` + +--- + + +### pools + +Get a set of pools. + +```js +const response = await client.pools( + new PoolsRequest({ operators, include_stakes }) +); +``` + +**Request** + +```ts +class PoolsRequest { + operators: Set; + include_stakes: boolean; +} +``` + +**Response** + +```ts +class PoolsResponse { + pools: Map>; + block_hash: Sha256Hash; +} +``` + +--- + +### deposits + +Get a set of deposits. + +```js +const response = await client.deposits( + new DepositsRequest({ stakes }) +); +``` + +**Request** + +```ts +class DepositsRequest { + stakes: Set<[PublicAddress, PublicAddress]>; +} +``` + +**Response** + +```ts +class DepositsResponse { + deposits: Map<[PublicAddress, PublicAddress], Option>; + block_hash: Sha256Hash; +} +``` + +--- + +### stakes + +Get a set of stakes. + +```js +const response = await client.stakes( + new StakesRequest({ stakes }) +); +``` + +**Request** + +```ts +class StakesRequest { + stakes: Set<[PublicAddress, PublicAddress]>; +} +``` + +**Response** + +```ts +class StakesResponse { + stakes: Map<[PublicAddress, PublicAddress], Option>; + block_hash: Sha256Hash; +} +``` + +--- + + +### view + +Call a method in a contract in a read-only way. + +```js +const response = await client.view( + new ViewRequest({ target, method, args }) +); +``` + +**Request** + +```ts +class ViewRequest { + target: PublicAddress; + method: Uint8Array; + args: Option; +} +``` + +**Response** + +```ts +class ViewResponse { + receipt: CommandReceipt; +} +``` + +--- + + +## Types Referenced in State RPC Responses + +### Account-related types + +```ts +class Account extends Enum { + accountWithContract?: AccountWithContract; + accountWithoutContract?: AccountWithoutContract; +} + +class AccountWithContract { + nonce: u64; + balance: u64; + contract: Option; + cbi_version: Option; + storage_hash: Option; +} + +class AccountWithoutContract { + nonce: u64; + balance: u64; + cbi_version: Option; + storage_hash: Option; +} +``` + +### Staking-related types + +```ts +class ValidatorSet extends Enum { + poolsWithDelegator?: PoolWithDelegator[]; + poolsWithoutDelegator?: PoolWithoutDelegator[]; +} + +class PoolWithDelegators { + operator: PublicAddress; + power: u64; + commission_rate: number; + operator_stake: Option; + delegated_stakes: Stake[]; +} + +class PoolWithoutDelegators { + operator: PublicAddress; + power: u64; + commission_rate: number; + operator_stake: Option; +} + +class Deposit { + owner: PublicAddress; + balance: u64; + auto_stake_rewards: boolean; +} + +class Stake { + owner: PublicAddress; + power: u64; +} + +class Pool extends Enum { + poolWithDelegator?: PoolWithDelegator; + poolWithoutDelegator?: PoolWithoutDelegator; +} +``` \ No newline at end of file diff --git a/docs/for_developers/parallelchain_client_apis/rust_client_apis.md b/docs/for_developers/parallelchain_client_apis/rust_client_apis.md new file mode 100644 index 00000000..d3928ecb --- /dev/null +++ b/docs/for_developers/parallelchain_client_apis/rust_client_apis.md @@ -0,0 +1,627 @@ +--- +tags: + - Tools + - ParallelChain RPC API + - Rust + - Client +--- + +# Rust Client APIs + +ParallelChain RPC APIs are the HTTP APIs that Fullnodes make available to clients. + +In the section [ParallelChain Client Library](#parallelchain-client-library-rust), we introduce the Rust Library to make RPC calls programatically. + +The Client Library allows you to easily submit RPC requests and parse RPC responses without the need to understand the details of HTTP URL, request format or response format. The formation of HTTP APIs is specified in [ParallelChain Protocol](https://github.com/parallelchain-io/parallelchain-protocol/blob/master/RPC.md). + +## ParallelChain Client Library (Rust) + +[ParallelChain Client Library](https://github.com/parallelchain-io/pchain-client-rust) is a Rust programming language implementation of ParallelChain RPC API. We will show how to use the library by example code. To use the library in your rust project, first add dependency [pchain-client](https://crates.io/crates/pchain-client) in `Cargo.toml` file. You will also need the dependency [pchain-types](https://crates.io/crates/pchain-types) for necessary basic types, and the dependency [tokio](https://crates.io/crates/tokio) to run the client in asynchronous application. + +Cargo.toml: +```rust +[dependencies] +pchain-client = "0.4.3" +pchain-types = "0.4.3" +tokio = {version = "1", features = ["full"]} +``` + +You can instantiate the struct `pchain_client::Client` by providing the link to a ParallelChain RPC endpoint. + +```rust +#[tokio::main] +async fn main() { + /// Connect to Testnet RPC endpoint + let client = Client::new("https://pchain-test-rpc02.parallelchain.io"); + /// ... +} +``` + +!!! Note + RPC endpoints for [Mainnet](../../fundamentals/networks.md#parallelchain-mainnet) and [Testnet](../../fundamentals/networks.md#parallelchain-testnet) are `https://pchain-main-rpc02.parallelchain.io` and `https://pchain-test-rpc02.parallelchain.io` respectively. + +## Transaction Related RPCs + +### submit_transaction + +Submit a transaction to the mempool. + + +```rust +// The function submit_transaction creates SubmitTransactionRequest from the input transaction. +let response: SubmitTransactionResponse = client + .submit_transaction(&Transaction::new( + &signer, + nonce, + vec![Command::Transfer(TransferInput { + amount, + recipient, + })], + gas_limit, + max_base_fee_per_gas, + priority_fee_per_gas, + )) + .await + .unwrap(); +``` +!!! Note + The variable `signer` is the [Keypair](https://docs.rs/pchain-types/0.4.3/pchain_types/cryptography/type.Keypair.html) of the [EOA](../../fundamentals/accounts.md) as the signer of the transaction. Check out the module [pchain_types::cryptograhy](https://docs.rs/pchain-types/0.4.3/pchain_types/cryptography/index.html) for generating or importing keypair. + + In case you need free tokens for submitting transactions to Testnet, check out the [Faucet Service](../../fundamentals/networks.md#faucet-service) for details. + +**Request** + +```rust +struct SubmitTransactionRequest { + transaction: Transaction, +} +``` + +**Response** + +```rust +struct SubmitTransactionResponse { + error: Option, +} +``` + +Where `SubmitTransactionError`: +```rust +enum SubmitTransactionError { + UnacceptableNonce, + MempoolFull, + Other, +} +``` + +--- + +### transaction + +Get a transaction and optionally its receipt. + + +```rust +let response: TransactionResponse = client + .transaction(&TransactionRequest { + transaction_hash, + include_receipt, + }) + .await + .unwrap(); +``` + +**Request** + +```rust +struct TransactionRequest { + transaction_hash: CryptoHash, + include_receipt: bool, +} +``` + +**Response** + +```rust +struct TransactionResponse { + transaction: Option, + receipt: Option, + block_hash: Option, + position: Option, +} +``` + +--- + +### transaction_position + +Find out where a transaction is in the blockchain. + +```rust +let response: TransactionPositionResponse = client + .transaction_position(&TransactionPositionRequest { transaction_hash }) + .await + .unwrap(); +``` + +**Request** + +```rust +struct TransactionPositionRequest { + transaction_hash: CryptoHash, +} +``` + +**Response** + +```rust +struct TransactionPositionResponse { + transaction_hash: Option, + block_hash: Option, + position: Option, +} +``` + +--- + +### receipt + +Get a transaction's receipt. + +```rust +let response: ReceiptResponse = client + .receipt(&ReceiptRequest { transaction_hash }) + .await + .unwrap(); +``` + +**Request** + +```rust +struct ReceiptRequest { + transaction_hash: CryptoHash, +} +``` + +**Response** + +```rust +struct ReceiptResponse { + transaction_hash: CryptoHash, + receipt: Option, + block_hash: Option, + position: Option, +} +``` + +## Block Related RPCs + +### block + +Get a block by its block hash. + +```rust +let response: BlockResponse = client + .block(&BlockRequest { block_hash }) + .await + .unwrap(); +``` + +**Request** + +```rust +struct BlockRequest { + block_hash: CryptoHash, +} +``` + +**Response** + +```rust +struct BlockResponse { + block: Option, +} +``` + +--- + +### block_header + +Get a block header by its block hash. + +```rust +let response: BlockHeaderResponse = client + .block_header(&BlockHeaderRequest { block_hash }) + .await + .unwrap(); +``` + +**Request** + +```rust +struct BlockHeaderRequest { + block_hash: CryptoHash, +} +``` + +**Response** + +```rust +struct BlockHeaderResponse { + block_header: Option, +} +``` + +--- + +### block_height_by_hash + +Get the height of the block with a given block hash. + +```rust +let response: BlockHeightByHashResponse = client + .block_height_by_hash(&BlockHeightByHashRequest { block_hash }) + .await + .unwrap(); +``` + +**Request** + +```rust +struct BlockHeightByHashRequest { + block_hash: CryptoHash, +} +``` + +**Response** + +```rust +struct BlockHeightByHashResponse { + block_hash: CryptoHash, + block_height: Option, +} +``` + +--- + +### block_hash_by_height + +Get the hash of a block at a given height. + +```rust +let response: BlockHashByHeightResponse = client + .block_hash_by_height(&BlockHashByHeightRequest { block_height }) + .await + .unwrap(); +``` + +**Request** + +```rust +struct BlockHashByHeightRequest { + block_height: BlockHeight, +} +``` + +**Response** + +```rust +struct BlockHashByHeightResponse { + block_height: BlockHeight, + block_hash: Option, +} +``` + +--- + +### highest_committed_block + +Get the hash of the highest committed block. + +```rust +let response: HighestCommittedBlockResponse = client + .highest_committed_block() + .await + .unwrap(); +``` + +**Request** + +None. + +**Response** + +```rust +struct HighestCommittedBlockResponse { + block_hash: Option, +} +``` + +## State Related RPCs + +State RPCs return multiple entities in the world state in a single response. This allows clients to get a consistent snapshot of the world state in a single call. + +Every response structure includes the hash of the highest committed block when the snapshot is taken. + +Some of the following RPCs' response structures reference types unique to this document. These are specified in [types referenced in state RPC responses](#types-referenced-in-state-rpc-responses). + +--- + +### state + +Get the state of a set of accounts (optionally including their contract code), and/or a set of storage tuples. + +```rust +let response: StateResponse = client + .state(&StateRequest { + accounts, + include_contract, + storage_keys, + }) + .await + .unwrap(); +``` + +**Request** + +```rust +struct StateRequest { + accounts: HashSet, + include_contracts: bool, + storage_keys: HashMap>>, +} +``` + +**Response** + +```rust +struct StateResponse { + accounts: HashMap, + storage_tuples: HashMap, Vec>>, + block_hash: CryptoHash, +} +``` + +--- + +### validator_sets + +Get the previous, current, and next validator sets, optionally including the stakes delegated to them. + +```rust + let response: ValidatorSetsResponse = client + .validator_sets(&ValidatorSetsRequest { + include_prev, + include_prev_delegators, + include_curr, + include_curr_delegators, + include_next, + include_next_delegators, + }) + .await + .unwrap(); +``` + +**Request** + +```rust +struct ValidatorSetsRequest { + include_prev: bool, + include_prev_delegators: bool, + include_curr: bool, + include_curr_delegators: bool, + include_next: bool, + include_next_delegators: bool, +} +``` + +**Response** + +```rust +struct ValidatorSetsResponse { + // The inner Option is None if we are at Epoch 0. + prev_validator_set: Option>, + curr_validator_set: Option, + next_validator_set: Option, + block_hash: CryptoHash, +} +``` + +--- + +### pools + +Get a set of pools. + +```rust +let response = client + .pools(&PoolsRequest { + include_stakes, + operators, + }) + .await + .unwrap(); +``` + +**Request** + +```rust +struct PoolsRequest { + operators: HashSet, + include_stakes: bool, +} +``` + +**Response** + +```rust +struct PoolsResponse { + pools: HashMap>, + block_hash: CryptoHash, +} +``` + +--- + +### deposits + +Get a set of deposits. + +```rust +let response: DepositsResponse = client + .deposits(&DepositsRequest { stakes }) + .await + .unwrap(); +``` + +**Request** + +```rust +struct DepositsRequest { + stakes: HashSet<(Operator, Owner)>, +} +``` + +**Response** + +```rust +struct DepositsResponse { + deposits: HashMap<(Operator, Owner), Option>, + block_hash: CryptoHash, +} +``` + +--- + +### stakes + +Get a set of stakes. + +```rust +let response: StakesResponse = client + .stakes(&StakesRequest { stakes }) + .await + .unwrap(); +``` + +**Request** + +```rust +struct StakesRequest { + stakes: HashSet<(Operator, Owner)>, +} +``` + +**Response** + +```rust +struct StakesResponse { + stakes: HashMap<(Operator, Owner), Option>, + block_hash: CryptoHash, +} +``` + +--- + +### view + +Call a method in a contract in a read-only way. + +```rust +let response: ViewResponse = client + .view(&ViewRequest { + target, + method, + arguments, + }) + .await + .unwrap(); +``` + +**Request** + +```rust +struct ViewRequest { + target: PublicAddress, + method: Vec, + arguments: Option>>, +} +``` + +**Response** + +```rust +struct ViewResponse { + receipt: CommandReceipt, +} +``` + +--- + +## Types Referenced in State RPC Responses + +### Account-related types +```rust +enum Account { + WithContract(AccountWithContract), + WithoutContract(AccountWithoutContract), +} + +struct AccountWithContract { + nonce: Nonce, + balance: Balance, + contract: Option>, + cbi_version: Option, + storage_hash: Option, +} + +struct AccountWithoutContract { + nonce: Nonce, + balance: Balance, + cbi_version: Option, + storage_hash: Option, +} +``` + +### Staking-related types + +```rust +enum ValidatorSet { + WithDelegators(Vec), + WithoutDelegators(Vec), +} + +type Operator = PublicAddress; +type Owner = PublicAddress; + +struct PoolWithDelegators { + operator: PublicAddress, + power: Balance, + commission_rate: u8, + operator_stake: Option, + delegated_stakes: Vec, +} + +struct PoolWithoutDelegators { + operator: PublicAddress, + power: Balance, + commission_rate: u8, + operator_stake: Stake, +} + +struct Deposit { + owner: PublicAddress, + balance: u64, + auto_stake_rewards: bool, +} + +struct Stake { + owner: PublicAddress, + power: Balance, +} + +enum Pool { + WithStakes(PoolWithStakes), + WithoutStakes(PoolWithoutStakes), +} +``` \ No newline at end of file diff --git a/docs/developer_guides/smart_contract_sdk/advance/params.md b/docs/for_developers/smart_contracts/advanced/accessing_info_about_blockchain.md similarity index 85% rename from docs/developer_guides/smart_contract_sdk/advance/params.md rename to docs/for_developers/smart_contracts/advanced/accessing_info_about_blockchain.md index 8946de91..a90e0af0 100644 --- a/docs/developer_guides/smart_contract_sdk/advance/params.md +++ b/docs/for_developers/smart_contracts/advanced/accessing_info_about_blockchain.md @@ -8,9 +8,9 @@ tags: # Accessing Information about the Blockchain -Contract Methods can be written not only depending on call arguments and the contract's storage, but also on information about the Blockchain, e.g., the previous block hash, or the identity of the External Account that originated the Call Transaction. +Contract Methods can be written to not only depend on call arguments and the contract's storage, but also on information about the Blockchain, e.g., the previous block hash, or the identity of the External Account that originated the Transaction with Call Command. -Functions for getting information about the Transaction that triggered a Contract call and information about the larger Blockchain, in general, are defined in `pchain_sdk::transaction` and `pchain_sdk::blockchain` respectively. Internally, these functions are thin wrappers around functions defined in the Imports Set of the Contract ABI. +Functions for getting information about the Transaction that triggered a Contract call and information about the larger Blockchain in general are defined in `pchain_sdk::transaction` and `pchain_sdk::blockchain` respectively. Internally, these functions are thin wrappers around functions defined in the Imports Set of the CBI. ## Parameters from Blockchain and Transaction diff --git a/docs/for_developers/smart_contracts/advanced/contract_methods.md b/docs/for_developers/smart_contracts/advanced/contract_methods.md new file mode 100644 index 00000000..0a58bec7 --- /dev/null +++ b/docs/for_developers/smart_contracts/advanced/contract_methods.md @@ -0,0 +1,39 @@ +--- +tags: + - pchain-sdk + - Smart Contract + - Contract Methods +--- + +In ParallelChain Smart Contract Programming Model, a contract is like a `Rust` `struct` that controls access to persistent storage. Accounts can interact with contracts by submitting transactions that include a call command to invoke methods of the contract. These methods are sometimes called just "methods" for short. + +## Contract Methods + +The Model defines methods with macro `#[call]` as Contract Methods, each corresponding to a method that is callable to a Call Command in the CBI Subprotocol. + +In order to produce to appropriate CBI Exports Set bindings that ultimately allow Methods to be called from the outside world, you must write Method definitions inside an `impl Contract` statement marked with the `#[contract_methods]` macro, as illustrated in the following examples. + +```rust +#[contract_methods] +impl PrinceTheDog { + #[call] + pub fn eat_food(&mut self, food: DogFood) { + ... + } +} +``` + +Methods may mutate Contract Storage. Note however, that (as specified in the Transaction Subprotocol) mutations to Contract Storage made in a Call Transaction only get applied if the Transaction is Successful (e.g., the Transaction must exit with sufficient gas, must have not panicked during execution, etc.). + +A function can be called if and only if: + +1. The macro #[call] is added above the function declaration. +2. Its (zero or more) other arguments implement BorshDeserialize. +3. Its return value implements BorshSerialize, or it does not have a return value. + + +## Accepting Parameters and Returning Values + +Some of the code snippets provided as examples in this document depict Contract Methods that take in function arguments (besides a borrow of the Contract struct) and/or return a value. In order for a Contract to receive arguments from and return values to the 'outside world' (callers), both Contract and caller need to agree on a serialization format. + +`pchain-sdk` expects callers to serialize Method arguments using the [borsh](https://crates.io/crates/borsh) serialization standard, and generates code to serialize values into borsh for inclusion in a Transaction's Receipt. To be precise, Transaction Command Call specify the Contract Method to call and provide the arguments for the call by including a borsh-serialized data structure `Option>>` in its `arguments` field, and contracts include a borsh-serialized `ContractMethodOutput` struct. The former type is defined in `pchain-types`, while the latter is defined in `pchain-sdk`. In the future, we plan to move both into the SDK. \ No newline at end of file diff --git a/docs/developer_guides/smart_contract_sdk/advance/contract_storage.md b/docs/for_developers/smart_contracts/advanced/contract_storage.md similarity index 97% rename from docs/developer_guides/smart_contract_sdk/advance/contract_storage.md rename to docs/for_developers/smart_contracts/advanced/contract_storage.md index 1966af5b..54f90d3a 100644 --- a/docs/developer_guides/smart_contract_sdk/advance/contract_storage.md +++ b/docs/for_developers/smart_contracts/advanced/contract_storage.md @@ -30,7 +30,6 @@ struct DogToy { ``` ## Accessing Storage ---- SDK provides functions to access Storage by read-write operations. The function `get_network_state` is particularly used to get the state from the Network Account of the blockchain. @@ -46,7 +45,6 @@ pub fn set(key: &[u8], value: &[u8]); ``` ## Storage and Collections ---- Because Storage is so gas-expensive, loading all of a Contract's fields before Method execution and writing them all into Storage after execution typically results in Contracts that are not very economical. For Contracts that do not keep much in Storage, or whose Methods *always* read and write into most fields, this may be okay, or even ideal, however, some applications cannot avoid keeping a lot of on-chain states, and for these applications eagerly loading and saving fields in every call may be unacceptably expensive. @@ -94,7 +92,7 @@ impl Pet { Lazily stores a list of items in `Storage`. Vector implements `Index`, `IndexMut`, and has an `iter` method, so most of the things you can do with `std::vec::Vec`, you can probably do with `Vector` too. -In the below example, the contract field `nicknames` is a `Vector` of `String`. It loads data from the world state only when it is needed to be read, and stores data after the method call. It calls `iter()` to get an iterator as `std::vec::Vec` and cal `push()` to save data to the world state. Besides, it supports indexing for accessing particular indexed elements. +In the below example, the contract field `nicknames` is a `Vector` of `String`. It loads data from the world state only when it is needed to be read, and stores data after the method call. It calls `iter()` to get an iterator as `std::vec::Vec`, and calls `push()` to save data to the world state. Besides, it supports indexing for accessing particular indexed elements. ```rust #[contract] diff --git a/docs/for_developers/smart_contracts/advanced/cross_contract_call.md b/docs/for_developers/smart_contracts/advanced/cross_contract_call.md new file mode 100644 index 00000000..ee4afd97 --- /dev/null +++ b/docs/for_developers/smart_contracts/advanced/cross_contract_call.md @@ -0,0 +1,27 @@ +--- +tags: + - pchain-sdk + - Smart Contract + - Cross Contract Call +--- + +# Cross Contract Call + +The SDK includes a pair of functions to make Contract-To-Contract internal calls: + +- `call` and `call_untyped` + +It does the obvious: to call a method in a specified Contract with the given arguments. + +Related APIs in `pchain_sdk::internal`: + +```rust +/// A call to contract. The caller should already know the data type of return value from the function call. +/// It returns Option of T where T is return value from the function. +/// If data type T is different from the actual return value type of the function, None is returned. +fn call(address: PublicAddress, method_name: &str, arguments: Vec, value: u64) -> Option; + +/// A call to contract, with vector of bytes as return type. +/// It returns Option of Vec of bytes. Interpretation on the bytes depends on caller +fn call_untyped(contract_address: PublicAddress, method_name: &str, arguments: Vec, value: u64) -> Option>; +``` \ No newline at end of file diff --git a/docs/developer_guides/smart_contract_sdk/advance/crypto.md b/docs/for_developers/smart_contracts/advanced/cryptographic_functions.md similarity index 53% rename from docs/developer_guides/smart_contract_sdk/advance/crypto.md rename to docs/for_developers/smart_contracts/advanced/cryptographic_functions.md index a36d726e..a9f35a8c 100644 --- a/docs/developer_guides/smart_contract_sdk/advance/crypto.md +++ b/docs/for_developers/smart_contracts/advanced/cryptographic_functions.md @@ -9,7 +9,7 @@ tags: Cryptographic Function refers to cryptographic functions that are supported from execution runtime so that gas cost can be reduced by avoiding implementation inside a contract. Moreover, It helps in providing complicated calculations which are not feasible in the Wasmer environment (e.g. encryption, hashing). -In ParallelChain Mainnet SDK, precompiles are a set of functions that can be called directly. Please be noted that some functions are selected based on the popularity of the blockchain ecosystem, but are not necessary adopted in the implementation of the ParallelChain Mainnet node. +Please be noted that some functions are selected based on the popularity of the blockchain ecosystem, but are not necessary adopted in the implementation of the ParallelChain Mainnet node. | Function | Description | Gas Cost | |:---|:---|:---| @@ -20,10 +20,16 @@ In ParallelChain Mainnet SDK, precompiles are a set of functions that can be cal The gas consumption is estimated by the compute costs for precompile functions used by developers to deploy smart contracts on ParallelChain Mainnet. -To use the functions, include the module `crypto` and then call the associate methods. For example, +Related APIs in `pchain_sdk::crypto`: ```rust -use pchain_sdk::crypto; - -crypto::sha256(input); +/// Computes the SHA256 digest (32 bytes) of arbitrary input. +fn sha256(input: Vec) -> Vec; +/// Computes the Keccak256 digest (32 bytes) of arbitrary input. +fn keccak256(input: Vec) -> Vec; +/// Computes the RIPEMD160 digest (20 bytes) of arbitrary input. +fn ripemd(input: Vec) -> Vec; +/// Returns whether an Ed25519 signature was produced by a specified by a specified address over some specified message. +/// Contract call fails if the input `address` or `signature` is not valid. +fn verify_ed25519_signature(input: Vec, signature: Vec, address: Vec) -> bool; ``` \ No newline at end of file diff --git a/docs/developer_guides/smart_contract_sdk/advance/staking.md b/docs/for_developers/smart_contracts/advanced/staking_in_contract.md similarity index 51% rename from docs/developer_guides/smart_contract_sdk/advance/staking.md rename to docs/for_developers/smart_contracts/advanced/staking_in_contract.md index 697c5e9b..18cbc9d2 100644 --- a/docs/developer_guides/smart_contract_sdk/advance/staking.md +++ b/docs/for_developers/smart_contracts/advanced/staking_in_contract.md @@ -5,14 +5,13 @@ tags: - Staking --- -Contract address can be used as owner in staking, in other words, to perform staking on behalf of a contract. It is done by invoking a contract call to create Network command(s) (i.e. Create Deposit, TopupDeposit, ... etc) inside the contract method. The execution of these network commands will be deferred after the successful execution of the entire contract call. To create deferred network command, you can call functions `defer_*` provided by the SDK. +Contract address can be used as owner in staking, in other words, to perform staking on behalf of a contract. It is done by invoking a contract call to create [staking command(s)](../../../fundamentals/transactions.md#staking-commands) (i.e. Create Deposit, TopupDeposit, ... etc) inside the contract method. The execution of these staking commands will be deferred after the successful execution of the entire contract call. To create deferred staking command, you can call functions `defer_*` provided by the SDK. -__Notes:__ - -- The owner of the staking is using a contract address. -- There is no additional command receipt. Failure of deferred network command execution results in failure of the entire contract call. -- The `return values` in the final receipt will be overwritten (if any) by the network command. -- In the cross-contract-call scenario, deferred network command is not executed after the internal contract call, but after the origin contract call. +!!! Notes + - The owner of the staking is using a contract address. + - There is no additional command receipt. Failure of deferred staking command execution results in failure of the entire contract call. + - The `return values` in the final receipt will be overwritten (if any) by the staking command. + - In the cross-contract-call scenario, deferred staking command is not executed after the internal contract call, but after the origin contract call. Related APIs in `pchain_sdk::network`: @@ -29,6 +28,4 @@ fn defer_withdraw_deposit(operator: PublicAddress, max_amount: u64); fn defer_stake_deposit(operator: PublicAddress, max_amount: u64); /// Remove stakes from an existing Pool. fn defer_unstake_deposit(operator: PublicAddress, max_amount: u64); -``` - -Check out the [Tutorial 6](../tutorial/chapter_6.md) for the tutorial on using `defer` calls in smart contracts. \ No newline at end of file +``` \ No newline at end of file diff --git a/docs/developer_guides/smart_contract_sdk/advance/internal_transaction.md b/docs/for_developers/smart_contracts/advanced/transferring_balance.md similarity index 80% rename from docs/developer_guides/smart_contract_sdk/advance/internal_transaction.md rename to docs/for_developers/smart_contracts/advanced/transferring_balance.md index a9f44bb6..9812512d 100644 --- a/docs/developer_guides/smart_contract_sdk/advance/internal_transaction.md +++ b/docs/for_developers/smart_contracts/advanced/transferring_balance.md @@ -11,15 +11,16 @@ tags: `pchain_sdk::transfer` transfers the balance from the Contract Account to another Account and returns the balance of the recipient after the transfer. +Related API in `pchain_sdk::internal`: + ```rust /// Transfer the balance amount to another address. fn transfer(recipient: PublicAddress, amount: u64); ``` -__Notes:__ - -- Balance is deducted from the contract, but not the caller's account. -- Gas cost is deducted from the caller's account. +!!! Notes + - Balance is deducted from the contract, but not the caller's account. + - Gas cost is deducted from the caller's account. Example: diff --git a/docs/for_developers/smart_contracts/getting_started.md b/docs/for_developers/smart_contracts/getting_started.md new file mode 100644 index 00000000..f2131d50 --- /dev/null +++ b/docs/for_developers/smart_contracts/getting_started.md @@ -0,0 +1,270 @@ +--- +tags: + - pchain-sdk + - Smart Contract +--- + +# Getting Started + +Before we dive deep into the structure of a contract and the SDK's semantics, we require some background information about the semantics enforced by ParallelChain Mainnet. The full capabilities of ParallelChain Mainnet continue to grow with active developers +and a growing community. Let's see how smart contracts are called and processed by a node in the form of transactions. + +First, the ParallelChain Client (`pchain_client`) will submit a transaction when making a smart contract call to the validating node using a serialization crate [pchain-types](https://crates.io/crates/pchain-types). The node's RPC service and mempool will process the list of transactions and check for validity and correctness. + +[Transactions](../../fundamentals/transactions.md#how-transaction-works) that fail the validation check may not be included in a [block](../../fundamentals/blocks.md#how-block-works). The transactions are then packed in a block and sent to the execution engine in the node to execute the transactions. + +The executor will call [wasmer](https://crates.io/crates/wasmer) (Web Assembly Engine) which provides an isolated context to perform the execution. This enables the smart contract code to read the current state of the blockchain and interact with it. However, the execution results are temporarily stored and subject to further checks before the block may be committed or rolled back on error. + +`wasmer` also computes the [gas](../../fundamentals/gas.md) fees through a metering module, which is responsible for limiting the execution to the amount of gas paid. Each transaction returns a result in the form of receipts along with logs. The receipts (with or without log), transactions and block itself will contain its hash (or Merkle proof) and will be all included in the same block. + + +## Smart Contract Development Kit + +Smart Contract can be created by using [ParallelChain SDK](https://github.com/parallelchain-io/pchain-sdk). Example contracts can be found in [example-smart-contracts](https://github.com/parallelchain-io/example-smart-contracts). + +A ParallelChain Smart Contract is a rust crate that imports the SDK. It uses the SDK's features to interact with the blockchain. The folder structure of a typical ParallelChain +Mainnet Smart Contract looks like this: +```bash +my_first_contract +├── src/ +│ └── lib.rs # The main source code of your smart contract. +└── Cargo.toml # You import your packages and the SDK here +``` + +For more information on Rust's crate system, see [Rust Book Chapter 7: Packages and Crates](https://doc.rust-lang.org/stable/book/ch07-01-packages-and-crates.html) + +Please specify the dependency in `Cargo.toml` for using SDK by fetching from [crates.io](https://crates.io/) or repository in Github. + +=== "Crates.io" + ```toml + [lib] + crate-type = ["cdylib"] + + [dependencies] + pchain-sdk = "0.4" + ``` + +=== "Github" + ```toml + [lib] + crate-type = ["cdylib"] + + [dependencies] + pchain-sdk = { git = "https://github.com/parallelchain-io/pchain-sdk" } + ``` + +### Implement Smart Contract + +Let's start with a sample smart contract for illustration in this guide. The smart contract code is written in the file `lib.rs`. + +```rust +use pchain_sdk::{call, contract, contract_methods}; + +#[contract] +struct MyContract { } + +#[contract_methods] +impl MyContract { + + #[call] + fn hello_from(name :String) -> u32 { + pchain_sdk::log( + "topic: Hello From".as_bytes(), + format!("Hello, Contract. From: {}", name).as_bytes() + ); + name.len() as u32 + } +} +``` + +The details about the macros (e.g. `contract`, `contract_methods`, `call`) used in the code can be found in later sections [Contract Methods](./advanced/contract_methods.md) and [Contract Storage](./advanced/contract_storage.md). Let's skip knowing them first, and continue reading about building and deploying the contract in following sections. + +## Building The Contract With `pchain_compile` + +[pchain_compile](https://github.com/parallelchain-io/pchain-compile) is a CLI build tool for smart contract developers to build their source code to WASM binaries for deployment on +ParallelChain Mainnet. + +The WASM binary generated from a generic cargo build process has the following disadvantages: + + - The build process is not toolchain version agnostic i.e. it does not guarantee uniform WASM binaries with different versions of compiler and + rust crate dependencies. This will make it difficult for smart contract developers to verify their source code on the blockchain. + + - The build process generates a large file size, which leads to higher gas costs for deployment and contract calls. + +**pchain_compile** solves these shortcomings by: + + - Executing the build process in a docker environment with pre-defined toolchain versioning. + + - Optimizing and compressing the size of the WASM binary with the help of [wasm-snip](https://crates.io/crates/wasm-snip) and [wasm-opt](https://crates.io/crates/wasm-opt) packages. + + +### Download **pchain_compile** + +`pchain_compile` supports Linux, macOS and Windows. Depending on the operating system, they can be downloaded from Assets of ParallelChain Lab's Git Hub [release page](https://github.com/parallelchain-io/pchain-compile/releases). + +The binary can also be installed and built by executing the following commands: +``` +cargo install pchain_compile +``` + +!!! Pre-Requisites + `pchain_compile` builds the source code in a docker environment. To know more about Docker and install it, refer to the [official instructions](https://docs.docker.com/engine/install/). + + + +### Build WASM Binary + +In order to build a `WASM` binary of the smart contract, run the following command: + +=== "Linux / macOS" + ```bash + ./pchain_compile build --source + ``` +=== "Windows PowerShell" + ```PowerShell + ./pchain_compile.exe build --source + ``` + +If you installed `pchain_compile` with `cargo install`, you can simply run: + +``` +pchain_compile build --source +``` + +A `.wasm` file will be generated in the current directory. + +## Deploying a Smart Contract + +You can deploy the contract using the pchain_client command line tool. You should make sure to [know your latest account nonce](../../for_users/pchain_client_cli/querying_blockchain.md#check-account-related-information) before submitting the transaction. + +=== "Linux / macOS" + ```bash + ./pchain_client transaction create + --nonce \ + --gas-limit \ + --max-base-fee-per-gas \ + --priority-fee-per-gas \ + deploy \ + --contract-code \ + --cbi-version + ``` +=== "Windows PowerShell" + ```PowerShell + ./pchain_client.exe transaction create ` + --nonce ` + --gas-limit ` + --max-base-fee-per-gas ` + --priority-fee-per-gas ` + deploy ` + --contract-code ` + --cbi-version + ``` + +You can follow the instruction in [Create Transaction](../../for_users/pchain_client_cli/creating_transaction.md) about submiting a transaction through `pchain-client`. + +## Checking Contract In State + +To verify that the smart contract is deployed correctly, you can run the command `query` with the flag `contract`. It queries the state of the blockchain and saves the wasm code as `code.wasm` in the current directory. +If you want to store the contract file in your preferred location, you need to provide the flag `destination` to specify the path with your preferred file extension: + +=== "Linux / macOS" + ```bash + ./pchain_client query contract --address + ``` +=== "Windows PowerShell" + ```PowerShell + ./pchain_client.exe query contract --address + ``` + +## Calling Contract + +Suppose you have already deployed a contract that contains a `call` method named `hello_from` as mentioned in previous section [Implement Smart Contract](#implement-smart-contract): + +> +```rust +#[call] +fn hello_from(name :String) -> u32 +``` + +To invoke this contract by using `pchain_client`, you can prepare a JSON file that contains a list of arguments and matches with the `call` method. For example, this `call` method takes a string argument. Then, the content of the JSON file should be as follows: + +```json +{ + "arguments": [ + {"argument_type":"String", "argument_value": "\"Alice\""} + ] +} +``` + +This JSON file will be used in creating a transaction with [Call Command](../../fundamentals/transactions.md#account-commands). + +### Submit Transaction With Call Command + +To call a smart contract, submit a transaction with your account nonce and contract address using the `pchain_client`. + +Here is the command to call a contract: + +=== "Linux / macOS" + ```bash + ./pchain_client transaction create \ + --nonce \ + --gas-limit \ + --max-base-fee-per-gas \ + --priority-fee-per-gas \ + call \ + --target \ + --method \ + --arguments + --amount \ + ``` +=== "Windows PowerShell" + ```PowerShell + ./pchain_client.exe transaction create ` + --nonce ` + --gas-limit ` + --max-base-fee-per-gas ` + --priority-fee-per-gas ` + call ` + --target ` + --method ` + --arguments ` + --amount + ``` + +The command argument `method` is the name of the method with macro `#[call]` in the code. Take the contract in [Implement Smart Contract](#implement-smart-contract) as example, "hello_from" should be set as the value of the command argument `method`. + +The command argument `arguments` is the JSON file that contains the method arguments to the method being called in the contract. The way to create this JSON file is described in previous section [Calling Contract](#calling-contract). + +The gas limit required for the transaction depends on the complexity of the smart contract. For safety reasons, you can always set a higher gas limit. You can also test contract calls on testnet to reassure. + +You can follow the instruction in [Create Transaction](../../for_users/pchain_client_cli/creating_transaction.md) about submiting a transaction through `pchain-client`. + +To query the resulting receipt of the transaction, + +=== "Linux / macOS" + ```bash + ./pchain_client query tx --hash + ``` +=== "Windows PowerShell" + ```PowerShell + ./pchain_client.exe query tx --hash + ``` + +The commands stored in `transaction` and command receipts in `receipt` are following the same order. That means you can always find the corresponding transaction from a command receipt. + +### Parse Call Result + +To parse the response from the contract method, represented in the field named `return value` , which is in `CallResult` format, you can use the `parse call-result` command in ParallelChain Client. + +For example, if the contract method returns a u32 integer, the `return value` is "BAAAAAUAAAA" you can parse the `CallResult` data structure using the `--data-type u32` flag: + +=== "Linux / macOS" + ```bash + pchain_client parse call-result --value BAAAAAUAAAA --data-type u32 + ``` +=== "Windows PowerShell" + ```PowerShell + ./pchain_client.exe parse call-result --value BAAAAAUAAAA --data-type u32 + ``` + +The output will be the parsed value of the `CallResult`, which in this case is `4`. For more details, you can use the `help` command to see the usage of the tool or take a look at the example `argument,json`. \ No newline at end of file diff --git a/docs/developer_guides/smart_contract_sdk/installation.md b/docs/for_developers/smart_contracts/installing_sdk.md similarity index 50% rename from docs/developer_guides/smart_contract_sdk/installation.md rename to docs/for_developers/smart_contracts/installing_sdk.md index 01ed4d25..23adeb9f 100644 --- a/docs/developer_guides/smart_contract_sdk/installation.md +++ b/docs/for_developers/smart_contracts/installing_sdk.md @@ -5,20 +5,17 @@ tags: - Rust --- -## Install Rust ---- +## Installing Rust -To install the required toolkits, the standard method is by `rustup`, which maintains dependencies and is a version manager for `cargo` and `rustc` (the rust compiler). Detailed installation instructions can be found on the [official website](https://www.rust-lang.org/tools/install) +To install the required toolkits, the standard method is by `rustup`, which maintains dependencies and is a version manager for `cargo` and `rustc` (the rust compiler). Detailed installation instructions can be found on the [official website](https://www.rust-lang.org/tools/install). ## Setting up a Development Environment ---- -A recommended Integrated Development Environment (IDE) is [VSCode](https://code.visualstudio.com/), which allows the addition of the [rust](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust) plugin or [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=matklad.rust-analyzer) to type-check all of your code on save. This feature allows you to locate errors in the code easily, and the error messages displayed in the IDE are the same as when executing the `cargo build` command. However, any other editor that is comfortable for you can be used. However, any other editor that is comfortable for you can be used. +A recommended Integrated Development Environment (IDE) is [VSCode](https://code.visualstudio.com/), which allows the addition of the plugin [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=matklad.rust-analyzer) to type-check all of your code on save. This feature allows you to locate errors in the code easily, and the error messages displayed in the IDE are the same as when executing the `cargo build` command. However, any other editor that is comfortable for you can be used. However, any other editor that is comfortable for you can be used. -## Install Wasm Toolchain (Optional) ---- +## Installing Wasm Toolchain (Optional) -ParallelChain Mainnet also provides a smart contract compilation tool called `pchain-compile` to compile your Rust smart contract into WASM bytecode. While not necessary, the Installation of Wasm Toolchain can help check if your code is compilable before using the time-consuming process in the use of `pchain-compile`. +ParallelChain Mainnet also provides a smart contract compilation tool called [pchain-compile](getting_started.md#building-the-contract-with-pchain_compile) to compile your Rust smart contract into WASM bytecode. While not necessary, the Installation of Wasm Toolchain can help check if your code is compilable before using the time-consuming process in the use of `pchain-compile`. The `wasm32-unknown-unknown` toolchain is required for smart contracts to compile as WASM. To add the wasm toolchain in Rust, type the command below: ```bash diff --git a/docs/for_developers/smart_contracts/introduction.md b/docs/for_developers/smart_contracts/introduction.md new file mode 100644 index 00000000..6e3197a1 --- /dev/null +++ b/docs/for_developers/smart_contracts/introduction.md @@ -0,0 +1,40 @@ +--- +tags: + - pchain-sdk + - Smart Contract +--- + +# Introduction to Smart Contracts + +A **smart contract** presents a method of executing computer programs on a decentralized network with security and fault tolerance. Through smart contracts, users can develop code to support their most crucial business applications, all within a global, decentralized network. + +To use smart contracts on ParallelChain Mainnet, developers can write a Contract Binary Interface (CBI) Subprotocol that is implemented in [WebAssembly](https://webassembly.org) (WASM). However, for most developers, it's easier to use the [ParallelChain Mainnet Contract SDK](#parallelchain-mainnet-contract-sdk) (`pchain-sdk`) to write a Contract in **Rust**, and subsequently use a tool named [pchain-compile](getting_started.md#building-the-contract-with-pchain_compile) to compile the Rust source code into WASM bytecode. + + +## Smart Contract Programming Model + +The Smart Contract Programming Model follows Object-Oriented Programming (OOP) principles. In this model, a contract resembles a Rust `struct` that regulates access to persistent storage. Accounts can engage with contracts by submitting transactions containing a call command to invoke the contract's methods. These methods are commonly referred to as just "methods". + +## Why Rust and WebAssembly (WASM)? + +Writing smart contracts in Rust and executing them as WebAssembly (WASM) bytecode on a blockchain has several benefits: + +1. **Efficiency and Security**: [Rust](https://www.rust-lang.org) is a systems programming language that provides a balance between performance and safety. It is designed to prevent common programming errors such as null pointer dereferencing and buffer overflows, which can cause security vulnerabilities. Rust's ownership model and borrow checker also help prevent memory leaks and race conditions. When compiled to WASM, Rust code can run efficiently and securely on a blockchain. + +2. **Interoperability**: WASM is a binary format that can be executed in different environments, such as web browsers and servers. This means that smart contracts written in programming languages and compiled to [WASM](https://webassembly.org) can be executed on the blockchain that supports the WASM execution context. This provides more options for developers to choose from and promotes interoperability between different blockchain ecosystems. + +2. **Tooling and Ecosystem**: Rust has a rich ecosystem of libraries and tools for building systems and applications. This includes the mentioned `pchain-sdk`, which provides types and macros for writing smart contracts in Rust for the ParallelChain Mainnet blockchain. Rust's [cargo](https://crates.io) package manager also makes it easy to manage dependencies and build projects. By leveraging the Rust ecosystem, developers can build smart contracts faster and with less effort. + +3. **Community Support**: Rust has a growing community of developers and contributors who are passionate about the language and its ecosystem. This means that there are resources available for learning Rust and getting help when needed. It also means that the language and ecosystem are constantly evolving and improving. + +## ParallelChain Mainnet Contract SDK + +The [ParallelChain Mainnet Contract SDK](https://github.com/parallelchain-io/pchain-sdk) (pchain-sdk) is an open-source Rust crate designed to aid in smart contract development. It furnishes Rust structs, functions, types, and macros to facilitate the creation of smart contracts executable in **WebAssembly (WASM)** engines, implementing the **ParallelChain Mainnet Contract Binary Interface (CBI) Subprotocol.** + +This documentation caters to both novice and advanced users, aiming to guide them toward successfully creating their first smart contract in ParallelChain. + + +For sharing smart contract code, addresses, or any assistance with smart contract creation, please visit [GitHub Discussions](https://github.com/parallelchain-io/parallelchain-sdk/discussions). + + +For issues related to the SDK or smart contracts, please visit [GitHub issues](https://github.com/parallelchain-io/parallelchain-sdk/issues). diff --git a/docs/for_developers/smart_contracts/preparing_env.md b/docs/for_developers/smart_contracts/preparing_env.md new file mode 100644 index 00000000..2f0d69df --- /dev/null +++ b/docs/for_developers/smart_contracts/preparing_env.md @@ -0,0 +1,30 @@ +--- +tags: + - mainnet + - testnet + - explorer +--- + +# Preparing Environment + +You have the the tools to develop smart contracts. You also need the environment to deploy and call your smart contracts. You can utilize the [Mainnet](../../fundamentals/networks.md#parallelchain-mainnet) as a production environment for your business application, as well as the [Testnet](..//../fundamentals/networks.md#parallelchain-testnet) as a testing environment before deploying your release to Mainnet. + +## Checking the Network + +You can check the [**Mainnet**](../../fundamentals/networks.md#parallelchain-mainnet) by viewing the ParallelChain Explorer: + +* [ParallelChain Mainnet Explorer](https://explorer.parallelchain.io/explorer) + +The explorer can explore transactions, addresses, information about the network, and blocks. + +To verify that [**Testnet**](../../fundamentals/networks.md#parallelchain-testnet) is alive: + +* [https://pchain-test-rpc02.parallelchain.io](https://pchain-test-rpc02.parallelchain.io) + +You can use [ParallelChain Client CLI](../../for_users/pchain_client_cli/getting_started.md) (called `pchain_client`) to interact with the `Testnet` node. + +## Setting Up ParallelChain Client CLI + +Before we start developing the smart contracts, the `pchain_client` executable needs to be configured. + +If you are not yet familiar with `pchain_client`, See [Install and Setup](../../for_users/pchain_client_cli/getting_started.md) to install `pchain_client` and learn about the basic functionalities before proceeding with smart contract development. diff --git a/docs/concepts/PRFC.md b/docs/for_developers/smart_contracts/prfc.md similarity index 51% rename from docs/concepts/PRFC.md rename to docs/for_developers/smart_contracts/prfc.md index bd0f1ba0..72ecd140 100644 --- a/docs/concepts/PRFC.md +++ b/docs/for_developers/smart_contracts/prfc.md @@ -9,6 +9,6 @@ tags: PRFC (ParallelChain Request for Comments) defines application layer standards which specifies common interface of ParallelChain Smart Contract and its state representation so that applications running on ParallelChain can interact with for a well-defined purpose. -The number suffix is identified as each standard’s unique ID. At the time of writing, there have been 3 PRFCs proposed: PRFC1 defines a standard interface for fungible tokens, and PRFC2 for non-fungible tokens (similar meanings as ERC20 and ERC721 in Ethereum). +The number suffix is identified as each standard’s unique ID. For example, PRFC1 defines a standard interface for fungible tokens, and PRFC2 for non-fungible tokens (similar meanings as [ERC20](https://eips.ethereum.org/EIPS/eip-20) and [ERC721](https://eips.ethereum.org/EIPS/eip-721) in Ethereum). -You can find all PRFCs in this GitHub repository: [https://github.com/parallelchain-io/prfcs](https://github.com/parallelchain-io/prfcs). Please feel free to leave your comments or submit proposals on the Issues page. \ No newline at end of file +You can find all PRFCs in this GitHub repository [prfcs](https://github.com/parallelchain-io/prfcs). Please feel free to leave your comments or submit proposals on the Issues page. \ No newline at end of file diff --git a/docs/developer_guides/smart_contract_sdk/tutorial/chapter_1.md b/docs/for_developers/smart_contracts/smart_contract_examples/1_hello_contract.md similarity index 60% rename from docs/developer_guides/smart_contract_sdk/tutorial/chapter_1.md rename to docs/for_developers/smart_contracts/smart_contract_examples/1_hello_contract.md index 4e4a477c..b3a0925f 100644 --- a/docs/developer_guides/smart_contract_sdk/tutorial/chapter_1.md +++ b/docs/for_developers/smart_contracts/smart_contract_examples/1_hello_contract.md @@ -5,16 +5,16 @@ tags: - Smart Contract --- -# Chapter 1 +# Example - Hello Contract -In this chapter, we will go through the steps of creating a simple smart contract with the help of `pchain-sdk`. +We will go through the steps of creating a simple smart contract with the help of `pchain-sdk`. Firstly, we have to prepare the `Cargo.toml`, which specifies the name, version, and year of edition of the smart contract. We need to use `pchain-sdk` for this smart contract development, so remember to add `pchain-sdk = { version = "LATEST_VERSION"}` under dependencies. ### Cargo.toml ```toml [package] name = "hello_contract" -version = "0.1.0" +version = "0.4.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html @@ -23,22 +23,19 @@ edition = "2021" crate-type = ["cdylib"] [dependencies] -pchain-sdk = { version = "LATEST_VERSION"} +pchain-sdk = { git = "https://github.com/parallelchain-io/pchain-sdk.git" } ``` ---- - -After preparing `Cargol.toml`, we can now start preparing the smart contract. +After preparing `Cargo.toml`, we can now start preparing the smart contract. -`#[contract]` defines basic struct as a programming model of a contract. +`#[contract]` defines basic [struct](https://doc.rust-lang.org/book/ch05-01-defining-structs.html) as a programming model of a contract. Fields are data representations of contract storage. -`#[contract_methods]` defines impl for the contract struct. -Methods declared in the impl are callable by Transaction Command Call if their visibility is `pub`. +`#[contract_methods]` defines [impl](https://doc.rust-lang.org/std/keyword.impl.html) for the contract struct. -`#[call]` macro applies to impl methods for the contract method call. +`#[call]` macro applies to impl methods for the contract method call. Methods declared under this macro are callable by [Transaction Command - Call](../../../fundamentals/transactions.md#account-commands). -In the file, we have added a method called `hello()`, `pchain_sdk::log()` logs the key and value and stores them into a tmp directory when the method is invoked. +In the file, we have added a method called `hello()`. In this method, the SDK provided function `pchain_sdk::log()` logs the information as a key-value pair and appends it to the [Logs](../../../fundamentals/transactions.md#receipt-and-logs) in a transaction receipt. ### lib.rs ```rust @@ -62,9 +59,7 @@ impl HelloContract { } ``` ---- - -Next, we can add two other methods, which illustrate how we can set or read values from the storage. +Next, we can add two other methods, which illustrate how we can set and get values from the storage by using the SDK provided functions in crate [pchain_sdk::storage](../advanced/contract_storage.md#accessing-storage). ```rust #[call] diff --git a/docs/developer_guides/smart_contract_sdk/tutorial/chapter_2.md b/docs/for_developers/smart_contracts/smart_contract_examples/2_my_little_pony.md similarity index 67% rename from docs/developer_guides/smart_contract_sdk/tutorial/chapter_2.md rename to docs/for_developers/smart_contracts/smart_contract_examples/2_my_little_pony.md index b7ef4285..a4696a54 100644 --- a/docs/developer_guides/smart_contract_sdk/tutorial/chapter_2.md +++ b/docs/for_developers/smart_contracts/smart_contract_examples/2_my_little_pony.md @@ -5,18 +5,18 @@ tags: - Smart Contract --- -# Chapter 2 +# Example - My Little Pony -In Chapter 2, we will implement a smart contract called `MyLittlePony`, to demonstrate how a contract can: +We will implement a smart contract called `MyLittlePony`, to demonstrate how a contract can: - define entrypoint methods - define fields as data in contract storage -From the last chapter, we have learned that the macro `contract` on struct allows loading or storing fields from or into the world state. -The key to be stored is an u8 integer ordered by the index of the fields. +From the last chapter, we have learned that the macro `contract` on struct allows getting or setting data from or into the [world state](../../../fundamentals/nodes.md#world-state). +The key to be stored started with a zero-indexed u8 integer ordered by the fields in the contract struct. -In this chapter, we first create a struct, `MyLittlePony`, that consists of `name`, `age`, and `gender`. In this case, `name` has key [0] while `age` has key [1]. +In this chapter, we first create a struct, `MyLittlePony`, that consists of `name`, `age`, and `gender`. In this case, `name` has key `[0]` while `age` has key `[1]`. ### lib.rs: define MyLittlePony @@ -34,8 +34,8 @@ pub struct MyLittlePony { ``` Next, we need to declare the `Gender` struct, which is the type of the `gender` field. To use the nested -struct in the contract struct, we need the `contract_field` macro to access the key-value pair in canonical format. -For instance, `name` in `Gender` struct has a key [2][0] in the contract `MyLittlePony`. +struct in the contract struct, we need the `contract_field` macro to define the key of its fields in canonical format. +For instance, `gender` should have a key started with `[2]` in the contract `MyLittlePony`, so the `name` in `Gender` struct has a key `[2][0]`. ### lib.rs: define Gender ```rust @@ -46,10 +46,8 @@ struct Gender { } ``` ---- - After getting all the structs ready, we should start implementing the contract methods. This smart -contract should provide three functionalities: +contract should provide three method calls: - self_introduction() - grow_up() @@ -57,8 +55,7 @@ contract should provide three functionalities: Firstly, `self_introduction()` uses receiver `&self` to load all data before executing this method. -All data will be loaded to the receiver self from the world state. Therefore, we can have access to all the -fields in the contract, including the fields in the `Gender` struct. +All data will be loaded to the receiver self from the world state. In this way, we can obtain all the values of the fields in the contract, including the fields in the `Gender` struct. ### lib.rs: load data with &self ```rust @@ -73,12 +70,11 @@ impl MyLittlePony { } ``` -In the next method, we are going to illustrate how we can use contract getter and setter to obtain/store -data from or to the world state. Write cost is smaller compared to what we did in `self_introduction()` -because there is only one key-value pair in the world state to be mutated. +In the next method, we are going to illustrate how we can use contract getter and setter to access the data in the world state. The advantage of this is that the Write [gas cost](../../../fundamentals/gas.md) is smaller compared to what we did in `self_introduction()` +because only one key-value pair (i.e. `age`) is involved. -Instead of passing `&self` as an argument, simply do `Self::get_()` to obtain value and -`Self::set_()` to store updated value. +Instead of passing `&self` as an argument, simply do `Self::get_()` to get the value and +`Self::set_()` to set updated value. ### lib.rs: getter and setter ```rust @@ -91,7 +87,7 @@ fn grow_up() { Lastly, we want to change our little pony, so we use a mutable receiver `&mut self` to load data before executing this method, then store all data after execution. However, we should be cautious when using -a mutable receiver as it is expensive to load and store since it mutates all key-value pairs in the world state. +a mutable receiver as it is expensive to load and store since it mutates all key-value pairs (i.e. `name`, `age` and `gender`) in the world state. ### lib.rs: load data with a mutable receiver ```rust @@ -107,6 +103,4 @@ fn change_pony(&mut self, name: String, age: u32, gender_name: String, descripti } ``` ---- - **Now you should have learned how to get and set contract fields in your smart contract.** \ No newline at end of file diff --git a/docs/developer_guides/smart_contract_sdk/tutorial/chapter_3.md b/docs/for_developers/smart_contracts/smart_contract_examples/3_my_bank.md similarity index 69% rename from docs/developer_guides/smart_contract_sdk/tutorial/chapter_3.md rename to docs/for_developers/smart_contracts/smart_contract_examples/3_my_bank.md index 66e4e868..7628477d 100644 --- a/docs/developer_guides/smart_contract_sdk/tutorial/chapter_3.md +++ b/docs/for_developers/smart_contracts/smart_contract_examples/3_my_bank.md @@ -5,15 +5,14 @@ tags: - Smart Contract --- -# Chapter 3 -We have introduced macros including `contract`, `contract methods`, and `call` in Chapter 1 and accessing values of -fields from storage in Chapter 2. In this chapter, we will put together all the knowledge and implement the bank -smart contract that simulates banking operations with data stored in ParallelChain Mainnet. +# Example - My Bank -Before diving into the writing of a smart contract, let's build the data struct `BankAccount` using the `sdk_method_bindgen` -macro provided by Parallelchain Mainnet Smart Contract SDK. +We have introduced macros including `contract`, `contract methods`, and `call` in the contract [Hello Contract](1_hello_contract.md) and accessing values of +fields from storage in the contract [My Little Pony](2_my_little_pony.md). Here we will put together all the knowledge and implement the bank smart contract that simulates banking operations with data stored in ParallelChain Mainnet. -`bank_account.rs` defined the `BankAccount` data struct which consists of four fields, `first_name`, `last_name`, `account_id`, and `amount`. All these fields will be initialized to 0 or empty upon deployment. +Before diving into the writing of a smart contract, let's define the data struct `BankAccount` which will be stored in the storage. + +`bank_account.rs` defined the struct `BankAccount` which consists of four fields, `first_name`, `last_name`, `account_id`, and `amount`. ### bank_account.rs: define data struct @@ -36,26 +35,17 @@ pub struct BankAccount { } ``` -After defining the data struct, add the following two functions which are responsible for -loading and storing the value with a given key accordingly. -> **Note** -> The key to be stored is an u8 integer ordered by the index of the fields, e.g. `first_name` -has key [0]. - -`get_bank_account()` retrieve the value of the given key using `pchain_sdk::storage::get()`, -deserialize the result and return an `Option`. - -`set_bank_account()` stores the given key-value pair in the storage using -`pchain_sdk::storage::set()`. - - -We are using **BorshDeserialize** and **BorshSerialize** in the above code, so remember to update -the Cargo.toml by adding the **borsh** crate. We need the **base64** crate for encoding the account_id -too. Therefore, add the following two lines under the dependencies section in Cargo.toml: +We are using **BorshDeserialize** and **BorshSerialize** in the above struct because we will serialize this struct into bytes and store them into the storage. Remember to update the Cargo.toml by adding the crate [borsh](https://crates.io/crates/borsh). We need the crate [base64](https://crates.io/crates/base64) for encoding the corresponding Account ID too. Therefore, add the following two lines under the dependencies section in Cargo.toml: - base64 = "0.13" - borsh = "=0.10.2" +Here we are not going to define the `BankAccount` data as a field in contract struct. But we will be able to load and save the data by using `storage::get` and `storage::set` explicitly. Let's add the following two methods for getting and setting the value with a given key. + +`get_bank_account()` retrieves the value (i.e. `BankAccount`) of the given key from storage by using `pchain_sdk::storage::get()`. + +`set_bank_account()` stores the value (i.e. `BankAccount`) of the given key to storage by using +`pchain_sdk::storage::set()`. ### bank_account.rs: accessing storage ```rust @@ -100,14 +90,13 @@ impl BankAccount { } ``` ---- - After having the `BankAccount` struct ready, it is time to start writing the bank smart contract. `use bank_account::BankAccount;` allows us to use the methods defined in `bank_account.rs`. -The macro `contract` on the data struct allows loading/storing fields from/into the world state. The contract struct, `MyBank`, has -only one field, `num_of_account`, indicating the number of accounts associated with this bank. As mentioned in the previous -section, the key of `num_of_account` in the storage will be [0] according to its index. +The macro `contract` above struct defines the basic structure of the contract which has +only one field, `num_of_account`, indicating the number of accounts associated with this bank. This field has a key `[0]`. +!!! Note + The key to be stored started with a zero-indexed u8 integer ordered by the fields in the contract struct. ### lib.rs: define contract struct @@ -127,12 +116,12 @@ struct MyBank { } ``` -As mentioned in Chapter 1, the macro `#[contract_methods]` generates entrypoint methods that can be called in transaction. +Remember that the macro `#[contract_methods]` generates entrypoint methods that can be called in transaction. We will create the first entrypoint method in `MyBank` impl. Firstly, we need the entrypoint method `open_account()` to create a brand-new account, with the specified `first_name`, `last_name`, `account_id`, and `initial_deposit`. -In `open_account()`, we initialize an instance of `BankAccount`, and store it in the storage directly by invoking `bank_account::set_bank_account`. +In `open_account()`, we initialize an instance of `BankAccount`, and store it in the storage directly by invoking `bank_account::set_bank_account()` with its Account ID as a key. -After storing the newly generated account into storage, we have to update the `num_of_account`. Therefore, we obtain the value of the field by doing `MyBank::get_num_of_account()`, like how we get the fields of our pony in Chapter 2. Similarly, store the updated +After storing the newly generated account into storage, we have to update the `num_of_account`. Therefore, we obtain the value of the field by doing `MyBank::get_num_of_account()`, like how we get the fields of our little pony in Chapter 2. Similarly, set the updated value by calling `MyBank::set_num_of_account()`. ### lib.rs: open a new account @@ -190,26 +179,26 @@ impl MyBank { } ``` -Now, we have successfully created a function that creates a new bank account, we should support other +Now, we have successfully implemented an entrypoint method that creates a new bank account, we should support other basic banking functionalities. Let's start with checking account balance, users need to know how much money is left in their accounts. -By calling `bank_account::get_bank_account()` with a given `account_id`, `Option` will be returned. If +The method `bank_account::get_bank_account()` returns `Option` by a given `account_id`. If `None` is returned, the account does not exist; otherwise, we will be able to obtain the balance of the account by -accessing the value of the field `amount`. +accessing the field `amount`. ### lib.rs: query account balance ```rust #[call] fn query_account_balance(account_id: String) { match bank_account::get_bank_account(account_id.as_bytes()) { - Some(balance) => { + Some(account) => { pchain_sdk::log( format!("bank: query_account_balance").as_bytes(), format!( "The current balance is: {}", - &balance.amount + &account.amount ).as_bytes() ); }, @@ -225,19 +214,19 @@ fn query_account_balance(account_id: String) { ``` Lastly, finish up the functionalities of the bank by completing the implementation of `withdraw_money()` and -`deposit_money` using the methods mentioned in all previous sections. +`deposit_money()` using the methods mentioned in all previous sections. ### lib.rs: withdrawal and deposit ```rust #[call] fn withdraw_money(account_id: String, amount_to_withdraw: u64) { match bank_account::get_bank_account(account_id.as_bytes()) { - Some(mut query_result) => { - match query_result.withdraw_from_balance(amount_to_withdraw) { + Some(mut account) => { + match account.withdraw_from_balance(amount_to_withdraw) { Some(balance) => { // update the world state - bank_account::set_bank_account(account_id.as_bytes(), &query_result); + bank_account::set_bank_account(account_id.as_bytes(), &account); pchain_sdk::log( format!("bank: withdraw_money").as_bytes(), @@ -245,9 +234,9 @@ fn withdraw_money(account_id: String, amount_to_withdraw: u64) { Name: {} {}\n Account Number: {}\n Balance: {}", - &query_result.first_name, - &query_result.last_name, - &query_result.account_id, + &account.first_name, + &account.last_name, + &account.account_id, &balance).as_bytes() ); } @@ -269,19 +258,19 @@ fn withdraw_money(account_id: String, amount_to_withdraw: u64) { #[call] fn deposit_money(account_id: String, amount_to_deposit: u64) { match bank_account::get_bank_account(account_id.as_bytes()) { - Some(mut query_result) => { - query_result.deposit_to_balance(amount_to_deposit); + Some(mut account) => { + account.deposit_to_balance(amount_to_deposit); // update the world state - bank_account::set_bank_account(account_id.as_bytes(), &query_result); + bank_account::set_bank_account(account_id.as_bytes(), &account); pchain_sdk::log( format!("bank: deposit_money").as_bytes(), format!("The updated balance is: \nName: {} {}\nAccount Number: {}\nBalance: {}", - &query_result.first_name, - &query_result.last_name, - &query_result.account_id, - &query_result.amount).as_bytes() + &account.first_name, + &account.last_name, + &account.account_id, + &account.amount).as_bytes() ); }, None => pchain_sdk::log( diff --git a/docs/developer_guides/smart_contract_sdk/tutorial/chapter_4.md b/docs/for_developers/smart_contracts/smart_contract_examples/4_contract_proxy.md similarity index 61% rename from docs/developer_guides/smart_contract_sdk/tutorial/chapter_4.md rename to docs/for_developers/smart_contracts/smart_contract_examples/4_contract_proxy.md index dbb6ce00..8143978f 100644 --- a/docs/developer_guides/smart_contract_sdk/tutorial/chapter_4.md +++ b/docs/for_developers/smart_contracts/smart_contract_examples/4_contract_proxy.md @@ -5,19 +5,16 @@ tags: - Smart Contract --- -# Chapter 4 +# Example - Contract Proxy -This chapter introduces the use of the `use_contract` macro to interact with other contracts. -We have `ContractProxy` that serves as a middle-man to another contract `MyLittlePony`, the -contract that we implemented in the last chapter. We are going to explore the interaction between -the two contracts by calling entrypoint methods and sending tokens from the balance of one contract -to another contract. +We will look at how the contract `ContractProxy` use the `use_contract` macro to interact with other contracts. In general, `ContractProxy` is a contract that serves as a middle-man to another contract [My Little Pony](2_my_little_pony.md). ---- +There are two kinds of interaction between the two contracts: + +- calling another contract's entrypoint methods. +- sending tokens from the balance of one contract to another contract. -Firstly, use the macro `use_contract` to specify the contract entrypoint methods in a trait. -The address is hard-coded when using this macro. It is recommended to remove or comment out -the methods that are not intended to be used. +To call another contract, firstly use the macro `use_contract` to specify the contract entrypoint methods in a trait. The address is hard-coded when using this macro. It is recommended to remove or comment out the methods that are not intended to be used. Recall that we have a deployed contract called `MyLittlePony` that consists of three methods, `self_introduction()`, `grow_up()`, and `change_person()`. We are going to use `grow_up()` in @@ -37,12 +34,11 @@ pub trait MyLittlePony { } ``` -After preparing the trait `MyLittlePony`, we start implementing the functionalities of `ContractProxy`. - The trait will be transformed to mod by using the macro `use_contract`, Calling the contract `MyLittlePony` -can be simply calling associate methods according to the defined method in the trait. One way of calling +can be simply calling the methods in the trait as [associated functions](https://doc.rust-lang.org/rust-by-example/fn/methods.html). For example, one way of calling `grow_up()` is to simply do `my_little_pony::grow_up(0)`. +After defining the trait that specifies the other contract, we start implementing the functionalities of our contract `ContractProxy`. ### lib.rs: use_contract macro ```rust @@ -59,9 +55,7 @@ impl ContractProxy { } ``` ---- - -The above example has shown how we can use the `use_contract` macro to do cross-contract calls. It is also possible +The above example has shown how we can use the `use_contract` macro to do [cross-contract calls](../advanced/cross_contract_call.md). It is also possible to use `pchain_sdk::call_untyped()` to do so. We pass the contract address as an argument so that the contract address does not need to be hard-coded in the contract. @@ -79,11 +73,9 @@ fn grow_up_2(address: String) { } ``` ---- - ### lib.rs: transfer contract balance Except by calling the entrypoint methods from `MyLittlePony`, we can also transfer the balance from the -contract to a specific address by `pchain_sdk::transfer()`. +contract to a specific address by `pchain_sdk::transfer()` (see [Transferring Balance](../advanced/transferring_balance.md)). ```rust #[call] diff --git a/docs/developer_guides/smart_contract_sdk/tutorial/chapter_5.md b/docs/for_developers/smart_contracts/smart_contract_examples/5_my_collections.md similarity index 91% rename from docs/developer_guides/smart_contract_sdk/tutorial/chapter_5.md rename to docs/for_developers/smart_contracts/smart_contract_examples/5_my_collections.md index 25fe78fc..381d1a8f 100644 --- a/docs/developer_guides/smart_contract_sdk/tutorial/chapter_5.md +++ b/docs/for_developers/smart_contracts/smart_contract_examples/5_my_collections.md @@ -1,4 +1,3 @@ - --- tags: - pchain-sdk @@ -6,12 +5,11 @@ tags: - Smart Contract --- -# Chapter 5 +# Example - My Collections -In the previous chapters, we have understood how we write contract methods and access storage in the world state. -In this chapter, we are going to demonstrate the functionality of collections provided by `pchain-sdk`. +We are going to demonstrate the use of module [collections](https://github.com/parallelchain-io/pchain-sdk/blob/main/README.md#storage-and-collections) in `pchian-sdk`. -`pchain-sdk` provides several collection structures that are designed for gas efficiency: +`collections` are designed as a data structure for gas efficiency: - Cacher: allows lazy initialization - Vector: lazily stores a list of items @@ -38,8 +36,6 @@ pub struct MyCollections { } ``` ---- - ### Cacher `Cacher` is a data wrapper to support Lazy Read and Lazy Write to Contract Storage. @@ -65,8 +61,6 @@ impl MyCollections { } ``` ---- - ### Vector ``` rust @@ -88,8 +82,6 @@ fn push(&mut self, num: i32) -> usize { } ``` ---- - ### FastMap ```rust /// Here we use the receiver `&self` without loading data before executing this method. @@ -109,8 +101,6 @@ fn add_record(&mut self, address: Address, name: String) { } ``` ---- - ### IterableMap ```rust /// Here we use the receiver `&self` without loading data before executing this method. diff --git a/docs/developer_guides/smart_contract_sdk/tutorial/chapter_6.md b/docs/for_developers/smart_contracts/smart_contract_examples/6_my_pool.md similarity index 56% rename from docs/developer_guides/smart_contract_sdk/tutorial/chapter_6.md rename to docs/for_developers/smart_contracts/smart_contract_examples/6_my_pool.md index 57277a8a..aecbb156 100644 --- a/docs/developer_guides/smart_contract_sdk/tutorial/chapter_6.md +++ b/docs/for_developers/smart_contracts/smart_contract_examples/6_my_pool.md @@ -6,11 +6,12 @@ tags: - Staking --- -# Chapter 6 - Network Commands +# Example - My Pool -In the last chapter of the tutorial, we are going to talk about how to use network commands in smart contracts. +We are going to study how to use [staking commands](../../../fundamentals/transactions.md#staking-commands) in smart contracts. + +In ParallelChain Mainnet, there are six different staking commands: -In ParallelChain Mainnet, there are six different network commands: - Create deposit - Set deposit settings - Top-up deposit @@ -18,9 +19,9 @@ In ParallelChain Mainnet, there are six different network commands: - Stake deposit - Unstake deposit -We will demonstrate how the above network commands can be created and sent to -the network through the use of a smart contract. We will use the contract, `MyPool` -to guide you through the steps of creating a stake in a pool with the network commands. +We will demonstrate how the above staking commands can be created within a smart contract +which acts as owner of the deposit/stakes (See [Staking in Contract](../advanced/staking_in_contract.md)). We will use the contract, `MyPool`, +to guide you through the steps of creating a stake in a pool. ### lib.rs: define a struct ```rust @@ -37,10 +38,9 @@ pub struct MyPool { } ``` -We have created the struct `MyPool`, which consists of the addresses of the `pool_operator` and `my_friend`. However, as mentioned in previous chapters, it will be initialized to 0 upon deployment. Therefore, we have to add an init function to initialize the address -to the values we specified. +We have created the struct `MyPool`, which consists of the addresses of the `pool_operator` and `my_friend`. These data will be all zeros by default. Therefore, we have to add an initialization function to set the addresses we want. -### lib.rs: initialise struct +### lib.rs: initialize struct ```rust #[contract_methods] impl MyPool { @@ -53,21 +53,22 @@ impl MyPool { } ``` ---- - After adding the `init()` function, we can try creating a deposit into the pool. `pchain_sdk::network:defer_create_deposit()` allows us to deposit some XPLL into a specified pool. In this contract, we have already specified the pool in the field `pool_operator`. -The network commands are "deferred" because the actual execution of such commands occurs after the execution of a successful call. -> **Note**: -> The deposit is created on behalf of the contract address, not from your account address, so make sure to transfer +The staking commands are "deferred" because the actual execution of such commands occurs after the execution of a successful call. + +!!! Note + The deposit is created on behalf of the contract address, not from your account address, so make sure to transfer sufficient balance to the contract for the operation. -To check if the deposit is successful, you can check the deposit using `pchain-client` with the following command: -> ./pchain_client query deposit --operator --owner +To check if the deposit is successful, you can check the deposit using `pchain-client` with the following [command](../../../for_users/pchain_client_cli/querying_blockchain.md#get-deposit-and-stake): +```sh +./pchain_client query deposit --operator --owner +``` -### lib.rs: successful network command +### lib.rs: successful staking command ```rust #[call] fn create_deposit(balance: u64, auto_stake_rewards: bool) { @@ -79,7 +80,7 @@ It was mentioned above that the `defer` call will only take place after a succes Check the deposit again using `pchain-client`, the deposit balance in the pool should remain unchanged. -### lib.rs: failed network command +### lib.rs: failed staking command ```rust #[call] @@ -90,14 +91,12 @@ Check the deposit again using `pchain-client`, the deposit balance in the pool s } ``` ---- - -Another characteristic of the network commands is that the return value in the transaction receipt will be -overwritten by the deferred staking commands. +!!! Note + The [return values](../../../fundamentals/transactions.md#receipt-and-logs) in the transaction receipt will be overwritten by the deferred staking commands. In the method `stake_deposit()`, we should be expecting that the `return_values` in the receipt will be the -balance of the contract. However, since there is a defer network command in the method call, the `return_values` -will be overwritten by the return value from the `pchain_sdk::network::defer_staking_deposit()` command. +balance of the contract (see [ParallelChain Mainnet Protocol](https://github.com/parallelchain-io/parallelchain-protocol/blob/master/Runtime.md)). However, since there is another deferred staking command in the method call, the `return_values` +will be overwritten by the result of executing `pchain_sdk::network::defer_staking_deposit()` command. ### lib.rs: overwriting return value ```rust @@ -108,15 +107,12 @@ will be overwritten by the return value from the `pchain_sdk::network::defer_sta } ``` ---- - -Lastly, we can include multiple network commands within one transaction. In this `multiple_defer()` function, -we put the commands for unstaking and withdrawing deposits in the same function. +Lastly, we can include multiple deferred staking commands within one transaction. In this method `multiple_defer()`, +we put the deferred staking commands for unstaking and withdrawing deposits together. -Both the commands will be executed after the success of the transaction, and in the order they were called -in the method call. After invoking this method call, the stake of the deposit should have been successfully withdrawn. +Both the commands will be executed after the success of the transaction, and in the order they were called. After invoking this method call, the stake of the deposit should have been successfully unstaked and withdrawn. -### lib.rs: multiple network commands +### lib.rs: multiple staking commands ```rust #[call] fn multiple_defer(max_amount: u64) { @@ -127,6 +123,4 @@ in the method call. After invoking this method call, the stake of the deposit sh ``` ---- - **Congratulations! You have completed all tutorials and are ready to write your smart contract!** \ No newline at end of file diff --git a/docs/developer_guides/wallet_browser_extension/provider/api_documentation.md b/docs/for_developers/xperience_browser_provider_apis/api_reference.md similarity index 93% rename from docs/developer_guides/wallet_browser_extension/provider/api_documentation.md rename to docs/for_developers/xperience_browser_provider_apis/api_reference.md index 05cd1125..48578b7d 100644 --- a/docs/developer_guides/wallet_browser_extension/provider/api_documentation.md +++ b/docs/for_developers/xperience_browser_provider_apis/api_reference.md @@ -5,7 +5,7 @@ tags: - provider API --- -# API Documentation +# API Reference ## Properties @@ -175,7 +175,7 @@ type GetAccountsResult = string[]; ## Get Active Account -Get the [address][3] of the currently [active account][12]; +Get the [address][3] of the currently [active account][11]; return `undefined` if the user still needs to register. !!! warning @@ -203,7 +203,7 @@ type GetActiveAccountResult = string | undefined; ## Get Active Account Balance -Return the balance of the [active account][12] in [XPLL][5]. +Return the balance of the [active account][11] in [XPLL][5]. !!! warning The `get_active_account_balance` should have the permission granted; otherwise, @@ -231,7 +231,7 @@ type GetActiveAccountBalanceResult = string; ## Get Active Account Latest Transactions -Return the latest transactions of the [active account][12]. +Return the latest transactions of the [active account][11]. ### Params @@ -337,7 +337,7 @@ Transfer tokens to another account; return the transaction hash if the request i !!! tip Send Token is only for XPLL transfers. - If you want to transfer the [PRFC1 token][11], we should use [Call Contract](#call-contract) instead. + If you want to transfer the [PRFC1 token][10], we should use [Call Contract](#call-contract) instead. ```ts interface SendTokenRequest { @@ -403,10 +403,10 @@ return the transaction hash if the request is successful. The arguments of the contract method should be serialized as [Uint8Array][6] before passing to the `call_contract` method. -The primitive types are serialized based on [Borsh binary serialization format][7]. You can use the library [borsh-js][10] to help serialize the arguments. +The primitive types are serialized based on [Borsh binary serialization format][7]. You can use the library [borsh-js][9] to help serialize the arguments. The address is a base64 encoded string. -For more details about the base64 serialization, please check [MDN][9]. +For more details about the base64 serialization, please check [MDN][8]. The option type is also based on [Borsh binary serialization format][7]. For instance, `Option` is serialized as: @@ -419,8 +419,8 @@ const optionBytes = new Uint8Array([1, ...addressBytes]); // Option +ParallelChain client (`pchain_client`) is a command-line tool for you to connect and interact with +the ParallelChain Mainnet/Testnet. + +USAGE: + pchain_client + +OPTIONS: + -h, --help Print help information + -V, --version Print version information + +SUBCOMMANDS: + transaction Construct and submit Transactions to ParallelChain network + query Query blockchain and world state information for ParallelChain network + keys Locally stores and manage account keypairs you created. (Password required) + parse Utilities functions to deserialize return values in CommandReceipt, and + compute contract address + config Get and set Fullnode RPC url to interact with ParallelChain + help Print this message or the help of the given subcommand(s) +``` -## Installation ---- +## Installing ParallelChain Client CLI `pchain_client` is an available tool for users on Unix/Linux, MacOS, and Windows operating systems. Simply download the pre-built binary corresponding to your platform and install the `pchain_client`. @@ -61,9 +86,8 @@ The installation process for Linux and macOS is similar. To install `pchain_clie If this is your first time using `pchain_client`, you need to set up `$PCHAIN_CLI_HOME` in environment variables to specify the home path. See more [here](https://chlee.co/how-to-setup-environment-variables-for-windows-mac-and-linux/). ## Running pchain_client ---- -### Creating Password +### Create Password For the first time to use `pchain_client`, you need to create your password for using it. The terminal should prompt you as follows: @@ -89,10 +113,9 @@ You will be required to enter your password twice. If your password is set succe The password is not sent and saved anywhere. You won't be able to recover the password if you lose it. Please keep your password safe. You will be required to provide this password to submit transactions and manage keypairs later. -## Prepare Environment ---- +## Preparing Environment -### Setting Environmental Variables +### Set Environmental Variables Specify the location of the directory for storing your config and keypair by setting the environmental variable `PCHAIN_CLI_HOME`. @@ -130,7 +153,7 @@ The following command will set the environmental variable **permanently**: setx PCHAIN_CLI_HOME "" ``` -### Setting Endpoint Interacting with Parallelchain +### Setup Endpoint After installation of `pchain_client`, you had to update the Mainnet / Testnet endpoint to communicate with the Mainnet / Testnet. diff --git a/docs/developer_guides/pchain_cli/smart_contract.md b/docs/for_users/pchain_client_cli/interacting_with_smart_contract.md similarity index 99% rename from docs/developer_guides/pchain_cli/smart_contract.md rename to docs/for_users/pchain_client_cli/interacting_with_smart_contract.md index 0b5caf09..1013ef6b 100644 --- a/docs/developer_guides/pchain_cli/smart_contract.md +++ b/docs/for_users/pchain_client_cli/interacting_with_smart_contract.md @@ -5,10 +5,6 @@ tags: - pchain-cli-rust --- - -## Smart Contract ---- - Smart contracts are computer programs that are stored on a blockchain. You need to provide some necessary information such as contract address, method name, and arguments in order to invoke method of the contract. ### Retrieve Contract Address diff --git a/docs/developer_guides/pchain_cli/manage_account.md b/docs/for_users/pchain_client_cli/managing_account.md similarity index 98% rename from docs/developer_guides/pchain_cli/manage_account.md rename to docs/for_users/pchain_client_cli/managing_account.md index f60d4d4a..82c58b18 100644 --- a/docs/developer_guides/pchain_cli/manage_account.md +++ b/docs/for_users/pchain_client_cli/managing_account.md @@ -5,10 +5,6 @@ tags: - pchain-cli-rust --- - -## Manage Account ---- - In ParallelChain, an account is identified by the public key of Ed25519 keypair. You can either generate new keys or import your existing Ed25519 keypair to make transactions in `pchain_client`. Both operations require password (if you setup before). ### Generate New Keypair diff --git a/docs/developer_guides/pchain_cli/query.md b/docs/for_users/pchain_client_cli/querying_blockchain.md similarity index 85% rename from docs/developer_guides/pchain_cli/query.md rename to docs/for_users/pchain_client_cli/querying_blockchain.md index 14eb3b6f..6e3cc527 100644 --- a/docs/developer_guides/pchain_cli/query.md +++ b/docs/for_users/pchain_client_cli/querying_blockchain.md @@ -5,11 +5,6 @@ tags: - pchain-cli-rust --- - - -## Query ---- - `pchain_client` allows you to query different data from the ParallelChain, not just Transaction or Account related information, but also details of Validators and Stake Pool in ParallelChain network. Use `pchain_client query --help` to check the full list available to query. @@ -44,7 +39,7 @@ Command: ``` ### Get Transaction with Receipt -In [Submit Transaction to ParallelChain](./transaction.md#submit-transaction-to-parallelchain) section, after you successfully make transaction on ParallelChain, you should receive the transaction hash (tx_hash) in the response. This hash is the identity of your transaction. You can always retrieve the transaction details with receipt by the transaction hash. +In [Submit Transaction to ParallelChain](./creating_transaction.md#submit-transaction-to-parallelchain) section, after you successfully make transaction on ParallelChain, you should receive the transaction hash (tx_hash) in the response. This hash is the identity of your transaction. You can always retrieve the transaction details with receipt by the transaction hash. Command: diff --git a/docs/user_guides/wallet_web_based_tool/create_account.md b/docs/for_users/web_wallet/create_account.md similarity index 80% rename from docs/user_guides/wallet_web_based_tool/create_account.md rename to docs/for_users/web_wallet/create_account.md index 30baf579..56f89025 100644 --- a/docs/user_guides/wallet_web_based_tool/create_account.md +++ b/docs/for_users/web_wallet/create_account.md @@ -4,24 +4,23 @@ tags: - explorer --- -**Xperience** is your ParallelChain wallet, and **ParallelChain Explorer** is a web-based tool that allows you to access your wallet. +You can use **Web Wallet** on [ParallelChain Explorer](../../fundamentals/networks.md#parallelchain-explorer) on without any installation. -To conduct transactions on ParallelChain Mainnet you will first need to create an account on the blockchain to access the network. Accounts are free to create, and they can be set up through **ParallelChain Explorer**—or through the new **Xperience Browser Extension**. +To conduct transactions on ParallelChain Mainnet you will first need to create an account on the blockchain to access the network. Accounts are free to create, and they can be set up through **ParallelChain Explorer**—or through the new [**Xperience Browser Extension**](../xperience_browser_extension/create_account.md). -The blockchain account you create on ParallelChain is non-custodial, which means only you have control and access to it. You must store your recovery key securely and properly to avoid losing access to your assets. There is no way to retrieve it if it is lost. +The account ([EOA](../../fundamentals/accounts.md#accounts)) you create on ParallelChain is non-custodial, which means only you have control and access to it. You must store your recovery key securely and properly to avoid losing access to your assets. There is no way to retrieve it if it is lost. Learn how to create and manage your ParallelChain account using **ParallelChain Explorer** with the steps below. ## Creating Your ParallelChain Wallet Account ---- ![create acount](../../img/explorer/account/1_creating_an_account.jpg){ width=80% style="display: block; margin: 0 auto" } -### Step 1: Access ParallelChain Explorer +### Access ParallelChain Explorer Access [ParallelChain Explorer](https://explorer.parallelchain.io/explorer?network=Mainnet) to start your account creation process. -### Step 2: Create Your Account +### Create Your Account 1. Create your ParallelChain wallet account by selecting **CONNECT NOW**. 2. Click the **REGISTER** button. @@ -30,7 +29,7 @@ Access [ParallelChain Explorer](https://explorer.parallelchain.io/explorer?netwo 5. Click **NEXT** once you have stored it safely -### Step 3: Verify Your Recovery Key +### Verify Your Recovery Key 1. To make sure that your recovery key are stored securely, you will be prompted to fill in blanks which correspond to the phrases displayed in the previous step. 2. Enter the words which correspond to the chronological positions of the recovery key. @@ -38,7 +37,7 @@ Access [ParallelChain Explorer](https://explorer.parallelchain.io/explorer?netwo 4. If an error message appears, refer to your recovery key again and check if you have keyed in the wrong phrase. -### Step 4: Create Your Password +### Create Your Password 1. Create a password for your wallet. Your password can contain any characters, and it must be at least 8 characters long. 2. This password is only limited to the wallet access on the particular device you are registering your account on, and it cannot be used on another device. @@ -47,7 +46,7 @@ Access [ParallelChain Explorer](https://explorer.parallelchain.io/explorer?netwo 5. You will be prompted to enter your password again to access your wallet. Enter your password in the empty field, then click **VERIFY**. -### Step 5: Logging Into Your Wallet +### Login Your Wallet 1. To log in, click on the round icon on the top right hand corner of the webpage and enter your password 2. Press the **VERIFY** button. @@ -65,9 +64,9 @@ Access [ParallelChain Explorer](https://explorer.parallelchain.io/explorer?netwo 2. Enter your 12-phrase recovery key that you have stored securely when you first created your wallet, then press **NEXT**. 3. Next, enter your desired password and re-enter it under the **Confirm Password** box, then press **REGISTER**. 4. You will be prompted to enter your password again to access your wallet. Enter your password in the empty field, and select **VERIFY**. -5. Importing your wallet only recovers accounts associated with the recovery key. Refer to the steps under [Exporting Your Account With Public And Private Keys](#exporting-your-account-with-public-and-private-keys) and [Importing Your Account Using Public And Private Keys](#importing-your-account-using-public-and-private-keys) to export and import individual accounts. +5. Importing your wallet only recovers accounts associated with the recovery key. Refer to the steps under [Export Your Account](#export-your-account) and [Import Your Account From Public And Private Keys](#import-your-account-from-public-and-private-keys) to export and import individual accounts. -## Configure Your Security & Login +## Configuring Security & Login ### View Your Recovery Key ![view recovery key](../../img/explorer/account/3_view_recovery_key.jpg){ width=80% style="display: block; margin: 0 auto" } @@ -78,7 +77,7 @@ Access [ParallelChain Explorer](https://explorer.parallelchain.io/explorer?netwo 4. Tap on **VIEW RECOVERY KEY** to preview your recovery key. -### Change Passwords +### Change Your Password ![change password](../../img/explorer/account/4_change_password.jpg){ width=80% style="display: block; margin: 0 auto" } 1. Click the icon with three dots on the top right hand corner of the wallet. @@ -98,16 +97,16 @@ Access [ParallelChain Explorer](https://explorer.parallelchain.io/explorer?netwo 5. If you do not remember your password, you can choose to log in with your recovery key by selecting **VERIFY WITH RECOVERY KEY** and re-entering your 12-phrase recovery key. 6. You will be shown a loading screen that says **Erasing Wallet Data**. Your wallet data has now been removed from your device. -### Exporting Your Account With Public And Private Keys +### Export Your Account ![export account](../../img/explorer/account/6_download_key.jpg){ width=80% style="display: block; margin: 0 auto" } 1. To export an existing account, click on the *drop-down arrow* right beside your wallet address. Your wallet address acts as your **public key**. 2. Click on the *key* icon to preview your account **private key**. 3. Save your public and private key in a secure location. 4. You can also download the key pair of your current account through the *download* icon beside your wallet address as a **JSON file**. -5. Store the JSON file in a secure manner. If you wish to recover your account on another wallet, you can do so by following the instructions under [Importing Your Account Using Public And Private Keys](#importing-your-account-using-public-and-private-keys), or import it with the JSON file under [Importing Your Account With A JSON file](#importing-your-account-with-a-json-file). You can view the information by opening the file with a text-based document such as Microsoft Word. +5. Store the JSON file in a secure manner. If you wish to recover your account on another wallet, you can do so by following the instructions under [Import Your Account From Public And Private Keys](#import-your-account-from-public-and-private-keys), or import it with the JSON file under [Import Your Account From a JSON file](#import-your-account-from-a-json-file). You can view the information by opening the file with a text-based document such as Microsoft Word. -### Importing Your Account Using Public And Private Keys +### Import Your Account From Public And Private Keys ![import account](../../img/explorer/account/7_importing_your_account.jpg){ width=80% style="display: block; margin: 0 auto" } 1. To import an existing account, click on the *drop-down arrow* right beside your wallet address @@ -115,18 +114,18 @@ Access [ParallelChain Explorer](https://explorer.parallelchain.io/explorer?netwo 3. Enter your desired account name under the **Account Name** 4. Enter your public key in the **Public Key** field. 5. Enter your private key in the **Private Key** field. -6. If you are not sure where to find your public and private key, learn how to find them under [Exporting Your Account With Public And Private Keys](#exporting-your-account-with-public-and-private-keys). +6. If you are not sure where to find your public and private key, learn how to find them under [Export Your Account](#export-your-account). 7. Click **IMPORT** once you are done. -### Importing Your Account With A JSON file +### Import Your Account From a JSON file ![import json](../../img/explorer/account/8_importing_your_account_with_JSON.jpg){ width=80% style="display: block; margin: 0 auto" } 1. To import an existing account, click on the *drop-down arrow* right beside your wallet address. 2. Click the **IMPORT** button -3. Click on **Import With File** and select the appropriate JSON file. Learn how to export your JSON file under [Exporting Your Account With Public & Private Keys](#exporting-your-account-with-public-and-private-keys). +3. Click on **Import With File** and select the appropriate JSON file. Learn how to export your JSON file under [Export Your Account](#export-your-account). 4. Once you are done, click on **IMPORT** and your account will be added to the wallet. -### Locking Your Wallet +### Lock Your Wallet ![import json](../../img/explorer/account/9_lock_wallet.jpg){ width=80% style="display: block; margin: 0 auto" } 1. Click the icon with *three dots* on the top right hand corner of the wallet. @@ -134,7 +133,6 @@ Access [ParallelChain Explorer](https://explorer.parallelchain.io/explorer?netwo 3. You will be prompted to enter your password to access your wallet. Enter your password in the empty field and press **VERIFY’**. ## Navigating Your ParallelChain wallet ---- 1. **Congratulations** on creating your ParallelChain account. 2. Your first account will be automatically created for you. @@ -146,24 +144,24 @@ Access [ParallelChain Explorer](https://explorer.parallelchain.io/explorer?netwo 8. If you are unsure of any particular steps while following the tutorial guide, you can also watch the video tutorial [here](https://www.youtube.com/watch?v=_lDRXPmeNzU). ## FAQ ---- ### Are my ParallelChain wallet and account the same thing? -No, your wallet and your account are not the same. Your account is registered on ParallelChain Mainnet, and your wallet extension helps connect you to your account. This means you are able to recover your account should you lose the device that your wallet extension is installed. +No, your wallet and your [account](../../fundamentals/accounts.md) are not the same. Your account is registered on ParallelChain Mainnet, and your wallet extension helps connect you to your account. This means you are able to recover your account should you lose the device that your wallet extension is installed. +--- ### What kind of digital assets can I store in my Xperience account? -Currently, it can store XPLL. In the near future, you will be able to store other ParallelChain-based cryptocurrencies and non-fungible tokens (NFTs). +Currently, it can store [XPLL](../../introduction.md#what-is-xpll). In the near future, you will be able to store other ParallelChain-based cryptocurrencies and non-fungible tokens (NFTs). +--- ### Can I send XPLL tokens to other blockchains like Ethereum? -No, you cannot send XPLL tokens to other blockchains at the moment. XPLL and other PRFC tokens currently only exist on ParallelChain Mainnet network, and sending your tokens to other network addresses will cause you to lose your tokens. -Ethereum Virtual Machine (EVM) compatibility is targeted to come with the Lamport epoch as part of the [development roadmap](https://parallelchain.io/roadmap). - +No, you cannot send XPLL tokens to other blockchains at the moment. XPLL and other [PRFC](../../for_developers/smart_contracts/prfc.md) tokens currently only exist on ParallelChain Mainnet network, and sending your tokens to other network addresses will cause you to lose your tokens. +--- ### What happens if I lose my recovery key and password? @@ -172,9 +170,12 @@ Xperience is a non-custodial wallet which only you have the access to. If you lo If you have lost access to your existing account, you can opt to create a new account by clearing the cache of your current browser, then refreshing the page. After that, create a new account by following the steps under [Creating Your ParallelChain Wallet Account](#creating-your-parallelchain-wallet-account). Please check online to find out how you can clear your respective browser caches. +--- ### Are Xperience and Parallel wallet different? Yes, Xperience and ParallelWallet are two different types of non-custodial wallets. You can store XPLL on both wallets, but the recovery keys are not interchangeable and you should still store them in a secure manner. +--- + ### Is the wallet in Xperience Browser Extension the same as the wallet in ParallelChain Explorer? Yes, they are the same. You can access your wallet through either **Xperience Browser Extension** or **ParallelChain Explorer**. diff --git a/docs/user_guides/wallet_web_based_tool/lockup_contract.md b/docs/for_users/web_wallet/lockup_contract.md similarity index 76% rename from docs/user_guides/wallet_web_based_tool/lockup_contract.md rename to docs/for_users/web_wallet/lockup_contract.md index 99274e2f..3b77a382 100644 --- a/docs/user_guides/wallet_web_based_tool/lockup_contract.md +++ b/docs/for_users/web_wallet/lockup_contract.md @@ -7,32 +7,29 @@ tags: Your XPLL allocation might be subject to a vesting schedule that determines how many of your tokens are vested (unlocked) as time goes on. In order to **claim** the unlocked portion in the future, you need to first ***register** the Lock-up Contract* of your allocation to your account. -!!! note +!!! Note Each Lock-up Contract is unique to each holder. Follow the steps below to register your Lock-up Contract to your ParallelChain wallet account. You can also watch the video tutorial [here](https://www.youtube.com/watch?v=ZxojrGycSmQ). -## Registering Your Lock-Up Contract - - -### Step 1: Check Your Email For Your Lock-up Contract Address -Copy your Lock-up Contract address in the email - -### Step 2: Access Your Xperience Explorer Account +## Logging in Your Wallet ![access account](../../img/explorer/lock-up/1_login.jpg){ width=80% style="display: block; margin: 0 auto" } -1. Access the [blockchain explorer](https://explorer.parallelchain.io/explorer?network=Mainnet), or click on the **EXPLORER** button on the [ParallelChain homepage](https://parallelchain.io/). -2. To log in, click on the *round* icon on the top right hand corner of the explorer page and enter your password. + +1. Access the [ParallelChain Explorer](https://explorer.parallelchain.io), or click on the **EXPLORER** button on the [ParallelChain homepage](https://parallelchain.io/). +2. To log in, click on the round icon on the top right hand corner of the explorer page and enter your password. 3. Press the **LOGIN** button. +4. If you do not remember your password, you can choose to log in with your recovery key. Once you have access to your account, you should set a new password through your wallet settings. +5. Once you are verified, you can access your wallet account. - !!! note - If you do not remember your password, you can choose to log in with your recovery key. Once you have access to your account, you should set a new password through your wallet settings. +## Registering Your Lock-Up Contract -4. Once you are verified, you can access your wallet account. +### Step 1: Get Your Lock-Up Contract Address +1. Your lock-up contract address would have been sent to you **via email**. Check your email and copy your lock-up contract address. -### Step 3: Register Your Lock-Up Contract +### Step 2: Register Your Lock-Up Contract ![register contract](../../img/explorer/lock-up/2_contract.jpg){ width=80% style="display: block; margin: 0 auto" } 1. Click the *pink icon* located on the right side of the **STAKE** button. @@ -45,7 +42,7 @@ Copy your Lock-up Contract address in the email 5. Click the **CONFIRM** button to confirm. -!!! note +!!! Note For **Node Round participants** who will operate validator nodes on ParallelChain, the *locked balance* shown will be **0** as your allocation has been automatically staked on one of the existing validator nodes. @@ -54,26 +51,7 @@ Watch the video tutorial to register your locked-up contract [here](https://yout ## Claiming Your Vested Tokens - -### Step 1: Log Into Your ParallelChain Wallet Account - - -1. Access the [blockchain explorer](explorer.parallelchain.io) , or click on the **EXPLORER** button on the [ParallelChain homepage](https://parallelchain.io/). - -2. To log in, click on the *round* icon on the top right hand corner of the webpage and enter your password. - - -3. Press the **LOGIN** button. - - - !!! note - If you do not remember your password, you can choose to log in with your recovery key. Once you have access to your account, you should set a new password through your wallet settings. - - -4. Once you are verified, you can access your wallet account. - - -### Step 2: Check Your Vested Balance +### Step 1: Check Your Vested Balance ![check vested balance](../../img/explorer/lock-up/5_click_button.jpg){ width=80% style="display: block; margin: 0 auto" } @@ -92,7 +70,7 @@ Watch the video tutorial to register your locked-up contract [here](https://yout 4. Under tte **UNLOCKED** field, you can see the amount of tokens that is currently available to claim (unlock). -### Claim Your Vested Tokens +### Step 2: Claim Your Vested Tokens ![claim](../../img/explorer/lock-up/6_claim.jpg){ width=80% style="display: block; margin: 0 auto" } 1. Under the **UNLOCKED** field, press the **CLAIM** button to initiate your token claim. diff --git a/docs/user_guides/wallet_web_based_tool/staking.md b/docs/for_users/web_wallet/staking.md similarity index 91% rename from docs/user_guides/wallet_web_based_tool/staking.md rename to docs/for_users/web_wallet/staking.md index 997ee787..aacc6215 100644 --- a/docs/user_guides/wallet_web_based_tool/staking.md +++ b/docs/for_users/web_wallet/staking.md @@ -7,20 +7,19 @@ tags: You can stake XPLL with network validators to help secure the blockchain and earn rewards in the meantime. Follow the steps below to stake XPLL tokens with your ParallelChain account. You can also watch the video tutorial [here](https://youtu.be/aEa1T-sopmA). -## Access Your Xperience Explorer Account ---- +## Logging in Your Wallet + ![access account](../../img/explorer/staking/1_login.jpg){ width=90% style="display: block; margin: 0 auto" } -1. Access the [blockchain explorer](explorer.parallelchain.io), or click on the **EXPLORER** button on the [ParallelChain homepage](https://parallelchain.io/). +1. Access the [ParallelChain Explorer](https://explorer.parallelchain.io), or click on the **EXPLORER** button on the [ParallelChain homepage](https://parallelchain.io/). 2. To log in, click on the round icon on the top right hand corner of the explorer page and enter your password. 3. Press the **LOGIN** button. 4. If you do not remember your password, you can choose to log in with your recovery key. Once you have access to your account, you should set a new password through your wallet settings. 5. Once you are verified, you can access your wallet account. -## Depositing XPLL to Staking Wallet ---- +## Depositing Your XPLL ### Step 1: Select a validator ![select validator](../../img/explorer/staking/2_select_validator.png){ width=90% style="display: block; margin: 0 auto" } @@ -29,8 +28,9 @@ You can stake XPLL with network validators to help secure the blockchain and ear 2. You will see the list of validator pools you can stake in. 3. Choose from the list, or search for a specific validator via the search bar at the top labelled **SEARCH OPERATOR ADDRESS**. +### Step 2: Deposit XPLL -### Step 2a: Deposit XPLL Through Your Balance Account +#### Through Your Account ![validator details](../../img/explorer/staking/3_validator_details.png){ width=90% style="display: block; margin: 0 auto" } 1. Once you have selected your desired validator, the details of the validator pool will be displayed. @@ -45,7 +45,7 @@ You can stake XPLL with network validators to help secure the blockchain and ear 4. If you would like to auto-stake your rewards, toggle the **AUTO STAKE REWARDS** field on. -### Step 2b: Deposit XPLL Through Your Lock-Up Contract +#### Through Your Lock-Up Contract 1. Once you have selected your desired validator, the details of the validator pool will be displayed. - **LOCK-UP CONTRACT (XPLL)** field and **LOCKED** field, your tokens that are still vested are shown here. @@ -63,9 +63,9 @@ You can stake XPLL with network validators to help secure the blockchain and ear 1. The following fields will appear: - **Nonce** - This field will be automatically populated for you. - - **Max Base Fee per Gas**- This field will be automatically populated for you based on the current Base Fee per Gas of the network. - - **Priority Fee per Gas**- This determines the priority of your transaction, and the minimum fee is 0 XPLL. - - **Gas Limit**- This field will be automatically populated for you. + - **Max Base Fee per Gas** - This field will be automatically populated for you based on the current Base Fee per Gas of the network. + - **Priority Fee per Gas** - This determines the priority of your transaction, and the minimum fee is 0 XPLL. + - **Gas Limit** - This field will be automatically populated for you. 2. Once you are satisfied with the populated fields, press **NEXT** at the bottom. 3. Preview the summary of the transaction, then press **CONFIRM** to continue, or **CANCEL** to make edits @@ -83,7 +83,7 @@ Watch the video tutorial to learn how to deposit XPLL to the staking wallet [her You can stake XPLL which you have deposited with validators to earn rewards. -### Step 1: Navigate to your chosen validator +### Step 1: Navigate To Your Chosen Validator ![selet validator](../../img/explorer/staking/5_navigate_to_validator.png){ width=90% style="display: block; margin: 0 auto" } 1. On the main page, select the **STAKES** tab which is located beside the **TRANSACTIONS** tab. Then select the pool which you wish to top up XPLL. @@ -98,7 +98,9 @@ You can stake XPLL which you have deposited with validators to earn rewards. 3. To stake XPLL, tap on the arrow beside the **TENTATIVE STAKE** field. -### Step 2a: Stake With XPLL From Your Balance Account +### Step 2: Stake XPLL + +#### From Your Account ![validator details](../../img/explorer/staking/7_stake.png){ width=90% style="display: block; margin: 0 auto" } 1. The details of the validator pool will be displayed as shown: @@ -115,7 +117,7 @@ You can stake XPLL which you have deposited with validators to earn rewards. 4. To add more staked XPLL, select the **STAKE** button. Enter the amount of XPLL you wish to stake in the **STAKE MAX** field. The number cannot exceed the amount of XPLL you have deposited. 5. Press **NEXT** once you are comfortable with the amount. -### Step 2b: Stake With XPLL From Your Lock-Up Contract +#### From Your Lock-Up Contract 1. The details of the validator pool will be displayed as shown: - **LOCK-UP CONTRACT (XPLL)**/**LOCKED** - your tokens that are still vested. @@ -146,18 +148,17 @@ You can stake XPLL which you have deposited with validators to earn rewards. 2. Once you are satisfied with the populated fields, press **NEXT** at the bottom. 3. Preview the summary of the transaction, then press **CONFIRM** to continue, or **CANCEL** to make edits. 4. The status of the token deposit will be shown as **PENDING**. When it is validated by the network, a **SUCCESS** will be shown under its status tab. - !!! note - Due to the network state when your transaction gets included, the actual amount may differ slightly from your desired amount. -5. The staking will take approximately two epochs to be confirmed. +!!! Note + Due to the network state when your transaction gets included, the actual amount may differ slightly from your desired amount. Watch the video tutorial on how to stake your XPLL [here](https://youtu.be/aEa1T-sopmA). -## Top-Up Your Stake +## Topping Up Your Stake -### Step 1: Navigate to your chosen validator +### Step 1: Navigate To Your Chosen Validator ![validator details](../../img/explorer/staking/9_top_up_select_validator.png){ width=90% style="display: block; margin: 0 auto" } 1. On the main page, select the **STAKES** tab which is located beside the **TRANSACTIONS** tab. Then select the pool which you wish to top up XPLL. @@ -174,7 +175,7 @@ Watch the video tutorial on how to stake your XPLL [here](https://youtu.be/aEa1T -### Step 2: Top-up Your Stake Through Your Balance Account +### Step 2: Top-up Your Stake Through Your Account 1. Once you have selected your desired validator, the details of the validator pool will be displayed as shown: - Selecting the drop-down arrow under the **POOL NAME**: @@ -211,7 +212,7 @@ Watch the video tutorial on how to top up your XPLL [here](https://youtu.be/aEa1 ## Withdrawing Your Stakes -### Step 1: Navigate to your chosen validator +### Step 1: Navigate To Your Chosen Validator ![validator details](../../img/explorer/staking/12a_withdraw_select_validator.png){ width=90% style="display: block; margin: 0 auto"} 1. On the main page, select the **STAKES** tab which is located beside the **TRANSACTIONS** tab. Then select the pool which you wish to withdraw XPLL. @@ -227,7 +228,9 @@ Watch the video tutorial on how to top up your XPLL [here](https://youtu.be/aEa1 3. To withdraw XPLL, tap on the arrow beside the **DEPOSIT** field. -### Step 2a: Withdraw Stakes To Your Balance Account +### Step 2: Withdraw Stakes + +#### To Your Account 1. The details of the validator pool will be displayed as shown: @@ -244,7 +247,7 @@ Watch the video tutorial on how to top up your XPLL [here](https://youtu.be/aEa1 3. The **WITHDRAW MAX** field will appear, and you can enter the amount you wish to withdraw. The amount cannot exceed the current amount deposited with the validator. -### Step 2b: Withdraw Stakes Through Your Lock-Up Contract +#### To Your Lock-Up Contract 1. The details of the validator pool will be displayed as shown: - **LOCK-UP CONTRACT (XPLL)**/**LOCKED** - your tokens that are still vested. @@ -272,7 +275,10 @@ Watch the video tutorial on how to top up your XPLL [here](https://youtu.be/aEa1 2. Once you are satisfied with the populated fields, press **NEXT** at the bottom 3. Preview the summary of the transaction, then press **CONFIRM** to continue, or **CANCEL** to make edits -4. The status of the token withdrawal will be shown as **PENDING**. When it is validated by the network, a **SUCCESS** will be shown under its status tab. Due to the network state when your transaction gets included, the actual amount may differ slightly from your desired amount. +4. The status of the token withdrawal will be shown as **PENDING**. When it is validated by the network, a **SUCCESS** will be shown under its status tab. + +!!! Note + Due to the network state when your transaction gets included, the actual amount may differ slightly from your desired amount. Watch the video tutorial to withdraw your XPLL [here](https://youtu.be/aEa1T-sopmA). @@ -280,7 +286,7 @@ Watch the video tutorial to withdraw your XPLL [here](https://youtu.be/aEa1T-sop ## Unstaking Your XPLL -### Step 1: Navigate to your chosen validator +### Step 1: Navigate To Your Chosen Validator ![validator details](../../img/explorer/staking/14a_unstake_select_validator.png){ width=90% style="display: block; margin: 0 auto"} @@ -296,8 +302,9 @@ Watch the video tutorial to withdraw your XPLL [here](https://youtu.be/aEa1T-sop 3. To unstake XPLL, tap on the arrow beside the **TENTATIVE STAKE**field. +### Step 2: Unstake XPLL -### Step 2a: Unstake XPLL To Your Balance Account +#### To Your Account ![unstake](../../img/explorer/staking/15_unstake.png){ width=90% style="display: block; margin: 0 auto" } @@ -314,7 +321,7 @@ Watch the video tutorial to withdraw your XPLL [here](https://youtu.be/aEa1T-sop 4. Press **NEXT** once you are comfortable with the amount. -### Step 2b: Unstake XPLL To Your Lock-Up Contract +#### To Your Lock-Up Contract 1. The details of the validator pool will be displayed as shown: - **LOCK-UP CONTRACT (XPLL)**/**LOCKED** - your tokens that are still vested. @@ -344,39 +351,47 @@ Watch the video tutorial to withdraw your XPLL [here](https://youtu.be/aEa1T-sop 2. Once you are satisfied with the populated fields, press **NEXT** at the bottom. 3. Preview the summary of the transaction, then press **CONFIRM** to continue, or **CANCEL** to make edits. -4. The status of the token deposit will be shown as **PENDING**. When it is validated by the network, a **SUCCESS** will be shown under its status tab. Due to the network state when your transaction gets included, the actual amount may differ slightly from your desired amount. -5. The request to unstake will take approximately two epochs to be confirmed. +4. The status of the token deposit will be shown as **PENDING**. When it is validated by the network, a **SUCCESS** will be shown under its status tab. + +!!! Note + Due to the network state when your transaction gets included, the actual amount may differ slightly from your desired amount. + Watch the video tutorial to unstake your XPLL [here](https://youtu.be/aEa1T-sopmA). ## FAQ ---- ### Why am I not able to stake XPLL tokens? You will need to retain a certain amount of XPLL in your account balance to pay for transaction fees. Ensure that you have reserved a small amount of XPLL tokens to pay for the gas fee of your deposit, stake, or unstake XPLL tokens. +--- ### How do I know which validator to stake with? The validators securing ParallelChain Mainnet are trusted participants which are required to stake a significant number of XPLL. You may check the **yield** and **commission fee** of each validator by tapping on the drop-down arrow of the **Operator** field. +--- ### How long is the unstaking period? The staking duration is measured by epochs. If you stake and unstake within the same epoch, the waiting time is considerably shorter. If the staking and unstaking are not within the same epoch, you will need to wait at least for another two epochs before unstaking. +--- ### How long is an Epoch? One full epoch lasts approximately one day before it enters the next epoch. The epoch itself is a protocol-defined period for measuring performance of operators on the network. +--- ### How do I withdraw my staking rewards? You can withdraw the rewards you have earned from staking by unstaking them to your Token Deposit. Additionally, you may toggle the **AUTO STAKE REWARDS** to avoid the process of unstaking your rewards. From there, you can then withdraw the amount to your wallet. Please refer to the section of [Unstaking Your XPLL](#unstaking-your-xpll) and [Withdrawing Your Stakes](#withdrawing-your-stakes) for the required steps. +--- ### Can I move my staked XPLL to another validator? Yes, you can. You will need to unstake your XPLL tokens, withdraw them to the Token Deposit, then back to your wallet. You can then transfer those tokens to a Token Deposit with another validator before staking your tokens with them. Please refer to the sections above to move your XPLL to another validator. +--- ### The status is still showing **PENDING**. Why is my transaction not confirmed yet? Transactions are prioritised by the amount of Priority Fee per Gas paid, and lower priority transactions may need more time to be confirmed. You may choose to pay a higher Priority Fee during peak periods for a faster transaction, or you may check your wallet address on the blockchain explorer to monitor its transaction status. \ No newline at end of file diff --git a/docs/user_guides/wallet_web_based_tool/transfer_tokens.md b/docs/for_users/web_wallet/transfer_tokens.md similarity index 87% rename from docs/user_guides/wallet_web_based_tool/transfer_tokens.md rename to docs/for_users/web_wallet/transfer_tokens.md index 7e7f8c08..10d0ed68 100644 --- a/docs/user_guides/wallet_web_based_tool/transfer_tokens.md +++ b/docs/for_users/web_wallet/transfer_tokens.md @@ -7,10 +7,9 @@ tags: Sending and receiving assets with digital wallets is a keystone of any blockchain's decentralised infrastructure. Follow the steps below to send and receive XPLL tokens with your ParallelChain account. You can also watch the video tutorials to send XPLL tokens [here](https://youtu.be/WvJhzw3fYKo). -## Sending XPLL Tokens ---- +## Sending XPLL -### Step 1: Log Into Your Wallet +### Step 1: Login Your Wallet ![send_and_receive](../../img/explorer/transfer/1_send_receive.jpg){ width=80% style="display: block; margin: 0 auto" } 1. Access the blockchain explorer via explorer.parallelchain.io, or click on the **EXPLORER** button on the [ParallelChain homepage](https://parallelchain.io/). @@ -20,7 +19,7 @@ Sending and receiving assets with digital wallets is a keystone of any blockchai 5. Once you are verified, you can access your wallet account. -### Step 2: Send Tokens To Another Address +### Step 2: Send XPLL to Another Address 1. Click the **SEND** button below the display that shows your XPLL balance. @@ -38,7 +37,7 @@ Sending and receiving assets with digital wallets is a keystone of any blockchai 6. Once you are satisfied with the populated fields, press **NEXT** at the bottom. -### Step 3: Confirm Your Transaction Details +### Step 3: Confirm Your Transaction ![send_and_receive](../../img/explorer/transfer/3_send_receive.jpg){ width=80% style="display: block; margin: 0 auto" } 1. Preview the summary of the transaction, then press **CONFIRM** to continue, or **CANCEL** to make edits. @@ -47,8 +46,7 @@ Sending and receiving assets with digital wallets is a keystone of any blockchai 3. Watch the video tutorial to send XPLL tokens [here](https://youtu.be/WvJhzw3fYKo). -## Receiving XPLL Tokens ---- +## Receiving XPLL ### Step 1: Share Your Account Address @@ -58,7 +56,7 @@ Sending and receiving assets with digital wallets is a keystone of any blockchai - The sender should paste your address in the **To Address** field in their ParallelChain wallet. -### Step 2: Receive Your XPLL Tokens +### Step 2: Receive Your XPLL - After the sender has confirmed the transaction, be patient as the transaction is being validated by the network. @@ -66,11 +64,11 @@ Sending and receiving assets with digital wallets is a keystone of any blockchai ## FAQ ---- -### I have not received my XPLL tokens. Where can I check the transaction status? -To check the status of your transaction, you can access the [ParallelChain blockchain explorer](https://explorer.parallelchain.io/) and key in your wallet address. It will display the status and amount being sent. If you are the transaction initiator, you can refer to the status on your wallet's **ACTIVITY** tab. +### I have not received my XPLL. Where can I check the transaction status? +To check the status of your transaction, you can access the [ParallelChain Explorer](https://explorer.parallelchain.io/) and key in your wallet address. It will display the status and amount being sent. If you are the transaction initiator, you can refer to the status on your wallet's **ACTIVITY** tab. +--- ### Can I cancel or refund transactions? No, once a transaction request has been made, it cannot be cancelled. \ No newline at end of file diff --git a/docs/user_guides/wallet_browser_extension/create_account.md b/docs/for_users/xperience_browser_extension/create_account.md similarity index 92% rename from docs/user_guides/wallet_browser_extension/create_account.md rename to docs/for_users/xperience_browser_extension/create_account.md index 1ed84fcf..c9f381d5 100644 --- a/docs/user_guides/wallet_browser_extension/create_account.md +++ b/docs/for_users/xperience_browser_extension/create_account.md @@ -1,11 +1,11 @@ --- tags: -- Xperience extension +- Xperience browser extension --- -!!! note +!!! Note This process is the same on Xperience Browser Extension as it is on ParallelChain Explorer. -**Xperience** is your ParallelChain wallet, and **Xperience Browser Extension** is its browser extension. +**Xperience Browser Extension** is browser extension of your ParellelChain Explorer Wallet. To conduct transactions on ParallelChain Mainnet you will first need to create an account on the blockchain to access the network. Accounts are free to create, and they can be set up through **Xperience Browser Extension**—or through the good old **ParallelChain Explorer**. @@ -13,19 +13,15 @@ The blockchain account you create on ParallelChain is non-custodial, which means Learn how to create and manage your ParallelChain account using **Xperience Browser Extension** with the steps below. - +## Installing Xperience Browser Exension -## Install **Xperience Browser Exension** ---- - -For Chrome users, install the extension via the [Chrome Web Store](https://chromewebstore.google.com/detail/xperience-browser-extensi/gpfllmjckejjhmmdmgbgmclmhopekjpf). The extension currently only works on Chrome. +The extension currently only works on Chrome. Chrome user can install the extension via the [Chrome Web Store](https://chromewebstore.google.com/detail/xperience-browser-extensi/gpfllmjckejjhmmdmgbgmclmhopekjpf). If necessary, refer to [these instructions](https://support.google.com/chrome_webstore/answer/2664769?hl=en) on installing Chrome extensions. -## Register for a New Wallet ---- +## Registering for a New Wallet -### Obtain Your Recovery Key +### Getting Your Recovery Key ![Create your account](../../img/extension/1_Welcome.png){ width=80% style="display: block; margin: 0 auto" } @@ -39,7 +35,7 @@ If necessary, refer to [these instructions](https://support.google.com/chrome_we 5. Click **Next**. -### Verify Your Recovery Key +### Verifying Your Recovery Key ![Verify your recovery key](../../img/extension/2_Seed%20Phrase.png){ width=80% style="display: block; margin: 0 auto" } 1. You will be prompted to fill in some missing words in your recovery key. Refer to your recovery key to enter all the missing words in the blanks. @@ -48,7 +44,7 @@ If necessary, refer to [these instructions](https://support.google.com/chrome_we 3. If an error message appears, refer to your recovery key again and check if you have entered the correct words. -### Create Your Password +### Creating Your Password 1. Create a password for your wallet and enter it in the **Password** field. Your password can contain any characters, but it must satisfy the following conditions: - at least 8 characters long, - at least 1 uppercase letter, @@ -57,7 +53,7 @@ If necessary, refer to [these instructions](https://support.google.com/chrome_we 2. Enter your password again in the **Confirm Password** field. If you receive a `Passwords do not match` error, re-enter your password and check that both your entries are the same. - !!! note + !!! Note This password is only limited to the wallet access on the particular device you are registering your account on, and it cannot be accessed from another device. 3. Click **REGISTER**. Congratulations! Your ParallelChain account has now been created. @@ -65,7 +61,7 @@ If necessary, refer to [these instructions](https://support.google.com/chrome_we 4. You will be prompted to enter your password again to log in to your wallet. ## Importing an Existing Wallet ---- + ![Importing existing wallet](../../img/extension/3_Import%20Existing%20Wallet.png){ width=40% style="display: block; margin: 0 auto" } 1. Open **Xperience Browser Extension** by clicking on the extension icon next to your browser address bar. @@ -78,11 +74,11 @@ If necessary, refer to [these instructions](https://support.google.com/chrome_we You will be prompted to create a password for your wallet. You can follow the instructions [here](#create-your-password). -!!! note - Importing your wallet only recovers accounts associated with the recovery key. Refer to the steps in [Exporting Account with Public and Private Keys](#exporting-account-with-public-and-private-keys) and [Importing Your Account Using Public and Private Keys](#importing-account-with-public-and-private-keys) to export and import individual accounts. +!!! Note + Importing your wallet only recovers accounts associated with the recovery key. Refer to the steps in [Exporting Account](#exporting-account) and [Importing Account](#importing-account) to export and import individual accounts. ## Logging into Your Wallet ---- + ![Logging ](../../img/extension/4_Logging%20In.png){ width=40% style="display: block; margin: 0 auto" } 1. Open **Xperience Browser Extension** by clicking on the extension icon next to your browser address bar. @@ -107,7 +103,6 @@ If you do not remember your password, you can reset your password with your reco 5. You will be prompted to enter your password again to log in to your wallet. Enter your new password and click **VERIFY**. You can now access your wallet. --> ## Configuring Your Security and Login ---- ### Viewing Your Recovery Key
@@ -121,11 +116,10 @@ If you do not remember your password, you can reset your password with your reco 3. Enter your password and click **VERIFY**. - !!! note - If you do not remember your password, you can **log in with your recovery key**. - + !!! Note + If you do not remember your password, you can **log in with your recovery key**. + - Click **VERIFY WITH RECOVERY KEY**. - - Enter your 12-word recovery key and click **Next**. 6. Click **View Recovery Key**. You will see your 12-word recovery key. @@ -142,7 +136,7 @@ If you do not remember your password, you can reset your password with your reco 3. Enter your password and click **VERIFY**. - !!! note + !!! Note If you do not remember your password, you can reset your password with your recovery key. - Click **VERIFY WITH RECOVERY KEY**. @@ -157,7 +151,7 @@ If you do not remember your password, you can reset your password with your reco 5. Enter your password again in the **Confirm Password** field. If you receive a `Passwords do not match` error, re-enter your password and check that both your entries are the same. - !!! note + !!! Note This password is only limited to the wallet access on the particular device you are registering your account on, and it cannot be accessed from another device. @@ -177,7 +171,7 @@ If you do not remember your password, you can reset your password with your reco 3. Enter your password and click **VERIFY**. - !!! note + !!! Note If you do not remember your password, you can reset your password with your recovery key. - Click **VERIFY WITH RECOVERY KEY**. @@ -211,8 +205,8 @@ If you do not remember your password, you can reset your password with your reco 2. Click the download icon beside your wallet address to start the download. 3. Store the JSON file securely. You can open the file with any text editor, like Notepad or Microsoft Word. -!!! note - If you wish to recover your account on another wallet, you can do so by importing your accounts. Refer to the steps in [Importing Your Account with Public & Private Keys]() or [Importing Your Account with a JSON File](). +!!! Note + If you wish to recover your account on another wallet, you can do so by importing your accounts. Refer to the steps in [Importing Account](#importing-account). ## Importing Account @@ -228,7 +222,7 @@ If you do not remember your password, you can reset your password with your reco 4. Enter your private key in the **Private Key** field. 5. Enter your desired account name in the **Account Name** field. - !!! note + !!! Note If you are not sure where to find your public and private keys, refer to [Exporting Account as Public & Private Keys](#as-public-and-private-keys). 6. Click **IMPORT**. You have successfully imported your account. @@ -244,13 +238,13 @@ If you do not remember your password, you can reset your password with your reco 2. Click **IMPORT**. 3. Click **IMPORT WITH FILE** and select the appropriate JSON file. - !!! note - If you are not sure how to export your JSON file, refer to [Exporting Your Account as a JSON File](#as-a-json-file). + !!! Note + If you are not sure how to export your JSON file, refer to [Exporting Account as a JSON File](#as-a-json-file). 4. Click **IMPORT**. You have successfully imported your account. ## Locking Your Wallet ---- +
@@ -266,14 +260,20 @@ If you do not remember your password, you can reset your password with your reco Yes, they are the same. You can access your wallet through either **Xperience Browser Extension** or **ParallelChain Explorer**. +--- + ### Is my Xperience Browser Extension the same as my ParallelChain account? No, they are not the same. Your ParallelChain account is the keypair registered on the **ParallelChain Mainnet**, and the Xperience browser extension is simply a platform that connects you to your ParallelChain account. You can access your ParallelChain account as long as you have your keypair, even if you lose the device the Xperience Browser Extension is installed on. +--- + ### Can I send XPLL tokens to other blockchains like Ethereum? No, you cannot send XPLL tokens to other blockchains at the moment. XPLL and other PRFC tokens are currently only compatible with the ParallelChain Mainnet network, and sending your tokens to other network addresses will lose your tokens. +--- + ### What happens if I lose both my recovery key and password? Xperience is a non-custodial wallet that only you have access to. If you lose your recovery key and password, you will lose access to your wallet. We recommend that you write down your recovery key and store it in a secure place. @@ -283,6 +283,8 @@ After that, register for a new wallet by following the steps under [Register for If you have exported your public and private keys before, you can then recover access to your assets by importing your old account with its public and private keys. For more details, follow the steps under [Exporting Account](#exporting-account) and [Importing Account](#importing-account). +--- + ### Where can I seek support or report bugs? You can visit ParallelChain's [Discord](https://discord.gg/parallelchainofficial) for community help. If you cannot resolve your issue there, you can write to [walletsupport@parallelchain.io](mailto:walletsupport@parallelchain.io). diff --git a/docs/user_guides/wallet_browser_extension/lockup_contract.md b/docs/for_users/xperience_browser_extension/lockup_contract.md similarity index 98% rename from docs/user_guides/wallet_browser_extension/lockup_contract.md rename to docs/for_users/xperience_browser_extension/lockup_contract.md index e0150301..76ad0bed 100644 --- a/docs/user_guides/wallet_browser_extension/lockup_contract.md +++ b/docs/for_users/xperience_browser_extension/lockup_contract.md @@ -4,21 +4,21 @@ tags: - xpll - lockup contract --- -!!! note +!!! Note This process is the same on Xperience Browser Extension as it is on ParallelChain Explorer. Your XPLL allocation might be subject to a **vesting schedule** that determines how many of your tokens are vested (unlocked) as time goes on. You need to first *register the lock-up contract of your allocation* to your account so you can *claim your unlocked tokens* in the future, -!!! note +!!! Note Each lock-up contract is unique to its holder. Follow the steps below to register your lock-up contract and claim your tokens with your ParallelChain wallet. -!!! note +!!! Note Before you can perform the following steps, you need to have created and logged in to your ParallelChain account. If you are not sure how to do so, refer to [Xperience Browser Extension Tutorials: Creating and Managing Your Account](./create_account.md). ## Registering Your Lock-Up Contract ---- + ### Step 1: Get Your Lock-Up Contract Address 1. Your lock-up contract address would have been sent to you **via email**. Check your email and copy your lock-up contract address. @@ -43,7 +43,7 @@ Follow the steps below to register your lock-up contract and claim your tokens w - **Contract Address** - your lock-up contract address. - !!! note + !!! Note You will have to manually claim the vested tokens to have them transferred to your normal account. 4. Click **CONFIRM**. Your lock-up contract has now been registered. @@ -52,11 +52,11 @@ Follow the steps below to register your lock-up contract and claim your tokens w 5. You will be taken back to the main page. If you scroll right, you will see your **Lock-Up Contract (XPLL)** balance next to your main balance. -!!! note +!!! Note Your account comes with a small number of XPLL to pay for the gas fee for the first transaction. For Node Round participants who will operate validator nodes on ParallelChain, the locked balance shown will be **0**, as your allocation has been automatically staked on one of the existing validator nodes. ## Claiming Your Vested Tokens ---- + ### Step 1: Check Your Vested Balance ![check vested balance](../../img/extension/14_Select%20a%20validator.png){ width=40% style="display: block; margin: 0 auto" } @@ -111,10 +111,12 @@ Follow the steps below to register your lock-up contract and claim your tokens w 9. You can check the status of your transaction in the **Transactions** tab. When the transaction is validated by the network, the transaction status will show **SUCCESS**. The claimed tokens have now been transferred to your account. ## FAQ ---- + ### Do I need to wait for the full vesting period before I can claim the locked XPLL? A set number of XPLLs will be unlocked after a set period of time. The unlocked number of XPLL will be displayed in the **Unlocked** field. You may choose to claim the XPLL each time it is unlocked, but **note that gas fees will have to be paid for each claim**. You may also choose to accumulate the unlocked XPLL and claim it in one transaction. +--- + ### Where can I seek support or report bugs? You can visit ParallelChain’s [Discord](https://discord.gg/parallelchainofficial) for community help. If you cannot resolve your issue there, you can write to [walletsupport@parallelchain.io](mailto:walletsupport@parallelchain.io). \ No newline at end of file diff --git a/docs/user_guides/wallet_browser_extension/managing_tokens.md b/docs/for_users/xperience_browser_extension/managing_tokens.md similarity index 98% rename from docs/user_guides/wallet_browser_extension/managing_tokens.md rename to docs/for_users/xperience_browser_extension/managing_tokens.md index 179012da..5fb5659f 100644 --- a/docs/user_guides/wallet_browser_extension/managing_tokens.md +++ b/docs/for_users/xperience_browser_extension/managing_tokens.md @@ -4,19 +4,17 @@ tags: - xpll --- -!!! note +!!! Note This process is new to **Xperience Browser Extension**. It is not available on **ParallelChain Explorer**. You can manage other tokens apart from XPLL using the Xperience Browser Extension. Follow the steps below to manage tokens in your ParallelChain account. -!!! note +!!! Note Before you can perform the following steps, you need to have created and logged in to your ParallelChain account. If you are not sure how to do so, refer to [Xperience Browser Extension Tutorials: Creating and Managing Your Account](./create_account.md). ## Importing Tokens ---- - ![import tokens](../../img/tokens/3_Importing%20Tokens.png){ width=40% style="display: block; margin: 0 auto" } 1. On the main page, click the **Tokens** tab. @@ -40,7 +38,7 @@ You can manage other tokens apart from XPLL using the Xperience Browser Extensio 8. If you click **CONFIRM**, you will be taken back to the main page. Your token has now been imported and you will see it under the **Tokens** tab. ## Viewing Token Details ---- + ![import tokens](../../img/tokens/6.Navigation%20Token%20tab.png){ width=40% style="display: block; margin: 0 auto" } 1. On the main page, click the **Tokens** tab. @@ -63,10 +61,10 @@ You can manage other tokens apart from XPLL using the Xperience Browser Extensio - The **Contract Address** - the token contract address. - The **Token Custom Name** - the custom name you entered for the token. -5. You can click the arrow next to the **Balance** field to send tokens. For more details on how to send tokens, refer to [Sending Tokens](./transfer_tokens.md#sending-tokens). +5. You can click the arrow next to the **Balance** field to send tokens. For more details on how to send tokens, refer to [Sending Tokens](./create_account.md#sending-tokens). ## Removing Imported Tokens ---- + ![import tokens](../../img/tokens/8_Remove%20Imported%20Token%20(Navi).png){ width=40% style="display: block; margin: 0 auto" } 1. On the main page, click the **Tokens** tab. @@ -82,16 +80,21 @@ You can manage other tokens apart from XPLL using the Xperience Browser Extensio 6. If you click **CONFIRM**, you will be taken back to the main page. Your token has now been removed and you will no longer see the removed token under the **Tokens** tab. ## FAQ ---- ### What types of tokens can I import into my wallet? In this version of Xperience Browser Extension, you can only import **PRFC1 tokens** to your wallet. +--- + ### Can I add NFTs to my wallet? This version of Xperience Browser Extension (v1.0.2) does not support NFT. +--- + ### Can I remove XPLL from my wallet? No, you cannot remove XPLL from your wallet. You can only remove tokens that you have imported. +--- + ### Where can I seek support or report bugs? You can visit ParallelChain’s [Discord](https://discord.gg/parallelchainofficial) for community help. If you cannot resolve your issue there, you can write to [walletsupport@parallelchain.io](mailto:walletsupport@parallelchain.io). \ No newline at end of file diff --git a/docs/user_guides/wallet_browser_extension/staking.md b/docs/for_users/xperience_browser_extension/staking.md similarity index 97% rename from docs/user_guides/wallet_browser_extension/staking.md rename to docs/for_users/xperience_browser_extension/staking.md index 75c02720..7ed99703 100644 --- a/docs/user_guides/wallet_browser_extension/staking.md +++ b/docs/for_users/xperience_browser_extension/staking.md @@ -4,27 +4,26 @@ tags: - staking - xpll --- -!!! note +!!! Note This process is the same on Xperience Browser Extension as it is on ParallelChain Explorer. You can stake XPLL with network validators to help secure the blockchain and earn rewards. Follow the steps below to stake XPLL tokens with your ParallelChain account. -!!! note +!!! Note Before you can perform the following steps, you need to have created and be logged in to your ParallelChain account. If you are not sure how to do so, refer to [Xperience Browser Extension Tutorials: Creating and Managing Your Account](./create_account.md). -## Depositing XPLL with a Validator ---- +## Depositing Your XPLL ### Step 1: Select a Validator ![Select validtor](../../img/extension/16_Stake%20XPLL.png){ width=40% style="display: block; margin: 0 auto" } -1. Click **STAKE XPLL** +1. Click **STAKE XPLL**. 2. You will see the list of validators. Select a validator from the list, or search for a specific validator via the search bar at the top. ### Step 2: Deposit XPLL -#### Through Your Account Balance +#### Through Your Account ![Deposit XPLL your account balance](../../img/extension/17_Validator%20Details.png){ width=40% style="display: block; margin: 0 auto" } 1. You will see the following details of the validator: @@ -72,9 +71,7 @@ You can stake XPLL with network validators to help secure the blockchain and ear 7. To start earning XPLL from staking, follow the instruction in the **Staking Your XPLL** section below. ## Staking Your XPLL -You can stake the XPLL that you ahve deposited with the validators to earn rewards. - ---- +You can stake the XPLL that you have deposited with the validators to earn rewards. ### Step 1: Navigate to Your Chosen Validator ![Stake xpll](../../img/extension/19_View%20Stakes.png){ width=40% style="display: block; margin: 0 auto" } @@ -98,10 +95,11 @@ You can stake the XPLL that you ahve deposited with the validators to earn rewar - **Next Epoch** - when the next epoch will occur. ![tentaive stake](../../img/extension/20_Tentative%20Stakes.png){ width=40% style="display: block; margin: 0 auto" } + 4. Click the arrow beside the **Tentative Stake** field. -### Step 2: Stake with XPLL -#### From Your Account Balance +### Step 2: Stake XPLL +#### From Your Account ![Stake xpll from account balance](../../img/extension/21_Stake%20amount.png){ width=40% style="display: block; margin: 0 auto" } 1. You will see the following details of the validator: @@ -149,17 +147,17 @@ You can stake the XPLL that you ahve deposited with the validators to earn rewar 5. You can check the status of your transaction in the **Transactions** tab. It is labelled **STAKE DEPOSIT**. When the transaction is validated by the network, the transaction status will show **SUCCESS**. Your XPLL have now been staked with the validator. -!!! note - Depending on the network state when your transaction gets included, the actual amount may differ slightly from your desired amount. The staking will take approximately **two epochs** to be confirmed. +!!! Note + Depending on the network state when your transaction gets included, the actual amount may differ slightly from your desired amount. -## Unstaking Your XPLL ---- -### Step 1: Navigate to Your Chosen Validator -![Check status](../../img/extension/23_Unstake%20Amount.png){ width=40% style="display: block; margin: 0 auto" } +## Topping Up Your Stake + +### Step 1: Navigate to Your Chosen Validator +![Check status](../../img/extension/27_Top%20up.png){ width=40% style="display: block; margin: 0 auto" } 1. On the main page, click the **Stakes** tab. -2. Click the validator pool that you wish to unstake XPLL from. +2. Click the validator pool that you wish to top up your deposit with. 3. You will see the following details of the validator: - **Pool Name** - the name of the validator. - **Operator** - the validator's address. @@ -174,15 +172,12 @@ You can stake the XPLL that you ahve deposited with the validators to earn rewar - **Auto Stake Rewards** - whether you have chosen to stake your rewards automatically. - **Next Epoch** - when the next epoch will occur. - ![Check status](../../img/extension/24_Arrow%20next%20to%20'Tentative%20Stake'.png){ width=40% style="display: block; margin: 0 auto" } - -4. Click the arrow beside the **Tentative Stake** field. - -### Step 2: Unstake XPLL + ![Check status](../../img/extension/28_Top%20up%20(Deposit).png){ width=40% style="display: block; margin: 0 auto" } -#### To Your Account Balance +4. Click the arrow beside the **Deposit** field. -![Check status](../../img/extension/25_Unstake%20Amount%20Field.png){ width=40% style="display: block; margin: 0 auto" } +### Step 2: Top-Up Your Stake Through Your Account +![Check status](../../img/extension/29_Top%20up%20(Through%20Balance).png){ width=40% style="display: block; margin: 0 auto" } 1. You will see the following details of the validator: - **Pool Name** - the name of the validator. @@ -192,23 +187,10 @@ You can stake the XPLL that you ahve deposited with the validators to earn rewar - **Deposit** - the number of XPLL you have deposited with the validator. - **Tentative Stake** - the number of XPLL you have in the validator pool that will become part of the current stake in the future. -2. Click **UNSTAKE**. -3. The **Unstake** field will appear. Enter the number of XPLL you wish to unstake. The number cannot exceed the number of XPLL you have staked. +2. Click **TOP-UP** to deposit more XPLL with the validator. +3. The **Top-Up** field will appear. Enter the number of XPLL you wish to top up. The number cannot be more than your account balance. 4. Click **NEXT**. -#### To Your Lock-Up Contract -1. You will see the following details of the validator: - - **Lock-Up Contract (XPLL)**/**Locked** - the number tokens that are still vested. - - **Pool Name** - the name of the validator. - - **Operator** - the validator's address. - - **Pool Stake** - the number of XPLL staked with the validator. - - **Commission Fee** - the percentage of your rewards that validator will take as a commission fee. - - **Deposit** - the number of XPLL you have deposited with the validator. - - **Tentative Stake** - the number of XPLL you have in the validator pool that will become part of the current stake in the future. - -2. The **Unstake** field will be automatically filled in for you when you unstake XPLL to your lock-up contract. -3. Click **NEXT**. - ### Step 3: Confirm Your Transaction 1. You will see the following additional fields: - **Nonce** - will be automatically filled in for you. @@ -218,22 +200,21 @@ You can stake the XPLL that you ahve deposited with the validators to earn rewar - **Estimated Gas Fee** - the approximate gas fee that will be charged for your transaction. 2. If you are satisfied with the fields, click **NEXT**. -3. Preview the summary of the tranasction. Click **CONFIRM** to continue or **CANCEL** to make edits. -4. You will see the detais of the transaction. The transaction status will show **PENDING**. Click **CLOSE**. +3. Preview the summary of the transaction. Click **CONFIRM** to continue or **CANCEL** to make edits. +4. The transaction will show **PENDING**. Click **CLOSE**. - ![Check status](../../img/extension/26_Check%20Unstaking%20Transaction.png){ width=40% style="display: block; margin: 0 auto" } +![Check status](../../img/extension/30_Check%20Pending%20Transaction%20(Top%20up).png){ width=40% style="display: block; margin: 0 auto" } -5. You can check the status of your transaction in the **Transactions** tab. It is labelled **UNSTAKE DEPOSIT**. When the transaction is validated by the network, the transaction status will show **SUCCESS**. Your XPLL have now been unstaked from the validator. -!!! note - Depends on the network state when your transaction gets included, the actual amount may differ slightly from your desired amount. The staking will take approximately **two epochs** to be confirmed. +5. You can check the status of your transaction in the **Transaction** tab. It is labelled **TOP UP DEPOSIT**. When the transaction is validated by the network, the transaction status will show **SUCCESS**. Your deposit has now been topped up. + +## Unstaking Your XPLL -## Topping Up Your Stake ---- ### Step 1: Navigate to Your Chosen Validator -![Check status](../../img/extension/27_Top%20up.png){ width=40% style="display: block; margin: 0 auto" } + +![Check status](../../img/extension/23_Unstake%20Amount.png){ width=40% style="display: block; margin: 0 auto" } 1. On the main page, click the **Stakes** tab. -2. Click the validator pool that you wish to top up your deposit with. +2. Click the validator pool that you wish to unstake XPLL from. 3. You will see the following details of the validator: - **Pool Name** - the name of the validator. - **Operator** - the validator's address. @@ -248,12 +229,15 @@ You can stake the XPLL that you ahve deposited with the validators to earn rewar - **Auto Stake Rewards** - whether you have chosen to stake your rewards automatically. - **Next Epoch** - when the next epoch will occur. - ![Check status](../../img/extension/28_Top%20up%20(Deposit).png){ width=40% style="display: block; margin: 0 auto" } + ![Check status](../../img/extension/24_Arrow%20next%20to%20'Tentative%20Stake'.png){ width=40% style="display: block; margin: 0 auto" } -4. Click the arrow beside the **Deposit** field. +4. Click the arrow beside the **Tentative Stake** field. + +### Step 2: Unstake XPLL -### Step 2: Top Up Your Stake through Your Account Balance -![Check status](../../img/extension/29_Top%20up%20(Through%20Balance).png){ width=40% style="display: block; margin: 0 auto" } +#### To Your Account + +![Check status](../../img/extension/25_Unstake%20Amount%20Field.png){ width=40% style="display: block; margin: 0 auto" } 1. You will see the following details of the validator: - **Pool Name** - the name of the validator. @@ -263,10 +247,23 @@ You can stake the XPLL that you ahve deposited with the validators to earn rewar - **Deposit** - the number of XPLL you have deposited with the validator. - **Tentative Stake** - the number of XPLL you have in the validator pool that will become part of the current stake in the future. -2. Click **TOP-UP** to deposit more XPLL with the validator. -3. The **Top-Up** field will appear. Enter the number of XPLL you wish to top up. The number cannot be more than your account balance. +2. Click **UNSTAKE**. +3. The **Unstake** field will appear. Enter the number of XPLL you wish to unstake. The number cannot exceed the number of XPLL you have staked. 4. Click **NEXT**. +#### To Your Lock-Up Contract +1. You will see the following details of the validator: + - **Lock-Up Contract (XPLL)**/**Locked** - the number tokens that are still vested. + - **Pool Name** - the name of the validator. + - **Operator** - the validator's address. + - **Pool Stake** - the number of XPLL staked with the validator. + - **Commission Fee** - the percentage of your rewards that validator will take as a commission fee. + - **Deposit** - the number of XPLL you have deposited with the validator. + - **Tentative Stake** - the number of XPLL you have in the validator pool that will become part of the current stake in the future. + +2. The **Unstake** field will be automatically filled in for you when you unstake XPLL to your lock-up contract. +3. Click **NEXT**. + ### Step 3: Confirm Your Transaction 1. You will see the following additional fields: - **Nonce** - will be automatically filled in for you. @@ -276,16 +273,17 @@ You can stake the XPLL that you ahve deposited with the validators to earn rewar - **Estimated Gas Fee** - the approximate gas fee that will be charged for your transaction. 2. If you are satisfied with the fields, click **NEXT**. -3. Preview the summary of the transaction. Click **CONFIRM** to continue or **CANCEL** to make edits. -4. The transaction will show **PENDING**. Click **CLOSE**. - -![Check status](../../img/extension/30_Check%20Pending%20Transaction%20(Top%20up).png){ width=40% style="display: block; margin: 0 auto" } +3. Preview the summary of the tranasction. Click **CONFIRM** to continue or **CANCEL** to make edits. +4. You will see the detais of the transaction. The transaction status will show **PENDING**. Click **CLOSE**. -5. You can check the status of your transaction in the **Transaction** tab. It is labelled **TOP UP DEPOSIT**. When the transaction is validated by the network, the transaction status will show **SUCCESS**. Your deposit has now been topped up. + ![Check status](../../img/extension/26_Check%20Unstaking%20Transaction.png){ width=40% style="display: block; margin: 0 auto" } +5. You can check the status of your transaction in the **Transactions** tab. It is labelled **UNSTAKE DEPOSIT**. When the transaction is validated by the network, the transaction status will show **SUCCESS**. Your XPLL have now been unstaked from the validator. +!!! Note + Depends on the network state when your transaction gets included, the actual amount may differ slightly from your desired amount. ## Withdrawing Your Stakes ---- + ### Step 1: Navigate to Your Chosen Validator ![Check status](../../img/extension/31_Withdraw%20staking%20rewards%20(Navigation).png){ width=40% style="display: block; margin: 0 auto" } @@ -312,7 +310,7 @@ You can stake the XPLL that you ahve deposited with the validators to earn rewar ### Step 2: Withdraw Stakes -#### To Your Account Balance +#### To Your Account ![Check status](../../img/extension/33_Click%20to%20withdraw.png){ width=40% style="display: block; margin: 0 auto" } @@ -356,35 +354,48 @@ You can stake the XPLL that you ahve deposited with the validators to earn rewar ![Check status](../../img/extension/34_Check%20Transactions.png){ width=40% style="display: block; margin: 0 auto" } 5. You can check the status of your transaction in the **Transactions** tab. It is labelled **WITHDRAW DEPOSIT**. When the transaction is validated by the network, the transaction status will show **SUCCESS**. Your XPLL have now been withdrawn. -!!! note - Depending on the network state when your transaction gets included, the actual amount may differ slightly from your desired amount. The staking will take approximately **two epochs** to be confirmed. +!!! Note + Depending on the network state when your transaction gets included, the actual amount may differ slightly from your desired amount. ## FAQ ---- + ### Why am I not able to stake XPLL tokens? You will need to retain a certain number of XPLL in your account balance to pay for transaction fees. Ensure that you have reserved enough XPLL to pay for the gas fees for depositing, staking, unstaking, topping up, or withdrawing XPLL. +--- + ### How do I know which validator to stake with? All the validators securing ParallelChain Mainnet are trusted participants who are required to stake a significant number of XPLL. You can check the yield and commission fee of each validator by tapping on the drop-down arrow of the **Operator** field. +--- + ### How long is the unstaking period? The staking duration is measured by epochs. If you stake and unstake within the same epoch, the waiting time is considerably shorter. If you do not stake and unstake within the same epoch, you will need to wait at least for another two epochs before unstaking. +--- + ### How long is an epoch? One full epoch lasts approximately **one day** before it enters the next epoch. The epoch is a protocol-defined period for measuring performance of operators on the network. +--- + ### How do I withdraw my staking rewards? You can withdraw the rewards you have earned from staking by unstaking them to your token deposit. Additionally, you may toggle **Auto Stake Rewards** on to avoid the process of unstaking your rewards. After that, you can withdraw the rewards to your account balance. Please refer to the section on [Unstaking Your XPLL](#unstaking-your-xpll) and [Withdrawing Your Stakes](#withdrawing-your-stakes) for the required steps. +--- + ### Can I move my staked XPLL to another validator? Yes, you can. You will need to *unstake your XPLL tokens* to move them to your token deposit, then *withdraw them to your account balance*. You can then *deposit those tokens to another validator pool*, then *stake your tokens* with them. +--- ### The transaction status is still showing ‘PENDING’. Why is my transaction not confirmed yet? Transactions are prioritised by the amount of *Priority Fee per Gas* paid. Lower priority transactions may need more time to be confirmed. You may choose to pay a higher Priority Fee during peak periods for a faster transaction, or continue checking your wallet address to monitor the transaction status. +--- + ### Where can I seek support or report bugs? You can visit ParallelChain’s [Discord](https://discord.gg/parallelchainofficial) for community help. If you cannot resolve your issue there, you can write to [walletsupport@parallelchain.io](mailto:walletsupport@parallelchain.io). \ No newline at end of file diff --git a/docs/user_guides/wallet_browser_extension/transfer_tokens.md b/docs/for_users/xperience_browser_extension/transfer_tokens.md similarity index 99% rename from docs/user_guides/wallet_browser_extension/transfer_tokens.md rename to docs/for_users/xperience_browser_extension/transfer_tokens.md index c2de5ea6..73780bb5 100644 --- a/docs/user_guides/wallet_browser_extension/transfer_tokens.md +++ b/docs/for_users/xperience_browser_extension/transfer_tokens.md @@ -3,17 +3,17 @@ tags: - Xperience extension - xpll --- -!!! note +!!! Note This process is the same on Xperience Browser Extension as it is on ParallelChain Explorer. Sending and receiving assets with digital wallets is a keystone of any blockchain’s decentralised infrastructure. Follow the steps below to send and receive tokens with your ParallelChain account. -!!! note +!!! Note Before you can perform the following steps, you need to have created and logged in to your ParallelChain account. If you are not sure how to do so, refer to [Xperience Browser Extension Tutorials: Creating and Managing Your Account](./create_account.md). ## Sending Tokens ---- + ![check transfer](../../img/tokens/1_Send%20Tokens.png){ width=40% style="display: block; margin: 0 auto" } ### Step 1: Fill in Transaction Details @@ -21,7 +21,7 @@ Sending and receiving assets with digital wallets is a keystone of any blockchai 2. Select the token to send by clicking the down arrow in the **Token** field. 3. Enter the address that you want to send tokens to in the **To Address** field. - !!! note + !!! Note If you are transferring tokens between your own accounts, you can access your different accounts by clicking the down arrow next to your account name and address. You can copy the address of the receiving account by clicking the copy icon beside its address. 4. Enter the number of tokens you would like to send in the **Send** field. The amount must not be a negative number, and it cannot be more than the number of tokens you currently have. 5. Click **NEXT**. @@ -44,7 +44,7 @@ Sending and receiving assets with digital wallets is a keystone of any blockchai 5. You can check the status of your transaction in the **Transactions** tab. It is labeled **TRANSFER**. When the transaction is validated by the network, the transaction status will show **SUCCESS**. Your tokens have now been sent. ## Receiving XPLL Tokens ---- + ### Step 1: Share Your Wallet Address 1. Click the copy icon next to your wallet address to copy it. 2. Share your wallet address with the sender through a secure text messaging application. @@ -55,19 +55,25 @@ Sending and receiving assets with digital wallets is a keystone of any blockchai 2. Once the transaction is confirmed, your wallet balance will be automatically updated. ## FAQ ---- + ### What tokens can I send or receive? You can send or receive XPLL using either **Xperience Browser Extension** or **ParallelChain Explorer**. However, you can only send or receive **PRFC1 tokens** using **Xperience Browser Extension** for now. +--- + ### I have not received my tokens. Where can I check the transaction status? To check the transaction status of the token transfer, you can use [ParallelChain Explorer](https://explorer.parallelchain.io/explorer?network=Mainnet). Click on your wallet address in **Xperience Browser Extension**. This will open **ParallelChain Explorer**. Enter your wallet address in the search field. Under the **Transactions** section, **RECEIVED** tab, you can see your transactions for receiving tokens. +--- + ### Can I cancel or refund transactions? No, once a transaction request has been made, it cannot be cancelled. +--- + ### Where can I seek support or report bugs? You can visit ParallelChain’s [Discord](https://discord.gg/parallelchainofficial) for community help. If you cannot resolve your issue there, you can write to [walletsupport@parallelchain.io](mailto:walletsupport@parallelchain.io). \ No newline at end of file diff --git a/docs/fundamentals/accounts.md b/docs/fundamentals/accounts.md new file mode 100644 index 00000000..2bee1e57 --- /dev/null +++ b/docs/fundamentals/accounts.md @@ -0,0 +1,62 @@ +--- +tags: + - Account + - EOA + - Network Account +--- + +# Accounts + +**Account** is the basic identity of an agent on the blockchain. An account is identified by its address. + +In Parallelchain Mainnet, accounts are divided into two types: + +- __Externally Owned Accounts (EOA)__: The address of an EOA is the public key of the keypair that is compatible with [ed25519-dalek](https://github.com/dalek-cryptography/curve25519-dalek/). +- __Contract Accounts__: A contract account is created from contract deployment. The address is the [SHA256](https://en.wikipedia.org/wiki/SHA-2) hash of the concatenation of a contract's bytecode and the nonce of the **EOA** that deploys the contract. + +Elements inside an account include: + +- **Nonce**: The number of transactions made to the blockchain under this account. +- **Balance**: The balance of the account. + +The followings are elements that only apply to Contract Accounts: + +- **Contract Code**: The binary of the [smart contract](../for_developers/smart_contracts/introduction.md) that was deployed to the blockchain (applies to Contract Accounts). +- **CBI Version**: The version of the Contract Binary Interface. +- **Storage Hash**: The 32-byte SHA256 root hash of its Storage Trie. This is empty for an External. + +## How Account Works + +You can create **EOA** account by **ed25519-dalek** key generation algorithm. The account is composed of a 32-byte public key and a 32-byte private key. This public key is the **Address** which can be known to others. While your private key, which is used for signing [transactions](transactions.md), **MUST** be kept in secret. + +Address is usually displayed in [Base64url](https://datatracker.ietf.org/doc/html/rfc4648#section-5) format in ParallelChain Mainnet ecosystem. Here is an example: + +```text +Tc0bU2oS0A0_GrjPKsDLSyVa3gc7PvzwWIAGRk-_SmA +``` + +If you want to transfer [XPLL](../introduction.md#what-is-xpll) to Alice's account, first you need to know her address. Then, you create a transaction with Alice's address as [recipient](transactions.md#account-commands), and sign it by using your private key. The **Balance** of your and Alice's account will be updated when this signed transaction is made to blockchain successfully. The **Nonce** of your account will be increased by 1. + +On the other hand, a **Contract Account** is not made up of cryptographic keys. Its address is a 32-byte hash. It is not able to sign a transaction. But similar to **EOA**, it has its own balance, and can receive XPLL from other accounts. See [Smart Contract](../for_developers/smart_contracts/introduction.md) for details. + +!!! Note + The type of account cannot be distinguished from each other just by looking at the address format. + +See also: + +- [Create Account by CLI](../for_users/pchain_client_cli/managing_account.md) +- [Create Account by Web Wallet](../for_users/web_wallet/create_account.md) +- [Create Account by Xperience Browser Extension](../for_users/xperience_browser_extension/create_account.md) + + +## Network Account + +A **Network Account** is a single identified network-wide account that maintains the [state](nodes.md#world-state) of ParallelChain Mainnet. The purpose of this state is to implement the [staking](staking.md) related protocol. This account is not associated with Ed25519 material. The network-significant data that the Network Account stores are composed of various fields: + +- **Previous Validator Set**: The set of pools that form the validator set in the previous epoch. The stake in this validator set is locked until the next epoch. +- **Current Validator Set**: The set of pools that form the validator set in the current epoch. +- **Next Validator Set**: The limited-size pools with the largest powers. These will become the validator set in the next epoch. +- **Pools**: The set of pools that are accepting stakes and currently competing to become part of the next validator set. +- **Deposits**: The locked balance used to determine the amount of stake that can be contributed to a pool. +- **Current Epoch**: The current epoch number. + diff --git a/docs/fundamentals/blocks.md b/docs/fundamentals/blocks.md new file mode 100644 index 00000000..adc72661 --- /dev/null +++ b/docs/fundamentals/blocks.md @@ -0,0 +1,131 @@ +--- +tags: + - Block Header +--- + +# Blocks + +**Block** is a fundamental data structure in a blockchain. It describes execution of a batch of [transactions](transactions.md). Blocks are "chained" by attaching a cryptographic hash of an earlier block. The hash is the proof of the data integrity of the earlier blocks because if their content have been changed, the hash will not be the same. This is how blockchain provides data immutability. + +Summary of the elements inside a block: + +- `Hash` - the unique identifier for the block +- `Height` - a number that represents the position of the block on the blockchain +- `Justify` - a certificate that proves the block was authorized by the network +- `Data Hash` - a hash that covers the content of the block header +- `Chain ID` - a number that identifies a particular Parallelchain Mainnet-based blockchain +- `Proposer` - the public address of the block producer +- `Timestamp` - the time the block was created, measured in seconds since 1970-01-01 +- [Base Fee Per Gas](nodes.md#base-fee-per-gas-in-parallelchain-mainnet) - the minimum number of grays that a transaction must pay for every gas used to be included in the block +- `Gas Used` - the amount of [gas](gas.md) used in a block, which is the total sum of the gas used in executing the included transactions +- `Transactions Hash` - the root hash of the Merkle Tree that contains the transactions included in the block +- `Receipt Hash` - the root hash of the Merkle Tree that contains the execution results of the transactions included in the block +- `State Hash` - the root hash of the Merkle Tree that represents the current world state +- `Log Bloom` - a 256-byte block-level [Bloom Filter](https://en.wikipedia.org/wiki/Bloom_filter) that combines all the Bloom Filters of each Log topic from the block's receipts +- [Transactions](transactions.md) - the transactions that are included in the block +- [Receipts](transactions.md#receipt-and-logs) - the execution results of the transactions that are included in the block + +## Inside a Block + +Each block contains a unique identifier known as the `block hash`, which is calculated based on the contents of the block. The block hash acts as a fingerprint for the block, making it tamper-evident. Any change to the block's contents would alter its hash, making it easily detectable by network participants. + +The block header contains important metadata about the block, including the block's `height`, `timestamp`, and the `address of the block producer`, among others. It also includes Merkle Patricia Tree root hashes for transactions, receipts, and the current state of the blockchain. + +Transactions contained within the block are executed by the blockchain system, with the results recorded in receipts. These receipts contain information about the execution status of each transaction and are stored in a Merkle Patricia Tree, with the root hash included in the block header. + +In addition to transactions and receipts, the block also contains a Bloom filter, which is a probabilistic data structure used to efficiently query logs associated with the transactions contained in the block. + +Example of a block queried by [ParallelChain Client CLI](../for_users/pchain_client_cli/querying_blockchain.md): + +```json +{ + "header": { + "chain_id": 10000, + "block_hash": "Yn0SAN6KDA3v2uDjN_j1P_tFCCqgqCbak1g7zvHwr9Q", + "height": 2844080, + "justify": { + "chain_id": 10000, + "view": 2844930, + "block": "zT3iUT2sCmD80ztBDScBlAvUXhbzba7RTLtSiBLsvRg", + "phase": "Generic", + "signatures": { + "signatures": [ + "hin8bfLnbuuUBRVB7GbClI0g1Ad0rfM_oDfvYILhwKPG_eqqZEDVyNj1c1VZeeRuUW94pqEQzAqbz4zQuTz0Dg", + "5usLkVtsEsFCIHQOKi8X_LjvMxzBd4xxJJz7QSbl1pGLimFUkpV5MCBi1SGRY9jVHCArxu6v3B_jn3xCZfhrCg", + null, + null, + "XqLSsQP6YkvtbBpPo7NX4o2Q7GvjAU-5dHfKPiDrdIBZPzTric_LvqJCgZLemUmzKkELkUl9BCBtFLth61qhAg", + null, + null, + null, + "PWhCgGM_SQpEf3NTZIdEIHecaFEd9MHptZqUyM4l7J4oR5aMrxkPYLRQ89msWfRtCF6fSvYVLZhTR-FjcIJqBg", + "lLnEWWKxoToD-URLN7PDWFBQTyC1waS9KHBAskgdXdn_bZIyr3XYoqxIbTcHW6f0m6qozQGkZTXQukGbi08fCA" + ] + } + }, + "data_hash": "Tr4Z99mUiaHGVuzW5eyZ73bKqEXUcYPV1C5RkUVCP2U", + "timestamp": 1711515120, + "base_fee": 8, + "txs_hash": "wDUDiSjWumCmyEu_Fz0H8zqs3jSlpCMxN2NnST7fieM", + "state_hash": "rU3ilPOG1Lr-4fYtGTHpSXsMvZM8v0l5JX3PgK-wauc", + "receipts_hash": "uXRT1micHUt7orVPifaFg5BvOQJLd9K4mNAFo0zW0x4", + "proposer": "TY0vjFcDm681NupNBVSU9DKNunP6JlwNNhc7lDJ2uU0" + }, + "transactions": [ + { + "commands": [ + { + "Transfer": { + "recipient": "kxrCl32WEzr7gr4Awb3jAMQtoh5zY8grabqlu-x42jY", + "amount": 2000000000 + } + } + ], + "signer": "qPReY5x_DPKAx1v30UrU1x1RI61Wd2OxeZo2eSWcjMU", + "priority_fee_per_gas": 0, + "gas_limit": 67500000, + "max_base_fee_per_gas": 8, + "nonce": 428, + "hash": "dOrjtT7o5Y97mlLJFaCvdNUq6UgVQItVYGXHPoDw5n4", + "signature": "RLM3k5VDDzBqkQ7ios4TMP9LwL50n8hNQ7OjH-wcTE0Ts6F3uWDaA5J52sCyYr3aGGGElXKiIatqH15qVwMUAA" + } + ], + "receipts": [ + [ + { + "status_code": "Success", + "gas_used": 32820, + "return_values": "", + "logs": [] + } + ] + ] +} +``` + +## How Block Works + +Blocks are produced by validator [Nodes](nodes.md). To produce a block, the node executes transactions and creates receipts as a result of execution. The transactions and receipts become the content of a block, and the node will then compute the metadata such as `block height`, `timestamp`, hashes, etc. in the block header. + +When a block is created by a node, the validator nodes will validate it and then agree on the block content through a [consensus mechanism](consensus_mechanism.md). An agreed block is said to be **committed**. If the block is invalid, it will not be part of the blockchain. Nodes will keep producing new blocks, and this process repeats within a time interval (i.e. block time). As a result, the blockchain grows with more and more blocks. + +## Epoch Block + +**Epoch Block** is a special block created by executing a transaction with [Next Epoch Command](transactions.md#protocol-commands). This special block signifies the last block in an **Epoch**. + +Epoch is a protocol-defined period for measuring the performance of operators on the blockchain network. + +The primary purpose of epochs in a blockchain is to facilitate various network functionalities and maintain consensus among network participants by defining a common reference point, which could be utilized to validate transactions. During one epoch, there would be block creation and block addition to the blockchain. + +In the ParallelChain Mainnet ecosystem, an `epoch` is defined by a predetermined block height or the number of blocks added to the blockchain, which is 8640. When a specific block height is reached or another 8640 blocks are added to the blockchain, the blockchain network would move from the current epoch to the next. The epoch transition could trigger critical events: + +- Reward stakes in Current Validator Set + - *Increase deposits* of owner and operator + - *Update stakes* if auto-stake-rewards is enabled + +- Replacing Previous Validator Set with Current Validator Set +- Replacing Current Validator Set with Next Validator Set +- Returning Next Validator Set for the next leader selection + +Epoch transition ensures that only one set of validators is active on the blockchain network at any given time, which makes the information on the blockchain tamper-proof. + diff --git a/docs/concepts/consensus.md b/docs/fundamentals/consensus_mechanism.md similarity index 62% rename from docs/concepts/consensus.md rename to docs/fundamentals/consensus_mechanism.md index a537b549..ca7574f2 100644 --- a/docs/concepts/consensus.md +++ b/docs/fundamentals/consensus_mechanism.md @@ -4,56 +4,21 @@ tags: - hotstuff.rs --- -# HotStuff-rs -HotStuff-rs is a Rust Programming Language implementation of the HotStuff consensus protocol. It offers: +# Consensus Mechanism -1. Guaranteed Safety and Liveness in the face of up to 1/3rd of Voting Power being Byzantine at any given moment, -2. A small API (`Executor`) for plugging in state machine-based applications like blockchains, and -3. Well-documented, 'obviously correct' source code, designed for easy analysis and extension. +A blockchain consensus mechanism is a protocol that enables multiple participants in a blockchain network to agree on the current state of the blockchain and validate transactions without a centralised authority. By doing so, consensus mechanisms ensure the security of the blockchain and validate the authenticity of transactions. -A Rust Programming Language library for Byzantine Fault Tolerant state machine replication, intended for production -systems. - -HotStuff-rs implements a variant of the HotStuff consensus protocol, but with extensions like block-sync and dynamic -validator sets that make this library suited for real-world use cases (and not just research systems). Some desirable -properties that HotStuff-rs has are: - -1. **Provable Safety** in the face of up to 1/3rd of voting power being Byzantine at any given moment. -2. **Optimal Performance**: consensus in (amortized) 1 round trip time. -3. **Simplicity**: A small API (App) for plugging in arbitrary stateful applications. -4. **Modularity**: pluggable networking, state persistence, and view-synchronization mechanism. -5. **Dynamic Validator Sets** that can update without any downtime based on state updates: a must for PoS blockchain - applications. -6. **Batteries included**: comes with a block-sync protocol and (coming soon) default implementations for networking, - state, and pacemaker: you write the app, and we handle the replication. - -## Terminology ---- - -- **App**: user code which implements the App trait. This can be any business logic that can be expressed - as a deterministic state machine, i.e., a pure function of kind: `(Blockchain, App State, Validator Set, Block) -> - (Next Blockchain, Next App State, Next Validator Set)`. -- **Replica**: a public-key-identified process that hosts an implementation of the HotStuff-rs protocol, e.g., this - library. There are two kinds of replicas: validators, and listeners. -- **Blockchain**: a growing sequence of **Blocks**, which can be thought of as instructions to update a replica's App - State and Validator Set. -- **App State**: a key-value store that applications can use to store anything; two replicas with the same Blockchain - are guaranteed to have the same app state. -- **Validator Set**: the set of replicas who can vote in a consensus decision. -- **Progress protocol**: the protocol replicas use to create new blocks through consensus and grow the blockchain. -- **Sync protocol**: the protocol new or previously offline replicas use to quickly catch up to the head of the - blockchain. +ParallelChain Mainnet uses a variant of consensus procotol called **HotStuff** to validate transactions on the network. ## The HotStuff Consensus Protocol ---- HotStuff works by building a 'BlockTree': a directed acyclic graph of Blocks. Block is a structure with a `data` field which applications are free to populate with arbitrary byte-arrays. In consensus algorithm literature, we typically talk of consensus algorithms as maintaining state machines that change their internal states in response to commands, hence the choice of terminology. HotStuff guarantees that committed Blocks are *immutable*. That is, they can never be *un*-committed as long as at least a supermajority of voting power faithfully executes the protocol. This guarantee enables applications to make hard-to-reverse actions with confidence. -![A graphic depicting a Tree (DAG) of Blocks. Blocks are coloured depending on how many confirmations they have.](/docs/img/concept_consensus_blocktree%20_diagram.png) +![A graphic depicting a Tree (DAG) of Blocks. Blocks are coloured depending on how many confirmations they have.](../img/BlockTree%20Structure%20Diagram.png) -A Block becomes *committed* the instant its third confirmation is written into the BlockTree. Confirmation for a Block `A` is another Block `B` such that there is a path between `B` to `A`. +A Block becomes **committed** the instant its third confirmation is written into the BlockTree. Confirmation for a Block `A` is another Block `B` such that there is a path between `B` to `A`. The choice of third confirmation to define commitment--as opposed to first or second--is not arbitrary. HotStuff's safety and liveness properties hinge upon this condition. You can read this [paper](https://github.com/parallelchain-io/hotstuff_rs/blob/master/readme_assets/HotStuff%20paper.pdf) to learn more about it. To summarize: @@ -62,9 +27,26 @@ The choice of third confirmation to define commitment--as opposed to first or se HotStuff is the first consensus algorithm with a simple leader-replacement algorithm that does not have a 'wait-for-N seconds' step and thus can make progress as fast as network latency allows. +## Hotstuff-rs -## Getting Started ---- +[HotStuff-rs](https://github.com/parallelchain-io/hotstuff_rs) is a Rust Programming Language implementation of the HotStuff consensus protocol. It offers: + +1. Guaranteed Safety and Liveness in the face of up to 1/3rd of Voting Power being Byzantine at any given moment, +2. A small API (`Executor`) for plugging in state machine-based applications like blockchains, and +3. Well-documented, 'obviously correct' source code, designed for easy analysis and extension. + +A Rust Programming Language library for Byzantine Fault Tolerant state machine replication, intended for production +systems. + +HotStuff-rs implements a variant of the HotStuff consensus protocol, but with extensions like block-sync and dynamic +validator sets that make this library suited for real-world use cases (and not just research systems). Some desirable +properties that HotStuff-rs has are: -If you're trying to learn about HotStuff-rs by reading the source code or Cargo docs, we recommend starting from -the [replica](https://github.com/parallelchain-io/hotstuff_rs/blob/master/src/replica.rs) module. This is the entry point of user code into this library. +1. **Provable Safety** in the face of up to 1/3rd of voting power being Byzantine at any given moment. +2. **Optimal Performance**: consensus in (amortized) 1 round trip time. +3. **Simplicity**: A small API (App) for plugging in arbitrary stateful applications. +4. **Modularity**: pluggable networking, state persistence, and view-synchronization mechanism. +5. **Dynamic Validator Sets** that can update without any downtime based on state updates: a must for PoS blockchain + applications. +6. **Batteries included**: comes with a block-sync protocol and (coming soon) default implementations for networking, + state, and pacemaker: you write the app, and we handle the replication. diff --git a/docs/concepts/gas.md b/docs/fundamentals/gas.md similarity index 78% rename from docs/concepts/gas.md rename to docs/fundamentals/gas.md index 211f496b..98af3bdd 100644 --- a/docs/concepts/gas.md +++ b/docs/fundamentals/gas.md @@ -1,26 +1,25 @@ --- tags: - gas + - base fee formula + - gas estimation --- -To use resources on ParallelChain Mainnet, transactions impost some cost for storage and execution. ParallelChain Mainnet implements gas units in terms of XPLL (i.e., 1 Gray equals 1 gas). This means the actual cost of gas used during transactions is dynamically balanced when the price of the token increases or decreases due to economic factors. Please see the section [Base Fee Formula](https://github.com/parallelchain-io/parallelchain-protocol/blob/master/Blockchain.md#Base-fee-formula) in ParallelChain Mainnet Protocol for details. - # Gas **Gas** is a representation of the cost incurred by resources per transaction in the ParallelChain Mainnet ecosystem. Every transaction is assigned a cost through gas metering. There are different categories of gas cost in the ParallelChain Mainnet ecosystem: -- WASM opcode execution inside a contract call +- WASM opcode execution inside a contract [call](transactions.md#account-commands) - Reading and writing WASM memory from host functions inside a contract call - Transaction-related data storage -- World state storage and access +- [World state](nodes.md#world-state) storage and access - Cryptographic operations Details about gas can be found in [ParallelChain Mainnet Protocol](https://github.com/parallelchain-io/parallelchain-protocol/blob/master/Gas.md). ## How are Gas Fees Calculated? ---- **Gas Fee** here refers to the amount that is paid with the account's balance for the gas consumed in transaction execution. It can be generalized by the following equation: @@ -29,11 +28,10 @@ Gas Fee = Gas Consumption x (Base Fee Per Gas + Priority Fee Per Gas) ``` - `Gas Consumption` is the gas unit consumed during the transaction execution. -- `Base Fee Per Gas` is the dynamically adjusted value that depends on the traffic of the network at the time of transaction execution. +- `Base Fee Per Gas` is the dynamically adjusted value that depends on the traffic of the network at the time of transaction execution. Please see the section [Base Fee Formula](https://github.com/parallelchain-io/parallelchain-protocol/blob/master/Blockchain.md#Base-fee-formula) in ParallelChain Mainnet Protocol for details. - `Priority Fee Per Gas` is the amount specified in the transaction by the signer, which is transferred to block producer, on per-gas basis. ## Gas Estimation ---- Transaction can fail for setting the Gas limit too low. There is no absolute answer to what gas limit should be specified. In general, the gas limit must be **greater than Transaction Inclusion Cost** and **smaller than Block Gas Limit (500000000)**. diff --git a/docs/fundamentals/networks.md b/docs/fundamentals/networks.md new file mode 100644 index 00000000..9d6a16db --- /dev/null +++ b/docs/fundamentals/networks.md @@ -0,0 +1,68 @@ +--- +tags: + - ParallelChain Mainnet + - ParallelChain Testnet + - Testnet 4 + - Explorer + - Xperience Broswer Extension +--- + +# Networks + + +## ParallelChain Mainnet + +**ParallelChain Mainnet** is a high-performance blockchain designed for enterprise-level use cases. It provides a platform for developers to build decentralised applications (dApps) with its efficient smart contract execution engine. + +It is designed to balance high performance and genuine decentralization. It is protected by the a Byzantine Fault Tolerant (BFT) consensus protocol, which adopts a sophisticated class-based node system to ensure fast and accountable consensus. + +For more information about the consensus protocol, please read the section [Consensus Mechanism](./consensus_mechanism.md). + +## ParallelChain Testnet + +To ensure the new features in ParallelChain Mainnet have what it takes to survive decentralised deployment, they must first be battle-tested. This is where ParallelChain Testnet comes into play by allowing developers, or simply users, to develop and run smart contracts or transactions on ParallelChain and experiment with the blockchain, at no cost. + +Both Mainnet and Testnet are accessible through [Explorer](#parallelchain-explorer). But only onTestnet, a service called [Faucet Service](#faucet-service) provides free tokens to users. + +## Accessing the Networks + +There are two client tools for accessing Mainnet and Testnet. + +- **ParallelChain Explorer**: Web-based tool with a crypto wallet for interacting with Mainnet and Testnet. +- **Xperience Browser Extension**: Browser Extension of the ParallelChain Explorer Wallet. + +### ParallelChain Explorer + +**ParallelChain Explorer** is a web-based tool integrated with the ParallelChain Mainnet ecosystem, which allows users to visualize and interact with the Mainnet and Testnet. By using the explorer, users can search for real-time and historical information about the blockchain. + +What you can do: + +- **Search and Navigation**: Find specific blocks, transactions, and accounts easily by using block hash, transaction hash, and account address. +- **Block Details**: Explore details of specific blocks, including block height, timestamp, transaction information, etc. +- **Transaction Details**: Explore details of specific transactions, including signer/recipient account information, timestamp, consumed gas, etc. +- **Account Details**: Explore details of specific accounts, including nonce, contract count, transaction history, etc. +- **Staking Details**: Explore details of staking information for each pool, including operator, pool power, and commission rate, etc. +- **Network Statistics**: Gain insights into network-wide statistics, including gas consumption, block production time, reward issuance, etc. +- **Wallet**: Seamlessly create a ParallelChain wallet account and make transactions. + +**Check out our [ParallelChain Explorer](https://explorer.parallelchain.io/explorer)!** + +### Xperience Browser Extension + +**Xperience Browser Extension** is a browser extension that allows you to integrate your [dApp](../for_developers/xperience_browser_provider_apis/introduction.md) with ParallelChain Wallet. + +This enables your dapp to interact with your dapp users' XPLL accounts, to: + +- Send [transactions](transactions.md) + - [Stake](staking.md) XPLL +- Trigger confirmation for [smart contract](../for_developers/smart_contracts/introduction.md) calls + +**The browser extension is available on the [Chrome Web Store](https://chromewebstore.google.com/detail/xperience-browser-extensi/gpfllmjckejjhmmdmgbgmclmhopekjpf) now.** + +### Faucet Service + +The **Faucet Service** of our Testnet issues free testing tokens to users to test the blockchain network on Testnet. + +To obtain testing tokens, create your Testnet account first. Account can be easily created by using Web Wallet in **ParallelChain Explorer** (See [here](../for_users/web_wallet/create_account.md)), or **Xperience Browser Extension** (See [here](../for_users/xperience_browser_extension/create_account.md)). + +The created account should have an empty balance initially. **You can request free tokens from [Faucet Service](https://faucet.parallelchain.io).** \ No newline at end of file diff --git a/docs/fundamentals/nodes.md b/docs/fundamentals/nodes.md new file mode 100644 index 00000000..c131c747 --- /dev/null +++ b/docs/fundamentals/nodes.md @@ -0,0 +1,75 @@ +--- +tags: + - nodes + - runtime + - world state + - p2p + - mempool +--- + +# Nodes + +ParallelChain Lab currently operates 10 [validator](staking.md#validator) nodes. They are all in the same node type - Fullnode. + +Fullnode is node software that stores and maintains a full copy of the blockchain. The specification can be found in the [ParallelChain Mainnet Protocol](https://github.com/parallelchain-io/parallelchain-protocol). + +Fullnode starts with exchanging messages with other nodes in a [P2P Network](#p2p-network). Through a [Consensus Machanism](consensus_mechanism.md), it produces and validates blocks by executing transactions. The execution takes place in a component call [Runtime](#runtime) which transits the state of the blockchain. The resulting state is then stored in a data structure called [World State](#world-state). + +Fullnode also runs a HTTP server to serve RPC requests. Transactions can be submitted in the RPC request. Fullnode buffers those transactions in the [Mempool](#mempool), and then waits for executing them. + +## Runtime + +The [Runtime](https://github.com/parallelchain-io/pchain-runtime) is the component in the ParallelChain protocol which executes transactions. + +Runtime can be considered as a **Transition Function** that deterministically executes transactions. Execution of the transition function proceeds through three phases: Pre-Charge, Commands, and Charge. The sequence flow of the pre-charge and charge phases are common to all transactions, while the sequence flow of the commands phase varies according to the composition of a transaction's vector of [commands](transactions.md#commands). + +![Runtime Sequence Flow](../img/Runtime%20Phases.png) + +- **Pre-Charge Phase**: makes simple checks to ensure that the transaction can be included in the block. +- **Commands Phase**: executes the sequence of commands included in the transaction. +- **Charge Phase**: performs settlement of balances for charging the total gas used in previous phases. + + +## World State + +The [World State](https://github.com/parallelchain-io/pchain-world-state) is a set of key-value tuples representing the state of every account, stored inside a set of Merkle Patricia Trie (MPT) data structures. Key-value tuples can be inserted to a MPT. The MPT in return computes a hash value called **state hash** that is deterministic to all the data that it has. + +ParallelChain Protocol uses two kinds of MPT: + +- **Accounts Trie**: The singular Accounts Trie. It stores the fields such as **Nonce** and **Balance** of all the [accounts](accounts.md) in the blockchain. +- **Storage Tries**: Unlike the `Accounts Trie`, there can be many `Storage Tries`. It stores key-value tuples associated with a specific account. These accounts are generally the [Contract Accounts](accounts.md) which inserts the key-value tuples according to its [Contract](../for_developers/smart_contracts/introduction.md) implementation. It is also used by a special account called [Network Account](accounts.md#network-account). + + + +## P2P Network + +[ParallelChain Network](https://github.com/parallelchain-io/pchain-network) is a peer-to-peer networking (P2P) component for ParallelChain replicas. It is built using [libp2p](https://docs.libp2p.io/concepts/introduction/overview/) which provides functionalities of messaging and peer discovery. + +- **Messaging**: P2P enables replicas to send messages to each other to replicate the state machine, maintain a pool of pending transactions, as well as notify each other of dropped transactions. +- **Peer Discovery**: in order for messages to eventually be received by all of their intended recipients, the P2P network needs to be connected. However, forming a connected network topology is challenging, because the number of replicas for any particular ParallelChain blockchain is unbounded and can far exceed the number of transport-layer connections that a computer can feasibly maintain. Starting from a small set of "boot nodes", P2P's peer discovery forms and maintains a connected network topology without requiring every replica to be aware of every other replica. + +## Mempool + +[Mempool](https://github.com/parallelchain-io/pchain-mempool) is a component of the blockchain network that keeps transactions that have not yet been added to a block. It can refer to two things: + +- The mempool of validating nodes and fullnodes, which accepts pending transactions for future inclusion in a block. (Only validating nodes can create new blocks.) +- The set of not-yet-confirmed transactions that are stored in the individual mempools of nodes in the network. This set can vary between nodes due to network delays and partitions. + +### How does Mempool Work? + +When a transaction is submitted to the blockchain network, it is first sent to the mempool where it waits to be executed. The mempool acts like a queue, storing the pending transactions and arranging them to be executed by block producers. Transactions are prioritized based on how much the sender is willing to pay for network resources, which is indicated in a field called `Max Base Fee Per Gas` within the transaction. The higher the fee, the higher the priority of the transaction. + +### Base Fee Per Gas in ParallelChain Mainnet + +In ParallelChain Mainnet, the `base fee per gas` is calculated according to the [Base fee formula](https://github.com/parallelchain-io/parallelchain-protocol/blob/master/Blockchain.md#base-fee-formula). This is nearly identical to Ethereum's EIP-1559 and shares the same purpose: *adjust the cost of a transaction based on how busy the network is*. + +!!! Note + Validator nodes in ParallelChain Mainnet provided at the initial Launch do not take `priority fee` into the ranking calculation. + +### Max Base Fee Per Gas and EIP-1559 in Ethereum + +The priority ranking method based on the `Max Base Fee Per Gas` is a crucial component of the EIP-1559 model for transaction processing in Ethereum. + +In the EIP-1559 model, each transaction specifies two fees: the `base fee` and the `priority fee`. The `base fee` is dynamically determined by the network based on the current demand for block space and adjusts itself to keep block utilization at a target level. The `priority fee` is the amount that the user is willing to pay in addition to the base fee to prioritize their transaction. + +When a transaction is submitted to the network, it is placed in the mempool, and the `priority fee` value of the transaction is used to rank it. Transactions with higher priority fees are placed higher in the mempool, making them more likely to be included in the next block. However, unlike the traditional method of simply sorting transactions by the fee amount, EIP-1559 allows for more efficient use of block space by dynamically adjusting the `base fee`, which incentivizes users to pay only what they need to get their transaction included. This helps to prevent congestion and ensures that transactions are processed in an efficient and timely manner. \ No newline at end of file diff --git a/docs/fundamentals/staking.md b/docs/fundamentals/staking.md new file mode 100644 index 00000000..bcf690db --- /dev/null +++ b/docs/fundamentals/staking.md @@ -0,0 +1,146 @@ +--- +tags: + - Staking +--- + +# Staking + +**Staking** is a process of holding a cryptocurrency or token as a way to support the operations of a blockchain network. It involves locking up a certain amount of tokens for a period of time to participate in the process of validating transactions, adding new blocks to the chain, and maintaining the security and integrity of the network. + +In return for staking, users may receive rewards in the form of additional tokens issued by the network. In Parallelchain Mainnet Proof-of-Stake (PoS) [consensus algorithm](consensus_mechanism.md), the voting power of a validator depends on the its stake amount, rather than the computational power they can provide, as in Proof-of-Work (PoW) algorithms. + +Elements inside a staking process include: + +- **Pool**: represents an operator and its delegators who can combine their stakes as a whole. The stake amount reflects the voting power of the pool operator. The stake amount also determines the rewards earned from an [epoch](blocks.md#epoch-block) if the pool operator is a validator. +- **Stake**: the amount that a participant locks up as collateral to be contributed to a pool. +- **Deposit**: the locked balance used to determine the amount of stake. + +## How Staking Works + +In this staking process, there are two main actors: **pool operators** and **owner**. A pool operator can create, update, and destroy pools. An owner can deposit their [XPLL](../introduction.md#what-is-xpll) into a pool, top-up their deposit, withdraw their deposit, and set the amount they want to stake in the pool. However, they cannot stake more than the amount they have deposited. + +If a pool has enough power (determined by the amount of stakes), it can join as a [validator](#validator) in the next epoch. In each [epoch](blocks.md#epoch-block), block rewards are distributed to owners' deposits, and the validator set is updated according to the validators' power, which will determine the validators in consensus for the current epoch. + +An owner can withdraw their deposit from a pool, but the amount they withdraw cannot make their deposit less than the maximum stake amount in the current and previous epoch. + +## Validator + +In a delegated proof-of-stake (DPoS) blockchain network, a validator is a participant in the network who is responsible for validating [transactions](transactions.md) and creating new [blocks](blocks.md). To validate transactions, validators must check that the transaction is valid, for example, the sender has enough balance to complete the transaction. + +Validators are selected based on the amount of tokens they hold and their stake in the network. This stake serves as collateral and incentivizes validators to act honestly and maintain the security of the network. The more stakes they have, the greater their chances of being selected to be one of the validators in the next epoch. + +## Delegator + +In a delegated proof-of-stake (DPoS) blockchain network, a delegator is a participant who delegates their tokens to a staking pool. Delegators do not validate transactions or create new blocks themselves, but they can participate in the network's consensus process by proxy through a pool. + +Delegating tokens to a pool allows the delegator to earn rewards, for doing so, without having to run [nodes](nodes.md) themselves. Delegators typically choose a pool based on their reputation, track record, and the commission fee they charge. The exact amount of rewards earned may depend on various factors, such as the number of tokens staked, the length of time the tokens are staked for, and the network's overall performance. + +See also: + +- [Staking XPLL by Web Wallet](../for_users/web_wallet/staking.md) +- [Staking XPLL by Xperience Browser Extension](../for_users/xperience_browser_extension/staking.md) + +## Rewards + +Rewards serve as an incentive for validators who actively contribute to the creation of new blocks within the blockchain network. + +In DPoS blockchains, validators are selected to validate transactions and generate new blocks based on the quantity of XPLL they have staked within the network. As a reward for their contributions, validators receive two kinds of rewards: +1. **Priority Fees**: an amount of *existing* XPLL that transaction signers *transfer* to block proposers to reward them for including their transaction. +2. **Block Rewards**: an amount of *new* XPLL created ("issued") at the end of every epoch according to a function of the total amount of XPLL staked. + +Block rewards play a crucial role in blockchain networks by serving multiple purposes. They incentivize miners and validators' participation in the network's consensus process, thereby upholding the security and integrity of the network. Additionally, block rewards facilitate the introduction of new XPLL into circulation, ensuring the long-term sustainability of the network. + +This document provides a rough overview of the calculation of block rewards. The exact formulas that Fullnodes use to calculate rewards are specified near the end of the ["next epoch" section](https://github.com/parallelchain-io/parallelchain-protocol/blob/master/Runtime.md#next-epoch) of the Runtime chapter of the ParallelChain Protocol specification. + + +### Reward Rate + +The block reward amount gradually decreases as additional blocks are incorporated into the blockchain over time. This process, which is known as the **block reward reduction**, is a characteristic found in various blockchain networks, such as Bitcoin (where it is popularly called "halving"). By implementing the block reward reduction, the supply of cryptocurrency is regulated, effectively curbing inflationary pressures. + +Block rewards in ParallelChain Mainnet gradually reduce according to the following formula: + +- First year: 8% per annum +- Reduce 15% per annum +- After 10 year (3650 days): keep at 1.5% per annum + +The **total amount of rewards (issuance)** introduced to the network is calculated as follows: + +$$ +\text{Total amount of stake} \times \text{Issuance rate} +$$ + +For example, if the *total amount of stake* of a validator is `100,000 XPLL` currently, and the *issuance rate* is `0.001`, then the *total amount of XPLL to be issued* to that validator in the next epoch will be `100,000 * 0.001 = 100 XPLL`. + + +The **issuance rate** is calculated as follows: + +$$ +\text{Issuance rate at n-th epoch} = 0.0835 \times \frac{0.85^{\frac{n}{365}}}{365} +$$ + +after 10 years (or equivalently, after $n >= 3650$), the issuance rate will become a constant: + +$$ +\text{Issuance rate per epoch after 10 years} = \frac{0.0150}{365} +$$ + +### Delegator Reward + +Delegators receive a portion of the newly issued rewards based on the amount they have staked with the validator. However, it's important to note that the delegator rewards will be reduced by a commission fee, which is determined by the validator and can be adjusted in their settings. + +Let's assume that in the upcoming epoch, the validator `V` will receive a *total reward* of `100 XPLL`. `V` has set a *commission fee* of `1%`. Additionally, one of its delegators, `D`, has contributed `10%` of the total staked amount to `V`. Then in the next epoch, `D` will be rewarded: + +$$ +\text{Reward} = 100 \text{ XPLL} \times 10\% \times (100\% - 1\%) = 9.99 \text{ XPLL} +$$ + +## FAQ + +#### Why am I not able to stake XPLL tokens? +You will need to retain a certain amount of XPLL in your account balance to pay for transaction fees. Ensure that you have reserved a small amount of XPLL tokens to pay for the gas fee of your deposit, stake, or unstake XPLL tokens. + +--- + +#### How do I know which validator to stake with? +The validators securing the ParallelChain Mainnet are trusted participants who are required to stake a significant number of XPLL. You may check the yield and commission fee of each validator by looking into their account details on [ParallelChain Explorer](./networks.md#parallelchain-explorer). + +--- + +#### How long is the unstaking period? +The staking duration is measured by epochs. If you stake and unstake within the same epoch, the waiting time is considerably shorter. If the staking and unstaking are not within the same epoch, you will need to wait for at least another two epochs before unstaking. + +--- + +#### How long is an Epoch? +One full epoch lasts approximately one day before it enters the next epoch. The epoch itself is a protocol-defined period for measuring the performance of operators on the network. + +--- + +#### How do I withdraw my staking rewards? +You can withdraw the rewards you have earned from staking by unstaking them to your Token Deposit. Additionally, you may toggle the `AUTO STAKE REWARDS` to avoid the process of unstaking your rewards. From there, you can then withdraw the amount to your wallet. Please refer to the section on Unstaking Your XPLL and Withdrawing Your Staking Rewards for the required steps. + +--- + +#### Can I move my staked XPLL to another validator? +Yes, you can. You will need to unstake your XPLL tokens, withdraw them to the Token Deposit, and then back to your wallet. You can then transfer those tokens to a Token Deposit with another validator before staking your tokens with them. Please refer to the sections above to move your XPLL to another validator. + +--- + +#### Can I stake to more than one node? +Yes, you can. To do so, you will need to create a Token Deposit on the validator node you wish to stake with. Once done, you can stake tokens with the validator node. To stake XPLL with more than one validator, repeat the same process of creating a Token Deposit with the other validator node, deposit tokens from your account to the Token Deposit, and you can stake with the second validator. Repeat this process with other validator nodes you wish to stake with. + +--- + +#### The status is still showing `PENDING`. Why is my transaction not confirmed yet? +Transactions are prioritized by the amount of Priority Fee per Gas paid, and lower priority transactions may need more time to be confirmed. You may choose to pay a higher Priority Fee during peak periods for a faster transaction, or you may check your wallet address on the [ParallelChain Explorer](networks.md#parallelchain-explorer) to monitor its transaction status. + +--- + +#### Are the rewards automatically staked? +Depends on the setting of your stake. Your staking rewards will not be automatically staked unless the **AUTO STAKE REWARDS** field is toggled on. You can toggle it on or off anytime you want. + +--- + +#### Is there any locking period? +There is no locking period to stake your XPLL tokens, but the staking duration is measured by epochs. If you stake and unstake within the same epoch, the waiting time is considerably shorter. If the staking and unstaking are not within the same epoch, you will need to wait for at least another two epochs before unstaking. + diff --git a/docs/concepts/transaction.md b/docs/fundamentals/transactions.md similarity index 53% rename from docs/concepts/transaction.md rename to docs/fundamentals/transactions.md index 39f59f27..829b6b67 100644 --- a/docs/concepts/transaction.md +++ b/docs/fundamentals/transactions.md @@ -7,17 +7,76 @@ tags: - Log --- -# Transaction, Command and Receipt +# Transactions -## Command ---- +A **transaction** is a digitally signed instruction that tells the Mainnet state machine to execute a sequence of commands. + +A transaction has the following fields: -A command is a useful operation that Parallelchain allows the user to do. A sequence of commands can be inserted into a transaction to be carried out. There are currently 13 different kinds of commands, each corresponding to a variant of the command enum type. These are further divided into three categories: **account commands**, **staking commands**, and **protocol commands**. Most commands take inputs, which are part of the command type as the fields of its corresponding variant. +- `Signer`: the public address of the external-owned account that signed this transaction. +- `Nonce`: the number of transactions signed by the signer that has been included on the blockchain before this transaction. This ensures that all of the signer’s transactions are included in the blockchain in an expected order and prevents the same transaction from being included in multiple blocks. +- `Commands`: a sequence of [Commands](#commands) to be executed in a transaction. +- `Gas Limit`: the maximum number of [gas](gas.md) units that should be used in executing this transaction. +- `Max Base Fee per Gas`: the maximum number of grays that the signer is willing to burn for a gas unit used in this transaction. +- `Priority Fee per Gas`: the number of grays that the signer is willing to pay the block proposer for including this transaction in a block. +- `Signature`: the signature formed by signing over content in this transaction using the signer’s private key. +- `Hash`: the cryptographic hash of the signature. +Example of a transaction queried by [ParallelChain Client CLI](../for_users/pchain_client_cli/querying_blockchain.md): + +```json +{ + "transaction": { + "commands": [ + { + "Transfer": { + "recipient": "kxrCl32WEzr7gr4Awb3jAMQtoh5zY8grabqlu-x42jY", + "amount": 2000000000 + } + } + ], + "signer": "qPReY5x_DPKAx1v30UrU1x1RI61Wd2OxeZo2eSWcjMU", + "priority_fee_per_gas": 0, + "gas_limit": 67500000, + "max_base_fee_per_gas": 8, + "nonce": 428, + "hash": "dOrjtT7o5Y97mlLJFaCvdNUq6UgVQItVYGXHPoDw5n4", + "signature": "RLM3k5VDDzBqkQ7ios4TMP9LwL50n8hNQ7OjH-wcTE0Ts6F3uWDaA5J52sCyYr3aGGGElXKiIatqH15qVwMUAA" + }, + "receipt": [ + { + "status_code": "Success", + "gas_used": 32820, + "return_values": "", + "logs": [] + } + ] +} +``` + +## How Transaction Works + +A transaction is created by an [EOA](accounts.md#accounts) who sets the fields such as `nonce`, `gas_limit` of a transaction. The field `signer` is the address (public key) of the account, and the signature is created by signing the the content of the transaction with the private key of the account. Finally, the field `hash` is computed from the signature field. + +EOA submits transaction to the blockchain [network](networks.md). The [nodes](nodes.md) will then execute the transaction in order to produce a block. The transaction execution mutates the [state](nodes.md#world-state) of blockchain. For example, if the transaction includes a [Transfer Command](#account-commands), balances of the signer and recipient can be updated upon a successful execution. + +In the end, the transaction becomes part of a [block](blocks.md) if it is executed and validated successfully, Otherwise, the transaction will be dropped by the network. + +See also: + +- [Create Transaction by CLI](../for_users/pchain_client_cli/creating_transaction.md) +- [Transferring Tokens by Web Wallet](../for_users/web_wallet/transfer_tokens.md) +- [Transferring Tokens by Xperience Browser Extension](../for_users/xperience_browser_extension/transfer_tokens.md) + +## Commands + +A command is a useful operation that Parallelchain allows the user to do. A sequence of commands can be inserted into a transaction to be carried out. There are currently 13 different kinds of commands, each corresponding to a variant of the command enum type. These are further divided into three categories: [account commands](#account-commands), [staking commands](#staking-commands), and [protocol commands](#protocol-commands). Most commands take inputs, which are part of the command type as the fields of its corresponding variant. + +In the below subsections, the input types are represented in [Rust programming language](https://www.rust-lang.org). For example, `PublicAddress` is 32-byte data. `Vec` is vector of unsigned 8-bit integers (bytes). ### Account commands -#### Transfer +**Account commands** are the commands specific to mutate state of [Accounts](accounts.md) in the blockchain. |**Name**|**Input**|**Description**| |---|---|---| @@ -27,6 +86,7 @@ A command is a useful operation that Parallelchain allows the user to do. A sequ ### Staking commands +**Staking commands** are mainly associated with the [staking](staking.md) process in ParallelChain Mainnet ecosystem. |**Name**|**Input**|**Description**| |---|---|---| @@ -40,36 +100,20 @@ A command is a useful operation that Parallelchain allows the user to do. A sequ |Stake|
  • Operator (`PublicAddress`)
  • Max amount (`u64`)
  • |Try to stake a given amount from a deposit.| |Unstake|
  • Operator (`PublicAddress`)
  • Max amount (`u64`)
  • |Try to reduce a deposit's stake by a given amount.| -> **Notes**: - -> *The actual amount of tokens that could be withdrawn, staked, or unstaked by the final three kinds of commands depends on timing and order, factors that users do not have precise control over. For example, the number of tokens that can be withdrawn from a deposit can change significantly between epochs as the deposit's [bonded balance](https://github.com/parallelchain-io/parallelchain-protocol/blob/master/Blockchain.md#delegated-proof-of-stake) decreases, or increases.* +!!! Note + *The actual amount of tokens that could be withdrawn, staked, or unstaked by the final three kinds of commands depends on timing and order, factors that users do not have precise control over. For example, the number of tokens that can be withdrawn from a deposit can change significantly between epochs as the deposit's [bonded balance](https://github.com/parallelchain-io/parallelchain-protocol/blob/master/Blockchain.md#delegated-proof-of-stake) decreases, or increases.* -> *Therefore, these commands accept as input a "max amount" instead of a precise amount. These commands try to withdraw, stake, or unstake as close to the maximum amount as possible, and inform the precise amount in its return value.* + *Therefore, these commands accept as input a "max amount" instead of a precise amount. These commands try to withdraw, stake, or unstake as close to the maximum amount as possible, and inform the precise amount in its return value.* ### Protocol commands -|**Name**|**Input**|**Description**| -|---|---|---| -|Next epoch|None|Reward the current epoch's validators, and confirm the next epoch's validator set.| - -## Transaction ---- - -A **transaction** is a digitally signed instruction that tells the Mainnet state machine to execute a sequence of commands. -A transaction has the following fields: - -- `Signer`: the public address of the external-owned account that signed this transaction. -- `Nonce`: the number of transactions signed by the signer that has been included on the blockchain before this transaction. This ensures that all of the signer’s transactions are included in the blockchain in an expected order and prevents the same transaction from being included in multiple blocks. -- `Commands`: a sequence of [Commands](transaction.md#command) to be executed in a transaction. -- `Gas Limit`: the maximum number of gas units that should be used in executing this transaction. -- `Max Base Fee per Gas`: the maximum number of grays that the signer is willing to burn for a gas unit used in this transaction. -- `Priority Fee per Gas`: the number of grays that the signer is willing to pay the block proposer for including this transaction in a block. -- `Signature`: the signature formed by signing over content in this transaction using the signer’s private key. -- `Hash`: the cryptographic hash of the signature. +**Protocol commands** are the commands which mutates the state of the whole network (i.e. mutates the state of [Network Account](accounts.md#network-account) in the blockchain). The current protocol version has only one protocol command, `Next Epoch`. +|**Name**|**Input**|**Description**| +|---|---|---| +|Next epoch|None|Reward the current [epoch](blocks.md#epoch-block)'s validators, and confirm the next epoch's validator set.| ## Receipt and Logs ---- A **receipt** is produced upon execution of each transaction. It consists of a sequence of `CommandReceipt`, which provides a succinct summary of what happened during the execution of the corresponding `Command` in a transaction. diff --git a/assets/images/BlockTree Structure Diagram.png b/docs/img/BlockTree Structure Diagram.png similarity index 100% rename from assets/images/BlockTree Structure Diagram.png rename to docs/img/BlockTree Structure Diagram.png diff --git a/docs/img/Runtime Phases.png b/docs/img/Runtime Phases.png new file mode 100644 index 00000000..a0b9e538 Binary files /dev/null and b/docs/img/Runtime Phases.png differ diff --git a/docs/index.md b/docs/index.md index a0d4f9e7..c1486dd2 100644 --- a/docs/index.md +++ b/docs/index.md @@ -22,6 +22,5 @@ Whether you are a seasoned blockchain developer or just getting started with sma **Let's get started!** ## Contact us ---- If you are interested in ParallelChain Mainnet, reach out on us from our [Official Telegram Group](https://t.me/parallelchainofficial) or [Discord channel](https://discord.com/invite/parallelchainofficial). diff --git a/docs/introduction.md b/docs/introduction.md new file mode 100644 index 00000000..bd8d6209 --- /dev/null +++ b/docs/introduction.md @@ -0,0 +1,89 @@ +--- +tags: + - ParallelChain + - Mainnet +--- + +## What is ParallelChain + +**ParallelChain** is a dual-blockchain ecosystem powered by two Layer-1 blockchain networks, **ParallelChain Mainnet** and **ParallelChain Enterprise**. + +ParallelChain Mainnet is a **Delegated Proof-of-Stake** open-source platform that is suitable for building decentralised, web2 and web3-interoperable blockchain applications; and ParallelChain Enterprise is a business-native, permissioned blockchain that supports decentralised enterprise solutions that feature stronger privacy, scalability, and compliance features. The coupling of both blockchains in a permissioned-permissionless blockchain interoperability will bring Web2 and Web3 into a scalable, networked economy. + +The continued development of ParallelChain is supported by the **ParallelChain Foundation**, an independent governance body based in Switzerland, and it is dedicated to increasing awareness and growing a strong builder community for ParallelChain. + + +## Why ParallelChain? + +ParallelChain excels where most other blockchains stumble, providing: + + 1. speed, + 2. scalability, and + 3. connectivity. + +ParallelChain's dual-blockchain ecosystem drives near instant transactions. The public ParallelChain Mainnet and permissioned ParallelChain Enterprise both offer extremely **high transaction speed**—the latter operating at 130,000 transactions per second with a 3 millisecond finality. + +This speed brings **scalability** to public decentralised applications and enterprise solutions alike. Both networks help projects and companies scale up the amount of bandwidth needed, especially during peak usage where on-chain activities such as NFT minting periods could otherwise clog up the network and raise transaction gas fees. + +Moreover, heterogenous blockchains are unable to inter-communicate meaningfully due to their difference in architecture and consensus mechanism. With ParallelChain, the blockchain network achieves true **native chain communication** between permissioned and permissionless chains for deep level interoperability and allow enterprise users to tap into the decentralised space in a private, secure manner with Inter-ParallelChain Protocol (IPP). + +IPP essentially acts as the bridge that connects the enterprise chain to DeFi networks built on the ParallelChain Mainnet, and this enables decentralised applications (dApps) to work across both layers. By doing so, we create wider accessibility between communities that are traditionally isolated. + +## What is XPLL +**XPLL** is the native cryptocurrency of ParallelChain Mainnet (**TXPLL** in Testnet). The users of the ParallelChain Mainnet need XPLLs to pay for their transaction fees when using the network. The transaction fee is denoted in GRAY, the smallest unit of XPLL, where 1 GRAY = 0.00000001 XPLL. Other than that, XPLL also plays an important role in this Delegated Proof-of-Stake (DPoS) Mainnet; it incentivizes good behaviors and punishes actions that threaten the network's security, availability, and user experience. + +For more information about XPLL, including allocations, circulation, and inflation, please refer to the [XPLL Token Metrics](https://parallelchain.io/parallelchain/mainnet/papers/xpll-metrics). + + +### Utilities + +XPLL acts like your ticket to the ParallelChain Ecosystem; its utilities include the following: + +- **Pay** transaction fees on ParallelChain +- **Stake** XPLL to run a validator node +- **Delegate** to earn block rewards +- **Vote** on proposals and help govern the network + +### Denomination + +The smallest denomination of XPLL is called **Gray**. Users buy XPLL to pay for gas costs with the ParallelChain Mainnet and other purposes as mentioned in previous [Utilities](#utilities) section. + +The goal of defining a denomination for XPLL is to standardize its scale with all currencies in the financial system. The table below shows the different denominations of XPLL, their abbreviations, and their equivalent values in terms of XPLL. + +| Denomination | Abbreviation | Value in XPLL| +|:--- |:--- |:---| +|Gray |Gr | 0.00000001 XPLL| +|KiloGray |KGr | 0.00001 XPLL| +|MegaGray |MGr | 0.01 XPLL| +|XPLL |XPLL | 1 XPLL| +|TeraGray |TGr | 10000 XPLL| +|PetaGray |PGr | 10000000 XPLL| + +>*Gray is named in honor of **James Nicholas Gray**, a renowned computer scientist who was considered a pioneer in modern database technology. He was the award winner of the prestigious ACM Turing Award in 1998, which is the highest distinction in the field of computer science.* + +## How to Get XPLL + +There are several ways to obtain XPLLs, the native tokens of ParallelChain. + +### Staking Rewards + +Users can stake XPLL with the network validators to help secure the blockchain and earn rewards in the meantime. Staking is a process of locking up a certain amount of XPLL for a period of time in the process of validating transactions, adding new blocks, etc. Therefore, users will be rewarded with additional XPLL for contributing to the security and integrity of the network. + +To learn more about staking, read [Staking](./fundamentals/staking.md). + + + +### Ecosystem Activities - Ambassador Programme + +Users can earn XPLL by participating in our **Ambassador Programme** on [Zealy.io](https://zealy.io/c/parallelchain/questboard). There are a variety of tasks and missions for community members to complete. In return, community members will receive rewards, perks, and badges by leveling up on Zealy. This is an opportunity for community members to earn XPLLs while keeping everyone engaged. + +For more information about the ParallelChain Ambassador Programme, read [here](https://parallelchain.io/company/newsroom/parallelchain-zealy-announcement-and-ambassador-programme-update). + + +### KuCoin + +XPLL is now listed on [KuCoin](https://www.kucoin.com/price/XPLL), and the XPLL/USDT trading pair is available on the KuCoin platform. You can simply create an account on KuCoin, deposit your fund, and start trading for XPLL. + +>KuCoin is a global cryptocurrency exchange with a user-oriented platform that focuses on inclusiveness and community action reach. It offers over 700 digital assets and currently provides spot trading, margin trading, P2P fiat trading, futures trading, staking, and lending to its 27 million users in 207 countries and regions. KuCoin is currently one of the top 5 crypto exchanges, according to CoinMarketCap. + +For more information about the listing of XPLL, read [here](https://www.kucoin.com/news/en-parallelchain-xpll-gets-listed-on-kucoin-world-premiere). \ No newline at end of file diff --git a/docs/introduction/what_parallelchain.md b/docs/introduction/what_parallelchain.md deleted file mode 100644 index 42927f0e..00000000 --- a/docs/introduction/what_parallelchain.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -tags: - - ParallelChain - - Mainnet ---- - -# What is ParallelChain - -**ParallelChain** is a dual-blockchain ecosystem powered by two Layer-1 blockchain networks, **ParallelChain Mainnet** and **ParallelChain Enterprise**. - -ParallelChain Mainnet is a **Delegated Proof-of-Stake** open-source platform that is suitable for building decentralised, web2 and web3-interoperable blockchain applications; and ParallelChain Enterprise is a business-native, permissioned blockchain that supports decentralised enterprise solutions that feature stronger privacy, scalability, and compliance features. The coupling of both blockchains in a permissioned-permissionless blockchain interoperability will bring Web2 and Web3 into a scalable, networked economy. - -The continued development of ParallelChain is supported by the **ParallelChain Foundation**, an independent governance body based in Switzerland, and it is dedicated to increasing awareness and growing a strong builder community for ParallelChain. \ No newline at end of file diff --git a/docs/introduction/why_parallelchain.md b/docs/introduction/why_parallelchain.md deleted file mode 100644 index 6cf0234f..00000000 --- a/docs/introduction/why_parallelchain.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -tags: - - ParallelChain - - Mainnet ---- - -# Why ParallelChain? - -ParallelChain excels where most other blockchains stumble, providing: - - 1. speed, - 2. scalability, and - 3. connectivity. - -ParallelChain's dual-blockchain ecosystem drives near instant transactions. The public ParallelChain Mainnet and permissioned ParallelChain Enterprise both offer extremely **high transaction speed**—the latter operating at 130,000 transactions per second with a 3 millisecond finality. - -This speed brings **scalability** to public decentralised applications and enterprise solutions alike. Both networks help projects and companies scale up the amount of bandwidth needed, especially during peak usage where on-chain activities such as NFT minting periods could otherwise clog up the network and raise transaction gas fees. - -Moreover, heterogenous blockchains are unable to inter-communicate meaningfully due to their difference in architecture and consensus mechanism. With ParallelChain, the blockchain network achieves true **native chain communication** between permissioned and permissionless chains for deep level interoperability and allow enterprise users to tap into the decentralised space in a private, secure manner with Inter-ParallelChain Protocol (IPP). - -IPP essentially acts as the bridge that connects the enterprise chain to DeFi networks built on the ParallelChain Mainnet, and this enables decentralised applications (dApps) to work across both layers. By doing so, we create wider accessibility between communities that are traditionally isolated. \ No newline at end of file diff --git a/docs/introduction/xpll/how_to_get.md b/docs/introduction/xpll/how_to_get.md deleted file mode 100644 index 48212f2e..00000000 --- a/docs/introduction/xpll/how_to_get.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -tags: - - XPLL ---- - -# How to Get XPLL - -There are several ways to obtain XPLLs, the native tokens of ParallelChain. - -## Staking Rewards ---- -Users can stake XPLL with the network validators to help secure the blockchain and earn rewards in the meantime. Staking is a process of locking up a certain amount of XPLL for a period of time in the process of validating transactions, adding new blocks, etc. Therefore, users will be rewarded with additional XPLL for contributing to the security and integrity of the network. - -To learn more about staking, read [Staking](../../concepts/staking/what_is_staking.md). - - - -## Ecosystem Activities - Ambassador Programme ----- -Users can earn XPLL by participating in our **Ambassador Programme** on [Zealy.io](https://zealy.io/c/parallelchain/questboard). There are a variety of tasks and missions for community members to complete. In return, community members will receive rewards, perks, and badges by leveling up on Zealy. This is an opportunity for community members to earn XPLLs while keeping everyone engaged. - -For more information about the ParallelChain Ambassador Programme, read [here](https://parallelchain.io/company/newsroom/parallelchain-zealy-announcement-and-ambassador-programme-update). - - -## KuCoin ---- -XPLL is now listed on [KuCoin](https://www.kucoin.com/price/XPLL), and the XPLL/USDT trading pair is available on the KuCoin platform. You can simply create an account on KuCoin, deposit your fund, and start trading for XPLL. - ->KuCoin is a global cryptocurrency exchange with a user-oriented platform that focuses on inclusiveness and community action reach. It offers over 700 digital assets and currently provides spot trading, margin trading, P2P fiat trading, futures trading, staking, and lending to its 27 million users in 207 countries and regions. KuCoin is currently one of the top 5 crypto exchanges, according to CoinMarketCap. - -For more information about the listing of XPLL, read [here](https://www.kucoin.com/news/en-parallelchain-xpll-gets-listed-on-kucoin-world-premiere). \ No newline at end of file diff --git a/docs/introduction/xpll/what_is_xpll.md b/docs/introduction/xpll/what_is_xpll.md deleted file mode 100644 index 083b84d8..00000000 --- a/docs/introduction/xpll/what_is_xpll.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -tags: - - XPLL - - TXPLL - - Gray ---- - -# What is XPLL -**XPLL** is the native cryptocurrency of ParallelChain Mainnet (**TXPLL** in Testnet). The users of the ParallelChain Mainnet need XPLLs to pay for their transaction fees when using the network. The transaction fee is denoted in GRAY, the smallest unit of XPLL, where 1 GRAY = 0.00000001 XPLL. Other than that, XPLL also plays an important role in this Delegated Proof-of-Stake (DPoS) Mainnet; it incentivizes good behaviors and punishes actions that threaten the network's security, availability, and user experience. - -For more information about XPLL, including allocations, circulation, and inflation, please refer to the [XPLL Token Metrics](https://parallelchain.io/parallelchain/mainnet/papers/xpll-metrics). - - -## Utilities ---- -XPLL acts like your ticket to the ParallelChain Ecosystem; its utilities include the following: - -- **Pay** transaction fees on ParallelChain -- **Stake** XPLL to run a validator node -- **Delegate** to earn block rewards -- **Vote** on proposals and help govern the network - -## Denomination ---- -The smallest denomination of XPLL is called **Gray**. Users buy XPLL to pay for gas costs with the ParallelChain Mainnet and other purposes as mentioned in the [Utilities](./what_is_xpll.md#utilities) section. - -The goal of defining a denomination for XPLL is to standardize its scale with all currencies in the financial system. The table below shows the different denominations of XPLL, their abbreviations, and their equivalent values in terms of XPLL. - -| Denomination | Abbreviation | Value in XPLL| -|:--- |:--- |:---| -|Gray |Gr | 0.00000001 XPLL| -|KiloGray |KGr | 0.00001 XPLL| -|MegaGray |MGr | 0.01 XPLL| -|XPLL |XPLL | 1 XPLL| -|TeraGray |TGr | 10000 XPLL| -|PetaGray |PGr | 10000000 XPLL| - ->*Gray is named in honor of **James Nicholas Gray**, a renowned computer scientist who was considered a pioneer in modern database technology. He was the award winner of the prestigious ACM Turing Award in 1998, which is the highest distinction in the field of computer science.* diff --git a/docs/running_nodes/requirement.md b/docs/running_nodes/requirement.md deleted file mode 100644 index 527e3bca..00000000 --- a/docs/running_nodes/requirement.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -tags: - - Requirements ---- - -# Requirements - -## Hardware Requirements ---- -Available soon. - -## Software Requirements ---- -### Operating System -`Ubuntu 20.04` - -### Toolchain -| Toolchain Component | Version | Utility | -|:---: |:---: | :---: | -|rustc | 1.66.1 (ad779e08b 2023-01-10) |Compiler for Rust| - -### Required packages - -| Package Name | Version | -|:---: |:---: | -|libssl-dev |1.1.1f-1ubuntu2.16 | -|zlib1g-dev |1:1.2.11.dfsg-2ubuntu1.4| -|build-essential |12.8ubuntu1 | -|clang |10.0.0-4ubuntu1 | \ No newline at end of file diff --git a/docs/running_nodes/running_node.md b/docs/running_nodes/running_node.md deleted file mode 100644 index 6d7a3e50..00000000 --- a/docs/running_nodes/running_node.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -tags: - - Running Nodes ---- - -# Running a Node - -## Set up ---- -Generate `config.toml` along with `keypair.json`, `genesis.json` and `config.toml` - ->❗To join a network, make sure `genesis.json` is exactly the same as other members participating in the network. - -*Example Config File* -```toml - title = "Fullnode Configuration" - - standard_api_listening_port = 40000 - logs_path = "/tmp/parallelchain-f/logs" - - [engine] - app_id = 0 - produce_block_time_limit = 5000 - validate_block_time_limit = 5000 - blocks_per_epoch = 8 - - [engine.executor] - contract_cache_folder = "/home/.parallelchain/fullnode/contract_cache" - contract_memory_limit = 1073741824 - - [engine.genesis] - genesis_path = "/home/.parallelchain/fullnode/config/genesis.json" - genesis_timestamp = 1672531200 - treasury_address = "HLW3Lch72b2m9snDwDF8pHgm_0mwzyTgnM_VtRRQfg4" - - [node] - identity_path = "/home/.parallelchain/fullnode/config/keypair.json" - block_tree_storage_path = "/home/.config/parallelchain/hotstuff_rs/block_tree_storage" - - [pacemaker] - minimum_view_timeout = 10 - sync_request_limit = 10 - sync_response_timeout = 3 - - [network] - listening_port = 30000 - send_command_buffer_size = 8 - private_msg_buffer_size = 1024 - broadcast_msg_buffer_size = 1024 - peer_discovery_interval = 10 - - # hotstuff_rs.static_participant_set represents the list of participants that belong to - # `hotstuff_rs::config::Configuration::static_participant_set`. In this example, only one participant - # is available. Duplicate this entire segment [[hotstuff_rs.static_participant_set]] if you intend - # to add more participants. - [[network.bootstrap]] - address = "k9LhEzdX7SxssikrwNFMGiRfj4ugM3u3LNJvE0MY63U" - ip_address = "172.16.3.1" - port = 30000 - [[network.bootstrap]] - address = "wT7l6TSj3h6Gg6xJQof-woz0qtYBrb-kLxWxO5q5sTw" - ip_address = "172.16.3.2" - port = 30000 - [[network.bootstrap]] - address = "l1RjOEHtM-RvUh7BxmCBgu33Pw1vqb8AgKJLMLqz3js" - ip_address = "172.16.3.3" - port = 30000 - [[network.bootstrap]] - address = "ipy_VXNiwHNP9mx6-nKxht_ZJNfYoMAcCnLykpq4x_k" - ip_address = "172.16.3.4" - port = 30000 -``` - -!!!Tips - - Make sure keypair and ip pairs underneath network are consistent with the previous bootstrapped nodes present in the network. - - Add your own public key and ip_address in this section. - - Make sure your keypair file is kept in the correct identity_path provided in `config.toml`. - -## Run Binary ---- -Run fullnode binary: - -=== start from genesis -```bash -./fullnode --config-path /home/.parallelchain/fullnode/config/config.toml start-from-genesis -``` - -=== have existing storage -```bash -./fullnode --config-path /home/.parallelchain/fullnode/config/config.toml -``` \ No newline at end of file diff --git a/docs/user_guides/pchain_cli/create_account.md b/docs/user_guides/pchain_cli/create_account.md deleted file mode 100644 index 1920e076..00000000 --- a/docs/user_guides/pchain_cli/create_account.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -tags: - - pchain-client - - account - - mainnet - - testnet 4 - - faucet ---- - -The guide will walk you through the steps to generate and manage your Mainnet / Testnet account by using `pchain_client`. Alternatively, you can generate account by using [ParallelChain Explorer](https://explorer.parallelchain.io). *Please refer to the [Explorer Account Tutorial](https://parallelchain.io/company/newsroom/explorer-account-tutorial)*. - -## Generating Keypair ---- - -To create an account, type the following command below: -=== "Linux / macOS" - ```bash - ./pchain_client keys create --name - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe keys create --name - ``` - -You will be asked to input your password to save the new keypair. - -This command generates a set of ed25519_dalek-compatible keys. A keypair file in json format is created in the folder specified by the environment variable `PCHAIN_CLI_HOME`. These are the keys required for making transactions in the network. Its public key is the public address of your account. You can view it as follows: - -=== "Linux / macOS" - ```bash - ./pchain_client keys list - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe keys list - ``` - -
    Terminal Output -```bash -Keypair Name (First 50 char) Public key -------------------------- ------------------------- -doc mF0a_r31a_cNNnKbngoUGUuy71V_l872yGxy7iwIBwA -``` -
    - -You will need the keypair and public key to submit transactions. - -You can check the account balance using the account address (public key). -=== "Linux / macOS" - ```bash - ./pchain_client query balance --address
    - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe query balance --address
    - ``` -
    Terminal Output -```bash -0 -``` -
    - -The balance of a new account is 0. Therefore, you need to request tokens from the faucet. - -## Exporting Keypair - -Right now, the key pair is only in your machine. It will go away if your machine somehow breaks. It may also be lost if you forget your password. - -To secure your keypair and money, you must export it and save it somewhere secure, or at least make a copy of it. - -=== "Linux / macOS" - ```bash - ./pchain_client keys export --name - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe keys export --name - ``` - -You will be asked to input your password to export the keypair. The keypair will be saved in the current directory, in JSON format, with the same name as the keypair itself. - -## Importing Keypair - -To add your keypair, type the following command below: -=== "Linux / macOS" - ```bash - ./pchain_client keys import --public --private --name - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe keys import --public --private --name - ``` - -You will be asked to input your password to import the new keypair. - -## Request for tokens from Faucet (Testnet) ---- - -The Faucet Service of our Testnet issues free testing tokens to users to test the blockchain network on Testnet. - -Right now, you have your keypair (account) to associate with the blockchain. But the account should have an empty balance. You can now request tokens from [Faucet Service](https://faucet.parallelchain.io). \ No newline at end of file diff --git a/docs/user_guides/pchain_cli/staking.md b/docs/user_guides/pchain_cli/staking.md deleted file mode 100644 index 1eaf0db4..00000000 --- a/docs/user_guides/pchain_cli/staking.md +++ /dev/null @@ -1,219 +0,0 @@ ---- -tags: - - pchain-client - - Staking - - Network Transaction ---- - -The staking process consists of several Staking Commands. Each command usually works with each other to serve a particular purpose. It is recommended to read paragraph [How does staking work](../concepts/staking/how_does_staking_work.md#how-does-staking-work) before trying out the commands which are described on this page. - -This page guides you to create staking transactions by using the CLI. The CLI creates a JSON file which can be used to submit the staking transaction in the same way as [submitting transfer transaction](./transfer.md#submitting-transaction). - -## Creating Deposit ---- - -First, before you stake, you have to lock up (stake) some balance tied to an operator to prepare for the stake. This step is done by the CLI subcommand `deposit create`, which reduces the balance of your account. - -=== "Linux / macOS" - ```bash - ./pchain_client transaction create \ - --nonce \ - --gas-limit \ - --max-base-fee-per-gas \ - --priority-fee-per-gas \ - deposit create \ - --operator \ - --balance \ - --auto-stake-rewards - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe transaction create ` - --nonce ` - --gas-limit ` - --max-base-fee-per-gas ` - --priority-fee-per-gas ` - deposit create ` - --operator ` - --balance ` - --auto-stake-rewards - ``` -The last flag for `auto-stake-rewards` is optional. By default, it is false. It indicates whether your rewards should be staked to the Pool in each epoch. - -After you create a deposit, you can do follows: - -- Top-up the amount of the deposit -- Update deposit settings (i.e. toggling `auto-stake-rewards`) -- Stake deposit to the pool -- Withdraw the deposit - -!!! Important Notes - Now you have just created the Deposit to a Pool, but you still have no stake in the pool. At this stage, you will **NOT** have the rewards, because your reward amount is calculated by the amount that you staked, not the Deposit you created. - -### Topping up Deposit - -After creating a Deposit in a Pool, use the CLI subcommands `deposit top-up` if you want to put more in the same Pool. - -=== "Linux / macOS" - ```bash - ./pchain_client transaction create \ - --nonce \ - --gas-limit \ - --max-base-fee-per-gas \ - --priority-fee-per-gas \ - deposit top-up \ - --operator \ - --amount - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe transaction create ` - --nonce ` - --gas-limit ` - --max-base-fee-per-gas ` - --priority-fee-per-gas ` - deposit top-up ` - --operator ` - --amount - ``` - -### Toggling `auto-stake-rewards` ---- - -You specified the flag `auto-stake-rewards` when you created the Deposit. You can change the value of this flag by submitting another transaction using the CLI subcommand `deposit update-settings`. - -=== "Linux / macOS" - ```bash - ./pchain_client transaction create \ - --nonce \ - --gas-limit \ - --max-base-fee-per-gas \ - --priority-fee-per-gas \ - deposit update-settings \ - --operator \ - --auto-stake-rewards - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe transaction create ` - --nonce ` - --gas-limit ` - --max-base-fee-per-gas ` - --priority-fee-per-gas ` - deposit update-settings ` - --operator ` - --auto-stake-rewards - ``` - -## Staking and Unstaking ---- - -After you create a Deposit to a Pool, you should now stake some amount of it to the pool with the CLI subcommand `stake stake`. - -=== "Linux / macOS" - ```bash - ./pchain_client transaction create \ - --nonce \ - --gas-limit \ - --max-base-fee-per-gas \ - --priority-fee-per-gas \ - stake stake \ - --operator \ - --max-amount - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe transaction create ` - --nonce ` - --gas-limit ` - --max-base-fee-per-gas ` - --priority-fee-per-gas ` - stake stake ` - --operator ` - --max-amount - ``` - -The `max-amount` specifies the maximum amount of Deposits that are going to stake. After submitting the transaction, the resulting staked amount is not necessary to be as same as the `max-amount`. - -You can also unstake your stake on with the CLI subcommand `stake unstake`. - -=== "Linux / macOS" - ```bash - ./pchain_client transaction create \ - --nonce \ - --gas-limit \ - --max-base-fee-per-gas \ - --priority-fee-per-gas \ - stake unstake \ - --operator \ - --max-amount - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe transaction create ` - --nonce ` - --gas-limit ` - --max-base-fee-per-gas ` - --priority-fee-per-gas ` - stake unstake ` - --operator ` - --max-amount - ``` - -### Creating Transaction with Multiple Staking Commands - -Staking in a pool requires two steps: `Create Deposit` and `Stake Deposit`. But it does not mean that there must be two corresponding transactions to be made. You can create a single transaction with two staking commands. For example, you can do both `Create Deposit` and `Stake Deposit` in a transaction by the CLI command `append`. - -Suppose you created the transaction file (i.e. `tx.json`) from the step [Creating Deposit](#creating-deposit). - -=== "Linux / macOS" - ```bash - ./pchain_client transaction append \ - --file \ - stake stake \ - --operator \ - --max-amount - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe transaction append ` - --file ` - stake stake ` - --operator ` - --max-amount - ``` - -The transaction file will then be modified. Then, you can submit it as a single transaction. - -## Withdrawing Deposit ---- - -Your Deposit can be increased due to reward distribution in each epoch. If you want to pull out the Deposit from the Pool to the balance of your account, make use of the CLI subcommand `deposit withdraw`. - -=== "Linux / macOS" - ```bash - ./pchain_client transaction create \ - --nonce \ - --gas-limit \ - --max-base-fee-per-gas \ - --priority-fee-per-gas \ - deposit withdraw \ - --operator \ - --max-amount - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe transaction create ` - --nonce ` - --gas-limit ` - --max-base-fee-per-gas ` - --priority-fee-per-gas ` - deposit withdraw ` - --operator ` - --max-amount - ``` - -The balance in your account will be increased for the Deposit that you withdrew from the Pool. - -!!! Tips - If you withdraw the Deposit without unstaking (assuming you already staked), you may not be able to withdraw all deposited tokens because you cannot withdraw the staked Deposit in the current Pool. In this case, you have to unstake first and wait for the next two epochs before you withdraw the Deposit. diff --git a/docs/user_guides/pchain_cli/transfer_tokens.md b/docs/user_guides/pchain_cli/transfer_tokens.md deleted file mode 100644 index 042ed0f3..00000000 --- a/docs/user_guides/pchain_cli/transfer_tokens.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -tags: - - pchain-client - - mainnet - - testnet ---- - -This guide will walk you through the process of transferring tokens on ParallelChain Mainnet / Testnet. - -## Creating Transaction with a Transfer Command ---- - -To create a transaction, you first need to know the `nonce` of your account, which is an account-related entity required to submit a transaction. Here's how to check your account's `nonce` using `pchain_client`: - -=== "Linux / macOS" - ```bash - ./pchain_client query nonce --address - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe query nonce --address - ``` -When you run this command, you'll see the output of your account's `nonce` value, like this: -```bash -0 -``` - -Next, to transfer tokens from your account to someone else's account using `pchain_client`, you need to create a transaction file containing one transfer command first. - -=== "Linux / macOS" - ```bash - ./pchain_client transaction create \ - --nonce \ - --gas-limit \ - --max-base-fee-per-gas \ - --priority-fee-per-gas \ - transfer \ - --recipient \ - --amount - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe transaction create ` - --nonce ` - --gas-limit ` - --max-base-fee-per-gas ` - --priority-fee-per-gas ` - transfer ` - --recipient ` - --amount - ``` - -A file with the name `tx.json` will be saved in the current directory if the `destination` flag is not specified. If you want to store the transaction file in your preferred location, specify the path with your preferred file name and JSON extension under the `destination` flag. - -Please note that `max-base-fee-per-gas` had to be at least 8. - -Make sure to replace - -- `` with your account's nonce value; -- `` with the gas limit of the transaction; -- `` with the maximum base fee you want to pay; -- `` with the priority fee you want to pay; -- `` with the recipient's account address; -- `` with the number of tokens you want to transfer; - -## Submitting Transaction ---- - -=== "Linux / macOS" - ```bash - ./pchain_client transaction submit --file --keypair-name - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client transaction submit ` - --file ` - --keypair-name - ``` -After submitting the transaction to RPC successfully, you should receive a message that describes the content of the transaction. The transaction hash in the content will be useful later on when you want to check its status. Still, transactions may fail for various reasons. We suggest you test the transaction and estimate the gas used in the testnet. - -## Querying Transaction ---- - -You can check the transaction status using `pchain_client` with the following command: - -=== "Linux / macOS" - ```bash - ./pchain_client query tx --hash - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe query tx --hash - ``` - -Make sure to replace `` with the transaction hash that you want to check. - -## Creating Transaction with Multiple Transfer Commands ---- - -You may append an extra transfer transaction with `pchain_client`. After creating a transaction with single transfer command in the last tutorial, instead of submitting the transaction, you can append extra command on the `tx.json` generated by `pchain_client`. - -=== "Linux / macOS" - ```bash - ./pchain_client transaction append \ - --file \ - transfer \ - --recipient \ - --amount - ``` -=== "Windows PowerShell" - ```PowerShell - ./pchain_client.exe transaction append ` - --file ` - transfer ` - --recipient ` - --amount - ``` - -Currently, if you construct a transaction with `pchain_client`, the fields `nonce`, `gas limit`, `max base fee per gas` and `priority fee per gas` are already filled in after calling command `create`. You need to manually change the transaction JSON file if you want to change them: - -After chaining up commands you are satisfied with, you can submit the transaction as you did in a single command transaction. diff --git a/mkdocs.yml b/mkdocs.yml index 05c6da7f..50d3ceea 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -5,111 +5,69 @@ repo_url: https://github.com/parallelchain-io/parallelchain-docs copyright: ParallelChain Lab 2023 nav: - - Introduction: - - What is ParallelChain?: introduction/what_parallelchain.md - - Why Build on ParallelChain?: introduction/why_parallelchain.md - - XPLL: - - What is XPLL?: introduction/xpll/what_is_xpll.md - - How to get XPLL?: introduction/xpll/how_to_get.md - - Concepts: - - Account: concepts/account.md - - Block: concepts/block.md - - Transaction, Command and Receipt: concepts/transaction.md - - Epoch: concepts/epoch.md - - Consensus: concepts/consensus.md - - Gas: concepts/gas.md - - Mempool: concepts/mempool.md - - Smart Contract: concepts/smartcontract.md - - PRFC: concepts/PRFC.md - - Staking: - - What is staking?: concepts/staking/what_is_staking.md - - How does staking work?: concepts/staking/how_does_staking_work.md - - Validators: concepts/staking/validator.md - - Delegators: concepts/staking/delegator.md - - Block reward: concepts/staking/block_reward.md - - FAQ: concepts/staking/faq.md - - Storage: concepts/storage.md - - Explorer: concepts/explorer.md - - Wallet: concepts/wallet.md - - Mainnet: concepts/mainnet.md - - Testnet: concepts/testnet.md - # - Architecture: - # - Reading Data from ParallelChain - # - Writing Data to ParallelChain - # - Interacting with Account and Wallet - # - Running Nodes: - # - Hardware & Software Requirements: running_nodes/requirement.md - # - Running a Node: running_nodes/running_node.md - # - ParallelChain Core Contracts - # - Fungible Token Contract - # - Non-Fungible Token Contract - # - Staking Contract - # - Epoch Contract - - Developer Guides: - - pchain-client: - - Introduction: developer_guides/pchain_cli/introduction.md - - Install and Setup: developer_guides/pchain_cli/install_and_setup.md - - Manage Account: developer_guides/pchain_cli/manage_account.md - - Create Transaction: developer_guides/pchain_cli/transaction.md - - Query: developer_guides/pchain_cli/query.md - - Smart Contract: developer_guides/pchain_cli/smart_contract.md - - Smart Contract Development: - - Introduction: developer_guides/smart_contract_sdk/introduction.md - # - What is Smart Contract on ParallelChain? - # - Advantages of ParallelChain Smart Contracts - # - ParallelChain Smart Contract Language - - Install SDK: developer_guides/smart_contract_sdk/installation.md - - Prepare Environment: developer_guides/smart_contract_sdk/prepare_env.md - - Develop Contract: developer_guides/smart_contract_sdk/develop_contract.md - - Build Contract: developer_guides/smart_contract_sdk/build_contract.md - - Deploy Contract: developer_guides/smart_contract_sdk/deploy_contract.md - - Call Contract: developer_guides/smart_contract_sdk/call_contract.md - - Tutorial: - - Chapter 1: developer_guides/smart_contract_sdk/tutorial/chapter_1.md - - Chapter 2: developer_guides/smart_contract_sdk/tutorial/chapter_2.md - - Chapter 3: developer_guides/smart_contract_sdk/tutorial/chapter_3.md - - Chapter 4: developer_guides/smart_contract_sdk/tutorial/chapter_4.md - - Chapter 5: developer_guides/smart_contract_sdk/tutorial/chapter_5.md - - Chapter 6: developer_guides/smart_contract_sdk/tutorial/chapter_6.md - - Advance: - - Contract Methods: developer_guides/smart_contract_sdk/advance/entrypoints.md - - Contract Storage: developer_guides/smart_contract_sdk/advance/contract_storage.md - - Accessing Information About the Blockchain: developer_guides/smart_contract_sdk/advance/params.md - - Cross Contract Call: developer_guides/smart_contract_sdk/advance/cross_contract.md - - Transferring Balance: developer_guides/smart_contract_sdk/advance/internal_transaction.md - - Crypto: developer_guides/smart_contract_sdk/advance/crypto.md - - Staking in Contract: developer_guides/smart_contract_sdk/advance/staking.md - - ParallelChain RPC API: - - Introduction: developer_guides/rpc/introduction.md - - Transaction-related RPC: developer_guides/rpc/transaction_rpc.md - - Block-related RPC: developer_guides/rpc/block_rpc.md - - State-related RPC: developer_guides/rpc/state_rpc.md - # - pchain-client-rust: developer_guides/pchain_client_rust.md - - Wallet Browser Extension: - - Introduction: developer_guides/wallet_browser_extension/intro.md - - Definitions: developer_guides/wallet_browser_extension/definition.md - - Extension Provider API: - - Introduction: developer_guides/wallet_browser_extension/provider/intro.md - - Errors: developer_guides/wallet_browser_extension/provider/error.md - - Events: developer_guides/wallet_browser_extension/provider/event.md - - Permissions: developer_guides/wallet_browser_extension/provider/permission.md - - API Documentation: developer_guides/wallet_browser_extension/provider/api_documentation.md - - User Guides: - - Wallet Web-Based Tool: - - Creating and Managing Your Account: user_guides/wallet_web_based_tool/create_account.md - - Transferring Tokens: user_guides/wallet_web_based_tool/transfer_tokens.md - - Staking XPLL: user_guides/wallet_web_based_tool/staking.md - - Lock-Up Contract: user_guides/wallet_web_based_tool/lockup_contract.md - - Wallet Browser Extension: - - Creating and Managing Your Account: user_guides/wallet_browser_extension/create_account.md - - Transferring Tokens: user_guides//wallet_browser_extension/transfer_tokens.md - - Managing Tokens: user_guides/wallet_browser_extension/managing_tokens.md - - Staking XPLL: user_guides/wallet_browser_extension/staking.md - - Lock-Up Contract: user_guides/wallet_browser_extension/lockup_contract.md - - pchain-cli: - - Create Account: user_guides/pchain_cli/create_account.md - - Transfer Tokens: user_guides/pchain_cli/transfer_tokens.md - - Staking: user_guides/pchain_cli/staking.md + - Introduction: introduction.md + - Fundamentals: + - Accounts: fundamentals/accounts.md + - Blocks: fundamentals/blocks.md + - Transactions: fundamentals/transactions.md + - Gas: fundamentals/gas.md + - Nodes: fundamentals/nodes.md + - Networks: fundamentals/networks.md + - Consensus Mechanism: fundamentals/consensus_mechanism.md + - Staking: fundamentals/staking.md + - For Developers: + - Smart Contracts: + - Introduction: for_developers/smart_contracts/introduction.md + - Installing SDK: for_developers/smart_contracts/installing_sdk.md + - Preparing Environment: for_developers/smart_contracts/preparing_env.md + - Getting Started: for_developers/smart_contracts/getting_started.md + - Smart Contract Examples: + - Hello Contract: for_developers/smart_contracts/smart_contract_examples/1_hello_contract.md + - My Little Pony: for_developers/smart_contracts/smart_contract_examples/2_my_little_pony.md + - My Bank: for_developers/smart_contracts/smart_contract_examples/3_my_bank.md + - Contract Proxy: for_developers/smart_contracts/smart_contract_examples/4_contract_proxy.md + - My Collections: for_developers/smart_contracts/smart_contract_examples/5_my_collections.md + - My Pool: for_developers/smart_contracts/smart_contract_examples/6_my_pool.md + - Advanced: + - Contract Methods: for_developers/smart_contracts/advanced/contract_methods.md + - Contract Storage: for_developers/smart_contracts/advanced/contract_storage.md + - Accessing Information About the Blockchain: for_developers/smart_contracts/advanced/accessing_info_about_blockchain.md + - Cross Contract Call: for_developers/smart_contracts/advanced/cross_contract_call.md + - Transferring Balance: for_developers/smart_contracts/advanced/transferring_balance.md + - Cryptographic Functions: for_developers/smart_contracts/advanced/cryptographic_functions.md + - Staking in Contract: for_developers/smart_contracts/advanced/staking_in_contract.md + - PRFC: for_developers/smart_contracts/prfc.md + - ParallelChain Client APIs: + - JavaScript APIs: for_developers/parallelchain_client_apis/javascript_apis.md + - Rust Client APIs: for_developers/parallelchain_client_apis/rust_client_apis.md + - Xperience Browser Provider APIs: + - Introduction: for_developers/xperience_browser_provider_apis/introduction.md + - Definitions: for_developers/xperience_browser_provider_apis/definitions.md + - Errors: for_developers/xperience_browser_provider_apis/error.md + - Events: for_developers/xperience_browser_provider_apis/event.md + - Permissions: for_developers/xperience_browser_provider_apis/permissions.md + - API Reference: for_developers/xperience_browser_provider_apis/api_reference.md + + - For End-Users: + - ParallelChain Client CLI: + - Getting Started: for_users/pchain_client_cli/getting_started.md + - Managing Account: for_users/pchain_client_cli/managing_account.md + - Creating Transaction: for_users/pchain_client_cli/creating_transaction.md + - Querying Blockchain: for_users/pchain_client_cli/querying_blockchain.md + - Interacting with Smart Contract: for_users/pchain_client_cli/interacting_with_smart_contract.md + + - Web Wallet: + - Creating and Managing Your Account: for_users/web_wallet/create_account.md + - Transferring Tokens: for_users/web_wallet/transfer_tokens.md + - Staking XPLL: for_users/web_wallet/staking.md + - Lock-Up Contract: for_users/web_wallet/lockup_contract.md + + - Xperience Browser Extension: + - Creating and Managing Your Account: for_users/xperience_browser_extension/create_account.md + - Transferring Tokens: for_users//xperience_browser_extension/transfer_tokens.md + - Managing Tokens: for_users/xperience_browser_extension/managing_tokens.md + - Staking XPLL: for_users/xperience_browser_extension/staking.md + - Lock-Up Contract: for_users/xperience_browser_extension/lockup_contract.md extra_css: - stylesheets/extra.css