> Agents can also search and read this documentation through its [MCP server](https://pao.peerplays.com/~gitbook/mcp).

# Peerplays 2.0

## Introduction

Peerplays 2.0 is a new blockchain with Proof of Pulse consensus mechanism. The chain is built using Substrate SDK.

## Features

* Ethereum supporting tools are easy to be used with Peerplays2.0
* Handful of ways to deploy smart contracts.&#x20;


# Deployment Guides

This section of the documentation provides steps deploy Peerplays2.0 and tools required to operate the blockchain as well as support tools like block explorers.

{% content-ref url="/pages/f1Bz1RlFcmpZxzcjbOE0" %}
[Deployment in a box](https://pao.peerplays.com/peerplays-2.0/deployment-guides/deployment-in-a-box)
{% endcontent-ref %}

{% content-ref url="/pages/jS6JmqhVpTy5Do9i1qrb" %}
[Blockscout Explorer Deployment](https://pao.peerplays.com/peerplays-2.0/deployment-guides/blockscout-explorer-deployment)
{% endcontent-ref %}

{% content-ref url="/pages/6ET8LN8Xxjg1r74wFysz" %}
[Solidity Smart contracts](https://pao.peerplays.com/peerplays-2.0/solidity-smart-contracts)
{% endcontent-ref %}

{% content-ref url="/pages/wPep5zBPfH54KBAmqEQR" %}
[Solidity smart contract deployment using hardhat](https://pao.peerplays.com/peerplays-2.0/solidity-smart-contracts/solidity-smart-contract-deployment-using-hardhat)
{% endcontent-ref %}

{% content-ref url="/pages/wgjiK3Ha3PsdULGOdrmW" %}
[Solidity smart contract deployment using REMIX IDE](https://pao.peerplays.com/peerplays-2.0/solidity-smart-contracts/solidity-smart-contract-deployment-using-remix-ide)
{% endcontent-ref %}

{% content-ref url="/pages/FWdZvKmxLT1BiYHyV2SZ" %}
[Metamask Deployment](https://pao.peerplays.com/peerplays-2.0/solidity-smart-contracts/metamask-deployment)
{% endcontent-ref %}


# Deployment in a box

## A. Introduction

This document explains about the steps involved in Peerplays2.0 deployment in a box. The environment provides all the tools to quickly start Peerplays2.0 envionrment.  Deployment in a box consists of a set of docker images which are self contained, ready to install procedure. The purpose of this document is provide a user with simple step-by-step procedure to create an end-to-end environment to test Peerplays 2.0 using docker.

## B. Features

The software used to run Peerplays2.0 is the latest docker image from the master branch in the discovery repository <https://gitlab.com/PBSA/Peerplays_2.0/discovery/-/blob/master/Dockerfile>

The following details are the list of aspects in this Test environment,

* **Peerplays 2.0 Private Testnet Multi Node network** - 11 Peerplays 2.0 nodes, running 11 validators.
* Private Docker network used for connecting all containers.
* Polkadot UI, customized for Peerplays 2.0.
* Contracts UI, to handle Ink contracts.
* The start script for Funded **substrate** accounts will point to the below endpoints,\
  **For dev:** Alice\
  **For testnet:** init00, init01, init02, init03, init04, init05, init06, init07, init08, init09, init10\
  **For mainnet:** init00, init01, init02, init03, init04, init05, init06, init07, init08, init09, init10
* The start script for  Funded **ETH** accounts will point to the below endpoints,\
  **For dev:** Alice, Alith\
  **For testnet:** init00\
  **For mainnet:** init00

## C. Software Requirements

* [ ] Officially supported Operating System - Ubuntu 20.04 OS (always use the latest version)
* [ ] Docker-compose version 1.25.0&#x20;

{% hint style="danger" %}
The testing and deployment of Peerplays 2.0 components are performed only in the Ubuntu environment.

If the user wish to test in the other environments such as Windows or MacOS, there might be a build failure. The solution to such cases are out of scope at the moment and user is on their own to find the possible solution.
{% endhint %}

## D. Steps to Deploy Peerplays 2.0 in a box <a href="#user-content-building" id="user-content-building"></a>

Follow the steps from the README file linked below to build Peerplays 2.0 hassle free,

{% embed url="<https://gitlab.com/PBSA/Peerplays_2.0/discovery/-/tree/master/discovery-qa>" %}
Detailed steps to build Peerplays2.0
{% endembed %}

The readme file provides the updated steps around the clock and the deployment can be done without any hindrance. However, the brief description for each step is provided below,

### 1. Build the image <a href="#user-content-building" id="user-content-building"></a>

The image can be build either fully or partially based on user's option. The **Full build** image will use a single command to build 11 images at a time. while, the **Partial build** option allows user to build one image at a time. Both build procedure involves docker commands. Refer the [README](https://gitlab.com/PBSA/Peerplays_2.0/discovery/-/blob/master/discovery-qa/README.md#building) file for the commands.

### 2. Run a custom image <a href="#user-content-running-a-custom-image" id="user-content-running-a-custom-image"></a>

The QA environment facilitates the user with an option to use custom image as **`discovery-base`** image. In order to use a custom discovery image, that image has to be published in container registry. The dockerized job has to be run in the MR pipeline manually, to publish a docker image. The image will be published based on branch name and commit SHA in the below location,

{% embed url="<https://gitlab.com/PBSA/Peerplays_2.0/discovery/container_registry>" %}

Refer to the steps in the [README](https://gitlab.com/PBSA/Peerplays_2.0/discovery/-/blob/master/discovery-qa/README.md#running-a-custom-image) file to complete the rebuild procedure.

### 3. Start the nodes <a href="#user-content-starting-nodes" id="user-content-starting-nodes"></a>

There are two options to start the node, either a full start or a partial start based on the user's choice.&#x20;

* Full start, will start all the 11 node with a single command.
* Partial start, will allow the user to start the 11 node one-by-one using unique commands.

Refer the [README](https://gitlab.com/PBSA/Peerplays_2.0/discovery/-/blob/master/discovery-qa/README.md#starting-nodes) file to start the nodes.

### 4. Block confirmation  <a href="#user-content-confirmation" id="user-content-confirmation"></a>

As per the criteria, more than 8 nodes has to started and stay active to successfully communicate with each other. Only after the communication, the user will be able to see the finalized blocks.&#x20;

An example showing the finalized block is given below:

{% code overflow="wrap" %}

```docker
discovery-validator-grace_1    | 2023-05-03 10:51:07 💤 Idle (10 peers), best: #5 (0x52a5…77cd), finalized #3 (0xff76…a8fc), ⬇ 54.3kiB/s ⬆ 50.8kiB/s
```

{% endcode %}

### 5. Stop the nodes <a href="#user-content-stopping-nodes" id="user-content-stopping-nodes"></a>

Nodes can be stopped using a single command line. Refer the [README](https://gitlab.com/PBSA/Peerplays_2.0/discovery/-/blob/master/discovery-qa/README.md#stopping-nodes) file to check the command.


# Blockscout Explorer Deployment

Blockchain explorer for examining and inspecting EVM chains.

## A. Introduction

Blockscout is a fully-featured open-source blockchain explorer which can be used by any Ethereum virtual machine (EVM) chain. Blockscout provide access to essential on-chain data, the ability to interact with smart contracts, and tools to analyse any transactions at ease. The major features of blockscout are multichain, highly configurable, and open source. The explorer allows the user to search blocks, transaction, addresses and also connect & interact with smart contract, application, bridges, wallets, etc.,

## B. Hardware Requirements

The hardware requirement details to install the explorer for **Peerplays2.0** is provided below.

### 1. Recommended Base Hardware (Provided by Blockscout)

EVM chains can differ in size and requirements, these are the recommendations for optimal performance.

| CPU | 16 core, 32 thread |
| --- | ------------------ |
| RAM | 128GB              |

### 2. Currently Deployed Hardware For Peerplays2

| CPU  | 8         |
| ---- | --------- |
| RAM  | 16GB      |
| Disk | 160GB SSD |

### 3. Current Hardware Utilized Connected To Peerplays2

| CPU                            | 8 Core/Thread Virtualized |
| ------------------------------ | ------------------------- |
| RAM                            | 16GB                      |
| Disk                           | 15GB                      |
| CPU Average (1, 5, 15 Minutes) | 0.25, 0.11, 0.10          |
| RAM Usage                      | 5.95GB                    |
| Disk Usage                     | 25GB                      |

## C. Software Requirements

Before installing the Blockscout explorer, the user must ensure that the below required software are installed in their machine. Follow the CLI below to install the desired software,

### 1. Docker

Docker is an open software platform that enables the user to build, deploy, test, and update applications swiftly. Docker uses containers for all the execution. A container is a total software package of an application's code, its libraries and other dependencies. The main advantage of using container is that, our application is portable and the same code can be executed on any device. The cli to install docker is provided below:

{% code overflow="wrap" %}

```sh
curl -fsSL [<https://get.docker.com>](<https://get.docker.com/>) -o [install-docker.sh](<http://install-docker.sh/>)

sudo sh install-docker.sh
```

{% endcode %}

### 2. Erlang

Erlang is used to build massive scalable soft real-time system with requirements on high availability. Install using the below command:

```bash
sudo apt install erlang
```

### 3. Elixir

Elixir is a dynamic, functional language for building scalable and maintainable applications. Elixir runs on the Erlang VM, known for creating low-latency, distributed, and fault-tolerant systems. Install the Elixir using the below command:

```bash
sudo add-apt-repository ppa:rabbitmq/rabbitmq-erlang
sudo apt update
sudo apt install elixir
```

### 4. PostgreSQL 14

PostgreSQL is an open source relational database management system emphasizing extensibility and SQL compliance. It is the primary primary datastore or data warehouse for  many web, mobile, geospatial, and analytics application. Install PostgreSQL 14 using the below CLI:

{% code overflow="wrap" %}

```bash
sudo sh -c 'echo "deb <http://apt.postgresql.org/pub/repos/apt> $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
wget --quiet -O - <https://www.postgresql.org/media/keys/ACCC4CF8.asc> | sudo apt-key add -
sudo apt update
sudo apt install postgresql-14
```

{% endcode %}

### 5. Node 18.x

Node 18 execute the JavaScript using the updated version to  boost the performance of web applications. It allows to create and execute tests without intervention from any third party package before adding code to action. Its the build-in node. Install latest Node 18 version using the below commands:

{% code overflow="wrap" %}

```bash
curl -fsSL <https://deb.nodesource.com/setup_18.x> | sudo -E bash -
sudo apt-get install -y nodejs
```

{% endcode %}

#### 6. Apt dependencies

The apt dependencies are the supporting packages required to run the application in Linux without interruption. Install the necessary package using below command:

```bash
sudo apt install automake libtool inotify-tools libgmp-dev make g++
```

## **D. Setting up the application**

In the terminal, follow the step-by-step procedure given below to setup the application

1. **Grab the repository**\
   Clone the repository from the GitHub.

```bash
git clone <https://github.com/blockscout/blockscout> && cd blockscout
```

2. **Ensure connectivity to PostgreSQL**\
   Login the PSQL using the correct database user.

```bash
sudo --login --user=postgres psql
```

3. **Export PostgreSQL database URL**\
   Export the database to blockscout.

```bash
export DATABASE_URL=postgresql://user:password@localhost:5432/blockscout
```

4. **Install Mix dependencies and compile them**

```bash
mix do deps.get, local.rebar --force, deps.compile
```

5. **Generate a new secret\_key\_base for the DB**\
   Using the below command, generate the key for database:

```bash
mix phx.gen.secret
```

6. **Export the secret key**

```bash
export SECRET_KEY_BASE=<output-of-phx.gen.secret>
```

7. **Set the following environment variables specific to Peerplays2.0**\
   The below environment details are specific to Peerplays2.0 application:

```bash
 export COIN_NAME=PPY-Test && \\
 export RUST_VERIFICATION_SERVICE_URL=http://0.0.0.0:8043/ && \\
 export MIX_ENV="prod" && \\
 export MICROSERVICE_SC_VERIFIER_ENABLED=true && \\
 export ETHEREUM_JSONRPC_HTTP_URL=http://<IP-OF-YOUR-SERVER>:9944 && \\
 export ETHEREUM_JSONRPC_TRACE_URL=http://<IP-OF-YOUR-SERVER>:9944 && \\
 export ETHEREUM_JSONRPC_TRACE_URL=http://<IP-OF-YOUR-SERVER>:9944 && \\
 export ETHEREUM_JSONRPC_WS_URL=ws://<IP-OF-YOUR-SERVER>:9944 && \\
 export ETHEREUM_JSONRPC_HTTP_INSECURE=true && \\
 export PORT=4000 && \\
 export BLOCKSCOUT_PROTOCOL=http && \\
 export POOL_SIZE=100 && \\
 export INDEXER_EMPTY_BLOCKS_SANITIZER_BATCH_SIZE=1000 && \\
 export DISPLAY_TOKEN_ICONS=true && \\
 export LINK_TO_OTHER_EXPLORERS=false && \\
 export DISABLE_EXCHANGE_RATES=true && \\
 export INDEXER_DISABLE_BLOCK_REWARD_FETCHER=true && \\
 export INDEXER_DISABLE_PENDING_TRANSACTIONS_FETCHER=true && \\
 export INDEXER_DISABLE_INTERNAL_TRANSACTIONS_FETCHER=true && \\
 export INDEXER_EMPTY_BLOCKS_SANITIZER_BATCH_SIZE=1000 && \\
 export LOGO=/images/PPYIcon.svg && \\
 export LOGO_FOOTER=/images/PPYIcon.svg && \\ 
 export NETWORK=POP Network
 export SUBNETWORK=Peerplays
```

8. **Start Smart contract verification micro-service with docker**\
   Use below command to start the docker:

```bash
docker run -p 8050:8050 ghcr.io/blockscout/smart-contract-verifier:latest
```

9. **Compile the application**\
   compile using the below command:

```bash
mix compile
```

10. &#x20;**Create and migrate database**

```bash
mix do ecto.create, ecto.migrate
```

11. **Installing node.js dependencies**\
    Install the required modules using below commands:

{% code overflow="wrap" %}

```bash
cd apps/block_scout_web/assets; 
npm install && node_modules/webpack/bin/webpack.js --mode production; 
cd -
cd apps/explorer && npm install; 
cd -
```

{% endcode %}

12. **Build static assets (if any)**

```bash
mix phx.digest
```

13. **Generate self signed certs for running locally (use certbot if deploying production)**\
    The required certificate can be generated using below commands:

{% code overflow="wrap" %}

```bash
cd apps/block_scout_web; 
mix phx.gen.cert blockscout blockscout.local; 
cd
```

{% endcode %}

14. **Start the server with tmux**\
    To have multiple sessions and to switch between, start the application with tmux.

{% code overflow="wrap" %}

```bash
tmux new -s blockscout
mix phx.server
Hold CTRL & Tap b, then d to detach from the tmux session
Reattach to tmux with - tmux attach -s blockscout
```

{% endcode %}

## E. Restoring from a PostgreSQL backup

First, create `blockscout` database dump using a **proper database user**. It's important because the application can be restored only using this data. Follow the below steps,

1. **Create a dump of the `blockscout` database using below command:**

{% code overflow="wrap" %}

```bash
pg_dump -F t blockscout > blockscout.tar
```

{% endcode %}

2. Drop the database and recreate an empty database from **`~/blockscout/`**

```
mix do ecto.drop, ecto.create
```

{% hint style="warning" %}
Restarting blockscout from the above location will result in error, as the database has not been migrated - Follow next step to restore the database.
{% endhint %}

3. **Restore the database using the dump taken earlier using below command:**

{% code overflow="wrap" %}

```bash
pg_restore --verbose --clean --no-acl -h localhost -U <db-user> -d blockscout blockscout.tar
```

{% endcode %}

The Application has to be restarted from here and it starts the indexing again from where it left off last in the database dump.


# Deploying Microservices to run Blockscout Explorer locally

The deployment uses Docker Compose

## Introduction

Docker Compose is a tool that helps you define and share multi-container applications. With Compose, you can create a YAML file to define the services and with a single command, you can spin everything up or tear it all down. The document explains about the steps to run blockscout locally in Docker containers with docker compose.

Click [here](https://github.com/docker/compose), to learn about docker compose in detail.

The detailed explanation about Docker-compose configuration is explained in the below link,

{% embed url="<https://github.com/blockscout/blockscout/tree/master/docker-compose#readme>" %}

## The brief explanation about docker compose configuration is explained below:

The blockscout explorer can be run locally in Docker container with docker compose.

## Deployment Steps

### Prerequisites

* Docker v20.10+
* Docker-compose 2.x.x+
* Running Ethereum JSON RPC client

## Steps

1. There are two ways in building the docker,&#x20;

* [Building Docker containers from source](https://github.com/blockscout/blockscout/tree/master/docker-compose#building-docker-containers-from-source-with-native-smart-contract-verification-deprecated)
* [Building Docker container](https://github.com/blockscout/blockscout/tree/master/docker-compose#building-docker-containers-from-source-with-native-smart-contract-verification-deprecated) from source with native smart contract verification (deprecated)

2. There are different [configs available for Ethereum clients](https://github.com/blockscout/blockscout/tree/master/docker-compose#configs-for-different-ethereum-clients). The repository contains built-in configs for different clients without a need to build the image.


# Glossary

## Glossary

|   Term  | Explanation                                                                                                                                                                                                                                                                                                            |
| :-----: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| VS Code | Visual Studio Code is a streamlined code editor with support for development operations like debugging, task running, and version control. It aims to provide just the tools a developer needs for a quick code-build-debug cycle and leaves more complex workflows to fuller featured IDEs, such as Visual Studio IDE |
| Hardhat | Hardhat is a development environment for Ethereum software. It consists of different components for editing, compiling, debugging and deploying your smart contracts and dApps, all of which work together to create a complete development environment.                                                               |
|         |                                                                                                                                                                                                                                                                                                                        |


# Howto & FAQ

The following list of commands helps the user to query the details in a node

1. Querying a node for PeerID

{% code overflow="wrap" %}

```sh
curl -H "Content-Type: application/json" -d '{"id":1, "jsonrpc":"2.0", "method": "system_localPeerId", "params":[]}' http://192.168.150.105:10933
```

{% endcode %}

2. Querying a node for block details using block hash

*Assuming that the chain is running on the localhost with default RPC port*

{% code overflow="wrap" %}

```shell
curl -H "Content-Type: application/json" -d '{"id":1, "jsonrpc":"2.0", "method": "eth_getBlockByHash", "params":["0x2f57daea521ff418d3ef3e35433264085a185c045969e1edcd1d04ad14220a3e", true]}' http://localhost:9944 | jq


```

{% endcode %}

3. Genesis mismatch

When we try to sync the chain,  we might get errors about geneis mismatch like below:

`Report 12D3KooWEyoppNCUx8Yx66oV9fJnriXwCcXwDDUA2kj6vnc6iDEp: -2147483648 to -2147483648. Reason: Genesis mismatch. Banned, disconnecting.`

This means that the genesis file of the original network is different  from the one available to the node being started. We must get the correct genesis file from the source location/chain. To generate genesis file on running node using `peerplays build-spec`

Example: `./peerplays build-spec --chain=testnet > genesis.json`

Than run node with parameter `--chain=genesis.json`

```bash
./peerplays --chain=genesis.json --base-path ./peerplays_data_dir/ --bootnodes /ip4/192.168.20.204/tcp/30333/p2p/12D3KooWEyoppNCUx8Yx66oV9fJnriXwCcXwDDUA2kj6vnc6iDEp
```


# Guide to backup and restore Blockchain data

## Introduction

The purpose of this document is to guide the user through the process of creating a backup and restoring blockchain data using Docker containers. In the below procedure, the "**discovery-archive-node-b**" container is focused which contains the entire blockchain data. The automation code and its notes are stored in the [README.md](https://gitlab.com/PBSA/infrastructure/devops-misc-issues/-/blob/main/production/blockchain/README.md?ref_type=heads) file.

{% hint style="warning" %}
The example commands in this guide assume that your project is deployed in the **`/runtime/peerplays2-testnet/`**&#x64;irectory. \
In case of a difference in the setup, please adjust the paths accordingly.
{% endhint %}

## Why do we need a Backup?

The blockchain technology is designed to provide decentralized, secure, and transparent record-keeping of transactions across the network. There are several reasons like data loss prevention, cybersecurity threats, disaster recovery, human errors, ensuring consistency, etc., which may be a threat to data. Thus, having a backup for blockchain data should be a fundamental practice to ensure data integrity, security, and continuity. The below steps provide a detailed explanation of backup creation and restoring blockchain data.

## **Steps to create a backup**

The procedure to create a backup involves 3 steps,

### 1. Stop the Docker Container

To optimize the RocksDB WAL journal, the first step is to restart the Docker container. After restarting, you should wait for at least 2 minutes before proceeding with the next steps. Then, stop the "**discovery-archive-node-b**" Docker container that holds the blockchain data.

{% hint style="danger" %}
Collect the finalized block height value before starting the backup and use the value as a check for successful restoration. &#x20;

**Check the section:** [https://app.gitbook.com/o/-Lpj4bCPw8iNnqCwrLCQ/s/PPsAwLpyOeItHVo4Fslw/\~/changes/6/peerplays-2.0/guide-to-backup-and-restore-blockchain-data#id-5.-checks-for-successful-restore](#id-5.-checks-for-successful-restore)
{% endhint %}

{% code overflow="wrap" %}

```bash
/usr/local/bin/docker-compose -f  /runtime/peerplays2-testnet/docker-compose.yaml restart discovery-archive-node-b 

sleep 120

/usr/local/bin/docker-compose -f  /runtime/peerplays2-testnet/docker-compose.yaml stop discovery-archive-node-b
```

{% endcode %}

### 2. Copy Data from Docker Volume

After stopping the container, copy the data from the Docker volume using the following command:

{% code overflow="wrap" %}

```bash
tar -cjvf /tmp/blockchain_backup.tar.bz /runtime/peerplays2-testnet/docker-volumes/archive-node-b 
```

{% endcode %}

### 3. Start the container

Once the data is copied, start the "**discovery-archive-node-b**" container to resume blockchain operations.

{% code overflow="wrap" %}

```bash
/usr/local/bin/docker-compose -f /runtime/peerplays2-testnet/docker-compose.yaml up -d discovery-archive-node-b
```

{% endcode %}

## Restoring from Backup

Restoring from a backup entails restoring the system or data to a previous state (state before the issue) by using a backup copy of the data.

## Steps to restore from backup

The procedure to restore from backup is explained below:

### 1. Stop the Running Blockchain Service

Before restoring, make sure to stop the blockchain service that is currently running. Run the below command on **each node**:

{% code overflow="wrap" %}

```bash
/usr/local/bin/docker-compose -f /runtime/peerplays2-testnet/docker-compose.yaml down
```

{% endcode %}

### 2. Delete Docker Volumes (Validators and Archive Nodes)

If necessary, delete all Docker volumes associated with validators and archive nodes. If required, create a backup of these volumes before deleting them (Follow the steps above to create any backup).

{% code overflow="wrap" %}

```bash
rm -rf /runtime/peerplays2-testnet/docker-volumes
```

{% endcode %}

{% hint style="info" %}
When restoring from scratch, docker volumes related to Validators and Archive Nodes required to be empty.&#x20;

**Example:** \
**I**f there is a existing chain with data and want to restore from backup, then the data need to be deleted before restoring operation.

As long as the chain is not running and there is no data present, it is not necessary to delete the docker volume.
{% endhint %}

### 3. Restore Data from Backup created on `discovery-archive-node-b` to docker volume of `discovery-validator-alice`

Copy the previously saved blockchain data from the Backup to the Docker volume directory for the "**discovery-validator-alice**" node.&#x20;

The copy command used in the backup section also can be used here.

{% code overflow="wrap" %}

```bash
# run on server with discovery-validator-alice

tar -xjvf tmp/blockchain_backup.tar.bz -C /
mv /runtime/peerplays2-testnet/docker-volumes/archive-node-b /runtime/peerplays2-testnet/docker-volumes/alice
```

{% endcode %}

### **4. Start the Blockchain Service**

After restoring the data, start the blockchain service again.&#x20;

{% code overflow="wrap" %}

```bash
# Run on each node with the related docker container name 

/usr/local/bin/docker-compose -f /runtime/peerplays2-testnet/docker-compose.yaml up -d "specify docker container"
```

{% endcode %}

The above steps can be followed to create a backup for the blockchain data, and the data can be restored if necessary.

### 5. Checks for Successful Restore&#x20;

It is important to collect the **finalized block height** number before starting the backup operation and after restoring from the backup. Compare the two values and it should be identical which will ensure a successful restoration.

There are two ways to find the finalized block height value. Use the below commands to get the number of blocks and use the values for comparison.

#### **Command 1:**

{% code overflow="wrap" %}

```bash
curl -sS -H "Content-Type: application/json" -d '{"id":1, "jsonrpc":"2.0", "method": "chain_getHeader"}' http://localhost:9944/ | jq '.result.number' | xargs printf '%d\n'
```

{% endcode %}

{% hint style="info" %}
<http://localhost:9944> -> Replace it with the address and port of the running node
{% endhint %}

**Output:**

The output will be just the number of finalized blocks.

{% code overflow="wrap" %}

```bash
2022
```

{% endcode %}

#### **Command 2:**

```
docker logs "container name"
```

**Example:**

{% code overflow="wrap" %}

```bash
docker logs discovery-validator-alice 
```

{% endcode %}

**Extracted Output for reference:**

{% code overflow="wrap" %}

```bash
2024-01-16 15:07:48 💤 Idle (10 peers), best: #2025 (0x08c3…8370), finalized #2022 (0xe1d3…c408), ⬇ 19.8kiB/s ⬆ 19.8kiB/s
```

{% endcode %}

Follow these steps carefully to ensure the integrity of your blockchain data.


# Key Metrics

## Monitoring setup

Please refer to the substrate node guide to set up monitoring.

{% embed url="<https://docs.substrate.io/tutorials/build-a-blockchain/monitor-node-metrics/>" %}

## Hardware requirements

Before starting the node, check that the system has at least 2GiB of free space

During node startup pay attention to the host performance check there will be entries in the log with the current hardware score

&#x20;   🏁 CPU score:\
&#x20;   🏁 Memory score: \
&#x20;   🏁 Disk score (seq. writes): \
&#x20;   🏁 Disk score (rand. writes):&#x20;

In case of insufficient resources, there will be a message:

{% hint style="danger" %}
&#x20;⚠️ The hardware does not meet the minimal requirements for the role of 'Authority'.
{% endhint %}

## Important metrics to monitor

1. Block construction time should not be more than 5 seconds

**Metrics:**&#x20;

```
substrate_proposer_block_constructed_bucket
```

**Usage example with Prometheus:**

{% code overflow="wrap" %}

```promql
histogram_quantile(0.90, sum(rate(substrate_proposer_block_constructed_bucket[5m])) by (le))
```

{% endcode %}

2. 'Finalized' chain shouldn't lag behind 'best' for more than 10 blocks ('best' - 'finalized' < 10)

**Metrics:**

```
substrate_block_height{status="best"} 
substrate_block_height{status="finalized"}
```

**Usage example with Prometheus:**

{% code overflow="wrap" %}

```promql
sum by (name, instance) (substrate_block_height{status="best", chain="testnet"}) - sum by (name, instance)(substrate_block_height{status="finalized", chain="testnet"})
```

{% endcode %}

3. Number of connected peers should be more than 0 and depends on network size. On large networks, it will be limited by libp2p default value of 300.

**Metrics:**

```
substrate_sub_libp2p_peers_count
```


# Solidity Smart contracts

## Description

A smart contract is a self executing program that automates the actions required in an agreement or contract. After the task completion, the transaction is trackable and irreversible.

## What is a Solidity Smart contract ?

A solidity smart contract provide a highly secured digital transactions which doesn't involve the third parties.

Solidity is an object-oriented programming language created specially by the Ethereum Network Team for constructing and designing smart contracts on Blockchain platforms.

For Peerplays 2.0 there are two methods adapted to deploy the smart contract,

{% content-ref url="/pages/wgjiK3Ha3PsdULGOdrmW" %}
[Solidity smart contract deployment using REMIX IDE](https://pao.peerplays.com/peerplays-2.0/solidity-smart-contracts/solidity-smart-contract-deployment-using-remix-ide)
{% endcontent-ref %}

{% content-ref url="/pages/wPep5zBPfH54KBAmqEQR" %}
[Solidity smart contract deployment using hardhat](https://pao.peerplays.com/peerplays-2.0/solidity-smart-contracts/solidity-smart-contract-deployment-using-hardhat)
{% endcontent-ref %}


# Solidity smart contract deployment using REMIX IDE

## Deployment using REMIX IDE

1. Open Remix IDE using the below link, <https://remix.ethereum.org/#lang=en&optimize=false&runs=200&evmVersion=null&version=soljson-v0.8.18+commit.87f61d96.js>. The default workspace looks similar like below,

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2F9urX0q5MdwOOy84yqmIk%2FDefault-workspace.JPG?alt=media&amp;token=efec5d4f-bdc2-4ea8-a942-2674633136c8" alt=""><figcaption><p>Default workspace</p></figcaption></figure>

2. A) Next step is to create a workspace, click on the **Workspace** option and select **create -> create workspace**. This will open a new tab to choose the type of workspace as required.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2FvvRhHmuD0TnfXu0ue2HU%2Fworkspace-create-1.jpg?alt=media&amp;token=af0b247f-50a2-430f-9cb4-4fc871978cf8" alt=""><figcaption><p>Create new workspace</p></figcaption></figure>

B) The new tab has various **Template** options to choose for the new workspace. The option selected here is **Open Zeppelin ->ERC20.** Open Zeppelin is the open source library/framework mainly used in the smart contract deployment for ethereum. It provides a set of audited and reusable contracts for the developers.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2Fi00Q0ZopKdLDIpgURfDk%2Fworkspace-creation-2.jpg?alt=media&amp;token=5b95164b-a2a2-4115-a580-dea25f172200" alt=""><figcaption><p>Choose Template for workspace</p></figcaption></figure>

C) Click on **OK**, the next page has some customizable template options for the new workspace. Choose the required options and click **OK** to create the workspace.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2Fmh6ggI3xheIF72K7JmXA%2Fworkspace-creation-3.JPG?alt=media&amp;token=973e6afc-ae0b-4be1-be87-9a868fc3acd5" alt=""><figcaption><p>Template customizable options</p></figcaption></figure>

{% hint style="info" %}
The template settings can be modified anytime after the workspace creation too.&#x20;
{% endhint %}

Now, the **Workspace** is created successfully.

D) The new workspace created will be similar to the below page and it has its own files and folders.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2FpDMvArUN6dmk1MgNutqM%2FOpenziplin-workspace.JPG?alt=media&amp;token=e3cbc376-c27a-4e3b-a10c-384e3bdbed89" alt=""><figcaption></figcaption></figure>

3. There is one more application called **MetaMask**, which is required to begin the smart contract deployment. If the user has an existing MetaMask wallet then it can be used or else the new account has to be created. The steps to deploy MetaMask is explained in the below section.

{% content-ref url="/pages/FWdZvKmxLT1BiYHyV2SZ" %}
[Metamask Deployment](https://pao.peerplays.com/peerplays-2.0/solidity-smart-contracts/metamask-deployment)
{% endcontent-ref %}

4. Once the MetaMask configuration is completed, switch back to the REMIX IDE workspace to resume the steps.
5. Choose **Deploy & Run Transactions** tab from the left pane of the workspace. To select the **Environment** option, click on the drop-down menu to choose **Injected provider - MetaMask.**

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2FLk9P8RbY11pIlW9Mguzm%2FEnv-inject-provider.JPG?alt=media&amp;token=e00ec222-491c-483a-a5ae-7d16f9e574bb" alt=""><figcaption></figcaption></figure>

6. A) Next, a new tab will prompt to connect with Metamask wallet. Choose the desired MetaMask account that has to be connected with the Remix IDE workspace.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2FcLNrL4gnRSHqpgfcG00B%2Fconnect-with-metamask.JPG?alt=media&amp;token=07cb4bc2-e90d-4829-a0a9-ebb5da3d98f6" alt=""><figcaption></figcaption></figure>

B) Click on **Next** to see the below screen and provide permission for the REMIX IDE to view the wallet details. Finally, click on **Connect** to complete the environment setup.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2F9YgiHpVsiOO2p2cERVRx%2Fconnect-with-metamask-connect.JPG?alt=media&amp;token=fb28dfe6-cab6-4460-9725-028125f19066" alt=""><figcaption></figcaption></figure>

C) Now, the MetaMask wallet is connected with the REMIX IDE. After successful connection, the Metamask wallet address will be populated in the setup details. Also, the wallet and its balance will be visible from the IDE.&#x20;

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2F1ZkkvYPzqOlBINqhma1i%2FRemix-metamask-connected.JPG?alt=media&amp;token=923ee797-f5fd-4d4f-b6d4-6aeb874964cb" alt=""><figcaption></figcaption></figure>

7. Switch to OpenZeppelin workspace to begin with the smart contract deployment. From the list of folders, select **contracts** and click on **MyToken.sol** which has the default configuration.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2FiaZi8qc7ajBIa7G9jTQg%2Fwork-space-token.JPG?alt=media&amp;token=d960886d-3769-468f-ad6f-e832617968ba" alt=""><figcaption></figcaption></figure>

8. The contract should be modified based on the requirements. The boiler plate for **MyToken.sol** is given below:

{% code overflow="wrap" %}

````solidity
```remix-solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract MyToken is ERC20 {
    constructor() ERC20("TEST_PPY_2.0", "TEST") 
    {
    _mint(msg.sender, 1000000000000000000000);
    }
}
```
````

{% endcode %}

The given example is used to mint 1000 token and based on user option the value can be modified.

{% hint style="info" %}
The token value must be followed by 18 Zero's. Because, the default setting for Ethereum minting is the values must be followed by "0"  up to 18 decimal counts.
{% endhint %}

The contract is modified and it is ready to be deployed. Click on **CTRL+S** to complete the compilation, only then the updates will be reflected.

One more option to compile is, choose **Solidity Compiler** option and select compile **MyToken.sol** button to finish compilation.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2FZ7pjfr9DCadcMuR7Z6oS%2Fcompile-tokens.JPG?alt=media&amp;token=3cff7926-a18d-4daa-a179-7ea7ca68af89" alt=""><figcaption></figcaption></figure>

9. Next, add the contract script in the Environment value and contract deployment is one step away!

A) Switch to **Deploy & Run Environment** option, choose **MyToken - contract/MyToken.sol** option from the drop down list.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2FfQnpZqyQCjwGbrS2MGy7%2Ftoken-addition.jpg?alt=media&amp;token=4a7b7367-0d85-4740-a17b-106686c71c67" alt=""><figcaption></figcaption></figure>

B) Click on **Deploy**, the MetaMask window will be prompted to complete the transaction. Click on **confirm** to finish the contract deployment.&#x20;

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2F3HQESm3eh7Vwedwzar1c%2Fdeploying-prompted.JPG?alt=media&amp;token=f06af9b2-00fa-4c4d-9188-de833cb7b290" alt=""><figcaption></figcaption></figure>

10. After confirmation, the deployment process begins and finally the contract deployment will be completed. The contract address is generated and click on copy icon to have a copy of address for verification.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2FSORUlXP22koCdQhkN0yO%2Fcontract-deployed.JPG?alt=media&amp;token=9e65b28c-c3d5-46e5-9205-da3fb40ba568" alt=""><figcaption></figcaption></figure>

The contract address will be similar to the below format:

````
// contract address example
```remix-solidity
0xde1aF1323bD6d092a9199d8f050A9806bcb57530
```
````

Solidity smart contract deployment using REMIX IDE is successful! ✅


# Solidity smart contract deployment using hardhat

## Deployment Using Hardhat

There are three steps involved in the contract deployment using Hardhat,

1. Create a new Hardhat project
2. Configure Hardhat project with targeted blockchain
3. Compile and deploy

## Requirement specification

1. Visual Studio - VS code
2. Hardhat&#x20;

## Software Installation

**A) Setup the Hardhat environment in the VS code:**

Follow the step-by-step procedure explained in the tutorial provided by Hardhat,

{% embed url="<https://hardhat.org/hardhat-runner/docs/guides/project-setup>" %}
Guide to install Hardhat
{% endembed %}

Now, the VS code will be installed with Hardhat framework and ready to begin with smart contract deployment.

## Solidity Smart contract Deployment using Hardhat

The steps to deploy smart contract using Hardhat is explained below,

1. Login to the VS code environment which has the Hardhat framework installed with necessary files and folders to access.
2. Next, OpenZeppelin is an external library which should be present in VS code for contract deployment and it can be installed using below command:

```visual-basic
npm install @openzeppelin/contracts
```

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2FyGzMLz0cUMwIYqR8M2wa%2FVS-code-file-structure.jpg?alt=media&amp;token=3b03d885-cf49-4f40-830f-c4dbc8ddc6f8" alt=""><figcaption><p>File structure</p></figcaption></figure>

The **`TEST_ERC20.sol`** is the script provided by OpenZeppelin library to provide the desired minting value.

3. There are two files used for contract deployment&#x20;

&#x20;        **A.** hardhat\_config.ts - Config file

&#x20;        **B.** deploy\_config.ts - Deploy script

Example script structure is provided below:

The user has to provide the account's private key for **`accounts`** value in the **`hardhat_config`** file.&#x20;

{% code overflow="wrap" %}

```tsconfig
// Hardhat_config
import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";

const config: HardhatUserConfig = {
  solidity: "0.8.19",
  defaultNetwork: 'peerplays',
  networks: {
    peerplays: {
      url: 'http://96.46.48.200:9933',
      accounts: [`0x` + process.env.PRIVATE_KEY], // Account's private key is added
      chainId: 33,
    },
  }
};

export default config;
```

{% endcode %}

Ethers library is provided by Ethereum and it has the necessary functions required for calls. Deploy script is required to deploy smart contract.&#x20;

{% code overflow="wrap" %}

```tsconfig
// Deploy_config
import { ethers } from "hardhat";

async function main() {

  const myToken = await ethers.deployContract("MyToken");

  await myToken.waitForDeployment();

  console.log(`MyToken deployed to: ${myToken.target}`) // Mention the Contract name used
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });
```

{% endcode %}

4. The command to deploy contract is given below:

```
npx hardhat run scripts/deploy.ts
```

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2FmwKAL23TYhKVK0DR5O4s%2FHardhat-deploy-image.png?alt=media&amp;token=ea69ea4e-6721-486b-bab8-c8b0083a5860" alt=""><figcaption></figcaption></figure>

The contract address will be generated with deployment successful message.

Solidity smart contract deployment using Hardhat is successful! ✅


# Metamask Deployment

## Introduction

Metamask is a cryptocurrency wallet used to interact with the Ethereum blockchain. Metamask is a  non-custodial wallet, which means that the crypto owner only will hold their private key and therefore their funds. There is no third party involved in any transactions as it has the decentralized wallet. This wallet securely connects the users with different blockchain-based applications and decentralized web.&#x20;

## Benefits

1. Safe and secured wallet to manage crypto investments.
2. User has the complete access to their funds and transaction as there is no middle man involved.
3. Offers advanced security features to protect the digital assets against phishing attacks.

## Limitations

1. By default, the wallet only comes with Ethereum network and user has to add additional networks manually.
2. Metamask doesn't support Bitcoin.

## Steps to add Peerplays2.0 network in Metamask

1. Download the browser extension for MetaMask based on the choice of web browser to create a wallet. The below link direct to the MetaMask webpage,\
   <https://metamask.io/>
2. After **successful wallet creation**, the user will be directed to MetaMask account with Ethereum Mainnet as default network.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2Fuv8JwR46aAyhYR29oCmx%2FAccount-creation.JPG?alt=media&amp;token=32deec33-04e5-42bd-bd59-929b665c2e31" alt=""><figcaption><p>Default account</p></figcaption></figure>

The user must add the required network to the MetaMask wallet to access it.

3. First, if the user wants to create a new account / import account / to use hardware wallet, click on the drop-down option from the account name and select necessary options.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2FH0PsAsQc39GeYR46BWEl%2FAdd-account.JPG?alt=media&amp;token=ffc23a09-6175-4206-8945-fd932784937d" alt=""><figcaption><p>Adding New account</p></figcaption></figure>

4. Next, with the selected account:\
   A) Click on the dots at the top right corner and choose **Settings** option, then select **Network tab** on the left pane of settings page.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2FEdGR2sGP9RXN61DCtIB1%2FSettings-network.JPG?alt=media&amp;token=a5365b48-4d99-4a07-aff5-b866c2898d13" alt=""><figcaption><p>settings option</p></figcaption></figure>

Click on "**Add a network**" button to input the values.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2FwVMMeTAoIZhFcaUbmhEW%2FAdd-network-2.JPG?alt=media&amp;token=40b809f9-55fd-4f09-9f90-b98fc27bc6e6" alt=""><figcaption><p>Add network option</p></figcaption></figure>

B) Otherwise, click the **drop down option** from the network name as highlighted below and click on **Add network** button.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2F4uoJP5aVAZm9gO4fi1vw%2FAdd-network-1.JPG?alt=media&amp;token=32ca82f6-aad8-41f8-a679-9071e7d04340" alt=""><figcaption><p>Add network option</p></figcaption></figure>

5. After selecting the "Add network" option, the following tab will be opened to input detail about the network.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2FKGQFOXh7lzmCZQCCbb0b%2Finput-details-manually.JPG?alt=media&amp;token=f742221a-2240-459d-966e-90257d14fa60" alt=""><figcaption><p>Input options</p></figcaption></figure>

6. Enter the exact values of your network manually and click on "**Save**" button to reflect the update.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2FIJ1r91GTcQilAXCgnkYL%2Fmanual-iput-details.JPG?alt=media&amp;token=06b3173d-6c71-49d1-9cd6-be84470eb470" alt=""><figcaption><p>Input values for network manually</p></figcaption></figure>

## Network Information

|       Name      |                 Value                |
| :-------------: | :----------------------------------: |
|   Network Name  |             Peerplays 2.0            |
|   RPC Endpoint  |       <http://96.46.48.73:9933>      |
|     Chain ID    |                  33                  |
| Currency Symbol |                 TEST                 |
|  Block Explorer | <http://96.46.48.73:3000/#/explorer> |
|      Bridge     |   <https://portfolio.metamask.io/>   |

7. Now, the new network is successfully added in the wallet for use.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2FKw8Sp9vkYYcmhIjqod5l%2Fnw-added-sucessfully.JPG?alt=media&amp;token=3dd98915-dd21-4c01-83a5-8e94c00a1a59" alt=""><figcaption><p>Network added successfully</p></figcaption></figure>

8. Click on the three dot on the top right corner of the page to explore the options available for the accounts.

<figure><img src="https://809720161-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPPsAwLpyOeItHVo4Fslw%2Fuploads%2FHAYoqGm1cT9IeabKHf3T%2Fsettings.JPG?alt=media&amp;token=22840619-4cc2-44fc-897b-313d61ed3994" alt=""><figcaption><p>Account explore options</p></figcaption></figure>

MetaMask Deployment is successful ✅


