# Introduction

## Oraichain

As the **world’s first AI-powered blockchain oracle and ecosystem**, **Oraichain** now transforms itself to become an advanced **AI Layer 1 for Data Economy and blockchain oracle services** that serve as a foundational layer for the creation of a new generation of smart contracts and Dapps and create a complete AI Ecosystem on blockchain.

This document describes Oraichain's system overview, use cases, and token economics.

## Introduction

#### Why conventional blockchain doesn’t include AI models?[#](https://docs.orai.io/docs/WhitePaper/Introduction#why-conventional-blockchain-doesnt-include-ai-models)

Current smart contracts cannot run AI models inside, and it is almost impossible to integrate an AI model into a smart contract. AI models should be complex approaches, such as SVM, neural networks, and clustering. The reasons come from three characteristics of smart contracts as follows:

* Strictness: smart contracts always follow strict rules in which the inputs must be 100% accurate (e.g. signature) to generate an output. However, AI models can hardly give such accuracy (e.g. face recognition). As a result, Oraichain is there to reduce some aspects of strictness to obtain better functionality and user experience.
* Environment: smart contracts are mostly written in high-level programming languages such as Solidity and Rust that provide stricter syntax and better security. Nevertheless, the AI models are typically written in Python or Java.
* Data size: On one hand, smart contracts often have relatively small storage since it help reduce transaction fees in some blockchain networks such as Ethereum. On the other hand, the size of an AI model is much bigger.

There are below scenarios where AI is very useful and necessary.

* Identification based on biometric methods, such as face and fingerprint
* Automated trading based on price prediction and AI strategies
* Lending based on credit scores
* Comparison of two products from their photos
* Evaluating the price of game items

#### Oraichain's Solutions

The proposed Oraichain could be a bridge to bring AI to smart contracts. The Oraichain mechanism seems similar to Band Protocol and Chainlink, but it focuses more on AI APIs and the quality of the provided AI models. In each user request, test cases are attached, and the providers’ API must pass a certain number of test cases to receive payment. The validators manage the features of test cases and AI model quality, and that makes Oraichain unique and different.

* AI blockchain oracles: Oraichain enables smart contracts to access external AI APIs securely. Artificial Intelligence helps enhance smart contracts.
* AI Marketplace: Have access to, look up, and choose ever-increasing AI algorithms and models from different providers around the world. Develop your applications along with the integration of AI services to increase your application functionalities as well as values.
* AI Provider: AI developers, individuals, or companies, can have a chance to publish, edit, and manage their work and earn rewards from the users on a global scale. Hence, you can improve your models, even more, collect data and continue to provide exceptional AI services.
* Staking & Earning: Staking means earning. By staking your ORAI tokens into one or more validators, you will have a chance to participate in the system as a governor while earning more. Moreover, by doing so, your contributions also have a positive impact on our operations of the network. It is a win-win for all sides.
* Users & AI requests: Users can make different requests for AI services that are not easy to find elsewhere, as the service providers may not have enough resources to provide a stand-alone AI service application. If the services are great, sending funds to these services can be worth considering to allow them to grow more and more.
* ORAI DAO: you are the governor of the product serving you. Oraichain is of, for, and by the community. Oraichain team just helps initialize the project and when the mainnet is started, any changes of Oraichain should be reviewed by validators and stakeholders.

#### Oracle data on Oraichain

Smart contracts are a self-operating computer program that automatically executes when specific conditions are met:

