# Introducing Phron AI

<figure><img src="/files/PL6TOkSx8PEYTZZQaq7b" alt=""><figcaption></figcaption></figure>

Phron AI brings a **Prompt-Based AI-Orchestration Blockchain Enabler**, facilitating the growth and expansion for users, developers and ecosystems. By integrating a **Multi Layer-Based dApp Builder**, enabled through our SuperApp, **openPhron**:

* **Automated and Smarter dApps**
* **AI Agent Management for your on-chain products.**
* **Efficient Chain Agnostic deployment.**

AI-powered blockchain tools can enhance security, efficiency, and accessibility through automated dApp creation. By leveraging AI-driven optimization, Phron AI enables the seamless deployment of dApps, smart contracts, AI Agents, and AI-powered oracles through a simple prompt-based system.

{% hint style="success" %}
&#x20;**Key Takeaway:** Phron AI is at the forefront of a new generation of AI-Infra Builder, paving the way for more intelligent, robust, and user-friendly creation system for dApps.
{% endhint %}


# AI as the Core Infrastructure Layer

Phron AI’s ecosystem is built around our main app, **openPhron**, a unified platform that streamlines the automation for blockchain development.&#x20;

By combining AI-driven dApp Creation, smart contract deployment, AI oracles integration, and AI agent management in a single environment, openPhron eliminates the fragmentation developers typically face.\
\
Compounding our **three primary components**, each contributing to a holistic AI-blockchain environment:

<figure><img src="/files/iM1Zlhr6ziZFzPuygmFo" alt=""><figcaption><p>Phron AI's AI-Infra Blockchain Solutions</p></figcaption></figure>

### [**openPhron** ](/openphron)

From natural language to a complete product, **openPhron** is our system that **automates smart contract creation** and fuels AI-native dApps, ensuring developers can quickly build, test, verify, audit, launch and utilize AI-driven decentralized applications.

### [PhronZero Prototype](#phronzero-prototype)

The foundational blockchain database. Providing the allocation for data provided from AI Oracles and AI Agents, through ML and Neural Network systems.&#x20;

### [**PhronZero** ](/phronzero)

Our AI-Infrastructure-as-a-Service (AI-IaaS) solution enabling users to **instantly deploy AI-optimized subchains** and benefit from advanced features like AI Oracles.&#x20;


# openPhron

Our SuperApp

**openPhron** is Phron AI's SuperApp, serving as the **automation engine** for Phron AI’s ecosystem, focusing on streamlined **smart contract generation and dApp creations** through accessible development workflows. Allowing users to interact **from Natural Language to full interactions on-chain** with simple steps:

* **Automated dApp and Smart Contract Creation**: Generate specialized contracts via an intuitive interface through natural language and AI-driven templates.
* **Developer Ecosystem**: Advanced ecosystem for better precision, AI Oracle implementation, libraries, and resources to build AI-enabled apps on top of all the available blockchains.
* **Chain-Agnostic**: Supports multi-chain deployments, letting developers bridge their dApps to multiple ecosystems seamlessly
* **AI-Agent Centric**: Provides the user the ability to manage their products through AI-Agents, reducing the interaction and knowledge entry-barrier for everyone.
* **AI Oracles**: Optimizing smart contracts through data-driven enabled Oracles, trained through LLM systems for expanded functionalities.

<figure><img src="/files/h9ZrYcRkzRfvbrJnry9g" alt=""><figcaption><p>openPhron Workflow</p></figcaption></figure>

## Deploy on:

<figure><img src="/files/KrOvRw1XNjt6GxLLpbHy" alt=""><figcaption></figcaption></figure>


# PhronZero Prototype

Our Blockchain Database

**The PhronZero Prototype** is the blockchain database of the ecosystem. It integrates the different functionalities located from AI Oracles and AI Agents that are available in openPhron, making it a complementary addition to their system.&#x20;

* **AI-Database Management**: Incorporates ML and Neural Networks algorithms to manage the data provided by the results given through the AI Oracles and AI Agents.
* **High Throughput**: Built to accommodate AI-scale transactions and complex smart contract operations.
* **Adaptive Security**: Advanced staking and node validation processes reduce attack surfaces while maintaining decentralization.

{% hint style="success" %}
**Real-Time Testnet Data - 6 Months Uptime**\
Explore live metrics on the official [**PhronScan Testnet Explorer**](https://testnet.phronscan.io).
{% endhint %}

<table><thead><tr><th>Metric</th><th width="249"> Value</th><th data-hidden></th></tr></thead><tbody><tr><td><strong>Block Time</strong></td><td>~1 second</td><td></td></tr><tr><td><strong>TTF</strong> <br><strong>(Time-to-Finality)</strong></td><td>~1 second</td><td></td></tr><tr><td><strong>Gas Fees</strong></td><td>~USD$ 0.0003</td><td></td></tr><tr><td><strong>TPS (Transactions/Second)</strong></td><td>60,000 TPS</td><td></td></tr></tbody></table>

{% hint style="info" %}
**Did You Know?**\
The PhronZero Prototype enables **intent-based** smart contracts, allowing AI-driven logic to adjust on-the-fly based on real-time data.
{% endhint %}


# PhronZero

AI-Infrastructure-as-a-Service

**PhronZero** is a **AI-Infrastructure-as-a-Service (AI-IaaS)** solution that lets projects quickly spin up **AI-optimized blockchains**. Based on the AI Contribution Layer tested, introducing specialized functionalities:

* **Masterclasses**: Spin off subchains through the automated systems.
* **Node-Block-Sharing**: Efficient replication of validated blocks across nodes to reduce redundancy and boost performance. Reducing costs for new operators, allowing Node Lending Mechanisms.
* **Adaptive AI Staking**: Stakers benefit from dynamic rewards, adjusted by AI models that evaluate network load, participation, and other metrics.

<figure><img src="/files/RBCPm6cg1CqL894JzIJ0" alt=""><figcaption><p>PhronZero Schematic</p></figcaption></figure>

{% hint style="success" %}
**Instant Deployment**\
Launching a specialized AI subchain through PhronZero can happen **in minutes**, with pre-configured smart contracts and governance parameters.
{% endhint %}


# Phron AI Node Sale

The **Phron AI Ecosystem** **Node Sale** offers an exclusive opportunity to own a Phron AI node license. **Only a limited number of nodes** are available, each offering **high-yield APR** plus additional **lifetime** benefits:

* **License Ownership**: Secure a **lifetime access** license to openPhron.
* **High Yield**: Earn up to **318% APR** as a node operator, with a sustainable system to provide rewards forever.
* **Extra Farming Rewards**: Benefit from **100% extra** farming rewards by staking your node license.
* **First Month Managed by Us**: No need to run the node yourself for the first month. **Phron AI handles it** on your behalf.
* **Cloud-Node Service:** Delegate your nodes, paid directly with your rewards. No need to make extra bothersome monthly payments to keep earning.
* **Nodes with Value:** Rewards =/= Assets. Your node holds assets WHILE providing you **lifetime** daily rewards.

{% hint style="success" %}
**Node Sale Whitelist**\
Register now at [nodes.phron.ai](https://nodes.phron.ai) to get a **15% discount** and a guaranteed spot in the upcoming sale.
{% endhint %}


# Node Utility

Phron AI nodes lie at the **core** of the network’s infrastructure, ensuring **robust performance**, **security**, and **flexible AI-centric services** across the entire **openPhron** GPU ecosystem. Alongside validating transactions, nodes provide essential support for both the **Phron AI-Contribution Layer** and **PhronZero**, while granting the Node License Operators an exclusive **lifetime subscription** to openPhron.

### Lifetime Access to openPhron

While earning from the GPU power provided for the smooth operations of openPhron, one of the greatest utilities tied to operating a Phron AI node is the **lifetime subscription** to **openPhron**:

* **Available Deployments**: Seamlessly launch automated smart contracts, dApps, or entire blockchains via openPhron’s intuitive interface—no extra licensing fees.
* **AI Agent System**: Integrate autonomous agents into your solutions, combining the power of AI with on-chain logic for advanced workflows.
* **Early Access to Add-ons & Features**: Node operators often receive exclusive or early access to new openPhron features, ensuring they stay at the cutting edge of AI-blockchain innovation.

### Supporting Phron AI-Contribution Layer

#### Maintaining Network Integrity

* **Consensus Enforcement**: Nodes participate in the Phronesis Consensus, helping validate and finalize blocks with AI-driven checks and optimizations.
* **Oracle-Verification Reliability**: By processing, relaying, and confirming transactions, nodes keep the network stable, secure, and censorship-resistant.
* **AI Data Processing**: The AI-optimized design leverages node resources to execute real-time computations, detect anomalies, and adapt block production to network conditions.

#### Enabling Scalable AI Workloads

* **High-Throughput Support**: Each node contributes to the chain’s capacity for intensive AI tasks, offering the throughput needed for advanced dApps.
* **Network Redundancy**: Distributed node architecture ensures minimal downtime and efficient load balancing, critical for large-scale AI deployments.

### PhronZero Infrastructure

As **PhronZero (Infra-as-a-Service)** evolves, nodes will also serve as **infrastructure** for these specialized subchains:

* **Infra Node for Custom Chains**: Node operators can provide computational services, data validation, and consensus participation for newly deployed PhronZero subchains.
* **AI-Focused Features**: Advanced functionalities rely on underlying node support to execute and coordinate seamlessly.
* **Resource Aggregation**: Nodes help pool computational, storage, and networking resources essential for hosting AI workloads across multiple independent PhronZero subchains.

{% hint style="info" %}
**Future-Ready:** PhronZero’s modular design makes it easy to add specialized features or scale existing ones. Nodes underpin these expansions by providing the necessary computing power and data integrity.
{% endhint %}


# Node Tiers

### Coming Soon

{% hint style="info" %}
**Note**: If a tier sells out quickly, you may not have another chance to purchase nodes at that price point. Stay updated on availability to secure your node license within your preferred tier.
{% endhint %}


# FAQs

## Node Sale FAQ

<details>

<summary><strong>Q:</strong> What is the Phron AI Node Sale?</summary>

**A:** The Node Sale is a limited-time opportunity to purchase a Phron AI Node License. Owning a license generates benefits from the GPU provided for the smooth operations of openPhron, while granting you lifetime access to its services, special rewards, and direct participation in securing the Phron AI ecosystem.

</details>

<details>

<summary><strong>Q:</strong> How many Node Licenses are available?</summary>

**A:** The total number of Node Licenses available is 30,000 Nodes.&#x20;

</details>

<details>

<summary><strong>Q:</strong> What benefits do I receive by purchasing a node license?</summary>

**A:** By acquiring a node license, you gain:

* **Lifetime Access** to openPhron
* **Up to 318% APR** potential earnings (see Farming Rewards for more info)
* **100% Bonus** by staking your license, doubling your farming rewards
* **First Month Free** node hosting (Phron AI runs it on your behalf)

</details>

<details>

<summary><strong>Q:</strong> Is there a discount or whitelist for the Node Sale?</summary>

**A:** Yes! By registering for the whitelist at [nodes.phron.ai](https://nodes.phron.ai) or by using a Referral Link provided to valuable Community Members or Key Opinion Leaders (KOLs), you receive a **15% discount** on the Node Sale. This also guarantees your spot when the sale goes live.

</details>

<details>

<summary><strong>Q:</strong> Do I have to run the node myself?</summary>

**A:** The **first month of hosting is handled by Phron AI at no cost**. Once the month expires, it's up to you. If you have the technical expertise and hardware, you can run the node directly. Alternatively, you can delegate your node license to a hosting service, where experts will maintain and operate it for you.&#x20;

</details>

<details>

<summary><strong>Q:</strong> How do I purchase a node license?</summary>

**A:** You just need to follow the next steps:\
1\. Visit the official Node Sale portal at [nodes.phron.ai](https://nodes.phron.ai). \
2\. Connect your wallet address to verify your whitelist status (if applicable). \
3\. Complete the purchase using the supported payment methods. \
4\. Receive your license key and set up your node (or delegate it).

</details>

<details>

<summary><strong>Q:</strong> How long will the Node Sale last?</summary>

**A:** The sale will run until all licenses are sold out. Given the limited supply and high demand, it's advised to join the whitelist and secure your node license early.

</details>

<details>

<summary><strong>Q:</strong> Do I need to pay every month to keep my Node running?</summary>

**A:** No, once you decide to delegate your node for our Cloud-Node Service, all expenses will be directly deducted from your rewards. Reducing the hassle and keeping your Node Purchase a One-Time Payment.

</details>

<details>

<summary><strong>Q:</strong> How much is the Cloud-Node Service?</summary>

**A:** Dependant on the volume and computational power required, it may varie between US$ 15.00 and US$ 30.00 per Node. To facilitate your experience, the costs will be taken directly by the rewards, making it easier for you.

</details>


# Farming Rewards

To reward community's participation, Phron AI incorporates the **Farming Rewards** program. We’ve allocated **5% of the total $PHRON supply** to reward both everyday token holders and dedicated node operators who stake their tokens to secure and grow our network. Here’s an example of how it will work:

| **Participation Type** | **Example APY** | **Bonus Factor** |
| ---------------------- | --------------- | ---------------- |
| Regular Staker         | \~100%          | —                |
| Node Operator          | \~200%          | 100% Bonus       |

#### Mechanics of the Program

1. **Designated Token Pool**
   * We allocate a fixed **5% of all $PHRON** to a dedicated rewards fund.
   * This pool is released gradually to ensure fair distribution over time.
2. **Staker vs. Validator**
   * **Regular Stakers** lock up tokens to earn an estimated **10% APY** (subject to governance and participation).
   * **Node Operators** receive a **100% bonus** on top of the APY rate, effectively **doubling** their rewards, providing an additional incentive on the Node Operator Role.
3. **Re-Staking for Growth**
   * Earned rewards can be **re-staked** for compounding benefits.
   * This cyclical process supports continuous growth and encourages participants to maintain their stake for the long haul.


# Roadmap

**Q2 2023 - Q2 2024**

* [x] AI-Infra R\&D Completed
* [x] AI Contribution Layer Prototype Completed

**Q3 2024**

* [x] Phron AI Ecosystem introduced to the Public
* [x] AI Contribution Layer - Testnet Launch
* [x] AI Contribution Layer - Audit by Hacken&#x20;
* [x] Gamified Airdrop Campaign (Phrony The Game) Launched

**Q4 2024**

* [x] PhronZero (AI-IaaS) Architecture Created
* [x] Phron AI (AI-Ecosystem Builder) Architecture Created&#x20;

**Q1 2025**

* [x] Phase 1: Natural Language Smart Contract Deployment
* [x] Phase 2: AI Agent Management System

**Q2 2025**

* [x] Phase 3: UI/UX Optimization
* [x] Deploy & Score Campaign

**Q3 2025**

* [ ] Phase 4: Complete dApp Deployment
* [ ] Staking and LP Farm launch
* [ ] TGE - ZPHR Token launch
* [ ] Launch of Freemium Model

**Q4 2025**

* [ ] PhronZero (AI-IaaS) Completed
* [ ] Phase 5: Plug-n-Play Market Products for Smart Contract and dApp Deployment

**Q1 2026**

* [ ] PhronZero Mainnet Launch
* [ ] Phase 6: Prompt-based Layer 1 Creation


# Official Links

Below are the trusted and verified channels for all things Phron AI. Check them out to stay up-to-date and receive continuous updates!

* **Phron AI Website**: <https://phron.ai>
* **Phron AI Whitepaper:** <https://phron.ai/whitepaper_pure.pdf>
* **X**: <https://x.com/phron_ai>
* **Telegram**: <https://t.me/PhronAI_Portal>

> **Tip**: Following our X account and joining the Telegram group ensures you’ll always receive the latest announcements, community updates, and support resources.


# Learn


# Why Build on Phron.ai?


# Performance & Scalability

Through Phronesis performance, alongside tool ecosystems provided, our Phron AI Layer 1 provides the required metrics for an optimized usage of resources for on-chain activity. It aligns with the functionalities required by any dApp that might come on board.


# AI-Optimized Consensus

Through the implementation of


# Flexible Use Cases

Companies, projects and individuals that develop Smart Contracts and AI projects will have a place to expand their reach through openPhron and PhronZero, providing a marketplace for the sale of their products, and an infrastructure to grow rapidly their audience through mass distribution.


# Core Concepts


# AI-Backed Consensus

Consensus powered through the utilization of encoder-decoder convolutional neural networks (CNN). This process is achieved through the implementation and communication between the nodes, considering each node a CNN that communicates with the other nodes through the Consensus Mechanism.


# DAG (Directed Acyclic Graph)

Data structure that represents a network of nodes with directed edges connecting them, where the connections have a one-way direction and do not form any cycles. This means you can only travel in one direction through the graph, and there’s no way to loop back to the same point. DAGs are widely used in various fields.


# Proof of Stake (PoS)

Consensus mechanism used in blockchain networks to validate transactions and create new blocks. Unlike Proof-of-Work (PoW), which requires miners to solve complex computational problems, PoS relies on participants staking—or locking up—their cryptocurrency to gain the chance to validate transactions and earn rewards.


# Phron.ai Ecosystem & Use Cases


# Ecosystem Overview

Phron AI is building a broad ecosystem with over 45 partnerships to strengthen its AI-powered blockchain platform, drawing support from companies like Hacken, DeXe Protocol, and Kredly. Each of these partnerships brings unique expertise to the table, from cybersecurity to DeFi applications, all helping Phron AI achieve a powerful blend of scalability, security, and interoperability within its blockchain.

The platform centers on an AI-driven Proof-of-Learning consensus mechanism, which actively adjusts to network demands, making it highly adaptable and responsive. This innovation supports a streamlined user experience through tools like PhronScan, PhronSwap, and PhronBridge, which are designed to simplify blockchain interactions and make the technology accessible for a wide range of users and applications.

As a Layer-1 blockchain with plans to introduce a Layer-0 architecture alongside an AI Web 3.0 Marketplace, Phron AI’s partners help the project deliver on its ambitious goals of flexibility, security, and enhanced performance. Together, this collaborative network is key to Phron AI’s mission to create blockchain solutions that can adapt in real time to user needs and market changes, aiming for a user-friendly and highly scalable system built on robust AI innovation.

<br>


# Example Use Cases

* List a few potential or existing use cases on[ Phron.ai](http://phron.ai), such as:
* Blockchain Security: Hacken, Solidproof
* Cloud Computing: VPS AI, Cluster Protocol, Power AI
* DeFi Platforms: DeXe, Kredly, VoluMint, HayaFinance, Hemera Trading AI, among others.
* AI-driven applications: SuperString AI, Ring AI, DSCLab
* Decentralized Data: Orbler, X-Alpha, GemX, XeroAI, Collably Network
* Real-world asset tokenization: Sky Hause.
* NFTs and digital art markets: OpenGate, We Rent Official, Just Read it.
* SocialFi: DMail AI, Paal AI, Open Gate, Social Data Analytics.


# DeFi platforms


# AI-driven applications


# Real-world asset tokenization


# NFTs and digital art markets


# Key Terminology


# Glossary of Key Terms


# What is Phron.ai?


# Brief Introduction

Phron AI is providing a Layer-Suite, blending AI-driven consensus technology with open accessibility to AI Web 3.0 Products.


# Core Features

* **Phronesis:** The first AI-driven dynamic Consensus, implementing Proof-of-Learning, applies Neural Networks in the node operation system of the consensus for non-linear evolution of the chains.
* **Proof-of-Concept Phron AI Layer 1:** Our prototype representation of the future Layer 1's technology that will be available through PhronZero.
* **PhronZero:** Our Infrastructure-as-a-Service Layer 0, allowing the creation of a Layer 1 with zero-coding in a couple minutes.
* **OpenPhron:** Our AI Web 3.0 Marketplace, your place for all AI Web 3.0 related products. From libraries from major vendors, to sellers providing AI smart contracts.&#x20;

<br>


# Whitepaper

### Introduction

This paper introduces Phron, a groundbreaking approach to blockchain technology by integrating artificial intelligence (AI) capabilities into the foundational Layer 0. Building upon the traditional principles of decentralization, security, and scalability, an AI-based Layer 0 blockchain aims to revolutionize the landscape of distributed ledger systems.

The core of our proposed solution lies in the incorporation of AI algorithms, enabling dynamic consensus mechanisms, predictive security measures, and adaptive scalability. By leveraging machine learning, the proposed chain adapts to evolving network conditions, enhancing efficiency and responsiveness in real-time. This adaptive consensus model not only strengthens resistance against attacks but also optimizes the network’s performance under various scenarios.

The proposed AI-based Layer 1 to be constructed on the master classes in Layer 0 introduces intelligent contract execution, augmenting the capabilities of smart contracts. Through integrated machine learning algorithms, the system gains the ability to autonomously optimize contract execution, predict potential vulnerabilities, and dynamically adjust gas fees based on current market conditions. This not only streamlines transaction processing but also enhances the overall security and efficiency of smart contract operations.

In this paper, we go over the design principles, technical architecture, the integration of AI master class modules into the Layer 0 blockchain, and how Layer 1 gains access to the underlying Layer 0 blockchain. We introduce novel approaches to solve Layer 1 bootstrapping issues while still securing the chain by Node - Block-Sharing (NBS). The introduction of Adaptive AI Staking (AAIS) builds on the built-in master classes to determine the node reward boost allowing for a more efficient anesthetization. Finally, we introduce the AI arbiter in the chain governance voting mechanism. The arbiter solves the long-standing issue of how to determine the voting power of the users.

We explore the impact of AI on decentralization, security, and scalability, presenting empirical evidence of improved performance through simulations and real-world use cases.


# Vision and Inspiration

PhronAI is the avant-garde Layer-1 blockchain that blends EVM compatibility and Proof-of-Stake, featuring an AI-driven Consensus Mechanism. PhronAi introduces a new proprietary consensus layer, enhanced by machine learning algorithms, with its core technology, Sophia, which enables transaction processing times of under 0.9 seconds at an average cost of $0.00001 and maintains over 31,000 transactions per second, achieving unparalleled network scalability without congestion.

PhronAI is the first chain that establishes the usage of a dynamic consensus algorithm through the appliance of Al tools managed automatically by the Sophia Protocol giving an available testing sandbox to understand and improve the current Al model used for our next application. Once PhronAI is optimally refined, the technology will transition to PhronZero. PhronZero expands each chain built upon it with AI technology, granting it heightened efficiency, simplicity, and communication capabilities.

PhronAI empowers projects to create tailored solutions across various digital and real-world sectors, enabling efficient, secure, interoperable communication. This ecosystem nurtures trustless cooperation among applications, positioning PhronAI as a cornerstone for constructing a Web3 future that leverages the full potential of AI technology \[1].

In the information era, blockchain and artificial intelligence are reshaping industries and redefining interactions with data and transactions. Both have emerged as transformative mediums, disrupting sectors ranging from finance to supply chain management. However, a genuine integration of the capabilities of both technologies, which would allow for a synergy that opens new possibilities, has yet to be realized.

The fusion of blockchain and artificial intelligence marks a significant leap forward in technological advancement, introducing a synergy that extends beyond the capabilities of each technology individually. Blockchain’s decentralized and secure infrastructure for managing transactions and data is complemented by artificial intelligence’s prowess in analyzing extensive datasets to uncover insights and streamline decision-making. This partnership not only can solve problems such as data privacy, security, and transparency but also sets the stage for the development of groundbreaking applications


# Problem Statement

In traditional blockchain architectures, scalability, security, and adaptability have often been cited as significant challenges. As the scale of blockchain networks grows, so does the complexity of maintaining consensus, ensuring security, and accommodating diverse transactional requirements. Moreover, existing blockchain solutions often struggle to adapt dynamically to changing network conditions, leading to inefficiencies and vulnerabilities.

PhronAI addresses these challenges by introducing an innovative approach to blockchain technology, integrating AI capabilities at its foundational layer. By leveraging machine learning algorithms, PhronAI seeks to create dynamic consensus mechanisms, predictive security measures, and adaptive scalability, thereby revolutionizing the landscape of distributed ledger systems.


# Proof-of-Concept: Phron Layer 1

The Phron AI Chain represents a groundbreaking advancement in blockchain technology, where artificial intelligence is seamlessly integrated into the foundational Layer 0.

Unlike conventional blockchain architectures, which rely solely on static rules and consensus mechanisms, the Phron AI Chain harnesses the power of AI to adapt and optimize its operations in real-time. This dynamic approach not only enhances the efficiency and responsiveness of the network but also fortifies its security against evolving threats.


# Phron AI: What’s under the hood?

At the heart of the Phron blockchain lies PhronAI, a sophisticated amalgamation of cutting-edge technologies designed to fuel its decentralized ecosystem. PhronAI operates as the brainpower behind the platform, orchestrating various functions to ensure efficiency, security, and scalability.

At its core, PhronAI harnesses the power of artificial intelligence (AI) to optimize consensus mechanisms, enhance data validation processes, and streamline transaction throughput. Leveraging AI algorithms, PhronAI dynamically adjusts network parameters, adapting to fluctuating demands and maintaining optimal performance levels.

One of the key features of PhronAI is its ability to autonomously detect and mitigate potential security threats, fortifying the network against malicious activities such as DDoS attacks, double-spending, and Sybil attacks. Through continuous monitoring and analysis of network behavior, PhronAI reinforces the blockchain’s resilience, safeguarding user assets and preserving the integrity of transactions.


# Sophia Protocol

Sophia utilizes a set of rules designed to analyze and interpret the metrics data of nodes, uncovering their functional capacity to participate in the network. Through this application, three categories of validators are activated to process a broad spectrum of transactions submitted at varying fee rates. This mechanism enhances the block production process by expanding the chain’s capabilities, setting the standard transaction fee remarkably low based on previously mentioned average metrics. This standard cost applies to all transactions created and submitted by end-users, ensuring their rapid processing is comparable to high-fee transactions on other blockchains

Periodically, Sophia evaluates individual statistics and generates a list categoriz ing validators into three groups. The Deep Learning Mechanisms oversee the PhronAi block sequence holistically, identifying any anomalies and initiating a Machine Learning auto-response mechanism to mitigate the risk posed by any potentially malicious party. Furthermore, validators within these groups are tasked with processing transactions immediately, based on fee values, benefiting end-users, node owners, and developers alike.

Validator participation within the network is carefully assessed using various metrics, which, after each mechanism cycle, serve as inputs for the next. Should a validator exhibit reduced participation, its metrics are recorded as low. With low metrics as inputs, there is a possibility of category shifts among validators, from super node to fast node or average node. Consequently, PhronAi motivates validators to engage actively in the network by processing blocks that include the maximum number of transactions. The first step involves collecting inputs from useful metrics that a node calculates independently. During the network’s initialization phase, these metrics, serving as input values, are supplied by the genesis file and a self-enforcing smart contract.

<figure><img src="/files/BwfvuXb9A2J10vNBWUmj" alt="" width="375"><figcaption></figcaption></figure>

Once the statistical algorithm becomes fully operational, metrics input values will also be directly obtained from the event trigger functionality.

Low latency, high throughput, the total number of votes, and maximum liveness metrics are sorted separately. For example, in the case of low latency, the individual matrices of all validators will be used for low-latency sorting. After this process, sorted lists from each metric are passed to the next step. The following details the criteria used in sorting each list of metrics for the super, fast, and average categories.

A variable is declared by defining an equation:

x= Total number of Validators / Number of Groups

The number of validator groups is 3. The top ’x’metrics in each sorted list are considered super metrics. Similarly, the remaining top ’x’metrics in each sorted list are considered fast metrics. All remaining metrics will be considered as average metrics.

Validators are categorized into super, fast, and average nodes based on a sorted list of all metrics. A validator is formally designated as a super node if it consistently appears as a super node in every sorted list. Similarly, a validator is classified as a fast node if it is listed as fast in at least three sorted lists. If these criteria are not met, the validator is designated as an average node. At this point, three comprehensive lists containing the IDs of all validators in the network are compiled, categorizing them as super, fast, and average nodes respectively.

In this phase, validator IDs within the super, fast, and average node categories retrieve their records from databases and caches, leading to the creation of fully functional validator objects ready to participate in the block-producing mechanisms. The registry service temporarily stores the active validator groups from these three categories. These groups are also permitted to engage in the event emission and evaluation process for a specific epoch round.

Concurrently, a self-enforcing event trigger service operates in parallel, generating input signals for the initial phase of the statistical algorithm. This service addition ally generates input signals in reaction to particular events, such as the addition or removal of a validator. Consequently, the data-capturing fields of input objects may be initialized or aligned with input matrices. Moreover, this phase is technically regarded as the concluding step of the statistical algorithm.

This final step also operates in parallel and shares its output with the continuous execution of the process already running in the previous step. Its primary purpose is to monitor the liveness of validators within each group. Should any changes in the liveness status occur, such as the addition of new validators or the removal of existing ones, a reporting event is generated and conveyed through the event trigger service.

Consists of three individual modules operating within their own boundaries yet transcending the functional capabilities internally, directly governing the consensus committee and managing the transaction pool state e.g the tx queue and gas cost overhead.

### A. NeuraClassi (The Arbiter)

A method for intelligently selecting an accounting node, relating to fields of blockchain, virtual currency and artificial intelligence, is provided, which includes:

1. Processing data
2. Training on processed data

#### *Processing data:*

The raw data we have is in the form of numeric values that need to be encoded in categorical values to do so we proposed an algorithm which can convert the given array of data for a variable into its category as super, fast and average depending upon calculations. The raw data shape we get as an input and proposed Arbiter algorithm for calculation are as under.

|  NODE ID | POWER RATIO (PR) | LATENCY (AL) | SUCCESSFUL THROUGHPUT (ST) | LIVENESS (AL) |
| :------: | :--------------: | :----------: | :------------------------: | :-----------: |
| Node - 1 |      0.0714      |    19 (ms)   |         1.9 (kbps)         |    3000 (s)   |
| Node - 2 |      0.0714      |    18 (ms)   |         1.8 (kbps)         |    2500 (s)   |
| Node - 3 |      0.1071      |    22 (ms)   |         1.6 (kbps)         |    4000 (s)   |
| Node - 4 |      0.1071      |    17 (ms)   |         1.3 (kbps)         |    500 (s)    |
| Node - 5 |      0.0714      |    15 (ms)   |         1.5 (kbps)         |    2000 (s)   |
| Node - 6 |      0.1071      |    17 (ms)   |         1.3 (kbps)         |    200 (s)    |
| Node - 7 |      0.1428      |    14 (ms)   |         1.0 (kbps)         |    1500 (s)   |
| Node - 8 |      0.1428      |    12 (ms)   |         1.7 (kbps)         |    800 (s)    |
| Node - 9 |      0.1785      |    11 (ms)   |         2.1 (kbps)         |    5000 (s)   |

#### *Arbiter Algorithm:*

1. Get data of different nodes having Power Ratio, Average Latency, Successful Throughput, Liveliness.
2. Sort the values of each data column in the form of arrays.
3. Calculate the X factor using the formula:

   &#x20; &#x20;

   Where the total number of nodes is the number of nodes running inside the network and Group of nodes are types of nodes that want to classify. In our case we are categorizing the nodes into super, fast and average so the group of nodes is equal to 3.

<figure><img src="/files/wlhUUFuG8HtHayc47iDB" alt="" width="375"><figcaption></figcaption></figure>

4. Divide the list into X\_factor sublists based on sorted values (Average, Fast, Super) in such a way that first list is assigned as Super, second list assigned as Fast and last list assigned as Average. &#x20;

<figure><img src="/files/6ipOaReNZJZTPJknlCTZ" alt="" width="375"><figcaption></figcaption></figure>

5. If some values overlap within multiple sublists then these values should be associated with the previous sublists.
6. Encode values in such a way to assign super, fast, average category to sublist 1, sublist 2 and sublist 3 respectively.
7. As the AI models work well on numerical categories we then assign 0 to average, 1 to fast and 2 to super values in the final list.
8. The output of the data after this algorithm is as follows.

<table><thead><tr><th align="center">NODE ID</th><th width="149" align="center">CATEGORY: PR </th><th align="center">CATEGORY: AL</th><th align="center">CATEGORY: ST</th><th align="center">CATEGORY: L</th></tr></thead><tbody><tr><td align="center">Node - 1</td><td align="center">0</td><td align="center">0</td><td align="center">2</td><td align="center">2</td></tr><tr><td align="center">Node - 2</td><td align="center">0</td><td align="center">0</td><td align="center">2</td><td align="center">1</td></tr><tr><td align="center">Node - 3</td><td align="center">1</td><td align="center">0</td><td align="center">1</td><td align="center">2</td></tr><tr><td align="center">Node - 4</td><td align="center">1</td><td align="center">1</td><td align="center">0</td><td align="center">0</td></tr><tr><td align="center">Node - 5</td><td align="center">0</td><td align="center">1</td><td align="center">1</td><td align="center">1</td></tr><tr><td align="center">Node - 6</td><td align="center">1</td><td align="center">1</td><td align="center">0</td><td align="center">0</td></tr><tr><td align="center">Node - 7</td><td align="center">2</td><td align="center">2</td><td align="center">0</td><td align="center">1</td></tr><tr><td align="center">Node - 8</td><td align="center">2</td><td align="center">2</td><td align="center">1</td><td align="center">0</td></tr><tr><td align="center">Node - 9</td><td align="center">2</td><td align="center">2</td><td align="center">2</td><td align="center">2</td></tr></tbody></table>

#### *AI Arbiter Model*

The AI Arbiter Model is a deep learning approach designed specifically for node type detection within blockchain networks. This section outlines the architecture, mathematical formulation, training procedure, and evaluation metrics associated with the AI Arbiter Model.

The AI Arbiter protocol aims to classify nodes within a blockchain network into different types based on their behavior, role, and network attributes. By accurately identifying node types such as Super nodes, Fast nodes and average nodes, the model assists in network management to take governance decisions based on AI module output which will help to overcome the problems described above in protocols.

#### *Model  Architecture:*

We propose a deep neural network architecture tailored for node type detection in blockchain networks. The model comprises multiple layers, including input, hidden, and output layers. By utilizing dense layers and appropriate activation functions, our model aims to capture intricate patterns and relationships within the input data.

#### Different types of layers include:

Input Layer:

1. The input data matrix X consists of features representing each node in the blockchain network. These features could include encoded parameters such as Power Ratio type , Average Latency type, Successful Throughput type, and Liveliness type.

<figure><img src="/files/AUCYe5WNuH5iIRn83t2v" alt="" width="375"><figcaption></figcaption></figure>

Here, m represents the number of nodes, and n represents the number of features associated with each node.

2. Hidden Layers:

The hidden layers introduce non-linearity into the model, enabling it to capture complex relationships within the input data. Each hidden layer l is computed as:

<figure><img src="/files/7B3I4eUXmozWVOAIBPw9" alt="" width="352"><figcaption></figcaption></figure>

Where W(l) denotes the weight matrix, b(l) represents the bias vector, and f is the activation function applied element-wise.

3. Output Layer:

The output layer produces predictions for the node types. Since this is a multi-class classification problem, we use a softmax activation function to obtain the probability distribution over the classes. The output Y is computed as:

<figure><img src="/files/AOoAbTspRNvOaQRAydNi" alt="" width="366"><figcaption></figcaption></figure>

Where W(out) and b(out) are the weight matrix and bias vector for the output layer, respectively. L denotes the index of the last hidden layer.

#### *Training Procedure:*

The model is trained using a suitable optimization algorithm such as stochastic gradient descent (SGD), Adam, or RMSprop. The objective is to minimize a suitable loss function such as categorical cross-entropy, which measures the dissimilarity between the predicted probabilities and the true labels. The annotated data sample shown above is used during the training process.

#### *Evaluation Metrics:*

To assess the performance of the model, evaluation metrics such as accuracy, precision, recall, and F1-score can be computed on a held-out validation set or through cross-validation.

### B. NeutraGuard

1. Performs as two way watchguard between NeuraClassi and SophiaExec, providing ***Guardrails*** to control any ***Emergent, Hallucinative or Suspicious*** behavior produced from relative modules, takes some predetermined measures and falls back to LockDown state to mitigate the situation as:
   1. Blocking AI influence to consensus or tx pool conditionally
   2. Switching to the state of defaults to keep network going smoothly
      1. The state could be triggered in case of any anomaly detection
   3. Controls how long the LockDown stays or it could only be restored through manual governance agreement.
2. NeutraGuard is also incharge to control the behavior of AI compliance with on-chain state; in case of any disagreement between the states from both modules the protocol will again fallback to LockDown state.
3. And as data channel telemetry across Sophia Protocol

#### *NeutraGuard Anomaly analysis:*

Isolation Forests(IF), similar to Random Forests, are built based on decision trees. And since there are no predefined labels here, it is an unsupervised model. Isolation Forest is a technique for identifying outliers in data. The approach employs binary trees to detect anomalies, resulting in a linear time complexity and low memory usage. Isolation. Isolation Forests were built based on the fact that anomalies are the data points that are “few and different”. In an Isolation Forest, randomly sub-sampled data is processed in a tree structure based on randomly selected features. The samples that travel deeper into the tree are less likely to be anomalies as they require more cuts to isolate them. Similarly, the samples which end up in shorter branches indicate anomalies as it was easier for the tree to separate them from other observations.

Isolation Forests for outlier detection are an ensemble of binary decision trees, each referred to as an Isolation Tree (iTree). The algorithm begins by training the data through the generation of Isolation Trees.

#### The flow is as follows:

1. Given a dataset D, a random subsample **Ds** is chosen and assigned to a binary tree.
2. Tree branching initiates by randomly selecting a feature from the set of all N features. Subsequently, branching occurs based on a random threshold within the range of minimum and maximum values of the selected feature.
   * Let *xi* denote the feature vector of data point i, and feat be the randomly selected feature.
   * Let thresh be a random threshold.
   * Branching condition: If **xi\[feat]\<thresh**, then go to the left branch; otherwise, go to the right branch.
3. If the value of a data point is less than the selected threshold, it follows the left branch; otherwise, it proceeds to the right branch. This process splits a node into left and right branches.
   * Let left(n) and right(n) denote the left and right branches of node n, respectively.
4. The process continues recursively until each data point is entirely isolated or until the maximum depth (if defined) is reached.
   * Let max\_depth be the maximum depth of the tree.
   * Recursive termination condition: If max\_depth is reached or only one data point remains in the node, stop recursion.
5. The above steps iteratively construct multiple random binary trees.
   * Let T be the set of all constructed trees.
6. Once the ensemble of iTrees (Isolation Forest) is formed, model training concludes. During scoring, each data point traverses through all previously trained trees. Subsequently, an 'anomaly score' is assigned to each data point based on the depth of the tree required to reach that point. This score aggregates the depths obtained from each of the iTrees. An anomaly score of -1 is assigned to anomalies, and 1 is assigned to normal points, based on the provided contamination parameter, which signifies the percentage of anomalies present in the data

### C. SophiaExec

SophiaExec is at the core which is actually responsible for executing the business logic of the protocol as follows

### *1. Block Authoring / Finalizing Committee*

Receives the nodes list in a categorized manner and let each node author blocks according to its position in the list, the total block capacity within the given timeframe will be divided as percentages, the nodes will get to author blocks according to their performance measured by the **NeuraClassi** module. For finality all nodes can take part except for the banned nodes without any distinction for the time being.

### Validators categorized for NeutraGuard:

* `validator`: Node that can become a member of committee (or already is) via rotation.
* `validators reserved`: immutable validators, i.e. they cannot be removed from the list.
* `validators non_reserved`: validators that can be banned from the list.

There are two options for choosing validators during election process:

1. `Permissionless`: choose all validators that are not banned.
2. &#x20;`Permissioned::reserved`: choose only reserved validators.
3. `Permissioned::non_reserved` choose only non\_reserved that are not banned.

These conditions provide help in LockDown situations as fallback for different sets of validators.

#### *2. Validator Bans*

In order to manage underperforming / misbehaving nodes the ban logic is required which is currently being managed by the root (pallet elections will be replaced once the NeuraClassi matures to involve in committee decisions) but the Ai module is also responsible to ban the misbehaving nodes or choose the committee set according to the given stats.

#### 3. TxPool Rearrangements

#### Security concern:

Networks that process low fee transactions are always vulnerable to pool flooding aka DDOS attacks for these scenarios the transaction pool and queue is carefully designed to deal with.

#### Computation:

Tx in Pool (%) / PoolLimit(%) \* MaxTTL = TTL

Pool Capacity - Total Tx in Pool / Pool Capacity \* MaxTTL \* Fee = Priority Factor

1. If PF equals or less than last Tx in the pool it won’t be accepted and if it beats one in that case the last transaction will be dropped.
2. If TTL of a transaction expires that will be dropped automatically.
3. All other transactions will be put into the ready and future queue according to the status tags.

Priority Factor will let some extremely low fee transactions pass through, as lucky transactions.

**Note:** The hardware metrics from the node are not supposed to be stored on chain but the resulting decision from the Ai module is, which will be considered a metric itself for further decision making.

<figure><img src="/files/lFiZpzfm0GXMvufBMb3t" alt="" width="375"><figcaption></figcaption></figure>

<figure><img src="/files/PYDxGuX5KHDXMV2eyRPd" alt="" width="375"><figcaption></figcaption></figure>


# AI Arbiter

The voting weight issue in blockchain governance revolves around the complexity of determining the influence each participant holds in decentralized decision-making within a blockchain network \[8, 9]. In decentralized governance systems, such as those prevalent in blockchain projects, decisions concerning protocol upgrades, changes, or community initiatives are typically made through a voting mechanism \[10]. The introduction of an AI arbiter within Phron’s governance system revolutionizes this aspect by harnessing advanced artificial intelligence algorithms. Unlike conventional methods reliant on static metrics like token holdings or stake sizes, the AI arbiter considers a diverse array of dynamic factors to fairly allocate voting influence to each participant.

The incorporation of an AI arbiter within the governance voting mechanism of the Phron chain signifies a breakthrough in addressing the persistent challenge of determining users’ voting power in decentralized decision-making processes. Traditionally, this issue has sparked debates regarding fairness, transparency, and susceptibility to manipulation. One pivotal advantage of employing an AI arbiter lies in its capability to analyze intricate datasets and discern patterns, trends, and user behaviors that may elude human observation. Through machine learning techniques, the AI arbiter continually adapts and improves, ensuring precise and equitable distribution of vot ing power over time. The AI arbiter introduces objectivity and impartiality, lacking in human-driven governance systems. By eliminating biases and subjective judgments, it guarantees decisions are based solely on merit and community interests, rather than individual inclinations.

From an efficiency point of view, the AI arbiter enhances governance efficiency and scalability by automating essential tasks such as voter registration, verification, and vote tabulation. This not only streamlines decision-making but also mitigates the risk of human error or manipulation.

Beyond its role in determining voting power, the AI arbiter offers valuable insights and recommendations to inform governance decisions. By analyzing historical voting patterns and market data, aids users in making informed decisions aligned with Phron chain’s long-term objectives and sustainability


# Indirect – LTFM Protocol

Sophia implements efficiently a set of processes to manage transactions while avoiding triggering spikes in transactions costs. Implemented indirectly as Low Transaction Fee Management (LTFM) Protocol. The transaction fees are being reduced by an incredible magnitude of 8X, the number is sure to make the chain even cheaper to interact with. This makes the blockchain even more suitable for accommodating, High-Frequency DeFi, or other large-scale use cases

But still dynamic fee adjustment is unavoidable. They create the financial incentives for providing services and guarantee the further development of the project in question.

So theoretically If the block has fewer transactions than the targeted block saturation, the price will diminish by a minor amount. If a block is subject to more transactions, the fees will be accordingly priced higher.


# Adaptive AI Staking (AAIS)

Blockchain staking is a mechanism used to secure and validate transactions on a blockchain network, as well as to incentivize network participants to actively contribute to the network’s operation. Staking involves users locking up a certain amount of cryptocurrency tokens as collateral to participate in the network’s consensus process. In return for staking their tokens, participants are rewarded with additional tokens as an incentive for helping to maintain the network’s security and integrity \[11].

Blockchain staking offers several advantages over traditional Proof of Work (PoW) consensus mechanisms, including reduced energy consumption, scalability improvements, and potentially enhanced decentralization. Additionally, staking enables cryptocurrency token holders to earn passive income by contributing to network validation, thereby encouraging sustained investment and involvement in blockchain ecosystems \[12].

Phron utilizes Adaptive AI Staking (AAIS), introduced by Dr. Adel ElMessiry, which is an innovative approach to blockchain staking that leverages artificial intelligence (AI) algorithms to dynamically adjust staking parameters based on real-time network conditions, user behavior, and market dynamics. This methodology aims to optimize staking rewards, mitigate risks, and enhance the efficiency of the staking process. The main characteristics of AAIS are expanded in the following sections.

### Dynamic Staking Parameters

AAIS utilizes AI algorithms to continuously analyze various factors such as network congestion, transaction volume, token price movements, and user participation. Based on this analysis, AAIS dynamically adjusts staking parameters such as staking duration, reward rates, and token allocation to maximize returns and adapt to changing network conditions.

### Risk Management

AAIS incorporates risk management strategies to mitigate potential losses and protect stakers’ interests. AI algorithms monitor market volatility, security threats, and other risk factors, and automatically adjust staking parameters to minimize exposure to risks such as price fluctuations and network vulnerabilities.

### Customizable

AAIS prioritizes the interests of stakers by tailoring staking parameters to individual preferences, risk tolerance, and investment goals. Users have the flexibility to customize their staking preferences and adjust parameters such as staking duration, reward distribution frequency, and withdrawal options to suit their needs.

### Optimized Reward Distribution

AAIS optimizes reward distribution mechanisms to ensure fair and equitable distribution of staking rewards among participants. AI algorithms dynamically adjust reward rates based on factors such as staking duration, token holdings, and network contribution, incentivizing active participation and encouraging long-term engagement.

### Continuous Learning

AAIS incorporates machine learning techniques to continuously learn from past performance, user feedback, and market data to refine its algorithms and improve staking efficiency over time. By analyzing historical data and identifying patterns, AAIS can make more accurate predictions and better optimize staking parameters to maxi mize returns for participants. The end goal of AAIS is to adjust the required staking amount and the rewards in a manner that rewards user behavior conducive to the entire ecosystem over the long run.


# PhronZero: Decentralizing Blockchain Development

A Layer 0 blockchain, sometimes referred to as a ”protocol layer” or ”foundational layer,” represents the underlying infrastructure upon which other blockchain layers operate. Unlike Layer 1, which typically encompasses blockchains like Bitcoin and Ethereum, Layer 0 is not concerned with specific applications or consensus mechanisms. Instead, it focuses on fundamental protocols and infrastructure components that provide the backbone for decentralized networks to function efficiently and securely \[2]. Phron Zero blockchain provides the foundational infrastructure and protocols that enable the functioning of decentralized networks. It sets the stage for innovation and development at higher layers, empowering developers to build decentralized applications (dApps), decentralized finance (DeFi) protocols, and other blockchain-based solutions on top of a robust and secure foundation. The main innovations of PhronZero are Master Class and Node-Block-Sharing (NBS).


# Master Class

The concept of classes in modern programming languages serves as a cornerstone for creating reusable structures from which objects can be instantiated \[3, 4]. Extending this paradigm to the realm of blockchain, the Phron Master Class introduces a pioneering approach to enhancing blockchain functionality and extensibility.

At its core, the Phron Master Class enables the blockchain to evolve and adapt by incorporating new functionalities through the addition of Master Classes. These Master Classes undergo a rigorous validation and regression testing process to ensure their compatibility and reliability within the blockchain ecosystem. Once validated, Master Classes are seamlessly integrated into the chain, becoming readily available for utilization by smart contracts.

The adoption of a Master Class is not only a technical decision but also an economic one. To invoke a Master Class, users are required to pay gas fees in addition to any other fees stipulated by the creator of the Master Class. This token economics frame work is meticulously designed to incentivize the creation of Master Classes and foster a vibrant ecosystem of innovation and collaboration within the blockchain community. By allowing Master Classes to be adopted into the chain, Phron empowers developers and stakeholders to introduce novel functionalities, optimizations, and improvements to the blockchain network.

Whether it’s introducing advanced cryptographic techniques, implementing complex algorithms, or enhancing interoperability with external systems, Master Classes serve as the building blocks for unlocking new capabilities and driving the evolution of blockchain technology.

<figure><img src="/files/fJu9y5ThonfXjL9e1RWe" alt="" width="375"><figcaption></figcaption></figure>

The integration of Master Classes fosters a culture of openness and collaboration, where developers can contribute their expertise and innovations to the broader blockchain ecosystem. Through a transparent and inclusive validation process, PhronAI ensures that Master Classes meet the highest standards of quality and reliability, thereby instilling confidence in their adoption by smart contracts and applications

The PhronAI Master Class represents a paradigm shift in blockchain development, offering a scalable and extensible framework for incorporating new functionalities and innovations. By incentivizing the creation of Master Classes and fostering a collaborative ecosystem, Phron paves the way for the continuous evolution and advancement of blockchain technology.


# Node-Block-Sharing (NBS)

The bootstrapping issue and lack of sufficient incentives for node operations are common challenges faced by Layer 1 blockchain networks \[5]. These issues can impede the growth and sustainability of newly deployed chains, limiting their ability to operate securely and efficiently \[6]. Node Block Sharing (NBS) presents a novel solution to these challenges, offering a comprehensive approach to address not only bootstrapping but also enhancing transaction processing and incentivizing node participation.

NBS leverages the underlying infrastructure of Phron Zero, a foundational protocol shared by all Layer 1 chains built upon it. This interoperability ensures cross-compatibility of transaction hashing, enabling nodes to seamlessly mine transactions across multiple Layer 1 chains. By tapping into a shared pool of participating nodes, each chain can access the necessary computational resources to process transactions efficiently, regardless of its individual node count.

One of the key benefits of NBS is its ability to address the bootstrapping issue by providing a decentralized network of nodes ready to support newly deployed chains. Instead of relying solely on the native node population of a specific chain, newly launched networks can leverage the existing infrastructure of Phron Zero, significantly reducing the time and resources required for network initialization and stabilization. NBS introduces a mechanism for optimizing mining rewards and transaction processing fees based on node status and network demand. By dynamically adjusting mining fees according to node availability and performance, each chain can incentivize node participation while ensuring fair compensation for computational resources contributed. This approach not only promotes a healthy ecosystem of node operators but also enhances the overall security and efficiency of transaction processing across Layer 1 chains.

To further enhance the efficiency and effectiveness of NBS, an AI agent can be employed to optimize the return on investment (ROI) for each participating node. By analyzing network dynamics, transaction volumes, and node performance metrics, the AI agent can dynamically adjust mining strategies and fee structures to maximize profitability for individual nodes while maintaining network stability and security.

<figure><img src="/files/qFw7q3pimCsCRIZRDdK7" alt="" width="375"><figcaption></figcaption></figure>

Node Block Sharing represents a pioneering approach to addressing the bootstrapping issue and incentivizing node participation in Layer 1 blockchain networks. By leveraging cross-chain compatibility, dynamic fee structures, and AI-driven optimization, NBS offers a scalable and sustainable solution to the challenges facing decentralized blockchain ecosystems


# Layer 1 Blockchain Minter Dashboard

Layer 1 Blockchain Minter implementation allows the user to create with a simple array of parameters the configuration of the future blockchain. This blockchain will work under the infrastructure and master classes available of PhronZero, permitting security, efficiency and intercommunication with other Layer 1 Blockchains.

<figure><img src="/files/QDsPmUf3VrXtpeKC5J0g" alt="" width="436"><figcaption></figcaption></figure>


# Token Economics

### Introduction

PhronZero presents a pioneering approach in the integration of blockchain and artificial intelligence (AI), offering a layer 0 infrastructure designed to empower layer 1 blockchains with unprecedented AI capabilities. The model aiming to ensure the sustainability, growth, and decentralized governance of the ecosystem and is constructed to incentivize participation, secure the network, and facilitate a vibrant economy centered around AI and blockchain synergy.

### Purpose of the Token

#### 1. Transaction Fees:

Used to pay for transactions and services within the PhronZero ecosystem, including smart contract deployments and AI service calls.

#### 2. Staking:

Required for participating in network consensus as validators, securing the network, and earning rewards

#### 3. Governance:

Grants holders the right to vote on proposals concerning the network’s development, feature integrations, and use of the ecosystem fund.

#### 4. AI Services Access:

Enables access to advanced AI capabilities and services provided by PhronZero, acting as a payment mechanism within the AI marketplace.

### Deflationary Mechanism

#### Transaction Fee Burns:

A portion of transaction fees (e.g., 0.5%) is burned, reducing the total supply over time and creating deflationary pressure.

#### AI Service Fee Burns:

Similar to transaction fees, a portion of the fees paid for using AI services within PhronZero will be burned.

### Staking and Validator Incentives

#### Dynamic Staking Rewards:

Adjusted based on network participation levels, total staked amount, and overall network performance to ensure attractive yet sustainable reward levels \[14]

### Dynamic Gas Fee Model

Optimizing for network efficiency and user experience, we employ a dynamic gas fee model, drawing inspiration from Ethereum’s EIP-1559 \[15], formulated thus:

<figure><img src="/files/ixxbGtUufT79Xm7nMJUU" alt="" width="375"><figcaption></figcaption></figure>

* **BaseFee(t):** Dynamically adjusts based on block space utilization, ensuring adaptability to network demand.
* **Tip:** An optional incentivization for validators to prioritize transactions, enhancing throughput during peak times.
* **∆C(τ ) and ∆N (τ ):** Represent the rate of change in transaction complexity and network congestion, respectively.
* **ϵ:** A sensitivity parameter for the token price stabilization mechanism.
* **Ptarget and P (t):** Target and current token prices, guiding fee adjustments to market conditions.

### Storage Fee Formulation

Reflecting considerations of data size, redundancy, and depreciating storage costs over time:

<figure><img src="/files/NYHppQEBQ1VjGzPefEsj" alt="" width="375"><figcaption></figcaption></figure>

* **StorageBaseFee:** Cost per unit of data storage.
* D: Size of the data stored.
* R: Redundancy factor for data reliability.
* λ: Reflects decreasing storage technology costs over time.

### Fee Distribution Mechanism

Encouraging a collaborative network through a model that rewards validators based on performance:

<figure><img src="/files/2PWMfRLqtP4aoc5Cg4dh" alt="" width="375"><figcaption></figcaption></figure>

* F : Total transaction fees collected.&#x20;
* α: Base coefficient for fee distribution between layers.&#x20;
* β: Adjusts distribution based on validator performance.&#x20;
* P : Performance metric for validators.

### Staking Rewards Dynamics

Enhancing network security and stakeholder engagement via a dynamic staking rewards model:

<figure><img src="/files/pmALhnGpWxUXRsk2SPwI" alt="" width="375"><figcaption></figcaption></figure>

* I: Inflation rate for reward distribution.&#x20;
* S(t): Total amount staked.&#x20;
* γ: Validator performance coefficient.&#x20;
* θ: Token price stabilization coefficient.

These mechanisms are crafted to ensure the blockchain remains adaptable, efficient, and economically sustainable, fostering a robust ecosystem conducive to long-term stability.

### Dual Token Architecture

A dual token architecture in blockchain refers to a system where there are two distinct types of tokens operating within the same ecosystem, typically with one token serving as the default base currency and another as a customizable token specific to individual layers or chains built on top of the base protocol. In this scenario, let’s explore the architecture with Phron Zero as the default token \[1, 16].

#### Phron Zero Token (Default Token)

Phron Zero token serves as the default base currency within the blockchain ecosystem. It is used for various purposes such as transaction fees, rewards, and value exchange within the network. Phron Zero token is the foundational token upon which the entire ecosystem is built. It ensures interoperability and consistency across different layers and chains within the ecosystem.

#### Layer 1 Custom Tokens

Any layer 1 blockchain built on top of Phron Zero can opt to incorporate a custom token specific to its chain. These custom tokens can have their own unique features, use cases, and economic models tailored to the specific requirements of the layer or chain. Custom tokens can be used for various purposes including governance, utility, incentivization, and more within their respective chains.

#### Interoperability Between Layer 1

The dual token architecture ensures interoperability between the default Phron Zero token and the custom tokens. Users can seamlessly transact and exchange value between different chains and layers within the ecosystem, irrespective of the specifc tokens being used. Smart contracts and protocols are designed to accommodate both Phron Zero and custom tokens, facilitating smooth interactions between them. Think of it as the reserve currency of the global monitor system.

#### Integration and Development

Developers building on top of Phron Zero can choose to integrate the default token or create custom tokens specific to their applications or layer 1 blockchains. Development frameworks, APIs, and toolkits are provided to simplify the process of token creation and integration, enabling developers to focus on building innovative solutions.

#### Economic Model and Governance

The economic model of the ecosystem may involve mechanisms for governing the issuance, distribution, and utilization of both Phron Zero and custom tokens \[17]. Governance structures ensure that the interests of token holders and participants are aligned with the overall goals and sustainability of the ecosystem. In summary, a dual token architecture in blockchain, with Phron Zero as the default token, allows for flexibility, customization, and interoperability within the ecosystem. It empowers developers to build diverse applications and layer 1 blockchains while maintaining a cohesive network supported by the foundational Phron Zero token.

### Incentives

An initial rewards curve for a newly launched protocol focuses on encouraging the use of a higher proportion of trusted Layer-0 (L0) nodes during the critical early stages of development and operation. This approach is strategically advantageous because it ensures a more secure and stable launch by leveraging the established security and reliability of L0 nodes. By incentivizing the utilization of these nodes through a rewards structure that makes it more cost-effective to use more L0 nodes rather than fewer, the protocol can maintain integrity and trustworthiness in its nascent phase.

<div align="center"><figure><img src="/files/Fbkm2edGannUrFqQDL5E" alt="" width="375"><figcaption></figcaption></figure></div>

As the project matures and gains stability, trust, and a wider validator base, the rewards curve can transition. This change reflects the growing confidence in the protocol’s own Layer-1 (L1) validators and a deliberate shift towards encouraging a more decentralized model. The upsloping rewards curve now incentivizes a gradual reduction in dependency on L0 nodes, rewarding the protocol for diversifying its validator network. This evolution in the incentives curve aligns with the project’s development trajectory, from relying on the foundational security of L0 nodes to fostering its autonomous, decentralized security apparatus as it matures.

<figure><img src="/files/NWRGMMyVXoCsUVMyJVOi" alt="" width="375"><figcaption></figcaption></figure>


# Staking

The Phron blockchain employs a novel approach to validator selection, leveraging both user staking and AI-ranked performance to ensure a robust, fair, and meritocratic system. This method prioritizes high-performing nodes while incorporating community trust and randomness to democratize the selection process.

### Meritocratic Selection

Validators are chosen based on a combination of AI-generated performance metrics and user staking, promoting a system where merit and community trust determine validator selection. The AI scores and ranks nodes by their operational efficacy, creating a competitive environment that motivates validators to uphold high standards. This merit-based selection system ensures that the most reliable and efficient validators are prioritized.

### Community Participation

Incorporation of user staking into the validator ranking allows the community to have a direct influence on the selection process. Validators that receive higher stakes from the community are perceived as more trusted, thereby integrating a democratic element into the system. This approach aligns the network’s operation with the preferences and trust of its users.

### Fairness and Randomness

To further ensure fairness, the system includes a random lottery element that considers both the AI rankings and the percentage of stakes. This mechanism introduces a degree of randomness, mitigating biases and providing opportunities for newer or smaller validators to participate in network validation.

### Selection Algorithm

The final decision on validator selection is based on the following factors:

1. The AI ranking of a node *k*, denoted as $$R^{k}\_{\text{AI}}$$, ranks nodes in ascending order based on their performance, with the best nodes receiving a higher rank.
2. The stake-based ranking of a node *k*, denoted as $$R^{k}\_{\text{Stake}}$$, applies the same ranking principle, prioritizing nodes with higher stakes.
3. A random lottery that accounts for both AI and stake-based rankings, calculating the probability P for a node k to be selected as a validator.

The algorithm is formalized by the following equations:

<figure><img src="/files/xgX0pzIWD9vxFV4JyCPJ" alt="" width="320"><figcaption></figcaption></figure>

where A is the sum of AI ranks for all nodes, B is the sum of stake-based ranks, and $$P\_{\text{k}}$$ represents the selection probability of node *k*

### Reward System

PHRON constitutes the link between the PhronAi Ecosystem and the holder. The PHRON reward system for node validators will work with the APR method; it is described with the following equation:

<figure><img src="/files/lelX53hBH3UWTscDYAY5" alt="" width="375"><figcaption></figcaption></figure>

where:

* 0 ≤ x < ∞&#x20;
* y is the APR (in decimal form)&#x20;
* x is the time (in years)

This APR calculation factors into the broader staking and reward mechanism, ensuring validators are incentivized proportionally to their commitment and performance over time.

<figure><img src="/files/wV8Rvo4S2tRtsHLohDzS" alt="" width="375"><figcaption></figcaption></figure>


# Governance

In an endeavor to ensure a high degree of decentralization, PhronAI introduces an on-chain governance model, predicated on a vote-escrowed mechanism. This approach empowers token holders to influence the ecosystem dynamically, aligning with the principles of decentralized autonomous organization (DAO) governance.

### Vote-Escrowed Tokenomics

Vote-escrowed tokenomics grants token holders the autonomy to determine a lock-up period for their tokens, effectively tying the token’s utility to the duration of its lock. The extended commitment to lock up tokens translates into enhanced influence within the network, manifesting in:

* Enhanced governance voting power.
* Increased staking rewards.
* Amplified voting impact on specific liquidity pools.

#### VeTokens Align Incentives:

The veToken model is designed to synchronize the protocol’s success with that of the token holders’. A prolonged lock-up period symbolizes a vested interest in the protocol’s prosperity.

#### VeTokens Encourage DAO Participation::

By offering additional voting power for longer lock-up periods, the protocol incentivizes users to ”max time-lock” their tokens, thereby strengthening their governance voice. This mechanism ensures that token holders deeply invested in the DAO’s future are rewarded with greater influence.

### Quadratic Voting

To further democratize the governance process and mitigate the risks of centralization and collusion, PhronAI will employ a quadratic voting system. This system ensures that as token holders acquire more tokens, the marginal increase in their voting power diminishes, promoting a more equitable distribution of governance influence.

The governance voting power, V , is determined by the equation:

<figure><img src="/files/e7LavVvraJEfBvtGiE3s" alt="" width="375"><figcaption></figcaption></figure>

where

* V represents the vePhron balance, indicating the voting power.
* &#x20;R denotes the Phron native token quantity.&#x20;
* L is the token lock-up period multiplier, enhancing the token’s voting power.

The vePhron balance declines linearly from the initiation of the lock-up period to its end, at which point stakeholders can reclaim their Phron tokens. However, token holders are afforded the flexibility to extend or renew their lock-up duration at any juncture, enabling them to either augment or maintain their vePhron balance and, by extension, their governance influence.


# Chain Simulations

### Transaction Throughput Simulation

To evaluate the robustness and scalability of the foundational Layer 0 network, we performed a simulation of transaction throughput for several Layer 1 projects running concurrently. The primary aim was to observe the network’s ability to manage and distribute its transaction processing capacity among the projects.

#### Simulation Parameters

The simulation was conducted under the following assumptions:

**Layer 0 Capacity:** The maximum transactions per second (tps) capacity was set at 31,000, reflecting a high-throughput blockchain infrastructure.

**Even Distribution:** The Layer 0 network’s tps capacity was evenly divided among the Layer 1 projects, emulating a fair and balanced load-sharing protocol.

**Temporal Scope:** The simulation covered a 100-second timeframe, providing a snapshot of network activity in a high-velocity environment.

#### Throughput Simulation Results

The throughput simulation \[18] results (Figure 5) showcased the transactions processed by each Layer 1 project over time. The graphical representation illustratedmthat despite the fluctuations typically observed in network conditions, each project maintained a consistent level of activity, indicating a resilient and well-dimensioned network infrastructure.

<figure><img src="/files/GEojdxNfJqtcOgnGt41X" alt="" width="375"><figcaption></figcaption></figure>

### Gas Fee Simulation

Complementary to the throughput analysis, a simulation of gas fees was executed \[19], capturing the computational and storage demands of various dApp types. This simulation aimed to offer insight into the costs associated with on-chain activity, from simple transactions to complex smart contract interactions.

#### Assumptions for Gas Fee Simulation

The following assumptions were integral to the gas fee simulation:

1. **Computational Complexity:** Each dApp type exhibited a distinct pattern of transaction complexity, informed by common use-case scenarios.
2. **Storage Requirements:** dApps with storage needs were attributed higher gas fees, proportional to the size of the data being managed.
3. **Network Congestion:** A sinusoidal model was applied to simulate network congestion, affecting the gas fees across all dApp types.

#### Phron Zero Gas Fee Simulation Results

Since Phron Zero is the foundation on which multiple layer ones will run, we need understand the holistic impact of each layer one chain on layer zero. Let’s first take a look on the assumed types of each layer one.

#### Simulated Gaming Focused Layer One

A gaming-focused blockchain is a specialized blockchain network designed specifically to cater to the needs and requirements of the gaming industry. Such a blockchain leverages the unique characteristics of blockchain technology to offer various features and functionalities tailored to gamers, game developers, and other stakeholders within the gaming ecosystem. The expected gas fees would be an order of magnitude higher for the gaming Dapps rather than the DEX or Storage.

<figure><img src="/files/fxzZhn39ab8bMXr7RqZt" alt="" width="375"><figcaption></figcaption></figure>

#### Simulated DEX Focused Layer One

A decentralized exchange (DEX) focused blockchain is a specialized blockchain network specifically designed to facilitate decentralized trading of digital assets, such as cryptocurrencies, tokens, and other blockchain-based assets. This type of blockchain prioritizes features and functionalities that enhance the performance, security, and user experience of decentralized exchange platforms. Naturally, such a chain would generate more swap related gas fees.

<figure><img src="/files/uoeRfprau56i5MaJRnB5" alt="" width="375"><figcaption></figcaption></figure>

#### Simulated Storage Focused Layer One

A storage-focused blockchain typically prioritizes the efficient and secure storage of data on the blockchain network. Gas fees, which represent the cost of performing transactions or executing smart contracts on the blockchain, play a crucial role in incentivizing network participants and maintaining the security and integrity of the system. In a storage-focused blockchain, gas fees may be structured in a way that reflects the costs associated with storing and accessing data on the blockchain. Gas fees in a storage-focused blockchain are designed to reflect the costs of storing and accessing data on the blockchain while incentivizing efficient resource usage and maintaining network security and performance. By implementing a dynamic and transparent fee structure, the blockchain ensures that gas fees remain competitive, responsive, and aligned with the needs of network participants.

### Phron Zero Simulated Gas Fee Consumption

The results, as visualized in Figure 9, depicted the variability of gas fees over time for gaming, DEX, and storage dApps. The simulation reflected that storage-intensive dApps may incur higher fees during peak data operations, whereas gaming and DEX dApps showed variable fees correlated with their interactive and market-driven activities.

<figure><img src="/files/ouZCDEg8BSL0eV7gB9YK" alt="" width="375"><figcaption></figcaption></figure>

### Conclusion

The simulations confirm the Layer 0 network’s capacity to support a multi-faceted blockchain ecosystem, managing both high-velocity transactions and complex dApp interactions efficiently. By mirroring realistic operational conditions, the simulations validate the network’s design philosophy, highlighting its ability to adaptively balance performance and cost for diverse Layer 1 projects.


# Economic Simulation

The methodology will center on the use of stochastic approximations to model and analyze the system. This approach allows us to estimate the collective behavior of agents within a system under conditions of uncertainty and variability. By leveraging stochastic approximations, we can efficiently simulate and predict outcomes without the need for detailed data on every individual component. This principle underpins our commitment to achieving both accuracy and computational efficiency in our simulations. Simulations will be used with a focus on understanding price dynamics, not with the aim of predicting the exact future price, but rather to comprehend the conditions and environment conducive to price appreciation or identifying factors leading to price declines.

While PhronAI is envisioned to evolve into a blockchain of blockchains, our current evaluation will concentrate exclusively on its initial layer-1. However, the potential of layer-1 should be assessed with the understanding that its scope extends beyond merely its launch. This principle underscores the importance of viewing PhronAI’s layer-1 not just as an isolated product, but as a foundational element that contributes to the overall growth and success of the ecosystem.

### Modeling Parameters

We have used the following parameters which we think are reasonable for this type of blockchain. Run time 5 years.

Starting monthly transaction volume = $30 million

Final monthly transaction volume = $300 million

Pricing equation: Equation of exchange P=T/(MV) Allocation and emissions are highlighted above.

Total tokens: 70% of the full supply (treasury and foundation are assumed to be out of circulation).

Holding time: Lognormal Distribution.

The holding time data utilized in our analysis was compiled from a collection of holding times extracted from various industry projects. This dataset has been adopted as a robust basis for determining holding times, underpinned by the rationale that observed patterns across these projects offer a substantial foundation for formulating well-informed assumptions about future asset holding durations. By leveraging this historical data, we have established a benchmark for holding times, ensuring our projections are anchored in tangible, real-world observations and trends.

<figure><img src="/files/AuzaFeuoyHPcMMRi323C" alt="" width="375"><figcaption></figcaption></figure>

A simulation was conducted to test the resilience of the current assumptions. The simulation ran for 100 iterations. Each iteration consisted of the parameters displayed above. The results are shown below. The solid blue line shows the mean fair price, while the shaded areas show 95% confidence intervals.

### Base Scenario Simulation

It looks like a launch price of $0.5 can lead to a fair value of close to $60 as a best-case scenario over 5 years.

<figure><img src="/files/hyNIe6RT55VHARwgxX4q" alt="" width="375"><figcaption></figcaption></figure>

### Conclusion

Price appreciation is observed even with conservative metrics. This indicates that even modest achievements relative to transaction volume can lead to significant value increases, highlighting the potential for growth despite cautious projections.

Price appreciation, along with the current token supply allocation and emissions, demonstrates that the tokenomics from a quantitative perspective are defensible and can appreciate even without modeling forward multiples, which are often observed in euphoric market conditions to be 5-10x.

Price appreciation is assessed exclusively within the scope of Phron L1, excluding consideration of the interconnectedness with L0 and other L1 networks. This approach underrate the real project’s value growth, which could be faster when the project’s ultimate vision is considered.

### Token Allocations

Token allocation refers to the distribution of the total supply of tokens in a blockchain project among various stakeholders, according to specific categories and purposes. This allocation is typically outlined in a project’s whitepaper or offering documents and is an essential component of a project’s economic and governance model. The tokenomics of Phron AI is structured with an initial circulating supply of 2,100,000,000 PHRON, with emissions for additional token creation to support future growth and scalability of the ecosystem. Effective token allocation is designed to align the incentives of developers, investors, users, and other stakeholders with the long-term success and sustainability of the project \[20].

**Private Sale (16%):** Unlocks at Token Generation Event (TGE), followed by a 6- month linear vesting period. This is designed to protect the ecosystem from excessive token infusion during the chain bootstrap phase.

**Public Sale (4%):** Unlocks at TGE, followed by a 2-month linear vesting period.

**Team (15%):** Subject to a 9-month cliff, with linear vesting from that point until month 24. The longer vesting period is designed to insure that the team will continue chain support for the next two years at a minimum.

**Ecosystem Supportive Nodes (15%):** This amount is reserved for the ecosystem nodes Locked indefinitely to support the nodes.

**Liquidity and market makers (17%):** Fully unlocked.

**Advisors (3%):** Subject to a 9-month cliff, with linear vesting from that point until month 24.

**Foundation (20%):** Fully unlocked. The funds will be used for building the L0 and the grants program. The grants program will fund L1s with a strategic focus, facilitating the creation of the Phron ecosystem. The foundation will be utilized to support the construction of Layer 0 and the development of the system. This allocation strategy is designed to prevent the distribution of excessively large stakes to any particular group, thereby helping to manage early-stage volatility.

**Treasury (10%):** Vesting over 4 years, linearly at 25

**Acknowledgements.**&#x20;

We would like to acknowledge&#x20;

the contributions of our community,&#x20;

especially to the completion of this work.

<figure><img src="/files/jcdJnfeYDDMoy0QRCDcN" alt="" width="375"><figcaption></figcaption></figure>


# References

ElMessiry, M., ElMessiry, A., ElMessiry, M.: Dual token blockchain economy framework. In: International Conference on Blockchain, pp. 157–170 (2019). Springer

Gangwal, A., Gangavalli, H.R., Thirupathi, A.: A survey of layer-two blockchain protocols. Journal of Network and Computer Applications 209, 103539 (2023)

Mitchell, J.C.: Concepts in Programming Languages. Cambridge University Press, ??? (2003)

Pierce, B.C.: Types and Programming Languages. MIT press, ??? (2002)

Garay, J.A., Kiayias, A., Leonardos, N., Panagiotakos, G.: Bootstrapping the blockchain, with applications to consensus and fast pki setup. In: Public-Key Cryptography- –PKC 2018: 21st IACR International Conference on Practice and Theory of Public-Key Cryptography, Rio de Janeiro, Brazil, March 25-29, 2018, Proceedings, Part II 21, pp. 465–495 (2018). Springer

Lantz, L., Cawrey, D.: Mastering Blockchain. O’Reilly Media, ??? (2020)

Sguanci, C., Spatafora, R., Vergani, A.M.: Layer 2 blockchain scaling: A survey. arXiv preprint arXiv:2107.10881 (2021)

Kiayias, A., Lazos, P.: Sok: blockchain governance. In: Proceedings of the 4th ACM Conference on Advances in Financial Technologies, pp. 61–73 (2022)

Tapscott, D., Tapscott, A.: Blockchain Revolution: How the Technology Behind Bitcoin Is Changing Money, Business, and the World. Penguin, ??? (2016)

Leonardos, S., Reijsbergen, D., Piliouras, G.: Weighted voting on the blockchain: Improving consensus in proof of stake protocols. International Journal of Network Management 30(5), 2093 (2020)

John, K., Rivera, T.J., Saleh, F.: Equilibrium staking levels in a proof-of-stake blockchain. Available at SSRN 3965599 (2021)

Choi, K.J., Jeon, J., Lim, B.H.: Optimal staking and liquid token holding decisions in cryptocurrency markets. Available at SSRN 4528742 (2023)

Kjorveziroski, V., Filiposka, S., Mishev, A.: Evaluating webassembly for orches- trated deployment of serverless functions. In: 2022 30th Telecommunications Forum (TELFOR), pp. 1–4 (2022). <https://doi.org/10.1109/TELFOR56187>. 2022.9983733

Tosh, D., Shetty, S., Foytik, P., Kamhoua, C., Njilla, L.: Cloudpos: A proof- of-stake consensus design for blockchain integrated cloud. In: 2018 IEEE 11Th International Conference on Cloud Computing (CLOUD), pp. 302–309 (2018). IEEE

Liu, Y., Lu, Y., Nayak, K., Zhang, F., Zhang, L., Zhao, Y.: Empirical analysis of eip-1559: Transaction fees, waiting times, and consensus security. In: Proceed- ings of the 2022 ACM SIGSAC Conference on Computer and Communications Security, pp. 2099–2113 (2022)

Cai, T., Cai, H., Wang, H., Cheng, X., Wang, L.: Analysis of blockchain system with token-based bookkeeping method. IEEE Access 7, 50823–50832 (2019)

Beck, R., Mu¨ller-Bloch, C., King, J.L.: Governance in the blockchain economy: A framework and research agenda. Journal of the association for information systems 19(10), 1 (2018)

Faria, C., Correia, M.: Blocksim: blockchain simulator. In: 2019 IEEE Interna- tional Conference on Blockchain (Blockchain), pp. 439–446 (2019). IEEE

Memon, R.A., Li, J.P., Ahmed, J.: Simulation model for blockchain systems using queuing theory. Electronics 8(2), 234 (2019)

Lee, J.Y.: A decentralized token economy: How blockchain and cryptocurrency can revolutionize business. Business Horizons 62(6), 773–784 (2019)


# Appendix A Simulation Code Example

The following is the code written in Python to generate the simulations used in the document above.

### Simulated Transactions Per Second (TPS) Over 24 Hours

````python
```python
import numpy as np
import matplotlib . pyplot as plt

base_tps_phronzero = 100000
base_tps_phronlayer1 = 50000

time_hours = np. arange (0, 24, 1)
network_load_factor_phronzero = 0.5 * np. sin (np .pi * time_hours / 12 - np.pi /2) + 1
network_load_factor_phronlayer1 = 0.5 * np.sin(np .pi * time_hours / 12 - np .pi /2) + 1.5

effective_tps_phronzero = base_tps_phronzero * network_load_factor_phronzero
effective_tps_phronlayer1 = base_tps_phronlayer1 * network_load_factor_phronlayer1

plt.figure ( figsize =(14 , 7))

plt.plot ( time_hours , effective_tps_phronzero , label ='PhronZero TPS', marker ='o')
plt.plot ( time_hours , effective_tps_phronlayer1 , label ='Phron Layer 1 TPS', marker ='x')

plt.title ('Simulated Transactions Per Second ( TPS) Over 24 Hours ')
plt.xlabel ('Time ( Hours )')
plt.ylabel (' Transactions Per Second ( TPS )')
plt.legend ()
plt.grid ( True )
plt.xticks ( time_hours )
plt.ylim (0, max ( effective_tps_phronzero ) + 50000)

plt.show ()
# \ end { verbatim *}
# \ subsection { Simulated Dynamic Gas Fee }
# \ begin { verbatim *}

def calculate_dynamic_gas_fee ( base_fee , tip , epsilon , p_target , p_current , delta_c ,
delta_n ):
    """
    Calculate the dynamic gas fee for a transaction based on the provided parameters .

    : param base_fee : Base fee of the transaction
    : param tip : Optional tip to miners / validators
    : param epsilon : Sensitivity parameter for token price stabilization
    : param p_target : Target token price
    : param p_current : Current token price
    : param delta_c : Rate of change in transaction complexity
    : param delta_n : Rate of change in network congestion
    : return : Calculated dynamic gas fee
    
    """
    price_adjustment = epsilon * ( p_target - p_current ) / p_current
    gas_fee = ( base_fee + tip + price_adjustment ) * ( delta_c + delta_n )
    return gas_fee

base_fee = 10
tip = 1
epsilon = 0.1
p_target = 1
p_current = 0.65
delta_c = 1
delta_n = 1
```
````

### Gas Fees for Storage Biased L1 with Secondary dApp Support

````python
```python
# Simulate dynamic gas fees over time for a single dApp type

time = np. arange(0, 10, 0.1)
gas_fees = [calculate_dynamic_gas_fee ( base_fee , tip , epsilon , p_target , p_current + t, delta_c , delta_n ) for t in time]

plt.figure( figsize =(10 , 6))
plt.plot(time , gas_fees , label ='Dynamic Gas Fee Over Time')
plt.title('Simulated Dynamic Gas Fee')
plt.xlabel('Time')
plt.ylabel('Gas Fee')
plt.legend()
plt.grid(True)
plt.show()
```
````

### Simulated Gas Fees

````python
```python
import numpy as np
import matplotlib . pyplot as plt

# Setup
t = np. linspace (0, 2 * np.pi , 400)
BaseRate = 10
StorageRate = 0.05
N = 0.5 * np. sin (t) + 1.5 # Network congestion

# Parameters for complexity (C)
A, B, V, M, S = 1.5 , 1, 2, 1.5 , 0.8
omega , eta , kappa , alpha , R,T= 2, 0.05 , 1, 0.1 , 5, 50
i = np. arange (1, int (np. max (t) / T) + 1) * T

# Gaming dApp
C_gaming = A * np.sin( omega * t) + B
D_gaming = np. zeros_like (t)
G_gaming = BaseRate * (1 + C_gaming + N) + StorageRate * D_gaming

# DEX
C_dex = V * np. log (1 + eta * t) + M * np. sin ( kappa * t)
D_dex = np. zeros_like (t)
G_dex = BaseRate * (1 + C_dex + N) + StorageRate * D_dex

# Storage dApp
C_storage = np. full_like (t, S)
D_storage = R * np.sum ([ np. exp(- alpha * (t - iT) **2) for iT in i], axis =0)
G_storage = BaseRate * (1 + C_storage + N) + StorageRate * D_storage

# Plotting
plt.figure( figsize =(12 , 8))
plt.plot(t, G_gaming , label ='Gaming dApp')
plt.plot(t, G_dex , label ='DEX')
plt.plot(t, G_storage , label ='Storage dApp', linestyle ='--')

plt.title('Simulated Gas Fees')
plt.xlabel('Time (in cycles )')
plt.ylabel('Gas Fee (in gui unit )')
plt.legend()
plt.grid(True)
plt.show()
```
````

### Gas Fees for Storage Biased L1 with Secondary dApp Support

````python
```python
import numpy as np
import matplotlib.pyplot as plt

# Setup
t = np. linspace (0, 2 * np.pi , 400)
BaseRate = 10
N = 0.5 * np. sin (t) + 1.5 # Simulated network congestion

C_gaming_primary = 1.5 * np. sin (2 * np .pi * t / max(t))
C_dex_secondary = 0.3 * np. sin (4 * np .pi * t / max(t)) # Reduced influence
C_storage_secondary = 0.2 * np. sin (4 * np .pi * t / max (t)) # Reduced influence

G_gaming = BaseRate * (1 + C_gaming_primary + N)
G_dex = BaseRate * (1 + C_dex_secondary + N)
G_storage = BaseRate * (1 + C_storage_secondary + N)

plt.figure ( figsize =(12 , 8))
plt.plot (t, G_gaming , label ='Gaming dApp - Primary ', color ='blue')
plt.plot (t, G_dex , label ='DEX dApp - Secondary ', color ='orange', linestyle ='--')
plt.plot (t, G_storage , label ='Storage dApp - Secondary ', color ='green', linestyle =':')

plt.title ('Gas Fees for Gaming Biased L1 with Secondary dApp Support ')
plt.xlabel ('Time (in cycles )')
plt.ylabel ('Gas Fee (in gwei )')
plt.legend ()
plt.grid ( True )
plt.show ()

plt.figure ( figsize =(12 , 8))

G_dex_primary = BaseRate * (1 + 2.0 * (np. sin (4 * np .pi * t / max (t)) **2) + N)
G_gaming_supportive = BaseRate * (1 + 0.3 * np.sin (2 * np .pi * t / max (t)) + N) 
# Increased presence from Gaming
G_storage_supportive = BaseRate * (1 + 0.2 * np.sin (4 * np .pi * t / max (t)) + N)

plt.plot (t, G_dex_primary , label ='DEX dApp - Primary', color ='orange')
plt.plot (t, G_gaming_supportive , label ='Gaming dApp - Supportive', color ='blue',linestyle ='--')
plt.plot (t, G_storage_supportive , label ='Storage dApp - Supportive', color ='green',
linestyle =':')

plt.title ('Gas Fees for DEX Biased L1 with Secondary dApp Support')
plt.xlabel ('Time (in cycles )')
plt.ylabel ('Gas Fee (in gwei )')
plt.legend ()
plt.grid ( True )
plt.show ()


plt.figure ( figsize =(12 , 8))
G_storage_primary = BaseRate * (1 + 0.8 * np. sum ([ np.exp ( -0.1 * (t - iT) **2) for iT in np. arange (1, int (np. max (t) / 50) + 1) * 50] , axis =0) + N)
G_gaming_supportive = BaseRate * (1 + 0.3 * np.sin (2 * np .pi * t / max (t)) + N) 
# Slightly increased presence from Gaming
G_dex_supportive = BaseRate * (1 + 0.2 * np. sin (4 * np .pi * t / max (t)) + N)

plt.plot (t, G_storage_primary , label ='Storage dApp - Primary', color ='green')
plt.plot (t, G_gaming_supportive , label ='Gaming dApp - Supportive', color ='blue', linestyle ='--')
plt.plot (t, G_dex_supportive , label ='DEX dApp - Supportive', color ='orange', linestyle =':')

plt.title ('Gas Fees for Storage Biased L1 with Secondary dApp Support')
plt.xlabel ('Time (in cycles )')
plt.ylabel ('Gas Fee (in gwei )')
plt.legend ()
plt.grid ( True )
plt.show ()
```
````

### Transaction Throughput for Layer 1 Projects and Total Usage on Layer 0 Network

````python
```python
import numpy as np
import matplotlib.pyplot as plt

# Simulation parameters
SIMULATION_DURATION = 100 # Total time for simulation in seconds
LAYER_0_TPS = 31000 # Layer 0's maximum tps
NUM_PROJECTS = 3 # Number of Layer 1 projects

# Assume an even distribution of Layer 0's TPS across Layer 1 projects
tps_distribution = LAYER_0_TPS / NUM_PROJECTS

# Simulating transaction throughput for each Layer 1 project over time
time_steps = np. linspace (0, SIMULATION_DURATION , SIMULATION_DURATION )
throughput_data = {}

# Total throughput at each time step
total_throughput = np. zeros ( SIMULATION_DURATION )

# Create throughput data for each project and calculate total throughput
for i in range ( NUM_PROJECTS ):
    # Randomly vary the tps for each project to simulate fluctuating network conditions
    tps_variation = np. random.normal (0, 1000 , SIMULATION_DURATION )
    throughput_data [f'Project {i +1}'] = tps_distribution + tps_variation
    total_throughput += throughput_data [f'Project {i +1}']

 # Plotting the multi - line chart for individual projects
plt.figure ( figsize =(14 , 7))
for project , tps in throughput_data.items ():
    plt.plot ( time_steps , tps , label = project )

# Adding the total usage curve
plt.plot ( time_steps , total_throughput , label ='Total Usage', color ='black', linewidth =2, linestyle ='--')

# Chart configurations
plt.title (' Transaction Throughput for Layer 1 Projects and Total Usage on Layer 0 Network')
plt.xlabel ('Time ( seconds )')
plt.ylabel (' Transactions per Second ( tps )')
plt.legend ()
plt.grid ( True )
plt.show ()
```
````

### The Annual Percentage Rate (APR)

````python
```python
import numpy as np
import matplotlib . pyplot as plt

def apr_function (x):
    base = 15 * 10**15
    apr_decimal = -np. log10 (x / 2000 + 0.0001) / np. log10 ( base ) - 0.1
    return apr_decimal * 100

x_values = np. linspace (0, 20, 400) # Assuming the time range is 0 to 20 years for illustration
y_values = apr_function ( x_values )

# Plotting the function
plt.figure( figsize =(10 , 5))
plt.plot( x_values , y_values , label ='APR over time')
plt.title('APR as a function of Time ( Percentage )')
plt.xlabel('Time ( years )')
plt.ylabel('APR (%)')
plt.legend()
plt.grid( True )
plt.show()
```
````


# Tokenomics

### Introduction

This paper introduces Phron, a groundbreaking approach to blockchain technology by integrating artificial intelligence (AI) capabilities into the foundational Layer 0. Building upon the traditional principles of decentralization, security, and scalability, an AI-based Layer 0 blockchain aims to revolutionize the landscape of distributed ledger systems.

The core of our proposed solution lies in the incorporation of AI algorithms, enabling dynamic consensus mechanisms, predictive security measures, and adaptive scalability. By leveraging machine learning, the proposed chain adapts to evolving network conditions, enhancing efficiency and responsiveness in real-time. This adaptive consensus model not only strengthens resistance against attacks but also optimizes the network’s performance under various scenarios.

The proposed AI-based Layer 1 to be constructed on the master classes in Layer 0 introduces intelligent contract execution, augmenting the capabilities of smart contracts. Through integrated machine learning algorithms, the system gains the ability to autonomously optimize contract execution, predict potential vulnerabilities, and dynamically adjust gas fees based on current market conditions. This not only streamlines transaction processing but also enhances the overall security and efficiency of smart contract operations.

In this paper, we go over the design principles, technical architecture, the integration of AI master class modules into the Layer 0 blockchain, and how Layer 1 gains access to the underlying Layer 0 blockchain. We introduce novel approaches to solve Layer 1 bootstrapping issues while still securing the chain by Node - Block-Sharing (NBS). The introduction of Adaptive AI Staking (AAIS) builds on the built-in master classes to determine the node reward boost allowing for a more efficient anesthetization. Finally, we introduce the AI arbiter in the chain governance voting mechanism. The arbiter solves the long-standing issue of how to determine the voting power of the users.

We explore the impact of AI on decentralization, security, and scalability, presenting empirical evidence of improved performance through simulations and real-world use cases.


# Vision and Inspiration

### Vision

PhronAI is the avant-garde Layer-1 blockchain that blends EVM compatibility and Proof-of-Stake, featuring an AI-driven Consensus Mechanism. PhronAi introduces a new proprietary consensus layer, enhanced by machine learning algorithms, with its core technology, Sophia, which enables transaction processing times of under 0.9 seconds at an average cost of $0.00001 and maintains over 31,000 transactions per second, achieving unparalleled network scalability without congestion.

PhronAI is the first chain that establishes the usage of a dynamic consensus algorithm through the appliance of Al tools managed automatically by the Sophia Protocol giving an available testing sandbox to understand and improve the current Al model used for our next application. Once PhronAI is optimally refined, the technology will transition to PhronZero. PhronZero expands each chain built upon it with AI technology, granting it heightened efficiency, simplicity, and communication capabilities.

PhronAI empowers projects to create tailored solutions across various digital and real-world sectors, enabling efficient, secure, interoperable communication. This ecosystem nurtures trustless cooperation among applications, positioning PhronAI as a cornerstone for constructing a Web3 future that leverages the full potential of AI technology \[1].

### Inspiration

In the information era, blockchain and artificial intelligence are reshaping industries and redefining interactions with data and transactions. Both have emerged as transformative mediums, disrupting sectors ranging from finance to supply chain management. However, a genuine integration of the capabilities of both technologies, which would allow for a synergy that opens new possibilities, has yet to be realized.

The fusion of blockchain and artificial intelligence marks a significant leap forward in technological advancement, introducing a synergy that extends beyond the capabilities of each technology individually. Blockchain’s decentralized and secure infrastructure for managing transactions and data is complemented by artificial intelligence’s prowess in analyzing extensive datasets to uncover insights and streamline decision-making. This partnership not only can solve problems such as data privacy, security, and transparency but also sets the stage for the development of groundbreaking applications


# Phron AI: What’s under the hood?

At the heart of the Phron blockchain lies PhronAI, a sophisticated amalgamation of cutting-edge technologies designed to fuel its decentralized ecosystem. PhronAI operates as the brainpower behind the platform, orchestrating various functions to ensure efficiency, security, and scalability.

At its core, PhronAI harnesses the power of artificial intelligence (AI) to optimize consensus mechanisms, enhance data validation processes, and streamline transaction throughput. Leveraging AI algorithms, PhronAI dynamically adjusts network parameters, adapting to fluctuating demands and maintaining optimal performance levels.

One of the key features of PhronAI is its ability to autonomously detect and mitigate potential security threats, fortifying the network against malicious activities such as DDoS attacks, double-spending, and Sybil attacks. Through continuous monitoring and analysis of network behavior, PhronAI reinforces the blockchain’s resilience, safeguarding user assets and preserving the integrity of transactions.


# Sophia: Statistical Consensus Mechanism

Sophia utilizes a set of rules designed to analyze and interpret the metrics data of nodes, uncovering their functional capacity to participate in the network. Through this application, three categories of validators are activated to process a broad spectrum of transactions submitted at varying fee rates. This mechanism enhances the block production process by expanding the chain’s capabilities, setting the standard transaction fee remarkably low based on previously mentioned average metrics. This standard cost applies to all transactions created and submitted by end-users, ensuring their rapid processing is comparable to high-fee transactions on other blockchains.

Periodically, Sophia evaluates individual statistics and generates a list categorizing validators into three groups. The Deep Learning Mechanisms oversee the PhronAi block sequence holistically, identifying any anomalies and initiating a Machine Learning auto-response mechanism to mitigate the risk posed by any potentially malicious party. Furthermore, validators within these groups are tasked with processing transactions immediately, based on fee values, benefiting end-users, node owners, and developers alike.

Validator participation within the network is carefully assessed using various metrics, which, after each mechanism cycle, serve as inputs for the next. Should a validator exhibit reduced participation, its metrics are recorded as low. With low metrics as inputs, there is a possibility of category shifts among validators, from super node to fast node or average node. Consequently, PhronAi motivates validators to engage actively in the network by processing blocks that include the maximum number of transactions. The first step involves collecting inputs from useful metrics that a node calculates independently. During the network’s initialization phase, these metrics, serving as input values, are supplied by the genesis file and a self-enforcing smart contract. Once the statistical algorithm becomes fully operational, metrics input values will also be directly obtained from the event trigger functionality.

Low latency, high throughput, the total number of votes, and maximum liveness metrics are sorted separately. For example, in the case of low latency, the individual matrices of all validators will be used for low-latency sorting. After this process, sorted lists from each metric are passed to the next step. The following details the criteria used in sorting each list of metrics for the super, fast, and average categories.

A variable is declared by defining an equation:

*x =TotalnumberofValidators/NumberofGroups*

The number of validator groups is 3.

The top 'x'metrics in each sorted list are considered super metrics. Similarly, the remaining top 'x'metrics in each sorted list are considered fast metrics. All remaining metrics will be considered as average metrics.

Validators are categorized into super, fast, and average nodes based on a sorted list of all metrics. A validator is formally designated as a super node if it consistently appears as a super node in every sorted list. Similarly, a validator is classified as a fast node if it is listed as fast in at least three sorted lists. If these criteria are not met, the validator is designated as an average node. At this point, three comprehensive lists containing the IDs of all validators in the network are compiled, categorizing them as super, fast, and average nodes respectively.

In this phase, validator IDs within the super, fast, and average node categories retrieve their records from databases and caches, leading to the creation of fully functional validator objects ready to participate in the block-producing mechanisms.

The registry service temporarily stores the active validator groups from these three categories. These groups are also permitted to engage in the event emission and evaluation process for a specific epoch round.

Concurrently, a self-enforcing event trigger service operates in parallel, generating input signals for the initial phase of the statistical algorithm. This service additionally generates input signals in reaction to particular events, such as the addition or removal of a validator. Consequently, the data-capturing fields of input objects may be initialized or aligned with input matrices. Moreover, this phase is technically regarded as the concluding step of the statistical algorithm.

This final step also operates in parallel and shares its output with the continuous execution of the process already running in the previous step. Its primary purpose is to monitor the liveness of validators within each group. Should any changes in the liveness status occur, such as the addition of new validators or the removal of existing ones, a reporting event is generated and conveyed through the event trigger service.


# PhronZero Layer 0

A Layer 0 blockchain, sometimes referred to as a "protocol layer" or "foundational layer," represents the underlying infrastructure upon which other blockchain layers operate. Unlike Layer 1, which typically encompasses blockchains like Bitcoin and Ethereum, Layer 0 is not concerned with specific applications or consensus mechanisms. Instead, it focuses on fundamental protocols and infrastructure components that provide the backbone for decentralized networks to function efficiently and securely (2]. Phron Zero blockchain provides the foundational infrastructure and protocols that enable the functioning of decentralized networks. It sets the stage for innovation and development at higher layers, empowering developers to build decentralized applications (dApps), decentralized finance (DeFi) protocols, and other blockchain-based solutions on top of a robust and secure foundation. The main innovations of PhronZero are Master Class and Node-Block-Sharing (NBS).

### Master Class

The concept of classes in modern programming languages serves as a cornerstone for creating reusable structures from which objects can be instantiated (3, 4]. Extending this paradigm to the realm of blockchain, the Phron Master Class introduces a pioneering approach to enhancing blockchain functionality and extensibility.

At its core, the Phron Master Class enables the blockchain to evolve and adapt by incorporating new functionalities through the addition of Master Classes. These Master Classes undergo a rigorous validation and regression testing process to ensure their compatibility and reliability within the blockchain ecosystem. Once validated, Master Classes are seamlessly integrated into the chain, becoming readily available for utilization by smart contracts.

The adoption of a Master Class is not only a technical decision but also an economic one. To invoke a Master Class, users are required to pay gas fees in addition to any other fees stipulated by the creator of the Master Class. This token economics framework is meticulously designed to incentivize the creation of Master Classes and foster a vibrant ecosystem of innovation and collaboration within the blockchain community.

By allowing Master Classes to be adopted into the chain, Phron empowers developers and stakeholders to introduce novel functionalities, optimizations, and improvements to the blockchain network. Whether it's introducing advanced cryptographic techniques, implementing complex algorithms, or enhancing interoperability with external systems, Master Classes serve as the building blocks for unlocking new capabilities and driving the evolution of blockchain technology. The integration

<figure><img src="/files/uO69Nc8eE3miGX9tvpzA" alt="" width="375"><figcaption></figcaption></figure>

of Master Classes fosters a culture of openness and collaboration, where developers can contribute their expertise and innovations to the broader blockchain ecosystem.

Through a transparent and inclusive validation process, Phron ensures that Master Classes meet the highest standards of quality and reliability, thereby instilling confidence in their adoption by smart contracts and applications.

The Phron Master Class represents a paradigm shift in blockchain development, offering a scalable and extensible framework for incorporating new functionalities and innovations. By incentivizing the creation of Master Classes and fostering a collaborative ecosystem, Phron paves the way for the continuous evolution and advancement of blockchain technology.

### Node-Block-Sharing (NBS)

The bootstrapping issue and lack of sufficient incentives for node operations are common challenges faced by Layer 1 blockchain networks (5]. These issues can impede the growth and sustainability of newly deployed chains, limiting their ability to operate securely and efficiently (6]. Node Block Sharing (NBS) presents a novel solution to these challenges, offering a comprehensive approach to address not only bootstrapping but also enhancing transaction processing and incentivizing node participation.

NBS leverages the underlying infrastructure of Phron Zero, a foundational protocol shared by all Layer 1 chains built upon it. This interoperability ensures cross-compatibility of transaction hashing, enabling nodes to seamlessly mine transactions across multiple Layer 1 chains. By tapping into a shared pool of participating nodes, each chain can access the necessary computational resources to process transactions efficiently, regardless of its individual node count.

One of the key benefits of NBS is its ability to address the bootstrapping issue by providing a decentralized network of nodes ready to support newly deployed chains. Instead of relying solely on the native node population of a specific chain, newly launched networks can leverage the existing infrastructure of Phron Zero, significantly reducing the time and resources required for network initialization and stabilization.

NBS introduces a mechanism for optimizing mining rewards and transaction processing fees based on node status and network demand. By dynamically adjusting mining fees according to node availability and performance, each chain can incentivize node participation while ensuring fair compensation for computational resources contributed. This approach not only promotes a healthy ecosystem of node operators but also enhances the overall security and efficiency of transaction processing across Layer 1 chains.

To further enhance the efficiency and effectiveness of NBS, an AI agent can be employed to optimize the return on investment (ROI) for each participating node. By analyzing network dynamics, transaction volumes, and node performance metrics, the AI agent can dynamically adjust mining strategies and fee structures to maximize profitability for individual nodes while maintaining network stability and security.

Node Block Sharing represents a pioneering approach to addressing the bootstrapping issue and incentivizing node participation in Layer 1 blockchain networks. By leveraging cross-chain compatibility, dynamic fee structures, and AI-driven optimization, NBS offers a scalable and sustainable solution to the challenges facing decentralized blockchain ecosystems

<figure><img src="/files/xNKVWYi20ynvYW4uUgLn" alt="" width="375"><figcaption></figcaption></figure>


# Phron Layer 1

A Layer 1 blockchain is the base layer of a blockchain network, where the primary functionalities such as transaction processing, consensus mechanisms, and smart contract execution take place. Layer 1 blockchains serve as the foundation upon which decentralized applications (dApps) and various other protocols are built \[7].

### AI Arbiter

The voting weight issue in blockchain governance revolves around the complexity of determining the influence each participant holds in decentralized decision-making within a blockchain network \[8, 9]. In decentralized governance systems, such as those prevalent in blockchain projects, decisions concerning protocol upgrades, changes, or community initiatives are typically made through a voting mechanism \[10]. The introduction of an AI arbiter within Phron’s governance system revolutionizes this aspect by harnessing advanced artificial intelligence algorithms. Unlike conventional methods reliant on static metrics like token holdings or stake sizes, the AI arbiter considers a diverse array of dynamic factors to fairly allocate voting influence to each participant \[11].

The incorporation of an AI arbiter within the governance voting mechanism of the Phron chain signifies a breakthrough in addressing the persistent challenge of determining users’ voting power in decentralized decision-making processes. Traditionally, this issue has sparked debates regarding fairness, transparency, and susceptibility to manipulation. One pivotal advantage of employing an AI arbiter lies in its capability to analyze intricate datasets and discern patterns, trends, and user behaviors that may elude human observation. Through machine learning techniques, the AI arbiter continually adapts and improves, ensuring precise and equitable distribution of voting power over time. The AI arbiter introduces objectivity and impartiality, which are lacking in human-driven governance systems. Eliminating biases and subjective judgments guarantees that decisions are based solely on merit and community interests rather than individual inclinations.

From an efficiency point of view, the AI arbiter enhances governance efficiency and scalability by automating essential tasks such as voter registration, verification, and vote tabulation. This not only streamlines decision-making but also mitigates the risk of human error or manipulation.

Beyond its role in determining voting power, the AI arbiter offers valuable insights and recommendations to inform governance decisions. By analyzing historical voting patterns and market data, it aids users in making informed decisions aligned with Phron chain’s long-term objectives and sustainability.

### Adaptive AI Staking (AAIS)

Blockchain staking is a mechanism used to secure and validate transactions on a blockchain network, as well as to incentivize network participants to actively contribute to the network’s operation. Staking involves users locking up a certain amount of cryptocurrency tokens as collateral to participate in the network’s consensus process. In return for staking their tokens, participants are rewarded with additional tokens as an incentive for helping to maintain the network’s security and integrity \[12]. Blockchain staking offers several advantages over traditional Proof of Work (PoW) consensus mechanisms, including reduced energy consumption, scalability improvements, and potentially enhanced decentralization. Additionally, staking enables cryptocurrency token holders to earn passive income by contributing to network validation, thereby encouraging sustained investment and involvement in blockchain ecosystems \[13].

Phron utilizes Adaptive AI Staking (AAIS), introduced by Dr. Adel ElMessiry, which is an innovative approach to blockchain staking that leverages artificial intelligence (AI) algorithms to dynamically adjust staking parameters based on real time network conditions, user behavior, and market dynamics. This methodology aims to optimize staking rewards, mitigate risks, and enhance the efficiency of the staking process. The main characteristics of AAIS are expanded in the following sections.

#### Dynamic Staking Parameters

AAIS utilizes AI algorithms to continuously analyze various factors such as network congestion, transaction volume, token price movements, and user participation. Based on this analysis, AAIS dynamically adjusts staking parameters such as staking duration, reward rates, and token allocation to maximize returns and adapt to changing network conditions.

#### Risk Management

AAIS incorporates risk management strategies to mitigate potential losses and protect stakers’ interests. AI algorithms monitor market volatility, security threats, and other risk factors and automatically adjust staking parameters to minimize exposure to risks such as price fluctuations and network vulnerabilities.

#### Customizable

AAIS prioritizes the interests of stakers by tailoring staking parameters to individual preferences, risk tolerance, and investment goals. Users have the flexibility to customize their staking preferences and adjust parameters such as staking duration, reward distribution frequency, and withdrawal options to suit their needs.

#### Optimized Reward Distribution

AAIS optimizes reward distribution mechanisms to ensure fair and equitable distribution of staking rewards among participants. AI algorithms dynamically adjust reward rates based on factors such as staking duration, token holdings, and network contribution, incentivizing active participation and encouraging long-term engagement.

#### Continuous Learning

AAIS incorporates machine learning techniques to continuously learn from past performance, user feedback, and market data to refine its algorithms and improve staking efficiency over time. By analyzing historical data and identifying patterns, AAIS can make more accurate predictions and better optimize staking parameters to maximize returns for participants. The end goal of AAIS is to adjust the required staking amount and the rewards in a manner that rewards user behavior that is conducive to the entire ecosystem over the long run.


# Token Economics

### Introduction

PhronZero presents a pioneering approach to the integration of blockchain and artificial intelligence (AI), offering a layer 0 infrastructure designed to empower Layer 1 blockchains with unprecedented AI capabilities. The model aims to ensure the sustainability, growth, and decentralized governance of the ecosystem and is constructed to incentivize participation, secure the network, and facilitate a vibrant economy centered around AI and blockchain synergy.

### Purpose of the Token

* Transaction Fees: Used to pay for transactions and services within the PhronZero ecosystem, including smart contract deployments and AI service calls.
* Staking: Required for participating in network consensus as validators, securing the network, and earning rewards.
* Governance: Grants holders the right to vote on proposals concerning the network’s development, feature integrations, and use of the ecosystem fund.
* AI Services Access: Enables access to advanced AI capabilities and services provided by PhronZero, acting as a payment mechanism within the AI marketplace

### Deflationary Mechanism

**Transaction Fee Burns:** A portion of transaction fees (e.g., 0.5%) is burned, reducing the total supply over time and creating deflationary pressure.

**AI Service Fee Burns:** Similar to transaction fees, a portion of the fees paid for using AI services within PhronZero will be burned.

### Staking and Validator Incentives

**Dynamic Staking Rewards:** Adjusted based on network participation levels, total staked amount, and overall network performance to ensure attractive yet sustainable reward levels \[14]

### Dynamic Gas Fee Model

Optimizing for network efficiency and user experience, we employ a dynamic gas fee model, drawing inspiration from Ethereum’s EIP-1559 \[15], formulated thus:

<figure><img src="/files/bjDWSDAxFGGpAmS12Wp6" alt="" width="375"><figcaption></figcaption></figure>

* **BaseFee(t):** Dynamically adjusts based on block space utilization, ensuring adaptability to network demand.
* **Tip:** An optional incentivization for validators to prioritize transactions, enhancing throughput during peak times.
* **∆C(τ ) and ∆N (τ ):** Represent the rate of change in transaction complexity and network congestion, respectively.
* **ϵ:** A sensitivity parameter for the token price stabilization mechanism.
* $$P\_{target}$$ **and P (t):** Target and current token prices, guiding fee adjustments to market conditions.

### Storage Fee Formulation

Reflecting considerations of data size, redundancy, and depreciating storage costs over time:

<figure><img src="/files/hvnttvFLcC1ZXC3v8wrG" alt="" width="375"><figcaption></figcaption></figure>

* **StorageBaseFee:** Cost per unit of data storage.
* D: Size of the data stored.
* R: Redundancy factor for data reliability.
* λ: Reflects decreasing storage technology costs over time.

### Fee Distribution Mechanism

Encouraging a collaborative network through a model that rewards validators based on performance:

* F : Total transaction fees collected.
* α: Base coefficient for fee distribution between layers.
* β: Adjusts distribution based on validator performance.
* P : Performance metric for validators.

### Staking Rewards Dynamics

Enhancing network security and stakeholder engagement via a dynamic staking rewards model:

<figure><img src="/files/Wu2IDYKHG1kKvdh9RTHb" alt="" width="375"><figcaption></figcaption></figure>

* I: Inflation rate for reward distribution.
* S(t): Total amount staked.
* γ: Validator performance coefficient.
* θ: Token price stabilization coefficient.

These mechanisms are crafted to ensure the blockchain remains adaptable, efficient, and economically sustainable, fostering a robust ecosystem conducive to long-term stability.

### Dual Token Architecture

A dual token architecture in blockchain refers to a system where there are two distinct types of tokens operating within the same ecosystem, typically with one token serving as the default base currency and another as a customizable token specific to individual layers or chains built on top of the base protocol. In this scenario, let’s explore the architecture with Phron Zero as the default token \[1, 16].

#### Phron Zero Token (Default Token)

Phron Zero token serves as the default base currency within the blockchain ecosystem. It is used for various purposes, such as transaction fees, rewards, and value exchange within the network. Phron Zero token is the foundational token upon which the entire ecosystem is built. It ensures interoperability and consistency across different layers and chains within the ecosystem.

#### Layer 1 Custom Tokens

Any Layer 1 blockchain built on top of Phron Zero can opt to incorporate a custom token specific to its chain. These custom tokens can have their own unique features, use cases, and economic models tailored to the specific requirements of the layer or chain. Custom tokens can be used for various purposes, including governance, utility, incentivization, and more within their respective chains.

#### Interoperability Between Layer 1

The dual token architecture ensures interoperability between the default Phron Zero token and the custom tokens. Users can seamlessly transact and exchange value between different chains and layers within the ecosystem, irrespective of the specific tokens being used. Smart contracts and protocols are designed to accommodate both Phron Zero and custom tokens, facilitating smooth interactions between them. Think of it as the reserve currency of the global monitor system.

#### Integration and Development

Developers building on top of Phron Zero can choose to integrate the default token or create custom tokens specific to their applications or layer 1 blockchains. Development frameworks, APIs, and toolkits are provided to simplify the process of token creation and integration, enabling developers to focus on building innovative solutions.

#### Economic Model and Governance

The economic model of the ecosystem may involve mechanisms for governing the issuance, distribution, and utilization of both Phron Zero and custom tokens \[17]. Governance structures ensure that the interests of token holders and participants are aligned with the overall goals and sustainability of the ecosystem. In summary, a dual token architecture in blockchain, with Phron Zero as the default token, allows for flexibility, customization, and interoperability within the ecosystem. It empowers developers to build diverse applications and layer 1 blockchains while maintaining a cohesive network supported by the foundational Phron Zero token.

### Incentives

An initial rewards curve for a newly launched protocol focuses on encouraging the use of a higher proportion of trusted Layer-0 (L0) nodes during the critical early stages of development and operation. This approach is strategically advantageous because it ensures a more secure and stable launch by leveraging the established security and reliability of L0 nodes. By incentivizing the utilization of these nodes through a reward structure that makes it more cost-effective to use more L0 nodes rather than fewer, the protocol can maintain integrity and trustworthiness in its nascent phase.

<figure><img src="/files/frDzMX1jL85aCpnsWuQ9" alt="" width="375"><figcaption><p>Fig. 2: Bootstrapping Phase Rewards Curve Model</p></figcaption></figure>

As the project matures and gains stability, trust, and a wider validator base, the rewards curve can transition. This change reflects the growing confidence in the protocol’s own Layer-1 (L1) validators and a deliberate shift towards encouraging a more decentralized model. The upsloping rewards curve now incentivizes a gradual reduction in dependency on L0 nodes, rewarding the protocol for diversifying its validator network. This evolution in the incentives curve aligns with the project’s development trajectory, from relying on the foundational security of L0 nodes to fostering its autonomous, decentralized security apparatus as it matures.

<figure><img src="/files/6xerHeNdvfeWdNNVsN8x" alt="" width="375"><figcaption><p>Fig. 3: Stability Phase Rewards Curve Model</p></figcaption></figure>


# Staking

The Phron blockchain employs a novel approach to validator selection, leveraging both user staking and AI-ranked performance to ensure a robust, fair, and meritocratic system. This method prioritizes high-performing nodes while incorporating community trust and randomness to democratize the selection process.

### Meritocratic Selection

Validators are chosen based on a combination of AI-generated performance metrics and user staking, promoting a system where merit and community trust determine validator selection. The AI scores and ranks nodes by their operational efficacy, creating a competitive environment that motivates validators to uphold high standards. This merit-based selection system ensures that the most reliable and efficient validators are prioritized.

### Community Participation

Incorporation of user staking into the validator ranking allows the community to have a direct influence on the selection process. Validators that receive higher stakes from the community are perceived as more trusted, thereby integrating a democratic element into the system. This approach aligns the network’s operation with the preferences and trust of its users.

### Fairness and Randomness

To further ensure fairness, the system includes a random lottery element that considers both the AI rankings and the percentage of stakes. This mechanism introduces a degree of randomness, mitigating biases and providing opportunities for newer or smaller validators to participate in network validation.

### Selection Algorithm

The final decision on validator selection is based on the following factors:

1. The AI ranking of a node *k*, denoted as $$R^{k}\_{\text{AI}}$$, ranks nodes in ascending order based on their performance, with the best nodes receiving a higher rank.
2. The stake-based ranking of a node *k*, denoted as $$R^{k}\_{\text{Stake}}$$, applies the same ranking principle, prioritizing nodes with higher stakes.
3. A random lottery that accounts for both AI and stake-based rankings, calculating the probability $$R\_{\text{k}}$$ for a node k to be selected as a validator.

The algorithm is formalized by the following equations:

<figure><img src="/files/mTaTJFxVWZ6XjEswV4O1" alt="" width="375"><figcaption></figcaption></figure>

where A is the sum of AI ranks for all nodes, B is the sum of stake-based ranks, and $$P\_{\text{k}}$$ represents the selection probability of node *k*

### Reward System

PHRON constitutes the link between the PhronAi Ecosystem and the holder. The PHRON reward system for node validators will work with the APR method; it is described with the following equation:

<figure><img src="/files/JpB9JMQeRaEnjqtBRTY1" alt="" width="375"><figcaption></figcaption></figure>

where:

* 0 ≤ x < ∞
* y is the APR (in decimal form)
* x is the time (in years)

This APR calculation factors into the broader staking and reward mechanism, ensuring validators are incentivized proportionally to their commitment and performance over time.

<figure><img src="/files/yAYYThnRfpDeZOBsEwKZ" alt="" width="375"><figcaption></figcaption></figure>


# Governance

In an endeavor to ensure a high degree of decentralization, PhronAI introduces an on-chain governance model predicated on a vote-escrowed mechanism. This approach empowers token holders to influence the ecosystem dynamically, aligning with the principles of decentralized autonomous organization (DAO) governance.

### Vote-Escrowed Tokenomics

Vote-escrowed tokenomics grants token holders the autonomy to determine a lock-up period for their tokens, effectively tying the token’s utility to the duration of its lock.

The extended commitment to lock up tokens translates into enhanced influence within the network, manifesting in:

* Enhanced governance voting power.
* Increased staking rewards.
* Amplified voting impact on specific liquidity pools.

**veTokens Align Incentives:** The veToken model is designed to synchronize the protocol’s success with that of the token holders’. A prolonged lock-up period symbolizes a vested interest in the protocol’s prosperity.

**VeTokens Encourage DAO Participation:** By offering additional voting power for longer lock-up periods, the protocol incentivizes users to ”max time-lock” their tokens, thereby strengthening their governance voice. This mechanism ensures that token holders who are deeply invested in the DAO’s future are rewarded with greater influence.

### Quadratic Voting

To further democratize the governance process and mitigate the risks of centralization and collusion, PhronAI will employ a quadratic voting system. This system ensures that as token holders acquire more tokens, the marginal increase in their voting power diminishes, promoting a more equitable distribution of governance influence.

The governance voting power, V , is determined by the equation:

<figure><img src="/files/9nzuLkOBjp5gr6rzx7Ns" alt="" width="375"><figcaption></figcaption></figure>

where:

* V represents the vePhron balance, indicating the voting power.
* R denotes the Phron native token quantity.
* L is the token lock-up period multiplier, enhancing the token’s voting power.

The vePhron balance declines linearly from the initiation of the lock-up period to its end, at which point stakeholders can reclaim their Phron tokens. However, token holders are afforded the flexibility to extend or renew their lock-up duration at any juncture, enabling them to either augment or maintain their vePhron balance and, by extension, their governance influence.


# Chain Simulations

### Transaction Throughput Simulation

To evaluate the robustness and scalability of the foundational Layer 0 network, we performed a simulation of transaction throughput for several Layer 1 projects running concurrently. The primary aim was to observe the network’s ability to manage and distribute its transaction processing capacity among the projects.

#### Simulation Parameters

The simulation was conducted under the following assumptions:

* **Layer 0 Capacity:** The maximum transactions per second (tps) capacity was set at 31,000, reflecting a high-throughput blockchain infrastructure.
* **Even Distribution:** The Layer 0 network’s tps capacity was evenly divided among the Layer 1 projects, emulating a fair and balanced load-sharing protocol.
* **Temporal Scope:** The simulation covered a 100-second timeframe, providing a snapshot of network activity in a high-velocity environment.

#### Throughput Simulation Results

The throughput simulation \[18] results (Figure 5) showcased the transactions processed by each Layer 1 project over time. The graphical representation illustrated that despite the fluctuations typically observed in network conditions, each project maintained a consistent level of activity, indicating a resilient and well-dimensioned network infrastructure.

<figure><img src="/files/hxYIvcnCp452i1WVc6ni" alt="" width="375"><figcaption><p>Fig. 5: Simulated Transaction Throughput for Layer 1 Projects on Layer 0 Network.</p></figcaption></figure>

### Gas Fee Simulation

Complementary to the throughput analysis, a simulation of gas fees was executed \[19], capturing the computational and storage demands of various dApp types. This simulation aimed to offer insight into the costs associated with on-chain activity, from simple transactions to complex smart contract interactions.

#### Assumptions for Gas Fee Simulation

The following assumptions were integral to the gas fee simulation:

1. **Computational Complexity:** Each dApp type exhibited a distinct pattern of transaction complexity, informed by common use case scenarios.
2. **Storage Requirements:** dApps with storage needs were attributed higher gas fees, proportional to the size of the data being managed.
3. **Network Congestion:** A sinusoidal model was applied to simulate network congestion, affecting the gas fees across all dApp types.

#### Phron Zero Gas Fee Simulation Results

Since Phron Zero is the foundation on which multiple Layer ones will run, we need to understand the holistic impact of each layer one chain on layer zero. Let’s first take a look at the assumed types of each layer one.

#### Simulated Gaming Focused Layer One

A gaming-focused blockchain is a specialized blockchain network designed specifically to cater to the needs and requirements of the gaming industry. Such a blockchain leverages the unique characteristics of blockchain technology to offer various features and functionalities tailored to gamers, game developers, and other stakeholders within the gaming ecosystem. The expected gas fees would be an order of magnitude higher for the gaming Dapps rather than the DEX or Storage.

<figure><img src="/files/KVjkZETNMTLbzxEiCRHM" alt="" width="375"><figcaption><p>Fig. 6: Simulated Gas Fee Consumption for Gaming Biased Layer 1.</p></figcaption></figure>

#### Simulated DEX Focused Layer One

A decentralized exchange (DEX) focused blockchain is a specialized blockchain network specifically designed to facilitate decentralized trading of digital assets, such as cryptocurrencies, tokens, and other blockchain-based assets. This type of blockchain prioritizes features and functionalities that enhance the performance, security, and user experience of decentralized exchange platforms. Naturally, such a chain would generate more swap related gas fees.

<figure><img src="/files/GrREkexasD8COZ832rJE" alt="" width="375"><figcaption><p>Fig. 7: Simulated Gas Fee Consumption for DEX Biased Layer 1.</p></figcaption></figure>

#### Simulated Storage Focused Layer One

A storage-focused blockchain typically prioritizes the efficient and secure storage of data on the blockchain network. Gas fees, which represent the cost of performing transactions or executing smart contracts on the blockchain, play a crucial role in incentivizing network participants and maintaining the security and integrity of the system. In a storage-focused blockchain, gas fees may be structured in a way that reflects the costs associated with storing and accessing data on the blockchain. Gas fees in a storage-focused blockchain are designed to reflect the costs of storing and accessing data on the blockchain while incentivizing efficient resource usage and maintaining network security and performance. By implementing a dynamic and transparent fee structure, the blockchain ensures that gas fees remain competitive, responsive, and aligned with the needs of network participants.

<figure><img src="/files/2VDl0aVi0k9ifbCE8RRK" alt="" width="375"><figcaption><p>Fig. 8: Simulated Gas Fee Consumption for Storage Biased Layer 1.</p></figcaption></figure>

### Phron Zero Simulated Gas Fee Consumption

The results, as visualized in Figure 9, depicted the variability of gas fees over time for gaming, DEX, and storage dApps. The simulation reflected that storage-intensive dApps may incur higher fees during peak data operations, whereas gaming and DEX dApps showed variable fees correlated with their interactive and market-driven activities.

<figure><img src="/files/qFfIV9iko4gBwXoA1Uz5" alt="" width="375"><figcaption><p>Fig. 9: Simulated Gas Fee Consumption for Different dApps.</p></figcaption></figure>

### Conclusion

The simulations confirm the Layer 0 network’s capacity to support a multi-faceted blockchain ecosystem, managing both high-velocity transactions and complex dApp interactions efficiently. By mirroring realistic operational conditions, the simulations validate the network’s design philosophy, highlighting its ability to adaptively balance performance and cost for diverse Layer 1 projects.


# Economic Simulation

The methodology will center on the use of stochastic approximations to model and analyze the system. This approach allows us to estimate the collective behavior of agents within a system under conditions of uncertainty and variability. By leveraging stochastic approximations, we can efficiently simulate and predict outcomes without the need for detailed data on every individual component. This principle underpins our commitment to achieving both accuracy and computational efficiency in our simulations. Simulations will be used with a focus on understanding price dynamics, not with the aim of predicting the exact future price, but rather to comprehend the conditions and environment conducive to price appreciation or identifying factors leading to price declines.

While PhronAI is envisioned to evolve into a blockchain of blockchains, our current evaluation will concentrate exclusively on its initial Layer-1. However, the potential of Layer 1 should be assessed with the understanding that its scope extends beyond merely its launch. This principle underscores the importance of viewing PhronAI’s Layer-1 not just as an isolated product but as a foundational element that contributes to the overall growth and success of the ecosystem.

### Modeling Parameters

* Run time 5 years.
* Initial price = $0.5
* Starting monthly transaction volume = $30 million
* Final monthly transaction volume = $300 million
* Pricing equation: Equation of exchange P=T/(MV) Allocation and emissions are highlighted above.
* Total tokens: 70% of the full supply (treasury and foundation are assumed to be out of circulation).
* Holding time: Lognormal Distribution.

The holding time data utilized in our analysis was compiled from a collection of holding times extracted from various industry projects. This dataset has been adopted as a robust basis for determining holding times, underpinned by the rationale that observed patterns across these projects offer a substantial foundation for formulating well-informed assumptions about future asset holding durations. By leveraging this historical data, we have established a benchmark for holding times, ensuring our projections are anchored in tangible, real-world observations and trends.

<figure><img src="/files/MqyG4EpJEp6rHHqkk9hB" alt="" width="375"><figcaption><p>Fig. 10: Visual Holding Time Representation as Lognormal Distribution.</p></figcaption></figure>

A simulation was conducted to test the resilience of the current assumptions. The simulation ran for 100 iterations. Each iteration consisted of the parameters displayed above. The results are shown below. The solid blue line shows the mean fair price, while the shaded areas show 95% confidence intervals.

### Base Scenario Simulation

It looks like a launch price of $0.5 can lead to a fair value of close to $60 as a best-case scenario over 5 years.

<figure><img src="/files/TchYqAv9GHFgAJllW6TR" alt="" width="375"><figcaption><p>Fig. 11: Base Scenario Simulation.</p></figcaption></figure>

### Conclusion

Price appreciation is observed even with conservative metrics. This indicates that even modest achievements relative to transaction volume can lead to significant value increases, highlighting the potential for growth despite cautious projections.

PPrice appreciation, along with the current token supply allocation and emissions, demonstrates that the tokenomics from a quantitative perspective are defensible and can appreciate even without modeling forward multiples, which are often observed in euphoric market conditions to be 5-10x.

Price appreciation is assessed exclusively within the scope of Phron L1, excluding consideration of the interconnectedness with L0 and other L1 networks. This approach underrates the real project’s value growth, which could be faster when the project’s ultimate vision is considered.

### Token Allocations

The tokenomics of Phron AI is structured with an initial circulating supply of 2,100,000,000 PHRON, with emissions for additional token creation to support future growth and scalability of the ecosystem.

1. **Private Sale (16%):** Unlocks at Token Generation Event (TGE), followed by a 6-month linear vesting period. This is designed to protect the ecosystem from excessive token infusion during the chain bootstrap phase.
2. **Public Sale (4%):** Unlocks at TGE, followed by a 2-month linear vesting period.
3. **Team (15%):** Subject to a 9-month cliff, with linear vesting from that point until month 24. The longer vesting period is designed to insure that the team will continue chain support for the next two years at a minimum.
4. **Ecosystem Supportive Nodes (15%):** This amount is reserved for the ecosystem nodes Locked indefinitely to support the nodes.
5. **Liquidity and market makers (17%):** Fully unlocked.
6. **Advisors (3%):** Subject to a 9-month cliff, with linear vesting from that point until month 24.
7. Foundation (20%): Fully unlocked. The funds will be used for building the L0 and the grants program. The grants program will fund L1s with a strategic focus, facilitating the creation of the Phron ecosystem. The foundation will be utilized to support the construction of Layer 0 and the development of the system. This allocation strategy is designed to prevent the distribution of excessively large stakes to any particular group, thereby helping to manage early-stage volatility.
8. Treasury (10%): Vesting over 4 years, linearly at 25

<figure><img src="/files/knyAEXkKVA3BkCsTco1c" alt="" width="375"><figcaption></figcaption></figure>

**Acknowledgements.** We would like to acknowledge the contributions of our community, especially to the completion of this work.


# Appendix A Simulation Code Example

The following is the code written in Python to generate the simulations used in the document above.

### Simulated Transactions Per Second (TPS) Over 24 Hours

````python
```python
import numpy as np
import matplotlib . pyplot as plt

base_tps_phronzero = 100000
base_tps_phronlayer1 = 50000

time_hours = np. arange (0, 24, 1)
network_load_factor_phronzero = 0.5 * np. sin (np .pi * time_hours / 12 - np.pi /2) + 1
network_load_factor_phronlayer1 = 0.5 * np.sin(np .pi * time_hours / 12 - np .pi /2) + 1.5

effective_tps_phronzero = base_tps_phronzero * network_load_factor_phronzero
effective_tps_phronlayer1 = base_tps_phronlayer1 * network_load_factor_phronlayer1

plt.figure ( figsize =(14 , 7))

plt.plot ( time_hours , effective_tps_phronzero , label ='PhronZero TPS', marker ='o')
plt.plot ( time_hours , effective_tps_phronlayer1 , label ='Phron Layer 1 TPS', marker ='x')

plt.title ('Simulated Transactions Per Second ( TPS) Over 24 Hours ')
plt.xlabel ('Time ( Hours )')
plt.ylabel (' Transactions Per Second ( TPS )')
plt.legend ()
plt.grid ( True )
plt.xticks ( time_hours )
plt.ylim (0, max ( effective_tps_phronzero ) + 50000)

plt.show ()
# \ end { verbatim *}
# \ subsection { Simulated Dynamic Gas Fee }
# \ begin { verbatim *}

def calculate_dynamic_gas_fee ( base_fee , tip , epsilon , p_target , p_current , delta_c ,
delta_n ):
    """
    Calculate the dynamic gas fee for a transaction based on the provided parameters .

    : param base_fee : Base fee of the transaction
    : param tip : Optional tip to miners / validators
    : param epsilon : Sensitivity parameter for token price stabilization
    : param p_target : Target token price
    : param p_current : Current token price
    : param delta_c : Rate of change in transaction complexity
    : param delta_n : Rate of change in network congestion
    : return : Calculated dynamic gas fee
    
    """
    price_adjustment = epsilon * ( p_target - p_current ) / p_current
    gas_fee = ( base_fee + tip + price_adjustment ) * ( delta_c + delta_n )
    return gas_fee

base_fee = 10
tip = 1
epsilon = 0.1
p_target = 1
p_current = 0.65
delta_c = 1
delta_n = 1
```
````

### Gas Fees for Storage Biased L1 with Secondary dApp Support

````python
```python
# Simulate dynamic gas fees over time for a single dApp type

time = np. arange(0, 10, 0.1)
gas_fees = [calculate_dynamic_gas_fee ( base_fee , tip , epsilon , p_target , p_current + t, delta_c , delta_n ) for t in time]

plt.figure( figsize =(10 , 6))
plt.plot(time , gas_fees , label ='Dynamic Gas Fee Over Time')
plt.title('Simulated Dynamic Gas Fee')
plt.xlabel('Time')
plt.ylabel('Gas Fee')
plt.legend()
plt.grid(True)
plt.show()
```
````

### Simulated Gas Fees

````python
```python
import numpy as np
import matplotlib . pyplot as plt

# Setup
t = np. linspace (0, 2 * np.pi , 400)
BaseRate = 10
StorageRate = 0.05
N = 0.5 * np. sin (t) + 1.5 # Network congestion

# Parameters for complexity (C)
A, B, V, M, S = 1.5 , 1, 2, 1.5 , 0.8
omega , eta , kappa , alpha , R,T= 2, 0.05 , 1, 0.1 , 5, 50
i = np. arange (1, int (np. max (t) / T) + 1) * T

# Gaming dApp
C_gaming = A * np.sin( omega * t) + B
D_gaming = np. zeros_like (t)
G_gaming = BaseRate * (1 + C_gaming + N) + StorageRate * D_gaming

# DEX
C_dex = V * np. log (1 + eta * t) + M * np. sin ( kappa * t)
D_dex = np. zeros_like (t)
G_dex = BaseRate * (1 + C_dex + N) + StorageRate * D_dex

# Storage dApp
C_storage = np. full_like (t, S)
D_storage = R * np.sum ([ np. exp(- alpha * (t - iT) **2) for iT in i], axis =0)
G_storage = BaseRate * (1 + C_storage + N) + StorageRate * D_storage

# Plotting
plt.figure( figsize =(12 , 8))
plt.plot(t, G_gaming , label ='Gaming dApp')
plt.plot(t, G_dex , label ='DEX')
plt.plot(t, G_storage , label ='Storage dApp', linestyle ='--')

plt.title('Simulated Gas Fees')
plt.xlabel('Time (in cycles )')
plt.ylabel('Gas Fee (in gui unit )')
plt.legend()
plt.grid(True)
plt.show()
```
````

### Gas Fees for Storage Biased L1 with Secondary dApp Support

````python
```python
import numpy as np
import matplotlib.pyplot as plt

# Setup
t = np. linspace (0, 2 * np.pi , 400)
BaseRate = 10
N = 0.5 * np. sin (t) + 1.5 # Simulated network congestion

C_gaming_primary = 1.5 * np. sin (2 * np .pi * t / max(t))
C_dex_secondary = 0.3 * np. sin (4 * np .pi * t / max(t)) # Reduced influence
C_storage_secondary = 0.2 * np. sin (4 * np .pi * t / max (t)) # Reduced influence

G_gaming = BaseRate * (1 + C_gaming_primary + N)
G_dex = BaseRate * (1 + C_dex_secondary + N)
G_storage = BaseRate * (1 + C_storage_secondary + N)

plt.figure ( figsize =(12 , 8))
plt.plot (t, G_gaming , label ='Gaming dApp - Primary ', color ='blue')
plt.plot (t, G_dex , label ='DEX dApp - Secondary ', color ='orange', linestyle ='--')
plt.plot (t, G_storage , label ='Storage dApp - Secondary ', color ='green', linestyle =':')

plt.title ('Gas Fees for Gaming Biased L1 with Secondary dApp Support ')
plt.xlabel ('Time (in cycles )')
plt.ylabel ('Gas Fee (in gwei )')
plt.legend ()
plt.grid ( True )
plt.show ()

plt.figure ( figsize =(12 , 8))

G_dex_primary = BaseRate * (1 + 2.0 * (np. sin (4 * np .pi * t / max (t)) **2) + N)
G_gaming_supportive = BaseRate * (1 + 0.3 * np.sin (2 * np .pi * t / max (t)) + N) 
# Increased presence from Gaming
G_storage_supportive = BaseRate * (1 + 0.2 * np.sin (4 * np .pi * t / max (t)) + N)

plt.plot (t, G_dex_primary , label ='DEX dApp - Primary', color ='orange')
plt.plot (t, G_gaming_supportive , label ='Gaming dApp - Supportive', color ='blue',linestyle ='--')
plt.plot (t, G_storage_supportive , label ='Storage dApp - Supportive', color ='green',
linestyle =':')

plt.title ('Gas Fees for DEX Biased L1 with Secondary dApp Support')
plt.xlabel ('Time (in cycles )')
plt.ylabel ('Gas Fee (in gwei )')
plt.legend ()
plt.grid ( True )
plt.show ()


plt.figure ( figsize =(12 , 8))
G_storage_primary = BaseRate * (1 + 0.8 * np. sum ([ np.exp ( -0.1 * (t - iT) **2) for iT in np. arange (1, int (np. max (t) / 50) + 1) * 50] , axis =0) + N)
G_gaming_supportive = BaseRate * (1 + 0.3 * np.sin (2 * np .pi * t / max (t)) + N) 
# Slightly increased presence from Gaming
G_dex_supportive = BaseRate * (1 + 0.2 * np. sin (4 * np .pi * t / max (t)) + N)

plt.plot (t, G_storage_primary , label ='Storage dApp - Primary', color ='green')
plt.plot (t, G_gaming_supportive , label ='Gaming dApp - Supportive', color ='blue', linestyle ='--')
plt.plot (t, G_dex_supportive , label ='DEX dApp - Supportive', color ='orange', linestyle =':')

plt.title ('Gas Fees for Storage Biased L1 with Secondary dApp Support')
plt.xlabel ('Time (in cycles )')
plt.ylabel ('Gas Fee (in gwei )')
plt.legend ()
plt.grid ( True )
plt.show ()
```
````

### Transaction Throughput for Layer 1 Projects and Total Usage on Layer 0 Network

````python
```python
import numpy as np
import matplotlib.pyplot as plt

# Simulation parameters
SIMULATION_DURATION = 100 # Total time for simulation in seconds
LAYER_0_TPS = 31000 # Layer 0's maximum tps
NUM_PROJECTS = 3 # Number of Layer 1 projects

# Assume an even distribution of Layer 0's TPS across Layer 1 projects
tps_distribution = LAYER_0_TPS / NUM_PROJECTS

# Simulating transaction throughput for each Layer 1 project over time
time_steps = np. linspace (0, SIMULATION_DURATION , SIMULATION_DURATION )
throughput_data = {}

# Total throughput at each time step
total_throughput = np. zeros ( SIMULATION_DURATION )

# Create throughput data for each project and calculate total throughput
for i in range ( NUM_PROJECTS ):
    # Randomly vary the tps for each project to simulate fluctuating network conditions
    tps_variation = np. random.normal (0, 1000 , SIMULATION_DURATION )
    throughput_data [f'Project {i +1}'] = tps_distribution + tps_variation
    total_throughput += throughput_data [f'Project {i +1}']

 # Plotting the multi - line chart for individual projects
plt.figure ( figsize =(14 , 7))
for project , tps in throughput_data.items ():
    plt.plot ( time_steps , tps , label = project )

# Adding the total usage curve
plt.plot ( time_steps , total_throughput , label ='Total Usage', color ='black', linewidth =2, linestyle ='--')

# Chart configurations
plt.title (' Transaction Throughput for Layer 1 Projects and Total Usage on Layer 0 Network')
plt.xlabel ('Time ( seconds )')
plt.ylabel (' Transactions per Second ( tps )')
plt.legend ()
plt.grid ( True )
plt.show ()
```
````

### The Annual Percentage Rate (APR)

````python
```python
import numpy as np
import matplotlib . pyplot as plt

def apr_function (x):
    base = 15 * 10**15
    apr_decimal = -np. log10 (x / 2000 + 0.0001) / np. log10 ( base ) - 0.1
    return apr_decimal * 100

x_values = np. linspace (0, 20, 400) # Assuming the time range is 0 to 20 years for illustration
y_values = apr_function ( x_values )

# Plotting the function
plt.figure( figsize =(10 , 5))
plt.plot( x_values , y_values , label ='APR over time')
plt.title('APR as a function of Time ( Percentage )')
plt.xlabel('Time ( years )')
plt.ylabel('APR (%)')
plt.legend()
plt.grid( True )
plt.show()
```
````


# References

ElMessiry, M., ElMessiry, A., ElMessiry, M.: Dual token blockchain economy framework. In: International Conference on Blockchain, pp. 157–170 (2019). Springer

Gangwal, A., Gangavalli, H.R., Thirupathi, A.: A survey of layer-two blockchain protocols. Journal of Network and Computer Applications 209, 103539 (2023)

Mitchell, J.C.: Concepts in Programming Languages. Cambridge University Press, ??? (2003)

Pierce, B.C.: Types and Programming Languages. MIT press, ??? (2002)

Garay, J.A., Kiayias, A., Leonardos, N., Panagiotakos, G.: Bootstrapping the blockchain, with applications to consensus and fast pki setup. In: Public-Key Cryptography- –PKC 2018: 21st IACR International Conference on Practice and Theory of Public-Key Cryptography, Rio de Janeiro, Brazil, March 25-29, 2018, Proceedings, Part II 21, pp. 465–495 (2018). Springer

Lantz, L., Cawrey, D.: Mastering Blockchain. O’Reilly Media, ??? (2020)

Sguanci, C., Spatafora, R., Vergani, A.M.: Layer 2 blockchain scaling: A survey. arXiv preprint arXiv:2107.10881 (2021)

Kiayias, A., Lazos, P.: Sok: blockchain governance. In: Proceedings of the 4th ACM Conference on Advances in Financial Technologies, pp. 61–73 (2022)

Tapscott, D., Tapscott, A.: Blockchain Revolution: How the Technology Behind Bitcoin Is Changing Money, Business, and the World. Penguin, ??? (2016)

Leonardos, S., Reijsbergen, D., Piliouras, G.: Weighted voting on the blockchain: Improving consensus in proof of stake protocols. International Journal of Network Management 30(5), 2093 (2020)

John, K., Rivera, T.J., Saleh, F.: Equilibrium staking levels in a proof-of-stake blockchain. Available at SSRN 3965599 (2021)

Choi, K.J., Jeon, J., Lim, B.H.: Optimal staking and liquid token holding decisions in cryptocurrency markets. Available at SSRN 4528742 (2023)

Kjorveziroski, V., Filiposka, S., Mishev, A.: Evaluating webassembly for orches- trated deployment of serverless functions. In: 2022 30th Telecommunications Forum (TELFOR), pp. 1–4 (2022). <https://doi.org/10.1109/TELFOR56187>. 2022.9983733

Tosh, D., Shetty, S., Foytik, P., Kamhoua, C., Njilla, L.: Cloudpos: A proof- of-stake consensus design for blockchain integrated cloud. In: 2018 IEEE 11Th International Conference on Cloud Computing (CLOUD), pp. 302–309 (2018). IEEE

Liu, Y., Lu, Y., Nayak, K., Zhang, F., Zhang, L., Zhao, Y.: Empirical analysis of eip-1559: Transaction fees, waiting times, and consensus security. In: Proceed- ings of the 2022 ACM SIGSAC Conference on Computer and Communications Security, pp. 2099–2113 (2022)

Cai, T., Cai, H., Wang, H., Cheng, X., Wang, L.: Analysis of blockchain system with token-based bookkeeping method. IEEE Access 7, 50823–50832 (2019)

Beck, R., Mu¨ller-Bloch, C., King, J.L.: Governance in the blockchain economy: A framework and research agenda. Journal of the association for information systems 19(10), 1 (2018)

Faria, C., Correia, M.: Blocksim: blockchain simulator. In: 2019 IEEE Interna- tional Conference on Blockchain (Blockchain), pp. 439–446 (2019). IEEE

Memon, R.A., Li, J.P., Ahmed, J.: Simulation model for blockchain systems using queuing theory. Electronics 8(2), 234 (2019)

Lee, J.Y.: A decentralized token economy: How blockchain and cryptocurrency can revolutionize business. Business Horizons 62(6), 773–784 (2019)


# Developers

Phron AI Layer 1 is a EVM-based L1 blockchain designed to empower developers with decentralized AI capabilities to provide optimized metrics across dApps. It provides an optimized environment for building, deploying, and integrating decentralized applications (dApps).


# Quick Start


# Rust toolchain

Rust is a modern, type-safe, and high-performance programming language that offers a comprehensive set of features for developing complex systems. Its strong emphasis on safety and concurrency makes it a popular choice among developers. The language is supported by an active and vibrant community, which contributes to a growing ecosystem of reusable libraries known as crates.

### Learning Rust

If you’re looking to dive into blockchain or smart contracts development you’ll need to become well-acquainted with Rust. Understanding the Rust programming language, its compiler, and toolchain management is essential for effectively utilising Substrate.

For beginners, a great starting point is [The Rust Programming Language book](https://doc.rust-lang.org/book/), often referred to as "the book," which provides a thorough introduction to the language. Additionally, the Rust website offers a variety of resources under the [Learn Rust](https://www.rust-lang.org/learn) section that can help guide your learning journey. As you set up your development environment, there are several key points to consider.

### About the Rust Toolchain

The Rust toolchain comprises essential components, including the rustc compiler, the cargo package and build manager, and the rustup toolchain manager. It's important to note that multiple versions of Rust can coexist in your environment, with different release channels available: stable, beta, and nightly builds. The rustup program is crucial for managing these versions and ensuring that you can easily switch between different toolchain programs based on your project’s requirements.

The rustc compiler is designed to produce binaries for various architectures, known as targets. Each target is specified by a string that informs the compiler about the desired output format. This functionality is particularly significant for Substrate, which compiles to both a native Rust binary and a WebAssembly (Wasm) target.


# Install

Before you can begin developing, it’s essential to prepare your development environment by installing the necessary compiler and tools. Since Substrate—and most of the tools used for Substrate development—are built using the Rust programming language, the first step is to install Rust on your computer.

The installation process for Rust varies depending on your operating system. Below are the instructions for each platform:

* **Linux**

Here's an improved version of your Rust installation guide. I've organized the information more clearly, enhanced readability, and provided additional context where needed.

## Rust Installation Guide for Linux

## Before You Begin

### Prerequisites

Before installing Rust, ensure your system meets the following requirements:

1. **Check Documentation:** Refer to your operating system's documentation for information about installed packages and how to download and install any necessary packages.
2. **Required Packages:** At a minimum, you need the following packages:

&#x20;        `clang`

&#x20;        `curl`

&#x20;        `git`

&#x20;        `make`

3. **Cryptography Support:** Since blockchain development requires standard cryptography for generating public/private key pairs and validating transaction signatures, you also need a package that provides cryptography:

&#x20;       For Debian-based systems (like Ubuntu): `libssl-dev`

&#x20;       For Red Hat-based systems (like Fedora): `openssl-devel`

## Install Required Packages

To install the necessary packages, follow these steps:

1. **Open a Terminal:** Log on to your computer and open a terminal shell.
2. **Check Installed Packages:** Use the appropriate package management command for your Linux distribution to check installed packages.
3. **Install Missing Dependencies:** Run the following command to install the required packages. Adjust the command based on your distribution.

### Example for Ubuntu:

{% code overflow="wrap" %}

```bash
sudo apt install --assume-yes git clang curl libssl-dev protobuf-compiler
```

{% endcode %}

### Other Distributions:

* **Debian:**

{% code overflow="wrap" %}

```bash
sudo apt install --assume-yes git clang curl libssl-dev llvm libudev-dev make protobuf-compiler
```

{% endcode %}

* **Arch:**

```bash
sudo pacman -S git clang curl openssl protobuf
```

* **Fedora:**

```bash
sudo dnf install git clang curl openssl-devel protobuf-compiler
```

* **OpenSUSE:**

{% code overflow="wrap" %}

```bash
sudo zypper install git clang curl libopenssl-devel protobuf-compiler
```

{% endcode %}

> ### **Note:**
>
> Different distributions may use different package managers and package names. Ensure you adjust the commands accordingly.

## Install Rust

1. **Download and Install rustup:** Use the following command to download and install the Rust toolchain:

```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
```

* Follow the on-screen prompts to proceed with the default installation.

2. **Update Your Shell:** To ensure your current shell session recognizes Cargo (Rust's package manager), run:

```bash
source $HOME/.cargo/env
```

3. **Verify Installation:** Check that Rust is installed correctly by running:

```bash
rustc --version
```

## Configure Rust Toolchain

1. **Set Default Toolchain:** Configure the Rust toolchain to default to the latest stable version:

{% code overflow="wrap" %}

```bash
rustup default stable
rustup update
```

{% endcode %}

2. **Add Nightly Release and Targets:** If you need nightly features or WebAssembly support, add the nightly release and targets:

```bash
rustup update nightly
rustup target add wasm32-unknown-unknown --toolchain nightly
```

3. **Verify Configuration:** Check your development environment configuration:

```bash
rustup show
rustup +nightly show
```

&#x20;  You should see output similar to:

<pre class="language-bash" data-overflow="wrap"><code class="lang-bash">   # rustup show
   active toolchain
   ----------------
   stable-x86_64-unknown-linux-gnu (default)
   rustc 1.62.1 (e092d0b6b 2022-07-16)

   # rustup +nightly show
   active toolchain
   ----------------
<strong>   nightly-x86_64-unknown-linux-gnu (overridden by +toolchain on the    command line)
</strong>   rustc 1.65.0-nightly (34a6cae28 2022-08-09)
</code></pre>

You have successfully installed the Rust toolchain on your Linux system! You can now start developing Rust applications. For more resources and documentation, visit [The Rust Programming Language](https://doc.rust-lang.org/book/).

* **macOS**

Here's an improved version of your documentation for installing Rust on macOS. You can copy this text into Google Docs to save it in .docx format.

## Rust Installation Guide for macOS

### Before You Install

Before setting up your development environment on macOS, ensure your computer meets the following requirements:

* **Operating System:** macOS 10.7 Lion or later
* **Processor Speed:** At least 2 GHz (3 GHz recommended)
* **Memory:** Minimum of 8 GB RAM (16 GB recommended)
* **Storage:** At least 10 GB of available storage
* **Internet Connection:** Broadband connection
* **Apple Silicon Support:** Ensure your setup supports Apple Silicon.

Additionally, **Protobuf** must be installed before the build process begins. To install it, run the following command:

```bash
brew install protobuf
```

## Install Homebrew

Homebrew is the recommended package manager for macOS. If you don't have it installed, follow these steps:

1. **Open Terminal:** Launch the Terminal application on your Mac.
2. **Install Homebrew:** Run the following command to download and install Homebrew:

{% code overflow="wrap" %}

```bash
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
```

{% endcode %}

3. **Verify Installation:** Check that Homebrew is installed successfully by running:

```bash
brew --version
```

You should see output similar to:

### Installation of Rust and Dependencies

To set up Rust and its dependencies, follow these steps:

1. **Open Terminal:** Ensure you are in the Terminal application.
2. **Update Homebrew:** Make sure Homebrew is up to date by running:

```bash
brew update
```

3. **Install OpenSSL:** Install the OpenSSL package:

```bash
brew install openssl
```

4. **Install Rust:** Download the `rustup` installation program and use it to install Rust:

```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
```

5. **Follow Prompts:** Follow the on-screen prompts to complete the default installation.
6. **Update Shell:** Include Cargo in your current shell session:

```bash
source ~/.cargo/env
```

7. **Verify Installation:** Confirm that Rust is installed correctly by running:

```bash
 rustc --version
```

## Configure the Rust Toolchain

1. **Set Default Toolchain:** Configure the Rust toolchain to use the latest stable version:

```bash
   rustup default stable
   rustup update
   rustup target add wasm32-unknown-unknown
```

2. **Add Nightly Release and Targets:** To include nightly features and WebAssembly support, run:

```bash
   rustup update nightly
   rustup target add wasm32-unknown-unknown --toolchain nightly
```

3. **Verify Configuration:** Check your Rust environment configuration:

```bash
   rustup show
   rustup +nightly show
```

&#x20;  You should see output similar to:

<pre class="language-bash" data-overflow="wrap"><code class="lang-bash"><strong>   # rustup show
</strong>   active toolchain
   ----------------
   stable-x86_64-apple-darwin (default)
   rustc 1.61.0 (fe5b13d68 2022-05-18)

   # rustup +nightly show
   active toolchain
   ----------------
   nightly-x86_64-apple-darwin (overridden by +toolchain on the command line)
   rustc 1.63.0-nightly (e71440575 2022-06-02)
</code></pre>

## Install CMake

To complete your setup, install CMake with the following command:

```bash
brew install cmake
```


# Developer CLI Tools

| [archive](https://docs.substrate.io/reference/command-line-tools/archive/) | Index and store all blocks, state, and transaction data for a Substrate-based chain in a relational SQL database. |
| -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| [sidecar](https://docs.substrate.io/reference/command-line-tools/sidecar/) | Use a REST service to interact with blockchain nodes built using FRAME.                                           |
| [subkey](https://docs.substrate.io/reference/command-line-tools/subkey/)   | Generate and manage public and private key pairs for accounts.                                                    |
| [subxt](https://docs.substrate.io/reference/command-line-tools/subxt/)     | Submit extrinsics to a Substrate node using RPC.                                                                  |


# Learn


# Why Substrate

### Substrate as a Strategic Foundation for PHRON

Substrate, a customizable blockchain framework, provides a robust foundation for PHRON. By leveraging its pre-built components, we can expedite development and ensure a solid technological basis for our project.

### Key Advantages of Substrate:

* Comprehensive Feature Set: Substrate offers a wide range of features, including peer-to-peer networking, consensus mechanisms, governance, and an Ethereum Virtual Machine (EVM), eliminating the need for redundant development.
* Tailored Customization: Substrate's modular architecture enables us to customize the framework to meet PHRON's specific requirements, ensuring compatibility with Ethereum.
* Performance and Efficiency: Rust, the programming language underlying Substrate, delivers performance comparable to C and C++, making it ideal for computationally intensive AI algorithms.
* Enhanced Security: Rust's strong memory safety guarantees help prevent common programming errors, bolstering the reliability and security of our AI systems.
* Concurrency and Parallelism: Substrate's concurrency primitives facilitate efficient utilization of multicore processors, optimizing the performance of AI algorithms.
* Rich Ecosystem: Substrate benefits from a thriving ecosystem of libraries and tools, including those specifically designed for machine learning and data processing, accelerating development and deployment.

### Leveraging Rust for AI Development:

Rust's combination of performance, memory safety, and concurrency features make it an exceptional choice for AI development. Its ability to handle complex algorithms efficiently, while ensuring reliability and security, is indispensable for AI applications that demand high performance and trustworthiness.

### Conclusion

By building PHRON on Substrate and utilizing Rust, we can establish a robust foundation for our AI-driven initiatives. The framework's comprehensive features, combined with Rust's performance and security, will empower us to develop efficient, secure, and scalable AI solutions.


# Ethereum Compatible

### Phron's EVM Compatibility: Bridging Ethereum and Beyond with Rust's Power

Phron's fully integrated Ethereum Virtual Machine (EVM) empowers developers to seamlessly deploy and execute smart contracts written in Solidity or other EVM-compatible languages. This compatibility leverages a robust Rust implementation of the EVM, built upon the well-established[ rust-ethereum/evm](https://github.com/rust-ethereum/evm) project. This choice of Rust ensures exceptional performance, memory safety, and security, making Phron a reliable platform for demanding smart contract applications.

### Key Benefits of Phron's EVM Integration with Rust's <mark style="color:green;">rust-ethereum/evm</mark>:

* Seamless Interoperability: Developers can leverage their existing Ethereum knowledge and codebase, minimizing the learning curve and accelerating development.
* Expanded Ecosystem: Phron benefits from a vast ecosystem of Ethereum tools, libraries, and developer communities, fostering innovation and collaboration.
* Enhanced Compatibility: Phron's EVM implementation adheres to Ethereum's security standards, providing a secure and reliable environment for smart contract execution.
* Advanced Performance: Rust's inherent efficiency provides a significant performance boost for running EVM bytecode compared to other languages.
* Exceptional Security: Rust's memory safety guarantees significantly reduce vulnerabilities often associated with traditional smart contract development languages.

### Key Differences Between PHRON and Ethereum

**Consensus Mechanisms:**

Phron employs a novel approach to consensus by combining Proof-of-Stake (PoS) and Directed Acyclic Graphs (DAGs) under the supervision of AI. The committee of validators, selected based on their overall performance and participation in the network chosen by SophiaAI protocol, is responsible for verifying the validity of transactions and blocks.

**Finality:**

PHRON and Ethereum have distinct approaches to finality mechanisms. Ethereum utilizes a checkpoint system wherein validators determine finality at designated block checkpoints, leading to an average delay of approximately 6.4 minutes for block finalization. In contrast, PHRON employs the AlephBFT finality gadget, which enables significantly faster finality, especially when enhanced by AI-driven processes.

When comparing finality mechanisms, AlephBFT offers advantages in terms of speed and efficiency. It is designed to achieve consensus quickly, making it particularly suitable for high-throughput environments. On the other hand, Ethereum’s GRANDPA (GHOST-based Recursive ANcestor Deriving Prefix Agreement) finality mechanism, while robust and secure, introduces latency due to its reliance on the checkpointing system.

Overall, the combination of AlephBFT and AI in PHRON allows for rapid and efficient block finalization, positioning it as a strong alternative to Ethereum's finality approach.

<br>


# Governance on PhronAI

### Participation[​](https://developers.flow.com/networks/governance#participation) <a href="#participation" id="participation"></a>

Participating in the governance process can take three forms:

* Being elected as a council member on the governing committee
* Putting forth a proposal for the community to vote on
* Staking to receive voting rights

Votes will be weighted based on locked tokens. All tokens staked by node operators will be eligible for voting, but other users can lock up their tokens to be given voting power. Anyone will be able to stake a Flow token to vote on issues (even if they aren’t participating as a staked node).

### Token Holder Rights[​](https://developers.flow.com/networks/governance#token-holder-rights) <a href="#token-holder-rights" id="token-holder-rights"></a>

Tokens may be staked for operation or governance rights which gives holders the right to participate in running a node and/or to participate in public votes.

### Process[​](https://developers.flow.com/networks/governance#process) <a href="#process" id="process"></a>

Proposals can be brought forward on a public forum where they will be evaluated by the governing committee. All decisions are made publicly and any stakeholder has the opportunity to organize grassroots action to veto specific decisions or to vote in or remove council members.

To ensure the progress of the network, the elected council first assesses the proposal and selects an answer they agree to be the "default choice". Voters can freely vote how they choose, but having a well-considered default allows forward progress without being blocked by passive participants. All decisions are voted on by all participants and decisions made by the council must be ratified by a public vote on the network.

#### Timing[​](https://developers.flow.com/networks/governance#timing) <a href="#timing" id="timing"></a>

Vote outcomes and upcoming votes will be published every Friday by 7am PT. All upcoming votes are available for review and voting for at least two weeks following their publication.

### Protocol Set Parameters[​](https://developers.flow.com/networks/governance#protocol-set-parameters) <a href="#protocol-set-parameters" id="protocol-set-parameters"></a>

The following parameters will be set on the network on day 1 and will not be candidates for a public vote when the network first launches.

* The staking ratio preserved between each node type
* The maximum inflation rate
* The role of FLOW as the main reserve asset for collateralized secondary tokens (e.g. stablecoins)
* The mechanism through which transaction inclusion, computation, and storage fees are determined and paid for

### Early Governance of the Protocol[​](https://developers.flow.com/networks/governance#early-governance-of-the-protocol) <a href="#early-governance-of-the-protocol" id="early-governance-of-the-protocol"></a>

Once governance is enabled, the community can participate in the following:

* Protocol upgrades, including things like: - the consensus algorithm - the low-level network communication structure - the execution environment - the number of seats available for each node type
* Management of Ecosystem Development Fund, including: - issuance of grants - bug & feature bounties
* Selecting council members
* Committee budgets for each of the operational arms of the Foundation, including the executive, technical, operational, legal, pricing, financial, and marketing branches.
* Management of legal affairs, including: - enforcing license and patent infringements - issuing takedown notices and copyright infringement - freezing accounts if illegal activity occurs - updating the community, security, contribution policies

During the Bootstrapping Phase, anyone may apply online to be set as a Validator by the Company. Approved Validators must then Stake a fixed minimum of FLOWs based on Validator type. Other FLOW holders may become “Delegators” when they dedicate or “Delegate” their FLOWs to approved Node Operators as a signal that they believe that Validator to be an effective and honest participant of the network. Staking and Delegation features are already enabled as of the Effective Date.

Each Validator makes an individual decision of which Protocol Version they choose to use. Since the value of blockchain networks is primarily due to the collectively verified execution state, there is a strong incentive for Validators to choose a Protocol Version that is compatible with the Protocol Version selected by the majority of other Validators. As a practical matter, the Protocol Version chosen by the overwhelming majority of Validators is likely to be the most recent Protocol Version produced and recommended by the Core Team, provided the proposed changes are not contentious. However, if a significant fraction of the community disagrees with any aspect of the most recent Protocol Version, they can band together to use a previous Protocol Version, or some other Protocol Version defined independently from the Core Team. This process of a “contentious forking” is rare, but does have several precedents in other networks (REF: Ethereum Classic, Bitcoin Cash).

The process by which the Core Team chooses the updates for each new Protocol Version follows the open process described above, using GitHub as an open discussion platform to gauge the priorities and needs of the entire Flow ecosystem. The proposed changes by the Core Team will be announced and discussed well before they are implemented, and any community member can propose their own changes or contribute code updates to implement any proposed changes. The details of a new Protocol Version are publicly available no less than 14 days before that version is formally recommended for use by Validators (a “Release”), with the complete implementation source code visible for no less than 7 days before a Release.


# Use


# Wallets

Cryptocurrency wallets are fundamental to the Web3 ecosystem, empowering users with full control over their assets. Phron provides its own native web wallet.

To set up a new **PHRON account** on the testnet, follow these steps:

1. **Visit the Testnet**: Go to [dev.phron.ai](https://dev.phron.ai).
2. **Select "Phron" Network**: In the top left corner of the page, ensure that "Phron" is selected as the active network.

At this point, you should see the interface where you can proceed with account creation and manage your testnet activities.

<figure><img src="/files/y5DUyC7D9GILPFbQI8uY" alt=""><figcaption></figcaption></figure>

That's the default view of the **Phron web wallet**—a block explorer displaying the most recent blocks and events. To access all account-related actions, simply navigate to the [**Accounts**](https://dev.phron.ai/#/accounts) tab, where you can manage your wallet, stake funds, and interact with other features of the Phron network.

Please note that many functionalities of the **Phron web wallet** require at least one account with funds present in the [**Accounts**](https://dev.phron.ai/#/accounts) tab. Without a funded account, some tabs and menus may be inaccessible or hidden, limiting your ability to utilize certain features of the wallet effectively.

### Account actions <a href="#account-actions" id="account-actions"></a>

{% hint style="info" %}
Please note that an **account** on the blockchain is distinct from the **wallet** used to create it. An account serves as an entry in the public blockchain database, storing information about funds, transactions, staking, and more. In contrast, a wallet is a tool that holds a private key (or mnemonic seed phrase) associated with an account, enabling interaction with it.

Importantly, the same account can be accessed through multiple wallets as long as the same mnemonic seed is used. Therefore, if you already have an account created with another wallet and wish to start using the web wallet, there’s no need to create a new account and transfer all your coins. Instead, simply import your existing account into [**dev.phron.ai**](https://dev.phron.ai) using the steps outlined below.
{% endhint %}

To **create a new account**, please:

1. Proceed to the [Accounts](https://dev.phron.ai/#/accounts) tab.
2. Click on Add Account.
3. You'll see your mnemonic seed. Save it in multiple secure locations to ensure you have access to your wallet.
4. Follow the on-screen instructions:
   1. Set a local name for your account.
   2. Choose a local password (it's only relevant for using this account via the [dev.phron.ai](https://dev.phron.ai) web wallet).
   3. At the final step, ensure you select the appropriate location to save your backup **.JSON files**. These files provide an additional method for wallet recovery in case you lose your mnemonic seed phrase. To recover your account using the **.JSON file**, you will need to enter the password you selected in the previous step. This added layer of security ensures that your funds remain protected while still being accessible in case of emergencies.

To **import an existing account using seed phrase**, please:

1. Proceed to the [Accounts](https://dev.phron.ai/#/accounts) tab.
2. Click on Add Account.
3. You'll see a random mnemonic seed. Replace it with the mnemonic seed of the account you wish to import
4. Follow the on-screen instructions (same as above)

To **import an existing account using .JSON backup**, please:

1. Proceed to the [Accounts](https://dev.phron.ai/#/accounts) tab.
2. Click on Restore JSON.
3. Upload your backup .JSON file and enter the associated password.

To **remove your account** from the web wallet, please:

1. Proceed to the [Accounts](https://dev.phron.ai/#/accounts) tab.
2. Next to the account you would like to remove, click 3 dots and select Forget this account.
3. Please note that this action happens purely on the client side and does not interact with the blockchain. Your account (together with all funds, staked coins, etc.) will stay on the chain unchanged. It will be only removed from the local list on the [Accounts](https://dev.phron.ai/#/accounts) tab. You can reimport it at any time using the procedures described above.

#### **Browser extensions** <a href="#browser-extensions" id="browser-extensions"></a>

An alternative way to manage your accounts accessible via the **phron.ai web wallet** is by using the **Phron Signer extension**, developed and maintained by the core team. This web browser extension securely stores your Phron blockchain accounts and allows you to use them seamlessly across the **phron.ai wallet** and other compatible websites, such as the **Staking Dashboard** and **Contracts UI**.

The process of **creating**, **importing**, or **removing** an account in the **Phron Signer extension** closely mirrors the steps described for the web wallet. The most important aspect to focus on is the **mnemonic seed phrase** linked to your account, as it ensures access and recovery across different platforms. Furthermore, the **backup .JSON files** generated by the web wallet are fully compatible with the browser extension, allowing for seamless account management between both tools.

Alternatively, [Polkadot{.js} extension](https://polkadot.js.org/extension/) works in a similar way.

## Phron AI DeWallet

### **Overview**

[**Phron AI DeWallet**](https://phron.ai/wallet) is a decentralized wallet designed to provide users with seamless control over their assets on Web3. The wallet offers a simple, user-friendly interface for managing cryptocurrencies, tokens, NFTs, and engaging in various blockchain transactions. Available for use in browsers like **Brave** and **Chrome**, Phron AI DeWallet supports transactions, token management, and staking directly from the browser.

**Key Features**

* **Decentralized Control**: Users maintain full ownership of their assets without relying on centralized intermediaries.
* **Multi-Asset Support**: Manage cryptocurrencies, tokens, and NFTs all in one place.
* **Ease of Use**: Intuitive design for both beginners and experienced blockchain users.
* **Cross-Platform**: Available on both **Brave** and **Chrome** browsers for smooth accessibility.

**Main Screens**

The wallet provides a streamlined interface divided into the following key screens:

1. **Login/Unlock Screen**
   * **Welcome Back**: Upon opening the wallet, users are greeted with the login interface. You can unlock the wallet using a Google account or another supported method.
   * **Security Options**: There are options for unlocking the wallet securely via biometric or password authentication.
2. **Transaction Screen**
   * **Sending**: The transaction screen allows users to easily send cryptocurrencies or tokens.
     * **Inputs**: Users can enter the recipient's address, the amount to be sent, and select the asset type (e.g., PHRN tokens).
     * **Gas Fees**: The screen shows a breakdown of gas fees to be paid for the transaction, giving users full control over how much they wish to spend.
     * **Confirmation**: Before sending, users can review the transaction details and confirm or reject.
3. **Accounts Screen**
   * **Balance Overview**: This screen displays the user’s accounts and their balances in PHRN or other supported assets.
   * **Asset Management**: The account screen allows users to easily access token balances, view recent transactions, and interact with their stored assets.

### **Supported Browsers**

[Phron AI DeWallet](https://phron.ai/wallet) is compatible with:

* **Brave Browser**
* **Chrome Browser**

**User Guide**

**1. Installing the Wallet**

* Visit the [Phron AI DeWallet](https://phron.ai/wallet) page and select the appropriate option for your browser (**Brave** or **Chrome**).
* Follow the installation instructions for your selected browser to add the extension.

**2. Creating/Importing an Account**

* After installation, launch the wallet and create a new account by generating a mnemonic seed phrase.
* Alternatively, import an existing account using your mnemonic seed or backup .JSON file.

<figure><img src="/files/9npV9eMtEPkbHhcmiEY1" alt=""><figcaption></figcaption></figure>

**3. Sending Tokens**

* Go to the "Send" section in the wallet.
* Enter the recipient's wallet address, select the amount and asset type (e.g., PHRN).
* Confirm the transaction details, review the gas fees, and click **Send**.

<figure><img src="/files/pwuCcMNrD4UVia9Z6349" alt=""><figcaption></figcaption></figure>

**4. Viewing Assets**

* Navigate to the **Accounts** section to see a breakdown of all your assets.
* From here, you can manage your tokens, stake assets, or transfer funds.

**Security**

* **Private Key Storage**: Your private keys are stored securely within the wallet and never shared with any third-party service.
* **Backup**: Ensure you back up your mnemonic seed phrase and/or .JSON file for wallet recovery.

**Conclusion**

[Phron AI DeWallet](https://phron.ai/wallet) is designed to simplify the management of Web3 assets, providing a secure and intuitive interface for users to engage with the blockchain. With compatibility across multiple browsers and support for various assets, it offers an ideal solution for managing cryptocurrency in a decentralized manner.

### **Third-Party Wallets** <a href="#third-party-wallets" id="third-party-wallets"></a>

There are also a number of third-party wallets available in the Phron ecosyste&#x6D;**:**

* [Talisman](https://talisman.xyz/)

{% hint style="danger" %}
Please note that the **core team** is not responsible for the development or maintenance of third-party wallets and, therefore, cannot guarantee their security measures. It is important to use third-party wallets with caution and ensure they follow proper security practices.
{% endhint %}


# Explorer

The Phron Explorer is available through PhronScan and provides real-time information on all on-chain activities.

<figure><img src="/files/Q2YxzNmU4dqj2nOc7ahF" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/RlBzZ0Eb9iY44cyEpL7U" alt=""><figcaption></figcaption></figure>

The **Phron explorer** is accessible through [**PhronScan**](https://testnet.phronscan.io), a high-precision Web3 service designed for **Substrate chains**. PhronScan offers real-time insights into various aspects of the network, including **Chain Data**, **Token Status**, **Latest Blocks**, **Transfers**, and **Validators**. Its user-friendly interface makes it easy to navigate and track important network activities.


# Bridge

### **Bridge User Guide: PhronAI, PHRToken, WrappedETH, and ETH**

This guide will walk you through the steps to bridge tokens between the PhronAI and Sepolia networks, converting PhronAI tokens to PHRToken (and vice versa) as well as WrappedETH on PhronAI to ETH on Sepolia (and vice versa).

#### **1. Connecting to the Bridge Platform**

* **Open the Bridge Interface**: Access the bridge platform and connect your multi-network wallet, such as MetaMask.
* **Select the Network**: Choose either **Sepolia** (for PHRToken/ETH) or **PhronAI** (for PhronAI/WrappedETH), depending on the direction of your transfer.

#### **2. Approve Token Transfers for Bridging**

1. **Choose Your Token**:
   * For **PhronAI to PHRToken**, select the PhronAI token on the PhronAI network.
   * For **WrappedETH to ETH**, select WrappedETH on the PhronAI network.
2. **Approve the Bridge Contract**:
   * You must allow the bridge contract to access your tokens for transfer. This approval only needs to be done once per token type. Confirm the approval request in your wallet.

#### **3. Converting Tokens (Bridging Transactions)**

1. **Enter the Amount**: Specify the amount of the token you wish to bridge.
2. **Initiate the Transfer**:
   * *For PhronAI to Sepolia*: Select “Transfer” to move PhronAI (or WrappedETH) to the Sepolia network. This locks the original tokens on PhronAI and mints PHRToken (or ETH) on Sepolia.
   * *For Sepolia to PhronAI*: Select “Transfer” to move PHRToken (or ETH) to the PhronAI network. The bridge contract locks the tokens on Sepolia and releases the equivalent amount on PhronAI as PhronAI or WrappedETH.

#### **4. Monitoring the Transaction**

1. **Transaction History**: Check the “Transaction History” section on the bridge interface for updates on your transfer status.
2. **Claim Tokens**:
   * For some transfers, you may need to click “Claim” once the transaction is confirmed on the destination network to complete the bridge process.
   * Tokens will appear in your wallet once finality is achieved.

#### **5. Withdrawing Tokens (Optional)**

* You can reverse the process if you wish to return PHRToken to PhronAI or WrappedETH to ETH. Follow the same steps, choosing the correct token and network for the direction of transfer.

#### **Conversion Rates and Fees**

* **Conversion Rates**: All bridge conversions are 1:1, meaning that PhronAI always converts to an equivalent amount of PHRToken, and WrappedETH always converts to an equivalent amount of ETH.
* **Fees**: Gas fees and potential bridge fees apply depending on network congestion and platform requirements. Confirm fees in the bridge interface before transferring.

This guide covers all steps for securely converting tokens between PhronAI and Sepolia networks. For further assistance, refer to the bridge’s support documentation or explore transaction history via the Sepolia and PhronAI blockchain explorers.


# Staking

### Direct Nomination: A Personalized Staking Approach

Direct nomination, also known as standalone nomination, offers a personalized staking experience where you, as the user, act as the sole nominator. This approach provides you with complete control over your nominations, allowing you to select validators and adjust your stake without adhering to unbonding periods.

### Minimum Stake Requirement:

To embark on direct nomination, you'll need a substantial minimum stake, currently set at 100 PHR. Please note that this requirement may increase over time as the network evolves.

#### Steps to Become a Direct Nominator:

1. Access the Staking Tab: Navigate to the Staking tab within the interface.
2. Enable Stashed Mode: Ensure that the Stashed mode is activated in the top-left corner of the Accounts tab.
3. Initiate Nomination: Click the "Nominator" button to start the nomination process.
4. Configure Nomination Settings: In the pop-up window, select your Stash account, specify the desired amount of coins to bond, and choose your preferred reward destination.
5. Select Validator: Choose the validator you wish to nominate from the available options.
6. Authorize Transaction: Confirm your nomination by authorizing the transaction.

### Understanding the Nomination Process:

Once you submit your nomination, it will initially appear as a "Waiting nomination" in the Accounts tab. This status will transition to "Active nomination" at the beginning of the next era.

<br>

### The following options are available as destinations for your staking rewards:

* Stash account (increase the amount at stake) - the rewards are sent to your stash account and automatically included in your bonded stake, meaning they will increase your future rewards.
* Stash account (do not increase the amount at stake) - the rewards are sent to your stash account, but are not automatically bonded. They are available as transferable coins right away and do not contribute to future rewards, unless manually bonded.
* Specified payment account - the rewards are sent as transferable coins to some other account of your choice.

## Unstaking :

## Reducing Your Staked Coins While Remaining a Nominator

To decrease the amount of staked coins while continuing as a nominator, please follow these steps:

1. Access the Staking Tab: Navigate to the Staking tab of the mainnet and select the Accounts tab. Ensure that the "Stashed mode" is enabled in the top left corner. You will see a list of all your accounts participating in direct nominations.
2. Select the Account for Unbonding: For the account from which you wish to reduce your stake, click the three dots at the end of the line and select Unbond funds.
3. Specify the Amount: In the pop-up menu, choose the amount of coins you would like to unbond. Please note that you cannot reduce your stake below the minimum amount of 100 PHR.
4. Complete the Unbonding Process: Click Unbond and sign the transaction.
5. View the Updated Nomination: In the Accounts tab, your updated nomination will result in a new entry appearing in the bonded column. The amount you chose to unbond will be indicated with a clock icon. Hovering over this icon will display the number of eras remaining in the unbonding period.
6. Withdraw Unbonded Funds: After the unbonding period has concluded, click the three dots button again and select Withdraw unbonded funds. Note that this option will be available only if your account has funds that have completed the unbonding process.
7. Finalize the Withdrawal: Sign the transaction to transfer your unbonded coins.

***

### Unstaking All Your Coins and Ceasing to Be a Nominator

To unstake all your coins and stop being a nominator, follow these steps:

1. Access the Staking Tab: Navigate to the Staking tab of the mainnet and select the Accounts tab. Ensure that the "Stashed mode" is enabled in the top left corner. You will see a list of all your accounts participating in direct nominations.
2. Stop Nominating: For the account from which you wish to stop nominating, click the Stop button at the end of the line and sign the transaction in the pop-up window.
3. Unbond Funds: Click the three dots at the end of the line and select Unbond funds.
4. Select All Bonded: In the pop-up menu, select the All Bonded toggle to ensure that all your funds will undergo unbonding. Entering the full value without this toggle may not work due to fractional coins that are not displayed in the UI.
5. Complete the Unbonding Process: Click Unbond and sign the transaction.
6. View the Updated Nomination: In the Accounts tab, a clock icon will appear in the bonded column, indicating your modified nomination. Hovering over the clock will show the number of eras remaining in the unbonding period.
7. Withdraw Unbonded Funds: After the unbonding period has finished, click the three dots button again and select Withdraw unbonded funds. This option will be active only if the corresponding account has funds that have completed the unbonding process.
8. Finalize the Withdrawal: Sign the transaction to make your unbonded coins transferable.


# Menu Overview

Overview of the Staking UI on dev.phron.ai

If you're ready to start staking immediately, you can jump to the section **How to Start Staking With the Developer Wallet**. The following section provides a deeper dive into the various tabs and menus available on the staking platform: <https://dev.phron.ai/#/staking>.

Most of the staking functionalities can be easily accessed through the **Staking** menu located under the **Network** tab.

<figure><img src="/files/ePD3XpZpu3PKWX8FeXUO" alt=""><figcaption><p>Accessing the Staking Menu</p></figcaption></figure>

{% hint style="info" %}
**Note**: The screenshots featured in this guide are taken from the Phron Testnet platform (available at [dev.phron.ai](https://dev.phron.ai)).
{% endhint %}

The **Staking** menu includes the following tabs: **Overview, Accounts, Payouts, Pools, Targets, Slashes, Validator Stats, Performance**, and **Suspensions**. Below, we provide an explanation of the contents and purpose of each tab.

### Overview <a href="#overview" id="overview"></a>

<figure><img src="/files/ucKepCxKS1x39pE1HgLQ" alt=""><figcaption><p>The Overview tab (testnet)</p></figcaption></figure>

This tab provides key global staking data, including:

* The number of validators elected in the current era.
* The number of nominators in both the current and upcoming eras.
* The total percentage of **staked PHRON**, shown as a fraction of all PHRON in circulation.
* **Current yearly inflation**: Beginning on October 14th, 2024, 27 million coins will be emitted for the first year. This emission rate will reduce exponentially each year until the community-approved maximum supply of 520 million coins is reached.
* The current **session** number and **era** number.

The table displays a list of all current validators, including their total stake (split into their own stake and that from nominators), a list of nominators, and their current commission rate.

### Accounts <a href="#accounts" id="accounts"></a>

This tab displays a list of all your accounts involved in staking. Please note that an account will only appear here if it has been added in the **Accounts** tab or injected via a browser extension. From this tab, you can perform all staking-related actions, such as bonding or unbonding coins, as well as selecting or changing the validator you wish to nominate. To view the available actions for each account, click the three dots button at the end of the corresponding account line.

In the **Stashed** view, you can perform actions related to direct nomination, as well as actions for being a validator.

<figure><img src="/files/j1uetuc0vkW69FUfiEgl" alt=""><figcaption><p>The Stashed view (testnet)</p></figcaption></figure>

### Payouts <a href="#payouts" id="payouts"></a>

This tab displays a list of rewards that have been awarded (for eras that have ended) but not yet claimed (distributed to the validator and their nominators). Currently, this tab is not very useful, as the Foundation operates an automated service that triggers payouts to all nominators and validators whenever they are available (note that this does not apply to pools). Therefore, this tab will almost always be empty. This is expected, and seeing it empty does not mean you have never received any rewards. If you want to view your historical payouts, we recommend using [**PhronScan**](https://testnet.phronscan.io)—simply enter your account in the search bar to display your account details, including staking rewards.

### Targets <a href="#targets" id="targets"></a>

<figure><img src="/files/PWNkv6XutbWhetbdRz7T" alt=""><figcaption><p>Targets tab on mainnet</p></figcaption></figure>

In this tab, you can easily analyze all available validators. Validators with a blue arrow next to them are currently part of the era committee. You can sort the list by parameters such as **return**, **total stake**, and others.

### Slashes <a href="#slashes" id="slashes"></a>

One of the defense mechanisms protecting the Phron blockchain against malicious agents is a slashing mechanism that financially penalizes users for disrupting the network's operations. The **Slashes** tab allows you to view users who have engaged in dishonest behavior and had their funds slashed. However, it's important to note that there is currently no automatic slashing on Phron. At the time of writing, there have been no reported cases of malicious behavior from any validators, so you will likely find this tab empty.

### Validator stats <a href="#validator-stats" id="validator-stats"></a>

<figure><img src="/files/TL5hDvYsvo91wRcZDn0y" alt=""><figcaption><p>Validator stats on testnet</p></figcaption></figure>

In this section, you can query the Account ID of any validator to view their basic statistics. This feature is primarily useful for validators, but as a nominator, you can also use it to assess the performance of your chosen validator, particularly to check for any recent sessions in which they may have underperformed. Below, you will find diagrams displaying:

* Rewards received in a given era and the average reward up to that era.
* Total stake for a given era.
* Validator commission in a given era.

The history accessible by this tab goes back 84 eras.

### Performance <a href="#performance" id="performance"></a>

<figure><img src="/files/V3J0Y7TR6mzj7TtvV2UG" alt=""><figcaption><p>Performance tab on mainnet</p></figcaption></figure>

The **Performance** tab allows you to track the current session in real-time and analyze past sessions to see how many blocks each validator has created. This information is primarily of interest to validators, as the numbers do not directly indicate the rewards that validators or their nominators will receive. If you would like to explore this topic further, please refer to the **Elections and Rewards Math** section.


# How to Start Staking with the Phron Dashboard

This guide will outline how to stake via the Phron Dashboard

First, you need to hold PHRON, which you can currently acquire through one of the available exchanges.

Currently, there are two ways to stake on Phron:

1. **Direct Nomination**: This method requires a significant minimum stake of 2,000 PHRON (as of the time of writing). Keep in mind that this minimum may increase in the future. With direct nomination, you have full control over your nominations and can change them freely without undergoing the unbonding period (which lasts 14 days).
2. **Pooled Nomination**: In this method, you join an existing staking pool that combines a group of stakers. One of the benefits is that you can stake as little as 10 PHRON. Additionally, it can be convenient for users who prefer not to select their own validator, as the pool operator makes that choice for you. However, there are some downsides: currently, switching between pools requires going through the unbonding period, and the only way to auto-compound your rewards is to manually claim them and periodically add them to the pool.

#### **Staking via a nomination pool** <a href="#staking-via-a-nomination-pool" id="staking-via-a-nomination-pool"></a>

* Head to the [mainnet web wallet](https://phron.ai) and create one account as per this tutorial OR directly via one of the compatible extensions (listed below). You only need one account to join a nomination pool.

**If you already have an account, you can skip this process.**

* Next, you need to ensure that you are using a compatible browser extension. If you are already using one, you can skip this step. If not, you will need to install a compatible extension and restore your accounts. The available options (with linked tutorials) are:
* [polkadot{.js} extension](https://support.polkadot.network/support/solutions/articles/65000169952-how-to-restore-your-account-in-the-polkadot-extension)
* Subwallet
* Talisman
* [Enkrypt](https://www.enkrypt.com/)
* Navigate to the **Phron Dashboard** and click on the **Pools** tab.
* Click **Connect** in the top right corner of the page and select your browser extension. This will prompt a pop-up from the extension.
* In the pop-up, authorize the connection.
* Select **Imported Accounts** and choose your account.
* Click **Join**, which will take you to the **All Pools** section. Then, click **Join** next to your desired pool.
* Enter the amount you wish to bond to the pool and submit the transaction via the extension. Depending on your settings, you may need to enter your account password at this point.

{% hint style="warning" %}

### **NOTE!**

When you stake through a nomination pool, it is normal for your coins to be transferred out of your account. Your coins are sent and bonded to the pool, meaning they cannot be accessed by the pool operator. Once you unbond (a process that takes 14 days), you will be able to withdraw your coins from the pool.
{% endhint %}

Congratulations! You have successfully staked your coins through a nomination pool. The **Pool Status** in the **Pools** tab should now display as **Nominating** and **Earning Rewards**.

### Staking via Direct Nomination

Starting with release 12.0, controller accounts are deprecated for new stakers. When bonding funds, you will be required to set the controller account to be the same as the stash account.

With the release of 13.0, you will have the option to use Proxy Accounts.

* **Create an Account**: Visit the Mainnet web wallet and create an account following this tutorial or directly through one of the compatible extensions listed below. If you already have an account, you can skip this step. Make sure your account has enough PHRON to cover transaction fees.
* **Check Browser Extension Compatibility**: Ensure that you are using a compatible browser extension. If you are already using one, you can skip this step. If not, you will need to install a compatible extension and restore your accounts. The available options (with linked tutorials) are:
* [polkadot{.js} extension](https://support.polkadot.network/support/solutions/articles/65000169952-how-to-restore-your-account-in-the-polkadot-extension)
* Subwallet
* Talisman
* [Enkrypt](https://www.enkrypt.com/)
* **Access the PHRON Dashboard**: Navigate to the **Nominate** tab.
* **Connect Your Wallet**: Click **Connect** in the top right corner of the page and select your browser extension. This will prompt a pop-up from the extension. Authorize the connection in the pop-up.
* **Select Your Account**: Click on **Imported Accounts** and choose your stash account. If you are using proxy accounts, you can select either the proxy or proxied account, and the dashboard will import both for you. The proxy account will be used to sign staking transactions from this point forward.
* **Start Nominating**: Click **Start Nominating** and follow the prompts until you reach the summary. You will need to enter or select the following details:
  * **Reward Destination**
  * **Validator**
  * **Amount to Stake**
* **Finalize Your Nomination**: Once you reach the summary, click **Start Nominating** and sign the transaction via the extension. Depending on your settings, you may need to enter your account password at this stage.

Congratulations! You have successfully made a direct nomination! Your status should now show as **Waiting for Active Nominations**. Once the next era begins, this status will change to **Nominating and Earning Rewards**.


# How to Change Nominations

Discover how to change your nominations while staking on Phron's secure blockchain, which incorporates privacy-enhancing technology.

Nominating a specific validator with your staked PHRON signifies your trust in their ability to act honestly and effectively produce blocks. As a nominator, it is your responsibility and in your best interest to ensure that your chosen validator is reliable and trustworthy. Always remember to do your own research.

If you decide to change your selected validator at any point, you can find step-by-step instructions below for both direct nominators and members of a nomination pool.

#### Direct nomination <a href="#direct-nomination" id="direct-nomination"></a>

1. **Access the Staking Tab**: Go to the **Staking** tab of the testnet, then navigate to the **Accounts** tab. Ensure that **Stashed mode** is enabled in the top left corner. You will see a list of all your accounts participating in direct nominations.
2. **Select the Account**: For the account from which you want to change the nomination, click on the three dots at the end of the line and select **Set Nominees**.
3. **View Current Nominations**: In the pop-up menu, you will see your currently selected validator in the **Nominated Accounts** column.
4. **Change Validator**: Click on the validator’s name to remove it from the nominated accounts.
5. **Choose a New Validator**: Find your new validator in the **Candidate Accounts** list and click on it. The name should now appear in the **Nominated Accounts** column.
6. **Finalize the Nomination**: Click the **Nominate** button and sign the transaction to complete the process.

In the **Accounts** tab, your newly modified nomination will change the status from **Active Nominations** to **Waiting Nominations**. Your choice will become active at the beginning of the next era.

Please note that you will continue to nominate your previous validator until the end of the current era. This ensures that switching to a new validator does not create any gaps in your nomination period, allowing you to receive rewards without interruption during the transition.

#### Nomination pools <a href="#nomination-pools" id="nomination-pools"></a>

Unlike the direct nomination mode, you cannot quickly switch to a different nomination pool and have the change take effect at the beginning of the next era. Instead, you must first leave your current pool, which requires waiting through a 14-day unbonding period, before joining the new pool.

For step-by-step instructions on how to do this, please refer to the sections related to nomination pools in **How to Stop Staking** and **How to Start Staking With the Developer Wallet**.


# How to Stop Staking

Follow these steps to stop staking on Aleph Zero, a secure blockchain with zk-proof technology.

Regardless of whether you are a direct nominator or a member of a nomination pool, you can decide to decrease your stake or withdraw from staking at any time. In either case, you will need to wait through the 14-day unbonding period before your coins are released and become transferable.

#### Direct nomination <a href="#direct-nomination" id="direct-nomination"></a>

**To decrease the amount of staked coins, but keep being a nominator please:**

1. **Access the Staking Tab**: Go to the Staking tab of the testnet and navigate to the Accounts tab. Ensure that Stashed mode is enabled in the top left corner. You will see a list of all your accounts participating in direct nominations.
2. **Select Your Account**: For the account from which you wish to reduce your stake, click the three dots at the end of the line and select **Unbond funds**.
3. **Specify the Amount**: In the pop-up menu, choose the amount of coins you would like to unbond. Please remember that you cannot decrease your stake below the minimum amount of 2,000 PHRON.
4. **Complete the Unbonding Process**: Click **Unbond** and sign the transaction.
5. **View Your Updated Nomination**: In the Accounts tab, your newly modified nomination will result in a new entry appearing in the bonded column. The amount you decided to unbond will be indicated with a clock icon. Hovering over the clock will show you how many eras are left in the unbonding period.
6. **Withdraw Unbonded Funds**: After the unbonding period is complete, click the three dots button again and select **Withdraw unbonded funds**. Note that this option is available only if your account has funds that have finished unbonding and are ready to be withdrawn.
7. **Finalize the Withdrawal**: Sign the transaction. Your unbonded coins are now transferable.

**To unstake all your coins and stop being a nominator please:**

* **Access the Staking Tab**: Navigate to the Staking tab of the testnet and select the Accounts tab. Ensure that **Stashed mode** is enabled in the top left corner. You will see a list of all your accounts participating in direct nominations.
* **Stop Nominating**: For the account from which you wish to stop nominating, click the **Stop** button at the end of the line and sign the transaction in the pop-up window.
* **Unbond Funds**:
  * Click the three dots at the end of the line and select **Unbond funds**.
  * In the pop-up menu, enable the **All Bonded** toggle to ensure all your funds will be subject to unbonding. Entering the full value without this toggle on may not work due to fractional coins that are not displayed in the UI.
* **Complete the Unbonding Process**: Click **Unbond** and sign the transaction.
* **Monitor the Unbonding Period**: In the Accounts tab, your modified nomination will now show a clock icon in the bonded column. Hovering over this icon will display how many eras are left in the unbonding period.
* **Withdraw Unbonded Funds**: After the unbonding period is complete, click the three dots button again and select **Withdraw unbonded funds**. This option will be available only when your account has funds that have finished unbonding and are ready for withdrawal.
* **Finalize the Withdrawal**: Sign the transaction. Your unbonded coins are now transferable.

#### Nomination pools <a href="#nomination-pools" id="nomination-pools"></a>

For members of nomination pools the procedure of decreasing the amount of staked coins is almost the same as the one for completely leaving the pool. Please follow the steps below:

#### Unbonding Funds from the Nomination Pool

1. **Access the Staking Tab**: Navigate to the **Staking** tab of the testnet. Ensure that the **Pooled mode** is enabled in the top left corner.
2. **View Your Accounts**: In the **Accounts** section, you'll see a list of all your accounts participating in the nomination pools.
3. **Select the Account**: For the account from which you want to reduce your stake, click on the three dots at the end of the line, then select **Unbond funds**.
4. **Choose the Amount to Unbond**:
   * In the pop-up menu, specify the amount of coins you wish to unbond.
   * **Important**: You must maintain a minimum balance of **10 PHRON** to remain a member of the nomination pool. If you intend to leave the pool entirely, toggle on the **All Bonded** option to unbond the entire amount. This ensures that you account for any fractional coins that may not be visible in the UI.
5. **Confirm the Unbonding**: Click **Unbond** and sign the transaction to initiate the process.
6. **Monitor the Unbonding Status**: In the **Accounts** tab, you'll notice a clock icon appearing in the **Bonded** column next to the amount you chose to unbond. Hovering over the clock will display the number of eras remaining in the unbonding period.
7. **Withdraw Unbonded Funds**: After the unbonding period is complete:
   * Click the three dots button again and select **Withdraw Unbonded**. Note that this option will only be available if your account has unbonded funds ready for withdrawal.
   * Sign the transaction to transfer your unbonded coins back to your account.


# Staking Rewards

This document provides a comprehensive explanation of the PHRON node staking process, focusing on how rewards are calculated, distributed, and influenced by key factors such as Annual Percentage Rate (APR) and total node participation. By detailing these mechanisms, this guide will help node operators understand the staking process and optimize their rewards over time.

## 1. Node Overview

* **Node Name: Zeus**\
  The node's name, Zeus, serves solely as a label and does not influence the staking or reward calculation processes.
* **Tokens Required:**\
  A minimum of 200,000 PHR tokens is required to set up and operate a Zeus node. These tokens remain locked within the node for the entire duration of its operation unless otherwise modified by the validator.
* **Price at Public Sale:**\
  During the public sale, 200,000 PHR tokens were valued at $14,200, which equates to a price of approximately $0.071 per PHR token.
* **Total Number of Nodes:**\
  The total number of available nodes in this scenario is 500, and the rewards pool is equally divided across these nodes unless a portion of stake is opened for nominators.
* **Total Supply of PHRON:**\
  The total supply of PHRON tokens is 2.1 billion.

## 2. Staking Rewards Structure

Staking rewards are distributed on a monthly basis, with both the APR and the total number of PHRON rewards decreasing over time. Node operators receive rewards in proportion to the performance and duration of their staked tokens, and they can open up part of their stake for nominators to participate..

**2.1 Key Factors Affecting Rewards:**

1. **APR (Annual Percentage Rate):**

* The APR represents the annual return on the staked PHRON tokens.
* The APR begins at a higher rate and gradually declines over time, meaning the annualized return decreases as more time passes.
* For instance, if the APR is 13.79%, the annualized return for stakers is 13.79% of their staked tokens, although this return is distributed monthly.

2. **Total Rewards (PHRON):**

* Each month, a predetermined number of PHRON tokens is allocated for distribution to all stakers.
* The total amount of rewards diminishes over time, aligning with the reduction in APR.

3. **Distribution Among Validators and Nominators:**

* Validators can choose to stake up to 75% of the required node tokens and leave the 25% open for nominators. This allows nominators to stake additional tokens and share rewards proportionally based on their contribution.

## Rewards System Explained:

This section outlines the PHRON node rewards distribution mechanism, focusing on how rewards are allocated between validators and nominators, and the new flexibility provided to validators in managing their stake.

### **1. 100% Rewards Distribution to Validators and Nominators**

In the system, 100% of the rewards generated by node staking are distributed to validators (also referred to as node operators) and nominators. This ensures that all participants contributing to the node's operation receive their fair share of the rewards.

* Validators: Validators are responsible for maintaining the integrity of the blockchain by validating transactions and blocks. Their contribution is critical to the network’s security and performance.
* Nominators: Nominators support validators by staking their own tokens on the validators they trust to act correctly and honestly within the network.

The total rewards generated in each staking cycle are proportionally divided between the validator and any nominators, depending on the percentage of stake each party holds.

### **2. Flexibility in Node Staking for Validators and Nominators**

In addition to managing the technical aspects of the node, validators now have the flexibility to open a portion of their node's stake requirement for public participation from nominators. Specifically, validators can set up their nodes to allow up to 25% of the required stake to be filled by nominators.

**Example Scenario:**

Consider the case where a validator is required to stake 200,000 PHRON tokens to operate a node. The validator has the option to modify their stake as follows:

* The validator can choose to personally stake 75% of the node’s required tokens (150,000 PHRON).
* This leaves 25% of the required stake (50,000 PHRON) open for nominators to contribute.

By allowing nominators to contribute, the validator enables other users to participate in the network while still maintaining control over the majority of the node's stake.

### **3. Staking Flexibility for Validators: Retrieving Tokens**

Once nominators begin to stake on a validator’s node, the validator has the option to retrieve the extra tokens staked by nominators if they wish. This feature provides the validator with flexibility over the node’s total staked amount:

* If the validator decides to retrieve the extra tokens (e.g., the tokens staked by the nominators), the validator will hold a larger percentage of the total stake and, consequently, will receive a higher share of the rewards.
* If the validator does not retrieve the tokens, the total stake will remain as is, and rewards will be distributed based on the percentage each party holds.

### **4. Rewards Distribution Based on Stake Percentages**

The staking rewards are distributed proportionally based on the percentage of total stake held by the validator and the nominators. This ensures a fair and transparent system, where both validators and nominators are rewarded according to their contribution.

### **Example of Reward Distribution:**

Assume the following distribution on a node:

* Validator holds 85% of the total staked PHRON.
* Nominator 1 has contributed 5%.
* Nominator 2 has contributed 10%.

The rewards generated by the node will be allocated based on these percentages:

* The validator, holding 85% of the total stake, will receive 85% of the total rewards.
* Nominator 1, holding 5% of the total stake, will receive 5% of the total rewards.
* Nominator 2, holding 10% of the total stake, will receive 10% of the total rewards.

This proportional rewards distribution model ensures that all participants—whether they are validators or nominators—are rewarded in alignment with their respective stakes.

### **5. Benefits of the Flexible Staking Mechanism**

The flexibility offered by this model benefits both validators and nominators:

* For Validators: Validators can control the majority of the stake while allowing nominators to contribute the remaining portion. This allows validators to operate their nodes with a lower personal stake if needed while still retaining the option to reclaim the tokens contributed by nominators.
* For Nominators: Nominators, who may not have enough tokens to operate a node independently, are now able to contribute to an existing validator's node and earn rewards in proportion to their stake.

This system provides an inclusive and adaptable framework, encouraging wider participation in the network while maintaining the integrity and control of validators over their nodes.

### Examples:

Example of Month 1 Rewards:

* APR for Month 1: 13.7927%
* Total Rewards for Month 1:  24,137,262.43 PHR Tokens.

### Calculation:

* The total reward of 24,137,262.43 PHR is distributed evenly among 500 nodes.
* Rewards per node for Month 1:\
  Reward per node = 24,137,262.43 / 500 = 48,274.52

Thus, each Zeuss node would receive 48,274.52 PHR tokens as rewards in Month 1.

### Example of Month 2 Rewards:

* APR for Month 2: 13.1005%
* Total Rewards for Month 2:  45,851,763.07 PHR Tokens.

### Calculation:

* The total reward of 45,851,763.07 PHR is distributed evenly among 500 nodes.
* Rewards per node for Month 2:\
  Reward per node = 45,851,763.07 / 500 = 91,703.53 PHR

Thus, each Zeuss node would receive 91,703.53 PHR tokens as rewards in Month 2.

Accumulated Rewards Over Time

Lets Calculate the total accumulated rewards for a node over a period of 6 months.

<table data-header-hidden><thead><tr><th width="109"></th><th width="147"></th><th></th><th></th></tr></thead><tbody><tr><td>Month</td><td>APR(%)</td><td>Total Rewards (PHRON)</td><td>Rewards per Node (PHRON)</td></tr><tr><td>1</td><td>13.79%</td><td>24,137,262.43</td><td>48,274.52</td></tr><tr><td>2</td><td>13.10%</td><td>45,851,763.07</td><td>91,703.53</td></tr><tr><td>3</td><td>12.55%</td><td>65,891,034.48</td><td>131,782.07</td></tr><tr><td>4</td><td>12.09%</td><td>84,661,707.04</td><td>169,323.41</td></tr><tr><td>5</td><td>11.70%</td><td>102,416,527.58</td><td>204,833.06</td></tr><tr><td>6</td><td>11.36%</td><td>119,326,661.82</td><td>238,653.32</td></tr></tbody></table>

### Total Rewards for the first 6 months would be:&#x20;

48,274.52 + 91,703.53 + 131,782.07 + 169,323.41 + 204,833.06 + 238,653.32&#x20;

\= 884,569.91 PHRON tokens.

### Long Term Projections:

If a node is staked for 12 months, the total rewards can be projected as:

<table data-header-hidden><thead><tr><th width="109"></th><th width="146"></th><th width="242"></th><th></th></tr></thead><tbody><tr><td>Month</td><td>APR(%)</td><td>Total Rewards (PHRON)</td><td>Rewards per Node (PHRON)</td></tr><tr><td>7</td><td>11.06%</td><td>135,515,183.25</td><td>271,030.37</td></tr><tr><td>8</td><td>10.79%</td><td>151,074,585.82</td><td>302,149.17</td></tr><tr><td>9</td><td>10.54%</td><td>166,076,782.61</td><td>332,153.57</td></tr><tr><td>10</td><td>10.32%</td><td>180,579,208.34</td><td>361,158.42</td></tr><tr><td>11</td><td>10.11%</td><td>194,628,744.71</td><td>389,257.49</td></tr><tr><td>12</td><td>9.92%</td><td>208,264,354.83</td><td>416,528.71</td></tr></tbody></table>

### Total Rewards for the first 6 months would be:&#x20;

&#x20;271,030.37 + 302,149.17 + 332,153.57 + 361,158.42 + 389,257.49 + 416,528.71&#x20;

\= 2,072,277 PHRON tokens.

Validators and Nominators: Flexible Staking Example

Validators can open up to 25% of their node’s stake for external nominators to participate. For example:

* Validator holds 85% of the node’s stake.
* Nominator 1 contributes 5%.
* Nominator 2 contributes 10%

### Rewards will be distributed proportionally:

* Validator receives 85% of total rewards.
* Nominator 1 receives 5%

Nominator 2 receives 10%


# Validate

## Becoming a Validator on the PHRON Network

To become a validator on the PHRON network, you must bond a minimum of 10,000 PHRON and meet the specified hardware requirements. For detailed information on validating, please refer to our comprehensive documentation. Validators play a critical role in the network by running nodes that verify the accuracy of transactions on PHRON. They are integral to the decentralized governance of the chain and are supported by nominators who delegate their stakes to validators they trust. Rewards assigned to a validator are shared proportionally between the validator and their nominators based on their respective stakes. In the event of malicious behavior, both the validator's and nominators' staked coins are subject to slashing.

### Monitoring Your Validator

To stay informed about your validator’s performance, including notifications for when your validator stops producing blocks, you can subscribe to the PHRON Alerts via Telegram. For more information, please visit our dedicated page.

### Transitioning from Nomination to Validation

If you are starting as a validator and wish to include PHRON currently nominated to another validator, you may not need to unbond and wait for the unbonding period to conclude. Below are various scenarios you might encounter, along with steps to minimize the amount of PHRON that needs to be unbonded (using standard web wallets on Testnet or Mainnet):

#### Case 1: Nomination of X ≥ 8,667 PHRON from a Single Account (acc\_1) to Use Entire Amount as Validator Stake

**Solution:** This is the simplest scenario. Select your account and click "Stop" to cease nomination. Then follow the standard procedure to generate and set your session keys. Afterward, click "Validate." The changes will take effect at the start of the next era, with no unbonding required.

#### Case 2: Nomination of X ≥ 8,667 PHRON from a Single Account (acc\_1) to Use a Smaller Amount Y < X as Validator Stake

**Solution:** Select your account and click "Stop" to stop nominating. Then click "Unbond funds" to adjust your total bond to Y. Follow the standard steps to generate and set your session keys, and then click "Validate." The changes will take effect with the start of the next era. You will unbond X - Y PHRON, which will be available after the unbonding period.

#### Case 3: Nomination of X < 8,667 PHRON from a Single Account (acc\_1) and Desire to Add Stake to Reach Y ≥ 8,667 and Become a Validator

**Solution:** Select your account and click "Stop" to cease nomination. Then click "Bond more funds" to increase your total bond to Y. Follow the standard steps to generate and set your session keys, then click "Validate." The changes will take effect at the start of the next era.

#### Case 4: Nomination of a Total of X ≥ 8,667 PHRON from Multiple Accounts and Desire to Become a Validator

**Solution:** In this case, you will need to unbond from all but one account and wait for the unbonding period to conclude. It is advisable to retain the account with the largest amount bonded. Once the unbonding period for the remaining accounts is complete, consolidate your funds into that account and proceed according to Case 3.

***

This streamlined process ensures that you can efficiently transition from being a nominator to a validator, maximizing your participation in the PHRON network while minimizing the amount of PHRON that needs to be unbonded.


# Dashboard

### **Key Features**

**A. Accounts Management**

* Creating Accounts: Use the “Accounts” tab to generate new accounts. This feature supports the creation of both single and multi-signature accounts for enhanced security.
* Importing Accounts: Import existing accounts using JSON files or mnemonic phrases, allowing for seamless transitions between different environments.
* Account Actions: Easily send tokens, check balances, and view transaction history. The dashboard supports batch transactions, allowing you to send tokens to multiple recipients in one go.

**B. Network Interaction**

* Block Explorer: Under the "Network" tab, you can explore blocks, extrinsics, and events on the blockchain. Each block displays detailed information, including block hashes, timestamp, author, and included extrinsics.
* Latest Transactions: Access a real-time feed of recent transactions and their statuses, with filter options for transaction type and status (e.g., pending, completed, failed).

**C. Staking**

* Staking Overview: Access the "Staking" tab for a comprehensive view of your staking activities, including active nominations, reward history, and unbonding status.
* Nominating Validators: Nominate validators by assessing their performance metrics, such as total stake, commission rates, and historical uptime percentages. You can also view detailed validator profiles, including their reward distribution strategies.

**D. Governance**

* Proposals and Referenda: Track current proposals, referenda, and voting activities in the "Governance" section. Each proposal includes details such as the proposer, status, and voting results.
* Submitting Proposals: If you're involved in governance, you can submit proposals directly through the dashboard, utilizing built-in templates for standard proposal types.

**E. Developer Tools**

* RPC Calls: Access the raw RPC interface for advanced interactions with the blockchain. You can test various methods, view responses, and troubleshoot issues using the console feature.
* Sign & Send Transactions: Use the dashboard to manually sign and send transactions, providing detailed options for configuring gas limits, nonce values, and other transaction parameters.

**4. Customization and Settings**

* User Preferences: Adjust the dashboard settings to suit your preferences, including language, themes (light/dark mode), and connection settings for different networks (e.g., mainnet, testnet).
* Extensions: Leverage browser extensions such as the PHRON wallet for enhanced security and convenience in managing your accounts, enabling easy signing of transactions.

**5. Resources and Support**

* **Documentation:** Utilize the official PHRON documentation for in-depth guides, API references, and examples of using the SDK for application development.
* **Community:** Engage with the PHRON community through forums, Discord channels, and GitHub repositories for support, collaboration, and sharing of best practices.


# Telemetry


# Node Operations


# Why & node types

### Hardware Requirements

To effectively operate a validator node, it's essential to have a machine capable of handling the necessary computations. While many validators opt for cloud providers for convenience, running your node on your own hardware is optimal for decentralization.

### **Key Considerations**

When selecting your hardware, prioritize a setup with fast input/output capabilities. We recommend using NVMe SSDs for storage, as they offer superior speed. Additionally, ensure your network connection has low latency and high reliability to maintain consistent performance.

### **Recommended Hardware Configuration**

Here’s a robust setup that will enable you to run your node smoothly, minimizing the risk of disruptions that could affect block production:

* **CPU:** A modern desktop x86\_64 processor (Intel or AMD) with at least 8 cores.
* **RAM:** 32GB for efficient multitasking and performance.
* **Storage Options:**

1. Pruned Node (recommended for validators): 500GB NVMe SSD.
2. Archive Node (necessary for RPC nodes): 2TB NVMe SSD.

* Network: A connection of 100+ Mbps, ensuring low latency for optimal node operation.

By adhering to these specifications, you’ll be well-equipped to contribute to the network effectively and maintain the integrity of your validator node.


# Build with PhronAI


# SDKs and Tools

APIs, SDKs and Tools


# Ethereum

Ethereum


# Contracts

### Common-good Contracts <a href="#common-goods-contracts" id="common-goods-contracts"></a>

The following contracts addresses have been established:<br>

<table><thead><tr><th width="230" align="center">Contract</th><th align="center">Address</th></tr></thead><tbody><tr><td align="center">WGLMR</td><td align="center">0xAcc15dC74880C9944775448304B263D191c6077F</td></tr><tr><td align="center">Multicall</td><td align="center">0x83e3b61886770de2F64AAcaD2724ED4f08F7f36B</td></tr><tr><td align="center">Multicall2</td><td align="center">0x6477204E12A7236b9619385ea453F370aD897bb2</td></tr><tr><td align="center">Multicall3</td><td align="center">0xcA11bde05977b3631167028862bE2a173976CA11</td></tr><tr><td align="center">Multisig Factory</td><td align="center">0xa6B71E26C5e0845f74c812102Ca7114b6a896AB2</td></tr><tr><td align="center"><a href="https://eips.ethereum.org/EIPS/eip-1820">EIP-1820</a></td><td align="center">0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24</td></tr></tbody></table>

### Precompiled Contracts <a href="#precompiled-contracts" id="precompiled-contracts"></a>

There are a set of precompiled contracts included on Phron that are categorized by address and based on the origin network. If you were to convert the precompiled addresses to decimal format, and break them into categories by numeric value, the categories are as follows:

* **0-1023** - Ethereum MainNet precompiles
* **1024-2047** - precompiles that are not in Ethereum and not Phron specific
* **2048-4095** - Phron specific precompiles

#### Ethereum MainNet Precompiles <a href="#ethereum-mainnet-precompiles" id="ethereum-mainnet-precompiles"></a>

<table><thead><tr><th width="234" align="center">Contract</th><th align="center">Address</th></tr></thead><tbody><tr><td align="center">ECRECOVER</td><td align="center">0x0000000000000000000000000000000000000001</td></tr><tr><td align="center">SHA256</td><td align="center">0x0000000000000000000000000000000000000002</td></tr><tr><td align="center">RIPEMD160</td><td align="center">0x0000000000000000000000000000000000000003</td></tr><tr><td align="center">Identity</td><td align="center">0x0000000000000000000000000000000000000004</td></tr><tr><td align="center">Modular Exponentiation</td><td align="center">0x0000000000000000000000000000000000000005</td></tr><tr><td align="center">BN128Add</td><td align="center">0x0000000000000000000000000000000000000006</td></tr><tr><td align="center">BN128Mul</td><td align="center">0x0000000000000000000000000000000000000007</td></tr><tr><td align="center">BN128Pairing</td><td align="center">0x0000000000000000000000000000000000000008</td></tr><tr><td align="center"><a href="https://polkadot-evm.github.io/frontier/rustdocs/pallet_evm_precompile_blake2/struct.Blake2F.html">Blake2</a></td><td align="center">0x0000000000000000000000000000000000000009</td></tr><tr><td align="center"><a href="https://github.com/ethereum/RIPs/blob/master/RIPS/rip-7212.md">P256Verify</a></td><td align="center">0x0000000000000000000000000000000000000100</td></tr></tbody></table>

#### Non-Phron Specific nor Ethereum Precompiles <a href="#non-moonbeam-specific-nor-ethereum-precompiles" id="non-moonbeam-specific-nor-ethereum-precompiles"></a>

<table><thead><tr><th width="235" align="center">Contract</th><th align="center">Address</th></tr></thead><tbody><tr><td align="center">SHA3FIPS256</td><td align="center">0x0000000000000000000000000000000000000400</td></tr><tr><td align="center"><a href="https://polkadot-evm.github.io/frontier/rustdocs/pallet_evm_precompile_dispatch/struct.Dispatch.html">Dispatch</a></td><td align="center">0x0000000000000000000000000000000000000401</td></tr><tr><td align="center"><a href="https://polkadot-evm.github.io/frontier/rustdocs/pallet_evm_precompile_simple/struct.ECRecoverPublicKey.html">ECRecoverPublicKey</a></td><td align="center">0x0000000000000000000000000000000000000402</td></tr></tbody></table>

#### Phron-Specific Precompiles <a href="#moonbeam-specific-precompiles" id="moonbeam-specific-precompiles"></a>

<table><thead><tr><th width="263" align="center">Contract</th><th align="center">Address</th></tr></thead><tbody><tr><td align="center">Parachain Staking</td><td align="center">0x0000000000000000000000000000000000000800</td></tr><tr><td align="center">Crowdloan Rewards</td><td align="center">0x0000000000000000000000000000000000000801</td></tr><tr><td align="center">ERC-20 Interface</td><td align="center">0x0000000000000000000000000000000000000802</td></tr><tr><td align="center">X-Tokens</td><td align="center">0x0000000000000000000000000000000000000804</td></tr><tr><td align="center">Relay Encoder</td><td align="center">0x0000000000000000000000000000000000000805</td></tr><tr><td align="center">XCM Transactor V1</td><td align="center">0x0000000000000000000000000000000000000806</td></tr><tr><td align="center">Author Mapping</td><td align="center">0x0000000000000000000000000000000000000807</td></tr><tr><td align="center">Batch</td><td align="center">0x0000000000000000000000000000000000000808</td></tr><tr><td align="center">Randomness</td><td align="center">0x0000000000000000000000000000000000000809</td></tr><tr><td align="center">Call Permit</td><td align="center">0x000000000000000000000000000000000000080a</td></tr><tr><td align="center">Proxy</td><td align="center">0x000000000000000000000000000000000000080b</td></tr><tr><td align="center">XCM Utilities</td><td align="center">0x000000000000000000000000000000000000080C</td></tr><tr><td align="center">XCM Transactor V2</td><td align="center">0x000000000000000000000000000000000000080d</td></tr><tr><td align="center">Treasury Council Collective</td><td align="center">0x0000000000000000000000000000000000000810</td></tr><tr><td align="center">Referenda</td><td align="center">0x0000000000000000000000000000000000000811</td></tr><tr><td align="center">Conviction Voting</td><td align="center">0x0000000000000000000000000000000000000812</td></tr><tr><td align="center">Preimage</td><td align="center">0x0000000000000000000000000000000000000813</td></tr><tr><td align="center">OpenGov Tech Committee</td><td align="center">0x0000000000000000000000000000000000000814</td></tr><tr><td align="center">Precompile Registry</td><td align="center">0x0000000000000000000000000000000000000815</td></tr><tr><td align="center">GMP</td><td align="center">0x0000000000000000000000000000000000000816</td></tr><tr><td align="center">XCM Transactor V3</td><td align="center">0x0000000000000000000000000000000000000817</td></tr><tr><td align="center">Identity</td><td align="center">0x0000000000000000000000000000000000000818</td></tr></tbody></table>


# Libraries


# Ethers.js

## Ethers.js JavaScript Library <a href="#ethersjs-javascript-library" id="ethersjs-javascript-library"></a>

### Introduction <a href="#introduction" id="introduction"></a>

The [Ethers.js](https://docs.ethers.org/v6) library provides a set of tools to interact with Ethereum Nodes with JavaScript, similar to Web3.js. Phron has an Ethereum-like API available that is fully compatible with Ethereum-style JSON-RPC invocations. Therefore, developers can leverage this compatibility and use the Ethers.js library to interact with a Phron node as if they were doing so on Ethereum. For more information on Ethers.js, check their [documentation site](https://docs.ethers.org/v6).

In this guide, you'll learn how to use the Ethers.js library to send a transaction and deploy a contract on Phron.

### Checking Prerequisites <a href="#checking-prerequisites" id="checking-prerequisites"></a>

For the examples in this guide, you will need to have the following:

* An account with funds. You can get DEV tokens for testing on Phron once every 24 hours from the Phron Faucet
* To test out the examples in this guide on Phron, you will need to have your own endpoint and API key, which you can get from one of the supported Endpoint Providers

> ### Note
>
> The examples in this guide assume you have a MacOS or Ubuntu 22.04-based environment and will need to be adapted accordingly for Windows.

### Installing Ethers.js <a href="#install-ethersjs" id="install-ethersjs"></a>

To get started, you'll need to start a basic JavaScript project. First, create a directory to store all of the files you'll be creating throughout this guide and initialize the project with the following command:

```bash
mkdir ethers-examples && cd ethers-examples && npm init --y
```

For this guide, you'll need to install the Ethers.js library and the Solidity compiler. To install both NPM packages, you can run the following command:

```bash
npm install ethers solc@0.8.0
```

### Setting up the Ethers Provider <a href="#setting-up-the-ethers-provider" id="setting-up-the-ethers-provider"></a>

Throughout this guide, you'll be creating a bunch of scripts that provide different functionality such as sending a transaction, deploying a contract, and interacting with a deployed contract. In most of these scripts you'll need to create an [Ethers provider](https://docs.ethers.org/v6/api/providers/) to interact with the network.

To configure your project for Phron, you will need to have your own endpoint and API key, which you can get from one of the supported Endpoint Providers.

To create a provider, you can take the following steps:

1. Import the `ethers` library
2. Define the `providerRPC` object, which can include the network configurations for any of the networks you want to send a transaction on. You'll include the `name`, `rpc`, and `chainId` for each network
3. Create the `provider` using the `ethers.JsonRpcProvider` method

```javascript
// 1. Import ethers
const ethers = require('ethers');

// 2. Define network configurations
const providerRPC = {
  phron: {
    name: 'phron',
    rpc: 'INSERT_RPC_API_ENDPOINT', // Insert your RPC URL here
    chainId: 7744, // 0x504 in hex,
  },
};
// 3. Create ethers provider
const provider = new ethers.JsonRpcProvider(providerRPC.phron.rpc, {
  chainId: providerRPC.phron.chainId,
  name: providerRPC.phron.name,
});
```

Save this code snippet as you'll need it for the scripts that are used in the following sections.

### Send a Transaction <a href="#send-a-transaction" id="send-a-transaction"></a>

During this section, you'll be creating a couple of scripts. The first one will be to check the balances of your accounts before trying to send a transaction. The second script will actually send the transaction.

You can also use the balance script to check the account balances after the transaction has been sent.

#### Check Balances Script <a href="#check-balances-script" id="check-balances-script"></a>

You'll only need one file to check the balances of both addresses before and after the transaction is sent. To get started, you can create a `balances.js` file by running:

```bash
touch balances.js
```

Next, you will create the script for this file and complete the following steps:

1. Set up the Ethers provider
2. Define the `addressFrom` and `addressTo` variables
3. Create the asynchronous `balances` function which wraps the `provider.getBalance` method
4. Use the `provider.getBalance` function to fetch the balances for the `addressFrom` and `addressTo` addresses. You can also leverage the `ethers.formatEther` function to transform the balance into a more readable number in ETH
5. Lastly, run the `balances` function

```javascript
// 1. Add the Ethers provider logic here:
// {...}

// 2. Create address variables
const addressFrom = 'INSERT_FROM_ADDRESS';
const addressTo = 'INSERT_TO_ADDRESS';

// 3. Create balances function
const balances = async () => {
  // 4. Fetch balances
  const balanceFrom = ethers.formatEther(await provider.getBalance(addressFrom));
  const balanceTo = ethers.formatEther(await provider.getBalance(addressTo));

  console.log(`The balance of ${addressFrom} is: ${balanceFrom} DEV`);
  console.log(`The balance of ${addressTo} is: ${balanceTo} DEV`);
};

// 5. Call the balances function
balances();
```

<details>

<summary>View the complete script</summary>

```javascript
// Import ethers
const ethers = require('ethers');

// Define network configurations
const providerRPC = {
  development: {
    name: 'phron-development',
    rpc: 'http://localhost:9944',
    chainId: 7744,
  },
  phron: {
    name: 'phron',
    rpc: 'https://testnet.phron.ai',
    chainId: 7744,
  },
};

// Create ethers provider
const provider = new ethers.JsonRpcProvider(providerRPC.phron.rpc, {
  chainId: providerRPC.phron.chainId,
  name: providerRPC.phron.name,
}); // Change to correct network

// Define addresses
const addressFrom = 'INSERT_FROM_ADDRESS';
const addressTo = 'INSERT_TO_ADDRESS';

// Create balances function
const balances = async () => {
  // Fetch balances
  const balanceFrom = ethers.formatEther(
    await provider.getBalance(addressFrom)
  );
  const balanceTo = ethers.formatEther(await provider.getBalance(addressTo));

  console.log(`The balance of ${addressFrom} is: ${balanceFrom} DEV`);
  console.log(`The balance of ${addressTo} is: ${balanceTo} DEV`);
};

// Call the balances function
balances();
```

</details>

To run the script and fetch the account balances, you can run the following command:

```bash
node balances.js
```

If successful, the balances for the origin and receiving address will be displayed in your terminal in DEV.

#### Send Transaction Script <a href="#send-transaction-script" id="send-transaction-script"></a>

You'll only need one file for executing a transaction between accounts. For this example, you'll be transferring 1 DEV token from an origin address (from which you hold the private key) to another address. To get started, you can create a `transaction.js` file by running:

```bash
touch transaction.js
```

Next, you will create the script for this file and complete the following steps:

1. Set up the Ethers provider
2. Define the `privateKey` and the `addressTo` variables. The private key is required to create a wallet instance. **Note: This is for example purposes only. Never store your private keys in a JavaScript file**
3. Create a wallet using the `privateKey` and `provider` from the previous steps. The wallet instance is used to sign transactions
4. Create the asynchronous `send` function which wraps the transaction object and the `wallet.sendTransaction` method
5. Create the transaction object which only requires the recipient's address and the amount to send. Note that `ethers.parseEther` can be used, which handles the necessary unit conversions from Ether to Wei - similar to using `ethers.parseUnits(value, 'ether')`
6. Send the transaction using the `wallet.sendTransaction` method and then use `await` to wait until the transaction is processed and the transaction receipt is returned
7. Lastly, run the `send` function

{% code overflow="wrap" %}

```javascript
// 1. Add the Ethers provider logic here:
// {...}

// 2. Create account variables
const accountFrom = {
  privateKey: 'INSERT_YOUR_PRIVATE_KEY',
};
const addressTo = 'INSERT_TO_ADDRESS';

// 3. Create wallet
let wallet = new ethers.Wallet(accountFrom.privateKey, provider);

// 4. Create send function
const send = async () => {
  console.log(`Attempting to send transaction from ${wallet.address} to ${addressTo}`);

  // 5. Create tx object
  const tx = {
    to: addressTo,
    value: ethers.parseEther('1'),
  };

  // 6. Sign and send tx - wait for receipt
  const createReceipt = await wallet.sendTransaction(tx);
  await createReceipt.wait();
  console.log(`Transaction successful with hash: ${createReceipt.hash}`);
};

// 7. Call the send function
send();
```

{% endcode %}

<details>

<summary>View the complete script</summary>

{% code overflow="wrap" %}

```javascript
// Import ethers
const ethers = require('ethers');

// Define network configurations
const providerRPC = {
  development: {
    name: 'phron-development',
    rpc: 'http://localhost:9944',
    chainId: 7744,
  },
  phronbase: {
    name: 'phron',
    rpc: 'https://testnet.phron.ai',
    chainId: 7744,
  },
};
// Create ethers provider
const provider = new ethers.JsonRpcProvider(providerRPC.phron.rpc, {
  chainId: providerRPC.phron.chainId,
  name: providerRPC.phron.name,
}); // Change to correct network

// Define accounts and wallet
const accountFrom = {
  privateKey: 'INSERT_YOUR_PRIVATE_KEY',
};
const addressTo = 'INSERT_TO_ADDRESS';
const wallet = new ethers.Wallet(accountFrom.privateKey, provider);

// Create send function
const send = async () => {
  console.log(
    `Attempting to send transaction from ${wallet.address} to ${addressTo}`
  );

  // Create transaction
  const tx = {
    to: addressTo,
    value: ethers.parseEther('1'),
  };

  // Send transaction and get hash
  const createReceipt = await wallet.sendTransaction(tx);
  await createReceipt.wait();
  console.log(`Transaction successful with hash: ${createReceipt.hash}`);
};

// Call the send function
send();
```

{% endcode %}

</details>

To run the script, you can run the following command in your terminal:

```bash
node transaction.js
```

If the transaction was succesful, in your terminal you'll see the transaction hash has been printed out.

You can also use the `balances.js` script to check that the balances for the origin and receiving accounts have changed. The entire workflow would look like this:

{% code overflow="wrap" %}

```bash
node balances.jsThe balance of 0x3B939FeaD1557C741Ff06492FD0127bd287A421e is: 3604.673685275447543445 DEVThe balance of 0xFFA0352d300cdd8aCdA5c947D87CbCc3f0B3485A is: 0 DEVnode transaction.jsAttempting to send transaction from 0x3B939FeaD1557C741Ff06492FD0127bd287A421e to 0xFFA0352d300cdd8aCdA5c947D87CbCc3f0B3485ATransaction successful with hash: 0x01e42c627fe79b1d5649a64d39fceec34aba3904e37d768e74ec71fcd62b897fnode balances.jsThe balance of 0x3B939FeaD1557C741Ff06492FD0127bd287A421e is: 3603.673682650447543445 DEVThe balance of 0xFFA0352d300cdd8aCdA5c947D87CbCc3f0B3485A is: 1.0 DEV
```

{% endcode %}

### Deploy a Contract <a href="#deploy-a-contract" id="deploy-a-contract"></a>

The contract you'll be compiling and deploying in the next couple of sections is a simple incrementer contract, arbitrarily named `Incrementer.sol`. You can get started by creating a file for the contract:

```bash
touch Incrementer.sol
```

Next, you can add the Solidity code to the file:

```solidity
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

contract Incrementer {
    uint256 public number;

    constructor(uint256 _initialNumber) {
        number = _initialNumber;
    }

    function increment(uint256 _value) public {
        number = number + _value;
    }

    function reset() public {
        number = 0;
    }
}
```

The `constructor` function, which runs when the contract is deployed, sets the initial value of the number variable stored on-chain (the default is `0`). The `increment` function adds the `_value` provided to the current number, but a transaction needs to be sent, which modifies the stored data. Lastly, the `reset` function resets the stored value to zero.

> ### Note
>
> This contract is a simple example for illustration purposes only and does not handle values wrapping around.

#### Compile Contract Script <a href="#compile-contract-script" id="compile-contract-script"></a>

In this section, you'll create a script that uses the Solidity compiler to output the bytecode and interface (ABI) for the `Incrementer.sol` contract. To get started, you can create a `compile.js` file by running:

```bash
touch compile.js
```

Next, you will create the script for this file and complete the following steps:

1. Import the `fs` and `solc` packages
2. Using the `fs.readFileSync` function, you'll read and save the file contents of `Incrementer.sol` to `source`
3. Build the `input` object for the Solidity compiler by specifying the `language`, `sources`, and `settings` to be used
4. Using the `input` object, you can compile the contract using `solc.compile`
5. Extract the compiled contract file and export it to be used in the deployment script

```javascript
// 1. Import packages
const fs = require('fs');
const solc = require('solc');

// 2. Get path and load contract
const source = fs.readFileSync('Incrementer.sol', 'utf8');

// 3. Create input object
const input = {
   language: 'Solidity',
   sources: {
      'Incrementer.sol': {
         content: source,
      },
   },
   settings: {
      outputSelection: {
         '*': {
            '*': ['*'],
         },
      },
   },
};
// 4. Compile the contract
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
const contractFile = tempFile.contracts['Incrementer.sol']['Incrementer'];

// 5. Export contract data
module.exports = contractFile;
```

#### Deploy Contract Script <a href="#deploy-contract-script" id="deploy-contract-script"></a>

With the script for compiling the `Incrementer.sol` contract in place, you can then use the results to send a signed transaction that deploys it. To do so, you can create a file for the deployment script called `deploy.js`:

```bash
touch deploy.js
```

Next, you will create the script for this file and complete the following steps:

1. Import the contract file from `compile.js`
2. Set up the Ethers provider
3. Define the `privateKey` for the origin account. The private key is required to create a wallet instance. **Note: This is for example purposes only. Never store your private keys in a JavaScript file**
4. Create a wallet using the `privateKey` and `provider` from the previous steps. The wallet instance is used to sign transactions
5. Load the contract `bytecode` and `abi` for the compiled contract
6. Create a contract instance with signer using the `ethers.ContractFactory` function, providing the `abi`, `bytecode`, and `wallet` as parameters
7. Create the asynchronous `deploy` function that will be used to deploy the contract
8. Within the `deploy` function, use the `incrementer` contract instance to call `deploy` and pass in the initial value. For this example, you can set the initial value to `5`. This will send the transaction for contract deployment. To wait for a transaction receipt you can use the `deployed` method of the contract deployment transaction
9. Lastly, run the `deploy` function

```javascript
// 1. Import the contract file
const contractFile = require('./compile');

// 2. Add the Ethers provider logic here:
// {...}

// 3. Create account variables
const accountFrom = {
  privateKey: 'INSERT_YOUR_PRIVATE_KEY',
};

// 4. Create wallet
let wallet = new ethers.Wallet(accountFrom.privateKey, provider);

// 5. Load contract information
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;

// 6. Create contract instance with signer
const incrementer = new ethers.ContractFactory(abi, bytecode, wallet);

// 7. Create deploy function
const deploy = async () => {
  console.log(`Attempting to deploy from account: ${wallet.address}`);

  // 8. Send tx (initial value set to 5) and wait for receipt
  const contract = await incrementer.deploy(5);
  const txReceipt = await contract.deploymentTransaction().wait();

  console.log(`Contract deployed at address: ${txReceipt.contractAddress}`);
};

// 9. Call the deploy function
deploy();
```

<details>

<summary>View the complete script</summary>

```javascript
// Import ethers and compile
const ethers = require('ethers');
const contractFile = require('./compile');

// Define network configurations
const providerRPC = {
  development: {
    name: 'phron-development',
    rpc: 'http://localhost:9944',
    chainId: 7744,
  },
  phronbase: {
    name: 'phron',
    rpc: 'https://testnet.phron.ai',
    chainId: 7744,
  },
};

// Create ethers provider
const provider = new ethers.JsonRpcProvider(providerRPC.phron.rpc, {
  chainId: providerRPC.phron.chainId,
  name: providerRPC.phron.name,
}); // Change to correct network

// Define accounts and wallet
const accountFrom = {
  privateKey: 'INSERT_YOUR_PRIVATE_KEY',
};
let wallet = new ethers.Wallet(accountFrom.privateKey, provider);

// Load contract info
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;

// Create contract instance with signer
const incrementer = new ethers.ContractFactory(abi, bytecode, wallet);

// Create deploy function
const deploy = async () => {
  console.log(`Attempting to deploy from account: ${wallet.address}`);

  // Send tx (initial value set to 5) and wait for receipt
  const contract = await incrementer.deploy(5);
  const txReceipt = await contract.deploymentTransaction().wait();

  console.log(`Contract deployed at address: ${txReceipt.contractAddress}`);
};

// Call the deploy function
deploy();
```

</details>

To run the script, you can enter the following command into your terminal:

```bash
node deploy.js
```

If successful, the contract's address will be displayed in the terminal.

{% code overflow="wrap" %}

```bash
node deploy.jsAttempting to deploy from account: 0x3B939FeaD1557C741Ff06492FD0127bd287A421eContract deployed at address: 0x2B9c71fc2730B7353Dd3865ae26881Fa38FE598A
```

{% endcode %}

#### Read Contract Data (Call Methods) <a href="#read-contract-data" id="read-contract-data"></a>

Call methods are the type of interaction that don't modify the contract's storage (change variables), meaning no transaction needs to be sent. They simply read various storage variables of the deployed contract.

To get started, you can create a file and name it `get.js`:

```bash
touch get.js
```

Then you can take the following steps to create the script:

1. Import the `abi` from the `compile.js` file
2. Set up the Ethers provider
3. Create the `contractAddress` variable using the address of the deployed contract
4. Create an instance of the contract using the `ethers.Contract` function and passing in the `contractAddress`, `abi`, and `provider`
5. Create the asynchronous `get` function
6. Use the contract instance to call one of the contract's methods and pass in any inputs if necessary. For this example, you will call the `number` method which doesn't require any inputs. You can use `await` which will return the value requested once the request promise resolves
7. Lastly, call the `get` function

```javascript
// 1. Import the ABI
const { abi } = require('./compile');

// 2. Add the Ethers provider logic here:
// {...}

// 3. Contract address variable
const contractAddress = 'INSERT_CONTRACT_ADDRESS';

// 4. Create contract instance
const incrementer = new ethers.Contract(contractAddress, abi, provider);

// 5. Create get function
const get = async () => {
  console.log(`Making a call to contract at address: ${contractAddress}`);

  // 6. Call contract 
  const data = await incrementer.number();

  console.log(`The current number stored is: ${data}`);
};

// 7. Call get function
get();
```

<details>

<summary>View the complete script</summary>

```javascript
// Import ethers and compile
const ethers = require('ethers');
const { abi } = require('./compile');

// Define network configurations
const providerRPC = {
  development: {
    name: 'phron-development',
    rpc: 'http://localhost:9944',
    chainId: 7744,
  },
  phronbase: {
    name: 'phron',
    rpc: 'https://testnet.phron.ai',
    chainId: 7744,
  },
};

const provider = new ethers.JsonRpcProvider(providerRPC.phron.rpc, {
  chainId: providerRPC.phron.chainId,
  name: providerRPC.phron.name,
}); // Change to correct network

// Contract address variable
const contractAddress = 'INSERT_CONTRACT_ADDRESS';

// Create contract instance
const incrementer = new ethers.Contract(contractAddress, abi, provider);

// Create get function
const get = async () => {
  console.log(`Making a call to contract at address: ${contractAddress}`);

  // Call contract
  const data = await incrementer.number();

  console.log(`The current number stored is: ${data}`);
};

// Call get function
get();
```

</details>

To run the script, you can enter the following command in your terminal:

```bash
node get.js
```

If successful, the value will be displayed in the terminal.

#### Interact with Contract (Send Methods) <a href="#interact-with-contract" id="interact-with-contract"></a>

Send methods are the type of interaction that modify the contract's storage (change variables), meaning a transaction needs to be signed and sent. In this section, you'll create two scripts: one to increment and one to reset the incrementer. To get started, you can create a file for each script and name them `increment.js` and `reset.js`:

```bash
touch increment.js reset.js
```

Open the `increment.js` file and take the following steps to create the script:

1. Import the `abi` from the `compile.js` file
2. Set up the Ethers provider
3. Define the `privateKey` for the origin account, the `contractAddress` of the deployed contract, and the `_value` to increment by. The private key is required to create a wallet instance. **Note: This is for example purposes only. Never store your private keys in a JavaScript file**
4. Create a wallet using the `privateKey` and `provider` from the previous steps. The wallet instance is used to sign transactions
5. Create an instance of the contract using the `ethers.Contract` function and passing in the `contractAddress`, `abi`, and `provider`
6. Create the asynchronous `increment` function
7. Use the contract instance to call one of the contract's methods and pass in any inputs if necessary. For this example, you will call the `increment` method which requires the value to increment by as an input. You can use `await` which will return the value requested once the request promise resolves
8. Lastly, call the `increment` function

```javascript
// 1. Import the contract ABI
const { abi } = require('./compile');

// 2. Add the Ethers provider logic here:
// {...}

// 3. Create variables
const accountFrom = {
  privateKey: 'INSERT_YOUR_PRIVATE_KEY',
};
const contractAddress = 'INSERT_CONTRACT_ADDRESS';
const _value = 3;

// 4. Create wallet
let wallet = new ethers.Wallet(accountFrom.privateKey, provider);

// 5. Create contract instance with signer
const incrementer = new ethers.Contract(contractAddress, abi, wallet);

// 6. Create increment function
const increment = async () => {
  console.log(
    `Calling the increment by ${_value} function in contract at address: ${contractAddress}`
  );

  // 7. Sign and send tx and wait for receipt
  const createReceipt = await incrementer.increment(_value);
  await createReceipt.wait();

  console.log(`Tx successful with hash: ${createReceipt.hash}`);
};

// 8. Call the increment function
increment();
```

<details>

<summary>View the complete script</summary>

```javascript
// Import ethers and compile
const ethers = require('ethers');
const { abi } = require('./compile');

// Define network configurations
const providerRPC = {
  development: {
    name: 'phron-development',
    rpc: 'http://localhost:9944',
    chainId: 7744,
  },
  phronbase: {
    name: 'phron',
    rpc: 'https://testnet.phron.ai',
    chainId: 7744,
  },
};

// Create ethers provider
const provider = new ethers.JsonRpcProvider(providerRPC.phron.rpc, {
  chainId: providerRPC.phron.chainId,
  name: providerRPC.phron.name,
}); // Change to correct network

// Create variables
const accountFrom = {
  privateKey: 'INSERT_YOUR_PRIVATE_KEY',
};
const contractAddress = 'INSERT_CONTRACT_ADDRESS';
const _value = 3;

// Create wallet
let wallet = new ethers.Wallet(accountFrom.privateKey, provider);

// Create contract instance with signer
const incrementer = new ethers.Contract(contractAddress, abi, wallet);

// Create reset function
const increment = async () => {
  console.log(
    `Calling the increment by ${_value} function in contract at address: ${contractAddress}`
  );

  // Sign and send tx and wait for receipt
  const createReceipt = await incrementer.increment(_value);
  await createReceipt.wait();

  console.log(`Tx successful with hash: ${createReceipt.hash}`);
};

// Call the reset function
increment();
```

</details>

To run the script, you can enter the following command in your terminal:

```bash
node increment.js
```

If successful, the transaction hash will be displayed in the terminal. You can use the `get.js` script alongside the `increment.js` script to make sure that value is changing as expected:

{% code overflow="wrap" %}

```bash
node get.jsMaking a call to contract at address: 0x2B9c71fc2730B7353Dd3865ae26881Fa38FE598AThe current number stored is: 5node increment.jsCalling the increment by 3 function in contract at address: 0x2B9c71fc2730B7353Dd3865ae26881Fa38FE598ATx successful with hash: 0xc7fe935db03cfacf56c5649cd79a566d1a7b68417f904f0095a1b1c203875bf2node get.jsMaking a call to contract at address: 0x2B9c71fc2730B7353Dd3865ae26881Fa38FE598AThe current number stored is: 8
```

{% endcode %}

Next you can open the `reset.js` file and take the following steps to create the script:

1. Import the `abi` from the `compile.js` file
2. Set up the Ethers provider
3. Define the `privateKey` for the origin account and the `contractAddress` of the deployed contract. The private key is required to create a wallet instance. **Note: This is for example purposes only. Never store your private keys in a JavaScript file**
4. Create a wallet using the `privateKey` and `provider` from the previous steps. The wallet instance is used to sign transactions
5. Create an instance of the contract using the `ethers.Contract` function and passing in the `contractAddress`, `abi`, and `provider`
6. Create the asynchronous `reset` function
7. Use the contract instance to call one of the contract's methods and pass in any inputs if necessary. For this example, you will call the `reset` method which doesn't require any inputs. You can use `await` which will return the value requested once the request promise resolves
8. Lastly, call the `reset` function

```javascript
// 1. Import the contract ABI
const { abi } = require('./compile');

// 2. Add the Ethers provider logic here:
// {...}

// 3. Create variables
const accountFrom = {
  privateKey: 'INSERT_YOUR_PRIVATE_KEY',
};
const contractAddress = 'INSERT_CONTRACT_ADDRESS';

// 4. Create wallet
let wallet = new ethers.Wallet(accountFrom.privateKey, provider);

// 5. Create contract instance with signer
const incrementer = new ethers.Contract(contractAddress, abi, wallet);

// 6. Create reset function
const reset = async () => {
  console.log(
    `Calling the reset function in contract at address: ${contractAddress}`
  );

  // 7. sign and send tx and wait for receipt
  const createReceipt = await incrementer.reset();
  await createReceipt.wait();

  console.log(`Tx successful with hash: ${createReceipt.hash}`);
};

// 8. Call the reset function
reset();
```

<details>

<summary>View the complete script</summary>

```javascript
// Import ethers and compile
const ethers = require('ethers');
const { abi } = require('./compile');

// Define network configurations
const providerRPC = {
  development: {
    name: 'phron-development',
    rpc: 'http://localhost:9944',
    chainId: 7744,
  },
  phron: {
    name: 'phron',
    rpc: 'https://testnet.phron.ai',
    chainId: 7744,
  },
};

// Create ethers provider
const provider = new ethers.JsonRpcProvider(providerRPC.phron.rpc, {
  chainId: providerRPC.phron.chainId,
  name: providerRPC.phron.name,
}); // Change to correct network

// Create variables
const accountFrom = {
  privateKey: 'INSERT_YOUR_PRIVATE_KEY',
};
const contractAddress = 'INSERT_CONTRACT_ADDRESS';

// Create wallet
let wallet = new ethers.Wallet(accountFrom.privateKey, provider);

// Create contract instance with signer
const incrementer = new ethers.Contract(contractAddress, abi, wallet);

// Create reset function
const reset = async () => {
  console.log(
    `Calling the reset function in contract at address: ${contractAddress}`
  );

  // Sign and send tx and wait for receipt
  const createReceipt = await incrementer.reset();
  await createReceipt.wait();

  console.log(`Tx successful with hash: ${createReceipt.hash}`);
};

// Call the reset function
reset();
```

</details>

To run the script, you can enter the following command in your terminal:

```bash
node reset.js
```

If successful, the transaction hash will be displayed in the terminal. You can use the `get.js` script alongside the `reset.js` script to make sure that value is changing as expected:

{% code overflow="wrap" %}

```bash
node get.jsMaking a call to contract at address: 0x2B9c71fc2730B7353Dd3865ae26881Fa38FE598AThe current number stored is: 8node reset.jsCalling the reset function in contract at address: 0x2B9c71fc2730B7353Dd3865ae26881Fa38FE598ATx successful with hash: 0xc452d21d8c2be6b81aadab7414103d68149c94a6399149ab8b79a58f0a3b5db7node get.jsMaking a call to contract at address: 0x2B9c71fc2730B7353Dd3865ae26881Fa38FE598AThe current number stored is: 0
```

{% endcode %}

This tutorial is for educational purposes only. As such, any contracts or code created in this tutorial should not be used in production.The information presented herein has been provided by third parties and is made available solely for general information purposes. Phron does not endorse any project listed and described on the Phron Doc Website (<https://docs.Phron.ai/>). Phron does not warrant the accuracy, completeness or usefulness of this information. Any reliance you place on such information is strictly at your own risk. Phron disclaims all liability and responsibility arising from any reliance placed on this information by you or by anyone who may be informed of any of its contents. All statements and/or opinions expressed in these materials are solely the responsibility of the person or entity providing those materials and do not necessarily represent the opinion of Phron. The information should not be construed as professional or financial advice of any kind. Advice from a suitably qualified professional should always be sought in relation to any particular matter or circumstance. The information herein may link to or integrate with other websites operated or content provided by third parties, and such other websites may link to this website. Phron has no control over any such other websites or their content and will have no liability arising out of or related to such websites or their content. The existence of any such link does not constitute an endorsement of such websites, the content of the websites, or the operators of the websites. These links are being provided to you only as a convenience and you release and hold Phron harmless from any and all liability arising from your use of this information or the information provided by any third-party website or service.


# Ethers.rs

## Ethers.rs Rust Library <a href="#ethersrs-rust-library" id="ethersrs-rust-library"></a>

### Introduction <a href="#introduction" id="introduction"></a>

The [Ethers.rs](https://ethers.rs/) library provides a set of tools to interact with Ethereum Nodes via the Rust programming language that works similar to Ethers.js. Phron has an Ethereum-like API available that is fully compatible with Ethereum-style JSON-RPC invocations. Therefore, developers can leverage this compatibility and use the Ethers.rs library to interact with a Phron node as if they were doing so on Ethereum. You can read more about how to use Ethers.rs on their [official crate documentation](https://docs.rs/crate/ethers/latest).

In this guide, you'll learn how to use the Ethers.rs library to send a transaction and deploy a contract on Phron.&#x20;

### Checking Prerequisites <a href="#checking-prerequisites" id="checking-prerequisites"></a>

For the examples in this guide, you will need to have the following:

* An account with funds. You can get DEV tokens for testing on Phron once every 24 hours from the Phron Faucet
* To test out the examples in this guide on Phron, you will need to have your own endpoint and API key, which you can get from one of the supported Endpoint Providers
* Have [Rust installed](https://www.rust-lang.org/tools/install) on your device
* Have [solc installed](https://docs.soliditylang.org/en/v0.8.9/installing-solidity.html) on your device. Using [solc-select](https://github.com/crytic/solc-select) is recommended by the Ethers.rs package

> ### Note
>
> The examples in this guide assumes you have a MacOS or Ubuntu 20.04-based environment and will need to be adapted accordingly for Windows.

### Create a Rust Project <a href="#create-a-rust-project" id="create-a-rust-project"></a>

To get started, you can create a new Rust project with the Cargo tool:

```bash
cargo init ethers-examples && cd ethers-examples
```

For this guide, you'll need to install the Ethers.rs library among others. To tell the Rust project to install it, you must edit the `Cargo.toml` file that's included with the document to include it under dependencies:

```rust
[package]
name = "ethers-examples"
version = "0.1.0"
edition = "2021"

[dependencies]
ethers = "1.0.2"
ethers-solc = "1.0.2"
tokio = { version = "1", features = ["full"] }
serde_json = "1.0.89"
serde = "1.0.149"
```

This example is using the `ethers` and `ethers-solc` crate versions `1.0.2` for RPC interactions and Solidity compiling. It also includes the `tokio` crate to run asynchronous Rust environments, since interacting with RPCs requires asynchronous code. Finally, it includes the `serde_json` and `serde` crates to help serialize/deserialize this example's code.

If this is your first time using `solc-select`, you'll need to install and configure the Solidity version using the following commands:

```bash
solc-select install 0.8.17 && solc-select use 0.8.17
```

### Setting up the Ethers Provider and Client <a href="#setting-up-the-ethers-provider-and-client" id="setting-up-the-ethers-provider-and-client"></a>

Throughout this guide, you'll be writing multiple functions that provide different functionality such as sending a transaction, deploying a contract, and interacting with a deployed contract. In most of these scripts you'll need to use an [Ethers provider](https://docs.rs/ethers-providers/latest/ethers_providers/index.html) or an [Ethers signer client](https://docs.rs/ethers/1.0.2/ethers/middleware/struct.SignerMiddleware.html) to interact with the network.

To configure your project for Phron, you will need to have your own endpoint and API key, which you can get from one of the supported Endpoint Providers.

There are multiple ways to create a provider and signer, but the easiest way is through `try_from`. In the `src/main.rs` file, you can take the following steps:

1. Import `Provider` and `Http` from the `ethers` crate
2. Add a `Client` type for convenience, which will be used once you start to create the functions for sending a transaction and deploying a contract
3. Add a `tokio` attribute above `async fn main()` for asynchronous excution
4. Use `try_from` to attempt to instantiate a JSON-RPC provider object from an RPC endpoint
5. Use a private key to create a wallet object (the private key will be used to sign transactions). **Note: This is for example purposes only. Never store your private keys in a plain Rust file**
6. Wrap the provider and wallet together into a client by providing them to a `SignerMiddleware` object

```rust
// 1. Import ethers crate
use ethers::providers::{Provider, Http};

// 2. Add client type
type Client = SignerMiddleware<Provider<Http>, Wallet<k256::ecdsa::SigningKey>>;

// 3. Add annotation
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 4. Use try_from with RPC endpoint
    let provider = Provider::<Http>::try_from(
        "INSERT_RPC_API_ENDPOINT"
    )?;
    // 5. Use a private key to create a wallet
    // Do not include the private key in plain text in any production code
    // This is just for demonstration purposes
    // Do not include '0x' at the start of the private key
    let wallet: LocalWallet = "INSERT_YOUR_PRIVATE_KEY"
        .parse::<LocalWallet>()?
        .with_chain_id(Chain::Phron);

    // 6. Wrap the provider and wallet together to create a signer client
    let client = SignerMiddleware::new(provider.clone(), wallet.clone());
    Ok(())
}
```

### Send a Transaction <a href="#send-a-transaction" id="send-a-transaction"></a>

During this section, you'll be creating a couple of functions, which will be contained in the same `main.rs` file to avoid additional complexity from implementing modules. The first function will be to check the balances of your accounts before trying to send a transaction. The second function will actually send the transaction. To run each of these functions, you will edit the `main` function and run the `main.rs` script.

You should already have your provider and client set up in `main.rs` in the way described in the previous section. In order to send a transaction, you'll need to add a few more lines of code:

1. Add `use ethers::{utils, prelude::*};` to your imports, which will provide you access to utility functions and the prelude imports all of the necessary data types and traits
2. As you'll be sending a transaction from one address to another, you can specify the sending and receiving addresses in the `main` function. **Note: the `address_from` value should correspond to the private key that is used in the `main` function**

```rust
// ...
// 1. Add to imports
use ethers::{utils, prelude::*};

// ...

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // ...

    // 2. Add from and to address
    let address_from = "YOUR_FROM_ADDRESS".parse::<Address>()?
    let address_to = "YOUR_TO_ADDRESS".parse::<Address>()?
}
```

#### Check Balances Function <a href="#check-balances-function" id="check-balances-function"></a>

Next, you will create the function for getting the sending and receiving accounts' balances by completing the following steps:

1. Create a new asynchronous function named `print_balances` that takes a provider object's reference and the sending and receiving addresses as input
2. Use the `provider` object's `get_balance` function to get the balances of the sending and receiving addresses of the transaction
3. Print the resultant balances for the sending and receiving addresses
4. Call the `print_balances` function in the `main` function

{% code overflow="wrap" %}

```rust
// ...

// 1. Create an asynchronous function that takes a provider reference and from and to address as input
async fn print_balances(provider: &Provider<Http>, address_from: Address, address_to: Address) -> Result<(), Box<dyn std::error::Error>> {
    // 2. Use the get_balance function
    let balance_from = provider.get_balance(address_from, None).await?;
    let balance_to = provider.get_balance(address_to, None).await?;

    // 3. Print the resultant balance
    println!("{} has {}", address_from, balance_from);
    println!("{} has {}", address_to, balance_to);

    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // ...

    // 4. Call print_balances function in main
    print_balances(&provider).await?;

    Ok(())
}
```

{% endcode %}

#### Send Transaction Script <a href="#send-transaction-script" id="send-transaction-script"></a>

For this example, you'll be transferring 1 DEV from an origin address (of which you hold the private key) to another address.

1. Create a new asynchronous function named `send_transaction` that takes a client object's reference and the sending and receiving addresses as input
2. Create the transaction object, and include the `to`, `value`, and `from`. When writing the `value` input, use the `ethers::utils::parse_ether` function
3. Use the `client` object to send the transaction
4. Print the transaction after it is confirmed
5. Call the `send_transaction` function in the `main` function

```rust
// ...

// 1. Define an asynchronous function that takes a client provider and the from and to addresses as input
async fn send_transaction(client: &Client, address_from: Address, address_to: Address) -> Result<(), Box<dyn std::error::Error>> {
    println!(
        "Beginning transfer of 1 native currency from {} to {}.",
        address_from, address_to
    );

    // 2. Create a TransactionRequest object
    let tx = TransactionRequest::new()
        .to(address_to)
        .value(U256::from(utils::parse_ether(1)?))
        .from(address_from);

    // 3. Send the transaction with the client
    let tx = client.send_transaction(tx, None).await?.await?;

    // 4. Print out the result
    println!("Transaction Receipt: {}", serde_json::to_string(&tx)?);

    Ok(())
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // ...

    // 5. Call send_transaction function in main
    send_transaction(&client, address_from, address_to).await?;

    Ok(())
}
```

<details>

<summary>View the complete script</summary>

{% code overflow="wrap" %}

```rust
use ethers::providers::{Provider, Http};
use ethers::{utils, prelude::*};

type Client = SignerMiddleware<Provider<Http>, Wallet<k256::ecdsa::SigningKey>>;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let provider: Provider<Http> = Provider::<Http>::try_from("https://testnet.phron.ai")?; // Change to correct network
    // Do not include the private key in plain text in any production code. This is just for demonstration purposes
    let wallet: LocalWallet = "INSERT_PRIVATE_KEY"
        .parse::<LocalWallet>()?
        .with_chain_id(Chain::Phron);  // Change to correct network
    let client = SignerMiddleware::new(provider.clone(), wallet.clone());

    let address_from = "INSERT_FROM_ADDRESS".parse::<Address>()?;
    let address_to = "INSERT_TO_ADDRESS".parse::<Address>()?;

    send_transaction(&client, &address_from, &address_to).await?;
    print_balances(&provider, &address_from, &address_to).await?;

    Ok(())
}

// Print the balance of a wallet
async fn print_balances(provider: &Provider<Http>, address_from: &Address, address_to: &Address) -> Result<(), Box<dyn std::error::Error>> {
    let balance_from = provider.get_balance(address_from.clone(), None).await?;
    let balance_to = provider.get_balance(address_to.clone(), None).await?;

    println!("{} has {}", address_from, balance_from);
    println!("{} has {}", address_to, balance_to);
    Ok(())
}


// Sends some native currency
async fn send_transaction(client: &Client, address_from: &Address, address_to: &Address) -> Result<(), Box<dyn std::error::Error>> {
    println!(
        "Beginning transfer of 1 native currency {} to {}.",
        address_from, address_to
    );
    let tx = TransactionRequest::new()
        .to(address_to.clone())
        .value(U256::from(utils::parse_ether(1)?))
        .from(address_from.clone());
    let tx = client.send_transaction(tx, None).await?.await?;

    println!("Transaction Receipt: {}", serde_json::to_string(&tx)?);

    Ok(())
}
```

{% endcode %}

</details>

To run the script, which will send the transaction and then check the balances once the transaction has been sent, you can run the following command:

```bash
cargo run
```

If the transaction was succesful, in your terminal you'll see the transaction details printed out along with the balance of your address.

{% code overflow="wrap" %}

```bash
cargo runCompiling ethers-examples v0.1.0 (/Users/phron/workspace/ethers-examples)Finished dev [unoptimized + debuginfo] target(s) in 32.76sRunning `target/debug/ethers-examples`Beginning transfer of 1 native currency 0x3b93…421e to 0xe773…8dde.Transaction Receipt: {"transactionHash":"0x6f2338c63286f8b27951ddb6748191149d82647b44a00465f1f776624f490ce9","transactionIndex":"0x0","blockHash":"0x8234eb2083e649ab45c7c5fcdf2026d8f47676f7e29305023d1d00cc349ba215","blockNumber":"0x7ac12d","from":"0x3b939fead1557c741ff06492fd0127bd287a421e","to":"0xe773f740828a968c8a9e1e8e05db486937768dde","cumulativeGasUsed":"0x5208","gasUsed":"0x5208","contractAddress":null,"logs":[],"status":"0x1","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","type":"0x0","effectiveGasPrice":"0x7735940"}0x3b93…421e has 36017039844708655891250xe773…8dde has 1000000000000000000
```

{% endcode %}

### Deploy a Contract <a href="#deploy-a-contract" id="deploy-a-contract"></a>

The contract you'll be compiling and deploying in the next couple of sections is a simple incrementer contract, arbitrarily named `Incrementer.sol`. You can get started by creating a file for the contract:

```bash
touch Incrementer.sol
```

Next, you can add the Solidity code to the file:

```solidity
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

contract Incrementer {
    uint256 public number;

    constructor(uint256 _initialNumber) {
        number = _initialNumber;
    }

    function increment(uint256 _value) public {
        number = number + _value;
    }

    function reset() public {
        number = 0;
    }
}
```

The `constructor` function, which runs when the contract is deployed, sets the initial value of the number variable stored on-chain (the default is `0`). The `increment` function adds the `_value` provided to the current number, but a transaction needs to be sent, which modifies the stored data. Lastly, the `reset` function resets the stored value to zero.

> ### Note
>
> This contract is a simple example for illustration purposes only and does not handle values wrapping around.

During the rest of this section, you'll be creating a couple of functions, which will be contained in the `main.rs` file to avoid additional complexity from implementing modules. The first function will be to compile and deploy the contract. The remaining functions will interact with the deployed contract.

You should already have your provider and client set up in `main.rs` in the way described in the Setting up the Ethers Provider and Client section.

Before getting started with the contract deployment, you'll need to add a few more imports to your `main.rs` file:

```rust
use ethers_solc::Solc;
use ethers::{prelude::*};
use std::{path::Path, sync::Arc};
```

The `ethers_solc` import will be used to compile the smart contract. The `prelude` from Ethers imports some necessary data types and traits. Lastly, the `std` imports will enables you to store your smart contracts and wrap the client into an `Arc` type for thread safety.

#### Compile and Deploy Contract Script <a href="#compile-and-deploy-contract-script" id="compile-and-deploy-contract-script"></a>

This example function will compile and deploy the `Incrementer.sol` smart contract you created in the previous section. The `Incrementer.sol` smart contract should be in the root directory. In the `main.rs` file, you can take the following steps:

1. Create a new asynchronous function named `compile_deploy_contract` that takes a client object's reference as input, and returns an address in the form of `H160`
2. Define a variable named `source` as the path for the directory that hosts all of the smart contracts that should be compiled, which is the root directory
3. Use the `Solc` crate to compile all of the smart contracts in the root directory
4. Get the ABI and bytecode from the compiled result, searching for the `Incrementer.sol` contract
5. Create a contract factory for the smart contract using the ABI, bytecode, and client. The client must be wrapped into an `Arc` type for thread safety
6. Use the factory to deploy. For this example, the value `5` is used as the initial value in the constructor
7. Print out the address after the deployment
8. Return the address
9. Call the `compile_deploy_contract` function in `main`

{% code overflow="wrap" %}

```rust
// ...

// 1. Define an asynchronous function that takes a client provider as input and returns H160
async fn compile_deploy_contract(client: &Client) -> Result<H160, Box<dyn std::error::Error>> {
    // 2. Define a path as the directory that hosts the smart contracts in the project
    let source = Path::new(&env!("CARGO_MANIFEST_DIR"));

    // 3. Compile all of the smart contracts
    let compiled = Solc::default()
        .compile_source(source)
        .expect("Could not compile contracts");

    // 4. Get ABI & Bytecode for Incrementer.sol
    let (abi, bytecode, _runtime_bytecode) = compiled
        .find("Incrementer")
        .expect("could not find contract")
        .into_parts_or_default();

    // 5. Create a contract factory which will be used to deploy instances of the contract
    let factory = ContractFactory::new(abi, bytecode, Arc::new(client.clone()));

    // 6. Deploy
    let contract = factory.deploy(U256::from(5))?.send().await?;

    // 7. Print out the address
    let addr = contract.address();
    println!("Incrementer.sol has been deployed to {:?}", addr);

    // 8. Return the address
    Ok(addr)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // ...

    // 9. Call compile_deploy_contract function in main
    let addr = compile_deploy_contract(&client).await?;

    Ok(())
}
```

{% endcode %}

#### Read Contract Data (Call Methods) <a href="#read-contract-data" id="read-contract-data"></a>

Call methods are the type of interaction that don't modify the contract's storage (change variables), meaning no transaction needs to be sent. They simply read various storage variables of the deployed contract.

Rust is typesafe, which is why the ABI for the `Incrementer.sol` contract is required to generate a typesafe Rust struct. For this example, you should create a new file in the root of the Cargo project called `Incrementer_ABI.json`:

```bash
touch Incrementer_ABI.json
```

The ABI for `Incrementer.sol` is below, which should be copied and pasted into the `Incrementer_ABI.json` file:

```json
[
    {
        "inputs": [
            {
                "internalType": "uint256",
                "name": "_value",
                "type": "uint256"
            }
        ],
        "name": "increment",
        "outputs": [],
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "inputs": [],
        "name": "number",
        "outputs": [
            {
                "internalType": "uint256",
                "name": "",
                "type": "uint256"
            }
        ],
        "stateMutability": "view",
        "type": "function"
    },
    {
        "inputs": [],
        "name": "reset",
        "outputs": [],
        "stateMutability": "nonpayable",
        "type": "function"
    }
]
```

Then you can take the following steps to create a function that reads and returns the `number` method of the `Incrementer.sol` contract:

1. Generate a type-safe interface for the `Incrementer` smart contract with the `abigen` macro
2. Create a new asynchronous function named `read_number` that takes a client object's reference and a contract address reference as input, and returns a U256
3. Create a new instance of the `Incrementer` object generated by the abigen macro with the client and contract address values
4. Call the `number` function in the new `Incrementer` object
5. Print out the resultant value
6. Return the resultant value
7. Call the `read_number` function in `main`

{% code overflow="wrap" %}

```solidity
// ...

// 1. Generate a type-safe interface for the Incrementer smart contract
abigen!(
    Incrementer,
    "./Incrementer_ABI.json",
    event_derives(serde::Deserialize, serde::Serialize)
);

// 2. Define an asynchronous function that takes a client provider and address as input and returns a U256
async fn read_number(client: &Client, contract_addr: &H160) -> Result<U256, Box<dyn std::error::Error>> {
    // 3. Create contract instance
    let contract = Incrementer::new(contract_addr.clone(), Arc::new(client.clone()));

    // 4. Call contract's number function
    let value = contract.number().call().await?;

    // 5. Print out number
    println!("Incrementer's number is {}", value);

    // 6. Return the number
    Ok(value)
}

// ...

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // ...

    // 7. Call read_number function in main
    read_number(&client, &addr).await?;

    Ok(())
}
```

{% endcode %}

<details>

<summary>View the complete script</summary>

{% code overflow="wrap" %}

```rust
use ethers::providers::{Provider, Http};
use ethers::{prelude::*};
use ethers_solc::Solc;
use std::{path::Path, sync::Arc};

type Client = SignerMiddleware<Provider<Http>, Wallet<k256::ecdsa::SigningKey>>;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let provider: Provider<Http> = Provider::<Http>::try_from("https://testnet.phron.ai")?; // Change to correct network
    // Do not include the private key in plain text in any production code. This is just for demonstration purposes
    // Do not include '0x' at the start of the private key
    let wallet: LocalWallet = "INSERT_PRIVATE_KEY"
        .parse::<LocalWallet>()?
        .with_chain_id(Chain::Phron);
    let client = SignerMiddleware::new(provider.clone(), wallet.clone());

    // Deploy contract and read initial incrementer value
    let addr = compile_deploy_contract(&client).await?;
    read_number(&client, &addr).await?;

    // Increment and read the incremented number
    increment_number(&client, &addr).await?;
    read_number(&client, &addr).await?;

    // Reset the incremented number and read it
    reset(&client, &addr).await?;
    read_number(&client, &addr).await?;

    Ok(())
}

// Need to install solc for this tutorial: https://github.com/crytic/solc-select
async fn compile_deploy_contract(client: &Client) -> Result<H160, Box<dyn std::error::Error>> {
    // Incrementer.sol is located in the root directory
    let source = Path::new(&env!("INSERT_CARGO_MANIFEST_DIR"));

    // Compile it
    let compiled = Solc::default()
        .compile_source(source)
        .expect("Could not compile contracts");

    // Get ABI & Bytecode for Incrementer.sol
    let (abi, bytecode, _runtime_bytecode) = compiled
        .find("Incrementer")
        .expect("could not find contract")
        .into_parts_or_default();

    // Create a contract factory which will be used to deploy instances of the contract
    let factory = ContractFactory::new(abi, bytecode, Arc::new(client.clone()));

    // Deploy
    let contract = factory.deploy(U256::from(5))?.send().await?;
    let addr = contract.address();

    println!("Incrementer.sol has been deployed to {:?}", addr);

    Ok(addr)
}

// Generates a type-safe interface for the Incrementer smart contract
abigen!(
    Incrementer,
    "./Incrementer_ABI.json",
    event_derives(serde::Deserialize, serde::Serialize)
);

async fn read_number(client: &Client, contract_addr: &H160) -> Result<U256, Box<dyn std::error::Error>> {
    // Create contract instance
    let contract = Incrementer::new(contract_addr.clone(), Arc::new(client.clone()));

    // Call contract's number function
    let value = contract.number().call().await?;

    // Print out value
    println!("Incrementer's number is {}", value);

    Ok(value)
}

async fn increment_number(client: &Client, contract_addr: &H160) -> Result<(), Box<dyn std::error::Error>> {
    println!("Incrementing number...");

    // Create contract instance
    let contract = Incrementer::new(contract_addr.clone(), Arc::new(client.clone()));

    // Send contract transaction
    let tx = contract.increment(U256::from(5)).send().await?.await?;
    println!("Transaction Receipt: {}", serde_json::to_string(&tx)?);

    Ok(())
}

async fn reset(client: &Client, contract_addr: &H160) -> Result<(), Box<dyn std::error::Error>> {
    println!("Resetting number...");

    // Create contract instance
    let contract = Incrementer::new(contract_addr.clone(), Arc::new(client.clone()));

    // Send contract transaction
    let tx = contract.reset().send().await?.await?;
    println!("Transaction Receipt: {}", serde_json::to_string(&tx)?);

    Ok(())
}
```

{% endcode %}

</details>

To run the script, which will deploy the contract and return the current value stored in the `Incrementer` contract, you can enter the following command into your terminal:

```bash
cargo run
```

If successful, you'll see the deployed contract's address and initial value set, which should be `5`, displayed in the terminal.

{% code overflow="wrap" %}

```bash
cargo runCompiling ethers-examples v0.1.0 (/Users/phron/workspace/ethers-examples)Finished dev [unoptimized + debuginfo] target(s) in 1.09sRunning `/Users/phron/workspace/ethers-examples/target/debug/ethers-examples`Incrementer.sol has been deployed to 0xeb8a4d5c7cd56c65c9dbd25f793b50a2c917bb5dIncrementer's number is 5
```

{% endcode %}

#### Interact with Contract (Send Methods) <a href="#interact-with-contract" id="interact-with-contract"></a>

Send methods are the type of interaction that modify the contract's storage (change variables), meaning a transaction needs to be signed and sent. In this section, you'll create two functions: one to increment and one to reset the incrementer. This section will also require the `Incrementer_ABI.json` file initialized when reading from the smart contract.

Take the following steps to create the function to increment:

1. Ensure that the abigen macro is called for the `Incrementer_ABI.json` somewhere in the `main.rs` file (if it is already in the `main.rs` file, you do not have to have a second one)
2. Create a new asynchronous function named `increment_number` that takes a client object's reference and an address as input
3. Create a new instance of the `Incrementer` object generated by the abigen macro with the client and contract address values
4. Call the `increment` function in the new `Incrementer` object by including a `U256` object as input. In this instance, the value provided is `5`
5. Call the `read_number` function in `main`

{% code overflow="wrap" %}

```solidity
// ...

// 1. Generate a type-safe interface for the Incrementer smart contract
abigen!(
    Incrementer,
    "./Incrementer_ABI.json",
    event_derives(serde::Deserialize, serde::Serialize)
);

// 2. Define an asynchronous function that takes a client provider and address as input
async fn increment_number(client: &Client, contract_addr: &H160) -> Result<(), Box<dyn std::error::Error>> {
    println!("Incrementing number...");

    // 3. Create contract instance
    let contract = Incrementer::new(contract_addr.clone(), Arc::new(client.clone()));

    // 4. Send contract transaction
    let tx = contract.increment(U256::from(5)).send().await?.await?;
    println!("Transaction Receipt: {}", serde_json::to_string(&tx)?);

    Ok(())
}

// ...

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // ...

    // 5. Call increment_number function in main
    increment_number(&client, &addr).await?;

    Ok(())
}
```

{% endcode %}

<details>

<summary>View the complete script</summary>

{% code overflow="wrap" %}

```rust
use ethers::providers::{Provider, Http};
use ethers::{prelude::*};
use ethers_solc::Solc;
use std::{path::Path, sync::Arc};

type Client = SignerMiddleware<Provider<Http>, Wallet<k256::ecdsa::SigningKey>>;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let provider: Provider<Http> = Provider::<Http>::try_from("https://testnet.phron.ai")?; // Change to correct network
    // Do not include the private key in plain text in any production code. This is just for demonstration purposes
    // Do not include '0x' at the start of the private key
    let wallet: LocalWallet = "INSERT_PRIVATE_KEY"
        .parse::<LocalWallet>()?
        .with_chain_id(Chain::Phron);
    let client = SignerMiddleware::new(provider.clone(), wallet.clone());

    // Deploy contract and read initial incrementer value
    let addr = compile_deploy_contract(&client).await?;
    read_number(&client, &addr).await?;

    // Increment and read the incremented number
    increment_number(&client, &addr).await?;
    read_number(&client, &addr).await?;

    // Reset the incremented number and read it
    reset(&client, &addr).await?;
    read_number(&client, &addr).await?;

    Ok(())
}

// Need to install solc for this tutorial: https://github.com/crytic/solc-select
async fn compile_deploy_contract(client: &Client) -> Result<H160, Box<dyn std::error::Error>> {
    // Incrementer.sol is located in the root directory
    let source = Path::new(&env!("INSERT_CARGO_MANIFEST_DIR"));

    // Compile it
    let compiled = Solc::default()
        .compile_source(source)
        .expect("Could not compile contracts");

    // Get ABI & Bytecode for Incrementer.sol
    let (abi, bytecode, _runtime_bytecode) = compiled
        .find("Incrementer")
        .expect("could not find contract")
        .into_parts_or_default();

    // Create a contract factory which will be used to deploy instances of the contract
    let factory = ContractFactory::new(abi, bytecode, Arc::new(client.clone()));

    // Deploy
    let contract = factory.deploy(U256::from(5))?.send().await?;
    let addr = contract.address();

    println!("Incrementer.sol has been deployed to {:?}", addr);

    Ok(addr)
}

// Generates a type-safe interface for the Incrementer smart contract
abigen!(
    Incrementer,
    "./Incrementer_ABI.json",
    event_derives(serde::Deserialize, serde::Serialize)
);

async fn read_number(client: &Client, contract_addr: &H160) -> Result<U256, Box<dyn std::error::Error>> {
    // Create contract instance
    let contract = Incrementer::new(contract_addr.clone(), Arc::new(client.clone()));

    // Call contract's number function
    let value = contract.number().call().await?;

    // Print out value
    println!("Incrementer's number is {}", value);

    Ok(value)
}

async fn increment_number(client: &Client, contract_addr: &H160) -> Result<(), Box<dyn std::error::Error>> {
    println!("Incrementing number...");

    // Create contract instance
    let contract = Incrementer::new(contract_addr.clone(), Arc::new(client.clone()));

    // Send contract transaction
    let tx = contract.increment(U256::from(5)).send().await?.await?;
    println!("Transaction Receipt: {}", serde_json::to_string(&tx)?);

    Ok(())
}

async fn reset(client: &Client, contract_addr: &H160) -> Result<(), Box<dyn std::error::Error>> {
    println!("Resetting number...");

    // Create contract instance
    let contract = Incrementer::new(contract_addr.clone(), Arc::new(client.clone()));

    // Send contract transaction
    let tx = contract.reset().send().await?.await?;
    println!("Transaction Receipt: {}", serde_json::to_string(&tx)?);

    Ok(())
}
```

{% endcode %}

</details>

To run the script, you can enter the following command into your terminal:

```bash
cargo run
```

If successful, the transaction receipt will be displayed in the terminal. You can use the `read_number` function in the `main` function to make sure that value is changing as expected. If you're using the `read_number` function after incrementing, you'll also see the incremented number, which should be `10`.

{% code overflow="wrap" %}

```bash
cargo runCompiling ethers-examples v0.1.0 (/Users/phron/workspace/ethers-examples)Finished dev [unoptimized + debuginfo] target(s) in 1.09sRunning `/Users/phron/workspace/ethers-examples/target/debug/ethers-examples`Incrementer.sol has been deployed to 0xeb8a4d5c7cd56c65c9dbd25f793b50a2c917bb5dIncrementer's number is 5Incrementing number...Transaction Receipt: {"transactionHash":"0x6f5c204e74b96b6cf6057512ba142ad727718646d4ebb7abe8bbabada198dafb","transactionIndex":"0x0","blockHash":"0x635a8a234b30c6ee907198ddda3a1478ae52c6adbcc4a67353dd9597ee626950","blockNumber":"0x7ac238","from":"0x3b939fead1557c741ff06492fd0127bd287a421e","to":"0xeb8a4d5c7cd56c65c9dbd25f793b50a2c917bb5d","cumulativeGasUsed":"0x68a6","gasUsed":"0x68a6","contractAddress":null,"logs":[],"status":"0x1","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","type":"0x2","effectiveGasPrice":"0xba43b740"}Incrementer's number is 10
```

{% endcode %}

Next you can interact with the `reset` function:

1. Ensure that the abigen macro is called for the `Incrementer_ABI.json` somewhere in the `main.rs` file (if it is already in the `main.rs` file, you do not have to have a second one)
2. Create a new asynchronous function named `reset` that takes a client object's reference and an address as input
3. Create a new instance of the `Incrementer` object generated by the abigen macro with the client and contract address values
4. Call the `reset` function in the new `Incrementer` object
5. Call the `reset` function in `main`

{% code overflow="wrap" %}

```rust
// ...

// 1. Generate a type-safe interface for the Incrementer smart contract
abigen!(
    Incrementer,
    "./Incrementer_ABI.json",
    event_derives(serde::Deserialize, serde::Serialize)
);

// 2. Define an asynchronous function that takes a client provider and address as input
async fn reset(client: &Client, contract_addr: &H160) -> Result<(), Box<dyn std::error::Error>> {
    println!("Resetting number...");

    // 3. Create contract instance
    let contract = Incrementer::new(contract_addr.clone(), Arc::new(client.clone()));

    // 4. Send contract transaction
    let tx = contract.reset().send().await?.await?;
    println!("Transaction Receipt: {}", serde_json::to_string(&tx)?);

    Ok(())
}

// ...

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // ...

    // 5. Call reset function in main
    reset(&client, &addr).await?;

    Ok(())
}
```

{% endcode %}

If successful, the transaction receipt will be displayed in the terminal. You can use the `read_number` function in the `main` function to make sure that value is changing as expected. If you're using the `read_number` function after resetting the number, you should see `0` printed to the terminal.

{% code overflow="wrap" %}

```bash
cargo runCompiling ethers-examples v0.1.0 (/Users/phron/workspace/ethers-examples)Finished dev [unoptimized + debuginfo] target(s) in 1.09sRunning `/Users/phron/workspace/ethers-examples/target/debug/ethers-examples`Incrementer.sol has been deployed to 0xeb8a4d5c7cd56c65c9dbd25f793b50a2c917bb5dIncrementer's number is 5Incrementing number...Transaction Receipt: {"transactionHash":"0x6f5c204e74b96b6cf6057512ba142ad727718646d4ebb7abe8bbabada198dafb","transactionIndex":"0x0","blockHash":"0x635a8a234b30c6ee907198ddda3a1478ae52c6adbcc4a67353dd9597ee626950","blockNumber":"0x7ac238","from":"0x3b939fead1557c741ff06492fd0127bd287a421e","to":"0xeb8a4d5c7cd56c65c9dbd25f793b50a2c917bb5d","cumulativeGasUsed":"0x68a6","gasUsed":"0x68a6","contractAddress":null,"logs":[],"status":"0x1","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","type":"0x2","effectiveGasPrice":"0xba43b740"}Incrementer's number is 10Resetting number...Transaction Receipt: {"transactionHash":"0xf1010597c6ab3d3cfcd6e8e68bf2eddf4ed38eb93a3052591c88b675ed1e83a4","transactionIndex":"0x0","blockHash":"0x5d4c09abf104cbd88e80487c170d8709aae7475ca84c1f3396f3e35222fbe87f","blockNumber":"0x7ac23b","from":"0x3b939fead1557c741ff06492fd0127bd287a421e","to":"0xeb8a4d5c7cd56c65c9dbd25f793b50a2c917bb5d","cumulativeGasUsed":"0x53c4","gasUsed":"0x53c4","contractAddress":null,"logs":[],"status":"0x1","logsBloom":"0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","type":"0x2","effectiveGasPrice":"0xba43b740"}Incrementer's number is 0
```

{% endcode %}

<details>

<summary>View the complete script</summary>

{% code overflow="wrap" %}

```rust
use ethers::providers::{Provider, Http};
use ethers::{prelude::*};
use ethers_solc::Solc;
use std::{path::Path, sync::Arc};

type Client = SignerMiddleware<Provider<Http>, Wallet<k256::ecdsa::SigningKey>>;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let provider: Provider<Http> = Provider::<Http>::try_from("https://testnet.phron.ai")?; // Change to correct network
    // Do not include the private key in plain text in any production code. This is just for demonstration purposes
    // Do not include '0x' at the start of the private key
    let wallet: LocalWallet = "INSERT_PRIVATE_KEY"
        .parse::<LocalWallet>()?
        .with_chain_id(Chain::Phron);
    let client = SignerMiddleware::new(provider.clone(), wallet.clone());

    // Deploy contract and read initial incrementer value
    let addr = compile_deploy_contract(&client).await?;
    read_number(&client, &addr).await?;

    // Increment and read the incremented number
    increment_number(&client, &addr).await?;
    read_number(&client, &addr).await?;

    // Reset the incremented number and read it
    reset(&client, &addr).await?;
    read_number(&client, &addr).await?;

    Ok(())
}

// Need to install solc for this tutorial: https://github.com/crytic/solc-select
async fn compile_deploy_contract(client: &Client) -> Result<H160, Box<dyn std::error::Error>> {
    // Incrementer.sol is located in the root directory
    let source = Path::new(&env!("INSERT_CARGO_MANIFEST_DIR"));

    // Compile it
    let compiled = Solc::default()
        .compile_source(source)
        .expect("Could not compile contracts");

    // Get ABI & Bytecode for Incrementer.sol
    let (abi, bytecode, _runtime_bytecode) = compiled
        .find("Incrementer")
        .expect("could not find contract")
        .into_parts_or_default();

    // Create a contract factory which will be used to deploy instances of the contract
    let factory = ContractFactory::new(abi, bytecode, Arc::new(client.clone()));

    // Deploy
    let contract = factory.deploy(U256::from(5))?.send().await?;
    let addr = contract.address();

    println!("Incrementer.sol has been deployed to {:?}", addr);

    Ok(addr)
}

// Generates a type-safe interface for the Incrementer smart contract
abigen!(
    Incrementer,
    "./Incrementer_ABI.json",
    event_derives(serde::Deserialize, serde::Serialize)
);

async fn read_number(client: &Client, contract_addr: &H160) -> Result<U256, Box<dyn std::error::Error>> {
    // Create contract instance
    let contract = Incrementer::new(contract_addr.clone(), Arc::new(client.clone()));

    // Call contract's number function
    let value = contract.number().call().await?;

    // Print out value
    println!("Incrementer's number is {}", value);

    Ok(value)
}

async fn increment_number(client: &Client, contract_addr: &H160) -> Result<(), Box<dyn std::error::Error>> {
    println!("Incrementing number...");

    // Create contract instance
    let contract = Incrementer::new(contract_addr.clone(), Arc::new(client.clone()));

    // Send contract transaction
    let tx = contract.increment(U256::from(5)).send().await?.await?;
    println!("Transaction Receipt: {}", serde_json::to_string(&tx)?);

    Ok(())
}

async fn reset(client: &Client, contract_addr: &H160) -> Result<(), Box<dyn std::error::Error>> {
    println!("Resetting number...");

    // Create contract instance
    let contract = Incrementer::new(contract_addr.clone(), Arc::new(client.clone()));

    // Send contract transaction
    let tx = contract.reset().send().await?.await?;
    println!("Transaction Receipt: {}", serde_json::to_string(&tx)?);

    Ok(())
}
```

{% endcode %}

</details>

This tutorial is for educational purposes only. As such, any contracts or code created in this tutorial should not be used in production.The information presented herein has been provided by third parties and is made available solely for general information purposes. Phron does not endorse any project listed and described on the Phron Doc Website (<https://docs.Phron.ai/>). Phron does not warrant the accuracy, completeness or usefulness of this information. Any reliance you place on such information is strictly at your own risk. Phron disclaims all liability and responsibility arising from any reliance placed on this information by you or by anyone who may be informed of any of its contents. All statements and/or opinions expressed in these materials are solely the responsibility of the person or entity providing those materials and do not necessarily represent the opinion of Phron. The information should not be construed as professional or financial advice of any kind. Advice from a suitably qualified professional should always be sought in relation to any particular matter or circumstance. The information herein may link to or integrate with other websites operated or content provided by third parties, and such other websites may link to this website. Phron has no control over any such other websites or their content and will have no liability arising out of or related to such websites or their content. The existence of any such link does not constitute an endorsement of such websites, the content of the websites, or the operators of the websites. These links are being provided to you only as a convenience and you release and hold Phron harmless from any and all liability arising from your use of this information or the information provided by any third-party website or service.


# Web3.js

## Web3.js JavaScript Library <a href="#web3js-javascript-library" id="web3js-javascript-library"></a>

### Introduction <a href="#introduction" id="introduction"></a>

[Web3.js](https://web3js.readthedocs.io/) is a set of libraries that allow developers to interact with Ethereum nodes using HTTP, IPC, or WebSocket protocols with JavaScript. Phron has an Ethereum-like API available that is fully compatible with Ethereum-style JSON-RPC invocations. Therefore, developers can leverage this compatibility and use the Web3.js library to interact with a Phron node as if they were doing so on Ethereum.

In this guide, you'll learn how to use the Web3.js library to send a transaction and deploy a contract on Phron.

### Checking Prerequisites <a href="#checking-prerequisites" id="checking-prerequisites"></a>

For the examples in this guide, you will need to have the following:

* An account with funds. You can get DEV tokens for testing on Phron once every 24 hours from the Phron Faucet
* To test out the examples in this guide on Phron, you will need to have your own endpoint and API key, which you can get from one of the supported Endpoint Providers

> ### Note
>
> The examples in this guide assume you have a MacOS or Ubuntu 22.04-based environment and will need to be adapted accordingly for Windows.

### Installing Web3.js <a href="#install-web3js" id="install-web3js"></a>

To get started, you'll need to start a basic JavaScript project. First, create a directory to store all of the files you'll be creating throughout this guide, and initialize the project with the following command:

```bash
mkdir web3-examples && cd web3-examples && npm init --y
```

For this guide, you'll need to install the Web3.js library and the Solidity compiler. To install both NPM packages, you can run the following command:

```bash
npm install web3 solc@0.8.0
```

### Setup Web3.js with Phron <a href="#setup-web3-with-phron" id="setup-web3-with-phron"></a>

You can configure Web3.js to work with any of the Phron networks. To configure your project for Phron, you will need to have your own endpoint and API key, which you can get from one of the supported Endpoint Providers.

The simplest way to get started with each of the networks is as follows:

```javascript
const { Web3 } = require('web3');

// Create Web3 instance
const web3 = new Web3('INSERT_RPC_API_ENDPOINT'); // Insert your RPC URL here
```

Save this code snippet, as you'll need it for the scripts that are used in the following sections.

### Send a Transaction <a href="#send-a-transaction" id="send-a-transaction"></a>

During this section, you'll be creating a couple of scripts. The first one will be to check the balances of your accounts before trying to send a transaction. The second script will actually send the transaction.

You can also use the balance script to check the account balances after the transaction has been sent.

#### Check Balances Script <a href="#check-balances-script" id="check-balances-script"></a>

You'll only need one file to check the balances of both addresses before and after the transaction is sent. To get started, you can create a `balances.js` file by running:

```bash
touch balances.js
```

Next, you will create the script for this file and complete the following steps:

1. Set up the Web3 provider
2. Define the `addressFrom` and `addressTo` variables
3. Create the asynchronous `balances` function, which wraps the `web3.eth.getBalance` method
4. Use the `web3.eth.getBalance` function to fetch the balances for the `addressFrom` and `addressTo` addresses. You can also leverage the `web3.utils.fromWei` function to transform the balance into a more readable number in DEV
5. Lastly, run the `balances` function

```javascript
// 1. Add the Web3 provider logic
// {...}

// 2. Create address variables
const addressFrom = 'INSERT_FROM_ADDRESS';
const addressTo = 'INSERT_TO_ADDRESS';

// 3. Create balances function
const balances = async () => {
  // 4. Fetch balance info
  const balanceFrom = web3.utils.fromWei(
    await web3.eth.getBalance(addressFrom),
    'ether'
  );
  const balanceTo = web3.utils.fromWei(
    await web3.eth.getBalance(addressTo),
    'ether'
  );

  console.log(`The balance of ${addressFrom} is: ${balanceFrom} DEV`);
  console.log(`The balance of ${addressTo} is: ${balanceTo} DEV`);
};

// 5. Call balances function
balances();
```

<details>

<summary>View the complete script</summary>

```javascript
const { Web3 } = require('web3');

// 1. Add the Web3 provider logic here:
const providerRPC = {
  development: 'http://localhost:9944',
  phron: 'https://testnet.phron.ai',
};
const web3 = new Web3(providerRPC.phron); // Change to correct network

// 2. Create address variables
const addressFrom = 'INSERT_FROM_ADDRESS';
const addressTo = 'INSERT_TO_ADDRESS';

// 3. Create balances function
const balances = async () => {
  // 4. Fetch balance info
  const balanceFrom = web3.utils.fromWei(await web3.eth.getBalance(addressFrom), 'ether');
  const balanceTo = web3.utils.fromWei(await web3.eth.getBalance(addressTo), 'ether');

  console.log(`The balance of ${addressFrom} is: ${balanceFrom} DEV`);
  console.log(`The balance of ${addressTo} is: ${balanceTo} DEV`);
};

// 5. Call balances function
balances();
```

</details>

To run the script and fetch the account balances, you can run the following command:

```bash
node balances.js
```

If successful, the balances for the origin and receiving address will be displayed in your terminal in DEV.

#### Send Transaction Script <a href="#send-transaction-script" id="send-transaction-script"></a>

You'll only need one file to execute a transaction between accounts. For this example, you'll be transferring 1 DEV token from an origin address (from which you hold the private key) to another address. To get started, you can create a `transaction.js` file by running:

```bash
touch transaction.js
```

Next, you will create the script for this file and complete the following steps:

1. Set up the Web3 provider
2. Define the `accountFrom`, including the `privateKey`, and the `addressTo` variables. The private key is required to create a wallet instance. **Note: This is for example purposes only. Never store your private keys in a JavaScript file**
3. Create the asynchronous `send` function, which wraps the transaction object, and the sign and send transaction functions
4. Create and sign the transaction using the `web3.eth.accounts.signTransaction` function. Pass in the `gas`, `addressTo`, `value`, `gasPrice`, and `nonce` for the transaction along with the sender's `privateKey`
5. Send the signed transaction using the `web3.eth.sendSignedTransaction` method and pass in the raw transaction. Then use `await` to wait until the transaction is processed and the transaction receipt is returned
6. Lastly, run the `send` function

```javascript
// 1. Add the Web3 provider logic
// {...}

// 2. Create account variables
const accountFrom = {
  privateKey: 'INSERT_YOUR_PRIVATE_KEY',
  address: 'INSERT_PUBLIC_ADDRESS_OF_PK',
};
const addressTo = 'INSERT_TO_ADDRESS'; // Change addressTo

// 3. Create send function
const send = async () => {
  console.log(
    `Attempting to send transaction from ${accountFrom.address} to ${addressTo}`
  );

  // 4. Sign transaction with PK
  const createTransaction = await web3.eth.accounts.signTransaction(
    {
      gas: 21000,
      to: addressTo,
      value: web3.utils.toWei('1', 'ether'),
      gasPrice: await web3.eth.getGasPrice(),
      nonce: await web3.eth.getTransactionCount(accountFrom.address),
    },
    accountFrom.privateKey
  );

  // 5. Send transaction and wait for receipt
  const createReceipt = await web3.eth.sendSignedTransaction(
    createTransaction.rawTransaction
  );
  console.log(
    `Transaction successful with hash: ${createReceipt.transactionHash}`
  );
};

// 6. Call send function
send();
```

<details>

<summary>View the complete script</summary>

```javascript
const { Web3 } = require('web3');

// 1. Add the Web3 provider logic
const providerRPC = {
  development: 'http://localhost:9944',
  phron: 'https://testnet.phron.ai',
};
const web3 = new Web3(providerRPC.phron); // Change to correct network

// 2. Create account variables
const accountFrom = {
  privateKey: 'INSERT_YOUR_PRIVATE_KEY',
  address: 'INSERT_PUBLIC_ADDRESS_OF_PK',
};
const addressTo = 'INSERT_TO_ADDRESS';

// 3. Create send function
const send = async () => {
  console.log(
    `Attempting to send transaction from ${accountFrom.address} to ${addressTo}`
  );

  // 4. Sign transaction with PK
  const createTransaction = await web3.eth.accounts.signTransaction(
    {
      gas: 21000,
      to: addressTo,
      value: web3.utils.toWei('1', 'ether'),
      gasPrice: await web3.eth.getGasPrice(),
      nonce: await web3.eth.getTransactionCount(accountFrom.address),
    },
    accountFrom.privateKey
  );

  // 5. Send transaction and wait for receipt
  const createReceipt = await web3.eth.sendSignedTransaction(
    createTransaction.rawTransaction
  );
  console.log(
    `Transaction successful with hash: ${createReceipt.transactionHash}`
  );
};

// 6. Call send function
send();
```

</details>

To run the script, you can run the following command in your terminal:

```bash
node transaction.js
```

If the transaction was successful, in your terminal, you'll see the transaction hash has been printed out.

You can also use the `balances.js` script to check that the balances for the origin and receiving accounts have changed. The entire workflow would look like this:

{% code overflow="wrap" %}

```bash
node balances.jsThe balance of 0x3B939FeaD1557C741Ff06492FD0127bd287A421e is: 3603.67979115380310679 DEVThe balance of 0xe29A0699e079FeBEe94A02f35C31B026f90F6040 is: 0. DEVnode transaction.jsAttempting to send transaction from 0x3B939FeaD1557C741Ff06492FD0127bd287A421e to 0xe29A0699e079FeBEe94A02f35C31B026f90F6040Transaction successful with hash: 0xf1d628ed12c5f40e03e29aa2c23c8c09680ee595c60607c7363a81c0be8ef3cbnode balances.jsThe balance of 0x3B939FeaD1557C741Ff06492FD0127bd287A421e is: 3602.67978852880310679 DEVThe balance of 0xe29A0699e079FeBEe94A02f35C31B026f90F6040 is: 1 DEV
```

{% endcode %}

#### Common Errors When Sending Transactions <a href="#common-errors" id="common-errors"></a>

When sending a transaction with Web3.js, it is important that you have all of the required data for the transaction. You'll need to provide the `from` address or the `nonce` of the sender, the `gas` or `gasLimit`, and the `gasPrice`.

If you do not specify the `from` address or the `nonce` of the sender, you may receive the following error:

{% code overflow="wrap" %}

```bash
UnableToPopulateNonceError: Invalid value given "UnableToPopulateNonceError". Error: unable to populate nonce, no from address available.
```

{% endcode %}

To fix this, simply add either the `from` or `nonce` field to the transaction object.

If you do not specify the gas correctly, you may receive the following error:

{% code overflow="wrap" %}

```bash
MissingGasError: Invalid value given "gas: 0x5208, gasPrice: undefined, maxPriorityFeePerGas: undefined, maxFeePerGas: undefined". Error: "gas" is missing.
```

{% endcode %}

To resolve this error, you'll need to make sure that you've provided a `gasPrice` for the transaction. You can use `await web3.eth.getGasPrice()` to programmatically get this value.

### Deploy a Contract <a href="#deploy-a-contract" id="deploy-a-contract"></a>

The contract you'll be compiling and deploying in the next couple of sections is a simple incrementer contract, arbitrarily named `Incrementer.sol`. You can get started by creating a file for the contract:

```bash
touch Incrementer.sol
```

Next, you can add the Solidity code to the file:

```solidity
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

contract Incrementer {
    uint256 public number;

    constructor(uint256 _initialNumber) {
        number = _initialNumber;
    }

    function increment(uint256 _value) public {
        number = number + _value;
    }

    function reset() public {
        number = 0;
    }
}
```

The `constructor` function, which runs when the contract is deployed, sets the initial value of the number variable stored on-chain (the default is `0`). The `increment` function adds the `_value` provided to the current number, but a transaction needs to be sent, which modifies the stored data. Lastly, the `reset` function resets the stored value to zero.

> ### Note
>
> This contract is a simple example for illustration purposes only and does not handle values wrapping around.

#### Compile Contract Script <a href="#compile-contract-script" id="compile-contract-script"></a>

In this section, you'll create a script that uses the Solidity compiler to output the bytecode and interface (ABI) for the `Incrementer.sol` contract. To get started, you can create a `compile.js` file by running:

```bash
touch compile.js
```

Next, you will create the script for this file and complete the following steps:

1. Import the `fs` and `solc` packages
2. Using the `fs.readFileSync` function, you'll read and save the file contents of `Incrementer.sol` to `source`
3. Build the `input` object for the Solidity compiler by specifying the `language`, `sources`, and `settings` to be used
4. Using the `input` object, you can compile the contract using `solc.compile`
5. Extract the compiled contract file and export it to be used in the deployment script

```javascript
// 1. Import packages
const fs = require('fs');
const solc = require('solc');

// 2. Get path and load contract
const source = fs.readFileSync('Incrementer.sol', 'utf8');

// 3. Create input object
const input = {
   language: 'Solidity',
   sources: {
      'Incrementer.sol': {
         content: source,
      },
   },
   settings: {
      outputSelection: {
         '*': {
            '*': ['*'],
         },
      },
   },
};
// 4. Compile the contract
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
const contractFile = tempFile.contracts['Incrementer.sol']['Incrementer'];

// 5. Export contract data
module.exports = contractFile;
```

#### Deploy Contract Script <a href="#deploy-contract-script" id="deploy-contract-script"></a>

With the script for compiling the `Incrementer.sol` contract in place, you can then use the results to send a signed transaction that deploys it. To do so, you can create a file for the deployment script called `deploy.js`:

```bash
touch deploy.js
```

Next, you will create the script for this file and complete the following steps:

1. Import the contract file from `compile.js`
2. Set up the Web3 provider
3. Define the `accountFrom`, including the `privateKey`, and the `addressTo` variables. The private key is required to create a wallet instance. **Note: This is for example purposes only. Never store your private keys in a JavaScript file**
4. Save the `bytecode` and `abi` for the compiled contract
5. Create the asynchronous `deploy` function that will be used to deploy the contract
6. Create the contract instance using the `web3.eth.Contract` function
7. Create the constructor and pass in the `bytecode` and the initial value for the incrementer. For this example, you can set the initial value to `5`
8. Create and sign the transaction using the `web3.eth.accounts.signTransaction` function. Pass in the `data`, `gas`, `gasPrice`, and `nonce` for the transaction along with the sender's `privateKey`
9. Send the signed transaction using the `web3.eth.sendSignedTransaction` method and pass in the raw transaction. Then use `await` to wait until the transaction is processed and the transaction receipt is returned
10. Lastly, run the `deploy` function

```javascript
// 1. Import the contract file
const contractFile = require('./compile');

// 2. Add the Web3 provider logic
// {...}

// 3. Create address variables
const accountFrom = {
  privateKey: 'INSERT_YOUR_PRIVATE_KEY',
  address: 'INSERT_PUBLIC_ADDRESS_OF_PK',
};

// 4. Get the bytecode and API
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;

// 5. Create deploy function
const deploy = async () => {
  console.log(`Attempting to deploy from account ${accountFrom.address}`);

  // 6. Create contract instance
  const incrementer = new web3.eth.Contract(abi);

  // 7. Create constructor transaction
  const incrementerTx = incrementer.deploy({
    data: bytecode,
    arguments: [5],
  });

  // 8. Sign transaction with PK
  const createTransaction = await web3.eth.accounts.signTransaction(
    {
      data: incrementerTx.encodeABI(),
      gas: await incrementerTx.estimateGas(),
      gasPrice: await web3.eth.getGasPrice(),
      nonce: await web3.eth.getTransactionCount(accountFrom.address),
    },
    accountFrom.privateKey
  );

  // 9. Send transaction and wait for receipt
  const createReceipt = await web3.eth.sendSignedTransaction(
    createTransaction.rawTransaction
  );
  console.log(`Contract deployed at address: ${createReceipt.contractAddress}`);
};

// 10. Call deploy function
deploy();
```

<details>

<summary>View the complete script</summary>

```javascript
// 1. Import web3 and the contract file
const { Web3 } = require('web3');
const contractFile = require('./compile');

// 2. Add the Web3 provider logic
const providerRPC = {
  development: 'http://localhost:9944',
  phron: 'https://testnet.phron.ai',
};
const web3 = new Web3(providerRPC.phron); // Change to correct network

// 3. Create address variables
const accountFrom = {
  privateKey: 'INSERT_YOUR_PRIVATE_KEY',
  address: 'INSERT_PUBLIC_ADDRESS_OF_PK',
};

// 4. Get the bytecode and API
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;

// 5. Create deploy function
const deploy = async () => {
  console.log(`Attempting to deploy from account ${accountFrom.address}`);

  // 6. Create contract instance
  const incrementer = new web3.eth.Contract(abi);

  // 7. Create constructor transaction
  const incrementerTx = incrementer.deploy({
    data: bytecode,
    arguments: [5],
  });

  // 8. Sign transaction with PK
  const createTransaction = await web3.eth.accounts.signTransaction(
    {
      data: incrementerTx.encodeABI(),
      gas: await incrementerTx.estimateGas(),
      gasPrice: await web3.eth.getGasPrice(),
      nonce: await web3.eth.getTransactionCount(accountFrom.address),
    },
    accountFrom.privateKey
  );

  // 9. Send transaction and wait for receipt
  const createReceipt = await web3.eth.sendSignedTransaction(
    createTransaction.rawTransaction
  );
  console.log(`Contract deployed at address: ${createReceipt.contractAddress}`);
};

// 10. Call deploy function
deploy();
```

</details>

To run the script, you can enter the following command into your terminal:

```bash
node deploy.js
```

If successful, the contract's address will be displayed in the terminal.

{% code overflow="wrap" %}

```bash
node deploy.jsAttempting to deploy from account 0x3B939FeaD1557C741Ff06492FD0127bd287A421eContract deployed at address: 0x6dcb33a7f6235e74fd553b50c96f900707142892
```

{% endcode %}

#### Read Contract Data (Call Methods) <a href="#read-contract-data" id="read-contract-data"></a>

Call methods are the type of interaction that doesn't modify the contract's storage (change variables), meaning no transaction needs to be sent. They simply read various storage variables of the deployed contract.

To get started, you can create a file and name it `get.js`:

```bash
touch get.js
```

Then you can take the following steps to create the script:

1. Import the `abi` from the `compile.js` file
2. Set up the Web3 provider
3. Create the `contractAddress` variable using the address of the deployed contract
4. Create an instance of the contract using the `web3.eth.Contract` function and passing in the `abi` and `contractAddress`
5. Create the asynchronous `get` function
6. Use the contract instance to call one of the contract's methods and pass in any inputs if necessary. For this example, you will call the `number` method which doesn't require any inputs. You can use `await`, which will return the value requested once the request promise resolves
7. Lastly, call the `get` function

```javascript
// 1. Import the contract ABI
const { abi } = require('./compile');

// 2. Add the Web3 provider logic
// {...}

// 3. Create address variables
const contractAddress = 'INSERT_CONTRACT_ADDRESS';

// 4. Create contract instance
const incrementer = new web3.eth.Contract(abi, contractAddress);

// 5. Create get function
const get = async () => {
  console.log(`Making a call to contract at address: ${contractAddress}`);

  // 6. Call contract
  const data = await incrementer.methods.number().call();

  console.log(`The current number stored is: ${data}`);
};

// 7. Call get function
get();
```

<details>

<summary>View the complete script</summary>

```javascript
// 1. Import Web3js and the contract ABI
const { Web3 } = require('web3');
const { abi } = require('./compile');

// 2. Add the Web3 provider logic
const providerRPC = {
  development: 'http://localhost:9944',
  phron: 'https://testnet.phron.ai',
};
const web3 = new Web3(providerRPC.phron); // Change to correct network

// 3. Create address variables
const contractAddress = 'INSERT_CONTRACT_ADDRESS';

// 4. Create contract instance
const incrementer = new web3.eth.Contract(abi, contractAddress);

// 5. Create get function
const get = async () => {
  console.log(`Making a call to contract at address: ${contractAddress}`);

  // 6. Call contract
  const data = await incrementer.methods.number().call();

  console.log(`The current number stored is: ${data}`);
};

// 7. Call get function
get();
```

</details>

To run the script, you can enter the following command in your terminal:

```bash
node get.js
```

If successful, the value will be displayed in the terminal.

#### Interact with Contract (Send Methods) <a href="#interact-with-contract" id="interact-with-contract"></a>

Send methods are the type of interaction that modifies the contract's storage (change variables), meaning a transaction needs to be signed and sent. In this section, you'll create two scripts: one to increment and one to reset the incrementer. To get started, you can create a file for each script and name them `increment.js` and `reset.js`:

```bash
touch increment.js reset.js
```

Open the `increment.js` file and take the following steps to create the script:

1. Import the `abi` from the `compile.js` file
2. Set up the Web3 provider
3. Define the `privateKey` for the origin account, the `contractAddress` of the deployed contract, and the `_value` to increment by. The private key is required to create a wallet instance. **Note: This is for example purposes only. Never store your private keys in a JavaScript file**
4. Create an instance of the contract using the `web3.eth.Contract` function and passing in the `abi` and `contractAddress`
5. Use the contract instance to build the increment transaction using the `methods.increment` function and passing in the `_value` as an input
6. Create the asynchronous `increment` function
7. Use the contract instance and the increment transaction you previously created to sign the transaction with the sender's private key. You'll use the `web3.eth.accounts.signTransaction` function and specify the `to` address, `data`, `gas`, `gasPrice`, and `nonce` for the transaction
8. Send the signed transaction using the `web3.eth.sendSignedTransaction` method and pass in the raw transaction. Then use `await` to wait until the transaction is processed and the transaction receipt is returned
9. Lastly, call the `increment` function

```javascript
// 1. Import the contract ABI
const { abi } = require('./compile');

// 2. Add the Web3 provider logic
// {...}

// 3. Create variables
const accountFrom = {
  privateKey: 'INSERT_YOUR_PRIVATE_KEY',
  address: 'INSERT_PUBLIC_ADDRESS_OF_PK',
};
const contractAddress = 'INSERT_CONTRACT_ADDRESS';
const _value = 3;

// 4. Create contract instance
const incrementer = new web3.eth.Contract(abi, contractAddress);

// 5. Build the increment transaction
const incrementTx = incrementer.methods.increment(_value);

// 6. Create increment function
const increment = async () => {
  console.log(
    `Calling the increment by ${_value} function in contract at address: ${contractAddress}`
  );

  // 7. Sign transaction with PK
  const createTransaction = await web3.eth.accounts.signTransaction(
    {
      to: contractAddress,
      data: incrementTx.encodeABI(),
      gas: await incrementTx.estimateGas(),
      gasPrice: await web3.eth.getGasPrice(),
      nonce: await web3.eth.getTransactionCount(accountFrom.address),
    },
    accountFrom.privateKey
  );

  // 8. Send transaction and wait for receipt
  const createReceipt = await web3.eth.sendSignedTransaction(
    createTransaction.rawTransaction
  );
  console.log(`Tx successful with hash: ${createReceipt.transactionHash}`);
};

// 9. Call increment function
increment();
```

<details>

<summary>View the complete script</summary>

```javascript
// 1. Import Web3js and the contract ABI
const { Web3 } = require('web3');
const { abi } = require('./compile');

// 2. Add the Web3 provider logic
const providerRPC = {
  development: 'http://localhost:9944',
  phron: 'https://testnet.phron.ai',
};
const web3 = new Web3(providerRPC.phron); // Change to correct network

// 3. Create variables
const accountFrom = {
  privateKey: 'INSERT_YOUR_PRIVATE_KEY',
  address: 'INSERT_PUBLIC_ADDRESS_OF_PK',
};
const contractAddress = 'INSERT_CONTRACT_ADDRESS';
const _value = 3;

// 4. Create contract instance
const incrementer = new web3.eth.Contract(abi, contractAddress);

// 5. Build increment transaction
const incrementTx = incrementer.methods.increment(_value);

// 6. Create increment function
const increment = async () => {
  console.log(
    `Calling the increment by ${_value} function in contract at address: ${contractAddress}`
  );

  // 7. Sign transaction with PK
  const createTransaction = await web3.eth.accounts.signTransaction(
    {
      to: contractAddress,
      data: incrementTx.encodeABI(),
      gas: await incrementTx.estimateGas(),
      gasPrice: await web3.eth.getGasPrice(),
      nonce: await web3.eth.getTransactionCount(accountFrom.address),
    },
    accountFrom.privateKey
  );

  // 8. Send transaction and wait for receipt
  const createReceipt = await web3.eth.sendSignedTransaction(
    createTransaction.rawTransaction
  );
  console.log(`Tx successful with hash: ${createReceipt.transactionHash}`);
};

// 9. Call increment function
increment();
```

</details>

To run the script, you can enter the following command in your terminal:

```bash
node increment.js
```

If successful, the transaction hash will be displayed in the terminal. You can use the `get.js` script alongside the `increment.js` script to make sure that value is changing as expected:

{% code overflow="wrap" %}

```bash
node get.jsMaking a call to contract at address: 0x6dcb33a7f6235e74fd553b50c96f900707142892The current number stored is: 5node increment.jsCalling the increment by 3 function in contract at address: 0x6dcb33a7f6235e74fd553b50c96f900707142892Tx successful with hash: 0xb03d1426376e7efc49d8b6c69aaf91e548578db7fd4a9ba575dbd8030821f6a3node get.jsMaking a call to contract at address: 0x6dcb33a7f6235e74fd553b50c96f900707142892The current number stored is: 8
```

{% endcode %}

Next, you can open the `reset.js` file and take the following steps to create the script:

1. Import the `abi` from the `compile.js` file
2. Set up the Web3 provider
3. Define the `privateKey` for the origin account and the `contractAddress` of the deployed contract. The private key is required to create a wallet instance. **Note: This is for example purposes only. Never store your private keys in a JavaScript file**
4. Create an instance of the contract using the `web3.eth.Contract` function and passing in the `abi` and `contractAddress`
5. Use the contract instance to build the reset transaction using the `methods.reset` function
6. Create the asynchronous `reset` function
7. Use the contract instance and the reset transaction you previously created to sign the transaction with the sender's private key. You'll use the `web3.eth.accounts.signTransaction` function and specify the `to` address, `data`, `gas`, `gasPrice`, and `nonce` for the transaction
8. Send the signed transaction using the `web3.eth.sendSignedTransaction` method and pass in the raw transaction. Then use `await` to wait until the transaction is processed and the transaction receipt is returned
9. Lastly, call the `reset` function

```javascript
// 1. Import the contract ABI
const { abi } = require('./compile');

// 2. Add the Web3 provider logic
// {...}

// 3. Create variables
const accountFrom = {
  privateKey: 'INSERT_YOUR_PRIVATE_KEY',
  address: 'INSERT_PUBLIC_ADDRESS_OF_PK',
};
const contractAddress = 'INSERT_CONTRACT_ADDRESS';

// 4. Create a contract instance
const incrementer = new web3.eth.Contract(abi, contractAddress);

// 5. Build reset transaction
const resetTx = incrementer.methods.reset();

// 6. Create reset function
const reset = async () => {
  console.log(
    `Calling the reset function in contract at address: ${contractAddress}`
  );

  // 7. Sign transaction with PK
  const createTransaction = await web3.eth.accounts.signTransaction(
    {
      to: contractAddress,
      data: resetTx.encodeABI(),
      gas: await resetTx.estimateGas(),
      gasPrice: await web3.eth.getGasPrice(),
      nonce: await web3.eth.getTransactionCount(accountFrom.address),
    },
    accountFrom.privateKey
  );

  // 8. Send transaction and wait for receipt
  const createReceipt = await web3.eth.sendSignedTransaction(
    createTransaction.rawTransaction
  );
  console.log(`Tx successful with hash: ${createReceipt.transactionHash}`);
};

// 9. Call reset function
reset();
```

<details>

<summary>View the complete script</summary>

```javascript
// 1. Import Web3js and the contract ABI
const { Web3 } = require('web3');
const { abi } = require('./compile');

// 2. Add the Web3 provider logic
const providerRPC = {
  development: 'http://localhost:9944',
  phron: 'https://testnet.phron.ai',
};
const web3 = new Web3(providerRPC.phron); // Change to correct network

// 3. Create variables
const accountFrom = {
  privateKey: 'INSERT_YOUR_PRIVATE_KEY',
  address: 'INSERT_PUBLIC_ADDRESS_OF_PK',
};
const contractAddress = 'INSERT_CONTRACT_ADDRESS';

// 4. Create contract instance
const incrementer = new web3.eth.Contract(abi, contractAddress);

// 5. Build reset transaction
const resetTx = incrementer.methods.reset();

// 6. Create reset function
const reset = async () => {
  console.log(`Calling the reset function in contract at address: ${contractAddress}`);

  // 7. Sign transaction with PK
  const createTransaction = await web3.eth.accounts.signTransaction(
    {
      to: contractAddress,
      data: resetTx.encodeABI(),
      gas: await resetTx.estimateGas(),
      gasPrice: await web3.eth.getGasPrice(),
      nonce: await web3.eth.getTransactionCount(accountFrom.address),
    },
    accountFrom.privateKey
  );

  // 8. Send transaction and wait for receipt
  const createReceipt = await web3.eth.sendSignedTransaction(createTransaction.rawTransaction);
  console.log(`Tx successful with hash: ${createReceipt.transactionHash}`);
};

// 9. Call reset function
reset();
```

</details>

To run the script, you can enter the following command in your terminal:

```bash
node reset.js
```

If successful, the transaction hash will be displayed in the terminal. You can use the `get.js` script alongside the `reset.js` script to make sure that value is changing as expected:

{% code overflow="wrap" %}

```bash
node get.jsMaking a call to contract at address: 0x6dcb33a7f6235e74fd553b50c96f900707142892The current number stored is: 8node reset.jsCalling the reset function in contract at address: 0x6dcb33a7f6235e74fd553b50c96f900707142892Tx successful with hash: 0x557e908ca4da05d5af50983dbc116fbf8049bb2e86b9ec1e9f7d3f516b8a4c55node get.jsMaking a call to contract at address: 0x6dcb33a7f6235e74fd553b50c96f900707142892The current number stored is: 0
```

{% endcode %}

This tutorial is for educational purposes only. As such, any contracts or code created in this tutorial should not be used in production.The information presented herein has been provided by third parties and is made available solely for general information purposes. Phron does not endorse any project listed and described on the Phron Doc Website (<https://docs.Phron.ai/>). Phron does not warrant the accuracy, completeness or usefulness of this information. Any reliance you place on such information is strictly at your own risk. Phron disclaims all liability and responsibility arising from any reliance placed on this information by you or by anyone who may be informed of any of its contents. All statements and/or opinions expressed in these materials are solely the responsibility of the person or entity providing those materials and do not necessarily represent the opinion of Phron. The information should not be construed as professional or financial advice of any kind. Advice from a suitably qualified professional should always be sought in relation to any particular matter or circumstance. The information herein may link to or integrate with other websites operated or content provided by third parties, and such other websites may link to this website. Phron has no control over any such other websites or their content and will have no liability arising out of or related to such websites or their content. The existence of any such link does not constitute an endorsement of such websites, the content of the websites, or the operators of the websites. These links are being provided to you only as a convenience and you release and hold Phron harmless from any and all liability arising from your use of this information or the information provided by any third-party website or service.


# Web3.py

## Web3.py Python Library <a href="#web3py-python-library" id="web3py-python-library"></a>

### Introduction <a href="#introduction" id="introduction"></a>

[Web3.py](https://web3py.readthedocs.io/) is a set of libraries that allow developers to interact with Ethereum nodes using HTTP, IPC, or WebSocket protocols with Python. Phron has an Ethereum-like API available that is fully compatible with Ethereum-style JSON-RPC invocations. Therefore, developers can leverage this compatibility and use the Web3.py library to interact with a Phron python3 as if they were doing so on Ethereum.

In this guide, you'll learn how to use the Web3.py library to send a transaction and deploy a contract on Phron.

### Checking Prerequisites <a href="#checking-prerequisites" id="checking-prerequisites"></a>

For the examples in this guide, you will need to have the following:

* An account with funds. You can get DEV tokens for testing on Phron once every 24 hours from the Phron Faucet
* To test out the examples in this guide on Phron, you will need to have your own endpoint and API key, which you can get from one of the supported Endpoint Providers

> ### Note
>
> The examples in this guide assume you have a MacOS or Ubuntu 22.04-based environment and will need to be adapted accordingly for Windows.

### Create a Python Project <a href="#create-a-python-project" id="create-a-python-project"></a>

To get started, you can create a directory to store all of the files you'll be creating throughout this guide:

```bash
mkdir web3-examples && cd web3-examples
```

For this guide, you'll need to install the Web3.py library and the Solidity compiler. To install both packages, you can run the following command:

```bash
pip3 install web3 py-solc-x solc-select
```

### Setup Web3.py with Phron <a href="#setup-web3-with-phron" id="setup-web3-with-phron"></a>

Throughout this guide, you'll be creating a bunch of scripts that provide different functionalities, such as sending a transaction, deploying a contract, and interacting with a deployed contract. In most of these scripts, you'll need to create a [Web3.py provider](https://web3py.readthedocs.io/en/stable/providers.html) to interact with the network.

To configure your project for Phron, you will need to have your own endpoint and API key, which you can get from one of the supported Endpoint Providers.

To create a provider, you can take the following steps:

1. Import the `web3` library
2. Create the `web3` provider using the `Web3(Web3.HTTPProvider())` method and providing the endpoint URL

```python
# 1. Import web3.py
from web3 import Web3

# 2. Create web3.py provider
web3 = Web3(Web3.HTTPProvider("INSERT_RPC_API_ENDPOINT")) # Insert your RPC URL here
```

Save this code snippet, as you'll need it for the scripts that are used in the following sections.

### Send a Transaction <a href="#send-a-transaction" id="send-a-transaction"></a>

During this section, you'll be creating a couple of scripts. The first one will be to check the balances of your accounts before trying to send a transaction. The second script will actually send the transaction.

You can also use the balance script to check the account balances after the transaction has been sent.

#### Check Balances Script <a href="#check-balances-script" id="check-balances-script"></a>

You'll only need one file to check the balances of both addresses before and after the transaction is sent. To get started, you can create a `balances.py` file by running:

```bash
touch balances.py
```

Next, you will create the script for this file and complete the following steps:

1. Set up the Web3 provider
2. Define the `address_from` and `address_to` variables
3. Get the balance for the accounts using the `web3.eth.get_balance` function and format the results using the `web3.from_wei`

```python
from web3 import Web3

# 1. Add the Web3 provider logic here:
provider_rpc = {
    "development": "http://localhost:9944",
    "phron": "https://testnet.phron.ai",
}
web3 = Web3(Web3.HTTPProvider(provider_rpc["phron"]))  # Change to correct network

# 2. Create address variables
address_from = 'INSERT_FROM_ADDRESS'
address_to = 'INSERT_TO_ADDRESS'

# 3. Fetch balance data
balance_from = web3.from_wei(
    web3.eth.get_balance(Web3.to_checksum_address(address_from)), "ether"
)
balance_to = web3.from_wei(
    web3.eth.get_balance(Web3.to_checksum_address(address_to)), "ether"
)

print(f"The balance of { address_from } is: { balance_from } DEV")
print(f"The balance of { address_to } is: { balance_to } DEV")
```

To run the script and fetch the account balances, you can run the following command:

```bash
python3 balances.py
```

If successful, the balances for the origin and receiving address will be displayed in your terminal in ETH.

#### Send Transaction Script <a href="#send-transaction-script" id="send-transaction-script"></a>

You'll only need one file for executing a transaction between accounts. For this example, you'll be transferring 1 DEV token from an origin address (from which you hold the private key) to another address. To get started, you can create a `transaction.py` file by running:

```bash
touch transaction.py
```

Next, you will create the script for this file and complete the following steps:

1. Add imports, including Web3.py and the `rpc_gas_price_strategy`, which will be used in the following steps to get the gas price used for the transaction
2. Set up the Web3 provider
3. Define the `account_from`, including the `private_key`, and the `address_to` variables. The private key is required to sign the transaction. **Note: This is for example purposes only. Never store your private keys in a Python file**
4. Use the [Web3.py Gas Price API](https://web3py.readthedocs.io/en/stable/gas_price.html) to set a gas price strategy. For this example, you'll use the imported `rpc_gas_price_strategy`
5. Create and sign the transaction using the `web3.eth.account.sign_transaction` function. Pass in the `nonce` `gas`, `gasPrice`, `to`, and `value` for the transaction along with the sender's `private_key`. To get the `nonce` you can use the `web3.eth.get_transaction_count` function and pass in the sender's address. To predetermine the `gasPrice` you'll use the `web3.eth.generate_gas_price` function. For the `value`, you can format the amount to send from an easily readable format to Wei using the `web3.to_wei` function
6. Using the signed transaction, you can then send it using the `web3.eth.send_raw_transaction` function and wait for the transaction receipt by using the `web3.eth.wait_for_transaction_receipt` function

```python
# 1. Add imports
from web3.gas_strategies.rpc import rpc_gas_price_strategy
from web3 import Web3

# 2. Add the Web3 provider logic here:
provider_rpc = {
    "development": "http://localhost:9944",
    "phron": "https://testnet.phron.ai",
}
web3 = Web3(Web3.HTTPProvider(provider_rpc["phron"]))  # Change to correct network

# 3. Create address variables
account_from = {
    'private_key': 'INSERT_YOUR_PRIVATE_KEY',
    'address': 'INSERT_PUBLIC_ADDRESS_OF_PK',
}
address_to = 'INSERT_TO_ADDRESS'

print(
    f'Attempting to send transaction from { account_from["address"] } to { address_to }'
)

# 4. Set the gas price strategy
web3.eth.set_gas_price_strategy(rpc_gas_price_strategy)

# 5. Sign tx with PK
tx_create = web3.eth.account.sign_transaction(
    {
        "nonce": web3.eth.get_transaction_count(
            Web3.to_checksum_address(account_from["address"])
        ),
        "gasPrice": web3.eth.generate_gas_price(),
        "gas": 21000,
        "to": Web3.to_checksum_address(address_to),
        "value": web3.to_wei("1", "ether"),
    },
    account_from["private_key"],
)

# 6. Send tx and wait for receipt
tx_hash = web3.eth.send_raw_transaction(tx_create.rawTransaction)
tx_receipt = web3.eth.wait_for_transaction_receipt(tx_hash)

print(f"Transaction successful with hash: { tx_receipt.transactionHash.hex() }")
```

To run the script, you can run the following command in your terminal:

```bash
python3 transaction.py
```

If the transaction was succesful, in your terminal you'll see the transaction hash has been printed out.

You can also use the `balances.py` script to check that the balances for the origin and receiving accounts have changed. The entire workflow would look like this:

{% code overflow="wrap" fullWidth="false" %}

```bash
python3 balances.pyThe balance of 0x3B939FeaD1557C741Ff06492FD0127bd287A421e is: 3563.79 DEVThe balance of 0x9Bf5Ae10540a1ab9B363bEA02A9406E6b2efA9af is: 0 DEVpython3 transaction.pyAttempting to send transaction from 0x3B939FeaD1557C741Ff06492FD0127bd287A421e to 0x9Bf5Ae10540a1ab9B363bEA02A9406E6b2efA9afTransaction successful with hash: 0xac70452510657ed43c27510578d3ce4b3b880d4cca1a24ade1497c6e0ee7f5d6python3 balances.pyThe balance of 0x3B939FeaD1557C741Ff06492FD0127bd287A421e is: 3562.79 DEVThe balance of 0x9Bf5Ae10540a1ab9B363bEA02A9406E6b2efA9af is: 1 DEV
```

{% endcode %}

### Deploy a Contract <a href="#deploy-a-contract" id="deploy-a-contract"></a>

The contract you'll be compiling and deploying in the next couple of sections is a simple incrementer contract, arbitrarily named `Incrementer.sol`. You can get started by creating a file for the contract:

```bash
touch Incrementer.sol
```

Next, you can add the Solidity code to the file:

```solidity
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

contract Incrementer {
    uint256 public number;

    constructor(uint256 _initialNumber) {
        number = _initialNumber;
    }

    function increment(uint256 _value) public {
        number = number + _value;
    }

    function reset() public {
        number = 0;
    }
}
```

The `constructor` function, which runs when the contract is deployed, sets the initial value of the number variable stored on-chain (the default is `0`). The `increment` function adds the `_value` provided to the current number, but a transaction needs to be sent, which modifies the stored data. Lastly, the `reset` function resets the stored value to zero.

> ### Note
>
> This contract is a simple example for illustration purposes only and does not handle values wrapping around.

#### Compile Contract Script <a href="#compile-contract-script" id="compile-contract-script"></a>

In this section, you'll create a script that uses the Solidity compiler to output the bytecode and interface (ABI) for the `Incrementer.sol` contract. To get started, you can create a `compile.py` file by running:

```bash
touch compile.py
```

Next, you will create the script for this file and complete the following steps:

1. Import the `solcx` package
2. **Optional** - If you haven't already installed the Solidity compiler, you can do so with by using the `solcx.install_solc` function
3. Compile the `Incrementer.sol` function using the `solcx.compile_files` function
4. Export the contract's ABI and bytecode

```solidity
# 1. Import solcx
import solcx

# 2. If you haven't already installed the Solidity compiler, uncomment the following line
# solcx.install_solc()

# 3. Compile contract
temp_file = solcx.compile_files(
    'Incrementer.sol',
    output_values=['abi', 'bin'],
    # solc_version='0.8.19'
)

# 4. Export contract data
abi = temp_file['Incrementer.sol:Incrementer']['abi']
bytecode = temp_file['Incrementer.sol:Incrementer']['bin']
```

> ### Note
>
> If you see an error stating that `Solc is not installed`, uncomment step 2 described in the code snippet.

#### Deploy Contract Script <a href="#deploy-contract-script" id="deploy-contract-script"></a>

With the script for compiling the `Incrementer.sol` contract in place, you can then use the results to send a signed transaction that deploys it. To do so, you can create a file for the deployment script called `deploy.py`:

```bash
touch deploy.py
```

Next, you will create the script for this file and complete the following steps:

1. Add imports, including Web3.py and the ABI and bytecode of the `Incrementer.sol` contract
2. Set up the Web3 provider
3. Define the `account_from`, including the `private_key`. The private key is required to sign the transaction. **Note: This is for example purposes only. Never store your private keys in a Python file**
4. Create a contract instance using the `web3.eth.contract` function and passing in the ABI and bytecode of the contract
5. Build a constructor transaction using the contract instance and passing in the value to increment by. For this example, you can use `5`. You'll then use the `build_transaction` function to pass in the transaction information including the `from` address and the `nonce` for the sender. To get the `nonce` you can use the `web3.eth.get_transaction_count` function
6. Sign the transaction using the `web3.eth.account.sign_transaction` function and pass in the constructor transaction and the `private_key` of the sender
7. Using the signed transaction, you can then send it using the `web3.eth.send_raw_transaction` function and wait for the transaction receipt by using the `web3.eth.wait_for_transaction_receipt` function

```solidity
# 1. Add imports
from compile import abi, bytecode
from web3 import Web3

# 2. Add the Web3 provider logic here:
provider_rpc = {
    "development": "http://localhost:9944",
    "phron": "https://testnet.phron.ai",
}
web3 = Web3(Web3.HTTPProvider(provider_rpc["phron"]))  # Change to correct network

# 3. Create address variable
account_from = {
    'private_key': 'INSERT_YOUR_PRIVATE_KEY',
    'address': 'INSERT_PUBLIC_ADDRESS_OF_PK',
}

print(f'Attempting to deploy from account: { account_from["address"] }')

# 4. Create contract instance
Incrementer = web3.eth.contract(abi=abi, bytecode=bytecode)

# 5. Build constructor tx
construct_txn = Incrementer.constructor(5).build_transaction(
    {
        "from": Web3.to_checksum_address(account_from["address"]),
        "nonce": web3.eth.get_transaction_count(
            Web3.to_checksum_address(account_from["address"])
        ),
    }
)

# 6. Sign tx with PK
tx_create = web3.eth.account.sign_transaction(
    construct_txn, account_from["private_key"]
)

# 7. Send tx and wait for receipt
tx_hash = web3.eth.send_raw_transaction(tx_create.rawTransaction)
tx_receipt = web3.eth.wait_for_transaction_receipt(tx_hash)

print(f"Contract deployed at address: { tx_receipt.contractAddress }")
```

To run the script, you can enter the following command into your terminal:

```
python3 deploy.py
```

If successful, the contract's address will be displayed in the terminal.

{% code overflow="wrap" %}

```bash
python3 deploy.pyAttempting to deploy from account: 0x3B939FeaD1557C741Ff06492FD0127bd287A421eContract deployed at address: 0xFef3cFb8eE1FE727b3848E551ae5DC8903237B08
```

{% endcode %}

#### Read Contract Data (Call Methods) <a href="#read-contract-data" id="read-contract-data"></a>

Call methods are the type of interaction that don't modify the contract's storage (change variables), meaning no transaction needs to be sent. They simply read various storage variables of the deployed contract.

To get started, you can create a file and name it `get.py`:

```bash
touch get.py
```

Then you can take the following steps to create the script:

1. Add imports, including Web3.py and the ABI of the `Incrementer.sol` contract
2. Set up the Web3 provider
3. Define the `contract_address` of the deployed contract
4. Create a contract instance using the `web3.eth.contract` function and passing in the ABI and address of the deployed contract
5. Using the contract instance, you can then call the `number` function

```solidity
# 1. Import the ABI
from compile import abi
from web3 import Web3

# 2. Add the Web3 provider logic here:
provider_rpc = {
    "development": "http://localhost:9944",
    "phron": "https://testnet.phron.ai",
}
web3 = Web3(Web3.HTTPProvider(provider_rpc["phron"]))  # Change to correct network

# 3. Create address variable
contract_address = 'INSERT_CONTRACT_ADDRESS'

print(f"Making a call to contract at address: { contract_address }")

# 4. Create contract instance
Incrementer = web3.eth.contract(address=contract_address, abi=abi)

# 5. Call Contract
number = Incrementer.functions.number().call()
print(f"The current number stored is: { number } ")
```

To run the script, you can enter the following command in your terminal:

```bash
python3 get.py
```

If successful, the value will be displayed in the terminal.

#### Interact with Contract (Send Methods) <a href="#interact-with-contract" id="interact-with-contract"></a>

Send methods are the type of interaction that modify the contract's storage (change variables), meaning a transaction needs to be signed and sent. In this section, you'll create two scripts: one to increment and one to reset the incrementer. To get started, you can create a file for each script and name them `increment.py` and `reset.py`:

```bash
touch increment.py reset.py
```

Open the `increment.py` file and take the following steps to create the script:

1. Add imports, including Web3.py and the ABI of the `Incrementer.sol` contract
2. Set up the Web3 provider
3. Define the `account_from`, including the `private_key`, the `contract_address` of the deployed contract, and the `value` to increment by. The private key is required to sign the transaction. **Note: This is for example purposes only. Never store your private keys in a Python file**
4. Create a contract instance using the `web3.eth.contract` function and passing in the ABI and address of the deployed contract
5. Build the increment transaction using the contract instance and passing in the value to increment by. You'll then use the `build_transaction` function to pass in the transaction information including the `from` address and the `nonce` for the sender. To get the `nonce` you can use the `web3.eth.get_transaction_count` function
6. Sign the transaction using the `web3.eth.account.sign_transaction` function and pass in the increment transaction and the `private_key` of the sender
7. Using the signed transaction, you can then send it using the `web3.eth.send_raw_transaction` function and wait for the transaction receipt by using the `web3.eth.wait_for_transaction_receipt` function

```solidity
# 1. Add imports
from compile import abi
from web3 import Web3

# 2. Add the Web3 provider logic here:
provider_rpc = {
    "development": "http://localhost:9944",
    "phron": "https://testnet.phron.ai",
}
web3 = Web3(Web3.HTTPProvider(provider_rpc["phron"]))  # Change to correct network

# 3. Create variables
account_from = {
    'private_key': 'INSERT_YOUR_PRIVATE_KEY',
    'address': 'INSERT_PUBLIC_ADDRESS_OF_PK',
}
contract_address = 'INSERT_CONTRACT_ADDRESS'
value = 3

print(
    f"Calling the increment by { value } function in contract at address: { contract_address }"
)

# 4. Create contract instance
Incrementer = web3.eth.contract(address=contract_address, abi=abi)

# 5. Build increment tx
increment_tx = Incrementer.functions.increment(value).build_transaction(
    {
        "from": Web3.to_checksum_address(account_from["address"]),
        "nonce": web3.eth.get_transaction_count(
            Web3.to_checksum_address(account_from["address"])
        ),
    }
)

# 6. Sign tx with PK
tx_create = web3.eth.account.sign_transaction(increment_tx, account_from["private_key"])

# 7. Send tx and wait for receipt
tx_hash = web3.eth.send_raw_transaction(tx_create.rawTransaction)
tx_receipt = web3.eth.wait_for_transaction_receipt(tx_hash)

print(f"Tx successful with hash: { tx_receipt.transactionHash.hex() }")
```

To run the script, you can enter the following command in your terminal:

```
python3 increment.py
```

If successful, the transaction hash will be displayed in the terminal. You can use the `get.py` script alongside the `increment.py` script to make sure that value is changing as expected:

{% code overflow="wrap" %}

```bash
python get.pyMaking a call to contract at address: 0xFef3cFb8eE1FE727b3848E551ae5DC8903237B08The current number stored is: 5python increment.pyCalling the increment by 3 function in contract at address: 0xFef3cFb8eE1FE727b3848E551ae5DC8903237B08Tx successful with hash: 0x47757fd97e3ef8db973e335d1f2d19c46b37d0dbd53fea1636ec559ccf119a13python get.pyMaking a call to contract at address: 0xFef3cFb8eE1FE727b3848E551ae5DC8903237B08The current number stored is: 8
```

{% endcode %}

Next you can open the `reset.py` file and take the following steps to create the script:

1. Add imports, including Web3.py and the ABI of the `Incrementer.sol` contract
2. Set up the Web3 provider
3. Define the `account_from`, including the `private_key`, and the `contract_address` of the deployed contract. The private key is required to sign the transaction. **Note: This is for example purposes only. Never store your private keys in a Python file**
4. Create a contract instance using the `web3.eth.contract` function and passing in the ABI and address of the deployed contract
5. Build the reset transaction using the contract instance. You'll then use the `build_transaction` function to pass in the transaction information including the `from` address and the `nonce` for the sender. To get the `nonce` you can use the `web3.eth.get_transaction_count` function
6. Sign the transaction using the `web3.eth.account.sign_transaction` function and pass in the reset transaction and the `private_key` of the sender
7. Using the signed transaction, you can then send it using the `web3.eth.send_raw_transaction` function and wait for the transaction receipt by using the `web3.eth.wait_for_transaction_receipt` function

```solidity
# 1. Add imports
from compile import abi
from web3 import Web3

# 2. Add the Web3 provider logic here:
provider_rpc = {
    "development": "http://localhost:9944",
    "phron": "https://testnet.phron.ai",
}
web3 = Web3(Web3.HTTPProvider(provider_rpc["phron"]))  # Change to correct network

# 3. Create variables
account_from = {
    'private_key': 'INSERT_YOUR_PRIVATE_KEY',
    'address': 'INSERT_PUBLIC_ADDRESS_OF_PK',
}
contract_address = 'INSERT_CONTRACT_ADDRESS'

print(f"Calling the reset function in contract at address: { contract_address }")

# 4. Create contract instance
Incrementer = web3.eth.contract(address=contract_address, abi=abi)

# 5. Build reset tx
reset_tx = Incrementer.functions.reset().build_transaction(
    {
        "from": Web3.to_checksum_address(account_from["address"]),
        "nonce": web3.eth.get_transaction_count(
            Web3.to_checksum_address(account_from["address"])
        ),
    }
)

# 6. Sign tx with PK
tx_create = web3.eth.account.sign_transaction(reset_tx, account_from["private_key"])

# 7. Send tx and wait for receipt
tx_hash = web3.eth.send_raw_transaction(tx_create.rawTransaction)
tx_receipt = web3.eth.wait_for_transaction_receipt(tx_hash)

print(f"Tx successful with hash: { tx_receipt.transactionHash.hex() }")
```

To run the script, you can enter the following command in your terminal:

```
python3 reset.py
```

If successful, the transaction hash will be displayed in the terminal. You can use the `get.py` script alongside the `reset.py` script to make sure that value is changing as expected:

{% code overflow="wrap" %}

```bash
python get.pyMaking a call to contract at address: 0xFef3cFb8eE1FE727b3848E551ae5DC8903237B08The current number stored is: 8python reset.pyCalling the reset function in contract at address: 0xFef3cFb8eE1FE727b3848E551ae5DC8903237B08Tx successful with hash: 0x152f07430b524838da848b44d58577db252681fba6fbeaf117b2f9d432e301b2python get.pyMaking a call to contract at address: 0xFef3cFb8eE1FE727b3848E551ae5DC8903237B08The current number stored is: 0
```

{% endcode %}

This tutorial is for educational purposes only. As such, any contracts or code created in this tutorial should not be used in production.The information presented herein has been provided by third parties and is made available solely for general information purposes. Phron does not endorse any project listed and described on the Phron Doc Website (<https://docs.Phron.ai/>). Phron does not warrant the accuracy, completeness or usefulness of this information. Any reliance you place on such information is strictly at your own risk. Phron disclaims all liability and responsibility arising from any reliance placed on this information by you or by anyone who may be informed of any of its contents. All statements and/or opinions expressed in these materials are solely the responsibility of the person or entity providing those materials and do not necessarily represent the opinion of Phron. The information should not be construed as professional or financial advice of any kind. Advice from a suitably qualified professional should always be sought in relation to any particular matter or circumstance. The information herein may link to or integrate with other websites operated or content provided by third parties, and such other websites may link to this website. Phron has no control over any such other websites or their content and will have no liability arising out of or related to such websites or their content. The existence of any such link does not constitute an endorsement of such websites, the content of the websites, or the operators of the websites. These links are being provided to you only as a convenience and you release and hold Phron harmless from any and all liability arising from your use of this information or the information provided by any third-party website or service.


# Dev Environments




---

[Next Page](/llms-full.txt/1)