> A smart contract is a computer program or a transaction protocol which is intended to automatically execute, control or document legally relevant events and actions according to the terms of a contract or an agreement. The objectives of smart contracts are the reduction of need in trusted intermediators, arbitrations and enforcement costs, fraud losses, as well as the reduction of malicious and accidental exceptions. (From [Ethereum whitepaper](https://ethereum.org/en/whitepaper) and [Wikipedia](https://en.wikipedia.org/wiki/Smart_contract))

The common use case of smart contracts is only tokenization, and it has not been adopted in the industry yet. The primary reason is that smart contracts are not connected to off-chain data that is not stored on the blockchain. Due to interacting with off-chain data that can lead to multiple states of the blockchain, it is not allowed to interact with off-chain data. A consensus protocol on the blockchain ensures a single state of the blockchain ledger.

The single state of the blockchain ledger makes all operations deterministic. It means that the same operation performed on different nodes should give the same result. Note that the difference in results will lead to failed consensus among blockchain nodes. A typical example of non-deterministic operations is calling an external API from outside since each API call could return different values.

Oracle, in terms of definition, is a person who can provide useful information. We also have a blockchain oracle as a name of a company, but this is not that Oracle. Oracle in the blockchain is a type of middleware that connects blockchain with the resources outside. In the past, blockchain could only have access to its internal data and resources, which is very limited, whereas other systems were free to do so with simple REST APIs. Now things have changed, oracle has come to provide blockchain with more functionalities by allowing it to call external APIs. In a blockchain, an oracle can be a node that collects data from other sources of data. It also can be a script file that calls a CURL request and receive the request's response before writing that response onto the blockchain.

Oraichain provides an oracle that helps fetch external data securely and its architecture is designed to focus more on AI data sources as follows:

* Request format including input parameters and test cases
* API testing based test cases that are the unique functionality.
* Test providers proposing suitable test cases that users can choose to test an AI API.
* API marketplace and test-case marketplace
* High scalability and performance
* Cross-chain compatibility that is able to serve data to most publicly available blockchains. The target blockchains can verify data on Oraichain efficiently.


# System Overview

Oraichain is a public blockchain that allows users to create different data requests. Instead of users, smart contracts can also request data securely from AI APIs through Oraichain. The blockchain network is built based on [Cosmos SDK](https://cosmos.network) along with [Terdemint](https://tendermint.com)’s [Byzantine Fault Tolerance](https://en.wikipedia.org/wiki/Byzantine_fault) consensus that helps speed up transactions’ confirmation time.

### Network Participants

The ORAI consensus protocol is similar to the delegated proof-of-stake (DPoS). Indeed, the network consists of numerous validators, each owning ORAI tokens while other ORAI token holders can be delegators staking their tokens to validators and get rewards for each newly created block.

The second task of the validators is to collect data from AI providers and validate that data before they are written to the blockchain. To validate an AI API, validators will do testing based on the test cases given by users, smart contracts, and test providers. If users do not know which test case is good, they can request some test cases from test providers.

### System Architecture

![](/files/-MXHGf-lyN8taJDu3wZs)

The flow of requesting an AI API is illustrated in the Oraichain’s System Overview figure. To perform a request, users or smart contracts need to call an oracle script that is available on the ORAI gateway or marketplace. In an oracle script, there are AI data sources (provided by AI providers), test cases, test source (optional), and transaction fees for each request. When a request comes, a random willing validator is chosen to perform this request. The chosen validator will fetch data from one or more AI providers on behalf of the user after executing the test scenarios, and if the AI provider fails in testing, the request is canceled.

A request is successful if its result is written to the Oraichain blockchain. The transaction result, which can be fetched from smart contracts and regular applications, is proof of execution, and fees are applied in this transaction. There is an overhead of reading results from Oraichain’s transactions, but it helps ensure that the AI API quality is good and there is no data tampering during the process of fetching data from AI providers.

Compared to Band Protocol and Chainlink, API testing based test cases is the unique functionality. Since Oraichain focuses on AI APIs, testing is very important to control the quality of AI providers. Besides, test providers can propose suitable test cases that users can choose to test an AI API. Test cases in the Oraichain marketplace can encourage AI providers to improve the accuracy of AI models.

Another interesting feature is that the Oraichain community has the power to rate the validators’ reputation for quality AI APIs improvement. If a validator has bad behavior, such as failing to perform test cases and validate AI providers, slow response time, and low availability, its holding token will be slashed.

Nevertheless, validators in Oraichain is responsible for performing many important tasks and could be a centralized point. Therefore, the number of chosen validators should be high in order to increase request performance, scalability, and high availability. Meanwhile, because we need many validators to participate in the Oraichain network and maintain their quality work, block reward and transaction fees must be applied for such validators to earn more ORAI tokens.

Specifically, there are two ways to incentivize validators as well as test case, data source providers.

#### First way

The validators that participate in the network can receive rewards after each block having transaction fees. Indeed, the validator proposing the block, which is called a proposer, collect a bonus reward for its helpful job of committing a block. The formulas are described below:

**(0) Propose multiplier = (base proposer reward + bonus proposer reward \* (sum of precommit voting power / total voting power))**

where **base proposer reward** is the base percentage of how much the proposer receives the reward; bonus proposer reward is the percentage for the amount of precommit voting power that the proposer has successfully collected when before committing a block. The current values are 1% and 4% respectively, so the maximum value of the propose multiplier is 5% or 0.05

**(1) Proposer reward (bonus) = Propose multiplier \* total fees within a block**

**(2) Remaining = Remaining - (1)**

**(3) vote multiplier = 1 - community tax - propose multiplier**

while the community tax is set to be 2% or 0.02

**(4) power fraction = voting power / total voting power**

**(5) a validator's reward = total fee \_reward multiplier**\_\*\* power fraction\*\*

**(6) remaining = remaining - reward for each validator**

the loop goes on until all validators have received their rewards.

**(7) The remaining reward is sent into the community pool, where it can be used to send to an abritary orai account.**

**Note**: The actual number of ORAI coins that a validator collect is the commission of the received reward. This figure is configured by each validator, and by default it is 0.1. The minimum gas price, on the other hand, must explicitly set in order to charge fees for each transaction. In addition, the tokens are allocated proportionally to the voting power. As a result, validators with more coins staked will receive more rewards.

#### Second way

The validators can actively participate in executing the oracle scripts to receive 20% of the rewards by publishing reports. A report contains information on the validator that created it, the data sources, test cases used, and the block containing that report transaction. Using this information, we can collect validators, test case owners, and data source owners involved in a specific block to reward them. Half of the total fees is reserved for rewarding data source and test case owners. Only those creating reports are able to receive the rewards. The formulas are as follows:

**Provider reward = total request fees within the previous block \* 0.5**

Here, we make sure that every Data Source and Test Case owner receives the correct amount that he requires after running the script. For example, an Oracle Script runs two AI Data Sources, 1 Test Case, each requires 0.05 ORAI to execute. As a result, the minimum fee needed is 1.5 ORAI, which is equal to total request fees within the previous block \* 0.5.

**Validator reward = Provider reward \_0.4 or total request fees within the previous block**\_\*\* 0.2\*\*

In here, validators that participate in the Oracle Script execution process will receive their rewards according to their voting powers within the **validator reward**.

The rest of the request fees (the remaining 30%) will be allocated to the validator that has successfully proposed a new block along with taxes that go into the community pool using the first way.


# AI Layer 1 for Data Economy & blockchain oracle services

Oraichain Mainnet 2.0, namely AI Layer 1 for Data Economy and blockchain oracle services, is a major upgrade of Oraichain Mainnet to get ready for mass adoption and interoperability with other chains.

Oraichain interconnects AI and Blockchain to introduce innovation and hence needs to revolutionize both to make them compatible and integrable. In the AI space, Oraichain focuses on providing decentralized platforms for Data and AI, standardizing how AI-based computation can be verifiable on-chain while ensuring the correctness of AI. In the Blockchain space, Oraichain emphasizes the scalability and interoperability of its blockchain oracle solutions and services with other networks to expand the utility of the Oraichain ecosystem; and through this, a wide range of unprecedented Dapps — more functional and intelligent can be made possible.

Oraichain’s technology and strategy for adoption have the main themes as follows:

**AI Layer 1 with high interoperability** — We bring our AI ecosystem and services to all major blockchain networks through our relaying protocols and bridges.

**Scale-up with Layer 2 solution** — We scale our blockchain oracle services and protocols like VRF in a subnetwork via a customized Layer 2 Rollup (for AI blockchain oracle and Oraichain’s protocols), which allows public participants and increases transaction throughput.

**Verifiable and Trustless AI Execution** — We design and implement “proof of correctness” and “proof of execution” for any AI computation. This plays a fundamental role in developing AI blockchain oracles for many smart contracts.

**Decentralized Data and AI Platform** — We develop Data and AI-related hubs through platforms like Data Hub or AI Marketplace (and other upcoming hubs) and standard protocols for creators like Royalty Protocol to establish decentralized environments for Data Economy and AI-based services.

**Standardized protocols for high applicability** — We make standard developing tools and protocols for developers such as Cosmwasm IDE, or upcoming SDK and development sandbox for Dapps, NFT, and Metaverse projects.


# Layer 2 Rollups and Subnetworks

The purpose of running subnetworks & Layer 2 rollups adaptations on Oraichain is separating the Mainnet and subnetworks is to scale up the performance of the Mainnet, also known as the Layer 1.

### Oraichain's Layer 2 Rollups

Rollups are Layer 2 solutions dominating Ethereum scaling and have been gaining a great popularity in many networks like Syscoin, Cosmos, and many specific projects like Immutable X, zkSync, StarkWare, Loopring, etc.

There are two types of rollups: optimistic rollups(optimism project) and zk-rollups (zksyncs project). Oraichain has customized these both types in its modules when implementing subnetworks for AI blockchain oracles and OraiDEX.

### Subnetworks

Subnetworks for running DApps on Oraichain Mainnet 2.0 are set to stay in Layer 2 while considerably helping in expanding the capacity of Mainnet but not affecting its core logic and security.

At the moment, Oraichain has launched two subnetworks: VRF Subnetwork and AI Execution Subnetwork.

**Subnetwork executors** play a role as a validator for the working of a subnetwork on Oraichain. Similar to a blockchain validator, an executor participates in the execution and verification of the computation, in this case, the calculation of the random data. However, compared to blockchain validators, VRF or AI Execution subnetwork executors require much less computing resources and don’t need to achieve 100% uptime.


# Verifiable and trustless AI Execution

We design and implement **“Proof of Correctness”** and **“Proof of Execution”** for any AI computation. This plays a fundamental role in developing AI blockchain oracles for many smart contracts while enabling smart contracts to safely use the results of AI computation to trigger actions, resulting in an absolute improvement compared to a centralized AI computation that is integrated into smart contracts.

**VRF Subnetwork** is the first subnetwork on Oraichain Mainnet 2.0 and we are now implementing an **AI Executor Subnetwork** with customized Optimistic Rollup and ZK-Rollup modules. With **Proof of Correctness** and **Proof of Execution** mechanisms, we create ***a verifiable and trustless AI Execution environment*** instead of a centralized AI solution brought to blockchains.


# Protocol Messages

### Cosmos SDK Messages

Since the Oraichain blockchain is built from the Cosmos network, it also supports all message types of Cosmos SDK so that they can be delivered to all nodes for execution and querying. For simplicity, all message types follow the same protocol, which are described on the [Cosmos SDK documentation](https://docs.cosmos.network/v0.45/building-modules/messages-and-queries.html)

### CosmWasm Messages

Oraichain uses `wasmd` module to leverage the power of smart contracts to build decentralized applications. The CosmWasm team describes clearly these messages in [their documentation](https://docs.cosmwasm.com/docs/smart-contracts/contract-semantics)


# IBC Integration

### Interblockchain Communication Protocol (IBC) <a href="#what-is-the-interblockchain-communication-protocol-ibc" id="what-is-the-interblockchain-communication-protocol-ibc"></a>

**IBC** stands for **Interblockchain Communication Protocol,** which have been widely used to allow direct communication and asset trading between independent blockchains.

> The Cosmos ecosystem has a vision of creating the "internet of blockchains," or a network of independent chains that can communicate in a decentralized way. To reach this goal, the Inter‐Blockchain Communication protocol (IBC) was created.

As part of the CosmosSDK-based ecosystem, Oraichain integrates the IBC protocol to [OraiDEX](https://blog.orai.io/-eb20ca5c93fe), our CosmWasm smart contract-based decentralized exchange with multi-chain interoperability, optimal speed and lots of liquidity options for users.


# Use Cases

AI will be the next big thing and upgrade of smart contracts in DApps. How to make smart contracts smarter with AI. We would like to introduce several use cases where smart contracts can leverage AI.

Oraichain also supports regular centralized applications in using AI APIs on the decentralized Oraichain marketplace. Users can find better AI providers with better price in this marketplace.

### aiRight: NFT audit and copyright management

To support a transparent and truly trustless NFT ecosystem, Oraichain has developed aiRight, a complete copyright management and farming platform for NFTs that harnesses the power of the world’s first AI blockchain oracle to determine authenticity and point of origin for multimedia works minted on-chain.

Link: <https://airight.io>

### Flexible smart contracts using face authentication

There are several scenarios in which face authentication is very useful as follows:

* Using your face to get your balance instead of using a private key.
* Withdraw using your face
* Using your face in order to reset your private/public key pair.
* Using both your private key and face in order to execute a smart contract.

![](/files/-MXHFspDeb7ovJsW2yBI)

Using face authentication might be riskier than a private key, but it helps increase user experience. In cases of checking balance and withdrawing tokens to registered wallets, face authenticatiion is safe and convenient.

### Fake news detection using different AI providers from Oraichain

This use case focuses more on a regular application that wants to check if the news can be trusted. Oraichain provides a marketplace in a decentralized manner in which combining results from different providers is possible. If the providers want to receive payments, their APIs must pass the test cases, which is when the APIs return the correct results of your own test cases.

### More other use cases is coming soon

* Smart contracts help check if a product is fake in the supply chain.
* Smart contracts deciding a loan based on users’ credit score.
* Smart contracts automatically pricing game items based on their characteristics and DNA.
* Marketplace of automated diagnostics for X-ray images, spam classification, handwriting detection using OCR, and citizen ID card detection using OCR.


# Token Economics

<mark style="background-color:red;">**FAQs (08/2023):**</mark> [<mark style="background-color:red;">**https://oraichain.notion.site/ORAI-Tokenomics-Transformation-FAQs-7c2bc5c4dc4a4fc8ba61dc9eb8478160**</mark>](https://oraichain.notion.site/ORAI-Tokenomics-Transformation-FAQs-7c2bc5c4dc4a4fc8ba61dc9eb8478160)

When we call **ORAI**, it means that it is native ORAI tokens created and contained in the Oraichain network. At the moment, there are three types of ORAI, including **ERC20 ORAI** on the Ethereum network, **BEP20 ORAI** on the BNB Chain, and **Native ORAI** on the Oraichain Mainnet.

**ERC20 ORAI contract address:** 0x4c11249814f11b9346808179cf06e71ac328c1b5

**BEP20 ORAI contract address:** 0xa325ad6d9c92b55a3fc5ad7e412b1518f96441c0

### Token Distribution Overview

Summary of Circulating Supply (as of August 2023)

* Ecosystem: 5,538,595 ORAI
* DAO Treasury: 1,700,000 ORAI
* Foundation: 6,062,294 ORAI (3,229,850 ORAI delegated in FDC Program)

**Total CS (8/2023): 15,078,971 ORAI -** [**Real-time circulating supply**](https://api.token.orai.io/v1/cs)

**Total supply (8/2023): 16,779,272 ORAI -**[ **Real-time total supply**](https://api.token.orai.io/v1/total-supply)

**Max supply: 19,779,272 ORAI**

**References:**&#x20;

* 1st token burn **(73% of initial total supply)** on December 22, 2020: <https://medium.com/oraichain/oraichain-tokenomics-v3-73-token-burn-and-key-updates-4e99d1972bcf>&#x20;
* 2nd token burn **(258,449.4 ORAI burnt from Team)** on March 28, 2021: <https://etherscan.io/tx/0xa66c06593dc8559f565e4a480c32c698ccbb128c49404f8a07a203a5f37902e1>&#x20;
* 3rd token burn **(3,000,000 ORAI tokens from Team, Advisors, and Foundation)** on June 23, 2021: <https://etherscan.io/tx/0x953694d378f036ff0e136441e78875ae241d9f212b583007eb4814bab64cf7e3>&#x20;
* **ORAI tokenomics for sustainable development:** <https://blog.orai.io/updating-orai-tokenomics-for-sustainable-development-48536becdf49>&#x20;

The table below demonstrates the specific percentage and amount for each allocation:

**Planned token release schedule from August 2023(%):**

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

### **How will each allocation be used?**&#x20;

As the Oraichain Foundation commits to providing deeper transparency for all current and future DAO members, it is helpful to understand the specific purpose and appropriate use of each allocation.

**Ecosystem**: Primarily used for Block Rewards, but can also be allocated for new liquidity pools and liquidity mining incentives.

**DAO Treasury**: Our expectation is that the Oraichain DAO will continue to organize, and formalize standard procedures for community-led initiatives, including developer incentives programming, marketing actions, and educational content creation. The Oraichain Foundation will continue to provide resources to meet the unique needs and assist the DAO as needed.

**Foundation**: Primarily used to support research and development for Oraichain’s open-source core protocols, provide funding for Foundation hosted hackathons, and continue to support the community-inspired Foundation Delegation Campaign (FDC), providing delegations to support our validators.

### Token Utilities&#x20;

Native ORAI tokens are required to secure and power the decentralized blockchain oracle network of validators. The native ORAI token is used in different scenarios below:

* **Transaction fee:** the ORAI token is required in order to run an AI request sent to the Oraichain network and run any transaction.
* **Staking for validators:** all validators are required to stake ORAI in order to be selected to create a block or fulfill data requests.
* **Participation in network governance:** the Oraichain network is organized in the DAO manner, all protocol upgrades and parameter changes must be voted by token holders.&#x20;

### About transaction fees on Oraichain Mainnet 2.0

The token plays a role as a transaction fee that is paid for parties as follows:

* Request-executing validators
* AI-API providers
* Testcase providers
* Block-creating validators.

The transaction fee is different depending on the fee requirement of request-executing validators, AI-API providers, and test-case providers. The transaction fee should be explicitly defined in MsgSetAIRequest of a request. When a request comes, request-executing validators must decide if they want to execute it. After that, a random validator, which is responsible for proposing a block will execute the request before firing an event to those request-executing validators.

Afterward, these validators interact with test cases and AI APIs to create a MsgResultReport in the end. A report contains the data sources, test cases used, the validator creating the report, and the block height of it. Using this information, we can collect validators, test case owners, and data source owners involved in a specific block to reward them. Only those creating reports are able to receive the rewards. If there is more than one validator asked in the MsgSetAIRequest (ValidatorCount), the transaction fee is divided proportionally to the voting power of each validator.

### Minting ORAI

There are two ways to mint ORAI tokens on the Oraichain Mainnet 2.0:&#x20;

* The first way is that the ORAI token is rewarded for each newly created block. In the Oraichain network, validators are responsible for creating new blocks, and a random validator is chosen to do that. To become a validator, one needs enough ORAI tokens that are staked or delegated. Note that new ORAI tokens are only mined when a block contains one or more transactions with transaction fees. Such fees will be converted into tokens in the form of rewards for the validators.
* The second way is briefly described above, in which the request-executing validators can earn some extra ORAI tokens by executing test cases and data sources. Similar to the first way, 70% of the total transaction fee is extracted as a reward for the first three parties mentioned earlier. The remaining 30% is saved to reward validators for the newly committed block. Nevertheless, this second way only occurs when there is at least a report broadcast to the Oraichain network at the end of a block.

### Inflation, Staking, and Slashing

To keep the value of the ORAI token, holders can stake their token to the Oraichain network. The rewarding token is divided based on the number of tokens that a holder is staking to a validator.

[**Slashing**](https://blog.orai.io/updating-orai-tokenomics-for-sustainable-development-48536becdf49) is a mechanism to penalize misbehaviors of validators in aspects of AI API quality, response time, and availability.

Read more about incentives on Oraichain Mainnet 2.0 & rewards for delegators and validators [**here**](https://blog.orai.io/oraichain-mainnet-incentives-rewards-for-delegators-and-validators-958db9b4bb4b).


# General

Oraichain supports CosmWasm smart contracts at the moment and it will enable EVM smart contracts in Q2/2022.

[CosmWasm IDE](https://marketplace.visualstudio.com/items?itemName=oraichain.cosmwasm-ide) (Powered by Oraichain x CosmWasm) aims to become a general tool for the developer community within the Cosmos ecosystem.

[Github](https://github.com/oraichain): Oraichain codebase and ecosystem tools are totally open source.


# Blockchain details

## Oraichain Endpoints:

### Mainnet

```
https://rpc.orai.io
https://lcd.orai.io
```

### Testnet:

```
https://testnet.rpc.orai.io
https://testnet.lcd.orai.io
```


# CosmWasm Contracts


# Compile a Contract

This guide will provide step-by-step instructions for compiling the cosmwasm smart contract. Example contracts for this can be found at <https://github.com/CosmWasm/cw-examples>.

{% hint style="info" %}
If you have ZERO experience with smart contracts, you need to check out [book.cosmwasm.com](https://book.cosmwasm.com) for setting up your environment, testnet, and the basics of CosmWasm.
{% endhint %}

## Install cosmwasm-tools

The easiest way is to simply use the [cosmwasm-tools](https://github.com/oraichain/cosmwasm-tools) to compile cosmwasm smart contract. Follow these steps to install cosmwasm-tools:

* Using npm:

```
npm install -g @oraichain/cwtools
```

* Or can use yarn:

```
yarn global add @oraichain/cwtools
```

After installed this package, to verify if installation process took place successfully, type to your terminal:

```
cwtools --version
```

For more information of cwtools command, type:

```
cwtools -h
```

## Compile cosmwasm contracts

To compile cosmwasm contract using cosmwasm-tools, use following command:

```
cwtools build path-to-contract
```

You can compile multiple cosmwasm contracts:

```
cwtools build path-to-contract_1 path-to-contract_2
```


# Deploy a Contract

## PreRequisite

Make sure you follow the [compile a contract](/developer-guides/cosmwasm-contract/compile-contract) guide first for your project. Once you have a contract compiled in the artifacts/\*.wasm directory, you are ready for this guide.

This guide will show you how to deploy and interact with a contract using CLI.

## Upload Contract

You need to upload the contract via the CLI to chain. To do this, perform the following

```bash
TXFLAGS="--chain-id Oraichain --gas auto --gas-adjustment 1.5 --fees 1000orai --node https://rpc.orai.io"

oraid tx wasm store artifacts/CONRTACT_NAME.wasm \
    --from <KEY> $TXFLAGS -y
```

This will then return a transaction hash. With this data, you need to query it to get the code id of the contract on chain

```bash
oraid q tx 38330E909CD219B80927009DA37FD69D334D19B2AD4EC47456A24E85034F0085 --output json --node https://rpc.orai.io
```

This will return the data about the transaction, and give us the code id of our contract

```json
{
  "height": "148",
  "txhash": "2A52A8B3201425A534052C1616C088271B90EBAFF3ECF4B9784420EF1D531B6D",
  "codespace": "",
  "code": 0,
  "data": "124E0A262F636F736D7761736D2E7761736D2E76312E4D736753746F7265436F6465526573706F6E7365122408011220795F644FE9F0CC5F5E2C48ADCE0F0C28B76AA8D3BF7DCF0104085A1B767248E1",
  "raw_log": "",
  "logs": [],
  "info": "",
  "gas_wanted": "1488045",
  "gas_used": "993511",
  "tx": {
    "@type": "/cosmos.tx.v1beta1.Tx",
    "body": {
      "messages": [
        {
          "@type": "/cosmwasm.wasm.v1.MsgStoreCode",
          "sender": "orai10vvuu8lgc70rrqdkr03jchtd4yk023gylsr84c",
          "wasm_byte_code": "FU4jZbtUYhyy2XsU2i1+2my2q3bepA0PSasjyNIKAftcBywqHisQMWnC1R8SlSl42jxxnwBcMu9N+a4jLIFkfkVc+RDglRa5LlTWs27naZIVsyRf4wdO1Pq2Kykjp0W6QCIcBRG0fKrPVFxAM3bCRXkOJiu1iodCkmMzuc1J5ESrRLsKQZOt3Oh17YhrQR5RyFB3inIym3OSoSLmZDqmZuu2Tw1Yphsdiw+cQILIJXdKMvwvCMjrXQBtlwcDEfkqGG9YARHySxEZIQ9cIy1xQe9aGEQxH4ReGcFhCcluiODtUPLOY2PL56HeI7k2QOSmkwQlWYKwHu3y0k7OpyPNnyOI/gUi2Y0gaqVvIURXsjEi/G+wuYAPonehX5bhTTJCMsT+TjebOzeSQnUQAQ90Q3hJE/LQso64JVqmB8LNtCIIUADFXC5pPgTQ3QCCkgRc/R4A18kXwwACCITQfOCS3F4v8nTIfyqBhNzrhfWwyQUbgAc2slJdWXiHB8A1MpA/QsBT9ICRyjs8XmgXv7fr/HsipoDXYwqYiilgaZ8CLuxT/k8AAAD//+oTrtn/FQIA",
          "instantiate_permission": null
        }
      ],
      "memo": "",
      "timeout_height": "0",
      "extension_options": [],
      "non_critical_extension_options": []
    },
    "auth_info": {
      "signer_infos": [
        {
          "public_key": {
            "@type": "/cosmos.crypto.secp256k1.PubKey",
            "key": "A6Le3gjpOFSjsX6mBy///SfMrmpKAYuCralBe30yc0jr"
          },
          "mode_info": { "single": { "mode": "SIGN_MODE_DIRECT" } },
          "sequence": "1"
        }
      ],
      "fee": {
        "amount": [{ "denom": "orai", "amount": "200" }],
        "gas_limit": "1488045",
        "payer": "",
        "granter": ""
      },
      "tip": null
    },
    "signatures": [
      "aU8Xty61MvidTNl5zbLY3r1882pAcvMnt4qYluZ3/zEhlHSvfELQszJcFdrNbsMU08IRwLMPQEPUM3aPs1pTUw=="
    ]
  },
  "timestamp": "2025-03-26T08:56:07Z",
  "events": [
    {
      "type": "coin_spent",
      "attributes": [
        {
          "key": "spender",
          "value": "orai10vvuu8lgc70rrqdkr03jchtd4yk023gylsr84c",
          "index": true
        },
        { "key": "amount", "value": "200orai", "index": true }
      ]
    },
    {
      "type": "coin_received",
      "attributes": [
        {
          "key": "receiver",
          "value": "orai17xpfvakm2amg962yls6f84z3kell8c5lr24r2w",
          "index": true
        },
        { "key": "amount", "value": "200orai", "index": true }
      ]
    },
    {
      "type": "transfer",
      "attributes": [
        {
          "key": "recipient",
          "value": "orai17xpfvakm2amg962yls6f84z3kell8c5lr24r2w",
          "index": true
        },
        {
          "key": "sender",
          "value": "orai10vvuu8lgc70rrqdkr03jchtd4yk023gylsr84c",
          "index": true
        },
        { "key": "amount", "value": "200orai", "index": true }
      ]
    },
    {
      "type": "message",
      "attributes": [
        {
          "key": "sender",
          "value": "orai10vvuu8lgc70rrqdkr03jchtd4yk023gylsr84c",
          "index": true
        }
      ]
    },
    {
      "type": "tx",
      "attributes": [{ "key": "fee", "value": "200orai", "index": true }]
    },
    {
      "type": "tx",
      "attributes": [
        {
          "key": "acc_seq",
          "value": "{\u0019�\u001f�Ǟ1��\u001b�,]m�,�E\u0004/1",
          "index": true
        }
      ]
    },
    {
      "type": "tx",
      "attributes": [
        {
          "key": "signature",
          "value": "aU8Xty61MvidTNl5zbLY3r1882pAcvMnt4qYluZ3/zEhlHSvfELQszJcFdrNbsMU08IRwLMPQEPUM3aPs1pTUw==",
          "index": true
        }
      ]
    },
    {
      "type": "message",
      "attributes": [
        {
          "key": "action",
          "value": "/cosmwasm.wasm.v1.MsgStoreCode",
          "index": true
        },
        {
          "key": "sender",
          "value": "orai10vvuu8lgc70rrqdkr03jchtd4yk023gylsr84c",
          "index": true
        },
        { "key": "module", "value": "wasm", "index": true },
        { "key": "msg_index", "value": "0", "index": true }
      ]
    },
    {
      "type": "store_code",
      "attributes": [
        {
          "key": "code_checksum",
          "value": "795f644fe9f0cc5f5e2c48adce0f0c28b76aa8d3bf7dcf0104085a1b767248e1",
          "index": true
        },
        { "key": "code_id", "value": "1", "index": true },
        { "key": "msg_index", "value": "0", "index": true }
      ]
    }
  ]
}

```

We can see events with type store\_code shows the code\_id being 1. If you wish the automate this return code in bash to a variable, you can

```bash
# ensure jq is installed
UPLOAD_TX_HASH=38330E909CD219B80927009DA37FD69D334D19B2AD4EC47456A24E85034F0085
CODE_ID=$(oraid q tx $UPLOAD_TX_HASH --output json | jq -r '.events[] | select(.type == "store_code") | .attributes[] | select(.key == "code_id") | .value') && echo "Code Id: $CODE_ID"
```

## Instantiate

With the code now being up on chain, we can now run logic to setup our own copy of the contract which we control. This will then give us a unique contract address for others to interact with in accordance with the contract logic. This example is from the [cosmwasm/cw-template](https://github.com/CosmWasm/cw-template).

Ensure you change CODE\_ID to match your code id from the store code

<pre class="language-sh"><code class="lang-sh"># Manual
CODE_ID=1
oraid tx wasm instantiate $CODE_ID  --label "some-contract" $FLAGS -y --admin &#x3C;your-address-here>
<strong># then query the tranasaction hash as we do above.
</strong>
# Automated return of the contract address
CODE_ID=1
TX_INIT=$(oraid tx wasm instantiate "$CODE_ID" '{"count":0}' --label "contract" $FLAGS -y --admin &#x3C;your-address-here> | jq -r '.txhash') &#x26;&#x26; echo $TX_INIT
CONTRACT_ADDR=$($BINARY query tx $TX_INIT --output json | jq -r '.events[] | select(.type == "instantiate") | .attributes[] | select(.key == "_contract_address") | .value') &#x26;&#x26; echo "CONTRACT_ADDR: $CONTRACT_ADDR"
</code></pre>


# Query a Contract

## Command Line Interface

The most common way to query a cosmwasm smart contract is within the oraid wasm smart query command. This follows the following format where query is a JSON string with no spaces. By default, the least amount of data this can be is an empty JSON payload `'{}'.`

```
oraid query wasm contract-state smart [contract_bech32] [query] [flags]
```

For this example, we will use a example scenario of NFT contract. This will show you how to brute force query a contract if you have no idea what the query schema of the contract is. At this time, there is no way to query the format of a contract's requests, but this is something many are actively working on.

Now we attempt to query this contract address and extract some data from it and get which queries are allowed. As you can see, we pass through a random payload for abcde so that the contract will return actual valid query requests

**NOTE**: A Query can never be empty such as `'{}'` given you need to specify the path of data you want to reach.

<pre class="language-sh"><code class="lang-sh">CONTRACT=orai1ase8wkkhczqdda83f0cd9lnuyvf47465j70hyk
oraid q wasm contract-state smart $CONTRACT '{"abcde":{}}' --node https://rpc.orai.io

<strong># Error parsing into type 
</strong><strong>#    Error parsing into type oraichain_nft::msg::QueryMsg: 
</strong>#    unknown variant `abcde`, 
#    expected one of `owner_of`, `approved_for_all`, `num_tokens`, `contract_info`, 
#    `nft_info`, `all_nft_info`, `tokens`, `all_tokens`, `minter` 
</code></pre>

{% hint style="info" %}
The query shows CW721 Base is this contracts name. As this is a standard contract, all messages can be found in the CosmWasm/cw-nfts repository on github\
\
<https://github.com/CosmWasm/cw-nfts/blob/main/contracts/cw721-base/src/msg.rs>
{% endhint %}

From this, we now know all of the query endpoints and can requests something more specific from the contract for our usage. Let's get

```sh
CONTRACT=orai1ase8wkkhczqdda83f0cd9lnuyvf47465j70hyk
oraid q wasm contract-state smart $CONTRACT '{"all_tokens":{}}' --node https://rpc.orai.io

data:
  tokens:
  - "10"
  - "100"
  - "1000"
  - "10005"
  - "10006"
  - "10009"
  - "1001"
  - "10010"
  - "10011"
  - "10023"
  
# You can use --output json to read it via JSON form
# oraid q wasm contract-state smart $CONTRACT '{"all_tokens":{}}' --output json | jq .data
```

Here we can see there are 8 tokens in this set. Lets query one of the NFTs information

```bash
CONTRACT=orai1ase8wkkhczqdda83f0cd9lnuyvf47465j70hyk
oraid q wasm contract-state smart $CONTRACT '{"nft_info":{}}' --node https://rpc.orai.io

# missing field `token_id`: query wasm contract failed
```

Just like the first query, we can see that the payload needs more information. It returned an error that we need to specify the token\_id we want the nft\_info for. Note, Uint128 sized numbers are read as a string

```bash
CONTRACT=orai1ase8wkkhczqdda83f0cd9lnuyvf47465j70hyk
oraid q wasm contract-state smart $CONTRACT '{"nft_info":{"token_id":"10"}}' --node https://rpc.orai.io

# data:
#   description: Thay pagoda, Hoai Duc, Ha Noi
#   image: https://gateway.ipfs.airight.io/ipfs/QmPhRnGtGWEd1He6zegcKZK86X5uRg2r17AZDNoCXoFqRL
#   name: Thay pagoda
```


# Send tokens to a Contract

## Command Line Interface

When you execute a message, a user can also pass through a flag which sends funds from their account to the contract to do logic. You can check if a user sends any funds in your contract's execute endpoint with the `info.funds` array of Coins sent by the user. These funds then get added to the contracts balance just like any other account. So it is up to you as the developer to ensure to save how many funds each user has sent via a BTreeMap or other object storage in state (if they can redeem funds back at a later time).

To send funds to a contract with some arbitrary endpoint, you use the `--amount` flag.

```sh
oraid tx wasm execute CONTRACT '{"some_endpoint":{}}' --amount 1000000orai
```

{% hint style="info" %}
If the "some\_endpoint" execute errors on the contract, the funds will remain in the users account.
{% endhint %}

## Typescript

```typescript
import { coin, makeCosmoshubPath } from "@cosmjs/amino";
import { GasPrice } from "@cosmjs/stargate";
import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
import "dotenv/config";
import { MsgExec } from "cosmjs-types/cosmos/authz/v1beta1/tx";
import { MsgSend } from "cosmjs-types/cosmos/bank/v1beta1/tx";

const main = async () => {
  const mnemonic = "YOUR_MNEMONIC_HERE";
  const chainInfo = {
    chainId: "Oraichain",
    rpcEndpoint: "https://rpc.orai.io",
    prefix: "orai",
    gasPrice: GasPrice.fromString("0.002orai"),
    feeToken: "orai",
  };
  const hdPath = makeCosmoshubPath(0);

  // Setup signer
  const offlineSigner = await DirectSecp256k1HdWallet.fromMnemonic(mnemonic, {
    prefix: chainInfo.prefix,
    hdPaths: [hdPath],
  });

  const { address } = (await offlineSigner.getAccounts())[0];
  console.log(`Connected to ${address}`);

  // Init SigningCosmWasmClient client
  const client = await SigningCosmWasmClient.connectWithSigner(
    chainInfo.rpcEndpoint,
    offlineSigner,
    {
      gasPrice: chainInfo.gasPrice,
    }
  );

  const balance = await client.getBalance(address, chainInfo.feeToken);
  console.log("balance: ", balance);

  const sendCoin = coin(1000, "orai");
  const tx = await client.execute(
    address,
    "CONTRACT_ADDRESS",
    "CONTRACT_MSG",
    "auto",
    "memo",
    [sendCoin]
  );

  console.log("txhash: ", tx.transactionHash);
};

main();
```


# Manage Contracts using design patterns

## Prerequisites

To follow this pattern, you need to install:

* [CosmWasm tools](/developer-guides/cosmwasm-contract/compile-contract#install-cosmwasm-tools)
* NPM - for managing a TypeScript mono repo
* Rust - for building CosmWasm smart contracts

## The pattern

Even though you can upload, deploy and interact with CosmWasm contracts any way you want, it is recommended to organize your code in a pattern that is scalable and portable to different dApps.

In Oraichain Labs, we use a `Nx` mono repo that consists of at least three packages below:

```
tonbridge-sdk/
├── packages/
│   ├── contracts-build/
│   └── contracts-sdk/
│   └── contracts-demo/
├── .gitignore
├── README.md
├── lerna.json
├── nx.json
├── package.json
├── tsconfig.json
└── yarn.lock
```

* **contracts-build**:

  * Contains .wasm files that are related to the service you're trying to develop. They are also useful when you want to write simulate tests in `Node.js` resembling the actual production code.
  * For example, Our [Ton Bridge SDK's contracts build](https://github.com/oraichain/tonbridge-sdk/tree/main/packages/contracts-build/data) contains 3 `.wasm` files: a bridge, a light client, and a cw20 token. These are up-to-date smart contract builds that are used for [simulation](/developer-guides/cosmwasm-contract/cosmwasm-simulate) and deployment to the Oraichain network. Meanwhile, the `src/index.ts` has two main functions: read the `.wasm` files and deploy those onto the Oraichain network.

  ```
  contracts-build/
  ├── data/
  │   ├── cw-tonbridge-bridge.wasm
  │   └── cw-tonbridge-validator.wasm
  │   └── oraiswap-token.wasm
  ├── src/
  │   ├── index.ts
  ```
* **contracts-sdk**:

  * Contains TypeScript code generated from the contract schemas. You can also generate types for multiple contracts and put them in the `contracts-sdk`. The types usually come from the contracts used in `contracts-build` for consistency. However, there are some common already been published on NPM that you can reuse. For example, the CW20 types are in the `@oraichain/oraidex-contracts-sdk`.
  * For example, [Ton Bridge SDK's contracts sdk](https://github.com/oraichain/tonbridge-sdk/tree/main/packages/contracts-sdk) contains types of the TON CW contracts.

  ```
  contracts-sdk/
  ├── src/
  │   ├── index.ts
  │   ├── TonbridgeBridge.client.ts
  │   ├── TonbridgeBridge.types.ts
  │   ├── TonbridgeValidator.client.ts
  │   ├── TonbrideValidator.types.ts
  │   ├── types.ts
  ```

  * These files are generated using [CosmWasm tools](/developer-guides/cosmwasm-contract/compile-contract#install-cosmwasm-tools). You will learn to build contracts and generate types in the [below section](#how-to-setup-the-pattern).
* **contracts-demo**:

  * The name speaks for itself. This package is for writing example codes to interact with the contracts you are developing.
  * Since intergrating the contract logic into an dApp can be confusing, having examples of how to use the contract end-to-end can be useful for other developers and for your future-self.
  * You can write anything in this package, and since it is just a demo package, you don't need to publish it onto NPM.
  * You can have a `tests/` directory for contract simulation testing in this package.

  ```
  contracts-demo/
  ├── src/
  │   ├── demo.ts
  ├── tests/
  │   ├── abcd.test.ts
  ```

Below is the demo of using TypeScript code gen `@oraichain/tonbridge-contracts-sdk` to interact with TON Light Client contract:

```ts
// url: https://github.com/oraichain/tonbridge-sdk/blob/5b481cdd96fcb9fbed99194ab42e10b51bb2aa9a/packages/contracts-demo/src/demo.ts
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
import { GasPrice } from "@cosmjs/stargate";
import { ORAI } from "@oraichain/oraidex-common";
import { TonbridgeValidatorClient } from "@oraichain/tonbridge-contracts-sdk";

(async () => {
  const signer = await DirectSecp256k1HdWallet.fromMnemonic(
    process.env.MNEMONIC,
    { prefix: ORAI }
  );
  const sender = (await signer.getAccounts())[0];
  const client = await SigningCosmWasmClient.connectWithSigner(
    "https://rpc.orai.io",
    signer,
    { gasPrice: GasPrice.fromString("0.001" + ORAI) }
  );
  const tonValidatorAddress =
    "orai16crw7g2rcvuga7vlnyxgwtdxtan46k8qqjjwhjqdjvjgk96n95es35q8vm";
  const validator = new TonbridgeValidatorClient(
    client,
    sender.address,
    tonValidatorAddress
  );

  await validator.updateOwner({ newOwner: tonValidatorAddress });
})();

```

## Benefits

You may ask, what's the benefits of following this coding pattern?. Say no more!

### **Increase portability**

* You can publish the `contracts-build` and `contracts-sdk` packages onto NPM and use them in various dApps.
* The `contracts-build` are for end-to-end dapp testing simulation, while the `contracts-sdk` are for easy contracts interaction.
* Whenever there are contract schema or code changes, dApps only need to pump the dependency versions and modify their code accordingly to the new types & .wasm.

### **Reduce Development time**

* By using a `Nx` mono repo, the devs don't need to publish any packages before making sure everything is correct.
* For example, after testing, they see that the contract schemas need to be updated to meet the user requirements. With a mono repo, they only need to update the contract code, re-generate the schemas and rebuild the mono repo if needed.
* The service is also loosely-coupled. For example, if there's a new feature changing the contract logic, but not the schemas, then we only need to update the `contracts-build` package and the dApp logic.

## How to setup the pattern

Assuming your contracts are located at the same level as your root project directory like below:

```
  oraichain-labs/
  ├── tonbridge-sdk/
  ├── tonbridge-cw-contracts/
  │   ├── contracts/
```

then you can run the following commands to build & generate types:

```bash
# build code. -o here is the output directory. -w is watch for hot-reloading when there's a change in the contract code
cwtools build ../tonbridge-cw-contracts/contracts/* -o packages/contracts-build/data -w
# build schema. -s is for schema
cwtools build ../tonbridge-cw-contracts/contracts/* -s
# gen typescript codes. -o here is the output directory
cwtools gents ../tonbridge-cw-contracts/contracts/* -o packages/contracts-sdk/src
```

You can also build multiple contracts at different directories at once. The same goes for `gents`:

```bash
cwtools build ../tonbridge-cw-contracts/contracts/* ../oraiswap/contracts/* -o packages/contracts-build/data
```


# End-to-end CosmWasm testing with CW-simulate

[CosmWasm Simulate](https://github.com/oraichain/cw-simulate) is an open-source tool that manages contract states to simulate the effects of CosmWasm contracts on the blockchain environments on which they are hosted.

Oraichain Labs forked the repository from [Cosmology Tech](https://github.com/cosmology-tech/cw-simulate), increased its testing performance, and added a lot of additional features:

* Simulating IBC states
* Gas simulation
* Simulating address native balances.
* Simulating block creation.

For more information, please visit our [CosmWasm Simulate README](https://github.com/oraichain/cw-simulate/blob/main/README.md)


# Local testnet chain

This guide will provide step-by-step how to run a local testnet chain

### **Step 1: Access the Oraichain repository**

The first thing you need to do is head over to the Oraichain repository. This repository is designed to help you launch and interact with local testnet chain. You can find this repo [here](https://github.com/oraichain/wasmd.git)

### **Step 2: Clone the repository**

After find Oraichain repo, clone it to your desire folder

```bash
git clone https://github.com/oraichain/wasmd.git && cd wasmd
```

### **Step 3: Set up**

* Build the binary

```bash
make build
```

* Check result

```bash
oraid version
```

### **Step 4: Start the local network**

```bash
./scripts/multinode-local-testnet.sh
```

This command essentially creates a local network of three validators running in the background.

## Logs

Validator1: screen -r validator1

Validator2: screen -r validator2

Validator3: screen -r validator3

CTRL + A + D to detach

## Directories

Validator1: `.oraid/validator1`

Validator2: `.oraid/validator2`

Validator3: `.oraid/validator3`

## Ports

"x, x, x, x, rpc, p2p, x"

Validator1: `1317, 9090, 9091, 26658, 26657, 26656, 6060`

Validator2: `1316, 9088, 9089, 26655, 26654, 26653, 6061`

Validator3: `1315, 9086, 9087, 26652, 26651, 26650, 6062`

Ensure to include the `--home` flag or `--node` flag when using a particular node.

## Examples

Validator2: `oraid status --node "tcp://localhost:26654"`

Validator3: `oraid status --node "tcp://localhost:26651"`

or

Validator1: `oraid keys list --keyring-backend test --home $HOME/.oraid/validator1`

Validator2: `oraid keys list --keyring-backend test --home $HOME/.oraid/validator2`


# Wallet


# OWallet

## OWallet: Cosmos x EVM in one Wallet&#x20;

OWallet supports both Cosmos-based and EVM-based networks including Cosmos Hub, Oraichain, Osmosis, Juno, Ethereum, BSC, and more.&#x20;

OWallet is developed based on Keplr and MetaMask source code and currently maintained by Oraichain Labs.&#x20;

Source code: <https://github.com/oraichain/owallet>&#x20;

OWallet website: [https://owallet.dev](https://owallet.dev/)&#x20;

(You can create a pull request to add your network)

**Supporting chains:** Oraichain, **Injective**, OraiBridge, Kawaiiverse Cosmos,  Kawaiiverse EVM, **Cosmos Hub**, **Osmosis**, **Juno, Noble, Bitcoin-segwit,** **BNBChain, Ethereum, TRON.**&#x20;

## Key Features:&#x20;

### OWallet’s key features:

**OWallet mobile features**

* Support managing multiple accounts, easily switching between one to another
* Create a new wallet with Mnemonic, import the existing wallet with a mnemonic, private key, or ledger
* Transfer tokens within chains
* Browse to other dApps: OraiDEX, OraiScan, Orchai, etc.
* Manage a variety of assets associated with the user's wallet: Buy, transfer, view balances, and check real-time prices and volumes..
* Manage your stakings on Mainnet (delegation) and claim rewards&#x20;
* View transaction history, and get notifications with all of the balance changes.&#x20;
* Incoming: Universal Swap

**OWallet extension**

* Support managing multiple accounts, easily switching between one to another
* Create a new wallet with the mnemonic, import the existing wallet with a Mnemonic, private key, or ledger
* Transfer tokens within chains
* Manage a variety of assets: View balance & transfer
* Manage networks: Add and remove
* Incoming: Universal Swap

## Sign  in with Owallet&#x20;

### Install Owallet

App Store: [IOS](https://apps.apple.com/vn/app/owallet/id1626035069)

Google Play Store: [Android](https://play.google.com/store/apps/details?id=com.io.owallet)

Google Web Store: [Extension](https://chrome.google.com/webstore/detail/owallet/hhejbopdnpbjgomhpmegemnjogflenga)

### Sign in to your wallet

To sign in, you have 3 options with Owallet as below.

![](/files/OvYXRiYVuXOzP2ZpcgpI)

A default wallet will be created on Oraichain if you choose to create a new wallet. Make sure to note the Mnemonic phrases down and keep it safe in case you need to import your wallet elsewhere.&#x20;

Note that you should not share Mnemonic/Private Key with anyone else including Oraichain members. \ <br>


# Price Feed


# CW Oracle Hub

## Introduction

The CW Oracle Hub is a crucial component of the Oraichain ecosystem that enables smart contracts to securely access and validate external data sources, particularly AI APIs. It serves as a bridge between blockchain smart contracts and off-chain data, ensuring data reliability and security through a decentralized validation mechanism.

## How It Works

### Core Components

1. **Price Feed Contract**
   * Manages and stores price data from various sources
   * Handles price updates and validation
   * Provides query interfaces for smart contracts to access price data
2. **Validator Network**
   * Validators collect and verify data from external sources
   * Execute test cases to ensure data quality
   * Participate in consensus for data validation
3. **Test Case System**
   * Allows users to define test cases for data validation
   * Ensures data quality and reliability
   * Provides flexibility in validation requirements

### Data Flow

1. **Request Initiation**
   * Smart contracts or users initiate data requests
   * Specify required data sources and test cases
   * Set validation parameters
2. **Data Collection**
   * Validators fetch data from specified sources
   * Execute test cases on the collected data
   * Validate data against predefined criteria
3. **Consensus & Storage**
   * Validators reach consensus on data validity
   * Validated data is stored on-chain
   * Results are made available to requesting contracts

### Integration with Smart Contracts

To integrate with the CW Oracle Hub, smart contracts need to:

1. Set the CW Oracle Hub address as admin
2. Implement the required message types
3. Handle price feed updates

Example integration:

```rust
// msg.rs
#[cw_serde]
pub enum SudoMsg {
    AppendPrice {
        key: String,
        price: Uint128,
        timestamp: u64,
    },
}

// contract.rs
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn execute(deps: DepsMut, _env: Env, msg: SudoMsg) -> Result<Response, ContractError> {
    match msg {
        ExecuteMsg::AppendPrice {
            key,
            price,
            timestamp,
        } => append_price(deps, info, key, price, timestamp),
    }
}
```

## Benefits

1. **Decentralized Validation**
   * Multiple validators ensure data reliability
   * No single point of failure
   * Transparent validation process
2. **Flexible Testing**
   * Customizable test cases
   * Quality assurance for data sources
   * Adaptable to different use cases
3. **Secure Integration**
   * Trustless data access
   * On-chain verification
   * Protected against data manipulation

## Use Cases

The CW Oracle Hub is particularly useful for:

1. **DeFi Applications**
   * Price feeds for trading
   * Asset valuation
   * Market data integration
2. **AI Services**
   * AI model outputs validation
   * Machine learning predictions
   * Data quality assurance
3. **Cross-chain Applications**
   * Multi-chain data synchronization
   * Cross-chain price feeds
   * Interoperable data access


# VRF 2.0


# Introduction to Oraichain VRF 2.0

#### Currently available on Oraichain Mainnet 2.0, supporting most prominent blockchains: BNB Chain, Ethereum, Polygon, Solana, Cosmos, Fantom, Polkadot and Avalanche.

**Please** [**contact us** ](https://landing.mailerlite.com/webforms/landing/t0c1f1)**for more information.**

## **The need for provably-fair randomness in the crypto world**

Random number generators (RNG) are utilized across a multitude of fields including academia, investment back-testing, and gaming. In the crypto space, the need for randomness is also apparent, as astute users and investors demand a bias-free distribution of opportunity. This is where **VRF** **(Verifiable Random Function)** comes into play. It serves as a blockchain oracle for smart contracts by which applications can generate unpredictable values with on-chain proof ensuring none of the involved parties tampered with the outcomes.

As a result, **VRF** plays an important role in the transparency and fairness of decentralized applications as well as normal applications. Utilizations include such as:

* NFT/ game item creation with varied rarities
* Winning odds for gambling/ casino-like projects
* Selecting the winner(s) for airdrop or whitelisting
* Selecting a representative sample concerning the mechanism of consensus
* Randomly assigning duties and resources
* And many more!

## **Current shortcomings of VRF**

VRF is widely trusted because, at its core, this solution solves the transparency problem by decentralizing the validation process of randomness generation.

![How current VRF works](/files/XTpEcdoA8mk3upejMpKX)

Each validator holds his or her own public key with which the collective group signature is generated. Similarly, a group signature is formed to validate the creation of a random value, or a set of it. It would appear that this model ensures tamper-proof unpredictability by delegating the verification process to a neutral party i.e. the validators. However, it is certain that the creation of the random value(s) and the verification of group signature still happens off-chain, which may hinder true decentralization and transparency.

Additionally, there is also a possibility that malicious validators can purposely send invalid data to undermine the randomness generation process, thereby delaying it.

![How a VRF can be abused](/files/hYVXsPfbY3d533XCjVTZ)

This may not seem problematic at first glance, but considering the characteristics of a project’s underlying blockchain consensus mechanism, validators (or miners) can leverage the delay to perform rewrite attacks, making a new VRF output that may work in their favor. By the same token, new random outputs can also be forcefully rerolled or manipulated via chain reorganization attacks, which can take full advantage of the said delay and pose a threat to VRF users.

In the worst-case scenario, a scheming VRF provider can also connive with its validators to agree upon a predetermined value under the facade of transparency and decentralization.

![Current VRF has the ability to skew random results in its own favor](/files/GgxcY2W3QyoV6wGz548O)

Although there have not been any formal records of a VRF provider and its validators conspiring against end-users leading to substantial financial loss and volatility, this risk is indeed palpable considering the current randomness generation process and group signature verification still function off-chain.

## Oraichain VRF 2.0

As a devoted supporter of decentralization, Oraichain has undergone extensive research and development to overcome the previously mentioned shortcomings of VRF with Oraichain VRF 2.0.

First, to verify validators’ signatures and create a group signature on-chain, we bind a pairing-based threshold cryptosystem library to our VRF smart contracts. When a request for randomness comes, each validator of the Oraichain VRF subnetwork will create a signature locally with the given seeding input number and the current round number. Next, the validators submit the signatures to the smart contract, at which the signatures will be validated against the input and the public keys of these validators.

After collecting enough signatures (based on a predefined threshold), the smart contract will automatically recover the final group signature, which will also be verified against the group public key. If it is valid, then the contract will apply a simple SHA256 hash function to the signature to produce the randomness value.

![How all shared parts of Oraichain VRF 2.0 function on-chain](/files/6GpFkZi2BlfvSMtXqZOZ)

Each signature contribution must be verified on-chain before storing. Anyone can also validate the group signature by making a simple query to the Oraichain’s smart contract, and it will return either true or false for the requested round.

**With this framework, Oraichain VRF 2.0 is the first-ever subnetwork that provides unpredictable, publicly verifiable, and bias-resistant random values in a fully decentralized manner.**


# Get a Random Value from API

This section showcases how to get a random value inside a smart contract using Oraichain VRF 2.0

## Prerequisite

Before integrating Oraichain VRF 2.0 into your tech stack, you need to install **Oraichain cosmosjs library**. Kindly follow the steps as demonstrated [here](https://www.npmjs.com/package/@oraichain/cosmosjs).

## Integration steps

### For Back-end Usage

#### Step 1: **Import Oraichain cosmosjs library**

```smali
const Cosmos = require("@oraichain/cosmosjs").default;

const lcdUrl = "https://lcd.orai.io";
const chainId = "Oraichain";
const mnemonic = "foo bar";
const requestFees = “100”;

const message = Cosmos.message;
const cosmos = new Cosmos(lcdUrl, chainId);
const childKey = cosmos.getChildKey(mnemonic);
const sender = cosmos.getAddress(mnemonic);

cosmos.setBech32MainPrefix('orai');
```

#### **Step 2:** Request a random transaction

```
const input = Buffer.from(
       JSON.stringify({
           request_random: {
               input: btoa(userInput),
           },
       })
   );
 
const txBody = getHandleMessage(contract, input, sender, requestFees);
const response = await cosmos.submit(childKey, txBody, "BROADCAST_MODE_BLOCK", isNaN(fees) ? 0 : parseInt(fees), gas);
```

Enter a string value of your preference at ***userInput***. You will see the fee for your request at ***requestFees***. Also, maximum gas and tx fee need to be decided before each request.

:warning: In the unlikely case that your request takes too long to respond, try switching "**BROADCAST\_MODE\_BLOCK"** to ***"*****BROADCAST\_MODE\_SYNC"**, and use tx hash to query until it is included on-chain.

Regarding how to query tx hash, please refer to [this example](https://lcd.orai.io/cosmos/tx/v1beta1/txs/%7Btx_hash%7D) or [this](https://lcd.orai.io/cosmos/tx/v1beta1/txs/397FAFB6973CC0717773290E3F0A0FF2101EDD4689AD983052C60AA3CF8AA5C0).

#### Step 3: Get a random round number

```
const round = response.tx_response.logs[0].events[1].attributes[3].value;
```

#### Step 4: **Get the information from a round**

```
const queryRoundInput = JSON.stringify({
       get_round: {round: parseInt(round)},
   });
 
   const roundOutput = await cosmos.get(`/wasm/v1beta1/contract
/${contract}/smart/${Buffer.from(queryRoundInput).toString("base64")}`);
```

***contract*** is the contract address of the VRF issued by Oraichain and can be reviewed on Oraiscan any time\*\*.\*\*

If the round result has not displayed the randomness output, you just need to wait for some time before querying again.

### **For browser usage**

#### **Step 1: Import Oraichain cosmosjs library**

```
import Cosmos from "@oraichain/cosmosjs";
const lcdUrl = "https://lcd.orai.io";
const chainId = "Oraichain";
const requestFees = “100”;

const message = Cosmos.message;
const cosmos = new Cosmos(lcdUrl, chainId);
```

#### Step 2: Import keystation for wallet use by creating a new js file

```
// @ts-nocheck
/* eslint-disable eqeqeq */
// Find Left Boundry of the Screen/Monitor
function FindLeftScreenBoundry() {
   // Check if the window is off the primary monitor in a positive axis
   // X,Y                  X,Y                    S = Screen, W = Window
   // 0,0  ----------   1280,0  ----------
   //     |          |         |  ---     |
   //     |          |         | | W |    |
   //     |        S |         |  ---   S |
   //      ----------           ----------
   if (window.leftWindowBoundry() > window.screen.width) {
       return window.leftWindowBoundry() - (window.leftWindowBoundry() - window.screen.width);
   }
 
   // Check if the window is off the primary monitor in a negative axis
   // X,Y                  X,Y                    S = Screen, W = Window
   // 0,0  ----------  -1280,0  ----------
   //     |          |         |  ---     |
   //     |          |         | | W |    |
   //     |        S |         |  ---   S |
   //      ----------           ----------
   // This only works in Firefox at the moment due to a bug in Internet Explorer opening new windows into a negative axis
   // However, you can move opened windows into a negative axis as a workaround
   if (window.leftWindowBoundry() < 0 && window.leftWindowBoundry() > window.screen.width * -1) {
       return window.screen.width * -1;
   }
 
   // If neither of the above, the monitor is on the primary monitor whose's screen X should be 0
   return 0;
}
 
window.leftScreenBoundry = FindLeftScreenBoundry;
 
function PopupCenter(url, title, w, h) {
   const newWindow = window.open(
       url,
       title,
       "resizable=1, scrollbars=1, fullscreen=0, height=" +
       h +
       ", width=" +
       w +
       ", screenX=" +
       window.leftScreenBoundry +
       " , left=" +
       window.leftScreenBoundry +
       ", toolbar=0, menubar=0, status=1"
   );
   return newWindow;
}
 
function openWindowV1(type, payload, account = "", self) {
   console.log(`open ${self.client}`);
 
   // The account parameter is required for users having multiple keychain accounts.
   let apiUrl = "";
   switch (type) {
       case "signin":
           apiUrl = "signin";
           break;
       case "transaction":
           apiUrl = "tx";
           break;
       default:
           apiUrl = "signin";
           break;
   }
 
   return PopupCenter(
       self.keystationUrl +
       "/" +
       apiUrl +
       "?account=" +
       encodeURIComponent(account) +
       "&client=" +
       encodeURIComponent(self.client) +
       "&lcd=" +
       encodeURIComponent(self.lcd) +
       "&path=" +
       encodeURIComponent(self.path) +
       "&payload=" +
       encodeURIComponent(JSON.stringify(payload)),
       "",
       "470",
       "760"
   );
}
 
function openWindowV2(type, payload, account = "", self) {
   console.log(`open ${self.client}`);
 
   // The account parameter is required for users having multiple keychain accounts.
   let apiUrl = "";
   switch (type) {
       case "signin":
           apiUrl = "signin";
           break;
       case "transaction":
           apiUrl = "transaction";
           break;
       case "ai-request":
           apiUrl = "ai_request/set";
           break;
       default:
           apiUrl = "auth";
           break;
   }
 
   const network = "Oraichain";
   return PopupCenter(
       self.keystationUrl +
       "/" +
       apiUrl +
       "?lcd=" +
       encodeURIComponent(self.lcd) +
       "&raw_message=" +
       encodeURIComponent(JSON.stringify(payload)) +
       "&signInFromScan=true" +
       "&network=" +
       network,
       "",
       "470",
       "760"
   );
}
 
export default class Keystation {
   constructor(params) {
       if (!params) {
           return;
       }
       const { client, lcd, path, keystationUrl } = params;
       this.client = client;
       this.lcd = lcd;
       this.path = path;
 
       this.keystationUrl = keystationUrl;
   }
 
   openWindow(type, payload, account = "") {
       const self = this;
       return process.env.REACT_APP_WALLET_VERSION == 2 ? openWindowV2(type, payload, account, self) : openWindowV1(type, payload, account, self);
   }
}
 
export const myKeystation = new Keystation({
   client: "https://api.wallet.orai.io",
   lcd: "https://lcd.orai.io",
   path: "44/118/0/0/0",
   keystationUrl: "https://api.wallet.orai.io",
});
```

#### Step 3: **Create a randomness request**

```
const input = Buffer.from(
       JSON.stringify({
           request_random: {
               input: btoa(userInput),
           },
       })
   );
 
const {privateKey, chainCode, network} = await getChildKey();
const childKey = fromPrivateKey(Buffer.from(privateKey), Buffer.from(chainCode), network);
 
const sender = cosmos.getAddress(childKey);
 
 
const txBody = getHandleMessage(contract, input, sender, requestFees);
const response = await cosmos.submit(childKey, txBody, "BROADCAST_MODE_BLOCK", isNaN(fees) ? 0 : parseInt(fees), gas);
```

Function ***getChildKey()*** is as follow:

```
   // const popup = window.open(`${config.walletapi}/auth?signInFromScan=true`, "", "resizable=1, scrollbars=1, fullscreen=0, width=470, height=760");
   const popup = myKeystation.openWindow("auth", "");
 
   return new Promise((resolve, reject) => {
       const loop = setInterval(function() {
           if (!popup) {
               clearInterval(loop);
               reject("window-blocked");
           } else if (popup.closed) {
               clearInterval(loop);
               reject("window-closed");
           }
       }, 500);
       const handler = e => {
           if (e.data.privateKey && e.data.chainCode && e.data.network) {
               clearInterval(loop);
               window.removeEventListener("message", handler);
               resolve(e.data);
           }
       };
       window.addEventListener("message", handler);
   });
};
```

#### **Step 4: Repeat the previously mentioned step 3 and 4 to get the random value and round information**


# Get VRF Value from different networks

This section showcases how to get a random value inside a smart contract from different blockchain networks like BSC and Fantom, etc.

![How VRF values are generated from different netw](/files/Qi2d3KsuJwUHwGH4nue5)

![How VRF values are generated from a different network](/files/cDJwjNNQDZlYASJZlppz)

VRF execution flow from Binance Smart Chain (BSC), Avalanche (AVAX) and Fantom (FTM):

VRF execution flow from BNB Chain (formerly Binance Smart Chain), Avalanche (AVAX) and Fantom (FTM):

* First of all, smart contract users must pay fees (in OraiToken with BSC network and native tokens with AVAX and FTM) and make a request to generate random numbers with VRFOracleOraichain contract
* Next, the VRFOracleOraichain contract checks the request of the user and the fee, if everything is verified, the VRFOracleOraichain will generate a corresponding reqId and return it to the user.
* A keeper bridge will listen for events on the VRFOracleOraichain smart contract and make a random generated request to Oraichain network. The random value takes the input from the seed provided by the smart contract user.
* Oraichain Mainnet uses submitted information to generate random numbers and proofs. After generating a random number and proof, the Oraichain Mainnet sends that data back to the keeper bridge.
* The keeper bridge receives the information and fullfills the VRFOracleOraichain contract, then the random number will be sent back to the user via consumer address and reqId.
* Note: Only authorized keepers can fulfill the VRFOracleOraichain smart contract. The random number is guaranteed by the signatures of Oraichain mainnet's validators.
* First of all, smart contract users must pay fees (in OraiToken with BSC network and native tokens with AVAX and FTM) and make a request to generate random numbers with VRFOracleOraichain contract
* Next, the VRFOracleOraichain contract checks the request of the user and the fee, if everything is verified, the VRFOracleOraichain will generate a corresponding reqId and return it to the user.
* A keeper bridge will listen for events on the VRFOracleOraichain smart contract and make a random generated request to Oraichain network. The random value takes the input from the seed provided by the smart contract user.
* Oraichain Mainnet uses submitted information to generate random numbers and proofs. After generating a random number and proof, the Oraichain Mainnet sends that data back to the keeper bridge.
* The keeper bridge receives the information and fullfills the VRFOracleOraichain contract, then the random number will be sent back to the user via consumer address and reqId.
* Note: Only authorized keepers can fulfill the VRFOracleOraichain smart contract. The random number is guaranteed by the signatures of Oraichain mainnet's validators.

To generate a VRF value from your blockchain of choice, your contract needs to inherit VrfOracleOraichain and define 2 required functions:

To generate a VRF value from your blockchain of choice, your contract needs to inherit VrfOracleOraichain and define 2 required functions:

1. **randomnessRequest**: initiate a request to generate random numbers
2. **fulfillRandomness**: will perform receiving and verifying data.

* :warning:Your contract needs to have enough ORAI or the needed token to make the request for a random number.
* :warning:Some of the values in the example below need to be particularly correct for each network.

## Examples for best practices

### ORAI token based VRF blockchain oracle (BNB Chain)

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


interface IERC20 {

    function transfer(address recipient, uint256 amount) external returns (bool);

    function approve(address spender, uint256 amount) external returns (bool);
}


interface IVRFOracleOraichain {
    function randomnessRequest(uint256 _seed, bytes calldata _data) external returns (bytes32 reqId);

    function getFee() external returns (uint256);
}

contract VRFConsumerExample {

    address public orai;
    address public oracle;
    uint256 public random;
    bytes32 public reqId;

    constructor (address _oraiToken, address _oracle) public {
        orai = _oraiToken;
        oracle = _oracle;
    }

    function randomnessRequest(uint256 _seed) public {
        IERC20(orai).approve(oracle, IVRFOracleOraichain(oracle).getFee());
        bytes memory data = abi.encode(address(this), this.fulfillRandomness.selector);
        reqId = IVRFOracleOraichain(oracle).randomnessRequest(_seed, data);
    }

    function fulfillRandomness(bytes32 _reqId, uint256 _random) external {
        require(msg.sender == oracle, "Caller must is oracle");
        random = _random;
    }

    function setOracle(address _oracle) public {
        oracle = _oracle;
    }

    function clearERC20(IERC20 token, address to, uint256 amount) external {
        token.transfer(to, amount);
    }
}

```

### Native token based VRF blockchain oracle (Avalanche, Fantom, etc.)

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


interface IVRFOracleOraichain {
    function randomnessRequest(uint256 _seed, bytes calldata _data) external payable returns (bytes32 reqId);

    function getFee() external returns (uint256);
}

contract VRFConsumerExampleNativeFee {

    address public oracle;
    uint256 public random;
    bytes32 public reqId;

    constructor (address _oracle) public payable {
        oracle = _oracle;
    }

    fallback() external payable {}

    function randomnessRequest(uint256 _seed) public {
        uint256 fee = IVRFOracleOraichain(oracle).getFee();
        bytes memory data = abi.encode(address(this), this.fulfillRandomness.selector);
        reqId = IVRFOracleOraichain(oracle).randomnessRequest.value(fee)(_seed, data);
    }

    function fulfillRandomness(bytes32 _reqId, uint256 _random) external {
        require(msg.sender == oracle, "Caller must is oracle");
        random = _random;
    }

    function clearNativeCoin(address payable _to, uint256 amount) public payable {
        _to.transfer(amount);
    }

}

```

#### Here are more tested examples for [Fantom](https://ftmscan.com/address/0x943Df3CF0796A902ab37ceaA0de2ce694339EF5f#code) and [Avalanche](https://snowtrace.io/address/0x3c58947e167b87520c2e9210847939a4b9660f4d#code) developers.

### General guideline for smart contract users&#x20;

* There are currently two payment methods for Oraichain VRF service, the first of which requires Orai token for Binance Smart Chain; the latter requires native token for Avalanche and Fantom Opera. You must therefore use your wallet accordingly.
* Next, copy either of the example codes above (respective to your network of choice) into Remix IDE to compile and deploy your smart contract.&#x20;
* After the contract is deployed, you need to transfer an [amount of fee](/developer-guides/vrf/get-a-random-value-from-api/contract-addresses-and-pricing) into it in order to request VRF value(s).
* You will find yourself using 2 important functions namely *randomnessRequest* and *fulfillRandomness*
* Run *randomnessRequest* function to request a random value. Each request is equivalent to a byte32 requestId retrieved from the oracle.
* *fulfillRandomness* is a callback function, which serves as a VRF value receiver. **It is imperative that your smart contract has a&#x20;*****fulfillRandomness*****&#x20;function with the input that resembles the examples above**. Otherwise, the VRF value-generating process shall be reverted.
* `require(msg.sender == oracle, "Caller must is oracle")`: your *fulfillRandomness* function neecds to make sure your VRF caller is affiliated with Oraichain.
* [⚠️](https://emojipedia.org/warning/)Note: You may need to use the function *clearERC20* or �*clearNativeCoin* to keep your asset from getting stuck &#x20;
* There are currently two payment methods for Oraichain VRF service, the first of which requires an Orai token for Binance Smart Chain; the latter requires a native token for Avalanche and Fantom Opera. You must therefore use your wallet accordingly.
* Next, copy either of the example codes above (respective to your network of choice) into Remix IDE to compile and deploy your smart contract.&#x20;
* After the contract is deployed, you need to transfer an [amount of fee](/developer-guides/vrf/get-a-random-value-from-api/contract-addresses-and-pricing) into it in order to request VRF value(s).
* You will find yourself using 2 important functions namely *randomnessRequest* and *fulfillRandomness*
* Run *randomnessRequest* function to request a random value. Each request is equivalent to a byte32 requestId retrieved from the oracle.
* *fulfillRandomness* is a callback function, which serves as a VRF value receiver. **It is imperative that your smart contract has a&#x20;*****fulfillRandomness*****&#x20;function with the input that resembles the examples above**. Otherwise, the VRF value-generating process shall be reverted.
* `require(msg.sender == oracle, "Caller must is oracle")`: your *fulfillRandomness* function neecds to make sure your VRF caller is affiliated to Oraichain.
* [⚠️](https://emojipedia.org/warning/)Note: You may need to use the function *clearERC20* or �*clearNativeCoin* to keep your asset from getting stuck &#x20;

### Specific example

Say you have to pick 3 winners out of 1000 participants. First, number the 1000 participants (from 1 to 1000). Then use fuction randomPlayer like the example below after getting a VRF value from Oraichain.

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


interface IVRFOracleOraichain {
    function randomnessRequest(uint256 _seed, bytes calldata _data) external payable returns (bytes32 reqId);

    function getFee() external returns (uint256);
}

contract VrfOracleOraichainExample {

    address public oracle;
    uint256 public random1;
    uint256 public random2;
    uint256 public random3;
    bytes32 public reqId;

    constructor (address _oracle) public {
        oracle = _oracle;
    }

    function randomnessRequest(uint256 _seed) public {
        uint256 fee = IVRFOracleOraichain(oracle).getFee();
        bytes memory data = abi.encode(address(this), this.fulfillRandomness.selector);
        reqId = IVRFOracleOraichain(oracle).randomnessRequest.value(fee)(_seed, data);
    }

    // get three randomnesses range(0:1000) from Oraichain randomness
    function fulfillRandomness(bytes32 _reqId, uint256 oraichainRandomness) public {
        random1 = random(oraichainRandomness, 1000);
        random2 = random(random1, 1000);
        random3 = random(random2, 1000);
    }

    function random(uint256 _oraiNumber, uint256 _weight) public returns (uint256){
        return uint256(keccak256(abi.encodePacked(_oraiNumber, block.difficulty, block.timestamp, block.coinbase, block.number, msg.sender))) % (_weight);
    }
} 
```


# Contract Addresses and Pricing

This section displays the addresses whereby VRF requests can be made and the needed fee for each request on its corresponding blockchain network.

**Please** [**contact us**](https://landing.mailerlite.com/webforms/landing/t0c1f1) **for more information regarding extensive use and further queries**

### **BSC Mainnet**

<table><thead><tr><th width="393.33387430600715">Address</th><th>0xc90095557d0B60d13E28BD0391050247088A0EE6</th></tr></thead><tbody><tr><td>Service</td><td>0.2 ORAI</td></tr></tbody></table>

### BSC Testnet

| Address      | 0x731b8bab775d3768D1D25Aa926D729db4e91a517                                            |
| ------------ | ------------------------------------------------------------------------------------- |
| Faucet token | <https://testnet.bscscan.com/address/0xe07D3c721F1f26fB49e93DE77589fAC2fD963780#code> |
| Service      | 0.2 ORAI                                                                              |

### **Avalanche**

<table><thead><tr><th width="150">Address </th><th>0x6b5866f4B9832bFF3d8aD81B1151a37393f6B7D5</th></tr></thead><tbody><tr><td>Service</td><td>0.015 AVAX</td></tr></tbody></table>

### **Avalanche Testnet**

| Address | 0x82174e5d7f2a4cCbCC9D14b3930C8935541e6222 |
| ------- | ------------------------------------------ |
| Service | 0.015 AVAX                                 |

### Fantom

| Address | 0xd73CfDBdC35BF6709BF261171021C87a3c09E3e2 |
| ------- | ------------------------------------------ |
| Service | 0.8 FTM                                    |

### **Fantom** Testnet

| Address | 0xf8E8E574fa6f0E0797F05fFeA17FE231ACD7d81b |
| ------- | ------------------------------------------ |
| Service | 0.8 FTM                                    |

### Ethereum Mainnet

| Address | 0x73d63CDa1CE9e27DE283Bd5019b0dBefB0af87FD |
| ------- | ------------------------------------------ |
| Service | 1 ORAI                                     |


# Validate a Group Signature

This section showcases how to validate a group signature using Oraiscan

You can always check the validity of a group signature generated by **Oraichain VRF 2.0** via [**Oraiscan**](https://scan.orai.io/randomness/orai15lv4hxxqew2jhfayfmad7y40zfr8zmgfulqdxj)**.**

The field ***Verified*** shows you the status a group signature:

1. ***True*** means the group signature you searched had been successfully aggregated and verified on-chain with Oraichain Smart Contract
2. ***False*** means the group signature you searched are either being verified or did not have the required signatures to form a group signature

![Easily check the validity of a group signature without the knowledge of smart contract](https://github.com/oraichain/docs/blob/master/developer-guides/.gitbook/assets/1Untitled%20Project1a931ff9.autosave.gif)

Search for a round of your choice at the field ***Search*****.** Note that the round value entered should not be larger than the current round displayed.


# Security Remarks

1\. The only accepted callback function is *fulfillRandomness*(bytes32 \_reqId, uint256 \_random) with the function selector being *0x1f1f897f*. This is required in order to avoid malicious callbacks.

2\. The *fulfillRandomness* function is able to verify the VRF value and minimize the amount of keep3rs that can fulfill data with the following check functions:

* `require(isFulfiller[msg.sender], "Must is fulfiller")` : fulfillRandomness function guarantees that only a fixed amount of keep3rs are able to fulfill data ;
* `require(isNode(validator), "Forbidden validator")`: The VRF value is guaranteed to be generated from Oraichain's validators.

3\. The gas limit is 800,000. This means that any fulfilling or callback request exceeding the limit amount can lead to tx getting reverted, at which case the blockchain oracle will ignore and refuse to execute such request.


# API Reference

## Index

#### Constructors

|              | Description               |
| ------------ | ------------------------- |
| Constructors | Oracle vrf initialization |

#### Functions

|                   | Description                                                   |
| ----------------- | ------------------------------------------------------------- |
| randomnessRequest | Make a request to generate random numbers                     |
| fulfillRandomness | VRF Oracle will call back when receiving valid VRF proof data |

## Constructors

```
constructor (address _oraiToken, address _oracle) public {
    fee = 1000000000000000000;
    orai = _oraiToken;
    oracle = _oracle;
}
```

## �Funtions

#### randomnessRequest

```
function randomnessRequest(uint256 _seed, bytes memory _data) public returns (bytes32 reqId);
```

* \_seed : a random number provided by the caller
* \_data : the result of callbackAddress and callbackFunc after encoding

```
bytes memory data = abi.encode(address(this), this.fulfillRandomness.selector);
```

* callbackAddress: smart contract address receive random number
* callbackFunct : hen a function is called, the first 4 bytes of `calldata` specifies which function to call.

#### fulfillRandomness

```
function fulfillRandomness(bytes32 reqId, bytes calldata _data, uint8 v, bytes32 r, bytes32 s) external;
```

* reqId: request id generated when calling function randomnessRequest
* \_data: includes callbackAddress and callbackFunc after encode
* v,r,s: proof vrf


# Get support from Oraichain team

For further queries and support, you can always reach us via email at **<contact@orai.io>** or Telegram at [**https://t.me/oraitech**](https://t.me/oraitech)


# OraiDEX

Oraichain has evolved into ***AI Layer 1 for Data Economy and Oracle Services*** with high throughput, more decentralization, and supporting both Cosmwasm and EVM smart contracts. In order to bring more liquidity, users, and transactions to Oraichain, OraiDEX is built as the first DEX on Oraichain.

**OraiDEX** is a **CosmWasm smart contract-based** decentralized exchange platform with **multichain interoperability, optimal speed, and a lot of liquidity options for users**.

## Features <a href="#id-49d2" id="id-49d2"></a>

**Token bridging:** moving native token or data from Bitcoin, Ethereum, TON Network, BSC, and other networks to Oraichain and vice versa in just one step!\
**OraiSwap:** easy token swapping, streamlined liquidity provision and farming with profitable APR\
**IBC compatibility:** allowing trustless communication between multiple Cosmos-based chains\
**NFT Bridge:** relocating NFT assets from Oraichain to other networks like Ethereum or Binance Smart Chain and vice versa


# ORAIX Token

**ORAIX** is the governance and utility token of OraiDEX, which is designed to balance its inflation from rewards and spending from utility fees as follows. Note that a portion of utility fees will be burnt. It will be decided by governance voting.

**Utilities:**

1. Pay meta-staking fee (the fee is taken directly from profits)
2. Pay pool creation fee
3. Pay OraiBridge fee
4. Pay NFT Bridge fee
5. Buy airdrop NFT tickets of newly listed projects on OraiDEX

**Governance:**

1. Fee structures
2. Meta-staking policies

## **Token distribution and listing price** <a href="#id-9136" id="id-9136"></a>

**Total supply: 1,000,000,000 ORAIX**

* Staking rewards: 30% (including fairdrop + initial listing)
* Liquidity mining incentives: 50%
* Developer pool: 15%
* Community pool: 5%

**Listing price on OraiDEX will be voted by ORAI holders (below is an example):**

* Listing price: $0.025
* Initial circulating supply: 20,000,000 ORAIX
* Initial market cap: $500K
* Diluted market cap: $25M

***Staking rewards, liquidity mining incentives, and developer pool will be vested in 5+ years.***

<br>


# OBridge

## OBridge

OBridge functions as a decentralized cross-chain bridge, seamlessly enabling interoperability and liquidity between Bitcoin, Ethereum, TON Network, BNB Chain, Oraichain, and 160+ other blockchains within the Cosmos ecosystem (Cosmos, Osmosis, Injective).

OBridge is now live and integrated directly into OraiDEX's AMM, accessible at <https://app.oraidex.io/universalswap>. OBridge will continue to expand its reach by supporting even more blockchains and having more integrations soon.

## Credits

🛠 Built by Oraichain Labs — if you like our tools, please consider delegating to [OWallet validators ⚛️](https://owallet.dev/validators)


# OraiBTC

OraiBTC is a subnetwork running on Oraichain Mainnet, designed to be a decentralized bridge for seamless BTC deposits into the Oraichain ecosystem. Inspired by Nomic’s design, it’s specifically tailored to Oraichain’s needs, offering an efficient and affordable way to transfer your Bitcoin to Oraichain & other networks.

OraiBTC has been fully integrated into OraiDEX UI at <https://app.oraidex.io/bridge>.&#x20;


# TON Bridge

## TON Bridge

![](/files/3nG4782DyfXjENGY2NJX)

🎯 This document describes the goals and expectations of TON Bridge to the Cosmos Ecosystem. It also outlines the MVP definition of the project as well as providing several top-level designs of the system.

***

## Overview

`TON Bridge` aims to create a trustless tunnel that allows users to bridge and swap TON tokens to the Cosmos Ecosystem and vice versa in one step.

The system makes sure to validate every transaction using light clients and merkle proofs via decentralized relayers, opening endless possibilities bringing the Cosmos Ecosystem to TON and vice versa.

Anyone can become a relayer who validates transactions and receive relayer fees as a reward.

## Abstraction

### Problem statement

* No known-to-date TON Bridge to the Cosmos Ecosystem.
* TON is currently not IBC-compatible.
* The current official TON Bridge to and from EVM networks are non-trustless & closed-source
* The RSquad team wrote two papers to design a trustless bridge system, but:
  * The source is outdated, buggy, and not production-ready.
  * TON → Cosmos Ecosystem:
    * There’s no Rust or Go library that fully implements the RSquad’s paper.
    * There’s also no CosmWasm contract that implements the paper.
  * Cosmos Ecosystem → TON:
    * No Func contract that implements the trustless system.
    * The design and implementation must match with the consensus model of Cosmos Ecosystem, not Ethereum.

💡 We need to design and implement a trustless, decentralized, and verifiable system that connects TON with the Cosmos Ecosystem.

### Understanding concepts

Our trustless TON Bridge is heavily influenced by [RSquad Blockchain Labs Trustless System](#rsquad-blockchain-labs-trustless-system)

About TON blockchain, recommend to check on our articulated document [TON Blockchain 101](/developer-guides/oraidex/obridge/ton-bridge/ton-blockchain-101)

Light client concept which is used to verify blocks, validators from both Oraichain and Ton Network is inspired from [IBC client standard](#understand-cosmos--ibc)

#### TON → Cosmos

* Each TON transaction is either included in a shard block or a masterchain block
* A shard block reference may or may not be included into a masterchain block.
  * A masterchain block only includes references to the latest shard blocks within a specific logical time.
  * The latest shard block will include references to the previous shard blocks so that these blocks are also verifiable.
  * Example

    ```markdown
    - Has shard block 100, 101, 102 of shard 2000 from logical time 1 to 5.
    - Has shard block 200 of shard 1000.
    - Masterchain block only includes references of shard block 102 and shard 200.
    - Shard block 102 includes a reference to shard block 101, and the shard block 101 includes 100's reference and so on.
    ```
* Each masterchain block is verified by a set of validators (PoS)
* Each masterchain keyblock contains the next set of validators within the 2-hour window after a consensus round has finished.

<details>

<summary>Question: How to process an arbitrary TON transaction for bridging?</summary>

1. Trusted setup - initial trusted validator set when initializing the contracts

   → Have a trusted validator set for validating current consensus round’s masterchain blocks.
2. When the next validator set appear in a keyblock

   1. Validate the keyblock using the current validator set
   2. Update the new validator set by parsing the keyblock

   → Have an updated validator set for validating both current and next consensus round’s masterchain blocks.
3. Validate the target masterchain block using the current active validator set.

   → Have a set of validated masterchain blocks stored on-chain.
4. Validate shard blocks included in the validated masterchain block above using merkle proofs:

   1. The merkle proof’s hash of the shard block referenced in the masterchain must equal to the masterchain’s block hash, which is verified above using the validator signatures.
   2. The remaining shard blocks are recursively verified by proving that its merkle proof’s hash is the block hash of the previously verified shard block.

   → Have a set of validated shard blocks stored on-chain
5. Validate the transaction:

   1. Prove that the transaction merkle proof’s hash of the transaction equals to the verified shard block above.
   2. Parse the transaction data and calculate its tx hash. The hash must match the hash stored in the transaction merkle proof.
   3. The transaction must come from the trusted Bridge Adapter contract on TON.

   → Have the target transaction validated.
6. Process the transaction:

   1. Parse the transaction body and collect data
   2. Validate the data and continue processing.

   → Have the target transaction validated, processed, and stored on-chain to prevent replay attack.

</details>

#### Cosmos → TON

* A full block queried from RPC contains:
  * All kinds of hashes for merkle proof validations from the block header (block hash, app hash,…).
  * Validator addresses and signatures.
  * Proof of packet existence based on key store inside state of blockchain at that block.
* We can use such data to:
  * Verify if a packet data is existed at a specific block based on app hash and proof of packet’s existence. ([ICS23](https://github.com/cosmos/ibc/tree/main/spec/core/ics-023-vector-commitments))\*\*
  * Verify if a block is valid by validating it against the validator signatures.

<details>

<summary>Question: How to process an arbitrary CosmWasm transaction for bridging?</summary>

1. Trusted setup - initial trusted validator set on the CosmWasm based network when initializing the contracts.

   → Have a trusted validator set for validating current block.
2. Validate the block that includes the target transaction:

   1. Use the current validator set, validate against the signatures in the block data.
   2. After validation, store the new validator set.

   → Have the validated block stored on-chain.
3. Validate the transaction:

   1. Hash the raw transaction & compares with target transaction hash (should match)
   2. Get the transaction’s merkle proof.
   3. Calculate the merkle proof’s root hash & compare with the block’s data hash (should match)

   → Have the target transaction validated.
4. Process the transaction:

   1. Parse the transaction body and collect data
   2. Validate the data and continue processing.

   → Have the target transaction validated, processed, and stored on-chain to prevent relay attack.

</details>

### Why we’re making this

With a reported over 700 million monthly active users on Telegram. The evolving of The Open Network (TON) eco-system is undeniable.

The success of top-tier projects like $unibot and $MEVFree (boasting monthly incomes exceeding $5 million, during bear marketing) not only proved high-demand from Telegram users, but also TON eco-system provide a lot success enablers to developers, such as:

* **TON's Native Payment:** with @Wallet
* **Telegram Community Promotion:** de-facto option for Crypto/Blockhain communities
* **Room for enhancing User Experience:** More than Bot + API + Mini App

With rapid growth of TVL of TON (from $71M to $994M in first half of 2024), We (Oraichain Labs) see it a huge potential for DeFi opportunities between Cosmos eco-system & TON eco-system - which currently being limited by official TON Bridge is only support Ethereum & BNB Chain.

* Move assets from across eco-systems natively
* Allow users on TON eco-system to interact with Cosmos eco-system’s DeFi products
* Introduce new liquidity opportunities

### Our Works

| Repository                                            | Description                                                                                                                                                                                                                                                             |
| ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| <https://github.com/oraichain/tonbridge-relayer>      | A decentralized middleware server that bridges the TON blockchain to Oraichain/Cosmos blockchains. It is responsible for delivering packets from TON or Oraichain/Cosmos, and can be compared to an IBC relayer.                                                        |
| <https://github.com/oraichain/ton-contracts>          | Func smart contracts which control Oraichain/Cosmos block validation and transactions, creating a trustless and secure interoperability environment on TON.                                                                                                             |
| <https://github.com/oraichain/tonbridge-cw-contracts> | CosmWasm smart contracts. These contracts are in charge of TON's block validation and transaction management, ensuring a trustless and secure interoperability environment on Oraichain/Cosmos.                                                                         |
| <https://github.com/oraichain/tonlib-rs>              | Rust library that interacts with the TON blockchain. It gives developers the tools they need to interface with the TON blockchain through their Rust apps. This library has been improved and refined for usage in the Cosmwasm contract for cell parsing and encoding. |
| <https://toncenter.orai.io/>                          | A server similar to the LCD server in the Cosmos environment. It is used to query and execute data on the TON blockchain, giving users a reliable interface for dealing with the blockchain.                                                                            |

## Solution Design

### 1. System level

![](/files/IpfavXPN5M6PYTGI5zR8)

### 2. Components level

🎯 [Follow graphics guideline by TON](https://docs.ton.org/contribute/docs/schemes-guidelines)

![](/files/oPuwpcf3q4FxHLsiCq6p)

### 3. Implementation Level

**From TON → Cosmos**

![TON → Cosmos](/files/xcuFJXUbTRD0ENz5w0q5)

**From Cosmos → TON**

![Cosmos → TON](/files/6dpVvGGVxyDV8hTHLkSC)

[Sequence diagrams for verifying TON light client](https://github.com/oraichain/docs/blob/master/developer-guides/oraidex/obridge/ton-bridge/ton-light-clients-verification.md)

## Common failures & recovery methods

#### Relayer

1. RPC nodes from Cosmos stop running due to network or connection errors.
2. Memory leaks.
3. Relayer wallets run out of native coins to pay for the fees.
4. TON’s lite client or Toncenter fails to return responses due to network or connection errors.
5. Cannot query proof due to pruned data.

<details>

<summary>Solutions</summary>

1. Manage RPC nodes using pm2 and notifies via Discord when having problems.
2. Manage the relayer via pm2 to have auto restart if there’s a leak, monitor RAM usage.
3. Use Authz to grant the relayer to spend fees from the granter wallet. Monitor the granter’s wallet balance.
4. The relayer notifies connection errors via Discord.
5. Manually investigate the case via transaction hash and sequence number.

</details>

#### Cosmos → TON

1. Packet is expired.
2. No acknowledgement from TON to clean up data.
3. Cosmos Tx failed but still included in a block.
4. The Jetton Bridge contract runs out of tokens to unlock to the receiver.
5. Cosmos Tx timestamp versus current timestamp gap is larger than the trusting period.

<details>

<summary>Solutions</summary>

1. When packet is timeouted, the Ton contract will emit ack packet for the Cosmos Contract to refund users.
2. If no acknowledgement passed timeout → The relayer will update the packet’s status based on timeout proof → handle manually.
3. Ton Adapter queries the Cosmos contract state with proof to verify if the packet is successful or not.
4. Use a bot to listen to the contract’s balances.
5. Ignore the tx.

</details>

#### TON → Cosmos

* Packet is expired.
* No acknowledgement from Cosmos to clean up data.
* Could not validate and update new validator set.
* The bridge contract runs out of tokens to unlock to the receiver.
* The block’s validator signatures are not greater than 2/3 of the total voting power.

<details>

<summary>Solutions</summary>

1. When packet is time-outed, the Cosmos contract will emit ack packet for the Ton Contract to refund users.
2. If no acknowledgement passed timeout → The relayer will update the packet’s status based on timeout proof → handle manually.
3. Manually update new validator set based on previous round, then update the current round to make it work. @Trung Nguyen Van
4. Use a bot to listen to the contract’s balances.
5. Ignore the tx.

</details>

## References

#### RSquad Blockchain Labs Trustless System:

* [TON -> Cosmos](https://docs.ton.org/trustless-interaction-with-ton_v1.1_23-05-15.pdf)
* [Cosmos -> TON](https://docs.ton.org/ton-trustless-bridge_tvm-and-zk_v1.1_23-05-15.pdf)

#### Understanding TON concept

[TON Blockchain 101](/developer-guides/oraidex/obridge/ton-bridge/ton-blockchain-101)

#### Understand Cosmos / IBC

* `Cosmos` term mentioned above mean Cosmos-based blockchains or Cosmos ecosystem
* IBC specifications
  * [ICS23 Proof merkle format for IBC](https://github.com/cosmos/ibc/tree/main/spec/core/ics-023-vector-commitments)
  * [ICS02 Client Semantics](https://github.com/cosmos/ibc/blob/main/spec/core/ics-002-client-semantics)

## Credits

🛠 Built by Oraichain Labs — if you like our tools, please consider delegating to [OWallet validators ⚛️](https://owallet.dev/validators)

## Disclaimer

> ⚠ **This software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.**

Or plainly spoken - this is a very complex piece of software which targets a bleeding-edge, experimental smart contract runtime. Mistakes happen, and no matter how hard you try and whether you pay someone to audit it, it may eat your tokens, set your printer on fire or startle your cat.

Cryptocurrencies are a high-risk investment, no matter how fancy.


# TON Blockchain 101

🎯 This document attempts to summarize key concepts of TON blockchain. Articulated during process of making TON Bridge by Oraichain Labs developers

## Common terminology

| Term                          | Definition                                                                                                                                                                                                                                                                                                                                            |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| TON actor                     | Like “smart contract”. Even user wallets are contracts. Actor properties (including but not limited to): Unique address; Code; Data ; Balance                                                                                                                                                                                                         |
| Transaction                   | A set of steps to modify actor’s properties. Transactions are ordered.                                                                                                                                                                                                                                                                                |
| Chain                         | Sequence of transactions                                                                                                                                                                                                                                                                                                                              |
| AccountChain                  | Sequence of transactions for a single address                                                                                                                                                                                                                                                                                                         |
| Blocks                        | Batch a set of transactions                                                                                                                                                                                                                                                                                                                           |
| ShardChain                    | A set of blocks including transactions of a set of accounts. Can merge (aggregate) or split ShardChains. Allow up to 2^60 shard chains                                                                                                                                                                                                                |
| Blockchain (called Workchain) | An aggregation of ShardChains with common set of rules. Ton allows many blockchains with diff set of rules (2^32 blockchains)                                                                                                                                                                                                                         |
| MasterChain                   | Chain for multichain state checkpoint. Masterchain blocks - blocks of the masterchain that include shard blocks of different workchains within a logical time (lt) range. A masterchain block does not include all shard blocks of a workchain, but only the highest-seqno shard block in that lt range. Masterchain is also a workchain with wc = -1 |
| Key block                     | Key block is a masterchain block containing prev, cur, and next validator sets                                                                                                                                                                                                                                                                        |

## Quickly TON blockchain

### Consensus algorithm

💡 Refer to [The TON Blockchain is based on PoS consensus](https://gist.github.com/awesome-doge/9bd53050077701e8321d06c0a8ded172) for detail

1. Ton uses BFT → each block should have > 2/3 voting power
2. Split consensus into multiple validation sessions
   1. Each session lasts about 18 hours (config params #15 in base 10)
   2. An election round is created to start a new session
      1. Election process takes around 7 hours (also config params #15)
      2. Send TON using special tx to election contract to participate
      3. After an election, has 2 hours before the session starts (also config params #15) → refund TON if not elected & show list of next validators when querying config & keyblock
3. Number of validators (config params #16 in base 10)
   1. Has a maximum global number of validators (current is 400 vals)
   2. Has a maximum main number of validators for each session. Current is 100 main vals. Chosen from the pool of max validators (pseudorandom)
   3. Main validators validate masterchain blocks
   4. The rest validate shard blocks
   5. Validators of each block is pseudorandom, but best effort to pick as many as possible.

### **Smart Contracts**

* `Components`: \<workchain\_id (1 byte)>\<account\_id (32 bytes)>
* `Account ID` : sha256(compiled\_code, initital\_state)
* `User friendly version (36 bytes)`: \<flags (1 byte)>\<workchain\_id>\<account\_id>\<verification (2 bytes)>
  * `flag` - isBounceable (if cannot send to then “bounce” fund back to sender); isTestnetOnly, isUrlSafe
  * `verification` - CRC16-CCITT signature from the previous 34 bytes
  * Then we base64(36 bytes) to get friendly address

### Development concept

💡 On TON, everything consists of cells, including contract code, stored data, blocks, achieving streamline and robust flexibility in the process.

![](/files/VhYnTe0WP8YzUP4TRIxR)

#### Cells

[Cells](https://docs.ton.org/develop/data-formats/cell-boc#cell) are entities in Ton for data storage.

* max = 1023 bits per cell
* max 4 references to other cells
* No circular ref with
* Form DAG
* 5 types of cells

![](/files/EeTn8kH1doaaQRaPv1wK)

#### Bag of Cells (BoC)

[Bag of Cells](https://docs.ton.org/develop/data-formats/cell-boc#bag-of-cells) is a data format to

* Serializing cells into bytes arrays
* Contracts send `BoC` to others

![](/files/8COtnBKFKyegjfcAoUb0)

#### TL-B (Type Language - Binary)

💡 Serves to describe the type system, constructors and existing functions. E.g TL-B schemes used to build binary structures associated with TON Blockchain

* Language: [TL-B](https://docs.ton.org/develop/data-formats/tl-b-language)
* Type: [TL-B Types](https://docs.ton.org/develop/data-formats/tl-b-types)

#### Ton FunC tutorials:

💡 A high-level language FunC is used to program smart contracts on TON: domain-specific, C-like, statically typed language.

1. [Learning FunC](https://github.com/romanovichim/TonFunClessons_Eng)
2. FunC standard library

## Best practices

* [Contract Sharding](https://blog.ton.org/how-to-shard-your-ton-smart-contract-and-why-studying-the-anatomy-of-tons-jettons)

## References

1. [En:Free TON Wiki | Freeton Wiki | Fandom](https://freeton.fandom.com/wiki/En:Free_TON_Wiki)
2. [Popular TON community libraries](https://github.com/ton-community/awesome-ton)
3. [**The TON Blockchain is based on PoS consensus.md**](https://gist.github.com/awesome-doge/9bd53050077701e8321d06c0a8ded172)
4. [TL-B Language](https://docs.ton.org/develop/data-formats/tl-b-language)
5. [TL-B Types](https://docs.ton.org/develop/data-formats/tl-b-types)
6. [TON Func Lessons](https://github.com/romanovichim/TonFunClessons_Eng)
7. [FunC Standard Libraries](https://docs.ton.org/develop/func/stdlib)
8. [TON Network chain config](https://tonviewer.com/config)


# Decentralization

To guarantee optimal function, OraiDEX's treasury, which supports various DeFi features within the platform, is currently secured by a suite of Multi-sig wallets. These wallets are under the management of our developer team. See full list below:

| Category          | Contract name      | Address                                                         |
| ----------------- | ------------------ | --------------------------------------------------------------- |
| Oraix Staking     | STAKING\_CONTRACT  | orai1xu9yw2xwd55d09pjce28yjklvk2kwwrqw4ql9gvyrs607z26kv0sl99040 |
| Co-harvest        | COHAVEST\_CONTRACT | orai1r4v3f8p2xethczvw5l5ed8cr05a9dqp6auy2zmz5dyvcq5h5g5kqg6m7vu |
| Futures           | ORAI vAMM          | orai1hgc4tmvuj6zuagyjpjjdrgwzj6ncgclm0n6rn4vwjg3wdxxyq0fs9k3ps9 |
| Futures           | INJ vAMM           | orai1rujsndzwez98c9wg8vfp0fcjfeprddnlud5dweesd3j0qume9nzqvs0ykn |
| Futures           | BTC vAMM           | orai13ma2kawhdhtec9vg75h35wnvtsvmsse8wpltt28st2zyevgwnceqc806jq |
| Futures           | TON vAMM           | orai1uclpn306nv45azqswevrgydv6x775clrwkk790jc87wedt8cdtms6whu9z |
| Futures           | Price Feed         | orai1s57duq6h0r0q6spfdhujnn695a3e9ka59zvv0yrvx7d80gvaf4hsfkezyr |
| Bridge            | IBC Bridge Wasm    | orai195269awwnt5m6c843q6w7hp8rt0k7syfu9de4h0wz384slshuzps8y7ccm |
| Orderbook         | Orderbook          | orai1nt58gcu4e63v7k55phnr3gaym9tvk3q4apqzqccjuwppgjuyjy6sxk8yzp |
| AMM               | Swap Router        | orai1j0r67r9k8t34pnhy00x3ftuxuwg0r6r4p8p6rrc8az0ednzr8y9s3sj2sf |
| AMM               | Staking LP         | orai19p43y0tqnr5qlhfwnxft2u5unph5yn60y7tuvu                     |
| Blockchain Oracle | Cw-Oracle-Hub      | orai19a5y29zj8qhvgew9e7vrgamzfjf63tpdrwr6545l568dd40q9c9s78fk36 |
| Blockchain Oracle | Cw-Oracle-Group    | orai188t4drjxk54ug20srd6f6khf2z8zl6clchdughkakzm4f8rdwe7q4dezp4 |

\
Our vision, however, goes beyond this. We remain steadfastly committed to achieving full decentralization - a goal that has always been on our roadmap. Active migration processes are underway to make this a reality in the imminent future.

<br>


# Indexers

Indexers, in a broad context, play a fundamental role in organising and optimising data retrieval within various systems. These tools act as navigational aids, allowing efficient access to specific information by creating structured indexes. In the realm of databases and information management, indexers enhance query performance by creating a roadmap to swiftly locate data entries.

In the context of blockchain and dApps, indexers go beyond traditional databases, facilitating streamlined access to on-chain data. This includes transaction histories, smart contract states, and event logs. In the dynamic and decentralised world of blockchain, indexers contribute to the efficiency of data queries, supporting real-time updates and ensuring the seamless functionality of diverse applications and platforms.

There are several indexer solutions available, each offering different levels of decentralisation, ease of development, and performance for you to consider. These solutions serve as intermediaries to assist in indexing Oraichain.


# SubQuery

SubQuery is a leading blockchain data indexer that provides developers with fast, flexible, universal, open source and decentralised APIs for web3 projects. SubQuery SDK allows developers to get rich indexed data and build intuitive and immersive decentralised applications in a faster and more efficient way. SubQuery supports 150+ ecosystems including Oraichain, Cosmos, Ethereum, Near, Polygon, Polkadot, Algorand, and Avalanche.

Another one of SubQuery's competitive advantages is the ability to aggregate data not only within a chain but across multiple blockchains all within a single project. This allows the creation of feature-rich dashboard analytics, multi-chain block scanners, or projects that index IBC transactions across zones.

## Useful resources:

* SubQuery Docs: [SubQuery Academy (Documentation)](https://academy.subquery.network/)
* Intro Quick Start Guide: [1. Create a New Project](https://academy.subquery.network/quickstart/quickstart.html)
* [Starter Project](https://github.com/subquery/cosmos-subql-starter/tree/main/Oraichain/oraichain-starter)

For technical questions and support reach out to us `start@subquery.network`

## Running and Hosting your Oraichain SubQuery APIs

SubQuery is open-source, meaning you have the freedom to run it in the following three ways:

* Locally on your own computer (or a cloud provider of your choosing), [view the instructions on how to run SubQuery Locally](https://academy.subquery.network/run_publish/run.html).
* You can publish it to SubQuery's enterprise-level [Managed Service](https://managedservice.subquery.network/), where we'll host your SubQuery project in production ready services for mission critical data with zero-downtime blue/green deployments. There even is a generous free tier. [Find out how](https://academy.subquery.network/run_publish/publish.html).
* You can publish it to the decentralised [SubQuery Network](https://subquery.network/network), the most open, performant, reliable, and scalable data service for dApp developers. The SubQuery Network indexes and services data to the global community in an incentivised and verifiable way and supports Oraichain from launch.


# OraichainEVM

Oraichain is a high-performance Proof-of-Stake blockchain that provides full compatibility and interoperability with the Ethereum Virtual Machine (EVM). Built on the Cosmos SDK and running on top of the CometBFT consensus engine, Oraichain achieves rapid finality, high transaction throughput, and minimal block times.

This architecture of Oraichain enables users to execute both Cosmos and EVM-formatted transactions, allows developers to build cross-chain EVM dApps using IBC, and supports tokens and assets from various independent sources while maintaining its core focus on AI Oracle services.

Oraichain achieves these capabilities through:

* Utilizing Cosmos SDK modules and mechanisms for core blockchain functionality
* Implementing CometBFT's Application Blockchain Interface (ABCI) for blockchain management
* Integrating \`geth\` as a library to ensure Ethereum compatibility and maintainability
* Providing a fully compatible Web3 JSON-RPC interface for seamless integration with existing Ethereum tools (Metamask, Remix, Truffle, etc)

These features allow developers to leverage existing Ethereum development tools while accessing Oraichain's unique AI Oracle capabilities and the broader Cosmos ecosystem.


# Getting started

Looking to build a dApp on Oraichain? Following this documentation and our academy you can learn how and become part of the rich ecosystem of EVM builders on Cosmos. Whether you are building new use cases on Oraichain or porting an existing dApp from another chain, you'll want to check out the sections on

1. Setup [Wallet](/developer-guides/oraichainevm/guides/metamask)
2. Connect to Oraichain
3. Building and deploying [EVM Smart Contracts](/developer-guides/oraichainevm/smart-contracts)
4. Available developer [Tools](/developer-guides/oraichainevm/guides/tools)


# Smart Contracts

Since the inception of Ethereum in 2015, the capability to govern digital assets through smart contracts has attracted a substantial community of developers, fostering the creation of decentralized applications (dApps) on the Ethereum Virtual Machine (EVM). This community continues to expand by developing comprehensive tools and establishing new standards, thereby accelerating the adoption of EVM-compatible technologies.

Whether you are developing novel use cases on Oraichain or migrating an existing dApp from another EVM-based blockchain, such as Ethereum, Oraichain provides a seamless environment to build and deploy EVM smart contracts to implement the core business logic of your dApp. Oraichain is fully compatible with the EVM, enabling the use of widely recognized tools, including Solidity, Remix, Oracles, and APIs like Ethereum JSON-RPC.

Furthermore, leveraging the interoperability of Cosmos-based blockchains, Oraichain facilitates the development of scalable cross-chain applications within the familiar EVM framework. The following section outlines the essential components involved in building and deploying EVM smart contracts on Oraichain.

### Build EVM smart contracts with Solidity <a href="#build-evm-smart-contracts-with-solidity" id="build-evm-smart-contracts-with-solidity"></a>

You can develop EVM smart contracts on Oraichain using [Solidity](https://github.com/ethereum/solidity). Solidity is also used to build smart contracts on Ethereum. So if you have deployed smart contracts on Ethereum (or any other EVM-compatible chain) you can use the same contracts on Oraichain.

Since it is the most widely used smart contract programming language in Blockchain, Solidity comes with well-documented and rich language support. Head over to our list of Tools and IDE Plugins to help you get started.

### EVM Precompiled contracts <a href="#evm-precompiled-contracts" id="evm-precompiled-contracts"></a>

EVM precompiled contracts that are built into the Ethereum Virtual Machine (EVM). Each offers specific functionality, that can be used by other smart contracts. Generally, they are used to perform operations that are either not possible or would be too expensive to perform with a regular smart contract implementation, such as hashing, elliptic curve cryptography, and modular exponentiation.

By adding custom EVM precompiled contracts to Ethereum's basic feature set, Oraichain allows developers to use previously unavailable functionality in smart contracts, like native Cosmos Bank operation. This will allow more complex smart contracts to be built on Oraichain and further improve the interoperability between Cosmos and Ethereum. It also is a key feature to achieve Oraichain' vision of being the definitive dApp chain, where any dApp can be deployed once and users can interact with a wide range of different blockchains natively.

To enable the described functionalities, Oraichain introduces so-called *stateful* precompiled smart contracts, which can perform a state transition, as opposed to those offered by the standard Go-Ethereum implementation, which can only read state information. This is necessary because an operation like e.g. staking tokens will ultimately change the chain state. View a list of available precompiled contract [here](https://docs.evmos.org/develop/smart-contracts/list-evm-extensions).

### Deploy with Ethereum JSON-RPC <a href="#deploy-with-ethereum-json-rpc" id="deploy-with-ethereum-json-rpc"></a>

Oraichain is fully compatible with the Ethereum JSON-RPC APIs, allowing you to deploy and interact with smart contracts on Oraichain and connect with existing Ethereum-compatible web3 tooling. This gives you direct access to reading Ethereum-formatted transactions or sending them to the network.

You can connect to the Oraichain [Testnet](/developer-guides/oraichainevm/guides/oraichain-evm-rpc) to deploy and test your smart contracts before moving to Mainnet.

**Block Explorers**[**​**](https://docs.evmos.org/develop/smart-contracts#block-explorers)**​**

You can use [block explorers](/developer-guides/oraichainevm/guides/tools) to view and debug interactions with your smart contracts deployed on Oraichain. Block explorers index blocks and their transactions so that you can search for real-time and historical information about the blockchain, including data related to blocks, transactions, addresses, and more.


# Oraichain EVM Precompiled Contracts

Page actionsEVM precompiled contracts on the core protocol allow dApps and users to access logic outside of the EVM. Acting as a gateway, these EVM Extensions define how smart contracts can perform cross-chain transactions (via IBC) and interact with core functionalities on the Oraichain (e.g. bank, auth, ...) from the EVM.Comment

### List of EVM Precompiles Contracts <a href="#list-of-evm-precompiles-contracts" id="list-of-evm-precompiles-contracts"></a>

| Address                                           | Name                                                                                                                       | Testnet | Mainnet       |
| ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ------- | ------------- |
| 0x9000000000000000000000000000000000000001Comment | Wasmd                                                                                                                      | ​✅​     | ​✅​           |
| 0x9000000000000000000000000000000000000002Comment | Json                                                                                                                       | ​✅​     | ​✅​           |
| 0x9000000000000000000000000000000000000003Comment | ​[Address](https://app.gitbook.com/o/-MWcR8FSKZBU6KvaxcLP/s/VpLm1Fn91YqukBDhp9gm/getting-started/smart-contracts/address)​ | ​✅​     | ​✅​           |
| 0x9000000000000000000000000000000000000004Comment | Bank                                                                                                                       | ​✅​     | ​✅​           |
| 0x9000000000000000000000000000000000000005Comment | Authz                                                                                                                      | ​✅​     | <p>​✅<br></p> |


# Address

Oraichain supports two types of addresses: the EVM address (0x...) for the Ethereum Virtual Machine (EVM) side and the Bech32 address (orai...) for the Cosmos side. The [Address](https://github.com/oraidex/evm-entry-point/blob/main/packages/contracts/contracts/precompiles/IAddr.sol) precompiled contract enables users to retrieve the association between these two address formats.&#x20;

## Solidity Interfaces

* getCosmosAddr

Get the associated Cosmos Address (orai...) by providing EVM address (0x...)

```
function getCosmosAddr(
        address addr
    ) external view returns (string memory response);
```

* getEvmAddr

Get the associated EVM address (0x...) by providing Cosmos Address (orai...)

```
function getEvmAddr(
        string memory addr
    ) external view returns (address response);
```

* associate

Get the associated EVM address and Cosmos Address by message signature components

```
function associate(
        string memory v,
        string memory r,
        string memory s,
        string memory customMessage
    ) external returns (string memory cosmosAddr, address evmAddr);
```

* associatePubKey

Get the associated EVM address and Cosmos Address by pubkey

```
function associatePubKey(
        string memory pubKeyHex
    ) external returns (string memory cosmosAddr, address evmAddr);
```


# Bank

[Bank ](https://github.com/oraidex/evm-entry-point/blob/main/packages/contracts/contracts/precompiles/IBank.sol)Precompiles contract is a gate-way that allowed Solidity contracts can interact with Cosmos SDK Bank module. This is convenient for developers as they don’t need to know the implementation details behind the `x/bank` module in the Cosmos SDK. Instead, they can interact with bank functions using the Ethereum interface they are familiar with.

## Solidity Interfaces

The Bank solidity interface includes the following transactions

* send

Send defined a method that perform sending logic to a specific address

```
function send(
        address toAddress,
        string memory denom,
        uint256 amount
    ) external returns (bool success);
```

* burn

Burn defined a method that perform burning amount of token from a specific address

```
function burn(
        address account,
        string memory denom,
        uint256 amount
    ) external returns (bool success);
```

* balance

Balance defined a query method that get a user balance of a specific denomination

```
function balance(
        address acc,
        string memory denom
    ) external view returns (uint256 amount);
```

* name

Get the Name that defined in Token Metadata

```
function name(
        string memory denom
    ) external view returns (string memory response);
```

* symbol

Get the Symbol that defined in Token Metadata

```
function symbol(
        string memory denom
    ) external view returns (string memory response);
```

* decimals

Get the token decimals that defined in Token Metadata

```
function decimals(
        string memory denom
    ) external view returns (uint8 response);
```

* supply

Get the total supply of the token

```
function supply(
        string memory denom
    ) external view returns (uint256 response);
```


# Wasm

Oraichain not only provides Ethereum Virtual Machine but also has CosmWasm for developing dApps. With the Wasm precompiled contract, the EVM contract can now interact with the CosmWasm smart contract.

## Solidity Interfaces

The Wasm solidity interfaces include the following transactions:

* instantiate

Instantiate method allows caller to instantiate a wasm contract

```
function instantiate(
        uint64 codeID,
        string memory admin,
        bytes memory payload,
        string memory label,
        bytes memory coins
    ) external returns (string memory contractAddr, bytes memory data);
```

* execute

Execute method allows caller to execute a wasm contract

```
function execute(
        string memory contractAddress,
        bytes memory payload,
        bytes memory coins
    ) external returns (bytes memory response);
```

* query

Query method allows caller to query wasm smart contract state

```
function query(
        string memory contractAddress,
        bytes memory req
    ) external view returns (bytes memory response);
```


# Authz

Authz Precompiles contract is a gate-way that allowed Solidity contracts can interact with Cosmos SDK Authz module. By this, user now can grants permission to execute a specific message to differents address.

## Solidity Interfaces

The Authz solidity interfaces include the following transactions:

* grant

Grant method allow to register grant in Authz module

```
function grant(
        address granter,
        address grantee,
        string memory denom
    ) external view returns (uint256 amount);
```

* setGrant

SetGrant method allow to grant a message in Authz module

```
function setGrant(
        address grantee,
        string memory denom,
        uint256 amount
    ) external returns (bool success);
```

* execGrant

ExecGrant method allowed caller to execute grant message

```
function execGrant(
        address granter,
        address recipient,
        string memory denom,
        uint256 amount
    ) external returns (bool success);
```


# Guides


# Metamask

Connect your Metamask wallet with OraichainEVM on a testnet mode.

## Connect Metamask with OraichainEVM

This guide will provide step-by-step how to run a  testnet chain

### Add a Custom Network for OraichainEVM

Open the Metamask extension on your browser, ou may have to log in to your Metamask account if you have not already. Then, click the top right circle and go to `Settings` > `Networks`. Press the `Add Network` button and fill out the form as shown below with your application `ChainID`.

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

### Downloading State

* To see metamask logs, go to top right circle -> settings -> advanced -> download state logs. If you search through the JSON file for the account address, you'll find the transaction history.


# Remix

Set up a Remix Ethermint testnet development environment.

[Remix](http://remix.ethereum.org/) is an in-browser IDE for [Solidity](https://github.com/ethereum/solidity) smart contracts. In this guide, we will learn how to deploy a contract to a running Ethermint network through Remix and interact with it.&#x20;

### Connect Oraichain Account to Remix

First, follow the steps in the Metamask guide to import your Oraichain private key into Metamask. Start the Oraichain daemon and rest server.Once that is complete, go to [Remix](http://remix.ethereum.org/). There are some contracts in the File Explorer. Select any of these contracts. In this example, we use `Counter.sol` from the Foundry guide. On the left-most bar, select the Solidity Compiler and compile the contract.CommentNext, select the `Deploy and Run` option. Select `injected provider - Metamask` as the environment. This will open a metamask popup for you to confirm connecting your Metamask to Remix. Hit confirm.CommentYou should see your account show up in the left-hand panel.Comment

<figure><img src="https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVpLm1Fn91YqukBDhp9gm%2Fuploads%2FahqsVzmCFb5PGmt0QUzp%2Fimage.png?alt=media&#x26;token=0e1fe1f2-6d0d-4e82-b350-5152acfa8f5b" alt=""><figcaption></figcaption></figure>

### Deploy and Interact with the Contract <a href="#deploy-and-interact-with-the-contract" id="deploy-and-interact-with-the-contract"></a>

Now that your account is connected, you can deploy the contract. Press the `Deploy` button. A metamask pop-up will appear, asking you to confirm. Confirm the transaction. You should see a log for the deployment transaction in the oraichain logslogs.

1. **Interact with Contract**:
   * The deployed contract will be visible under Deployed Contracts in Remix.

     * Use the Remix interface to interact. For `Counter.sol`, click `deploy`. Confirm the transaction in Metamask.

     <figure><img src="https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVpLm1Fn91YqukBDhp9gm%2Fuploads%2F61AAFwfAsYfDOGoSz1sQ%2Fimage.png?alt=media&#x26;token=9c6f8f9d-25e2-47ee-80c3-8b23d094ffc3" alt=""><figcaption></figcaption></figure>

     * Retrieve the counter value by clicking `getCounter`; it should return 1.

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


# Foundry

Install OraichainEVM by following the full instructions provided in the documentation.

### Create Foundry Project

Create a directory for your contracts and initialize it:

```bash
forge init oraichain-evm-foundry
cd oraichain-evm-foundry
```

For now, let’s check what the default template looks like:

```
tree . -d -L 1
.
├── lib
├── script
├── src
└── test

5 directories
```

Open `src/Counter.sol` with the following contract:

````solidity
```solidity
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

contract Counter {
    uint256 public number;

    function setNumber(uint256 newNumber) public {
        number = newNumber;
    }

    function increment() public {
        number++;
    }
}

```
````

Compile the contract:

```bash
forge build
```

### Anvil

Anvil is a fast local Ethereum development node.

Anvil is part of the Foundry suite and is installed alongside `forge`, `cast` and `chisel`. If you haven’t installed Foundry yet, see [Foundry installation](https://book.getfoundry.sh/getting-started/installation.html).

&#x20;To fork against a live OraichainEVM network run:

```
anvil --fork-url <RPC_URL>
```

### Deploy Contract

Migrate your contract in the foundry terminal:

```bash
forge create src/Counter.sol:Counter --rpc-url <RPC_URL> --private-key <PRIVATE_KEY> --broadcast
```

You should see deployment logs in the OraichainEVM terminal for each transaction.

### Run Foundry Tests

Run the tests using the OraichainEVM node:

```bash
forge test test/Counter.t.sol --rpc-url <RPC_URL>
```

This will confirm the contract's functionality.

### Run Foundry Script

To execute a script on OraichainEVM, run:

```bash
forge script script/Counter.s.sol --rpc-url <RPC_URL>
```

earched Pre-requisite reading installation run a node search.

For suggestions, contribute on GitHub!


# Hardhat

### Setting Up a Hardhat OraichainEVM Local Development Environment

Hardhat is a comprehensive Ethereum development environment that enables you to compile, deploy, test, and debug your Solidity code, also supporting EVM-compatible blockchains.

#### Install Dependencies

To get started, ensure you have Node.js installed, then initialize a new project and install Hardhat:

```shell
mkdir oraichain-evm-hardhat
cd oraichain-evm-hardhat
npm init -y
npm install --save-dev hardhat
```

#### Initialize Hardhat

Create a basic Hardhat project setup:

```
npx hardhat
```

Choose "Create a basic sample project" and proceed with the prompts.

For now, let’s check what the default template looks like:

```
tree . -d -L 1
.
├── lib
├── script
├── src
└── test
​
5 directories
```

Open `contracts/Lock.sol` with the following contract:

```solidity
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
​
// Uncomment this line to use console.log
// import "hardhat/console.sol";
​
contract Lock {
    uint public unlockTime;
    address payable public owner;
​
    event Withdrawal(uint amount, uint when);
​
    constructor(uint _unlockTime) payable {
        require(
            block.timestamp < _unlockTime,
            "Unlock time should be in the future"
        );
​
        unlockTime = _unlockTime;
        owner = payable(msg.sender);
    }
​
    function withdraw() public {
        // Uncomment this line, and the import of "hardhat/console.sol", to print a log in your terminal
        // console.log("Unlock time is %o and block timestamp is %o", unlockTime, block.timestamp);
​
        require(block.timestamp >= unlockTime, "You can't withdraw yet");
        require(msg.sender == owner, "You aren't the owner");
​
        emit Withdrawal(address(this).balance, block.timestamp);
​
        owner.transfer(address(this).balance);
    }
}
```

#### Configure the OraichainEVM Network

Modify `hardhat.config.js` to add the OraichainEVM network configuration:

```javascript
require("@nomiclabs/hardhat-ethers");
​
module.exports = {
  solidity: "0.8.13",
  networks: {
    oraichain: {
      url: "<RPC_URL>",
      accounts: [`0x${<PRIVATE_KEY>}`]
    }
  }
};
```

#### Compile Contracts

Compile your Solidity contracts using:

```
npx hardhat compile
```

#### Deploy Contracts

Deploy your contract with a Hardhat script. Create `scripts/deploy.js`:

```typescript
async function main() {
  const Lock = await ethers.getContractFactory("Lock");
  const lock = await Lock.deploy();
  console.log("Lock deployed to:", lock.address);
}
​
main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });
```

Run the deployment script:

```
npx hardhat run scripts/deploy.js --network oraichain
```

#### Run Tests

Run tests using Hardhat's testing environment:

```
npx hardhat test
```

#### Execute Scripts

You can further execute custom scripts for interaction with your contracts similarly by specifying the network:

```
npx hardhat run scripts/interact.js --network oraichain
```

Hardhat provides flexibility and robust tooling for your Solidity dApp development on EVM-compatible chains like OraichainEVM.


# Tools

## Block Explorers

Blockchain explorers allow users to query the blockchain for data. Explorers are often compared to search engines for the blockchain. By using an explorer, users can search and track balances, transactions, contracts, and other broadcast data to the blockchain.

* Mainnet

Scanium: <https://scanium.io/Oraichain>

* Testnet

## Faucet

The Oraichain Testnet Faucet distributes small amounts of ORAI to anyone who provide a valid testnet address.

After receiving funds from the faucet, view your account balance either by clicking on the Wallet extension or by using the Testnet Explorer.

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


# Oraichain EVM RPC

### Testnet:

<pre><code><strong>https://testnet-v2.evm.orai.io
</strong></code></pre>

### Mainnet:

```
```


# Privacy Policy

### Introduction

Thank you for visiting [https://orai.io/](https://orai.io) (together with all other websites, pages and services operated by or on behalf of Oraichain, the “Site”). Your privacy is important to us. We provide this privacy policy (“Privacy Policy”) explaining our policies regarding collection, use and disclosure of personal information we receive from users of the Site in accordance with applicable laws.

The term “personal information” refers to all information that can be used to contact or identify you, including, but not limited to, a first and last name, personal profile, a home or other physical address and an email address or other contact information, whether at work or at home.

We are committed to respecting your online privacy and recognize your need for appropriate protection and management of any personal information.

### Collection of personal information

We will obtain personal information about you when you visit us. Such information includes, but is not limited to, IP address and other unique identifiers for the computer, mobile or other device you use to access the Site and any referring website. When you visit us, we may monitor the use of this Site through the use of cookies and similar tracking devices which shall be conducted in accordance with the cookies and tracking policy below.

You may also give us information about you by submitting information on the Site or by corresponding with us by email or otherwise. This includes information you provide when you register to use the Site, subscribe to the Site services, participate in discussion boards or other functions on the Site, and when you report a problem with the Site.

Sometimes, the Site may permit interactions with third-party websites. This enables you to "like" a product or "share" content with third-party websites. In doing so, the information (i.e. that you "like" a certain product) will become public and the third-party website (like Facebook) will have access to this information. In addition, we may receive data about you if other users of a third-party website give us access to their profiles and you are one of their “connections”, or if information about you is otherwise accessible through your connection's social networking page.

### Use of personal information

We use the personal information that you share with us for providing, delivering, monitoring and improving the Site. This includes, but not limited to, delivering and enabling the services provided by the Site, verifying your identity, responding to your enquiry or request, providing customer support, gathering customer feedback, conducting research and development of the Site and the services, updating you on changes to the Site or complying with applicable laws.

### Disclosure of personal information

Oraichain strives to comply with all applicable laws around the globe that are designed to protect your privacy. Although legal requirements may vary from country to country, Oraichain intends to adhere to the principles set forth in this Privacy Policy even if, in connection with the above, we transfer your personal information from your country to countries that may not require an "adequate" level of protection for your personal information. In other words, our goal is to provide protection for your personal information no matter where that personal information is collected, transferred, or retained. Finally, we may disclose your personal information or any information you submitted via the Site and its services if we have an adequate understanding that disclosure of such information is helpful or reasonably necessary to (i) comply with any applicable law, regulation, legal process or governmental request, (ii) detect, prevent, or otherwise address fraud or security issues, or (iii) protect against harm to the rights, property or safety of Oraichain, its users, yourself or the public.

### Cookies and Other Tracking Technologies Web Cookies

A “Web Cookie” is a string of information that a website stores on a user’s computer, and that the user’s browser provides to the website each time the user submits a query to the Site. Like many sites, we use Web Cookies to track the pages that users visit during each Site session, both to help us improve users’ experiences and to help us understand how the site is being used. As with other non-personal information gathered from users of the Site, we analyze and disclose in aggregated form information gathered using Web Cookies, so as to help us, our partners and others better understand how the Site is being used.

When you first arrive on our site, a cookie banner will be shown. Users who do not wish to have web cookies placed on their computers can delete or control these cookies. However, this will impair certain features of the Site. Users who refuse web cookies assume all responsibility for any resulting loss of functionality.

We may use third-party service providers who are authorised to place third-party cookies and may also set cookies on this Site. In such case, these third-party service providers are responsible for the cookies they set on this Site. If you want further information, please go to the website of the relevant third party. If you would like to opt-out of all other types of technologies we employ on this Site, you may do so by changing your browser settings to block, delete or disable these technologies as your browser or device permits.

### Other privacy principles

You may choose whether or not to provide personal information to Oraichain. The notices we will provide where Oraichain collects personal information on the Site should help you to make this choice. If you choose not to provide the personal information we request, you can still visit most of the Site, but you may be unable to access certain options, offers, and services that involve our interaction with you.

We have implemented suitable security policies, rules and technical measures to protect and safeguard the personal information under our control from unauthorized access, improper use or disclosure, unauthorized modification, unlawful destruction or accidental loss. All our employees and data processors that have access to, and are associated with the processing of your personal information, are obliged to respect the confidentiality of your information.

To the extent that you do provide us with personal information, Oraichain wishes to maintain accurate personal information. You may check your profile and add information, delete information or correct any incorrect information.

### Links to Other Sites

Our Site may contain links to other sites. Other sites may also reference or link to our site. We are not responsible for the privacy practices or the content of such other sites.

### Children’s Privacy

The Site is not structured to attract children. Accordingly, we do not intend to collect personal information from anyone we know to be under 13 years of age.

### Commitment

We are committed to protecting your privacy. Protecting your privacy online is an evolving area, and Oraichain’s Sites are constantly evolving to meet these demands. If you have any comments or questions regarding our Privacy Policy, please contact us at <contact@orai.io>. While we cannot guarantee privacy perfection, we will address any issue to the best of our abilities as soon as possible.

### Your Consent

By using this Site, you consent to the terms of our Privacy Policy and to Oraichain’s processing of personal information for the purposes given above. If you do not agree to this Privacy Policy, please do not use our Site. We reserve the right, at our discretion, to change, modify, add, or remove portions from this Privacy Policy at any time. Your continued use of our Site following the posting of changes to these terms means you accept these changes.

### Your Privacy Rights

As we are committed to respecting your online privacy, you have the right to ask us not to collect, use, process, or disclose your personal information in any of the manner described herein. If you want us to halt the collection, use, processing, or disclosure of your personal information, you can give us notice of your intention at any time by contacting us at <contact@orai.io>.


# Networks


# Joining Mainnet

## 🚀 Joining Oraichain Mainnet

Welcome to **Oraichain Mainnet**! Below, you'll find essential details, recommended hardware, and snapshot options to get started smoothly.

### 🌐 Oraichain Mainnet Metadata

| Property                 | Value      |
| ------------------------ | ---------- |
| **Chain ID**             | Oraichain  |
| **Coin Minimal Denom**   | `orai`     |
| **Coin Decimal**         | `6`        |
| **BIP44 Coin Type**      | `118`      |
| **Cosmos SDK Version**   | `v0.50.12` |
| **CometBFT Version**     | `v0.38.17` |
| **CosmWasm-std Version** | `v2.1.3`   |

#### 🔗 Essential Endpoints

* **LCD (Light Client Daemon):** [lcd.orai.io](https://lcd.orai.io)
* **RPC (Remote Procedural Call):** [rpc.orai.io](https://rpc.orai.io)
* **gRPC:** [grpc.orai.io:9090](http://grpc.orai.io:9090)
* **Explorer:** [Scanium - Oraichain](https://scanium.io/Oraichain)

***

### ⚙️ Recommended Node Hardware

Oraichain supports **amd64** and **arm64** architectures, but we strongly recommend **amd64** for better performance.

#### ✅ Minimum Requirements

```
CPU: 4 vCPUs  
RAM: 8GB  
Storage: 500GB SSD  
```

#### 🔥 Recommended Requirements

```
CPU: 8 vCPUs  
RAM: 64GB  
Storage: 1TB SSD  
```

#### 🚀 100% uptime validator

```
CPU: 16 vCPUs  
RAM: 128GB  
Storage: 1TB SSD
Connection: 10 GBit/s
```

***

### 📥 Chain Pruned Data Download

To speed up synchronization, use these snapshot sources:

🔹 **Primary Snapshot:**

```bash
https://snapshot.orai.io
```

🔹 **Alternative Snapshots (from Oraichain validators):**

```bash
https://snapshot.owallet.io/
https://polkachu.com/tendermint_snapshots/orai
https://publicnode.com/snapshots
https://itrocket.net/services/mainnet/oraichain/#snapshot
https://server-3.stavr.tech/Mainnet/Orai/
```

📢 **Need help?** Join the [Oraichain Validators Group](https://t.me/joinchat/yH9nMLrokQRhZGY1) on Telegram to request snapshot data!


# Build Linux binary from source and become a Sentry Node Operator

Everything you need to go from zero to running a fully synced Oraichain node — the right way.

***

## 🧰 Prerequisites

Before diving in, make sure your system meets the following requirements.

### ✅ OS Compatibility

* Ubuntu LTS versions only: **22.04**
* ❌ Not supported: Ubuntu **16.04** or older

### ✅ Go (Golang)

* Required version: **1.22.6+**
* Follow the [Go installation guide](https://github.com/oraichain/docs/blob/master/nodes-validators/tutorials/install-go.md) if not already installed.
* Ensure `$GOPATH/bin` is included in your `$PATH`.

### ✅ Essential Packages

Install these if not already available:

```bash
sudo apt update && sudo apt install make gcc -y
```

***

## 🏗️ Build `oraid` from Source

Let’s compile the node binary from scratch.

### 1. Set your ORAI working directory

```bash
export ORAI_HOME="/root"
```

> 📝 If you're not using `/root`, replace all occurrences of `$ORAI_HOME` with your desired path.

### 2. Clone and build

```bash
cd $ORAI_HOME
git clone https://github.com/oraichain/wasmd
cd wasmd
git checkout v0.50.9  # or latest tag
make build
```

> ⚠️ Confirm the binary version:

```bash
oraid version
```

Expected output: `v0.50.9`

***

## ⚙️ Initialize Your Node

```bash
oraid init NODE_NAME --home $ORAI_HOME/.oraid --chain-id Oraichain
```

(*replace the NODE\_NAME with a name of your choosing*)

Download the latest genesis file:

```bash
wget -O $ORAI_HOME/.oraid/config/genesis.json https://raw.githubusercontent.com/oraichain/oraichain-static-files/master/genesis.json
```

✅ **Resulting directory structure:**

```
$ORAI_HOME/.oraid/
├── config
│   ├── app.toml
│   ├── client.toml
│   ├── config.toml
│   ├── genesis.json
│   ├── node_key.json
│   └── priv_validator_key.json
└── data
    └── priv_validator_state.json
```

***

## 🧠 Setup Cosmovisor (Optional but Recommended)

Cosmovisor makes future upgrades smooth and stress-free.

### 1. Install Cosmovisor

```bash
go install cosmossdk.io/tools/cosmovisor/cmd/cosmovisor@latest
```

### 2. Set up folders

```bash
mkdir -p $ORAI_HOME/.oraid/cosmovisor/genesis/bin
mkdir -p $ORAI_HOME/.oraid/cosmovisor/upgrades
cp $GOPATH/bin/oraid $ORAI_HOME/.oraid/cosmovisor/genesis/bin
```

### 3. Add environment variables

```bash
echo "# Cosmovisor Setup" >> ~/.profile
echo "export ORAI_HOME=/root" >> ~/.profile
echo "export DAEMON_NAME=oraid" >> ~/.profile
echo "export DAEMON_HOME=$ORAI_HOME/.oraid" >> ~/.profile
echo "export DAEMON_ALLOW_DOWNLOAD_BINARIES=false" >> ~/.profile
echo "export DAEMON_LOG_BUFFER_SIZE=512" >> ~/.profile
echo "export DAEMON_RESTART_AFTER_UPGRADE=true" >> ~/.profile
echo "export UNSAFE_SKIP_BACKUP=true" >> ~/.profile
source ~/.profile
```

Check installation:

```bash
cosmovisor version
oraid version
```

***

## ⛓️ Sync Chain Data

Download and extract the latest snapshot:

```bash
sudo apt install wget liblz4-tool aria2 -y
cd $ORAI_HOME/.oraid
wget -O oraichain_latest.tar.lz4 [SNAPSHOT_URL]
lz4 -c -d oraichain_latest.tar.lz4 | tar -x -C $ORAI_HOME/.oraid
```

We provide a snapshot file every hour, available at <https://snapshot.orai.io/>. Please change \[SNAPSHOT\_URL] to the provided link.

***

## 🛠️ Update Node Config

Edit config:

```bash
vim $ORAI_HOME/.oraid/config/config.toml
```

Update seeds:

```toml
seeds = "e18f82a6da3a9842fa55769955d694f62f7f48bd@seed1.orai.zone:26656,defeea41a01b5afdb79ef2af155866e122797a9c@seed4.orai.zone:26656"
```

> You may also add more from this list:

```
f223f1be06ef35a6dfe54995f05daeb1897d94d7@seed-node.mms.team:42656
8542cd7e6bf9d260fef543bc49e59be5a3fa9074@seed.publicnode.com:26656
fe0a0d46eb5436905bf8465f83d2da5a503bf4eb@mainnet-seed.konsortech.xyz:33165
ade4d8bc8cbe014af6ebdf3cb7b1e9ad36f412c0@seeds.polkachu.com:23356
5f5cfac5c38506fbb4275c19e87c4107ec48808d@seeds.nodex.one:11210
49165f4ef94395897d435f144964bdd14413ea28@seed.orai.synergynodes.com:26656
...
```

***

## 🔧 Run as a Systemd Service

Create a service file:

```bash
cat > /tmp/orai.service <<EOF
[Unit]
Description=Oraichain Cosmovisor Node
After=network-online.target

[Service]
User=$USER
Environment="ORAI_HOME=/root"
Environment="DAEMON_NAME=oraid"
Environment="DAEMON_HOME=${ORAI_HOME}/.oraid"
Environment="DAEMON_RESTART_AFTER_UPGRADE=true"
Environment="DAEMON_ALLOW_DOWNLOAD_BINARIES=false"
Environment="DAEMON_LOG_BUFFER_SIZE=512"
Environment="UNSAFE_SKIP_BACKUP=true"
ExecStart=$GOPATH/bin/cosmovisor run start --home ${ORAI_HOME}/.oraid --minimum-gas-prices=0.001orai
Restart=always
RestartSec=3
LimitNOFILE=infinity
LimitNPROC=infinity

[Install]
WantedBy=multi-user.target
EOF

sudo mv /tmp/orai.service /etc/systemd/system/orai.service
```

Enable and start:

```bash
sudo systemctl daemon-reload
sudo systemctl start orai
sudo systemctl enable orai
```

***

## 🩺 Monitor Your Node

### Check service status

```bash
sudo systemctl status orai
```

### View logs live

```bash
journalctl -u orai -f
```

### Sync status

```bash
oraid status | jq .SyncInfo
# OR
curl -s localhost:26657/status | grep "catching_up"
```

✅ If `catching_up` is `false`, you're fully synced!

***

## 👥 Join the Community

Join our Telegram group to get help, share ideas, and stay up to date:

👉 [Oraichain Validators Group](https://t.me/joinchat/yH9nMLrokQRhZGY1)

Some useful resource from validator community:

* <https://polkachu.com/networks/orai>
* [https://itrocket.net/services/mainnet/oraichain](https://itrocket.net/services/mainnet/oraichain/)
* [https://www.synergynodes.com/service/oraichain](https://www.synergynodes.com/service/oraichain/)
* [https://ccvalidators.com/oraichain](https://ccvalidators.com/oraichain/)
* [https://cosmos.directory/oraichain](https://cosmos.directory/oraichain/)


# Become a Validator

## Requirements

### 1. A Synced Node

You need to have a fully synced node running on the Oraichain mainnet. Follow our [tutorial](/nodes-and-validators/networks/mainnet/become-a-full-node-operator-from-source) to set up a node.

### 2. A Wallet

Your wallet must have some ORAI tokens to delegate and pay transaction fees.

#### Create a New Wallet

Replace `KEY_NAME` with your preferred wallet name:

```bash
oraid keys add KEY_NAME
```

**Important:** Save your passphrase, address, and mnemonic securely.

#### List All Keys

```bash
oraid keys list
```

#### Get Validator Public Key

```bash
oraid tendermint show-validator
```

***

## Create `validator.json` File

As of version **v0.50**, creating a `validator.json` file is required.

### Sample `validator.json`

```json
{
    "pubkey": {"@type":"/cosmos.crypto.ed25519.PubKey","key":"XXXXXXXX"},
    "amount": "1000000orai",
    "moniker": "myvalidator",
    "identity": "optional identity signature (ex. UPort or Keybase)",
    "website": "validator's (optional) website",
    "security": "validator's (optional) security contact email",
    "details": "validator's (optional) details",
    "commission-rate": "0.1",
    "commission-max-rate": "0.2",
    "commission-max-change-rate": "0.01",
    "min-self-delegation": "1"
}
```

Edit the file with your actual validator details:

* **`pubkey`**: The validator's Protobuf JSON encoded public key (retrieved from the previous command).
* **`amount`**: Amount of coins to bond (e.g., `1000000orai = 1 ORAI` token).
* **`moniker`**: Your validator's name.
* **`commission-rate`**: Initial commission rate (e.g., `0.1` for 10%).
* **`commission-max-rate`**: Maximum commission rate (e.g., `0.2` for 20%).
* **`commission-max-change-rate`**: Maximum daily commission rate change (e.g., `0.01` for 1% per day).
* **`min-self-delegation`**: Minimum self-delegation (e.g., `1` ORAI).
* **`website`**: (Optional) Your validator's website.
* **`details`**: (Optional) Additional validator information.

***

## Create Validator Command

Before creating your validator, **fund your wallet with some ORAI tokens** to activate it.

#### Command Format

```bash
oraid tx staking create-validator path/to/validator.json \
--from [KEY_NAME] \
--chain-id="Oraichain" \
--gas="auto" \
--gas-prices="[gas_price]"
```

#### Example

```bash
oraid tx staking create-validator /root/validator.json \
--from=light1 \
--chain-id="Oraichain" \
--gas="auto" \
--gas-prices=0.001orai
```

### Explanation of Flags

* **`--from`**: The name or address of the private key used to sign.
* **`--chain-id`**: The chain ID (fixed as `Oraichain`).
* **`--gas-prices`**: Gas prices in decimal format to determine the transaction fee.

***

## Track Your Validator

### Check Active Validator Set

Replace `OraichainValidator` with your moniker name:

```bash
oraid query staking validators | grep OraichainValidator
```

### Track Signing History

```bash
oraid query slashing signing-info $(oraid tendermint show-validator)
```

***

## Join the Validator Community

Join the [Oraichain validators group](https://t.me/joinchat/yH9nMLrokQRhZGY1) on Telegram to discuss ideas and troubleshoot issues!


# Joining Testnet

## Basic Oraichain testnet metadata & properties:

**Chain ID:** Oraichain-testnet

**Coin minimal denom:** orai

**Coin decimal:** 6

**Bip44 Coin type:** 118

**Light Client Daemon (LCD):** <https://testnet-v2.lcd.orai.io/>

**Remote Procedural Call (RPC):** <https://testnet-v2.rpc.orai.io/>

**Cosmos SDK version:** v0.50.13

**Faucet**: <https://testnet-faucet.orai.io/>

[Detailed tutorial to start a testnet fullnode](/nodes-and-validators/networks/testnet/become-full-node-testnet-from-source)


# Become Testnet Fullnode From Source

Instructions to install the oraid binary and run as a service by systemd

## Oraid Installation and setup

### Preresquites

#### Operating System

This tutorial assumes that your node is running Ubuntu LTS version (i.e: 18.04, 20.04 or 22.04). It does not work with Ubuntu 16.04 or older versions.

#### Go version (required)

The Golang version should be from 1.22.11 and above\
If you have not installed it yet, you can refer to [this document](https://github.com/oraichain/docs/blob/master/developer/tutorials/install-go.md).

Make sure that `$GOPATH` is in your `$PATH`. It's the crucial part of this tutorial.

#### Make (required)

If your node does not have Make, install using:

```bash
sudo apt update && sudo apt install make
```

#### Gcc (required)

You need to install Gcc to build the binary. Type:

```bash
sudo apt update && sudo apt install gcc
```

### Build the binary from source

Please define the `$ORAI_HOME` environment variable which will be used as the working directory, in this tutorial we will assume that your `$ORAI_HOME` is `root`. If you don't define it, all of the following installations will be using your `$HOME` folder as `$ORAI_HOME`, please replace `$ORAI_HOME` with `$HOME` in the corresponding commands (except export ORAI\_HOME command).

Make sure your user has enough permissions to write data to the `$ORAI_HOME` folder.

```bash
# Export ORAI_HOME env variable
export ORAI_HOME="/root"
```

```bash
# clone the Oraichain network repository
cd $ORAI_HOME
git clone https://github.com/oraichain/wasmd.git

# enter the repo
cd wasmd

# checkout the latest tag
git checkout <tag>
```

The `<version-tag>` will need to be set to either a testnet or the latest mainnet version tag.

{% hint style="warning" %}
The current mainnet version tag will be `v0.50.9` - i.e:

```bash
git checkout v0.50.9
```

{% endhint %}

Next, you should be able to build the binary file using the below command:

```bash
# go to main folder ($ORAI_HOME/wasmd)
cd wasmd
make build
```

After running the above commands, your `oraid` binary can be found in `$GOPATH/bin`.\
To confirm that the installation is succeeded, you can run (please make sure that `$GOPATH/bin` is in your `$PATH`):

```bash
oraid version
```

The current binary version for Linux users is v0.50.9

Libwasmvm version: `oraid query wasm libwasmvm-version`, which should give: 2.1.3

## Initialize Orai Testnet Node

Use oraid to initialize your node (replace the NODE\_NAME with a name of your choosing):

```bash
oraid init NODE_NAME --home $ORAI_HOME/.oraid --chain-id Oraichain-testnet
```

Download and place the genesis file in the orai config folder:

```bash
sudo apt-get install wget -y
wget -O $ORAI_HOME/.oraid/config/genesis.json https://orai.s3.us-east-2.amazonaws.com/testnet/genesis.20240117.json
```

#### Finally, your working directory should be like below:

```
$ORAI_HOME/.oraid/
├── config
│   ├── app.toml
│   ├── client.toml
│   ├── config.toml
│   ├── genesis.json
│   ├── node_key.json
│   └── priv_validator_key.json
└── data
    └── priv_validator_state.json
```

2 directories, 7 files

## Setup to run node

### Edit config

```bash
vim $ORAI_HOME/.oraid/config/config.toml
```

Update seed and persistent\_peers address

```bash
seeds = "e80c9d494188635284bb529308330cac10c326e9@143.198.28.190:26656, e80c9d494188635284bb529308330cac10c326e9@143.198.28.190:26656"
persistent_peers = "e80c9d494188635284bb529308330cac10c326e9@143.198.28.190:26656, e80c9d494188635284bb529308330cac10c326e9@143.198.28.190:26656"
```

Start your node

```bash
oraid start --home $ORAI_HOME/.oraid
```


# StateSync Testnet

## Oraid Installation and setup

You can see step of install and setup `oraid` [here](/nodes-and-validators/networks/testnet/become-full-node-testnet-from-source)

## Initialize Orai Testnet Node

Use oraid to initialize your node (replace the NODE\_NAME with a name of your choosing):

```bash
oraid init NODE_NAME --home $ORAI_HOME/.oraid --chain-id Oraichain-testnet
```

Download and place the genesis file in the orai config folder:

```bash
sudo apt-get install wget -y
wget -O $ORAI_HOME/.oraid/config/genesis.json https://orai.s3.us-east-2.amazonaws.com/testnet/genesis.20240117.json
```

#### Finally, your working directory should be like below:

```
$ORAI_HOME/.oraid/
├── config
│   ├── app.toml
│   ├── client.toml
│   ├── config.toml
│   ├── genesis.json
│   ├── node_key.json
│   └── priv_validator_key.json
└── data
    └── priv_validator_state.json
```

2 directories, 7 files

## State-sync Oraichain testnet

* Create `state-sync.sh` file with the following code:

```bash
#!/bin/bash

APP_TOML_PATH=$ORAI_HOME/.oraid/config/app.toml
CONFIG_TOML_PATH=$ORAI_HOME/.oraid/config/config.toml

SYNC_RPC="https://testnet-v2.rpc.orai.io:443"
PERSISTENT_PEER_1="e80c9d494188635284bb529308330cac10c326e9@143.198.28.190:26656"
PERSISTENT_PEER_2="e80c9d494188635284bb529308330cac10c326e9@143.198.28.190:26656"

LATEST_HEIGHT=$(curl -s $SYNC_RPC/block | jq '.result.block.header.height | tonumber')
TRUST_HEIGHT=$((LATEST_HEIGHT - 5000))
TRUST_HASH=$(curl -s $SYNC_RPC/block?height=$TRUST_HEIGHT | jq .result.block_id.hash)

echo "height: $LATEST_HEIGHT"
echo "trust height: $TRUST_HEIGHT"
echo "hash: $TRUST_HASH"

sed -i -e "s%^snapshot-interval *=.*%snapshot-interval = 1200%; " $APP_TOML_PATH

sed -i -E 's|tcp://127.0.0.1:26657|tcp://0.0.0.0:26657|g' $CONFIG_TOML_PATH
sed -i -e "s%^enable *=.*%enable = true%; " $CONFIG_TOML_PATH
sed -i -e "s%^allow_duplicate_ip *=.*%allow_duplicate_ip = true%; " $CONFIG_TOML_PATH
sed -i -e "s%^addr_book_strict *=.*%addr_book_strict = false%; " $CONFIG_TOML_PATH
sed -i -e "s%^persistent_peers *=.*%persistent_peers = \"$PERSISTENT_PEER_1,$PERSISTENT_PEER_2\"%; " $CONFIG_TOML_PATH
sed -i -e "s%^max_num_outbound_peers *=.*%max_num_outbound_peers = 0%; " $CONFIG_TOML_PATH
sed -i -e "s%^rpc_servers *=.*%rpc_servers = \"$SYNC_RPC,$SYNC_RPC\"%; " $CONFIG_TOML_PATH
sed -i -e "s%^trust_height *=.*%trust_height = \"$TRUST_HEIGHT\"%; " $CONFIG_TOML_PATH
sed -i -e "s%^trust_hash *=.*%trust_hash = $TRUST_HASH%; " $CONFIG_TOML_PATH
```

* Grant privilege to execute script:

```bash
chmod 700 state-sync.sh
./state-sync.sh
```

* Start your node

```bash
oraid tendermint unsafe-reset-all --home $ORAI_HOME/.oraid
oraid start --home $ORAI_HOME/.oraid
```


# Faucet Testnet

Oraichain Testnet Faucet: <https://testnet-faucet.orai.io/>


# Oraichain Tutorials


# Migrate one Oraichain node to another

Migrating your node to a new machine doesn't have to be complicated. Follow this structured guide to ensure a smooth transition with minimal downtime.

> \[!CAUTION] ⚠️ Do not put priv\_validator\_key.json on two running nodes simultaneously. Your validator will be jailed forever !!!

***

## **1. Back Up Your Current Node Information**

Before starting, **backup** your node's essential files to prevent any data loss:

```bash
cp -r ~/.oraid/config/priv_validator_key.json ~/.oraid/config/node_key.json ~/backup/
```

These files are crucial for maintaining your validator identity.

***

## **2. Set Up a New Node**

Initialize a new node to prepare for the migration. Follow the full node setup guide [here](https://docs.orai.io/developers/networks/mainnet/become-a-full-node-operator-from-source). You can reuse the same moniker as your existing node.

***

## **3. Sync the New Node with the Network**

Ensure your new node synchronizes with the network before migration to minimize downtime. Start your new node with a persistent connection to an existing network node.

```bash
oraid start --p2p.persistent_peers="<existing-node-id>@<ip>:<port>"
```

Let it fully sync before proceeding.

***

## **4. Shut Down the Old Node**

Once the new node is synced, gracefully stop the old node:

```bash
systemctl stop orai
```

This step prevents conflicts between the two nodes.

***

## **5. Transfer Node Data to the New Machine**

Copy the backed-up files to the new node:

```bash
scp ~/backup/priv_validator_key.json ~/backup/node_key.json <new-node-ip>:~/.oraid/config/
```

Ensure the new node retains the same identity by using the copied keys.

***

## **6. Restart the New Node**

Apply the changes by restarting the new node:

```bash
oraid start
```

Monitor logs to verify it is running correctly.

***

## **7. Verify Voting Power and Node ID**

Run the following command to check if your node has successfully migrated:

```bash
oraid status && oraid tendermint show-node-id
```

* If the **voting power** and **node ID** match your previous node, congratulations! 🎉 Your migration is complete.
* If not, double-check the copied files and restart the node.
* Common mistakes include not stopping the old node first or copying files before the new node has finished syncing.

***

## **8. Import Your Wallet (Optional)**

If you need to restore your wallet on the new node, use:

```bash
oraid keys add <wallet-name> --recover
```

Alternatively, use the **explorer** to manage your wallet effortlessly.

***

### **Final Thoughts**

Your old node remains unaffected throughout the process. If needed, you can always revert by restarting the old node.

🚀 **Happy validating!**


# Cosmovisor

`cosmovisor` is a lightweight process manager for Cosmos SDK application binaries that automates the upgrade process. It monitors the governance module for on-chain upgrade proposals and seamlessly handles binary upgrades by:

* Downloading and preparing the new binary
* Stopping the current binary
* Switching to the upgraded binary
* Restarting the node with the new binary

### **Why Use Cosmovisor?**

For validators, `cosmovisor` significantly reduces downtime during chain upgrades. Instead of manually handling upgrades, validators can pre-install new binaries, allowing `cosmovisor` to execute upgrades automatically when a proposal passes.

***

## **Configuration**

More details about `cosmovisor` settings can be found in the [official documentation](https://docs.cosmos.network/main/build/tooling/cosmovisor).

***

## **Installation**

### **1. Using Go Install**

Install the latest version of `cosmovisor` with:

```bash
go install cosmossdk.io/tools/cosmovisor/cmd/cosmovisor@latest
```

### **2. Manual Build**

Alternatively, build from source:

```bash
git clone https://github.com/cosmos/cosmos-sdk.git
cd cosmos-sdk
git checkout cosmovisor/vx.x.x
make cosmovisor
```

This builds `cosmovisor` in the `/cosmovisor` directory. To add it to your system’s PATH:

```bash
cp cosmovisor/cosmovisor ~/go/bin/cosmovisor
```

Verify the installation:

```bash
cosmovisor version
```

***

## **Directory Structure**

```
.
├── current -> genesis or upgrades/<name>
├── genesis
│   └── bin
│       └── $DAEMON_NAME
└── upgrades
    └── <name>
        ├── bin
        │   └── $DAEMON_NAME
        └── upgrade-info.json
```

***

## **Manual Software Upgrade Using Cosmovisor**

This tutorial assumes you have set up a validator node using [this guide](https://docs.orai.io/nodes-and-validators/networks/mainnet/become-a-full-node-operator-from-source).

### **Upgrade Process Overview**

#### **1. Foundation Team Publishes a New Release**

Example: [v0.50.8 Release](https://github.com/oraichain/wasmd/releases/tag/v0.50.8)

#### **2. Foundation Team Submits a Software Upgrade Proposal**

Example: [Proposal #310](https://scanium.io/Oraichain/gov/310)

* The most important detail is the **block height** at which the upgrade takes effect. In Proposal #310, the upgrade happens at block **`53006170`**.
* You can track this block height and estimate when the upgrade will occur.

#### **3. Validator's Steps: Prepare the Upgrade Binary**

1. Create the upgrade binary folder:

   ```bash
   mkdir -p $HOME/.oraid/cosmovisor/upgrades/v0.50.8/bin
   ```
2. Build the new binary:

   ```bash
   cd orai
   git pull
   git checkout v0.50.8
   make build
   ```
3. Copy the binary to the upgrade folder:

   ```bash
   cp $(which oraid) $HOME/.oraid/cosmovisor/upgrades/v0.50.8/bin
   ```
4. Verify the new binary version:

   ```bash
   oraid version
   $HOME/.oraid/cosmovisor/upgrades/v0.50.8/bin/oraid version
   ```

If both commands return `v0.50.8`, the setup is correct, and you are now ready for the upgrade.

#### **4. Automatic Upgrade at the Specified Block Height**

Once the network reaches block **`53006170`**, `cosmovisor` will automatically:

* Stop the current binary
* Switch to the new binary (`upgrades/v0.50.8/bin`)
* Restart the node

When **2/3 of validators approve the next block (`53006170`)**, the upgrade is considered **successful**.

***

### **Final Thoughts**

With `cosmovisor`, software upgrades are seamless and reduce validator downtime. Make sure to follow this guide for every upgrade and ensure your node is prepared in advance.

🚀 **Happy Validating!**


# Update validator image

A **validator image** is a visual representation of your validator, displayed on validator pages across different blockchain explorers.

### **Example Validator Pages:**

* **ORAI Scan:** [View Example](https://scan.orai.io/validators/oraivaloper1uhcwtfntsvk8gpwfxltesyl4e28aalmq9v9z0x)
* **Scanium:** [View Example](https://scanium.io/Oraichain/staking/oraivaloper1uhcwtfntsvk8gpwfxltesyl4e28aalmq9v9z0x)

***

## **How to Set or Update Your Validator Image**

### **On ORAI Scan (scan.orai.io)**

1. Navigate to your **validator page**.
2. **Double-click** on the validator image.
3. **Select** and upload your new image.
4. **Approve** the request to finalize the update.

***

### **On Scanium (scanium.io)**

Scanium fetches validator images directly from **Keybase**. Follow these steps to update your image:

#### **Step 1: Set Up a Keybase Profile**

* If you don’t have a **Keybase** account, create one.
* Retrieve your **public Keybase ID** (e.g., `2798DB6D73F30696`).

#### **Step 2: Update Your Validator Identity**

If your validator identity is not set, submit a transaction to link your Keybase ID:

```bash
oraid tx staking edit-validator \
--identity "your-keybase-id" \
--chain-id Oraichain \
--from wallet \
--gas-adjustment 1.4 \
--gas auto \
--gas-prices 0.01orai \
-y
```

#### **Step 3: Change Your Keybase Avatar**

* Set your **Keybase profile picture** to the desired validator image.
* Scanium will automatically fetch and update the validator image from your Keybase account.

***

### **Final Thoughts**

Keeping your validator image updated enhances your validator’s visibility and credibility in the network. Follow the steps above to ensure your validator stands out!

🚀 **Make your validator recognizable today!**


# Tenderduty

![sample](/files/5xf1xtlehYlo68DH7vUY)

## What is Tenderduty?

**Tenderduty** is a monitoring tool specifically designed for validators in **Tendermint-based blockchains**, such as **Cosmos, Osmosis, and other related networks**. It helps track validator performance, ensuring they remain online, properly sign blocks, and avoid slashing or jailing. Tenderduty allows validators to monitor their node's health and receive alerts in case of issues like downtime, missed blocks, or risks of slashing.

#### Key Features of Tenderduty:

* **Validator uptime and block signing performance monitoring.**
* **Alerts for missed blocks or downtime** (via email, Telegram, Discord, Slack, or PagerDuty).
* **Prevention of slashing risks** by identifying potential issues early.
* **A web interface** for viewing real-time statistics and logs.

Tenderduty is particularly useful for validators who need to ensure their node remains in good standing within the network. Downtime or misbehavior can result in penalties, including **slashing and jailing**.

***

## Installation

The [official Tenderduty repository](https://github.com/blockpane/tenderduty) is **archived**, but it is still a **useful monitoring tool for Cosmos validators** now and in the future.

In this tutorial, I recommend using **Docker** to install and configure Tenderduty for monitoring a validator on a Tendermint-based blockchain.

#### Prerequisites:

* **Operating System**: Linux (e.g., Ubuntu)
* **Docker**: Installed
* **Validator Node**: A running Tendermint-based node to monitor
* **Notification Service**: Tenderduty supports Discord, Telegram, Slack, and PagerDuty; you need a webhook or API key for notifications.

***

## Step-by-Step Guide

### 1. Create a Folder and `docker-compose.yml` File

First, create a directory for Tenderduty and navigate into it:

```bash
mkdir tenderduty
cd tenderduty
touch docker-compose.yml
touch config.yml
```

Then, add the following **Docker Compose** configuration to `docker-compose.yml`. This will set up Tenderduty with a web dashboard and Prometheus exporter.

```yaml
version: '3.2'
services:
  tenderduty:
    image: ghcr.io/blockpane/tenderduty:latest
    command: ""
    ports:
      - "8888:8888" # Web Dashboard
      - "28686:28686" # Prometheus Exporter
    volumes:
      - ./config.yml:/var/lib/tenderduty/config.yml
    logging:
      driver: "json-file"
      options:
        max-size: "20m"
        max-file: "10"
    restart: unless-stopped
```

If needed, you can **modify the exposed ports** (`8888` for the dashboard and `28686` for Prometheus).

***

### 2. Configure Tenderduty

Tenderduty requires a **configuration file** (`config.yml`) to specify the networks and validators to monitor.

#### Open the Configuration File:

```bash
nano config.yml
```

#### Example Configuration for **Oraichain** (Using **Discord Alerts**)

```yaml
---
enable_dashboard: yes
listen_port: 8888
hide_logs: no
node_down_alert_minutes: 3
node_down_alert_severity: critical
prometheus_enabled: yes
prometheus_listen_port: 28686

pagerduty:
  enabled: no
discord:
  enabled: yes
  webhook: https://discord.com/api/webhooks/999999999999999999/zzzzzzz
telegram:
  enabled: no
slack:
  enabled: no
healthcheck:
  enabled: no

chains:
  "Oraichain":
    chain_id: Oraichain
    valoper_address: oraivaloperXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    public_fallback: no
    alerts:
      discord:
        enabled: yes
        webhook: "https://discord.com/api/webhooks/999999999999999999/zzzzzzz"
    nodes:
      - url: tcp://localhost:26657
        alert_if_down: yes
      - url: https://rpc.orai.io:443
        alert_if_down: no        
```

**Explanation:**

* **Alerts are enabled via Discord.**
* **Two nodes are monitored**:
  * `localhost:26657` (your own validator node) – raises alerts if down.
  * `rpc.orai.io` (fallback public RPC) – does not raise alerts.

For a full example configuration, check the [official sample](https://github.com/blockpane/tenderduty/blob/main/example-config.yml).

***

### 3. Start Tenderduty

After setting up the configuration file, start Tenderduty:

```bash
docker compose up -d
```

#### Access the Web Interface:

Once running, visit **`http://localhost:8888`** in your browser to view the monitoring dashboard.

***

### 4. Monitoring & Alerts

Tenderduty will now:

* **Monitor your validator’s status** in real-time.
* **Send alerts** (via Discord, Telegram, Slack, etc.) if the node goes down or misses blocks.
* **Provide logs and metrics** accessible via the web dashboard.

To check the logs:

```bash
docker logs -f tenderduty
```

***

## Conclusion

Congratulations! 🎉 You have successfully set up **Tenderduty** to monitor your validator on a Tendermint-based blockchain. With Tenderduty running, you can **stay informed about validator health, avoid slashing risks, and react quickly to potential issues.** 🚀

For further customization, refer to the **official documentation** (though archived):\
👉 [Tenderduty GitHub Repository](https://github.com/blockpane/tenderduty)


# Grafana

![Sample](/files/U4pJCQDgZl4xlFCvGm77)

## **Prerequisites**

Before proceeding, ensure you have:

* **A running Oraichain validator node**
* [**Grafana**](https://grafana.com) **installed**
* [**Prometheus**](https://prometheus.io) **installed**

***

## **Step 1: Change Node Configuration**

Modify the configuration file to enable Prometheus.

```sh
nano ~/.oraid/config/config.toml
```

Find and update the `[instrumentation]` section:

```toml
[instrumentation]
prometheus = true
prometheus_listen_addr = ":26660"
max_open_connections = 3
namespace = "tendermint"
```

Then **restart your node** to apply the changes.

```sh
sudo systemctl restart oraid
```

The **Prometheus endpoint** will now be available on **port `26660`**.

***

## **Step 2: Setup Cosmos Exporter**

[`cosmos-exporter`](https://github.com/solarlabsteam/cosmos-exporter) collects validator metrics.

### **1. Download and Install**

```sh
wget https://github.com/solarlabsteam/cosmos-exporter/releases/download/v0.3.0/cosmos-exporter_0.3.0_Linux_x86_64.tar.gz
tar xvfz cosmos-exporter_0.3.0_Linux_x86_64.tar.gz
sudo mv ./cosmos-exporter /usr/bin/
sudo rm cosmos-exporter_0.3.0_Linux_x86_64.tar.gz
```

### **2. Create a Systemd Service**

```sh
sudo nano /etc/systemd/system/cosmos-exporter.service
```

Insert the following configuration (update the **gRPC endpoint** and **listening port `9300`** accordingly):

```ini
[Unit]
Description=Cosmos Exporter
After=network-online.target

[Service]
User=root
TimeoutStartSec=0
CPUWeight=95
IOWeight=95
ExecStart=cosmos-exporter --bech-account-prefix=orai --bech-account-pubkey-prefix=oraipub --bech-consensus-node-prefix=oraivalcons --bech-consensus-node-pubkey-prefix=oraivalconspub --bech-validator-prefix=oraivaloper --bech-validator-pubkey-prefix=oraivaloperpub --denom=orai --denom-coefficient=1000000 --listen-address=:9300 --log-level=debug --node=localhost:9090
Restart=always
RestartSec=2
LimitNOFILE=800000
KillSignal=SIGTERM

[Install]
WantedBy=multi-user.target
```

### **3. Enable and Start the Service**

```sh
sudo systemctl enable cosmos-exporter
sudo systemctl start cosmos-exporter
sudo systemctl status cosmos-exporter
sudo journalctl -u cosmos-exporter -f --output cat  # View logs
```

The Cosmos Exporter service is now **running on port `9300`**.

***

## **Step 3: Update Prometheus Configuration**

Edit your Prometheus configuration file:

```sh
nano /etc/prometheus/prometheus.yml
```

Add the following scrape jobs:

```yaml
scrape_configs:
  - job_name: "cosmops"
    static_configs:
      - targets: ["localhost:26660"]
        labels:
          group: "cosmops"

  - job_name: "validators"
    metrics_path: /metrics/validators
    static_configs:
      - targets: ["localhost:9300"]
        labels:
          group: "orai"

  - job_name: "validator"
    scrape_interval: 15s
    metrics_path: /metrics/validator
    static_configs:
      - targets:
          - oraivaloper100000000000000000000000000000000000000
    relabel_configs:
      - source_labels: [__address__]
        target_label: __param_address
      - source_labels: [__param_address]
        target_label: instance
      - target_label: __address__
        replacement: localhost:9300
```

This configuration:

* Scrapes **your node's metrics** from **port `26660`**.
* Collects **Cosmos Exporter metrics** from **port `9300`**.
* Separates **all validators** from **your validator** for detailed monitoring.
* Change `oraivaloper1000` to your own validator address.

Restart Prometheus to apply the changes:

```sh
sudo systemctl restart prometheus
```

***

## **Step 4: Configure Grafana**

### **1. Access Grafana**

Open your browser and go to grafana webUI.

### **2. Import the Cosmos Validator Dashboard**

1. Go to **Dashboards** → **Import**.
2. Enter the **Dashboard ID**: `15991`.
3. Select **Prometheus** as the data source.
4. Click **Import**.

Your Cosmos validator monitoring dashboard is now live! 🎉

***

## **Step 5: Summary of Steps**

| Step | Task                          | Description                                     |
| ---- | ----------------------------- | ----------------------------------------------- |
| 1    | **Enable Prometheus in Node** | Exposes metrics on port **`26660`**             |
| 2    | **Install Cosmos Exporter**   | Collects validator data on port **`9300`**      |
| 3    | **Update Prometheus Config**  | Scrapes **both `26660` and `9300`**             |
| 4    | **Setup Grafana Dashboard**   | Displays metrics with **Dashboard ID: `15991`** |

### **Ports Used**

| Service                    | Port    | Purpose                    |
| -------------------------- | ------- | -------------------------- |
| **Cosmos Node Prometheus** | `26660` | Exposes node metrics       |
| **Cosmos Exporter**        | `9300`  | Validator-specific metrics |
| **Prometheus**             | `9090`  | Metric collection          |
| **Grafana**                | `3000`  | Dashboard UI               |

***

## **Conclusion**

By following this guide, you’ve successfully set up monitoring for your Cosmos validator node using **Grafana, Prometheus, and Cosmos Exporter**.

**Last tip**: Monitoring stack needs to be deployed on seperate machine to be able to notify in case if validator goes down! To run monitoring stack you dont need beastly server with multiple cores. It will be more than enough to run it on smallest available vps (example: Ubuntu 22.04 / 1 VCPU / 2 GB RAM / 20 GB SSD)


# Tracking Unvoted Proposals

## **Introduction**

As an **Oraichain validator**, it’s crucial to stay updated with governance proposals and ensure you **cast your votes**. Missing votes can affect your reputation and might even lead to delegation losses. The `cosmos-proposals-checker` tool simplifies the process of tracking unvoted proposals.

This tutorial walks you through:

1. **Downloading the Binary**
2. **Setting Up the Configuration**
3. **Creating a Systemd Service**

***

## **1. Download and Install `cosmos-proposals-checker`**

### **Step 1: Download the Latest Release**

Check the latest release from the [GitHub repository](https://github.com/QuokkaStake/cosmos-proposals-checker)

Example with version **v5.14.1**:

```sh
wget https://github.com/QuokkaStake/cosmos-proposals-checker/releases/download/v5.14.1/cosmos-proposals-checker_5.14.1_linux_amd64.tar.gz -O cosmos-proposals-checker.tar.gz
```

### **Step 2: Extract and Move the Binary to the System Apps Folder**

```sh
tar -xzvf cosmos-proposals-checker.tar.gz
chmod +x cosmos-proposals-checker
sudo mv cosmos-proposals-checker /usr/local/bin/
```

### **Step 3: Verify Installation**

Now you can run it from anywhere:

```sh
cosmos-proposals-checker --version
```

The output should be:

```
cosmos-proposals-checker version 5.14.1
```

***

## **2. Setting Up the Configuration**

Now, let's **download and configure the config file**.

### **Step 1: Download the Example Configuration**

For this tutorial, we will place the configuration file in `/root/config.yml`, but you can choose your own path.

```sh
wget https://raw.githubusercontent.com/QuokkaStake/cosmos-proposals-checker/5cb45561274c78d9e153919b3bb33e3b3f364231/config.example.toml -O /root/config.yml
```

### **Step 2: Edit the Configuration File**

Open the configuration file:

```sh
vi /root/config.yml
```

### **Step 3: Update the Chain Configuration**

Modify the file to match **Oraichain settings**. Below is an example:

```toml
[[chains]]
name = "Oraichain"
pretty-name = "Oraichain"
keplr-name = "Oraichain"
mintscan-prefix = ""
lcd-endpoints = ["https://lcd.orai.io", "https://oraichain-rest.publicnode.com"]
wallets = [
    { address = "orai1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" }
]
```

Replace **`orai1aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa`** with your **actual validator wallet address**.

### **Step 4: Set the Reporting Interval**

To schedule daily reports at **04:00 AM**, update:

```toml
interval = "0 4 * * *"
```

### **Step 5: Configure Notification Channels**

`cosmos-proposals-checker` supports:

* **Telegram**
* **PagerDuty**

Modify the notifier settings in the configuration file based on your preferred method.

***

## **3. Create a Systemd Service**

To **automate execution**, we will create a **systemd service**.

### **Step 1: Create the Service File**

```sh
sudo nano /etc/systemd/system/cosmos-proposals-checker.service
```

### **Step 2: Add the Following Configuration**

```ini
[Unit]
Description=Cosmos Proposals Checker
After=network.target

[Service]
ExecStart=/usr/local/bin/cosmos-proposals-checker --config /root/config.yml
Restart=always
User=root

[Install]
WantedBy=multi-user.target
```

Make sure to replace `/root/config.yml` with your **actual configuration file path**.

***

### **Step 3: Reload and Start the Systemd Service**

```sh
sudo systemctl daemon-reload
sudo systemctl start cosmos-proposals-checker
sudo systemctl enable cosmos-proposals-checker
```

***

## **4. Check Logs and Service Status**

To verify that the service is running correctly:

### **Check the Service Status**

```sh
systemctl status cosmos-proposals-checker
```

### **View Logs in Real Time**

```sh
journalctl -u cosmos-proposals-checker -f
```

***

Now, your validator will **never miss governance votes again!** 🚀


# Tmtop

![sample](/files/s369U3V4o6wMpA0Z1nrJ)

## **tmtop: Real-time Tendermint Node Monitoring**

`tmtop` is a powerful CLI tool designed to monitor **Tendermint-based blockchain nodes** in real-time. It provides live insights into your node’s performance, including block heights, peer connections, transaction rates, and more.

#### **Repository:** [GitHub - QuokkaStake/tmtop](https://github.com/QuokkaStake/tmtop)

***

### **1. Installation**

You can install `tmtop` by building it from source.

#### **Step 1: Clone the Repository**

```bash
git clone https://github.com/QuokkaStake/tmtop.git
cd tmtop
```

#### **Step 2: Build the Binary**

```bash
go build -o tmtop
```

#### **Step 3: Move the Binary to Your Path**

```bash
sudo mv tmtop /usr/local/bin/
```

Verify the installation:

```bash
tmtop --version
```

***

### **2. Running tmtop**

Once installed, start `tmtop` by running:

```bash
tmtop <NODE_RPC_ENDPOINT>
```

For example, if your node is running locally on port 26657:

```bash
tmtop http://localhost:26657
```

#### **Common Flags**

| Flag                               | Description                                                                                     |
| ---------------------------------- | ----------------------------------------------------------------------------------------------- |
| --block-time-refresh-rate duration | Block time refresh rate (default 30s)                                                           |
| --chain-info-refresh-rate duration | Chain info refresh rate (default 5m0s)                                                          |
| --chain-type string                | Chain type. Allowed values are: 'cosmos-rpc', 'cosmos-lcd', 'tendermint' (default "cosmos-rpc") |
| --consumer-chain-id string         | Consumer chain ID                                                                               |
| --debug-file string                | Path to file to write debug info/logs to                                                        |
| --disable-emojis                   | Disable emojis in output                                                                        |
| --halt-height int                  | Custom halt-height                                                                              |
| --help                             | help for tmtop                                                                                  |
| --lcd-host string                  | LCD API host URL                                                                                |
| --provider-rpc-host string         | Provider chain RPC host URL                                                                     |
| --refresh-rate duration            | Refresh rate (default 1s)                                                                       |
| --timezone string                  | Timezone to display dates in                                                                    |
| --upgrade-refresh-rate duration    | Upgrades refresh rate (default 30m0s)                                                           |
| --validators-refresh-rate duration | Validators refresh rate (default 1m0s)                                                          |
| --verbose                          | Display more debug logs                                                                         |
| --version                          | version for tmtop                                                                               |

Example with a 5-second refresh rate:

```bash
tmtop http://localhost:26657 --refresh-rate=5
```

***

### **3. Troubleshooting**

#### **Issue: Cannot Connect to RPC**

**Error:** `failed to fetch data from RPC`\
**Solution:** Ensure your node’s RPC endpoint is accessible. Try:

```bash
curl http://localhost:26657/status
```

If the request fails, check your firewall and node settings.

#### **Issue: Incorrect Block Height**

If `tmtop` shows an outdated block height, your node might be lagging. Check logs:

```bash
journalctl -u oraid -f
```

Or you can use public oraichain RPC

```bash
tmtop https://rpc.orai.io:443
```

***

### **4. Conclusion**

`tmtop` is an excellent tool for real-time monitoring of Tendermint-based blockchain nodes. It provides vital stats that help in maintaining a healthy validator.

🔹 **Stay ahead, monitor your node, and ensure optimal performance with `tmtop`!** 🚀


