# Welcome To Ramestta

Ramestta was first proposed by **Open source community**. community believed that to achieve true decentralization, a community must have its own low cost blockchain solution. For this reason, Ramestta was presented as one of the primary goals of the community experiment as it, theoretically, would reduce transaction fees for those involved in the EVM ecosystem.&#x20;

community initially stated that Ramestta's transaction fees would be minimal, if not zero. "Ramestta will offer low fees for every service, game, or application built on it,".

Although one of the most secure blockchains in existence, Ethereum faces a number of challenges, including high gas fees.&#x20;

In the same vein as other projects, Ramestta the Layer-2 solution will also feature a simple and effective $RAMA burning mechanism. Moreover, Ramestta is designed to facilitate it and may also serve as a bridge between different ecosystems.

Continue reading to see how RAMA as the primary gas token for Ramestta continues to evolve the RVM Ecosystem!&#x20;


# Overview

**Polygon: Ramestta's Foundation**

Polygon is a highly successful blockchain scaling solution for Ethereum that aims to improve its scalability and overcome its limitations. Polygon enables faster and more cost-effective transactions by providing a layer 2 scaling solution that works in conjunction with the Ethereum network. The platform's blockchain technology allows users to create programmable tokens and smart contracts, similar to Ethereum, and is utilized for various applications such as initial coin offerings (ICOs) of fungible tokens and non-fungible tokens (NFTs).

Decentralized nodes on the Polygon network contribute to the security of the overall blockchain infrastructure, which is structured around the Ethereum ecosystem.

**Ramestta, The Side Chain of "Teh People"**

Ramestta has been designed to provide people, developers, and businesses with a side chain solution that offers faster transaction speeds and lower fees compared to other blockchains, making it a cost-effective option for those interested in blockchain technology. The side chain ensures secure and transparent creation and exchange of digital assets. Additionally, it serves as a base for the development of decentralized applications (DApps).

**Benefits of using Ramestta**&#x20;

There are many benefits of using the Ramestta side chain. Some of the key benefits include:

1. **Security:** The Ramestta side chain is a highly secure and tamper-proof platform that employs its own consensus mechanism, ensuring the security of the blockchain. Validators participate by staking their native tokens to validate transactions, enhancing the security of the side chain.
2. **Transparency:** Ramestta provides transparency, allowing users to track all transactions and activities on the side chain.
3. **Efficiency:** Ramestta is designed to be a faster and more efficient platform, processing transactions quickly and easily.
4. **Cost-effectiveness:** Users can save on transaction fees by utilizing Ramestta, making it a cost-effective side chain solution.
5. **Decentralization:** Ramestta's decentralized nature is achieved through a network of computers collectively maintaining a copy of the side chain. This ensures tamper-proof and immune operations, free from manipulation by any single entity.


# Ramestta Pos Chain

Ramestta's PoS (Proof-of-Stake) chain utilizes side-chains to process transactions, resulting in unparalleled transaction speed and cost efficiency. PoS also guarantees asset security by employing the reliable Plasma bridge framework and a decentralized network of PoS validators.

**Speed:** To keep users engaged and focused, apps, games, metaverses, and other utilities require fast transaction processing. Ramestta satisfies this requirement by completing transactions at an astonishingly fast pace, significantly outperforming Polygon transactions per second. Bridging, deposits, and withdrawals are seamless and effective. Ramestta maintains the security features of Polygon while substantially enhancing the blockchain's speed.

**Scalability:** Scalability is just as critical as speed, and Ramestta has been designed to scale and adjust to the requirements of any organization, product, platform, project, community, or token. It has been designed to be compatible with major ERC standards, ensuring seamless integration. Validators and checkpoints are submitted to Polygon to guarantee security, and a dynamic and enthusiastic community propels adoption and user engagement.

**Flexibility & Simplicity:** The transition to Web 3 and Web 4 will need a straightforward and adaptable UI, UX, and onboarding process to ensure a seamless flow of users from Web 2 (www) to this new system. Ramestta's network is fully EVM compatible, allowing smart contracts to be deployed directly on it. Building DApps on the blockchain is simpler, and it's easy to transfer tokens between Ramestta and Polygon.

**Cost:** In the current world, businesses must utilize Web 3 to stay competitive, but it's hard to do so when fees are cost-prohibitive. Ramestta solves this by keeping many transactions below a $.01! With Ramestta's proof-of-stake system, transaction costs are fractional, significantly lower than Polygon's. Burning EIP 1559 tokens will result in more predictable gas fees and deflationary token economics.

Currently, Ramestta's PoS chain provides the following services:

* Send, receive, and store your assets on the Ramestta network with the Ramestta Wallet.
* Ramestta Bridge, for cross-network withdrawals and deposits.
* Staking with Ramestta Staking: Get rewards for staking.


# Building on Ramestta

Polygon developers are by default Ramestta developers. Welcome. Simply switch to the Ramestta RPC and get started. All familiar tools used on Polygon are supported on Ramestta. Whether it is Truffle, Remix, or Web3js,Ethers,Viem,Wagmi, Ramestta offers the same UX as Polygon.

Connect your wallet and deploy any decentralized application to either Ramestta Mainnet or Ramestta Testnet.

Ramestta Testnet connects to Mumbai , which acts as its ParentChain, a testnet layer 1 (L1).

Find all the network-related details in the network documentation.

**Overview**

Ramestta is a layer 2 (L2) network to Polygon, employing a proof-of-stake (PoS) consensus mechanism, and thus composed of the following two layers:

Heimdall layer, a consensus layer consisting of a set of proof-of-stake Heimdall nodes for monitoring staking contracts deployed on the Polygon mainnet, and committing the Ramestta Network checkpoints to the Polygon mainnet. Heimdall is based on Tendermint. Bor layer, an execution layer which is made up of a set of block-producing Bor nodes shuffled by Heimdall nodes. Bor is based on Go Ethereum (Geth).

In order to be a validator on the Ramestta Network, you need to:

Run a sentry node, which is a separate machine running a Heimdall node and a Bor node. A sentry node is open to all nodes on the Ramestta Network. Run a validator node, which is a separate machine running a Heimdall node and a Bor node. A validator node is only open to its sentry node and closed to the rest of the network. Stake the RAMA tokens in the staking contracts deployed on the Polygon mainnet. Wallets¶

To interact with the Ramestta Network, you need to have a EVM-based wallet because Ramestta runs on Ramestta Virtual Machine (RVM). You can choose to set up a Metamask or Ramestta Wallet.

**Smart contracts**

Ramestta supports many services you can use to test, compile, debug, and deploy decentralized applications onto the Ramestta Network. These include deployment using thirdweb, Alchemy, Chainstack, QuickNode, Remix, Truffle, Hardhat, and Replit.

**Connecting to Ramestta Chain**

You can add Ramestta Chain to MetaMask or directly use Arkane, which allows you to connect to Ramestta using RPC.

In order to connect with the Ramestta network to read blockchain information, we recommend using the Alchemy SDK.

```
// Javascript
// Setup: npm install alchemy-sdk
const { Alchemy, Network } = require("alchemy-sdk");

const settings = {
  apiKey: "demo", // Can replace with your API Key from https://www.alchemy.com
  network: Network.Ramestta Mainnet, // Can replace with Ramestta mainnet
};

const alchemy = new Alchemy(settings);

async function main() {
  const latestBlock = await alchemy.core.getBlockNumber();
  console.log("The latest block number is", latestBlock);
}

main();

```

\
**Building a new dApp on Ramestta?**

Decentralized applications (dApps) act as the bridge between users and their data privacy on the blockchain. The increasing number of dApps validates their usefulness within the blockchain ecosystem, solving challenges like executing transactions between two participants without the need for central authority via smart contracts.

Suppose you have no prior experience building decentralized applications (dApps). In that case, the below-mentioned resources will give you a head start on the tools required to build, debug, and deploy dApps on the Ramestta Network.

Full Stack dApp: Tutorial Series Web3.js Ethers.js thirdweb Remix Truffle Metamask Arkane Develop a dApp using Fauna, Ramestta, and React


# Architecture

This section provides a detailed explanation of the Ramestta Proof of Stake (PoS) architecture, focusing on the node perspective. The Ramestta PoS system comprises two essential layers: Heimdall, responsible for consensus, and Bor, responsible for execution.

Nodes on Ramestta are structured with a two-layer implementation, represented by Bor (the block producer layer) and Heimdall (the validator layer). On the execution client side, the explanation delves into snapshots, state syncing, network configurations, and commonly used commands for running PoS nodes.

On the consensus client side, it describes how Heimdall manages the authentication of account addresses, validator key management, gas limit management, transaction verification enhancement, balance transfers, staking, and general chain management.

**Architectural Overview:-**&#x54;he Ramestta Network is divided into two layers:

#### Layer 1 (Polygon):

1. **Consensus Layer (Heimdall):**
   * Implement a consensus layer based on a Proof-of-Stake (PoS) mechanism, where Heimdall nodes monitor staking contracts on the Ethereum mainnet.
   * Heimdall nodes commit checkpoints to the Ethereum mainnet for added security.
   * This layer ensures the overall security and integrity of the network.
2. **Execution Layer (Bor):**
   * Utilize an execution layer, Bor, based on Go Ethereum (Geth).
   * Bor nodes produce blocks based on the information received from Heimdall nodes.
   * This layer is responsible for executing smart contracts and processing transactions.
3. **Staking Contracts:**
   * Deploy staking contracts on the Ethereum mainnet for validators to stake MATIC tokens.
   * Validators run Heimdall and Bor nodes and participate in securing the network.
4. **Interoperability:**
   * Ensure compatibility with Ethereum standards, allowing seamless integration with the broader Ethereum ecosystem.
   * Validators and checkpoints are submitted to Ethereum to maintain interoperability and security.

#### Layer 2 Side Chain (Ramestta):

1. **Consensus Layer (Heimdall for Ramestta):**
   * Implement a consensus layer (Heimdall for Ramestta) with a set of PoS nodes specifically for monitoring staking contracts on the Polygon mainnet.
   * Commit Ramestta Network checkpoints to the Polygon mainnet.
2. **Execution Layer (Bor for Ramestta):**
   * Utilize an execution layer, Bor for Ramestta, based on Go Ethereum (Geth).
   * Bor nodes for Ramestta produce blocks based on the information received from Heimdall for Ramestta nodes.
   * This layer handles the execution of smart contracts and transaction processing specific to Ramestta.
3. **Staking Contracts for Ramestta:**
   * Deploy staking contracts on the Polygon mainnet for Ramestta validators to stake tokens (e.g., RAMA tokens).
   * Validators run Heimdall for Ramestta and Bor for Ramestta nodes and play a crucial role in securing the Ramestta side chain.
4. **Interoperability with Polygon:**
   * Ensure compatibility with Polygon standards, allowing for interoperability with the Polygon network.
   * Validators and checkpoints may be submitted to the Polygon mainnet to maintain a connection with the broader Polygon ecosystem.

#### Inter-Chain Communication:

1. **Bridge Mechanism:**
   * Implement a bridge mechanism that facilitates the transfer of assets and information between the Polygon mainnet and the Ramestta mainnet.
   * Validators and checkpoints are involved in the bridging process.
2. **Cross-Chain Communication:**
   * Establish communication channels between the Polygon mainnet and the Ramestta side chain to enable interoperability.
   * Validators play a role in maintaining the consistency and security of cross-chain communication.
3. **Smart Contracts:**
   * Develop smart contracts that handle the locking and unlocking of assets during the bridging process.
4. **User Wallet Integration:**
   * Ensure that user wallets (e.g., Metamask, Arkane) can seamlessly interact with both the Polygon mainnet and the Ramestta side chain.


# Heimdall

Heimdall is the heart of the Ramestta network. It manages validators, block producer selection, spans, the state-sync mechanism between Polygon and Ramestta, and other essential aspects of the system. It uses the Cosmos-SDK and a forked version of Tendermint, called Peppermint. Heimdall removes some of the modules from Cosmos-SDK but mostly uses a customized version of it while following the same pattern.

## Heimdall and Bor

Heimdall’s `bor` module is responsible for managing span intervals and coordinating interactions with the Bor chain. Specifically, it determines when a new span can be proposed on Heimdall based on the current block number `n` and the current span `span`. A new span proposal is permissible when the current Bor chain block number `n` falls within the range of `span.StartBlock` and `span.EndBlock` (inclusive of `StartBlock` and exclusive of `EndBlock`). Validators on the Heimdall chain can propose a new span when these conditions are met.

### Messages <a href="#messages" id="messages"></a>

#### MsgProposeSpan <a href="#msgproposespan" id="msgproposespan"></a>

The `MsgProposeSpan` message plays a crucial role in setting up the validator committee for a specific span and records a new span in the Heimdall state. This message is detailed in the Heimdall source code at bor/handler.go#L27.

```
// MsgProposeSpan creates msg propose span
type MsgProposeSpan struct {
 ID         uint64                  `json:"span_id"`
 Proposer   hmTypes.HeimdallAddress `json:"proposer"`
 StartBlock uint64                  `json:"start_block"`
 EndBlock   uint64                  `json:"end_block"`
 ChainID    string                  `json:"bor_chain_id"`
}
```

**Selection of Producers**

The process for choosing producers from among all validators involves a two-step mechanism:

**1. Slot Allocation Based on Validator Power:** Each validator is assigned a number of slots proportional to their power. For instance, a validator with a power rating of 10 will receive 10 slots, while one with a power rating of 20 will receive 20 slots. This method ensures that validators with higher power have a correspondingly higher chance of being selected.

**2. Shuffling and Selection:** All allocated slots are then shuffled using a `seed` derived from the Polygon (MATIC 1.0) block hash corresponding to each span `n`. The first `producerCount` producers are selected from this shuffled list. The `bor` module on Heimdall employs the Polygon 2.0 shuffle algorithm for this selection process. The algorithm’s implementation can be viewed at bor/selection.go.

* This method of selection ensures that the process is both fair and weighted according to the validators’ power, thereby maintaining a balanced and proportional representation in the span committee.

```
// SelectNextProducers selects producers for the next span by converting power to slots
// spanEligibleVals - all validators eligible for next span
func SelectNextProducers(blkHash common.Hash, spanEligibleVals []hmTypes.Validator, producerCount uint64) (selectedIDs []uint64, err error) {
 if len(spanEligibleVals) <= int(producerCount) {
  for _, val := range spanEligibleVals {
   selectedIDs = append(selectedIDs, uint64(val.ID))
  }
  return
 }

 // extract seed from hash
 seed := helper.ToBytes32(blkHash.Bytes()[:32])
 validatorIndices := convertToSlots(spanEligibleVals)
 selectedIDs, err = ShuffleList(validatorIndices, seed)
 if err != nil {
  return
 }
 return selectedIDs[:producerCount], nil
}

// converts validator power to slots
func convertToSlots(vals []hmTypes.Validator) (validatorIndices []uint64) {
 for _, val := range vals {
  for val.VotingPower >= types.SlotCost {
   validatorIndices = append(validatorIndices, uint64(val.ID))
   val.VotingPower = val.VotingPower - types.SlotCost
  }
 }
 return validatorIndices
}
```

### Types <a href="#types" id="types"></a>

Here are the span details that Heimdall uses:

```
// Span structure
type Span struct {
 ID                uint64       `json:"span_id" yaml:"span_id"`
 StartBlock        uint64       `json:"start_block" yaml:"start_block"`
 EndBlock          uint64       `json:"end_block" yaml:"end_block"`
 ValidatorSet      ValidatorSet `json:"validator_set" yaml:"validator_set"`
 SelectedProducers []Validator  `json:"selected_producers" yaml:"selected_producers"`
 ChainID           string       `json:"bor_chain_id" yaml:"bor_chain_id"`
}
```

### Parameters <a href="#parameters" id="parameters"></a>

The Bor module contains the following parameters:

| Key             | Type   | Default value                        | Duration (\*)                 |
| --------------- | ------ | ------------------------------------ | ----------------------------- |
| SprintDuration. | uint64 | 16 blocks                            | 32 seconds                    |
| SpanDuration    | uint64 | 100 \* SprintDuration = 1,600 blocks | 3,200 seconds (53min and 20s) |
| ProducerCount   | uint64 | 4 blocks                             | 8 seconds                     |

(\*): Given that blocks are produced every 2 seconds on Bor.

### CLI Commands <a href="#cli-commands" id="cli-commands"></a>

#### Span propose tx <a href="#span-propose-tx" id="span-propose-tx"></a>

```
heimdallcli tx bor propose-span \
 --start-block <start-block> \
 --chain-id <heimdall-chain-id>
 
```

#### Query current span <a href="#query-current-span" id="query-current-span"></a>

```
heimdallcli query bor span latest-span --chain-id <heimdall-chain-id>
```

Expected output:

```
{
  "span_id":2,
  "start_block":6656,
  "end_block":13055,
  "validator_set":{
    "validators":[
      {
        "ID":1,
        "startEpoch":0,
        "endEpoch":0,
        "power":1,
        "pubKey":"0x04b12d8b2f6e3d45a7ace12c4b2158f79b95e4c28ebe5ad54c439be9431d7fc9dc1164210bf6a5c3b8523528b931e772c86a307e8cff4b725e6b4a77d21417bf19",
        "signer":"0x6c468cf8c9879006e22ec4029696e005c2319c9d",
        "last_updated":"",
        "accum":0
      }
    ],
    "proposer":{
      "ID":1,
      "startEpoch":0,
      "endEpoch":0,
      "power":1,
      "pubKey":"0x04b12d8b2f6e3d45a7ace12c4b2158f79b95e4c28ebe5ad54c439be9431d7fc9dc1164210bf6a5c3b8523528b931e772c86a307e8cff4b725e6b4a77d21417bf19",
      "signer":"0x6c468cf8c9879006e22ec4029696e005c2319c9d",
      "last_updated":"",
      "accum":0
    }
  },
  "selected_producers":[
    {
      "ID":1,
      "startEpoch":0,
      "endEpoch":0,
      "power":1,
      "pubKey":"0x04b12d8b2f6e3d45a7ace12c4b2158f79b95e4c28ebe5ad54c439be9431d7fc9dc1164210bf6a5c3b8523528b931e772c86a307e8cff4b725e6b4a77d21417bf19",
      "signer":"0x6c468cf8c9879006e22ec4029696e005c2319c9d",
      "last_updated":"",
      "accum":0
    }
  ],
  "bor_chain_id":"1370"
}
```

#### Query span by id <a href="#query-span-by-id" id="query-span-by-id"></a>

```
heimdallcli query bor span --span-id <span-id> --chain-id <heimdall-chain-id>
```

It prints the result in same format as above.

#### Parameters <a href="#parameters_1" id="parameters_1"></a>

To print all params;

```
heimdalldcli query bor params
```

Expected Result:

```
sprint_duration: 16
span_duration: 1600
producer_count: 4
```

### REST APIs <a href="#rest-apis" id="rest-apis"></a>

| Name            | Method | Endpoint          |
| --------------- | ------ | ----------------- |
| Span details    | GET    | /bor/span/span-id |
| Get latest span | GET    | /bor/latest-span  |
| Get params      | GET    | /bor/params       |

## Authentication

Heimdall’s `auth` module is responsible for specifying the base transaction and account types for an application. It contains the ante handler, where all basic transaction validity checks (signatures, nonces, auxiliary fields) are performed, and exposes the account keeper, which allows other modules to read, write, and modify accounts.

### Gas and fees <a href="#gas-and-fees" id="gas-and-fees"></a>

Fees serve two purposes for an operator of the network.

Fees limit the growth of the state stored by every full node and allow for general purpose censorship of transactions of little economic value. Fees are best suited as an anti-spam mechanism where validators are disinterested in the use of the network and identities of users.

Since Heimdall doesn’t support custom contract or code for any transaction, it uses fixed cost transactions. For fixed cost transactions, the validator can top up their accounts on the Ethereum chain and get tokens on Heimdall using the [Topup](https://docs.polygon.technology/pos/architecture/heimdall/topup/) module.

### Types <a href="#types" id="types"></a>

Besides accounts (specified in State), the types exposed by the auth module are **StdSignature**, the combination of an optional public key and a cryptographic signature as a byte array, **StdTx**, a struct that implements the `sdk.Tx` interface using **StdSignature**, and **StdSignDoc**, a replay-prevention structure for **StdTx** which transaction senders must sign over.

#### StdSignature <a href="#stdsignature" id="stdsignature"></a>

A `StdSignature` is the types of a byte array.

```
// StdSignature represents a sig
type StdSignature []byte
```

#### StdTx <a href="#stdtx" id="stdtx"></a>

A `StdTx` is a struct that implements the `sdk.Tx` interface, and is likely to be generic enough to serve the purposes of many types of transactions.

```
type StdTx struct {
  Msg       sdk.Msg      `json:"msg" yaml:"msg"`
  Signature StdSignature `json:"signature" yaml:"signature"`
  Memo      string       `json:"memo" yaml:"memo"`
}
```

#### StdSignDoc <a href="#stdsigndoc" id="stdsigndoc"></a>

A `StdSignDoc` is a replay-prevention structure to be signed over, which ensures that any submitted transaction (which is simply a signature over a particular byte string) will only be executable once on a Heimdall.

```
// StdSignDoc is replay-prevention structure.
// It includes the result of msg.GetSignBytes(),
// as well as the ChainID (prevent cross chain replay)
// and the Sequence numbers for each signature (prevent
// inchain replay and enforce tx ordering per account).
type StdSignDoc struct {
 ChainID       string          `json:"chain_id" yaml:"chain_id"`
 AccountNumber uint64          `json:"account_number" yaml:"account_number"`
 Sequence      uint64          `json:"sequence" yaml:"sequence"`
 Msg           json.RawMessage `json:"msg" yaml:"msg"`
 Memo          string          `json:"memo" yaml:"memo"`
}
```

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

It manages addresses, coins and nonce for transactions. It also signs and validates transactions.

```
type BaseAccount struct {
  Address types.HeimdallAddress `json:"address" yaml:"address"`
  Coins types.Coins `json:"coins" yaml:"coins"`
  PubKey crypto.PubKey `json:"public_key" yaml:"public_key"`
  AccountNumber uint64 `json:"account_number" yaml:"account_number"`
  Sequence uint64 `json:"sequence" yaml:"sequence"`
}
```

### Parameters <a href="#parameters" id="parameters"></a>

The auth module contains the following parameters:

| Key                    | Type   | Default value      |
| ---------------------- | ------ | ------------------ |
| MaxMemoCharacters      | uint64 | 256                |
| TxSigLimit             | uint64 | 7                  |
| TxSizeCostPerByte      | uint64 | 10                 |
| SigVerifyCostED25519   | uint64 | 590                |
| SigVerifyCostSecp256k1 | uint64 | 1000               |
| DefaultMaxTxGas        | uint64 | 1000000            |
| DefaultTxFees          | string | “1000000000000000” |

### CLI commands <a href="#cli-commands" id="cli-commands"></a>

#### Show account <a href="#show-account" id="show-account"></a>

To print account related data into Heimdall;

```
heimdalld show-account
```

Expected Result:

```
{
 "address": "0x68243159a498cf20d945cf3E4250918278BA538E",
 "pub_key": "0x040a9f6879c7cdab7ecc67e157cda15e8b2ddbde107a04bc22d02f50032e393f6360a05e85c7c1ecd201ad30dfb886af12dd02b47e4463f6f0f6f94159dc9f10b8"
}
```

#### Account and coin details <a href="#account-and-coin-details" id="account-and-coin-details"></a>

To display account details, coins, sequence and account number;

```
heimdallcli query auth account 0x68243159a498cf20d945cf3E4250918278BA538E --trust-node
```

Expected Result:

```
address: 0x68243159a498cf20d945cf3e4250918278ba538e
coins:
- denom: RAMA
    amount:
    i: "1000000000000000000000"
pubkey: ""
accountnumber: 0
sequence: 0
```

#### Parameters <a href="#parameters_1" id="parameters_1"></a>

To print all params;

```
heimdallcli query auth params
```

Expected Result:

```
max_memo_characters: 256
tx_sig_limit: 7
tx_size_cost_per_byte: 10
sig_verify_cost_ed25519: 590
sig_verify_cost_secp256k1: 1000
max_tx_gas: 1000000
tx_fees: "1000000000000000"
```

### REST APIs <a href="#rest-apis" id="rest-apis"></a>

| Name                     | Endpoint                          | Description                                |
| ------------------------ | --------------------------------- | ------------------------------------------ |
| Account details          | /auth/accounts/{address}          | Returns all details for an address         |
| Account sequence details | /auth/accounts/{address}/sequence | Returns only necessary details for signing |
| Auth params              | /auth/params                      | Returns all params auth module uses        |

## Key management

Each validator uses two keys to manage validator related activities on Ramestta. The Signer key is kept on the node and is generally considered a `hot` wallet, whereas the Owner key is supposed to kept very secure, is used infrequently, and is generally considered a `cold` wallet. The staked funds are controlled by the Owner key.

This separation of responsibilities has been done to ensure an efficient tradeoff between security and ease of use. Both keys are Polygon compatible addresses and work exactly the same manner. And yes, it is possible to have same Owner and Signer keys.

### Signer key <a href="#signer-key" id="signer-key"></a>

The signer key is an address that is used for signing Heimdall blocks, checkpoints, and other signing related activities. This key’s private key will be on the Validator node for signing purposes. It cannot manage stake, rewards or delegations.

The validator must keep two types of balances on this address:

* Rama tokens on Heimdall (through Topup transactions) to perform validator responsibilities on Heimdall
* MATIC on Polygon chain to send checkpoints on Polygon

### Owner key <a href="#owner-key" id="owner-key"></a>

The owner key is an address that is used for staking, re-stake, changing the signer key, withdraw rewards and manage delegation related parameters on the Polygon chain. The private key for this key must be secure at all cost.

All transactions through this key will be performed on the Polygon chain.

### Signer change <a href="#signer-change" id="signer-change"></a>

Following event is generated in case of signer change on Polygon chain on `StakingInfo.sol`:&#x20;

```
// Signer change
event SignerChange(
  uint256 indexed validatorId,
  address indexed oldSigner,
  address indexed newSigner,
  bytes signerPubkey
);
```

Heimdall bridge processes these events and sends transactions on Heimdall to change state based on the events.

\
Validation

Heimdall’s “Ante Handler” plays a crucial role in the integrity and efficiency of transaction processing. It is primarily responsible for the preliminary verification and validation of all transactions, ensuring that they meet the necessary criteria before being included in a block. This includes checking the sender’s balance to ensure there are sufficient funds to cover transaction fees and subsequently deducting these fees for successful transactions.

### Advanced Gas Management in Heimdall <a href="#advanced-gas-management-in-heimdall" id="advanced-gas-management-in-heimdall"></a>

#### Block and Transaction Gas Limits <a href="#block-and-transaction-gas-limits" id="block-and-transaction-gas-limits"></a>

Heimdall employs a gas limit system to regulate the computational and storage resources consumed by transactions and blocks. This system is designed to prevent excessive block sizes and ensure network stability.

**Block Gas Limit**

Each block in Heimdall has a maximum gas limit, constraining the total gas used by all transactions within the block. The sum of the gas used by each transaction in a block must not exceed this limit:

```
 block.GasLimit >= sum(tx1.GasUsed + tx2.GasUsed + ..... + txN.GasUsed)
```

The maximum block gas limit and block size are specified as part of the consensus parameters during the application setup, as seen in the Heimdall source code at app.go#L464-L471:

```
maxGasPerBlock   int64 = 10000000 // 10 Million
maxBytesPerBlock int64 = 22020096 // 21 MB

// Setting consensus parameters
ConsensusParams: &abci.ConsensusParams{
 Block: &abci.BlockParams{
  MaxBytes: maxBytesPerBlock,
  MaxGas:   maxGasPerBlock,
 },
 ...
},
```

**Transaction Gas Limit**

For individual transactions, the gas limit is determined by parameters in the `auth` module and can be modified through Heimdall’s governance (`gov`) module.

**Special Handling of Checkpoint Transactions**

Checkpoint transactions, which require Merkle proof verification on the Polygon chain, are treated distinctly. To streamline processing and avoid the overhead of additional Merkle proof verification, Heimdall restricts blocks containing a `MsgCheckpoint` transaction to just that one transaction:

```
// Gas requirement for checkpoint transaction
gasWantedPerCheckpoinTx sdk.Gas = 10000000 // 10 Million

// Special gas limit handling for checkpoint transactions
if stdTx.Msg.Type() == "checkpoint" && stdTx.Msg.Route() == "checkpoint" {
 gasForTx = gasWantedPerCheckpoinTx
}
```

### Enhanced Transaction Verification and Replay Protection <a href="#enhanced-transaction-verification-and-replay-protection" id="enhanced-transaction-verification-and-replay-protection"></a>

The Ante Handler in Heimdall is instrumental in ensuring the legitimacy and uniqueness of transactions. It performs a thorough verification of incoming transactions, including signature validation, as delineated in the source code at ante.go#L230-L266.

#### Sequence Number for Replay Protection <a href="#sequence-number-for-replay-protection" id="sequence-number-for-replay-protection"></a>

A critical aspect of transaction security in Heimdall is the use of a `sequenceNumber` in each transaction. This feature is a safeguard against replay attacks, where a transaction might be fraudulently or mistakenly repeated. To prevent such scenarios, the Ante Handler increments the sequence number for the sender’s account after each successful transaction. This incrementation ensures that each transaction is unique and that previous transactions cannot be replayed.

In summary, Heimdall’s Ante Handler, along with its sophisticated gas management and transaction verification systems, provides a robust framework for secure and efficient transaction processing. The careful balance of block and transaction gas limits, coupled with advanced replay protection mechanisms, ensures the smooth operation of the Heimdall chain within the Ramestta network.

## Balance transfers

Heimdall’s `bank` module handles balance transfers between accounts. This module corresponds to the `bank` module from cosmos-sdk.

### Messages <a href="#messages" id="messages"></a>

#### MsgSend <a href="#msgsend" id="msgsend"></a>

`MsgSend` handles transfer between accounts in Heimdall. Here is a structure for transaction message:

```
// MsgSend - high-level transaction of the coin module
type MsgSend struct {
 FromAddress types.HeimdallAddress `json:"from_address"`
 ToAddress   types.HeimdallAddress `json:"to_address"`
 Amount      types.Coins           `json:"amount"`
}
```

#### MsgMultiSend <a href="#msgmultisend" id="msgmultisend"></a>

`MsgMultiSend` handles multi transfer between account for Heimdall.

```
// MsgMultiSend - high-level transaction of the coin module
type MsgMultiSend struct {
 Inputs  []Input  `json:"inputs"`
 Outputs []Output `json:"outputs"`
}
```

### Parameters <a href="#parameters" id="parameters"></a>

The bank module contains the following parameters:

| Key           | Type | Default value |
| ------------- | ---- | ------------- |
| `sendenabled` | bool | true          |

### CLI Commands <a href="#cli-commands" id="cli-commands"></a>

#### Send Balance <a href="#send-balance" id="send-balance"></a>

Following command will send 1000 Rama tokens to mentioned `address`;

```
heimdallcli tx bank send <address> 1000rama --chain-id <chain-id>
```

## Staking <a href="#staking" id="staking"></a>

Staking module manages validator related transactions and state for Heimdall. Note that a validator stakes their tokens on the Polygon chain and becomes a validator. Respective validators send the transactions on Heimdall using necessary parameters to acknowledge the Polygon stake change. Once the majority of the validators agree on the change on the stake, this module saves the validator information on Heimdall state.

### Messages <a href="#messages" id="messages"></a>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2F9hd9GLz7TbAePHnQW3jn%2Fstake-management-flow.svg?alt=media&amp;token=3b432e64-3a80-40a9-8ddc-1d83da8c5a4e" alt=""><figcaption></figcaption></figure>

#### MsgValidatorJoin <a href="#msgvalidatorjoin" id="msgvalidatorjoin"></a>

`MsgValidatorJoin` handles the staking when a new validator joins the system. Once validator calls `stake` or `stakeFor` in `StakingManager.sol` on Polygon, and the new `Staked` event is emitted.

Source:&#x20;

```
/**
 * Staked event - emitted whenever new validator 
 * 
 * @param signer           Signer address for the validator
 * @param validatorId      Validator id
 * @param activationEpoch  Activation epoch for validator
 * @param amount           Staked amount
 * @param total            Total stake
 * @param signerPubKey     Signer public key (required by Heimdall/Tendermint)
 */
event Staked(
    address indexed signer,
    uint256 indexed validatorId,
    uint256 indexed activationEpoch,
    uint256 amount,
    uint256 total,
    bytes signerPubkey
);
```

`activationEpoch` is the checkpoint count from where a validator will become active on Heimdall.

Stake call on smart contract fails if slots are unavailable. Validator slots are the way to restrict a number of validators in the system. Slots are managed on Polygon smart contracts.

Here is `ValidatorJoin` message for Heimdall transaction:

```
type MsgValidatorJoin struct {
 From         hmTypes.HeimdallAddress `json:"from"`
 ID           hmTypes.ValidatorID     `json:"id"`
 SignerPubKey hmTypes.PubKey          `json:"pub_key"`
 TxHash       hmTypes.HeimdallHash    `json:"tx_hash"`
 LogIndex     uint64                  `json:"log_index"`
}
```

#### MsgStakeUpdate <a href="#msgstakeupdate" id="msgstakeupdate"></a>

`MsgStakeUpdate` handles the stake update when a validator the re-stakes or new delegation comes in. In either case, the new `StakeUpdate` event is emitted.

```
/**
 * Stake update event - emitted whenever stake gets updated 
 * 
 * @param validatorId      Validator id
 * @param newAmount        New staked amount
 */
event StakeUpdate(
 uint256 indexed validatorId, 
 uint256 indexed newAmount
);
```

Here is `MsgStakeUpdate` message for Heimdall transaction:

```
// MsgStakeUpdate represents stake update
type MsgStakeUpdate struct {
 From     hmTypes.HeimdallAddress `json:"from"`
 ID       hmTypes.ValidatorID     `json:"id"`
 TxHash   hmTypes.HeimdallHash    `json:"tx_hash"`
 LogIndex uint64                  `json:"log_index"`
}
```

#### MsgValidatorExit <a href="#msgvalidatorexit" id="msgvalidatorexit"></a>

`MsgValidatorExit` handles the validator exit process after a validator initiates the exit process on Ethereum. It emits `SignerUpdate` event.

```
/**
 * Unstake init event - emitted whenever validator initiates the exit
 * 
 * @param user                Signer
 * @param validatorId         Validator id
 * @param deactivationEpoch   Deactivation epoch for validator
 * @param amount              Unstaked amount
 */
event UnstakeInit(
    address indexed user,
    uint256 indexed validatorId,
    uint256 deactivationEpoch,
    uint256 indexed amount
);
```

Here is `MsgValidatorExit` message for Heimdall transaction:

```
type MsgValidatorExit struct {
 From     hmTypes.HeimdallAddress `json:"from"`
 ID       hmTypes.ValidatorID     `json:"id"`
 TxHash   hmTypes.HeimdallHash    `json:"tx_hash"`
 LogIndex uint64                  `json:"log_index"`
}
```

#### MsgSignerUpdate <a href="#msgsignerupdate" id="msgsignerupdate"></a>

`MsgSignerUpdate` handles the signer update when a validator updates signer key on Ethereum. It emits `SignerUpdate` event.

```
/**
 * Signer change event - emitted whenever signer key changes
 * 
 * @param validatorId      Validator id
 * @param oldSigner        Current old signer
 * @param newSigner        New signer
 * @param signerPubkey     New signer public key
 */
event SignerChange(
    uint256 indexed validatorId,
    address indexed oldSigner,
    address indexed newSigner,
    bytes signerPubkey
);
```

Here is `MsgSignerUpdate` message for Heimdall transaction:

```
// MsgSignerUpdate signer update struct
type MsgSignerUpdate struct {
 From            hmTypes.HeimdallAddress `json:"from"`
 ID              hmTypes.ValidatorID     `json:"id"`
 NewSignerPubKey hmTypes.PubKey          `json:"pubKey"`
 TxHash          hmTypes.HeimdallHash    `json:"tx_hash"`
 LogIndex        uint64                  `json:"log_index"`
}
```

### CLI Commands <a href="#cli-commands" id="cli-commands"></a>

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

**By signer address**

```
heimdallcli query staking validator-info \
 --validator=<signer-address> \
 --chain-id <chain-id>
```

This command should display the following output:

```
{
    "ID":1,
    "startEpoch":0,
    "endEpoch":0,
    "power":10,
    "pubKey":"0x04b12d8b2f6e3d45a7ace12c4b2158f79b95e4c28ebe5ad54c439be9431d7fc9dc1164210bf6a5c3b8523528b931e772c86a307e8cff4b725e6b4a77d21417bf19",
    "signer":"0x6c468cf8c9879006e22ec4029696e005c2319c9d",
    "last_updated":0,
    "accum":0
}
```

**By validator address**

```
heimdallcli query staking validator-info \
 --id=<validator-id> \
 --chain-id=<chain-id>
```

This command should display the following output:

```
{
    "ID":1,
    "startEpoch":0,
    "endEpoch":0,
    "power":10,
    "pubKey":"0x04b12d8b2f6e3d45a7ace12c4b2158f79b95e4c28ebe5ad54c439be9431d7fc9dc1164210bf6a5c3b8523528b931e772c86a307e8cff4b725e6b4a77d21417bf19",
    "signer":"0x6c468cf8c9879006e22ec4029696e005c2319c9d",
    "last_updated":0,
    "accum":0
}
```

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

This command sends validator join command through CLI:

```
heimdallcli tx staking validator-join \
 --signer-pubkey <signer-public-key> \
 --tx-hash <tx-hash>   \
 --log-index <log-index> \ 
 --chain-id <chain-id>
```

`tx-hash` value must be the same as Ethereum TX hash which emitted `Staked` event and `log-index` must be the same at which index the event is emitted.

### REST APIs <a href="#rest-apis" id="rest-apis"></a>

| Name                       | Method | Endpoint                        |
| -------------------------- | ------ | ------------------------------- |
| Get Heimdall validator set | GET    | /staking/validator-set          |
| Get validator details      | GET    | /staking/validator/validator-id |

All query APIs will result in following format:

```
{
 "height": "1",
 "result": {
  ...   
 }
}
```

Checkpoints

Checkpoints are vital components of the Ramestta network, representing snapshots of the Bor chain state. These checkpoints are attested by a majority of the validator set before being validated and submitted on Polygon contracts.

Heimdall, an integral part of this process, manages checkpoint functionalities using the `checkpoint` module. It coordinates with the Bor chain to verify checkpoint root hashes when a new checkpoint is proposed.

### Checkpoint life-cycle and types <a href="#checkpoint-life-cycle-and-types" id="checkpoint-life-cycle-and-types"></a>

#### Life-cycle <a href="#life-cycle" id="life-cycle"></a>

Heimdall selects the next proposer using Tendermint’s leader selection algorithm. The multi-stage checkpoint process is crucial due to potential failures when submitting checkpoints on the Polygon chain caused by factors like gas limit, network traffic, or high gas fees.

Each checkpoint has a validator as the proposer. The outcome of a checkpoint on the Polygon chain (success or failure) triggers an `ack` (acknowledgment) or `no-ack` (no acknowledgment) transaction, altering the proposer for the next checkpoint on Heimdall.

#### Types and structures <a href="#types-and-structures" id="types-and-structures"></a>

**Checkpoint block header**

```
type CheckpointBlockHeader struct {
 Proposer        types.HeimdallAddress `json:"proposer"`
 StartBlock      uint64                `json:"startBlock"`
 EndBlock        uint64                `json:"endBlock"`
 RootHash        types.HeimdallHash    `json:"rootHash"`
 AccountRootHash types.HeimdallHash    `json:"accountRootHash"`
 TimeStamp       uint64                `json:"timestamp"`
}
```

**Root hash calculation**

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FqSM1BNJdomSBKT6jL1ki%2Fcheckpoint.svg?alt=media&amp;token=ab9c66d5-2e04-40b1-a63a-36c1ebb7cec6" alt=""><figcaption></figcaption></figure>

The `RootHash` is calculated as a Merkle hash of Bor block hashes from `StartBlock` to `EndBlock`. The process involves hashing each block’s number, time, transaction hash, and receipt hash, then creating a Merkle root of these hashes.

```
blockHash = keccak256([number, time, tx hash, receipt hash])
```

Pseudocode for the root hash for `1` to `n` Bor blocks:

```
B(1) := keccak256([number, time, tx hash, receipt hash])
B(2) := keccak256([number, time, tx hash, receipt hash])
.
.
.
B(n) := keccak256([number, time, tx hash, receipt hash])

// checkpoint is Merkle root of all block hash
checkpoint's root hash = Merkel[B(1), B(2), ....., B(n)]
```

Here are some snippets of how checkpoint is created from Bor chain block headers.

Source:&#x20;

```
// Golang representation of block data used in checkpoint
blockData := crypto.Keccak256(appendBytes32(
 blockHeader.Number.Bytes(),
 new(big.Int).SetUint64(blockHeader.Time).Bytes(),
 blockHeader.TxHash.Bytes(),
 blockHeader.ReceiptHash.Bytes(),
))

// array of block hashes of Bor blocks
headers := [blockData1, blockData2, ..., blockDataN]

// merkel tree
tree := merkle.NewTreeWithOpts(merkle.TreeOptions{EnableHashSorting: false, DisableHashLeaves: true})
tree.Generate(convert(headers), sha3.NewLegacyKeccak256())

// create checkpoint's root hash
rootHash := tree.Root().Hash
```

#### AccountRootHash <a href="#accountroothash" id="accountroothash"></a>

`AccountRootHash` is the hash of the validator account-related information that needs to pass to the Polygon chain at each checkpoint.

```
eachAccountHash := keccak256([validator id, withdraw fee, slash amount])
```

Pseudocode for the account root hash for `1` to `n` Bor blocks:

```
B(1) := keccak256([validator id, withdraw fee, slash amount])
B(2) := keccak256([validator id, withdraw fee, slash amount])
.
.
.
B(n) := keccak256([validator id, withdraw fee, slash amount])

// account root hash is Merkle root of all block hash
checkpoint's account root hash = Merkel[B(1), B(2), ....., B(n)]
```

Golang code for the account hash can be found here:&#x20;

```
// DividendAccount contains Fee, Slashed amount
type DividendAccount struct {
 ID            DividendAccountID `json:"ID"`
 FeeAmount     string            `json:"feeAmount"`     // string representation of big.Int
 SlashedAmount string            `json:"slashedAmount"` // string representation of big.Int
}

// calculate hash for particular account
func (da DividendAccount) CalculateHash() ([]byte, error) {
 fee, _ := big.NewInt(0).SetString(da.FeeAmount, 10)
 slashAmount, _ := big.NewInt(0).SetString(da.SlashedAmount, 10)
 divAccountHash := crypto.Keccak256(appendBytes32(
  new(big.Int).SetUint64(uint64(da.ID)).Bytes(),
  fee.Bytes(),
  slashAmount.Bytes(),
 ))

 return divAccountHash, nil
}
```

### Messages in checkpoint module <a href="#messages-in-checkpoint-module" id="messages-in-checkpoint-module"></a>

#### MsgCheckpoint <a href="#msgcheckpoint" id="msgcheckpoint"></a>

`MsgCheckpoint` handles checkpoint verification on Heimdall, utilizing RLP encoding for Polygon chain verification. It prioritizes transactions with high gas consumption to ensure only one `MsgCheckpoint` transaction per block.

```
// MsgCheckpoint represents checkpoint transaction
type MsgCheckpoint struct {
 Proposer        types.HeimdallAddress `json:"proposer"`
 StartBlock      uint64                `json:"startBlock"`
 EndBlock        uint64                `json:"endBlock"`
 RootHash        types.HeimdallHash    `json:"rootHash"`
 AccountRootHash types.HeimdallHash    `json:"accountRootHash"`
}
```

#### MsgCheckpointAck <a href="#msgcheckpointack" id="msgcheckpointack"></a>

`MsgCheckpointAck` manages successful checkpoint submissions, updating the checkpoint count and clearing the `checkpointBuffer`.

```
// MsgCheckpointAck represents checkpoint ack transaction if checkpoint is successful
type MsgCheckpointAck struct {
 From        types.HeimdallAddress `json:"from"`
 HeaderBlock uint64                `json:"headerBlock"`
 TxHash      types.HeimdallHash    `json:"tx_hash"`
 LogIndex    uint64                `json:"log_index"`
}
```

#### MsgCheckpointNoAck <a href="#msgcheckpointnoack" id="msgcheckpointnoack"></a>

`MsgCheckpointNoAck` deals with unsuccessful checkpoints or offline proposers, allowing a timeout period before selecting a new proposer.

```
// MsgCheckpointNoAck represents checkpoint no-ack transaction
type MsgCheckpointNoAck struct {
 From types.HeimdallAddress `json:"from"`
}
```

### Parameters and CLI commands <a href="#parameters-and-cli-commands" id="parameters-and-cli-commands"></a>

#### Parameters <a href="#parameters" id="parameters"></a>

The checkpoint module contains the following parameters:

| Key                  | Type   | Default value       |
| -------------------- | ------ | ------------------- |
| CheckpointBufferTime | uint64 | 1000 \* time.Second |

#### CLI commands <a href="#cli-commands" id="cli-commands"></a>

Commands are available for various actions such as sending checkpoints, sending `ack` or `no-ack` transactions, and querying parameters.

#### Printing all parameters <a href="#printing-all-parameters" id="printing-all-parameters"></a>

```
heimdallcli query checkpoint params --trust-node
```

Expected Result:

```
checkpoint_buffer_time: 16m40s
```

#### Send Checkpoint <a href="#send-checkpoint" id="send-checkpoint"></a>

Following command sends checkpoint transaction on Heimdall:

```
heimdallcli tx checkpoint send-checkpoint \
 --start-block=<start-block> \
 --end-block=<end-block> \
 --root-hash=<root-hash> \
 --account-root-hash=<account-root-hash> \
 --chain-id=<chain-id>
```

#### Send `ack` <a href="#send-ack" id="send-ack"></a>

Following command sends ack transaction on Heimdall if checkpoint is successful on Polygon:

```
heimdallcli tx checkpoint send-ack \
 --tx-hash=<checkpoint-tx-hash>
 --log-index=<checkpoint-event-log-index>
 --header=<checkpoint-index> \
  --chain-id=<chain-id>
```

#### Send `no-ack` <a href="#send-no-ack" id="send-no-ack"></a>

Following command send no-ack transaction on Heimdall:

```
heimdallcli tx checkpoint send-noack --chain-id <chain-id>
```

### REST APIs <a href="#rest-apis" id="rest-apis"></a>

Heimdall provides several REST APIs for interacting with the checkpoint module, including endpoints for preparing messages, querying checkpoints, and more.

| Name                                                                          | Method | Endpoint                          |
| ----------------------------------------------------------------------------- | ------ | --------------------------------- |
| It returns the prepared msg for ack checkpoint                                | POST   | /checkpoint/ack                   |
| It returns the prepared msg for new checkpoint                                | POST   | /checkpoint/new                   |
| It returns the prepared msg for no-ack checkpoint                             | POST   | /checkpoint/no-ack                |
| Checkpoint by number                                                          | GET    | /checkpoints/\<checkpoint-number> |
| Get current checkpoint buffer state                                           | GET    | /checkpoints/buffer               |
| Get checkpoint counts                                                         | GET    | /checkpoints/count                |
| Get last no-ack details                                                       | GET    | /checkpoints/last-no-ack          |
| Get latest checkpoint                                                         | GET    | /checkpoints/latest               |
| All checkpoints                                                               | GET    | /checkpoints/list                 |
| It returns the checkpoint parameters                                          | GET    | /checkpoints/parama               |
| It returns the prepared checkpoint                                            | GET    | /checkpoints/prepare              |
| Get ack count, buffer, validator set, validator count and last-no-ack details | GET    | /overview                         |

For more details and the response format of these APIs, visit Heimdall API Documentation.

## Topup

Topups are amounts used to pay fees on the Heimdall chain.

There are two ways to topup your account:

1. When new validator joins, they can mention a `topup` amount as top-up in addition to the staked amount, which will be moved as balance on Heimdall chain to pays fees on Heimdall.
2. A user can directly call the top-up function on the staking smart contract on Polygon to increase top-up balance on Heimdall.

### Messages <a href="#messages" id="messages"></a>

#### MsgTopup <a href="#msgtopup" id="msgtopup"></a>

`MsgTopup` transaction is responsible for minting balance to an address on Heimdall based on Polygon chain’s `TopUpEvent` on staking manager contract.

Handler for this transaction processes top-up and increases the balance only once for any given `msg.TxHash` and `msg.LogIndex`. It throws `Older invalid tx found` error, if trying to process the top-up more than once.

Here is the structure for the top-up transaction message:

```
type MsgTopup struct {
 FromAddress types.HeimdallAddress `json:"from_address"`
 ID          types.ValidatorID     `json:"id"`
 TxHash      types.HeimdallHash    `json:"tx_hash"`
 LogIndex    uint64                `json:"log_index"`
}
```

#### MsgWithdrawFee <a href="#msgwithdrawfee" id="msgwithdrawfee"></a>

`MsgWithdrawFee` transaction is responsible for withdrawing balance from Heimdall to Polygon chain. A Validator can withdraw any amount from Heimdall.

Handler processes the withdraw by deducting the balance from the given validator and prepares the state to send the next checkpoint. The next possible checkpoint will contain the withdraw related state for the specific validator.

Handler gets validator information based on `ValidatorAddress` and processes the withdraw.

```
// MsgWithdrawFee - high-level transaction of the fee coin withdrawal module
type MsgWithdrawFee struct {
 ValidatorAddress types.HeimdallAddress `json:"from_address"`
 Amount           types.Int             `json:"amount"`
}
```

### CLI Commands <a href="#cli-commands" id="cli-commands"></a>

#### Topup fee <a href="#topup-fee" id="topup-fee"></a>

```
heimdallcli tx topup fee
 --log-index <log-index> 
 --tx-hash <transaction-hash> 
 --validator-id <validator ID here>
 --chain-id <heimdall-chain-id>
```

#### Withdraw fee <a href="#withdraw-fee" id="withdraw-fee"></a>

```
heimdallcli tx topup withdraw --chain-id <heimdall-chain-id>
```

To check reflected topup on account run following command

```
heimdallcli query auth account <validator-address> --trust-node
```

### REST APIs <a href="#rest-apis" id="rest-apis"></a>

| Name         | Method | URL             | Body Params                                                                                                                                             |
| ------------ | ------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Topup Fee    | POST   | /topup/fee      | `id` Validator id, `tx_hash` Transaction hash of successful topup event on Polygon chain, `log_index` Log index of topup event emitted on Polygon chain |
| Withdraw Fee | POST   | /topup/withdraw | `amount` Withdraw amount                                                                                                                                |

## Chain management

This document specifies an overview of the chain manager module of Heimdall.

The **chain manager** module provides all necessary dependencies like `contract-addresses`, `bor_chain_id,` and `tx_confirmation_time`. Other parameters can be added to this later on.

Params are updated through the `gov` module.

### Types <a href="#types" id="types"></a>

Chainmanager structure on Heimdall looks like the following:

```
type ChainParams struct {
 // BorChainID is valid bor chainId
 BorChainID            string                  `json:"bor_chain_id" yaml:"bor_chain_id"`

 // StakingManagerAddress is valid contract address
 StakingManagerAddress hmTypes.HeimdallAddress `json:"staking_manager_address" yaml:"staking_manager_address"`

 // RootChainAddress is valid contract address
 RootChainAddress      hmTypes.HeimdallAddress `json:"root_chain_address" yaml:"root_chain_address"`

 // StakingInfoAddress is valid contract address
 StakingInfoAddress    hmTypes.HeimdallAddress `json:"staking_info_address" yaml:"staking_info_address"`

 // StateSendedAddress is valid contract address
 StateSenderAddress    hmTypes.HeimdallAddress `json:"state_sender_address" yaml:"state_sender_address"`

 // Bor Chain Contracts
 // StateReceiveAddress is valid contract address
 StateReceiverAddress hmTypes.HeimdallAddress `json:"state_receiver_address" yaml:"state_receiver_address"`

 // ValidatorSetAddress is valid contract address
 ValidatorSetAddress  hmTypes.HeimdallAddress `json:"validator_set_address" yaml:"validator_set_address"`
}
```

### CLI commands <a href="#cli-commands" id="cli-commands"></a>

#### Parameters <a href="#parameters" id="parameters"></a>

To print all params;

```
heimdallcli query chainmanager params --trust-node
```

#### Expected result <a href="#expected-result" id="expected-result"></a>

```
tx_confirmation_time: 12s
chain_params:
  bor_chain_id: "1370"
  rama_token_address: "0x0000000000000000000000000000000000000000"
  staking_manager_address: "0x0000000000000000000000000000000000000000"
  root_chain_address: "0x0000000000000000000000000000000000000000"
  staking_info_address: "0x0000000000000000000000000000000000000000"
  state_sender_address: "0x0000000000000000000000000000000000000000"
  state_receiver_address: "0x0000000000000000000000000000000000000000"
  validator_set_address: "0x0000000000000000000000000000000000000000"
```

#### REST APIs <a href="#rest-apis" id="rest-apis"></a>

| Name   | Method | URL                 |
| ------ | ------ | ------------------- |
| Params | GET    | chainmanager/params |

All query APIs will provide response in the following format:

```
{
 "height": "1",
 "result": {
  ...   
 }
}
```

## Governance

Heimdall’s governance operates identically to the Cosmos-sdk `x/gov` module, as detailed in [Cosmos-sdk documentation](https://docs.cosmos.network/main/build/modules/gov).

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

In Heimdall, token holders can influence decisions by voting on proposals. Each token equals one vote. The governance system currently supports:

* **Proposal submission:** Validators can submit proposals along with a deposit. If the deposit reaches the minimum threshold within a set period, the proposal moves to a voting phase. Validators can reclaim their deposits after the proposal’s acceptance or rejection.
* **Voting:** Validators are eligible to vote on proposals that have met the minimum deposit requirement.

The governance module includes two critical periods: the deposit and voting periods. Proposals failing to meet the minimum deposit by the end of the deposit period are automatically rejected. Upon reaching the minimum deposit, the voting period commences, during which validators cast their votes. After the voting period, the `gov/Endblocker.go` script tallies the votes and determines the proposal’s fate based on `tally_params`: quorum, threshold, and veto. The tallying process is detailed in the source code at Heimdall GitHub repository.

#### Types of proposals <a href="#types-of-proposals" id="types-of-proposals"></a>

Currently, Heimdall supports the **Param Change Proposal**, allowing validators to modify parameters in any of Heimdall’s modules.

**Param Change Proposal example**

For instance, validators might propose to alter the minimum `tx_fees` in the `auth` module. If the proposal is approved, the parameters in the Heimdall state are automatically updated without the need for an additional transaction.

### Command Line Interface (CLI) commands <a href="#command-line-interface-cli-commands" id="command-line-interface-cli-commands"></a>

#### Checking governance parameters <a href="#checking-governance-parameters" id="checking-governance-parameters"></a>

To view all parameters for the governance module:

```
heimdallcli query gov params --trust-node
```

This command displays the current governance parameters, such as voting period, quorum, threshold, veto, and minimum deposit requirements.

#### Submitting a proposal <a href="#submitting-a-proposal" id="submitting-a-proposal"></a>

To submit a proposal:

```
heimdallcli tx gov submit-proposal \
 --validator-id 1 param-change proposal.json \
 --chain-id <heimdall-chain-id>
```

`proposal.json` is a JSON-formatted file containing the proposal details.

#### Querying proposals <a href="#querying-proposals" id="querying-proposals"></a>

To list all proposals:

```
heimdallcli query gov proposals --trust-node
```

To query a specific proposal:

```
heimdallcli query gov proposal 1 --trust-node
```

#### Voting on a proposal <a href="#voting-on-a-proposal" id="voting-on-a-proposal"></a>

To vote on a proposal:

```
heimdallcli tx gov vote 1 "Yes" --validator-id 1 --chain-id <heimdall-chain-id>
```

Votes are automatically tallied after the voting period concludes.

### REST APIs <a href="#rest-apis" id="rest-apis"></a>

Heimdall also offers REST APIs for interacting with the governance system:

| Name                         | Method | Endpoint                             |
| ---------------------------- | ------ | ------------------------------------ |
| Get all proposals            | GET    | `/gov/proposals`                     |
| Get proposal details         | GET    | `/gov/proposals/{proposal-id}`       |
| Get all votes for a proposal | GET    | `/gov/proposals/{proposal-id}/votes` |

These APIs facilitate access to proposal details, voting records, and overall governance activity.


# Bor

Bor, the core component of the Ramestta network, operates on the principles outlined in EIP-225, following the Clique consensus protocol.

&#x20;**Validator Committee Selection in Ramestta:** Ramestta relies on the Bor layer, where a committee of Validators is selected from the Validator pool based on their stake. This selection occurs at regular intervals and is shuffled periodically, determined by the Validator's governance concerning dynasty and network. The probability of being selected as a member of the block producer committee is determined by the ratio of Stake to Staking power.&#x20;

**Validator Selection Process:** Validators are assigned slots proportionally based on their stake. Historical Polygon block data is used as a seed to shuffle this array. Validators are then selected based on the producer count maintained by the Validator's governance. The Tendermint's proposer selection algorithm is employed to choose a producer for each sprint on Bor.&#x20;

**Bor Consensus Mechanics:** In the Proof-of-Stake (PoS) system of Ramestta, participants stake Rama tokens on a designated Polygon smart contract, known as the "staking contract," to become validators. The bor module in Heimdall selects active validators as block producers.&#x20;

**Span and Sprint Mechanism:** A span is a defined set of blocks in which a specific subset of validators is chosen. Within a span, each validator is assigned voting power, influencing their chances of being selected as a block producer. A sprint, a smaller subset of blocks within a span, designates a single block producer for block generation.&#x20;

**Block Authorization and Backup Mechanism:** Block producers, also known as signers, authorize blocks by signing the block's hash. Bor designates backup producers in case the primary producer fails to generate a block. The wiggle time, a predefined delay, determines when a backup producer starts generating a block.&#x20;

**Difficulty Metrics and Fork Resolution:** Blocks signed in-turn have higher difficulty than out-of-turn signatures. Bor addresses forks by selecting the fork with the highest cumulative difficulty, prioritizing in-turn block production.&#x20;

**View Change and Span Commitment:** At the end of each span, Bor undergoes a view change, fetching new producers for the subsequent span. This involves an HTTP call to the Heimdall node for new span data and a commitSpan call to the BorValidatorSet genesis contract.&#x20;

**State Synchronization with Polygon:** Bor features a mechanism to relay events from the Polygon chain. This involves triggering the StateSynced event on Polygon, monitoring by Heimdall, and commitment by Bor at the start of every sprint. State Sync ensures consistency between Polygon and Bor chains.

**State Sync Mechanism:** State Sync transfers data from Polygon to Bor through system calls. Validators on the Heimdall layer listen to StateSynced events and pass them on to the Bor layer. Bor updates its state using a system call after fetching new state-sync records post every sprint.&#x20;

**System Call and State Receiver Interface:** The system call is crucial for changing state to a contract without making a transaction. Bor calls it internally with the system address. The receiver contract on Bor implements the IStateReceiver interface, allowing the execution of onStateReceive.&#x20;

**State-Sync Logs and Bor Block Receipts:** State-sync logs are handled differently from normal logs in Bor. Bor produces a new transaction/receipt for the client after each sprint, including all logs for state-sync. The tx hash is derived from the block number and block hash, and it does not alter consensus logic.&#x20;

This comprehensive mechanism ensures the seamless operation of Ramestta, facilitating the integration and synchronization of data between different layers of the network.

## Commands

This guide provides a curated list of common commands and Ramestta-specific operations essential for node operators. Whether you’re setting up a full node, validator node or troubleshooting, these commands will assist you in managing your Ramestta PoS environment effectively.

### Frequently Used Commands for Bor & Heimdall <a href="#frequently-used-commands-for-bor-heimdall" id="frequently-used-commands-for-bor-heimdall"></a>

Use the tabs below to switch between commands for Bor and Heimdall:

To execute Bor IPC commands, use the following syntax:

```
bor attach .bor/data/bor.ipc <command>
```

| IPC Command                                                                 | RPC Command                                                                                                                                            | Description                                                      |
| --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------- |
| `admin.peers.length`                                                        | `curl -H "Content-Type: application/json" --data '{"jsonrpc": "2.0", "method": "net_peerCount", "params": [], "id": 74}' localhost:8545`               | Retrieves the number of peers connected to the node.             |
| `admin.nodeInfo`                                                            |                                                                                                                                                        | Provides detailed information about the node.                    |
| `eth.syncing`                                                               | `curl -H "Content-Type: application/json" -d '{"id":1, "jsonrpc":"2.0", "method": "eth_syncing","params": []}' localhost:8545`                         | Indicates whether the node is syncing (`true`) or not (`false`). |
| `eth.syncing.highestBlock - eth.syncing.currentBlock`                       |                                                                                                                                                        | Compares the current block of your node to the highest block.    |
| `eth.blockNumber`                                                           | `curl -H "Content-Type: application/json" -d '{"id":1, "jsonrpc":"2.0", "method": "eth_blockNumber","params": []}' localhost:8545`                     | Returns the latest block number processed by the node.           |
| `debug.setHead("0x"+((eth.getBlock('latest').number) - 1000).toString(16))` |                                                                                                                                                        | Rewinds the blockchain to 1000 blocks prior.                     |
| `admin.nodeInfo.enode`                                                      |                                                                                                                                                        | Retrieves the public enode URL of the node.                      |
| `eth.syncing.currentBlock * 100 / eth.syncing.highestBlock`                 |                                                                                                                                                        | Calculates the remaining percentage for block synchronization.   |
| `eth.getBlock("latest").number`                                             | `curl http://YourIP:8545 -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0", "id":1, "method":"bor_getSigners", "params":["0x98b3ea"]}'` | Queries the height of the latest Bor block.                      |
|                                                                             | `curl http://YourIP:8545 -X POST -H "Content-Type: application/json" --data '{"method":"eth_chainId","params":[],"id":1,"jsonrpc":"2.0"}'`             | Retrieves the `chainID`.                                         |

| Command                          | Description                                                                                 |                   |
| -------------------------------- | ------------------------------------------------------------------------------------------- | ----------------- |
| `curl localhost:26657/net_info?` | Returns the number of connected peers using `jq .result.n_peers`.                           |                   |
| `curl -s localhost:26657/status` | Retrieves Heimdall’s current block height using `jq .result.sync_info.latest_block_height`. |                   |
| `curl localhost:26657/net_info`  | Queries the node using its moniker with `grep moniker`.                                     |                   |
| `curl -s localhost:26657/status` | Checks if Heimdall is in sync using `jq .result.sync_info.catching_up`.                     |                   |
| `curl -s localhost:26657/status` | Verifies Heimdall’s sync status using \`jq .result \\                                       | jq .sync\_info\`. |
| `heimdalld unsafe-reset-all`     | Resets the database in case of issues.                                                      |                   |
| `curl localhost:26657/status`    | Provides comprehensive information about Heimdall.                                          |                   |

### Node Management Commands <a href="#node-management-commands" id="node-management-commands"></a>

| Description                         | Command                                      |
| ----------------------------------- | -------------------------------------------- |
| **Locate Heimdall genesis file**    | `$CONFIGPATH/heimdall/config/genesis.json`   |
| **Locate heimdall-config.toml**     | `/etc/heimdall/config/heimdall-config.toml`  |
| **Locate config.toml**              | `/etc/heimdall/config/config.toml`           |
| **Locate heimdall-seeds.txt**       | `$CONFIGPATH/heimdall/heimdall-seeds.txt`    |
| **Start Heimdall**                  | `$ sudo service heimdalld start`             |
| **Start Heimdall rest-server**      | `$ sudo service heimdalld-rest-server start` |
| **Start Heimdall bridge-server**    | `$ sudo service heimdalld-bridge start`      |
| **Locate Bor genesis file**         | `$CONFIGPATH/bor/genesis.json`               |
| **Start Bor**                       | `sudo service bor start`                     |
| **Retrieve Heimdall logs**          | `/var/log/`                                  |
| **Check Heimdall logs**             | `tail -f heimdalld.log`                      |
| **Check Heimdall rest-server logs** | `tail -f heimdalld-rest-server.log`          |
| **Check Heimdall bridge logs**      | `tail -f heimdalld-bridge.log`               |
| **Check Bor logs**                  | `tail -f bor.log`                            |

### Useful Configuration Commands <a href="#useful-configuration-commands" id="useful-configuration-commands"></a>

#### Sync Status of Heimdall <a href="#sync-status-of-heimdall" id="sync-status-of-heimdall"></a>

To check if Heimdall is synced, run:

```
curl http://localhost:26657/status
```

#### Latest Block Height on Heimdall <a href="#latest-block-height-on-heimdall" id="latest-block-height-on-heimdall"></a>

To check the latest block height on Heimdall, run:

```
curl localhost:26657/status
```

#### Latest Block Height on Bor <a href="#latest-block-height-on-bor" id="latest-block-height-on-bor"></a>

To check the latest block height on Bor, use:

```
curl http://<your ip>:8545 -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0", "id":1, "method":"bor_getSigners", "params":["0x98b3ea"]}'
```

#### Cleanup: Deleting Remnants of Heimdall and Bor <a href="#cleanup-deleting-remnants-of-heimdall-and-bor" id="cleanup-deleting-remnants-of-heimdall-and-bor"></a>

**For Linux package:**

```
sudo dpkg -i 
sudo rm -rf /etc/bor
```

**For Binaries:**

```
sudo rm -rf /etc/bor
sudo rm /etc/heimdall
```

#### Terminate Bor Process <a href="#terminate-bor-process" id="terminate-bor-process"></a>

**For Linux:**

```
ps -aux | grep bor
sudo kill -9 <PID>
```

**For Binaries:**

```
cd CS-2003/bor
bash stop.sh
```

#### Retrieve Latest Peer Details <a href="#retrieve-latest-peer-details" id="retrieve-latest-peer-details"></a>

To retrieve the latest peer details, run:

```
bor attach bor.ipc
admin.peers.forEach(function(value){
    console.log(value.enode+',')
})
exit
```

#### Stop Heimdall and Bor Services <a href="#stop-heimdall-and-bor-services" id="stop-heimdall-and-bor-services"></a>

**For Linux packages:**

```
sudo service heimdalld stop
sudo service bor stop
```

**For Binaries:**

```
pkill heimdalld
pkill heimdalld-bridge
cd CS-2001/bor
bash stop.sh
```

#### Remove Heimdall and Bor Directories <a href="#remove-heimdall-and-bor-directories" id="remove-heimdall-and-bor-directories"></a>

**For Linux packages:**

```
sudo rm -rf /etc/heimdall/*
sudo rm -rf /etc/bor/*
```

**For Binaries:**

```
sudo rm -rf /var/lib/heimdalld/
sudo rm -rf /var/lib/bor
```


# Contracts


# Genesis contracts

Here you will find a list of contracts deployed on Ramestta together with their initial address, that is, their location on the blockchain.

#### Mainnet: <a href="#mainnet" id="mainnet"></a>

**Parent chain: Polygon mainnet**

| Contracts                | [Address](https://polygonscan.com/)                                                                                      |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------ |
| BytesLib                 | [0xa6479dEc21D912f98D6642eDE416784004b7e7E6](https://polygonscan.com/address/0x07471540b1bfC37192654110189Bdc907e8B9525) |
| Common                   | [0xBd770416a3345F91E4B34576cb804a576fa48EB1](https://polygonscan.com/address/0xBd770416a3345F91E4B34576cb804a576fa48EB1) |
| ECVerify                 | [0xAA5b7473972800651E7da5B76B415ecAcFF3B6b3](https://polygonscan.com/address/0xAA5b7473972800651E7da5B76B415ecAcFF3B6b3) |
| Merkle                   | [0x14568a02d226eb519d505902FF71c2aCF7713F0F](https://polygonscan.com/address/0x14568a02d226eb519d505902FF71c2aCF7713F0F) |
| MerklePatriciaProof      | [0x5213DC5ea2Db0FC869a96fd847B7902CD6B4AeFD](https://polygonscan.com/address/0x5213DC5ea2Db0FC869a96fd847B7902CD6B4AeFD) |
| PriorityQueue            | [0xF527d2CADc9BE1AF4f41DfeD5BC969b9Ff96F1e6](https://polygonscan.com/address/0xF527d2CADc9BE1AF4f41DfeD5BC969b9Ff96F1e6) |
| RLPEncode                | [0xc6473B9F0C794A826043E7aD884b06841d5CafF1](https://polygonscan.com/address/0xc6473B9F0C794A826043E7aD884b06841d5CafF1) |
| RLPReader                | [0xADCb26Ba45B51Ce0B3bF33A52Bca8241Cc78B179](https://polygonscan.com/address/0xADCb26Ba45B51Ce0B3bF33A52Bca8241Cc78B179) |
| SafeMath                 | [0xb102c49cf0317F676a9950DD3B9436745F84fB39](https://polygonscan.com/address/0xb102c49cf0317F676a9950DD3B9436745F84fB39) |
| TransferWithSigUtils     | [0x8Cb27198DA2a14ec74e2d68732Bfa95c948Eab0A](https://polygonscan.com/address/0x8Cb27198DA2a14ec74e2d68732Bfa95c948Eab0A) |
| Governance               | [0x73a2137715F431DAc27a9B26cc991F2f39b6A22c](https://polygonscan.com/address/0x73a2137715F431DAc27a9B26cc991F2f39b6A22c) |
| GovernanceProxy          | [0x675162f45C7566E86e6261e40eF966cdDeddb8CC](https://polygonscan.com/address/0x675162f45C7566E86e6261e40eF966cdDeddb8CC) |
| Timelock                 | Coming Soon                                                                                                              |
| Registry                 | [0x07471540b1bfC37192654110189Bdc907e8B9525](https://polygonscan.com/address/0x07471540b1bfC37192654110189Bdc907e8B9525) |
| RootChain                | [0x81FADA3Ab7f998F0191C77f043c05eb55c789FE1](https://polygonscan.com/address/0x81FADA3Ab7f998F0191C77f043c05eb55c789FE1) |
| RootChainProxy           | [0x32BC23e5FFf7D567313dB4F41A5125Ad9D9Bca63](https://polygonscan.com/address/0x32BC23e5FFf7D567313dB4F41A5125Ad9D9Bca63) |
| ValidatorShareFactory    | [0xD7379c8BBFBEBc743cfa0ebF398c80b39c937802](https://polygonscan.com/address/0xD7379c8BBFBEBc743cfa0ebF398c80b39c937802) |
| StakingInfo              | [0x06FB27902B00a4CCF3850783dAB763364BF8654A](https://polygonscan.com/address/0x06FB27902B00a4CCF3850783dAB763364BF8654A) |
| StakingNFT               | [0x108E6890F660Dbe4f3554DC43769B4D734555981](https://polygonscan.com/address/0x108E6890F660Dbe4f3554DC43769B4D734555981) |
| StakeManager             | [0x710c591d0862d33F1dBfC8555778F23709aEA53c](https://polygonscan.com/address/0x710c591d0862d33F1dBfC8555778F23709aEA53c) |
| StakeManagerExtension    | [0xdb8Bf95B4B10c25c4eE3335d8B4d236988d53E85](https://polygonscan.com/address/0xdb8Bf95B4B10c25c4eE3335d8B4d236988d53E85) |
| StakeManagerProxy        | [0xc032E6C4D196CBf4CceddbA1d18661F7DD57f659](https://polygonscan.com/address/0xc032E6C4D196CBf4CceddbA1d18661F7DD57f659) |
| DrainStakeManager        | [0x9b055b4cE53D7b761dF9Fbc5026bdA72381fE457](https://polygonscan.com/address/0x9b055b4ce53d7b761df9fbc5026bda72381fe457) |
| SlashingManager          | [0xae032F1be5d139a679d975dB379E27aF2107D7D7](https://polygonscan.com/address/0xae032F1be5d139a679d975dB379E27aF2107D7D7) |
| ValidatorShare           | [0x2A53F2bb6023C262F34Ad936f10105fED67d13BB](https://polygonscan.com/address/0x2A53F2bb6023C262F34Ad936f10105fED67d13BB) |
| StateSender              | [0xE0C9051E655380D1d880b9B0f4b500cEbD09278f](https://polygonscan.com/address/0xE0C9051E655380D1d880b9B0f4b500cEbD09278f) |
| DepositManager           | [0x5C20eBdD45C0e2FFb394f41F310c9eB9CdBEaCD5](https://polygonscan.com/address/0x5C20eBdD45C0e2FFb394f41F310c9eB9CdBEaCD5) |
| DepositManagerProxy      | [0x81ebFB0c73d3165c4719E9604cDa55eF91226dAf](https://polygonscan.com/address/0x81ebFB0c73d3165c4719E9604cDa55eF91226dAf) |
| EventsHub                | [0x409B84308087B6886586121a897aE2d713a13bB4](https://polygonscan.com/address/0x409B84308087B6886586121a897aE2d713a13bB4) |
| EventsHubProxy           | [0x9Bc8dfB0e0565553f1464810cb67139Fc1DE87C1](https://polygonscan.com/address/0x9bc8dfb0e0565553f1464810cb67139fc1de87c1) |
| WithdrawManager          | [0xa643b9C389B557695025DBBb775bC4942601C5Ab](https://polygonscan.com/address/0xa643b9C389B557695025DBBb775bC4942601C5Ab) |
| ExitNFT                  | [0x9D770aa7a1959AF56694bafA56ecf6EeF8c62b2C](https://polygonscan.com/address/0x9D770aa7a1959AF56694bafA56ecf6EeF8c62b2C) |
| WithdrawManagerProxy     | [0x6e07F852bAC263492e8C710dB7c0d59275268db8](https://polygonscan.com/address/0x6e07F852bAC263492e8C710dB7c0d59275268db8) |
| ERC20Predicate           | [0xC0dA09523c92714d0Df17e72966B3B80f228df8e](https://polygonscan.com/address/0xC0dA09523c92714d0Df17e72966B3B80f228df8e) |
| ERC721Predicate          | [0x02F08C48DaB9739C49A1F6C681B32fEFeCa9F1A9](https://polygonscan.com/address/0x02F08C48DaB9739C49A1F6C681B32fEFeCa9F1A9) |
| Marketplace              | [0x03109D4f1C5AE269Ba192bbD012C4145B3Dd65B2](https://polygonscan.com/address/0x03109D4f1C5AE269Ba192bbD012C4145B3Dd65B2) |
| MarketplacePredicate     | [0x20BF5bdC34a0B1Cb7c420910475c44512cA3da9f](https://polygonscan.com/address/0x20BF5bdC34a0B1Cb7c420910475c44512cA3da9f) |
| TransferWithSigPredicate | [0x4b8e69350c35B0a53145807Fb09b2Dc110b181a7](https://polygonscan.com/address/0x4b8e69350c35B0a53145807Fb09b2Dc110b181a7) |
| MintableERC721Predicate  | [0xc4E350f980f5c5f7D05c2FA7C8B71801F28Ca21b](https://polygonscan.com/address/0xc4E350f980f5c5f7D05c2FA7C8B71801F28Ca21b) |
| **Tokens**               |                                                                                                                          |
| RamaToken                | [0x55a5CC06801bBa4C030568f1A7ee1c753FDcbe36](https://polygonscan.com/address/0x55a5CC06801bBa4C030568f1A7ee1c753FDcbe36) |
| RootERC721               | [0x80E9FCD559001D1Af75883d8fc7CAf99bdab51Bf](https://polygonscan.com/address/0x80E9FCD559001D1Af75883d8fc7CAf99bdab51Bf) |
| RamaWmatic               | [0x3413e262742c22BeEd13f778C26cacBd726C3aa8](https://polygonscan.com/address/0x3413e262742c22BeEd13f778C26cacBd726C3aa8) |
| TestToken                | [0x738EC5f482302D2cb30B1938b8f25FCb85D214ef](https://polygonscan.com/address/0x738EC5f482302D2cb30B1938b8f25FCb85D214ef) |

**Child chain: Ramestta mainnet**

| Contracts  | Address                                                                                                                   |
| ---------- | ------------------------------------------------------------------------------------------------------------------------- |
| ChildChain | [0xfE9abcBF139636208efbaf9214E79c4932491303](https://www.ramascan.com/address/0xfE9abcBF139636208efbaf9214E79c4932491303) |
| **Tokens** |                                                                                                                           |
| RamaToken  | [0x0000000000000000000000000000000000001010](https://www.ramascan.com/address/0x0000000000000000000000000000000000001010) |
| RamaWmatic | [0x15585227a07371c5cEC7730D54A46C45090e367b](https://www.ramascan.com/address/0x15585227a07371c5cEC7730D54A46C45090e367b) |
| TestToken  | [0xB4A44BD58072FD1d18626FFdc82936C22f571FB5](https://www.ramascan.com/address/0xB4A44BD58072FD1d18626FFdc82936C22f571FB5) |
| RootERC721 | [0xE9cb4C5Dd318096dEC473342B3dE028442A464f1](https://www.ramascan.com/address/0xE9cb4C5Dd318096dEC473342B3dE028442A464f1) |

**Testnet:**

**Parent chain: Mumbai**

| Contracts                | Address                                                                                                                         |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| Governance               | [0xFd2811a6D7960298dE5616aF3F6BFf25c554FA4f](https://mumbai.polygonscan.com/address/0xFd2811a6D7960298dE5616aF3F6BFf25c554FA4f) |
| GovernanceProxy          | [0xFF71EAA9a0dEA5F52cE37011C837A5dc64A5a976](https://mumbai.polygonscan.com/address/0xFF71EAA9a0dEA5F52cE37011C837A5dc64A5a976) |
| Registry                 | [0xcFff107085C32D8FC3dB72F38542BE57d1dD6Aec](https://mumbai.polygonscan.com/address/0xcFff107085C32D8FC3dB72F38542BE57d1dD6Aec) |
| RootChain                | [0x2C44209a146B62ed5d6a647DB439936bFD0D008b](https://mumbai.polygonscan.com/address/0x2C44209a146B62ed5d6a647DB439936bFD0D008b) |
| RootChainProxy           | [0x9B438173600B51BF50A66A87032A00419a4f4924](https://mumbai.polygonscan.com/address/0x9B438173600B51BF50A66A87032A00419a4f4924) |
| ValidatorShareFactory    | [0x62D4cE7DeFf3Ae50c1f34014Ad6AB0B7426c318F](https://mumbai.polygonscan.com/address/0x62D4cE7DeFf3Ae50c1f34014Ad6AB0B7426c318F) |
| StakingInfo              | [0x402fdC8fAf19C78B6650C820063697368AB87c40](https://mumbai.polygonscan.com/address/0x402fdC8fAf19C78B6650C820063697368AB87c40) |
| StakingNFT               | [0xbc80A2503A6B68D7786CB5224761ae00E066d3ce](https://mumbai.polygonscan.com/address/0xbc80A2503A6B68D7786CB5224761ae00E066d3ce) |
| StakeManager             | [0xBaE4E354111E2878dD58285c49441F30A2e8a605](https://mumbai.polygonscan.com/address/0xBaE4E354111E2878dD58285c49441F30A2e8a605) |
| StakeManagerExtension    | [0x595A46cE2337bE7AafF77B64B98E4B594C3cCAB5](https://mumbai.polygonscan.com/address/0x595A46cE2337bE7AafF77B64B98E4B594C3cCAB5) |
| StakeManagerProxy        | [0x4DeB327E827B48134F6ae1Ba1443145a3ECeb1A9](https://mumbai.polygonscan.com/address/0x4DeB327E827B48134F6ae1Ba1443145a3ECeb1A9) |
| SlashingManager          | [0xa655E65cc4341348c5ef847D6C7EC168EcB9b056](https://mumbai.polygonscan.com/address/0xa655E65cc4341348c5ef847D6C7EC168EcB9b056) |
| ValidatorShare           | [0x52735479CaD457Fb61f692D0ed0072c164E7c3F2](https://mumbai.polygonscan.com/address/0x52735479cad457fb61f692d0ed0072c164e7c3f2) |
| StateSender              | [0x924eEb1aeB7860Dce05546e6116D5bE1F2e8291A](https://mumbai.polygonscan.com/address/0x924eEb1aeB7860Dce05546e6116D5bE1F2e8291A) |
| DepositManager           | [0xc8a849d18DA4a7eE5382b0f69355822353511De8](https://mumbai.polygonscan.com/address/0xc8a849d18DA4a7eE5382b0f69355822353511De8) |
| DepositManagerProxy      | [0xcE23138bb8FF006257B3491c5112EE1325f9C3fa](https://mumbai.polygonscan.com/address/0xcE23138bb8FF006257B3491c5112EE1325f9C3fa) |
| DrainStakeManager        | [0x288FC3A8AD57848E2C1Db8Bb7020fB87bA1f1b94](https://mumbai.polygonscan.com/address/0x288FC3A8AD57848E2C1Db8Bb7020fB87bA1f1b94) |
| WithdrawManager          | [0xd9E80Fec473Bd312C5ED9e1517814857bB6c1e2e](https://mumbai.polygonscan.com/address/0xd9E80Fec473Bd312C5ED9e1517814857bB6c1e2e) |
| ExitNFT                  | [0x6cF8D0668BCd60aB236aB404f8F4B2272c630941](https://mumbai.polygonscan.com/address/0x6cF8D0668BCd60aB236aB404f8F4B2272c630941) |
| WithdrawManagerProxy     | [0x813D775Da59C2d0aAC61b487189E49DdD640DFaa](https://mumbai.polygonscan.com/address/0x813D775Da59C2d0aAC61b487189E49DdD640DFaa) |
| ERC20Predicate           | [0x1481e0265212cE02e26866cbA4dB50afc00f6452](https://mumbai.polygonscan.com/address/0x1481e0265212cE02e26866cbA4dB50afc00f6452) |
| ERC721Predicate          | [0xc8f3E2407Ff5F01EAdE185206147311bcF7F16d4](https://mumbai.polygonscan.com/address/0xc8f3E2407Ff5F01EAdE185206147311bcF7F16d4) |
| EventsHubProxy           | [0x6B67E9f35De42c98Ef9c51c5446e2a425421EcB9](https://mumbai.polygonscan.com/address/0x6B67E9f35De42c98Ef9c51c5446e2a425421EcB9) |
| EventsHub                | [0xE1cDb567A24Eb4cAD2b941166C1d739Cf136D300](https://mumbai.polygonscan.com/address/0xE1cDb567A24Eb4cAD2b941166C1d739Cf136D300) |
| Marketplace              | [0x44CF9c61Cb2eA4AACb9B897a87C309594F1FD4dF](https://mumbai.polygonscan.com/address/0x44CF9c61Cb2eA4AACb9B897a87C309594F1FD4dF) |
| MarketplacePredicate     | [0x79A016F0014ec6F0A2Aa3299325e8f7C2fB4db59](https://mumbai.polygonscan.com/address/0x79A016F0014ec6F0A2Aa3299325e8f7C2fB4db59) |
| TransferWithSigPredicate | [0x17813f09c052842D791de952b95230F2828E71Ae](https://mumbai.polygonscan.com/address/0x17813f09c052842D791de952b95230F2828E71Ae) |
| MintableERC721Predicate  | [0x47ec197B6b3F9DE425017D4e78751A23c9415653](https://mumbai.polygonscan.com/address/0x47ec197B6b3F9DE425017D4e78751A23c9415653) |
| BytesLib                 | [0x8a6E08f915A2B5099eED73765505cc45401a394A](https://mumbai.polygonscan.com/address/0x8a6E08f915A2B5099eED73765505cc45401a394A) |
| Common                   | [0x0B344c1f3bbbb5E0EE01bf8AA6542e9EA5af6539](https://mumbai.polygonscan.com/address/0x0B344c1f3bbbb5E0EE01bf8AA6542e9EA5af6539) |
| ECVerify                 | [0xA41F785Fa1841c97D59308291258A57Db8Ed799D](https://mumbai.polygonscan.com/address/0xA41F785Fa1841c97D59308291258A57Db8Ed799D) |
| Merkle                   | [0x1E5A9b8F13e796C3EFcEFA367b5e93E776527e57](https://mumbai.polygonscan.com/address/0x1E5A9b8F13e796C3EFcEFA367b5e93E776527e57) |
| MerklePatriciaProof      | [0x457Da8023e3fbEc1e8005e7C2D5B41Bf42c06776](https://mumbai.polygonscan.com/address/0x457Da8023e3fbEc1e8005e7C2D5B41Bf42c06776) |
| PriorityQueue            | [0xE035d776FB4E40aF22D2B67c4B16680B00d7b830](https://mumbai.polygonscan.com/address/0xE035d776FB4E40aF22D2B67c4B16680B00d7b830) |
| RLPEncode                | [0xbf43A531Fdc8B51f26d2BFff30fE20890A6cc6Bb](https://mumbai.polygonscan.com/address/0xbf43A531Fdc8B51f26d2BFff30fE20890A6cc6Bb) |
| RLPReader                | [0x169DDA5d093F0649258810E08db062c3a9557b76](https://mumbai.polygonscan.com/address/0x169DDA5d093F0649258810E08db062c3a9557b76) |
| SafeMath                 | [0xdc4FE123E4b46668b44AbA97F790FB338eC16ba7](https://mumbai.polygonscan.com/address/0xdc4FE123E4b46668b44AbA97F790FB338eC16ba7) |
| TransferWithSigUtils     | [0x6dF62CaFb0F012679E26976092b39595e4174189](https://mumbai.polygonscan.com/address/0x6dF62CaFb0F012679E26976092b39595e4174189) |
| **Tokens**               |                                                                                                                                 |
| RamaWmatic               | [0x23b15Da01CF9Fa62c64cBF51b0104930Ac50fc59](https://mumbai.polygonscan.com/address/0x23b15Da01CF9Fa62c64cBF51b0104930Ac50fc59) |
| RamaToken                | [0x1eB6956E6c5F27d822FC34DF076f38e6535fA079](https://mumbai.polygonscan.com/address/0x1eB6956E6c5F27d822FC34DF076f38e6535fA079) |
| RootERC721               | [0x346E78C2CBb4e6684f1897FF4e4D085EDfB3ed6C](https://mumbai.polygonscan.com/address/0x346E78C2CBb4e6684f1897FF4e4D085EDfB3ed6C) |
| TestToken                | [0xBca68f6B0f8BD5eb51465041C3E6073616f4eF4E](https://mumbai.polygonscan.com/address/0xBca68f6B0f8BD5eb51465041C3E6073616f4eF4E) |

**Child chain: Ramestta mainnet**

| Contracts  | Address                                    |
| ---------- | ------------------------------------------ |
| ChildChain | 0x0B344c1f3bbbb5E0EE01bf8AA6542e9EA5af6539 |
| **Tokens** |                                            |
| RamaToken  | 0x0000000000000000000000000000000000001010 |
| RamaWmatic | 0x8ed67eAE1AD7d3266d6E6Cb06D21D66af77018Ce |
| TestToken  | 0x8d816Cf6c9e5228d4311289AB455275181a613A1 |
| RootERC721 | 0xa36f23f322fBC06a09077C1d6d57cE1948C26E73 |


# Delegation via validator shares

Ramestta supports delegation via validator shares. By using this design,it is easier to distribute rewards and slash with scale (thousands of delegators) on Polygon contracts without much computation.

Delegators delegate by purchasing shares of a finite pool from validators. Each validator will have their own validator share token. Let’s call these fungible tokens RAMA for a validator `A`. As soon as a user delegates to a validator `A`, they will be issued RAMA based on an exchange rate of RAMA`/`RAMA pair. As users accrue value the exchange rate indicates that they can now withdraw more RAMA for each RAMA and when users get slashed, users withdraw less RAMA for their RAMA.

Note that `RAMA` is a staking token. A delegator needs to have `RAMA` tokens to participate in the delegation.

Initially, a delegator `D` buys tokens from validator `A` specific pool when `1 RAMA per 1 RAMA`.

When a validator gets rewarded with more `RAMA` tokens, new tokens are added to the pool. Let’s say with the current pool of `100 RAMA` tokens, `10 RAMA` rewards are added to the pool. But since the total supply of `RAMA` tokens didn’t change due to rewards, the exchange rate becomes `1 RAMA per 0.9 RAMA`. Now, delegator `D` gets more `RAMA` for the same shares.

`RAMA`: Validator specific minted validator share tokens (ERC20 tokens)

### Technical specification: <a href="#technical-specification" id="technical-specification"></a>

```
uint256 public validatorId; // Delegation contract for validator
uint256 public validatorRewards; // accumulated rewards for validator
uint256 public commissionRate; // validator's cut %
uint256 public validatorDelegatorRatio = 10; // to be implemented/used

uint256 public totalStake;
uint256 public rewards; // rewards for pool of delegation stake
uint256 public activeAmount; // # of tokens delegated which are part of active stake

```

Exchange rate is calculated as below:

```
ExchangeRate = (totalDelegatedPower + delegatorRewardPool) / totalDelegatorShares
```

### Methods and variables: <a href="#methods-and-variables" id="methods-and-variables"></a>

#### buyVoucher: <a href="#buyvoucher" id="buyvoucher"></a>

```
function buyVoucher(uint256 _amount) public;
```

* Transfer the `_amount` to stakeManager and update the timeline data structure for active stake.
* `updateValidatorState` is used to update timeline DS.
* `Mint` delegation shares using current `exchangeRate` for `_amount`.
* `amountStaked` is used to keep track of active stake of each delegator in order to calculate liquid rewards.

#### sellVoucher: <a href="#sellvoucher" id="sellvoucher"></a>

```
function sellVoucher() public;
```

* Using current `exchangeRate` and number of shares to calculate total amount (active stake + rewards).
* `unBond` active stake from validator and transfer rewards to delegator, if any.
* Must remove active stake from timeline using `updateValidatorState` in stakeManger.
* `delegators` mapping is used to keep track of stake in withdrawal period.

#### withdrawRewards: <a href="#withdrawrewards" id="withdrawrewards"></a>

```
function withdrawRewards() public;
```

* For a delegator, calculate the rewards and transfer, and depending upon `exchangeRate` burn count of shares.
* Example: if a delegator owns 100 shares and exchange rate is 200 so rewards are 100 tokens, transfer 100 tokens to delegator. Remaining stake is 100 so using exchange rate 200, now it is worth 50 shares. So burn 50 shares. Delegator now has 50 shares worth 100 tokens (which he initially staked / delegated).

#### reStake: <a href="#restake" id="restake"></a>

Restake can work in two ways: delegator can buy more shares using `buyVoucher` or reStake rewards.

```
function reStake() public;
```

Above function is used to reStake rewards. The number of shares aren’t affected because `exchangeRate` is the same; so just the rewards are moved into active stake for both validator share contract and stakeManager timeline.

`getLiquidRewards` is used for calculating accumulated rewards i.e., delegator owns 100 share and exchange rate is 200, so rewards are 100 tokens. Move 100 tokens into active stake, since exchange rate is still same number of share will also remain same. Only difference is that now 200 tokens are considered into active stake and can’t be withdrawn immediately (not a part of liquid rewards).

Purpose of reStaking is that since delegator’s validator has now more active stake and they will earn more rewards for that so will the delegator.

#### unStakeClaimTokens: <a href="#unstakeclaimtokens" id="unstakeclaimtokens"></a>

```
function unStakeClaimTokens()
```

Once withdrawal period is over, delegators who’ve sold their shares can claim their MATIC tokens. Must transfer tokens to user.

#### updateCommissionRate: <a href="#updatecommissionrate" id="updatecommissionrate"></a>

```
function updateCommissionRate(uint256 newCommissionRate)
        external
        onlyValidator
```

* Updates commission % for the validator.

#### updateRewards: <a href="#updaterewards" id="updaterewards"></a>

```
function updateRewards(uint256 reward, uint256 checkpointStakePower, uint256 validatorStake)
        external
        onlyOwner
        returns (uint256)
```

When a validator gets rewards for submitting checkpoint, this function is called for disbursements of rewards between validator and delegators.


# Staking manager

For the Ramestta’s Proof of Security based consensus, all the ⅔+1 proof verification and handling of staking, rewards are executed on the Polygon smart contract. The whole design follows this philosophy of doing less on the Mainnet contract. It does information verification and pushes all the computation-heavy operations to L2 (read about [Heimdall](/welcome-to-ramestta/architecture/heimdall)).

**Stakers** are divided into **validators**, **delegators**, and **watchers** (for fraud reporting).

[**StakeManager**](https://github.com/Ramestta-Blockchain/contracts/blob/main/contracts/staking/stakeManager/StakeManager.sol) is the main contract for handling validator related activities like `checkPoint` signature verification, reward distribution, and stake management. Since the contract is using **NFT ID** as a source of ownership, change of ownership and signer won’t affect anything in the system.

To ensure Proof of Security consensus, Ramestta executes all proof verification and staking operations on the Polygon smart contract, leaving the computation-heavy tasks to L2.&#x20;

Stakeholders can take on the role of a validator, delegate, or watcher for reporting fraud. StakeManager is the primary contract for validator-related activities such as stake management, reward distribution, and signature verification. Only one role, either validator or delegator, can be assigned to a single Polygon address as a design choice.&#x20;

Using NFT ID as the source of ownership ensures that changes in ownership and signer will not impact the system.

`validatorThreshold`: Shows the maximum number of validators accepted by the system, also called slots

#### AccountStateRoot[​](https://wiki.polygon.technology/docs/pos/contracts/stakingmanager#accountstateroot) <a href="#accountstateroot" id="accountstateroot"></a>

* For various accounting done on heimdall for validators and delegator account root is submitted while submitting the `checkpoint` .
* accRoot is used while `claimRewards` and `unStakeClaim` .

### Stake/stakeFor[​](https://wiki.polygon.technology/docs/pos/contracts/stakingmanager#stakestakefor) <a href="#stake-stakefor" id="stake-stakefor"></a>

StakeManager.sol

```
function stake(
    uint256 amount,
    uint256 heimdallFee,
    bool acceptDelegation,
    bytes calldata signerPubkey
) public;

function stakeFor(
    address user,
    uint256 amount,
    uint256 heimdallFee,
    bool acceptDelegation,
    bytes memory signerPubkey
) public;

```

* Allows anyone with amount (in RAMA tokens) greater `minDeposit` then if `currentValidatorSetSize` is less then `validatorThreshold` .
* MUST transfer `amount+heimdallFee` , puts validator into auction period for an auctionInterval.(more on auction in auction section)
* `updateTimeLine` updates special timeline data structure, which keeps track of active validators and active stake for given epoch/checkpoint count.
* One unique `NFT` is minted on each new stake/stakeFor call, which can be transferred to anyone but can be owned 1:1 ethereum address.
* `acceptDelegation` set true if validators want to accept delegation, `ValidatorShare` contract is deployed for the validator.

### unstake:[​](https://wiki.polygon.technology/docs/pos/contracts/stakingmanager#unstake) <a href="#unstake" id="unstake"></a>

1. If a validator decides to unstake, they will be removed from the validator set in the next epoch. However, this removal is only applicable for the current checkpoint.
2. To account for a validator's exit, their stake will be removed from the timeline data structure, and the count for their exit epoch will be updated.
3. If a validator had a delegation, they should collect all rewards before their exit, and their delegation contract should be locked to prevent new delegations.

### unstakeClaim:[​](https://wiki.polygon.technology/docs/pos/contracts/stakingmanager#unstakeclaim) <a href="#unstakeclaim" id="unstakeclaim"></a>

```
function unstakeClaim(uint256 validatorId) public;
```

* After `unstaking` validators are put into withdrawal period so that they can be slashed if any fraud found after `unstaking` for pas frauds.
* Once `WITHDRAWAL_DELAY` period is served validator's can call this function and do settlement with stakeManager(get rewards if any, get staked tokens back, burn NFT etc)

### Restake[​](https://wiki.polygon.technology/docs/pos/contracts/stakingmanager#restake) <a href="#restake" id="restake"></a>

```
function restake(uint256 validatorId, uint256 amount, bool stakeRewards) public;
```

* Allows validators to increase their stake by putting new amount or rewards or both.
* MUST update timeline(amount) for active stake.

### withdrawRewards[​](https://wiki.polygon.technology/docs/pos/contracts/stakingmanager#withdrawrewards) <a href="#withdrawrewards" id="withdrawrewards"></a>

```
function withdrawRewards(uint256 validatorId) public;
```

* Allows validators to withdraw accumulated rewards, must consider getting rewards from delegation contract if validator accepts delegation.

### updateSigner[​](https://wiki.polygon.technology/docs/pos/contracts/stakingmanager#updatesigner) <a href="#updatesigner" id="updatesigner"></a>

```
function updateSigner(uint256 validatorId, bytes memory signerPubkey) public
```

* Allows validators to update signer address(which is used to validate blocks on ramestta chain and checkpoint sigs on stakeManager)

#### topUpForFee[​](https://wiki.polygon.technology/docs/pos/contracts/stakingmanager#topupforfee) <a href="#topupforfee" id="topupforfee"></a>

```
function topUpForFee(uint256 validatorId, uint256 heimdallFee) public;
```

* Validators can top-up their balance for heimdall fee by invoking this method.

### claimFee[​](https://wiki.polygon.technology/docs/pos/contracts/stakingmanager#claimfee) <a href="#claimfee" id="claimfee"></a>

```
function claimFee(
        uint256 validatorId,
        uint256 accumSlashedAmount,
        uint256 accumFeeAmount,
        uint256 index,
        bytes memory proof
    ) public;

```

* Used to withdraw fee from heimdall.
* `accountStateRoot` is updated on each checkpoint, so that validators can provide proof of inclusion in this root for account on heimdall and withdraw fee.
* Note that `accountStateRoot` is re-written to prevent exits on multiple checkpoints(for old root and save accounting on stakeManager)
* `accumSlashedAmount` is unused atm, will be used for slashing on heimdall if needed.

#### StakingNFT[​](https://wiki.polygon.technology/docs/pos/contracts/stakingmanager#stakingnft) <a href="#stakingnft" id="stakingnft"></a>

* Standard erc721 with few restrictions like one token per user and minted in sequential manner.

### Validator Replacement[​](https://wiki.polygon.technology/docs/pos/contracts/stakingmanager#validator-replacement) <a href="#validator-replacement" id="validator-replacement"></a>

* In order to replace poor performing validator there is periodic auction for each validator slot.
* For individual validators there is auction window where wanna be validators can bid their amount and start an auction using `startAuction` function.
* Once the `auctionInterval` is over last bidder needs to close the auction in order to confirm and become validator. For which she needs to call `confirmAuctionBid` which accepts and behave similar to new `stake` function for upcoming validator and `unStake` for old validator.
* Current validator can bid for herself and try to keep that place.
* Whole mech dynamically balances the stake value and overall security according to market conditions and use of ramestta chain.

**startAuction**[​](https://wiki.polygon.technology/docs/pos/contracts/stakingmanager#startauction)

```
function startAuction(
    uint256 validatorId, /**  auction for validator */
    uint256 amount /**  amount greater then old validator's stake */
    ) external;

```

* In order to start a bid or bid higher on already running auction this function is used.
* Auction period runs in cycles like `(auctionPeriod--dynasty)--(auctionPeriod--dynasty)--(auctionPeriod--dynasty)` so it MUST check for correct auction period.
* `perceivedStakeFactor` is used to calculate exact factor\*old stake (note currently it is by default 1 WIP for picking the function).
* MUST check for auction from last auction period if any still going on (one can choose to not call `confirmAuction` in order to get her capital out in next auction).
* Normally continuous english auction is going on in a `auctionPeriod` .

**confirmAuctionBid**[​](https://wiki.polygon.technology/docs/pos/contracts/stakingmanager#confirmauctionbid)

```
function confirmAuctionBid(
        uint256 validatorId,
        uint256 heimdallFee, /** for new validator */
        bool acceptDelegation,
        bytes calldata signerPubkey
    ) external

```

* **MUST check that this is not an auctionPeriod.**
* If last bidder is owner of `validatorId` behaviour should be similar to restake.
* In second case unStake `validatorId` and add new user as validator from next checkpoint, for the new user behaviour should be similar to stake/stakeFor.

### checkSignatures[​](https://wiki.polygon.technology/docs/pos/contracts/stakingmanager#checksignatures) <a href="#checksignatures" id="checksignatures"></a>

```
function checkSignatures(
        uint256 blockInterval,
        bytes32 voteHash,
        bytes32 stateRoot,
        bytes memory sigs
    ) public;

```

* Writes are meant only for RootChain contract when submitting checkpoints
* `voteHash` on which all validators sign (BFT ⅔+1 agreement)
* This function validates only unique sigs and checks for ⅔+1 power has signed on checkpoint root (inclusion in `voteHash` verification in RootChain contract for all data) `currentValidatorSetTotalStake` provides current active stake.
* Rewards are distributed proportional to validator's stake.

#### &#x20;isValidator[​](https://wiki.polygon.technology/docs/pos/contracts/stakingmanager#isvalidator)

* Checks if given validator is active validator for current epoch.

#### Timeline data structure[​](https://wiki.polygon.technology/docs/pos/contracts/stakingmanager#timeline-data-structure) <a href="#timeline-data-structure" id="timeline-data-structure"></a>

```
struct State {
    int256 amount;
    int256 stakerCount;
}

mapping(uint256 => State) public validatorState;

```

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2F0pxYBd1K7N42YLRhwxKB%2Fstaking_manager.png?alt=media&amp;token=b447fa13-8cbd-4cc5-84db-9688127ab043" alt=""><figcaption></figcaption></figure>

## `StakingInfo:` <a href="#stakinginfo" id="stakinginfo"></a>

Source: [StakingInfo.sol](https://github.com/Ramestta-Blockchain/contracts/blob/main/contracts/staking/StakingInfo.sol)

Centralised logging contract for both validator and delegation events, Includes few read only functions.

### ValidatorShareFactory: <a href="#validatorsharefactory" id="validatorsharefactory"></a>

A factory contract to deploy `ValidatorShare` contract for each validator who opt-in for delegation. You can check out the source code of the [ValidatorShareFactory.sol](https://github.com/Ramestta-Blockchain/contracts/blob/main/contracts/staking/validatorShare/ValidatorShareFactory.sol) contract on GitHub.


# Burns

When a user makes a transaction on the network, the **base fee is locked on a contract** on Ramestta, while **the priority fee is paid to the validato**r. This base fee will be split in 70% burned and 30% set aside to maintain the network.

Once a certain amount of RAMA (25,000) is accumulated in the burn contract, users can start the burn process from Ramestta. Once this process starts, accumulated RAMA are sent to Polygon's L1, where an automated swap for RAMA takes place, and this amount gets burned calling its contract function. It is comparable to a withdrawal transaction, but instead of receiving tokens, they are burned and taken out of the total supply.

Users will be able to use a specific portal on Ramestta's website for this process.&#x20;

Anyone can initiate these burns by just clicking "Initiate burn", and they will need to complete the process by confirming a few transactions to allow the layer migration. Once the process is complete, RAMA tokens will be directly taken out of circulation and this will be reflected on the total max. supply.

#### What is the difference between base fee and priority fee?

The **Base Fee** is a crucial component of transaction fees on a blockchain. It represents the minimum amount that a transaction must pay in order to be considered valid. The Base Fee can fluctuate with each block and is influenced by the level of congestion in the network. Specifically, if the previous block is close to being full, the Base Fee will increase, and vice versa.

One key feature of the Base Fee is that it is burned, which means it is not paid to the block producer (such as a miner or validator). This helps to prevent the Base Fee from becoming a profit center for those who control the network. Instead, it ensures that the fee is used solely to prioritize transactions and maintain the security of the blockchain.

On the other side, the **Priority Fee** is the amount a transaction pays to a block producer when it gets included in a block. However, the Max Priority Fee is the maximum amount a transaction is willing to pay, as the block producer may choose to accept less. To limit the amount paid, a Max Gas Fee can be set, which is the total fee a transaction is willing to pay.\
\
The **Priority Fee** goes to the block producer who successfully includes the transaction in a block. This incentivizes validators to include transactions with higher Priority Fees in their blocks, as they will earn more rewards for doing so.\
\
Example:&#x20;

Let's say the current base fee on the Ramestta network is X RAMA and the priority fee for a particular transaction is set at Y Rama. When a validator includes this transaction in a block, they will receive the Y Rama priority fee as a reward for including the transaction.

However, the X Rama base fee is not paid to the validator. Instead, it is converted into RAMA and burned, which means it is removed from circulation and effectively reduces the total supply of RAMA over time. This mechanism helps to prevent inflation and ensures that miners/validators do not have an incentive to artificially increase the base fee in order to earn more rewards.


# Bridge

### Introduction

Welcome to the documentation for our Token Bridge, a vital infrastructure component of our Ramestta blockchain. This guide aims to provide an overview of what the Token Bridge is, its significance, and a summary of how users can interact with it.

#### What is the Token Bridge?

The Token Bridge is a functionality that allows for the secure and seamless transfer of tokens between our Polygon and Ramestta blockchain. By using this bridge, users can enjoy the benefits of the scalability, low fees, and fast transactions offered by the Ramestta network while remaining connected to the broader Polygon ecosystem.

Access the Token Bridge[ here](https://validator.ramestta.com).

#### Why Use the Token Bridge?

1. **Scalability**: Migrating tokens to the Ramestta network lets users benefit from higher throughput and low latency.
2. **Reduced Transaction Costs**: Transaction fees on the Ramestta network are generally much lower, making it a more cost-effective platform for trading and yield farming activities.
3. **Speed**: Faster Ramestta network block times allow quicker transaction confirmations.
4. **Interoperability**: Keep the utility and functionality of your tokens across different layers of the blockchain.
5. **Accessibility**: Transferring tokens to Ramestta allows users to participate in Ramestta-specific decentralized applications (dApps), services, and protocols unavailable on the Polygon network.
6. **Security**: The Token Bridge employs state-of-the-art cryptographic techniques to ensure that transactions are secure and tokens are transferred safely between Polygon and Ramestta.

#### Plasma and PoS Tokens

In Ramestta infrastructure, we support two types of tokens: Plasma tokens and Proof-of-Stake (PoS coming soon) tokens.

**RAMA Token (Plasma)**

The RAMA token operates under the Plasma framework, which ensures high scalability and security. Plasma tokens like RAMA allow for rapid and low-cost transactions and can be securely withdrawn to the Polygon network via the Plasma Bridge.

**PoS Tokens**

All other supported tokens on our Token Bridge are PoS tokens. These tokens leverage our Proof-of-Stake consensus mechanism, balancing efficiency with security. PoS tokens can be quickly and securely transferred between Polygon and Ramestta through the Token Bridge.

### Supported Tokens

At present, the Token Bridge supports only a curated list of tokens. This list is continuously updated to ensure security and compatibility with our networks.


# Core


# Polygon To Ramestta

In order to natively read Polygon data from the Ramestta EVM chain, the mechanism utilized is known as 'State Sync'. This process facilitates the transfer of arbitrary data from the Polygon chain to the Ramestta chain. The essential steps involved include validators on the Heimdall layer listening for a specific event called 'StateSynced' from a Sender contract. Once this event is detected, the associated data is written to the Receiver contract. More details about this mechanism can be found here.

To enable this functionality, it is imperative to map the Sender and Receiver contracts on Polygon. The StateSender.sol contract must be aware of each sender and receiver, and a mapping request can be initiated here.

In the subsequent walkthrough, we will deploy a Sender contract on Mumbai (Polygon Testnet) and a Receiver contract on Ramestta Testnet.Following that, we will transmit data from the Sender and read the data on the Receiver using web3 calls in a node script.

1. **Deploy Sender Contract:** The Sender contract's primary function is to call the 'syncState' function on the StateSender contract, which is Rama's state syncer contract. The deployed addresses for Mumbai and Polygon Mainnet are as follows:

* Mumbai: 0x924eEb1aeB7860Dce05546e6116D5bE1F2e8291A
* Polygon Mainnet: 0xE0C9051E655380D1d880b9B0f4b500cEbD09278f

The Sender.sol contract code is as follows:

```solidity
// Sender.sol

pragma solidity ^0.5.11;

contract IStateSender {
  function syncState(address receiver, bytes calldata data) external;
  function register(address sender, address receiver) public;
}

contract sender {
  address public stateSenderContract = 0x924eEb1aeB7860Dce05546e6116D5bE1F2e8291A;
  address public receiver = 0x83bB46B64b311c89bEF813A534291e155459579e;

  uint public states = 0;

  function sendState(bytes calldata data) external {
    states = states + 1 ;
    IStateSender(stateSenderContract).syncState(receiver, data);
  }
}
```

Use Remix to deploy the contract and note the address and ABI.

2. **Deploy Receiver Contract:** The Receiver contract is invoked by a Validator when the 'StateSynced' event is emitted. The Validator triggers the 'onStateReceive' function on the Receiver contract to submit the data.

The Receiver.sol contract code is as follows:

```solidity
// receiver.sol

pragma solidity ^0.5.11;

// IStateReceiver represents interface to receive state
interface IStateReceiver {
  function onStateReceive(uint256 stateId, bytes calldata data) external;
}

contract receiver {
  uint public lastStateId;
  bytes public lastChildData;

  function onStateReceive(uint256 stateId, bytes calldata data) external {
    lastStateId = stateId;
    lastChildData = data;
  }
}
```

Deploy Receiver.sol on Ramestta Testnet and note the address and ABI.

3. **Mapping Sender and Receiver:** Use the deployed addresses or deploy custom contracts and request a mapping here.
4. **Sending and Receiving Data:** Write a node script to send arbitrary hex bytes, receive them on Puppynet, and interpret the data.

The complete script is as follows:

```solidity
// test.js

const Web3 = require('web3');
const Network = require("@ramesttanetwork/meta/network");

const network = new Network('testnet', 'ramestta');

const main = new Web3(network.Main.RPC);
const matic = new Web3(network.Ramestta.RPC);

// ... (private key, contract addresses, and ABIs)

// Data to sync
function getData(string) {
  let data = matic.utils.asciiToHex(string);
  return data;
}

// Send data via Sender
async function sendData(data) {
  let r = await sender.methods
    .sendState(getData(data))
    .send({
      from: main.eth.accounts.wallet[0].address,
      gas: 8000000
    });
  console.log('Sent data from root, ', r.transactionHash);
}

// ... (functions to check sender and receiver)

async function test() {
  await sendData('Hello World!');
  await checkSender();
  // Add a timeout here to allow a time gap for the state to sync
  await checkReceiver();
}

test();
```

Run the script using `node test`. A successful execution will provide an output similar to:

```
Sent data from root 0x4f64ae4ab4d2b2d2dc82cdd9ddae73af026e5a9c46c086b13bd75e38009e5204
Number of states sent from sender: 1
Last state id: 453 and last data: 0x48656c6c6f20576f726c642021
Interpreted data: Hello World!
```


# Ramestta To Polygon

The process of transferring data from Ramestta to Polygon, involving RAMA instead of MATIC, and Ramestta Testnet in place of Mumbai, follows a specific mechanism facilitated by checkpoint transactions and validation by Validators. Here is a detailed explanation of the process:

#### Data Transfer Mechanism from Ramestta to Polygon

1. **Transaction Creation on Ramestta:**
   * Execute a transaction on the child contract deployed on Ramestta, emitting an event that includes the data intended for transfer to Polygon.
   * The data is encoded in bytes and emitted in the event.
2. **Checkpoints by Validators:**
   * Validators on the Ramestta network pick up the transaction at specific intervals (typically 10-30 minutes), validate it, and add it to the checkpoint on Polygon.
3. **Checkpointing on Polygon:**
   * Validators create a checkpoint transaction on the RootChain contract in Polygon, ensuring the inclusion of the Ramestta transaction hash.
   * The rama.js(coming soon) library can be used to check the checkpoint addition.
4. **RootChainManager Contract:**
   * After checkpointing, submit the hash of the Ramestta transaction to the RootChainManager contract on Polygon as proof.
   * The RootChainManager contract validates the transaction, confirms its inclusion in the checkpoint, and decodes the event logs.
5. **Predicate Contract Usage:**
   * Utilize a Predicate contract, triggered only by the RootChainManager contract, to secure state changes on Polygon.
   * The state changes on Polygon occur only when the Ramestta transaction is checkpointed and verified by the RootChainManager contract.

#### Overview:

* A transaction is executed on the child contract on Ramestta, emitting an event with the data to transfer.
* Validators validate and checkpoint the transaction on Polygon.
* The rama.js library is used to trigger the exit function of the RootChainManager contract, ensuring secure state changes on Polygon.

#### Implementation:

1. **Child Contract (Ramestta):**

```solidity
contract Child {
    event Data(address indexed from, bytes bytes_data);
    uint256 public data;

    function setData(bytes memory bytes_data) public {
        data = abi.decode(bytes_data, (uint256));
        emit Data(msg.sender, bytes_data);
    }
}
```

2. **Root Contract (Polygon):**

```solidity
contract Root {
    address public predicate;

    constructor(address _predicate) public {
        predicate = _predicate;
    }

    modifier onlyPredicate() {
        require(msg.sender == predicate);
        _;
    }

    uint256 public data;

    function setData(bytes memory bytes_data) public onlyPredicate {
        data = abi.decode(bytes_data, (uint256));
    }
}
```

#### Mapping Contracts:

* Deploy these contracts on Ramestta and Polygon.
* Use the PoS bridge to map these contracts to maintain a connection between them across chains.

#### Testing the Implementation:

1. Create a transaction on Ramessta by calling the setData function of the child contract.
2. Wait for the checkpoint to be completed.
3. Check the checkpoint inclusion.
4. Use the rama.js SDK to call the exit function of the RootChainManager.

The provided exit script can be used to verify the inclusion of the Ramestta transaction hash on the Polygon chain and trigger the exitToken function of the Predicate contract. This ensures secure state changes on the root contract in Polygon.


# Plasma

Unveiling the Plasma Bridge: Transforming the Future of Ramestta and Polygon

In the rapidly evolving landscape of blockchain technology, the integration of Layer 2 solutions has become imperative to address scalability issues and enhance transaction efficiency. One such groundbreaking development is the Plasma Bridge, a transformative solution initially designed for Polygon but poised to redefine the dynamics with its integration into Ramestta. This article explores the key features and advantages of the Plasma Bridge, emphasizing its potential to revolutionize the decentralized ecosystem.

1. **Scaling Horizons: The Genesis of Plasma Bridge**

   At its core, the Plasma Bridge represents a technological leap, offering a layer of scalability to blockchain networks. Originally tailored for Polygon, its successful implementation has prompted a paradigm shift, with developers now gearing up to seamlessly integrate this innovative solution into the Ramestta network. This transition holds the promise of unlocking new possibilities for both ecosystems.
2. **Enhanced Throughput and Reduced Latency**

   The Plasma Bridge's primary objective is to mitigate the congestion and latency challenges faced by blockchain networks. By introducing a layer of off-chain computation, it significantly enhances transaction throughput and reduces confirmation times. This efficiency boost is poised to propel Ramestta into a new era of responsiveness, ensuring users experience swift and seamless interactions within the decentralized environment.
3. **Interoperability Amplified: From Polygon to Ramestta**

   The beauty of the Plasma Bridge lies in its ability to seamlessly adapt to different blockchain networks. As it transitions from its original integration with Polygon to becoming an integral part of Ramestta, a new era of interoperability unfolds. Users can now expect cross-chain functionalities with ease, fostering collaboration and fluidity between Ramestta and other ecosystems.
4. **Cost-Efficient Transactions and Microtransactions**

   With the Plasma Bridge in play, the cost of transactions witnesses a significant reduction. The off-chain nature of computations enables microtransactions to flourish, catering to a broader spectrum of users. As this technology becomes ingrained in Ramestta, the cost-effectiveness of transactions is expected to attract a more diverse user base, driving mass adoption.
5. **Security Reinvented: Plasma Bridge and Ramestta's Fortress**

   Security is paramount in the decentralized realm, and the Plasma Bridge is designed with this principle at its core. As it extends its services to Ramestta, users can rest assured that their assets are protected by a robust and proven security framework. The integration is a testament to the commitment to maintaining the integrity of both blockchain ecosystems.
6. **User-Centric Design: Ramestta's Experience Amplified**

   Beyond the technical aspects, the Plasma Bridge aims to enhance the overall user experience within the Ramestta ecosystem. With smoother and faster transactions, users can engage with decentralized applications seamlessly. This user-centric design aligns with Ramestta's vision of creating a user-friendly and accessible blockchain environment.
7. **Future Prospects: Ramestta's Ascension in the Blockchain Hierarchy**

   The integration of the Plasma Bridge marks a pivotal moment in Ramestta's journey. As it joins forces with this cutting-edge technology, Ramestta positions itself as a frontrunner in the race towards blockchain scalability and efficiency. The future holds the promise of increased adoption, further development, and the emergence of a robust decentralized ecosystem.

The Plasma Bridge's journey from Polygon to Ramestta or vice versa  signifies a significant stride towards a more scalable, efficient, and interconnected blockchain landscape. The collaboration between these two ecosystems holds immense potential to reshape the future of decentralized technologies, offering users a more seamless and secure experience.


# Deposit

#### **Prerequisites**

* **Compatible Crypto Wallet**: It is essential to have a crypto wallet that's compatible with the Ramestta Network. We recommend using Metamask due to its user-friendly interface.
  * **Metamask Setup**: If you haven't yet set up a Metamask wallet, download and install the Metamask browser extension and follow the on-screen instructions to create your wallet.

***

#### Steps for Bridging Tokens to Ramestta

**Step 1: Connect Your Wallet**

* Open the Ramestta Bridge(Coming Soon) by navigating to the Ramestta Bridge.
* Click on "Launch APP" to initiate the connection process.

**Step 2: Wallet Confirmation**

* You'll receive a prompt asking to confirm the connection between your Metamask wallet and the Ramestta Network. Click "Confirm" to proceed.

**Step 3: Access the Bridge Interface**

* After confirmation, you'll be redirected to the Bridge interface. You can also access this manually by selecting "Bridge" from the left menu bar.

<figure><img src="broken://files/xu6HGI6Ir2yq0bu4s1TC" alt=""><figcaption></figcaption></figure>

**Step 4: Select the Deposit Tab and Token**

* In the Bridge interface, navigate to the "Deposit" tab.
* Select the token you wish to bridge from the list and enter the amount you want to transfer.
* Click on the "Transfer" option to proceed.

<figure><img src="broken://files/5qucLtCR9AL6o1f3Kabq" alt="" width="563"><figcaption></figcaption></figure>

**Step 5: Review Important Notes and Estimated Fees**

* Read the important notes and instructions displayed on the screen.
* Click "Continue" to view the estimated gas fee for your transaction.
* If you agree with the estimated fees, click "Continue" to move to the next step.

**Step 6: Final Review and Confirmation**

* Review all transaction details, including the amount to be transferred and the estimated transaction fee.
* Click "Continue" to proceed to the last step.

<figure><img src="broken://files/NGzoACZGULqzzFJ4rN5N" alt="" width="563"><figcaption></figcaption></figure>

**Step 7: Signature and Transfer Approval**

* You'll receive a Metamask prompt asking for your signature and approval for the transaction.
* Verify all the details are correct and click "Confirm" to finalize the transaction.

**Step 8: Transaction Monitoring**

* After confirming the transaction, you can monitor its status through your Ramestta wallet.
* Optionally, click "View on Polygonscan" to check the transaction status directly on the Polygon blockchain.

By following these steps, you can securely bridge your tokens from the Polygon network to the Ramestta network. Happy Bridging!

Note: It can take upto 1 hours to reflect your balance in Ramestta network.


# Withdraw

#### Preliminary Steps

1. **Connect MetaMask**: Make sure your MetaMask wallet is connected to the same admin address used during your grant creation.
2. **Navigate to Dashboard**: Once connected, the Ramestta Bridge dashboard should appear.
3. **Access Bridge Interface**: From the dashboard, navigate to the Ramestta Bridge page. Alternatively, you can also click on the Bridge icon in the left navigation drawer.

#### Withdrawal Steps

1. **Select 'Withdraw'**: Switch to the withdrawal view as described in the PoS section.
2. **Choose Tokens**: Select RAMA from the token list.
3. **Enter Amount**: Specify how much you wish to withdraw, or click 'MAX' to withdraw all.
4. **Confirm Transaction Fee**: Acknowledge the transaction fee and the time it may take (up to 7 days).
5. **Sign Transactions**: Sign two transactions, similar to the PoS method.
6. **Completion**: The withdrawal may take up to 7 days to complete. Once the time frame is completed user again has to submit the burn proof in the Polygon network (Calling process exit in withdrawal contract). Confirm using Polygonscan after that period.
7. **Verify Funds**: Once the challenge period is over, check your Polygon wallet to confirm the tokens have arrived.

#### Important Note

The 'challenge period' is the time required for the network to confirm the legitimacy of your transaction. It could take a few hours with PoS or up to 7 days with Plasma, depending on the method you choose.

### Plasma Bridge Withdrawal: Backend Operations

#### Plasma - Burn (Withdraw Function)

When you initiate a withdrawal request using the Plasma bridge, the first operation that happens in the backend is the invocation of a function known as `withdraw`. This function essentially "burns" the tokens you have in the Ramestta L2 layer. "Burning" in this context means these tokens are permanently removed from the circulating supply on the L2, rendering them unusable there. This step acts as a lock-in mechanism to ensure that the same tokens can't be used simultaneously on both L2 and L1. Essentially, it prepares your tokens for their journey from the Ramestta L2 back to the Polygon L1.

#### Confirm Withdraw (Checkpoint Submission)

The next phase in the backend is the `Confirm Withdraw` operation. However, this operation can't be immediately carried out. First, a "checkpoint" needs to be submitted to the main Polygon chain. A checkpoint is like a snapshot of all transactions that have taken place on the Ramestta L2 since the last snapshot. Once this checkpoint is successfully submitted and confirmed on the Polygon mainnet, the `startExitWithBurntTokens` function can be called. This function validates that the tokens have indeed been burnt (or locked) on Ramestta L2. Essentially, it confirms that the tokens are ready to be reissued on the Polygon L1 and marks them for exit.

#### Process Exit (Submit Proof of Burn)

The final backend operation in a Plasma-based withdrawal is the `Process Exit` phase. This involves a function known as `processExits`. Here, you are required to submit a "proof of burn" — essentially a cryptographic proof demonstrating that the tokens were genuinely burned on Ramestta L2. This is a security measure to prevent fraudulent withdrawals. Once the Polygon network validates this proof, the same number of tokens are reissued or "minted" on Polygon L1. These tokens are then transferred back into your wallet, completing the full circle of the withdrawal process.

\
So, while you interact with a user-friendly frontend interface to initiate the withdrawal, there are these critical backend operations being executed to ensure the secure and accurate transfer of your tokens from Ramestta to Polygon.


# PoS

Connecting Ramestta and Polygon with POS Chain

In the dynamic world of blockchain technology, the need for seamless interoperability has driven the development of innovative solutions like POS (Proof of Stake) chain bridges. This section  will delve into the intricacies of bridging Ramestta and Polygon using a POS chain, providing insights into the processes involved in both directions. Whether you are considering bridging from Ramestta to Polygon or vice versa, understanding the functionality of this POS chain bridge is crucial for unlocking the full potential of these interconnected blockchain networks.

1. **Bridging from Ramestta to Polygon: The POS Chain Perspective**

   a. **Staking and Asset Locking:** Initiating the bridge from Ramestta to Polygon involves users staking their assets on the Ramestta network. The POS chain then locks these assets, triggering the minting of equivalent assets on the Polygon network.

   b. **Proof of Stake Validation:** The POS chain utilizes a Proof of Stake consensus mechanism to validate transactions and ensure the security of the bridging process. Validators play a crucial role in confirming the legitimacy of the staked assets and the corresponding minted assets on the Polygon side.

   c. **Transparent Confirmation:** The POS chain guarantees transparency in confirming transactions, providing users with a verifiable and secure process for moving assets from Ramestta to Polygon.
2. **Bridging from Polygon to Ramestta: Leveraging Proof of Stake Dynamics**

   a. **Staking on Polygon:** Users looking to bridge from Polygon to Ramestta initiate the process by staking their assets on the Polygon network. The POS chain, recognizing this staking activity, facilitates the locking of assets on Polygon and the minting of equivalent assets on Ramestta.

   b. **POS Consensus for Cross-Chain Verification:** The POS chain employs its Proof of Stake consensus mechanism to verify and validate the cross-chain transactions. This decentralized validation ensures the authenticity of the locked assets on Polygon and their corresponding minted equivalents on Ramestta.

   c. **Efficient Transaction Settlement:** With the assistance of the POS chain, the bridging process efficiently settles transactions, allowing users to experience a smooth and secure transfer of assets between Polygon and Ramestta.
3. **The Role of Oracles in Cross-Chain POS Transactions**

   a. **Real-Time Asset Pricing:** Oracles continue to play a crucial role in cross-chain POS transactions. They provide real-time pricing information, ensuring that the value of assets moved between Ramestta and Polygon remains accurate and up-to-date.

   b. **Decentralized Validation:** Oracles contribute to the decentralization of the POS chain bridge, further validating transactions across the two blockchains without the need for a centralized authority. This enhances security and trust in the bridging process.
4. **Security Measures and Auditing Protocols**

   a. **POS Chain Audits:** The POS chain, along with Ramestta and Polygon, enforces rigorous audits of its mechanisms to ensure the security of the bridging process. Users can trust in the integrity of the POS chain, backed by thoroughly vetted and secure protocols.

   b. **Immutable Record Keeping:** The blockchain nature of both Ramestta and Polygon, coupled with the POS chain, ensures an immutable record of transactions. This transparency provides users with a tamper-proof history of asset movements.
5. **Future Perspectives: Forging a Collaborative Blockchain Ecosystem**

   a. **Versatile Use Cases:** The bidirectional POS chain bridge between Ramestta and Polygon unlocks diverse use cases, spanning from decentralized finance (DeFi) opportunities to cross-platform decentralized applications (dApps). This fosters innovation and collaboration across the blockchain ecosystems.

   b. **Community Engagement:** As the POS chain bridge gains traction, active involvement from the blockchain communities of Ramestta and Polygon becomes pivotal. Community engagement can drive further refinements, optimizations, and exploration of new possibilities for the POS chain bridging infrastructure.

The Bridging of Ramestta to Polygon or Polygon to Ramestta using a POS chain represents a transformative step towards a more interconnected and versatile blockchain landscape. As technology advances and user adoption grows, the bidirectional POS chain bridge paves the way for collaborative possibilities, enriching the decentralized experience for users on both blockchain networks.


# Deposit

{% hint style="info" %}
Pease follow the same steps as mention on Plasma's Deposit section.

[Click here for redirect to deposit page](/welcome-to-ramestta/bridge/plasma/deposit)&#x20;
{% endhint %}


# Withdraw

#### Preliminary Steps

1. **Connect MetaMask**: Make sure your MetaMask wallet is connected to the same admin address used during your grant creation.
2. **Navigate to Dashboard**: Once connected, the Ramestta Bridge dashboard should appear.
3. **Access Bridge Interface**: From the dashboard, navigate to the Ramestta Bridge page. Alternatively, you can click the Bridge icon in the left navigation drawer.

#### Withdrawal Steps

1. **Select 'Withdraw'**: By default, the 'Deposit' tab is active. Press the 'Withdraw' button to switch to the withdrawal view.

<figure><img src="broken://files/1rHwxvfAtJG5rMxaSCtT" alt=""><figcaption></figcaption></figure>

2. **Choose Tokens**: Select the token pair, usually MATIC (Matic - PoS), or simply pick the token you want to send. Click 'Transfer'.

<figure><img src="broken://files/AR8mfG5IxXoAJYd6fPzx" alt="" width="563"><figcaption></figcaption></figure>

3. **Enter Amount**: Specify the amount you wish to withdraw. Alternatively, click 'MAX' to withdraw all your MATIC.
4. **Confirm Transaction Fee**: A pop-up will appear, asking you to confirm the transaction fee and acknowledge that the process may take up to 4 hours.
5. **Sign Transactions**: You'll have to sign two transactions. One to burn the token and the second to exit it in the Polygon network.
6. **Completion**: After about 3 hours, the process should be complete. You can confirm on Polygonscan using both mainnet and testnet URLs.
7. **Verify Funds**: After the challenge period, check your Polygon wallet to make sure the tokens have arrived.


# PoS vs Plasma Bridge

Moving between two large-scale blockchain networks requires a secure and robust cross-chain bridge, and Ramestta has achieved this by utilizing both Plasma and PoS(coming soon) security to create a trustless and bi-directional transaction environment between Ramestta and Polygon enables users to transfer tokens between the two networks without any third-party risks or impact on market liquidity. **The network bridge is designed to be fast, cost-effective, and flexible, and also serves as a scaling solution.** It utilizes a dual consensus architecture (Plasma + PoS platform) to prioritize speed and decentralization, and has deliberately enabled arbitrary state transitions on its sidechains along with EVM support.When your token crosses the bridge, it does not change its circulating supply:

* **Ramestta mints the same number of tokens** (1:1) as a pegged token **when a token leaves the Polygon network**.
* In order to move tokens back to the Polygon network, **they are burned on the Ramestta network and unlocked on the Polygon network** during the process.

#### PoS vs Plasma[​](https://wiki.polygon.technology/docs/develop/ethereum-polygon/getting-started/#pos-vs-plasma)​ <a href="#pos-vs-plasma" id="pos-vs-plasma"></a>

|                                   | PoS Bridge (Recommended)                                                                | Plasma Bridge                                                                        |
| --------------------------------- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| **Short description**             | DApp Developers looking for flexibility and faster withdrawals with PoS system security | DApp Developers looking for increased security guarantees with Plasma exit mechanism |
| **Structure**                     | Highly flexible                                                                         | Rigid, Less Flexible                                                                 |
| **Deposit (Polygon →Ramestta)**   | 22-30 mins                                                                              | 22-30 mins                                                                           |
| **Withdrawal (Ramestta→Polygon)** | 1 checkpoint = \~ 30 mins to 6 hours                                                    | Call to the process-exit procedure on Polygon's contract.                            |
| **Security**                      | Proof-of-Stake system, secured by a robust set of external validators                   | Ramestta’s Plasma contracts piggybacks on Polygon’s security                         |
| **Support Standards**             | MATIC, RAMA20, RAMA721, RAMA1155 and others                                             | Only MATIC, RAMA20, RAMA721                                                          |

\ <br>


# Node Setup

Pre requisites:-

### System requirements <a href="#system-requirements" id="system-requirements"></a>

The system requirements listed in this section are both for the Sentry node and the Validator node.The **minimum** system requirements mean you can run the nodes but the setup is not future-proof.The **recommended** system requirements mean the nodes are future-proof. There is, however, no upper limit to future-proofing your nodes.You must always run the sentry node and the validator node on separate machines.

#### Minimum system requirements <a href="#minimum-system-requirements" id="minimum-system-requirements"></a>

* RAM: 32 GB
* CPU: 8-core
* Storage: 2.5 TB SSD

InfoFor Amazon Web Services (AWS), the equivalent of the minimum requirements instances are, **with unlimited credits selected**:

* For Sentry: **c5.2xlarge**
* For Validator node: **c5.4xlarge**

#### Recommended system requirements <a href="#recommended-system-requirements" id="recommended-system-requirements"></a>

* RAM: 64 GB
* CPU: 16-core
* Storage: 5 TB SSD
* Bandwidth: 1 Gbit/s

InfoFor Amazon Web Services (AWS), the equivalent of the recommended requirements instance is **m5d.4xlarge**.For OVH, the equivalent of the recommended requirements instance is **infra-3**.For network, expect 3-5 TB of data transferred per month.


# Sentry Node


# Mainnet

## Run a Sentry Node from Binaries

### Prerequisites: <a href="#prerequisites" id="prerequisites"></a>

`build-essential` installed on both the sentry and the validator machines.

To install:

```
sudo apt-get install build-essential
```

Go 1.18 installed on validator machine.

To install:

```
wget https://raw.githubusercontent.com/Ramestta-Blockchain/launch/master/go-install.sh
bash go-install.sh
sudo ln -nfs ~/.go/bin/go /usr/bin/go
```

Docker and RabbitMQ to install on validator machines.

```
sudo apt-get update
sudo apt install rabbitmq-server
```

To install sublime-text:

```
sudo snap install sublime-text --classic
```

#### Installing Heimdall: <a href="#installing-heimdall" id="installing-heimdall"></a>

Heimdall is the proof-of-stake verifier layer responsible for checkpointing the representation of the Plasma blocks to the Ramestta mainnet.

Clone the [Heimdall repository](https://github.com/Ramestta-Blockchain/heimdall):thumbsup:

```
git clone https://github.com/Ramestta-Blockchain/heimdall
```

```
cd heimdall
```

```
make build
make install
```

```
cd ~
source ~/.bashrc
```

Check the Heimdall installation:

```
heimdalld version --long
```

note

Before proceeding, Heimdall should be installed on both the sentry and validator machines.

#### Installing Bor​ <a href="#installing-bor" id="installing-bor"></a>

Bor is the sidechain operator that acts as the block production layer, which syncs with Heimdall to select block producers and verifiers for each span and sprint.

Clone the [Bor repository](https://github.com/Ramestta-Blockchain/bor):thumbsup:

```
git clone https://github.com/Ramestta-Blockchain/bor
```

```
cd bor
```

**Install Bor:**

```
make bor-all
```

**Create symlinks:**

```
sudo ln -nfs ~/bor/build/bin/bor /usr/bin/bor
sudo ln -nfs ~/bor/build/bin/bootnode /usr/bin/bootnode
```

**Check the Bor installation:**

```
bor version
```

note

Before proceeding, Bor should be installed on both the sentry and validator machines.

### Setting Up Node Files: <a href="#setting-up-node-files" id="setting-up-node-files"></a>

Node files need to be set up on both the sentry and validator machines.

#### Fetching the launch repository​ <a href="#fetching-the-launch-repository" id="fetching-the-launch-repository"></a>

Clone the[ launch repository](https://github.com/Ramestta-Blockchain/launch):

```
git clone https://github.com/Ramestta-Blockchain/launch
```

#### Setting up the launch directory​ <a href="#setting-up-the-launch-directory" id="setting-up-the-launch-directory"></a>

**On the validator machine​**

Create a `node` directory:

```
mkdir -p node
```

Copy the files and scripts from the `launch` directory to the `node` directory:

```
cp -rf launch/mainnet-v1/sentry/sentry/* ~/node
cp launch/mainnet-v1/sentry-service.sh ~/node
```

#### Setting up the network directories: <a href="#setting-up-the-network-directories" id="setting-up-the-network-directories"></a>

**Setting up Heimdall​**

Change to the `node` directory:

```
cd ~/node/heimdall
```

Run the setup script:

```
bash setup.sh
```

**Setting up Bor​**

Change to the `node` directory:

```
cd ~/node/bor
```

Run the setup script:

```
bash setup.sh
```

### show enode: <a href="#setting-up-the-services" id="setting-up-the-services"></a>

```
bootnode -nodekey ~/.bor/data/bor/nodekey -writeaddress
```

Run the setup script:

```
bash setup.sh
```

### Setting Up the Services: <a href="#setting-up-the-services" id="setting-up-the-services"></a>

Run this section both on the sentry and validator machines.

Navigate to the `node` directory:

```
cd ~/node
```

Run the setup script:

```
bash sentry-service.sh
```

Copy the service file to the system directory:

```
sudo cp *.service /etc/systemd/system/
```

#### Starting the Heimdall service​ <a href="#starting-the-heimdall-service-1" id="starting-the-heimdall-service-1"></a>

You will now start the Heimdall service on the validator machine. Once the Heimdall service syncs, you will start the Bor service on the validator machine.

**Start the Heimdall service:**

```
sudo service heimdalld start
```

**Start the Heimdall rest-server:**

```
sudo service heimdalld-rest-server start
```

**Check the Heimdall service logs:**

```
journalctl -u heimdalld.service -f
```

**Check the Heimdall rest-server logs:**

```
journalctl -u heimdalld-rest-server.service -f
```

**Check the sync status of Heimdall:**

```
curl localhost:26657/status
```

In the output, the `catching_up` value is:

* `true` — the Heimdall service is syncing.
* `false` — the Heimdall service is synced.

Wait for the Heimdall service to fully sync.

#### Starting the Bor service​ <a href="#starting-the-bor-service-1" id="starting-the-bor-service-1"></a>

Once the Heimdall service on the validator machine syncs, start the Bor service on the validator machine.

**Start the Bor service:**

```
sudo service bor start
```

**Check the Bor service logs:**

```
journalctl -u bor.service -f
```

### Service to Auto Start After Server Crash/Reboot <a href="#health-checks-with-the-community" id="health-checks-with-the-community"></a>

```
sudo systemctl enable heimdalld
sudo systemctl enable heimdalld-rest-server
sudo systemctl enable bor
```


# Testnet

## Run a Sentry Node from Binaries

### Prerequisites: <a href="#prerequisites" id="prerequisites"></a>

`build-essential` installed on both the sentry and the validator machines.

To install:

```
sudo apt-get install build-essential
```

Go 1.18 installed on validator machine.

To install:

```
wget https://raw.githubusercontent.com/Ramestta-Blockchain/launch/master/go-install.sh
bash go-install.sh
sudo ln -nfs ~/.go/bin/go /usr/bin/go
```

Docker and RabbitMQ to install on validator machines.

```
sudo apt-get update
sudo apt install rabbitmq-server
```

To install sublime-text:

```
sudo snap install sublime-text --classic
```

#### Installing Heimdall: <a href="#installing-heimdall" id="installing-heimdall"></a>

Heimdall is the proof-of-stake verifier layer responsible for checkpointing the representation of the Plasma blocks to the Ramestta mainnet.

Clone the [Heimdall repository](https://github.com/Ramestta-Blockchain/heimdall):thumbsup:

```
git clone https://github.com/Ramestta-Blockchain/heimdall
```

```
cd heimdall
```

```
make build
make install
```

```
cd ~
source ~/.bashrc
```

Check the Heimdall installation:

```
heimdalld version --long
```

note

Before proceeding, Heimdall should be installed on both the sentry and validator machines.

#### Installing Bor​ <a href="#installing-bor" id="installing-bor"></a>

Bor is the sidechain operator that acts as the block production layer, which syncs with Heimdall to select block producers and verifiers for each span and sprint.

Clone the [Bor repository](https://github.com/Ramestta-Blockchain/bor):thumbsup:

```
git clone https://github.com/Ramestta-Blockchain/bor
```

```
cd bor
```

**Install Bor:**

```
make bor-all
```

**Create symlinks:**

```
sudo ln -nfs ~/bor/build/bin/bor /usr/bin/bor
sudo ln -nfs ~/bor/build/bin/bootnode /usr/bin/bootnode
```

**Check the Bor installation:**

```
bor version
```

note

Before proceeding, Bor should be installed on both the sentry and validator machines.

### Setting Up Node Files: <a href="#setting-up-node-files" id="setting-up-node-files"></a>

Node files need to be set up on both the sentry and validator machines.

#### Fetching the launch repository​ <a href="#fetching-the-launch-repository" id="fetching-the-launch-repository"></a>

Clone the[ launch repository](https://github.com/Ramestta-Blockchain/launch):

```
git clone https://github.com/Ramestta-Blockchain/launch
```

#### Setting up the launch directory​ <a href="#setting-up-the-launch-directory" id="setting-up-the-launch-directory"></a>

**On the validator machine​**

Create a `node` directory:

```
mkdir -p node
```

Copy the files and scripts from the `launch` directory to the `node` directory:

```
cp -rf launch/testnet-v1/sentry/sentry/* ~/node
cp launch/testnet-v1/sentry-service.sh ~/node
```

#### Setting up the network directories: <a href="#setting-up-the-network-directories" id="setting-up-the-network-directories"></a>

**Setting up Heimdall​**

Change to the `node` directory:

```
cd ~/node/heimdall
```

Run the setup script:

```
bash setup.sh
```

**Setting up Bor​**

Change to the `node` directory:

```
cd ~/node/bor
```

Run the setup script:

```
bash setup.sh
```

### show enode: <a href="#setting-up-the-services" id="setting-up-the-services"></a>

```
bootnode -nodekey ~/.bor/data/bor/nodekey -writeaddress
```

Run the setup script:

```
bash setup.sh
```

### Setting Up the Services: <a href="#setting-up-the-services" id="setting-up-the-services"></a>

Run this section both on the sentry and validator machines.

Navigate to the `node` directory:

```
cd ~/node
```

Run the setup script:

```
bash sentry-service.sh
```

Copy the service file to the system directory:

```
sudo cp *.service /etc/systemd/system/
```

#### Starting the Heimdall service​ <a href="#starting-the-heimdall-service-1" id="starting-the-heimdall-service-1"></a>

You will now start the Heimdall service on the validator machine. Once the Heimdall service syncs, you will start the Bor service on the validator machine.

**Start the Heimdall service:**

```
sudo service heimdalld start
```

**Start the Heimdall rest-server:**

```
sudo service heimdalld-rest-server start
```

**Check the Heimdall service logs:**

```
journalctl -u heimdalld.service -f
```

**Check the Heimdall rest-server logs:**

```
journalctl -u heimdalld-rest-server.service -f
```

**Check the sync status of Heimdall:**

```
curl localhost:26657/status
```

In the output, the `catching_up` value is:

* `true` — the Heimdall service is syncing.
* `false` — the Heimdall service is synced.

Wait for the Heimdall service to fully sync.

#### Starting the Bor service​ <a href="#starting-the-bor-service-1" id="starting-the-bor-service-1"></a>

Once the Heimdall service on the validator machine syncs, start the Bor service on the validator machine.

**Start the Bor service:**

```
sudo service bor start
```

**Check the Bor service logs:**

```
journalctl -u bor.service -f
```

### Service to Auto Start After Server Crash/Reboot <a href="#health-checks-with-the-community" id="health-checks-with-the-community"></a>

```
sudo systemctl enable heimdalld
sudo systemctl enable heimdalld-rest-server
sudo systemctl enable bor
```


# Validator Node


# Mainnet

## Run a Validator Node from Binaries:

### Prerequisites: <a href="#prerequisites" id="prerequisites"></a>

`build-essential` installed on both the sentry and the validator machines.

To install:

```
sudo apt-get install build-essential
```

Go 1.18 installed on validator machine.

To install:

```
wget https://raw.githubusercontent.com/Ramestta-Blockchain/launch/master/go-install.sh
bash go-install.sh
sudo ln -nfs ~/.go/bin/go /usr/bin/go
```

Docker and RabbitMQ to install on validator machines.

```
sudo apt-get update
sudo apt install rabbitmq-server
```

To install sublime-text:

```
sudo snap install sublime-text --classic
```

#### Installing Heimdall: <a href="#installing-heimdall" id="installing-heimdall"></a>

Heimdall is the proof-of-stake verifier layer responsible for checkpointing the representation of the Plasma blocks to the Ramestta mainnet.

Clone the [Heimdall repository](https://github.com/Ramestta-Blockchain/heimdall):thumbsup:

```
git clone https://github.com/Ramestta-Blockchain/heimdall
```

```
cd heimdall
```

```
make build
make install
```

```
cd ~
source ~/.bashrc
```

Check the Heimdall installation:

```
heimdalld version --long
```

note

Before proceeding, Heimdall should be installed on both the sentry and validator machines.

#### Installing Bor​ <a href="#installing-bor" id="installing-bor"></a>

Bor is the sidechain operator that acts as the block production layer, which syncs with Heimdall to select block producers and verifiers for each span and sprint.

Clone the [Bor repository](https://github.com/Ramestta-Blockchain/bor):thumbsup:

```
git clone https://github.com/Ramestta-Blockchain/bor
```

```
cd bor
```

**Install Bor:**

```
make bor-all
```

**Create symlinks:**

```
sudo ln -nfs ~/bor/build/bin/bor /usr/bin/bor
sudo ln -nfs ~/bor/build/bin/bootnode /usr/bin/bootnode
```

**Check the Bor installation:**

```
bor version
```

Change directory

```
cd ~
```

Before proceeding, Bor should be installed on both the sentry and validator machines.

### Setting Up Node Files: <a href="#setting-up-node-files" id="setting-up-node-files"></a>

Node files need to be set up on both the sentry and validator machines.

#### Fetching the launch repository​ <a href="#fetching-the-launch-repository" id="fetching-the-launch-repository"></a>

Clone the [launch repository](https://github.com/Ramestta-Blockchain/launch):thumbsup:

```
git clone https://github.com/Ramestta-Blockchain/launch
```

#### Setting up the launch directory​ <a href="#setting-up-the-launch-directory" id="setting-up-the-launch-directory"></a>

**On the validator machine​**

Create a `node` directory:

```
mkdir -p node
```

Copy the files and scripts from the `launch` directory to the `node` directory:

```
cp -rf launch/mainnet-v1/sentry/validator/* ~/node
cp launch/mainnet-v1/service.sh ~/node
```

#### Setting up the network directories: <a href="#setting-up-the-network-directories" id="setting-up-the-network-directories"></a>

Run this section both on the sentry and validator machines.

**Setting up Heimdall​**

Change to the `node` directory:

```
cd ~/node/heimdall
```

Run the setup script:

```
bash setup.sh
```

**Setting up Bor​**

Change to the `node` directory:

```
cd ~/node/bor
```

Run the setup script:

```
bash setup.sh
```

### Setting Up the Services: <a href="#setting-up-the-services" id="setting-up-the-services"></a>

Run this section both on the sentry and validator machines.

**Navigate to the `node` directory:**

```
cd ~/node
```

**Run the setup script:**

```
bash service.sh
```

**Copy the service file to the system directory:**

```
sudo cp *.service /etc/systemd/system/
```

### Configuring the Validator Node​ <a href="#configuring-the-validator-node" id="configuring-the-validator-node"></a>

### Set the owner and signer key <a href="#set-the-owner-and-signer-key" id="set-the-owner-and-signer-key"></a>

On Ramestta, you should keep the owner and signer keys different. Generate New wallet, and use its private key in next step as POLYGON`_PRIVATE_KEY`

* Signer — the address that signs the checkpoint transactions. The recommendation is to keep at least 1 MATIC on the signer address.
* Owner — the address that does the staking transactions. The recommendation is to keep the RAMA tokens on the owner address.

#### Generating a Heimdall private key​ <a href="#generating-a-heimdall-private-key" id="generating-a-heimdall-private-key"></a>

You must generate a Heimdall private key only on the validator machine. Do not generate a Heimdall private key on the sentry machine.

To generate the private key, run:

```
heimdallcli generate-validatorkey POLYGON_PRIVATE_KEY[0x prefix]
```

where

* POLYGON`_PRIVATE_KEY` — your Polygon wallet’s private key.

This will generate `priv_validator_key.json`. Move the generated JSON file to the Heimdall configuration directory:

```
mv ./priv_validator_key.json ~/.heimdalld/config
```

#### Generating a Bor keystore file​ <a href="#generating-a-bor-keystore-file" id="generating-a-bor-keystore-file"></a>

You must generate a Bor keystore file only on the validator machine. Do not generate a Bor keystore file on the sentry machine.

To generate the private key, run:

```
heimdallcli generate-keystore POLYGON_PRIVATE_KEY[0x prefix]
```

where

* POLYGON`_PRIVATE_KEY` — your Polygon wallet’s private key.

When prompted, set up a password to the keystore file.

This will generate a `UTC-<time>-<address>` keystore file.

Move the generated keystore file to the Bor configuration directory:

```
mv ./UTC-<time>-<address> ~/.bor/keystore/
```

#### Add password.txt​ <a href="#add-passwordtxt" id="add-passwordtxt"></a>

Make sure to create a `password.txt` file then add the Bor keystore file password right in the `~/.bor/password.txt` file.

`mv password.txt ~/.bor/password.txt`

```
mkdir /etc/rama
```

```
cd ~/node
```

#### Add your Polygon address​ <a href="#add-your-ethereum-address" id="add-your-ethereum-address"></a>

Open for editing.

```
sudo nano metadata
```

In `metadata`, add your Polygon address. Example: `VALIDATOR_ADDRESS=0xca67a8D767e45056DC92384b488E9Af654d78DE2`.

Save the changes in `metadata`.

mv metadata /etc/rama/

### Starting the Validator Node​ <a href="#starting-the-validator-node" id="starting-the-validator-node"></a>

At this point, you must have:

* The Heimdall service on the sentry machine syncs and is running.
* The Bor service on the sentry machine running.
* The Heimdall service and the Bor service on the validator machine configured.
* Your owner and signer keys configured.

#### Starting the Heimdall service​ <a href="#starting-the-heimdall-service-1" id="starting-the-heimdall-service-1"></a>

You will now start the Heimdall service on the validator machine. Once the Heimdall service syncs, you will start the Bor service on the validator machine.

**Start the Heimdall service:**

```
sudo service heimdalld start
```

**Start the Heimdall rest-server:**

```
sudo service heimdalld-rest-server start
```

**Start the Heimdall bridge:**

```
sudo service heimdalld-bridge start
```

**Check the Heimdall service logs:**

```
journalctl -u heimdalld.service -f
```

**Check the Heimdall rest-server logs:**

```
journalctl -u heimdalld-rest-server.service -f
```

**Check the Heimdall bridge logs:**

```
journalctl -u heimdalld-bridge.service -f
```

**Check the sync status of Heimdall:**

```
curl localhost:26657/status
```

In the output, the `catching_up` value is:

* `true` — the Heimdall service is syncing.
* `false` — the Heimdall service is synced.

Wait for the Heimdall service to fully sync.

#### Starting the Bor service​ <a href="#starting-the-bor-service-1" id="starting-the-bor-service-1"></a>

Once the Heimdall service on the validator machine syncs, start the Bor service on the validator machine.

**Start the Bor service:**

```
sudo service bor start
```

**Check the Bor service logs:**

```
journalctl -u bor.service -f
```

### Service to Auto Start After Server Crash/Reboot <a href="#health-checks-with-the-community" id="health-checks-with-the-community"></a>

```
sudo systemctl enable heimdalld
sudo systemctl enable heimdalld-rest-server
sudo systemctl enable heimdalld-bridge
sudo systemctl enable bor
```

### Next Steps: Staking​ <a href="#next-steps-staking" id="next-steps-staking"></a>

Now that you have your sentry and validator nodes are health-checked, proceed to the Staking guide to start backing the network.


# Testnet

## Run a Validator Node from Binaries:

### Prerequisites: <a href="#prerequisites" id="prerequisites"></a>

`build-essential` installed on both the sentry and the validator machines.

To install:

```
sudo apt-get install build-essential
```

Go 1.18 installed on validator machine.

To install:

```
wget https://raw.githubusercontent.com/Ramestta-Blockchain/launch/master/go-install.sh
bash go-install.sh
sudo ln -nfs ~/.go/bin/go /usr/bin/go
```

Docker and RabbitMQ to install on validator machines.

```
sudo apt-get update
sudo apt install rabbitmq-server
```

To install sublime-text:

```
sudo snap install sublime-text --classic
```

#### Installing Heimdall: <a href="#installing-heimdall" id="installing-heimdall"></a>

Heimdall is the proof-of-stake verifier layer responsible for checkpointing the representation of the Plasma blocks to the Ramestta mainnet.

Clone the [Heimdall repository](https://github.com/Ramestta-Blockchain/heimdall):thumbsup:

```
git clone https://github.com/Ramestta-Blockchain/heimdall
```

```
cd heimdall
```

```
make build
make install
```

```
cd ~
source ~/.bashrc
```

Check the Heimdall installation:

```
heimdalld version --long
```

note

Before proceeding, Heimdall should be installed on both the sentry and validator machines.

#### Installing Bor​ <a href="#installing-bor" id="installing-bor"></a>

Bor is the sidechain operator that acts as the block production layer, which syncs with Heimdall to select block producers and verifiers for each span and sprint.

Clone the [Bor repository](https://github.com/Ramestta-Blockchain/bor):thumbsup:

```
git clone https://github.com/Ramestta-Blockchain/bor
```

```
cd bor
```

**Install Bor:**

```
make bor-all
```

**Create symlinks:**

```
sudo ln -nfs ~/bor/build/bin/bor /usr/bin/bor
sudo ln -nfs ~/bor/build/bin/bootnode /usr/bin/bootnode
```

**Check the Bor installation:**

```
bor version
```

Change directory

```
cd ~
```

Before proceeding, Bor should be installed on both the sentry and validator machines.

### Setting Up Node Files: <a href="#setting-up-node-files" id="setting-up-node-files"></a>

Node files need to be set up on both the sentry and validator machines.

#### Fetching the launch repository​ <a href="#fetching-the-launch-repository" id="fetching-the-launch-repository"></a>

Clone the [launch repository](https://github.com/Ramestta-Blockchain/launch):thumbsup:

```
git clone https://github.com/Ramestta-Blockchain/launch
```

#### Setting up the launch directory​ <a href="#setting-up-the-launch-directory" id="setting-up-the-launch-directory"></a>

**On the validator machine​**

Create a `node` directory:

```
mkdir -p node
```

Copy the files and scripts from the `launch` directory to the `node` directory:

```
cp -rf launch/testnet-v1/sentry/validator/* ~/node
cp launch/testnet-v1/service.sh ~/node
```

#### Setting up the network directories: <a href="#setting-up-the-network-directories" id="setting-up-the-network-directories"></a>

Run this section both on the sentry and validator machines.

**Setting up Heimdall​**

Change to the `node` directory:

```
cd ~/node/heimdall
```

Run the setup script:

```
bash setup.sh
```

**Setting up Bor​**

Change to the `node` directory:

```
cd ~/node/bor
```

Run the setup script:

```
bash setup.sh
```

### Setting Up the Services: <a href="#setting-up-the-services" id="setting-up-the-services"></a>

Run this section both on the sentry and validator machines.

**Navigate to the `node` directory:**

```
cd ~/node
```

**Run the setup script:**

```
bash service.sh
```

**Copy the service file to the system directory:**

```
sudo cp *.service /etc/systemd/system/
```

### Configuring the Validator Node​ <a href="#configuring-the-validator-node" id="configuring-the-validator-node"></a>

### Set the owner and signer key <a href="#set-the-owner-and-signer-key" id="set-the-owner-and-signer-key"></a>

On Ramestta, you should keep the owner and signer keys different. Generate New wallet, and use its private key in next step as POLYGON`_PRIVATE_KEY`

* Signer — the address that signs the checkpoint transactions. The recommendation is to keep at least 1 MATIC on the signer address.
* Owner — the address that does the staking transactions. The recommendation is to keep the RAMA tokens on the owner address.

#### Generating a Heimdall private key​ <a href="#generating-a-heimdall-private-key" id="generating-a-heimdall-private-key"></a>

You must generate a Heimdall private key only on the validator machine. Do not generate a Heimdall private key on the sentry machine.

To generate the private key, run:

```
heimdallcli generate-validatorkey POLYGON_PRIVATE_KEY[0x prefix]
```

where

* POLYGON`_PRIVATE_KEY` — your Polygon wallet’s private key.

This will generate `priv_validator_key.json`. Move the generated JSON file to the Heimdall configuration directory:

```
mv ./priv_validator_key.json ~/.heimdalld/config
```

#### Generating a Bor keystore file​ <a href="#generating-a-bor-keystore-file" id="generating-a-bor-keystore-file"></a>

You must generate a Bor keystore file only on the validator machine. Do not generate a Bor keystore file on the sentry machine.

To generate the private key, run:

```
heimdallcli generate-keystore POLYGON_PRIVATE_KEY[0x prefix]
```

where

* POLYGON`_PRIVATE_KEY` — your Polygon wallet’s private key.

When prompted, set up a password to the keystore file.

This will generate a `UTC-<time>-<address>` keystore file.

Move the generated keystore file to the Bor configuration directory:

```
mv ./UTC-<time>-<address> ~/.bor/keystore/
```

#### Add password.txt​ <a href="#add-passwordtxt" id="add-passwordtxt"></a>

Make sure to create a `password.txt` file then add the Bor keystore file password right in the `~/.bor/password.txt` file.

`mv password.txt ~/.bor/password.txt`

```
mkdir /etc/rama
```

```
cd ~/node
```

#### Add your Polygon address​ <a href="#add-your-ethereum-address" id="add-your-ethereum-address"></a>

Open for editing.

```
sudo nano metadata
```

In `metadata`, add your Polygon address. Example: `VALIDATOR_ADDRESS=0xca67a8D767e45056DC92384b488E9Af654d78DE2`.

Save the changes in `metadata`.

mv metadata /etc/rama/

### Starting the Validator Node​ <a href="#starting-the-validator-node" id="starting-the-validator-node"></a>

At this point, you must have:

* The Heimdall service on the sentry machine syncs and is running.
* The Bor service on the sentry machine running.
* The Heimdall service and the Bor service on the validator machine configured.
* Your owner and signer keys configured.

#### Starting the Heimdall service​ <a href="#starting-the-heimdall-service-1" id="starting-the-heimdall-service-1"></a>

You will now start the Heimdall service on the validator machine. Once the Heimdall service syncs, you will start the Bor service on the validator machine.

**Start the Heimdall service:**

```
sudo service heimdalld start
```

**Start the Heimdall rest-server:**

```
sudo service heimdalld-rest-server start
```

**Start the Heimdall bridge:**

```
sudo service heimdalld-bridge start
```

**Check the Heimdall service logs:**

```
journalctl -u heimdalld.service -f
```

**Check the Heimdall rest-server logs:**

```
journalctl -u heimdalld-rest-server.service -f
```

**Check the Heimdall bridge logs:**

```
journalctl -u heimdalld-bridge.service -f
```

**Check the sync status of Heimdall:**

```
curl localhost:26657/status
```

In the output, the `catching_up` value is:

* `true` — the Heimdall service is syncing.
* `false` — the Heimdall service is synced.

Wait for the Heimdall service to fully sync.

#### Starting the Bor service​ <a href="#starting-the-bor-service-1" id="starting-the-bor-service-1"></a>

Once the Heimdall service on the validator machine syncs, start the Bor service on the validator machine.

**Start the Bor service:**

```
sudo service bor start
```

**Check the Bor service logs:**

```
journalctl -u bor.service -f
```

### Service to Auto Start After Server Crash/Reboot <a href="#health-checks-with-the-community" id="health-checks-with-the-community"></a>

```
sudo systemctl enable heimdalld
sudo systemctl enable heimdalld-rest-server
sudo systemctl enable heimdalld-bridge
sudo systemctl enable bor
```

### Next Steps: Staking​ <a href="#next-steps-staking" id="next-steps-staking"></a>

Now that you have your sentry and validator nodes are health-checked, proceed to the Staking guide to start backing the network.


# Heimdall and Bor Snapshots

### Heimdall Snapshot[​](https://wiki.polygon.technology/docs/develop/network-details/snapshot-instructions-heimdall-bor#heimdall-snapshot) <a href="#heimdall-snapshot-.1" id="heimdall-snapshot-.1"></a>

Before starting the Heimdall services to sync, it is essential to set up the node with the necessary prerequisites as per the node setup guide. Once you have completed this step, follow the instructions below to use the snapshot:

1. To download the snapshot tar file of Heimdall on your VM, execute the following command.\
   *Note: Paste the latest link you will find on the Snapshot link into the URL code.*

```
aria2c -x6 -s6  <snapshot_url>
// For example, this will download the snapshot of Heimdall:
aria2c -x6 -s6 https://URL/heimdall-snapshot-2022-11-08.tar.gz
```

2. To unpack the tar file in the Heimdall data directory, run the following command.

```
// You must ensure you are running this command before you start the Heimdall service on your node.
// If your Heimdall service has started, please stop the service and run the following command:
// Once unpacking is complete, you can start the Heimdall service again:
tar -xzvf <snapshot file> -C <HEIMDALL_DATA_DIRECTORY>
// If your Heimdall data directory is different,
// please replace the directory name in the command for starting the Heimdall service.
// When this command completes, you may delete the tar file to reclaim space.
// For example, this will unpack the tar file in the Heimdall Data directory:
tar -xzvf heimdall-snapshot-2021-11-08.tar.gz -C ~/.heimdalld/data/
```

### Bor Snapshot[​](https://wiki.polygon.technology/docs/develop/network-details/snapshot-instructions-heimdall-bor#bor-snapshot) <a href="#bor-snapshot-.1" id="bor-snapshot-.1"></a>

To use the Bor snapshot to sync your node, follow the steps below after setting up your node with the prerequisites mentioned in the node setup guide:

1. To download the Bor snapshot tar file on your VM, execute the following command.\
   *Note: Paste the latest link you will find on the Snapshot link into the URL code.*

```
aria2c -x6 -s6  <snapshot_url>
// For example, this will download the snapshot of Heimdall:
aria2c -x6 -s6 https://URL/bor-fullnode-snapshot-2022-11-08.tar.gz
```

This command will initiate the download process of the Bor snapshot tar file from the provided link. Once the download is complete, the file will be saved in the current directory. You can then proceed with the steps required to use the snapshot and sync Bor, as per the instructions provided.

2. To unpack the Bor snapshot tar file in the Bor data directory, run the following command.

```
// You must ensure you are running this command before you start the Bor service on your node.
// If your Bor service has started, please stop the service and run the following command:
// Once unpacking is complete, you can start the Bor service again.
tar -xzvf <snapshot file> -C <BOR_DATA_DIRECTORY>
// If your bor data directory is different
// please replace the directory name in the command for starting the Bor service.
// When this command completes, you may delete the tar file to reclaim space.
// For example, this will unpack the tar file in the Bor data directory:
tar -xzvf bor-fullnode-snapshot-2022-11-08.tar.gz -C ~/.bor/data/bor/chaindata
```

This command will extract the contents of the Bor snapshot tar file and place them in the specified Bor data directory. Once the extraction is complete, you can proceed with starting the Bor services to begin syncing the node with the blockchain data from the snapshot.

NOTE: The aria2c method is an efficient way to download snapshots quickly, but there is also an alternate method that allows the downloaded snapshots to be extracted directly without any intervention.

This method involves using the "wget" command to download the snapshot file, followed by using the "tar" command to extract the contents of the snapshot directly into the data directory. The command to do this is:

For Heimdall:

```
wget -c https://URL/heimdall-snapshot-2022-11-30.tar.gz -O - | tar -xzf - -C ~/.heimdalld/data/
```

For Bor:

```
wget -c https://URL/bor-fullnode -O - | tar -xzf - -C ~/.bor/data/bor/chaindata
```


# Security models

Ramestta provides three types of security models for developers to build their DApps upon:

1. Proof of Stake security
2. Plasma security
3. Hybrid (Plasma + PoS)

What follows is a description of each of these security models offered by Ramestta Network, and what would be the developer workflow for each with an example DApp.

#### Proof of Stake security[​](https://wiki.polygon.technology/docs/home/architecture/security-models/#proof-of-stake-security) <a href="#proof-of-stake-security" id="proof-of-stake-security"></a>

A Proof of Stake layer for Tendermint is built on top of Heimdall & Bor. When two-thirds of the validators sign a checkpoint, it becomes part of the root chain.

We enable PoS on our platform by using Polygon staking management contracts and incentivized validators running Heimdall and Bor nodes. These implement the following features:

* The ability for anyone to stake RAMA tokens on the Polygon smart contract and join the system as a Validator
* Earn staking rewards for validating state transitions on Ramestta

The PoS mechanism also acts as a mitigation to the data unavailability problem for our sidechains in terms of Plasma.

The sidechain state is periodically finalized via checkpoints via our fast finality layer. Our fast finality helps us cement sidechain state. A chain compatible with EVM has fewer validators and a faster block time with high throughput. There is an emphasis on scalability over high levels of decentralization. Heimdall ensures that the final state commit is bulletproof and passes via a large validator set and hence high decentralization.

**For developers**

DApp developers can create a PoS security DApp simply by deploying their smart contract on Ramestta Chain. Because the account-based architecture enables an EVM-compatible sidechain, this is possible.

#### Plasma Security[​](https://wiki.polygon.technology/docs/home/architecture/security-models/#plasma-security) <a href="#plasma-security" id="plasma-security"></a>

Ramestta Chain provides Plasma Guarantees for different atack scenarios.

* Chain operator (or in Ramestta, the Heimdall layer) is corrupt.
* The user is corrupt.

Ramestta Chain offers a solution for users whose plasma chain assets have been compromised, as they can initiate a mass exit using rootchain smart contracts. The use of plasma contracts provides added security to Shibarium, as they rely on Polygon's smart contracts and consensus mechanism. This means that the plasma chain can use simpler consensus mechanisms while still maintaining a high level of security comparable to the main chain. However, the overall security of Ramestta is still ultimately dependent on the security of Polygon and indirectly with Ethereum .

**For developers**

If you want to build DApps on Ramestta Chain with Plasma security guarantee, you must write custom predicates for your smart contracts. Basically, this means writing the external contracts that handle the dispute conditions determined by Ramestta plasma.

#### Hybrid[​](https://wiki.polygon.technology/docs/home/architecture/security-models/#hybrid) <a href="#hybrid" id="hybrid"></a>

The DApps on Ramestta Network can utilize either pure Plasma security or pure Proof of Stake security, or a hybrid approach that combines both. Developers can choose to implement a hybrid approach to provide both plasma and proof of stake guarantees in specific workflows. For instance, a gaming DApp that utilizes its own erc20 token to reward players can deploy game logic smart contracts directly on the Ramestta sidechain, ensuring Proof of Stake security. At the same time, Erc20 token transfers can be secured with Plasma guarantees and fraud proofs that are embedded in Ramestta's rootchain contracts.


# Staking - Validators and Delegators

### **What is validator stake?**

Stakers are **rewarded for helping to validate the ledger**. They do this by delegating their stake to validator nodes. Those validators do the legwork of replaying the ledger and send votes to a per-node vote account to which stakers can delegate their stakes.

### **How does a validator work?**

A 'Validator' on a Blockchain is **like a banker who verifies every incoming transaction**. A transaction will only be completed on the blockchain when it has been verified by the validator. Validators are assigned the duty to verify transactions to whether or not they are legal and accurate.

### **Is staking profitable?**

The primary benefit of staking is that you earn more crypto, and interest rates can be very generous. In some cases, you can earn more than 10% or 20% per year. **It's potentially a very profitable way to invest your money**. And, the only thing you need is crypto that uses the PoS model.

To become a validator, you need to **stake RAMA tokens with staking management contracts residing on the Polygon mainnet**. Rewards are distributed to all stakers proportional to their stake at every checkpoint with an exception being the proposer getting an additional bonus.

&#x20;\
Validators are the key actor in maintaining the Ramestta network. Validators run a full node and secure the network by staking RAMA to produce blocks, validate and participate in PoS consensus.

Validator performance is critical for the stability and security of Ramestta. In order to ensure the network is in secure hands, in the early stages validator selection will be a manual process requiring an application and interview for consideration.\
&#x20;

To begin staking Ramestta (RAMA), you will need to have RAMA and MATIC on the Polygon Mainnet in your MetaMask wallet. &#x20;

### **Why do validators need staking?**

**In order to participate in securing the network and to be rewarded for this doing this,** validators are required to put up collateral “stake” which can be forfeited (i.e. “slashed”) programmatically if their actions break the programmatic rules that define the blockchain protocol which they secur.e

### **What are commissions for validators?**

In exchange for their role and service, validators receive rewards proportional to their stake. The rewards are divided among all participants based on the amount of tokens they have staked. The user's reward balance is recorded in a contract, which is used to determine the rewards that can be claimed.

To become a delegator users need to stake a certain amount and approve the request after that they will be added to the delegator list.

### What about delegators?

Delegators are individual users or an entity that participate in a consensus mechanism by delegating their voting rights to a validator. Delegators can choose to vote for a validator of their choice and delegate their voting power to that validator. The validator, in turn, uses the combined voting power of all delegators to help secure the network and validate transactions. This allows for a more efficient and scalable consensus mechanism compared toPoW.\
\
Delegators are people who own **RAMA** and choose to support the network by staking their tokens into **validator nodes** instead of running one themselves. They play an important role in the system by selecting which validator nodes will be responsible for validating transactions. Delegators choose to lend their tokens to validator nodes, and as a result, they are entitled to a portion of the rewards earned by those validators. \
\
On the other hand, this also implies that they are exposed to the same risks as validators. For example, if a validator fails to comply with the protocol, the delegators may lose a part of their tokens in relation to the amount they had delegated to that validator.


# Validate

A validator is a node on a blockchain network that participates in the process of validating transactions and blocks to maintain the integrity and security of the network.&#x20;

Validators play a crucial role in ensuring that Ramestta is decentralized and trustless, meaning that no single entity has control over the network and all transactions are verified by multiple independent parties.

Proof-of-stake (PoS) systems use validators to stake their own cryptocurrency (RAMA in Ramestta's case) as collateral to verify transactions and create new blocks.

Validators are responsible for ensuring that transactions are valid, that double-spending is prevented, and that blocks are added to the blockchain in a secure and efficient manner. They do this by running a full node on the network, which involves storing a complete copy of the blockchain and actively participating in the consensus mechanism to validate transactions and create new blocks.\
They are also responsible for maintaining the security and integrity of the network by monitoring and reporting any suspicious activity, and work together to prevent attacks and maintain the decentralized nature of the blockchain.\
\
In PoS systems, validators are chosen based on the amount of cryptocurrency they have staked as collateral. The more cryptocurrency a validator stakes, the more likely they are to be chosen to validate transactions and create new blocks. Validators are incentivized to act honestly and accurately because they risk losing their staked cryptocurrency if they behave maliciously.

On Ramestta's case, during the Testnet/Mainnet anyone can become a validator by applying through the intake form on the website. Validators will be selected manually by a trusted team to ensure the security of the network.\
The onboarding of these Validators will be done taking into account the experience, trust, knowledge and ensuring that these validators are committed to the health and integrity of Ramestta.

There's a total of 100 slots for validators. This means that new validators can only access when an active Validator leaves or loses his slot in the network.


# Validator Responsibilities

Validators on the Ramestta Network must:

* Ensure the network is available to users at all times.\
  \
  Ramestta nodes are measured by the number of checkpoint transactions they have signed.

  Polygon's testnet receives a checkpoint transaction approximately every 10-30 minutes. In the Ramestta network, all validators must sign the checkpoint transaction.

  In the absence of a signed checkpoint transaction, your validator node's performance will decrease.<br>
* Monitorize processes daily to find and address any issues that may arise from its activity.\
  \
  Regular checks of the services and processes associated with Heimdall and Bor are essential to ensure their smooth functioning. Nodes should perform these checks daily to identify and address any issues that may arise.

  Additionally, pruning of nodes should be carried out regularly to minimize disk usage. This involves removing unnecessary data from the blockchain to reduce the size of the blockchain data stored on the node's disk. This helps optimize the performance and efficiency of the node, ensuring it can operate at peak performance.<br>
* Ensure network is running correctly and efficiently.<br>
* Have between 5-10 MATIC on the signer address to sign and propose checkpoints.\
  \
  Minimum MATIC is needed to sign and propose checkpoint transactions on the Polygon mainnet. Not having a minimum amount of MATIC may result in delays in the transactions and checkpoint submission.<br>
* Be transparent with commission rates.<br>
* Report any issues and provide feedback or suggestions to us.


# Maintaining your validator node

[​](https://wiki.polygon.technology/docs/maintain/glossary#signer-address)Signer addresses are the addresses of Polygon accounts of Heimdall validator nodes. It is the signer address that signs and submits the checkpoint transactions.

In contrast to the signer key, which is kept on the node, the owner key must be kept in a secure place and used infrequently.

### Change the signer address[​](https://wiki.polygon.technology/docs/maintain/validate/change-signer-address#change-the-signer-address) <a href="#change-the-signer-address" id="change-the-signer-address"></a>

This guide refers to your current validator node as Node 1 and your new validator node as Node 2.

1. Log in to the staking dashboard with the Node 1 address.
2. On your profile, click **Edit Profile**.
3. In the *Signer's address* field, provide the Node 2 address.
4. In the *Signer's public key* field, provide the Node 2 public key.

   To get the public key, run the following command on the validator node:

   `heimdalld show-account`

The new details for your node will be saved when you click Save. Thus, Node 1 is your address that controls the stake, where rewards are sent, etc. As a result, Node 2 will be responsible for signing blocks, signing checkpoints, etc.

### Set up your commission rate as a validator <a href="#set-up-your-commission-rate-as-a-validator" id="set-up-your-commission-rate-as-a-validator"></a>

Validators can set up their commissions and change them at any time.

Validators may charge any commission rate they choose. Commissions would start at 0% and go up to 100% of the rewards earned, and they can be changed as often as validator likes.

### Change your commission rate[​](https://wiki.polygon.technology/docs/maintain/validate/validator-commission-operations#change-your-commission-rate) <a href="#change-your-commission-rate" id="change-your-commission-rate"></a>

You can change your commission rate.

1. With your owner address, login to the staking dashboard.
2. On your profile, click **Edit Profile**.
3. In the *Commission* field, provide your new commission rate.

Once you have confirmed and signed the transaction your commission rate will be set.

Once the commission is updated, there is a cool down period of 80 checkpoints.


# How to Become a Validator(Testnet)

In order to become a Ramestta Network validator (on the Testnet), you must stake a [**minimum of 10K** ](#user-content-fn-1)[^1]**RAMA**. Remember you will need test RAMA and MATIC on the Polygon Mumbai network.&#x20;

You can claim test MATIC at <https://mumbaifaucet.com/>\
You can claim test RAMA at [https://testnet.ramascan.com/](https://ramascan.com/tokens)[faucet](https://beta.shibariumtech.com/faucet)

**During Testnet**, anyone can become a validator (there's up to 10 slots). \
While this is a test environment, validators who don't behave correctly can be turned off to allow others to join the board.\
\
Also remember that during Testnet, validators will be receiving test Bone (they have no real monetary value).

1. Users can stake test RAMA using the Validator Dashboard.
2. Users are able to login using MetaMask or any wallet that has Wallet Connect enabled. In order to log in, users must use the same address where their tokens are stored.

Once you login , you will see the landing page and an option to become a Validator.

<figure><img src="broken://files/Cb80Rsl1XpKwX8FkwH7Y" alt=""><figcaption></figcaption></figure>

3. You can initiate the process by clicking Become a validator. Initially, you will be asked to configure the node.

<figure><img src="broken://files/DtO0ahDe9TrwrSNUZgrb" alt=""><figcaption></figcaption></figure>

4. Select Ansible or Binaries for setting the node.
5. Next button will be enabled.

<figure><img src="broken://files/zo0DD5nRShVXoHVkMv0j" alt=""><figcaption></figcaption></figure>

6. Clicking on Next will send you to next step, where you can add Validator details and the staking amount.
7. Confirm the checkbox and click on continue.

<figure><img src="broken://files/0mcvB8xAo7ctepRayep0" alt=""><figcaption></figcaption></figure>

8. The next section will appear after you click continue, where all the details are required.

<figure><img src="broken://files/aVukqDpI2YjcpMdPXzAG" alt=""><figcaption></figcaption></figure>

9. Upon clicking on next, you will be directed to the required staked amount section, where you can also enter the maximum amount by clicking the max button, the minimum staked amount is 10k.

<figure><img src="broken://files/I1A8uhAmBYlXtN6V7I5X" alt=""><figcaption></figcaption></figure>

10. Next you need to approve the permission from MetaMask.

<figure><img src="broken://files/IOH0HepPmHzDXiatynmJ" alt=""><figcaption></figcaption></figure>

<figure><img src="broken://files/rybvCv56myuOF7p1WBH1" alt=""><figcaption></figcaption></figure>

11. After confirming the transaction the data will get saved in db.

<figure><img src="broken://files/jsaJelxDf0hWpMjLZHum" alt=""><figcaption></figcaption></figure>

13. Confirm the transaction.

<figure><img src="broken://files/VBjw6QWR8aEAzmLnfivg" alt=""><figcaption></figcaption></figure>

14. As soon as the transaction is confirmed, the setup of the node will be completed.

<figure><img src="broken://files/VBjw6QWR8aEAzmLnfivg" alt=""><figcaption></figcaption></figure>

[^1]:


# Delegate

The only prerequisite is to have your test RAMA and MATIC tokens on the **Polygon Mumbai network**.

You can claim test MATIC at <https://mumbaifaucet.com/>\
You can claim test RAMA at [https://testnet.ramascan.com/](https://ramascan.com/tokens)[faucet](https://beta.shibariumtech.com/faucet)

### Access the dashboard[​](https://wiki.polygon.technology/docs/maintain/delegate/delegate/#access-the-dashboard) <a href="#access-the-dashboard" id="access-the-dashboard"></a>

1. In your wallet (e.g. MetaMask), choose the Polygon mainnet.
2. Log in into the Ramestta Web Wallet.

<figure><img src="broken://files/nqEZIM514uT41pkCbt7O" alt=""><figcaption><p>Connected with Wallet</p></figcaption></figure>

3. Once you log in, you will get the list of validators.

<figure><img src="broken://files/xZkbNsJ3W39LWPRI3apn" alt=""><figcaption><p>Validator's List</p></figcaption></figure>

### Delegate to a validator[​](https://wiki.polygon.technology/docs/maintain/delegate/delegate/#delegate-to-a-validator) <a href="#delegate-to-a-validator" id="delegate-to-a-validator"></a>

1. Click **Become a Delegator** or scroll down to a specific validator and click **Delegate**.
2. Provide the amount of RAMA tokens to delegate.<br>

   <figure><img src="broken://files/9l7Ol79fSYLeWMBuWAwi" alt=""><figcaption><p>Max or required bones will be added here</p></figcaption></figure>
3. Approve the delegation transaction and click **Delegate**.

<figure><img src="broken://files/6l9DGAxRDD5RJJKkHGwG" alt=""><figcaption><p>Delegate</p></figcaption></figure>

4. After the delegation transaction completes, you will see the *Delegation Submitted* message.

<figure><img src="broken://files/11IiJL9bbucRARr5JUIU" alt=""><figcaption><p>Delegation Completed</p></figcaption></figure>

&#x20;

### View your delegations[​](https://wiki.polygon.technology/docs/maintain/delegate/delegate/#view-your-delegations)

To view your delegations, click My Account.

### Withdraw rewards[​](https://wiki.polygon.technology/docs/maintain/delegate/delegate/#withdraw-rewards)

1. Click My Account.

<figure><img src="broken://files/vk8yezS5O1fv1oio3uiN" alt=""><figcaption><p>My Account</p></figcaption></figure>

&#x20;

2. Under your delegated validator, click **Withdraw Rewards**.

<figure><img src="broken://files/ldstv1ix8qzkkOEWpj4c" alt=""><figcaption><p>Withdraw Rewards</p></figcaption></figure>

&#x20;

This will withdraw the RAMA token rewards to your Polygon address.

### Restake rewards[​](https://wiki.polygon.technology/docs/maintain/delegate/delegate/#restake-rewards)

1. Click My Account
2. Under your delegated validator, click **Restake Rewards**.

This will restake the RAMA token rewards to the validator and increase your delegation stake.

### Unbound from a validator[​](https://wiki.polygon.technology/docs/maintain/delegate/delegate/#unbond-from-a-validator)

1. Click My Account
2. Under your delegated validator, click **Unbound**.

<figure><img src="broken://files/oUInEo7YOC6XerohXShH" alt=""><figcaption><p>Unbound</p></figcaption></figure>

&#x20;

This will withdraw your rewards and your entire stake from the validator.

A fund locking of approx 82 checkpoints for the unbounding period is in place to ensure there is no malicious behavior on the network.

### Move stake from one node to another node[​](https://wiki.polygon.technology/docs/maintain/delegate/delegate/#move-stake-from-one-node-to-another-node) <a href="#move-stake-from-one-node-to-another-node" id="move-stake-from-one-node-to-another-node"></a>

Moving stake from one node to another node is a single transaction. There are no delays or unbonding periods during this event.

1. Click My Account on the Staking dashboard.
2. Click **Move Stake** under your delegated validator.
3. Select an external validator and click **Stake here**.

<figure><img src="broken://files/nW3jW7d8p80vmH05Kx3u" alt=""><figcaption><p>Migrate Stake</p></figcaption></figure>

4. Provide the stake amount and click **Move Stake**.

<figure><img src="broken://files/Cnrhgwxj9CJJDEhrZEgh" alt=""><figcaption><p>Stake will be moved </p></figcaption></figure>

This will move the stake. The dashboard will update after 12 block confirmations.


# FAQ's

### What is the minimum stake amount?​

**1 RAMA** is the minimum stake amount.\
*(These are test numbers subject to change anytime)*

### Why does my transaction take so long?​

All staking transactions of Ramestta happen on Polygon for security reasons.

The time it takes to complete a transaction depends on the gas fees you have allowed, as well as the amount of congestion on Polygon at the time. When you use the "Speed Up" option, you can increase the gas fee to expedite the transaction.

### Which wallets are currently supported?​ <a href="#delegator-faq-whichwalletsarecurrentlysupported" id="delegator-faq-whichwalletsarecurrentlysupported"></a>

Just MetaMask at the time being.

### Are hardware wallets supported?​ <a href="#delegator-faq-arehardwarewalletssupported" id="delegator-faq-arehardwarewalletssupported"></a>

No, hardware wallets are not supported as of now.

### I have completed my delegation, where can I check the details?​

You can check the details by clicking on **My Account.**

<figure><img src="broken://files/EGYaqLDLuuHykkXlHlNs" alt=""><figcaption></figcaption></figure>

### Where can I check my rewards?

You can check the details by clicking on **My Account.**

<figure><img src="broken://files/mid3RrPDN4ns8bspwG7a" alt=""><figcaption></figcaption></figure>

### Do I need MATIC to pay for Gas fees?​

Yes, gas fees must be paid in MATIC, the Polygon network's native cryptocurrency.

### Do I need to deposit RAMA tokens to the Ramestta Testnet network for staking?​ <a href="#delegator-faq-doineedtodepositbonetokenstotheshibariumtestnetnetworkforstaking" id="delegator-faq-doineedtodepositbonetokenstotheshibariumtestnetnetworkforstaking"></a>

No. All your funds need to be on the Polygon Network.

### When I try to do the transaction my Confirm button is disabled.​ <a href="#delegator-faq-whenitrytodothetransactionmyconfirmbuttonisdisabled-whyso" id="delegator-faq-whenitrytodothetransactionmyconfirmbuttonisdisabled-whyso"></a>

This might be because you have an insufficient amount of the native token necessary to pay for the transaction.

### When does reward get distributed?​ <a href="#delegator-faq-whendoesrewardgetdistributed" id="delegator-faq-whendoesrewardgetdistributed"></a>

Rewards are paid out after every checkpoint is submitted.

### Why does reward keep getting decreased every checkpoint?​ <a href="#delegator-faq-whydoesrewardkeepgettingdecreasedeverycheckpoint" id="delegator-faq-whydoesrewardkeepgettingdecreasedeverycheckpoint"></a>

Rewards earned will depend on the amount of locked supply in the network at each checkpoint. It is expected that this will vary significantly as the number of RAMA tokens locked in staking contracts increases. The rewards will start out higher, and then decrease as the locked supply percentage rises. The checkpoints capture this change in locked supply, which is then used to calculate rewards.

### How can I claim my rewards?​ <a href="#delegator-faq-howcaniclaimmyrewards" id="delegator-faq-howcaniclaimmyrewards"></a>

Once the **unbonding period is complete**, the Claim Stake button will be enabled and you can then claim your staked tokens. The tokens will be transferred to your account.

1. Go to [https://validator.ramestta.com](https://beta.shibariumtech.com/unbond-history) (coming Soon)
2. Now check the claim stake enabled button.
3. Click on **Claim Now**.

<figure><img src="broken://files/uOgdHMEvASUbLYKz8SEZ" alt=""><figcaption></figcaption></figure>

4. You will get this pop up.

<figure><img src="broken://files/QpXOZRWCuEuNEXWfHZMt" alt=""><figcaption></figcaption></figure>

5. Now click on confirm, you will get a MetaMask confirmation or rejection option.

<figure><img src="broken://files/mjPkWKzxbRJCB8nXVIFh" alt=""><figcaption></figcaption></figure>

### What is the Unbounding period?​

The unbounding period on Ramestta is approximately 8-9 days. This period applies to the originally delegated amount and re-delegated amounts - it does not apply to any rewards that were not re-delegated.

### Will I keep receiving rewards after I unbound?​ <a href="#delegator-faq-willikeepreceivingrewardsafteriunbound" id="delegator-faq-willikeepreceivingrewardsafteriunbound"></a>

No. Once you unbound you stop receiving rewards.

### How many transactions does the delegation require?​ <a href="#delegator-faq-howmanytransactionsdoesthedelegationrequire" id="delegator-faq-howmanytransactionsdoesthedelegationrequire"></a>

Delegation requires 2 transactions one after the other - one to approve and another one to deposit.

### What does Redelegate Rewards mean?​ <a href="#delegator-faq-whatdoesredelegaterewardsmean" id="delegator-faq-whatdoesredelegaterewardsmean"></a>

Redelegating your rewards simply means that you want to increase your stake by restaking the rewards you have accumulated.

### Can I stake to any validator?​ <a href="#delegator-faq-canistaketoanyvalidator" id="delegator-faq-canistaketoanyvalidator"></a>

Yes.

### Which browser is compatible with Staking Dashboard?​ <a href="#delegator-faq-whichbrowseriscompatiblewithstakingdashboard" id="delegator-faq-whichbrowseriscompatiblewithstakingdashboard"></a>

All the browsers compatible with MetaMask.

### My Metamask is stuck at confirming, what can I do? <a href="#delegator-faq-mymetamaskisstuckatconfirmingafterlogin-whatdoido-ornothinghappenswhenitrytologin" id="delegator-faq-mymetamaskisstuckatconfirmingafterlogin-whatdoido-ornothinghappenswhenitrytologin"></a>

You may try the next solutions.

1\.     Restart your browser, or force close the mobile app and reopen.

2\.     Restart your computer or mobile device.

3\.     Lock and unlock MetaMask.

4\.     If your problem relates to a specific transaction, check the relevant block explorer for the network you're using, such as Polygonscan.(<https://mumbai.polygonscan.com/>)

<figure><img src="broken://files/5WKzispb7bDiyxCndtWS" alt=""><figcaption></figcaption></figure>

### How do I send funds from Binance or other exchanges to Ramestta wallet?​

First you must withdraw your funds from Binance or any other exchange to your Polygon address on Metamask.(Coming Soon)

### I have earned rewards while delegating. What happens if I add additional funds to the same validator node?​ <a href="#delegator-faq-ifihaveearnedrewardswhiledelegating-andifiaddadditionalfundstothesamevalidatornode-wha" id="delegator-faq-ifihaveearnedrewardswhiledelegating-andifiaddadditionalfundstothesamevalidatornode-wha"></a>

If you have not re-delegated your rewards before delegating additional funds to the same validator node, your rewards will be withdrawn automatically.

In case you don't want that to happen, re-delegate your rewards before delegating additional funds.

### I have delegated my tokens via MetaMask on the Staking dashboard. Do I need to keep my system or device on?​ <a href="#delegator-faq-ihavedelegatedmytokensviametamaskonthestakingdashboard.doineedtokeepmysystemordeviceon" id="delegator-faq-ihavedelegatedmytokensviametamaskonthestakingdashboard.doineedtokeepmysystemordeviceon"></a>

No. Once your Delegation transactions are confirmed, and you can see your tokens reflected in the Total Stake and New Reward cards/sections, then you are done. There is no need to keep your system or device on.

### I have unbounded, how long will it take to Unbond​ <a href="#delegator-faq-ihaveunbounded-howlongwillittaketounbond" id="delegator-faq-ihaveunbounded-howlongwillittaketounbond"></a>

The unbounding period is currently set to 82 checkpoints. This is approximately 9 days. Every checkpoint takes approximately 34 minutes. However, some checkpoints could be delayed upto \~1 hour due to congestion on Polygon.

### I have unbonded and I see the Claim Stake button, but it is disabled. <a href="#delegator-faq-ihaveunbonded-andinowseetheclaimstakebutton-butitisdisabled-whyisthat" id="delegator-faq-ihaveunbonded-andinowseetheclaimstakebutton-butitisdisabled-whyisthat"></a>

The Claim stake button will only be enabled when your unbonding period is complete. The unbounding period is currently set at 82 checkpoints. This is approximately 9 days.

### How do I switch my delegation from Foundation Nodes to External nodes?​ <a href="#delegator-faq-howdoiswitchmydelegationfromfoundationnodestoexternalnodes" id="delegator-faq-howdoiswitchmydelegationfromfoundationnodestoexternalnodes"></a>

You can switch your Delegation using the **Move Stake** option on the Staking UI. This will switch your Delegation from the Foundation node to any other external node of your choice.

<figure><img src="broken://files/8anTzVm6rXEgM8Imrsc9" alt=""><figcaption></figcaption></figure>

Select the validator frm where you want to migrate the stake.

<figure><img src="broken://files/psmebyUp1pbqylQC3zJG" alt=""><figcaption></figcaption></figure>

### Will there be any unbounding period when I switch delegation from foundation nodes to external nodes?​

You will not experience an unbounding period when switching delegation between foundation and external nodes. It will be a direct switch without any delays. However, if you are unbounding from a foundation node or an external node there will be an unbounding period for that.

### Are there any specifics to choose an external node during switch delegation?​ <a href="#delegator-faq-arethereanyspecificstochooseanexternalnodeduringswitchdelegation" id="delegator-faq-arethereanyspecificstochooseanexternalnodeduringswitchdelegation"></a>

No. You can choose any node.

### What happens to my accrued rewards if I switch delegation from foundation to external node?​ <a href="#delegator-faq-whathappenstomyrewardsthatareaccumulatedifiswitchdelegationfromfoundationtoexternalnod" id="delegator-faq-whathappenstomyrewardsthatareaccumulatedifiswitchdelegationfromfoundationtoexternalnod"></a>

If you haven't already claimed your rewards before switching delegation, then upon successful switch of your delegation from Foundation to External the Rewards that were accumulated till then will be transferred back to your account.

### Will delegation on the external nodes work the same as foundation nodes?​ <a href="#delegator-faq-willdelegationontheexternalnodesworkthesameasfoundationnodes" id="delegator-faq-willdelegationontheexternalnodesworkthesameasfoundationnodes"></a>

Yes, it will work the same as foundation nodes.

### Will I still get rewards after delegating to an external Node?​ <a href="#delegator-faq-willistillgetrewardsafterdelegatingtoanexternalnode" id="delegator-faq-willistillgetrewardsafterdelegatingtoanexternalnode"></a>

Yes, rewards will be distributed the same as earlier with the foundation nodes. Every successful submission of a checkpoint will yield in rewards. Rewards will be distributed and calculated at every checkpoint relative to the stake ratio, as currently implemented.

### Will there be any unbounding period if I unbound from an external node?​ <a href="#delegator-faq-willtherebeanyunboundingperiodifiunboundfromanexternalnode" id="delegator-faq-willtherebeanyunboundingperiodifiunboundfromanexternalnode"></a>

Yes, the unbounding period will stay the same as currently implemented 82 checkpoints. This is approximately 9 days.

### Will there be any locking period after I switch my delegation from foundation to external node?​ <a href="#delegator-faq-willtherebeanylockingperiodafteriswitchmydelegationfromfoundationtoexternalnode" id="delegator-faq-willtherebeanylockingperiodafteriswitchmydelegationfromfoundationtoexternalnode"></a>

No. There won't be any locking period after you switch your delegation.

### Can I partially switch my delegation from foundation to external nodes?​ <a href="#delegator-faq-canipartiallyswitchmydelegationfromfoundationtoexternalnodes" id="delegator-faq-canipartiallyswitchmydelegationfromfoundationtoexternalnodes"></a>

Yes, you will have the option to partially move your stake from foundation node to an external node. The remaining partial stake will remain on the foundation node. You can then move that to another node of your choice or the same node.

### Can I switch delegation from an external node to another external node?​ <a href="#delegator-faq-caniswitchdelegationfromanexternalnodetoanotherexternalnode" id="delegator-faq-caniswitchdelegationfromanexternalnodetoanotherexternalnode"></a>

No, the **Move Stake** option is only available on the foundation nodes. If you want to switch your delegation from an external node to another external node, you will have to unbound first and then delegate to another external node.

### How many transactions do I need to pay for Gas when I do a Move Stake?​ <a href="#delegator-faq-howmanytransactionsdoineedtopayforgaswhenidoamovestake" id="delegator-faq-howmanytransactionsdoineedtopayforgaswhenidoamovestake"></a>

The **Move Stak**e is a single transaction only. All transactions would be on the Polygon Blockchain so you would need to spend some MATIC while doing the **Move Stake** transaction.

*Some of the information found on this page has been developed using the open-source information provided by Polygon.*&#x20;


# Deploy smart contracts

Now that you know what Ramestta is, let's deploy a contract.

1. **Setting up MetaMask with Ramestta.**
2. **Obtaining test RAMA.**

For the smart contract to be deployed and interact with, you will need some test BONE tokens.

Copy your Metamask address and paste it into the address field of the faucet, and click on submit.\
The faucet will send you 0.1 test RAMA.\
\
You can find the faucet link by clicking here.

**coming soon**

### Writing the contract <a href="#deploying-the-contract" id="deploying-the-contract"></a>

Make a new solidity file using REMIX Ethereum, for example.

Your new Solidity script should contain the following code:

Contract writing

```
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0 <0.7.0;
contract SimpleStorage {
    uint storedData;
    function set(uint x) public {
        storedData = x;
    }
    function get() public view returns (uint) {
        return storedData;
    }
}
```

* Line 1: Specifying [SPDX license](https://spdx.org/licenses/) type, which is an addition after Solidity ^0.6.8. \
  Whenever the source code of a smart contract is made available to the public, these licenses can help resolve/avoid copyright issues. If you do not wish to specify any license type, you can use a special license [UNLICENSED](https://spdx.org/licenses/Unlicense.html) or simply skip the whole comment (it won’t result in an error, just a warning).
* Line 2: On the second line, we are declaring which Solidity compiler we want to use. For instance, we are targeting any version between ≥ 0.4.0 and <0.8.0.
* Line 3: You declare your contract here and name it as **SimpleStorage**.
* Line 4: Declaring a uint (Unsigned Integer) variable named **storedData.** This variable will be used to store data.
* Line 5-7: Next, you will add a **set** function, using which you will change the value of your variable **storeData**. The **set** function accepts a parameter **x** whose value you are placing into **storeData**. In addition, the function is marked as public which means that the function can be called outside the scope of this function and by other contracts.
* Line 8-10: You will add a **get** function to retrieve the value of **storeData** variable. This function is marked as view, which tells the Solidity compiler that this is a read-only function.\
  Other than that, the **get** function also has returns (uint), which means that the function will return a uint value.

### Deploying the contract <a href="#deploying-the-contract" id="deploying-the-contract"></a>

Click on the Solidity logo from the left menu and click on compile. After successful compilation, a green tick will appear on the Solidity logo.

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2F11YOpvLIfVj8qUwlpwir%2FScreenshot%202024-01-16%20at%2011.33.04%20AM.png?alt=media&amp;token=6ea6644a-c5a2-4b59-af49-8359f4a17c52" alt=""><figcaption></figcaption></figure>

Now, click on the option from the left menu to deploy the complied contract and select Injected Web3 as the environment. Below the environment, the name and chainid of your network will appear. Make sure you have the correct contract name selected under the contract option. Once you have checked everything, click on "Deploy" and accept the transaction from the MetaMask pop-up window.

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FYW5xS7JgZOZAIaeslKK9%2FScreenshot%202024-01-16%20at%2011.41.04%20AM.png?alt=media&amp;token=89d217d3-9195-4195-9169-c0ef02de22d2" alt=""><figcaption></figcaption></figure>

Once the contract deployment transaction is approved, the deployed contract will appear under the "Deployed Contracts" section.

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FclUbP5z8CgrwmurB9N8c%2FScreenshot%202024-01-16%20at%2011.46.21%20AM.png?alt=media&amp;token=4140a5b8-a8bd-429b-8a21-c37932a7dffc" alt=""><figcaption></figcaption></figure>

Expand the deployed contract and click on "get". It will return the value of **storedData**, which is currently zero since you have not input any number yet.

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FgWKyxnJ3YNOl0ExbEfyG%2FScreenshot%202024-01-16%20at%2011.48.31%20AM.png?alt=media&amp;token=5e5b25f7-fa8d-49d3-9c89-0e31c4644523" alt=""><figcaption></figcaption></figure>

To input a value, enter a number in the field near the set button, click on "set" and approve the transaction from the MetaMask pop-up. Once the transaction is approved, the value of **storedData** will be the input number. To verify this, click on "get", and the previously input value will be printed.

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FFjRLcmOe5FwJ0a8rNRwN%2FScreenshot%202024-01-16%20at%2011.49.12%20AM.png?alt=media&amp;token=2a175696-a7ff-49ed-9792-891dda86d2e4" alt=""><figcaption></figcaption></figure>

This is how contracts are deployed on Ramestta!


# MetaMask Installation & Set up Web3 RPC URL

To monitor the flow of funds in your network account, it is essential to set up Ramestta's URL on Metamask, whether you're using the testnet or mainnet. The use of MetaMask is a prerequisite for this process. \
\
MetaMask can be used on both mobile devices and web browsers for interacting with the Ethereum blockchain. By utilizing the browser-based Ethereum DApp, users can execute Ethereum apps directly within their browser. \
Communication between Infura and the Ethereum Ledger is enabled, while mnemonic private key encoding is non-custodial and HD private key storage is performed locally on the user's browser storage. \
\
To set up Metamask, please refer to the guide.

### How to create a MetaMask Wallet?

If you're interested in creating a cryptocurrency wallet, installing the MetaMask extension on your browser is a good place to start. \
Once installed, MetaMask injects a global API into websites visited by users, available at window\.ethereum (or window\.web3.currentProvider for legacy purposes). \
Websites can use this API to request user logins, fetch data from blockchains that the user has a connection to, and recommend the user to sign messages and transactions. This API can also be used to detect the user of a web3 browser.

Step 1. Get MetaMask for your browser.

Metamask is available for Chrome, Firefox, Brave, and Opera.

1. Open [https://metamask.io](https://metamask.io/) or search for “Metamask extension” using your favorite search engine.

In this tutorial we will be using Google Chrome as an example, but the workflow is the same for all browsers.

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FXBTpRCQrj3ltV7hdDXJG%2Fspaces_GRwEwyXrmn4CaQ9y2Z80_uploads_CBVnw7ycAM1ZWkiWsTxI_image.webp?alt=media&amp;token=75fac577-a6e4-4a00-90d6-26573ee4b71f" alt=""><figcaption></figcaption></figure>

1. Click **Chrome** to install MetaMask as a Google Chrome extension.
2. Click **Add to Chrome.**
3. Click **Add Extension**.

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FsN8FSZTlHId58OA2YEZC%2Fspaces_GRwEwyXrmn4CaQ9y2Z80_uploads_N2hJkPaa1mN04xKSUPkc_image.webp?alt=media&amp;token=eedfd395-b2f1-4e41-8332-6f313ab689b7" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2F6JcoX7d9JLaay1rzNfxF%2Fspaces_GRwEwyXrmn4CaQ9y2Z80_uploads_KsICWaSL3mB0Wykdej4f_image.webp?alt=media&amp;token=fb946371-132d-42db-a2c0-bc0f4b314738" alt=""><figcaption></figcaption></figure>

4. That’s all. You have successfully installed MetaMask extension!
5. The next step is to create an account.
   1. Click on the MetaMask icon in the upper right corner to open the extension.
   2. To install the latest version of MetaMask, click **Try it now**.
   3. Click **Continue.**

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FMzduXmk2UcMpTb5Nt3kk%2Fspaces_GRwEwyXrmn4CaQ9y2Z80_uploads_EqXuQBdsgdQ7mDQeM1dI_image.webp?alt=media&amp;token=0a8a3d1b-b85a-4418-a3cb-b5d6233ef58a" alt=""><figcaption></figcaption></figure>

6. You will be asked to create a new password. Create a strong password and click **Create**.

> Don’t forget to store your password for safekeeping!

<img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FM5QavkId1miAT0u8Yeqp%2Fspaces_GRwEwyXrmn4CaQ9y2Z80_uploads_rpPp7fULrRsOHwwLii0p_image.webp?alt=media&amp;token=d1738178-b8b7-43eb-817e-bf8a1f206938" alt="" data-size="original">

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FBc3rPXunwdaAFRzlpbXr%2Fspaces_GRwEwyXrmn4CaQ9y2Z80_uploads_FQz0yvfDwr9xLc4q07w0_image.webp?alt=media&amp;token=97e09d5f-2464-46f9-9d66-97313f2ba7cd" alt=""><figcaption></figcaption></figure>

1. Proceed by clicking **Next**, then accept Terms of Use.
2. Click **Reveal secret words**.
3. You will see a 12 words seed phrase. Save seed words as a file or copy them to a safe place and click **Next.**

Reveal secret words and copy your secret backup phrase to a safe place.

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FsHIR4t61cgIrUNIPUa4b%2Fspaces_GRwEwyXrmn4CaQ9y2Z80_uploads_zt4KCJbSsEVpssUWMioG_image.webp?alt=media&amp;token=1a9d7d5d-6747-4347-a1cd-4932a00f4e3a" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2F2LT3W740oUZqq2FXz0sQ%2Fspaces_GRwEwyXrmn4CaQ9y2Z80_uploads_YwmB6eG5wZV7yyFS069Y_image.webp?alt=media&amp;token=c95c2aa4-d20b-4855-ad04-c89b27a77f08" alt=""><figcaption></figcaption></figure>

Security tips: Write this phrase on a piece of paper and store in a secure location. If you want even more security, write it down on multiple pieces of paper and store each in 2–3 different locations. Memorize this phrase.

1. Verify your secret phrase by selecting the previously generated phrase. When done, click **Confirm**.

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2F6gGpnNaWaAnuPcrXaJcd%2Fspaces_GRwEwyXrmn4CaQ9y2Z80_uploads_zIcNTNuRVJQ2fOjnalDW_image.webp?alt=media&amp;token=395402cc-4be8-4572-9640-b490645192fd" alt=""><figcaption></figcaption></figure>

By “solving this puzzle” you are confirming that you know your secret phrase.

**Congratulations!** You have successfully created your MetaMask account. A new Ethereum wallet address was automatically generated for you.

## Add Ramestta Network <a href="#add-shibarium-network" id="add-shibarium-network"></a>

In order to view the flow of funds in your accounts, on the Ramestta Network, you will need to configure Ramestta `{testnet, mainnet}` URL on Metamask.

<https://www.ramestta.com/>

**Add the Ramesttta Network Manually (steps given below)**

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2F2455f9X7bI28dtfKgyUF%2FCreate%20token%20on%20Ramestta%20blockchain-3.jpg?alt=media&amp;token=c79e8a6b-818d-4374-8a3b-39e82f375399" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2F9GwyWFSF7X373JlVVHKQ%2FCreate%20token%20on%20Ramestta%20blockchain-4.jpg?alt=media&amp;token=69be3863-0d59-4640-a704-0617b0e4fdf5" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FjEDfkglVUV0v0KiGDVfh%2FCreate%20token%20on%20Ramestta%20blockchain-5.jpg?alt=media&amp;token=f99a6e73-eb53-4e1f-a1d2-2caca0b5c375" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FuKIh396vWBG9CUcYIcGu%2FCreate%20token%20on%20Ramestta%20blockchain-6.jpg?alt=media&amp;token=bc907105-f798-42c6-acc1-afe2a4553cbd" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FxvELAzEWG2wXp6Vh7SaA%2FCreate%20token%20on%20Ramestta%20blockchain-7.jpg?alt=media&amp;token=6a6406fb-d43e-4c08-b449-8fca8903ecea" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2F9Bv9CusKAk9PYwNw1VgE%2FCreate%20token%20on%20Ramestta%20blockchain-8.jpg?alt=media&amp;token=cd60bf0e-0893-4abe-9072-71381eff2335" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2F2q8DF99eYEgiGsDESq97%2FCreate%20token%20on%20Ramestta%20blockchain-9.jpg?alt=media&amp;token=d01b5f8b-3cb7-4822-9ed6-310d825241ca" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2F7dfG3Hx23MuiDNHGogxE%2FCreate%20token%20on%20Ramestta%20blockchain-10.jpg?alt=media&amp;token=c98703bb-f88a-4822-9787-67e21853d1a0" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FsolRYPdPhTAUAICOKL3c%2FCreate%20token%20on%20Ramestta%20blockchain-11.jpg?alt=media&amp;token=09b82e08-bad8-4f12-acbb-885570e78275" alt=""><figcaption></figcaption></figure>

<https://www.quicknode.com/guides/ethereum-development/smart-contracts/how-to-create-and-deploy-an-erc20-token>

**COPY THE ABOVE LINK TO OPEN IN CHROME OR ANY BROWSER**

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2F0gB6VIc5GbsL3ZHDzAks%2FCreate%20token%20on%20Ramestta%20blockchain-13.jpg?alt=media&amp;token=c17ae620-0687-4a77-b718-ad1a420c0fa2" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2F5PyrJ52Pt0R06VZXZu1h%2FCreate%20token%20on%20Ramestta%20blockchain-14.jpg?alt=media&amp;token=327f7c7c-40ee-4907-98ea-c2c105ec0e3e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FcDs0tirdiWj3zQMLMnbk%2FCreate%20token%20on%20Ramestta%20blockchain-15.jpg?alt=media&amp;token=13d7b926-b1ed-40eb-9d11-9e5f1252e933" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FiHt6y6XpaRcJE4Y4kx5j%2FCreate%20token%20on%20Ramestta%20blockchain-16.jpg?alt=media&amp;token=1029b6cf-3bf2-4513-8078-a66aea34f12d" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FO22OZUKvP7pORDYyyGKf%2FCreate%20token%20on%20Ramestta%20blockchain-17.jpg?alt=media&amp;token=f10d31fe-944b-421e-85c9-a2e721325b8e" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FdRfjYlsOJ4Ui84NZfT4R%2FCreate%20token%20on%20Ramestta%20blockchain-18.jpg?alt=media&amp;token=383b4686-4407-4c3a-a416-7fed4089136a" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FPNxQq8HbOSmElzFiZ7E9%2FCreate%20token%20on%20Ramestta%20blockchain-19.jpg?alt=media&amp;token=0307dbc4-2ffd-4843-83f9-3bec13a02d12" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2Fgneimza2xJJAlpVPPRwK%2FCreate%20token%20on%20Ramestta%20blockchain-20.jpg?alt=media&amp;token=39d11b4d-f20a-4354-bac2-b9eb04f498eb" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FrPqqKhOlIDuhTcKHWcUv%2FCreate%20token%20on%20Ramestta%20blockchain-21.jpg?alt=media&amp;token=69173c91-cd21-4c0f-8bbe-38517c3a24e7" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FC8erAt1QzrpeWIK1cZqt%2FCreate%20token%20on%20Ramestta%20blockchain-22.jpg?alt=media&amp;token=788b71a1-962e-4110-b376-b93b054f54a4" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2F9gok1PriilYUY9tVKLNh%2FCreate%20token%20on%20Ramestta%20blockchain-23.jpg?alt=media&amp;token=0546544e-40d3-4f2f-9f4b-4f5215959d66" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FwdnBbIT1mwDNTCZeZSUJ%2FCreate%20token%20on%20Ramestta%20blockchain-24.jpg?alt=media&amp;token=9d6602c8-7b48-4d27-9911-40be718e5907" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FO0eDBgs8lX94UZ0rzqSa%2FCreate%20token%20on%20Ramestta%20blockchain-25.jpg?alt=media&amp;token=2d57a3b8-6423-4ce8-8330-643bbd6510c9" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FbptuFGq8jUVhl0Yk22Ba%2FCreate%20token%20on%20Ramestta%20blockchain-26.jpg?alt=media&amp;token=ea351599-9b5d-400b-aa5d-61fe27585783" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FagpROmpfxtSoAGdh1iUQ%2FCreate%20token%20on%20Ramestta%20blockchain-27.jpg?alt=media&amp;token=3011b345-506e-4a7c-9c66-fb13466838cd" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FtChQIpRxkQUrO6Lo9Y53%2FCreate%20token%20on%20Ramestta%20blockchain-28.jpg?alt=media&amp;token=a6be474e-6188-4767-8f4a-00d1e87a3e9b" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FZZv2AHGdlkK0wePjQsYs%2FCreate%20token%20on%20Ramestta%20blockchain-29.jpg?alt=media&amp;token=83e110ba-b30e-40b4-964c-d7528dbcbf01" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FzmOPI2EInJexDbNEb6lb%2FCreate%20token%20on%20Ramestta%20blockchain-30.jpg?alt=media&amp;token=79c04c77-f2ed-49b0-b592-863e9e5c1e64" alt=""><figcaption></figcaption></figure>

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2Fc7ugZU4Mf3YLmfCvPvQx%2FCreate%20token%20on%20Ramestta%20blockchain-31.jpg?alt=media&amp;token=4a6a1035-6700-48f2-8c64-ed26694cf40b" alt=""><figcaption></figcaption></figure>


# Blockchain Fundamental

At the most basic level, blockchain technology is composed of cryptographic algorithms. The creator of blockchain, Satoshi Nakamoto, developed a system in which the trust that we traditionally place in organizations to maintain trusted records (like banks) is transferred to the blockchain and the cryptographic algorithms that it uses.

**The Cryptography Behind Blockchain**

The goal of the blockchain is to create a distributed, decentralized, and trusted record of the history of the system. The most famous blockchain, Bitcoin, uses this record to store the history of transactions, so people can make and receive payments on the Bitcoin blockchain and trust that their money won’t be lost or stolen.

In order to achieve this level of trust, the blockchain uses a couple of cryptographic algorithms as building blocks. Hash functions and public key cryptography are crucial to both the functionality and security of the blockchain ecosystem.

**Hash Functions**

A hash function is a mathematical function that can take any number as an input and produces an output in a fixed range of numbers. For example, 256-bit hash functions (which are commonly used in blockchain), produce outputs in the range 0-2256.

In order to be considered secure, a hash function needs to be collision-resistant, this means that it’s extremely difficult (to the point of being nearly impossible) to find two inputs that create the same hash output. Accomplishing this requires a few different features:

* No weaknesses in the hash function
* A large number of possible outputs
* A one-way hash function (can’t derive the input from the output)
* Similar inputs produce very different outputs

If a hash function meets these requirements, it can be used in blockchain. However, if any of these requirements are violated, then the security of the blockchain is at risk. Blockchain relies heavily on secure hash functions to ensure that transactions cannot be modified after being stored in the ledger.

<br>

**Public Key Cryptography**

The other cryptographic algorithm used in blockchain technology is public key cryptography. This type of cryptography is also widely used on the Internet as well since it has so many useful properties. With public key cryptography, you can:

* Encrypt a message so that only the intended recipient can read it
* Generate a digital signature proving that you sent a given message
* Use a digital signature to verify that a message was not modified in transit

In public key cryptography, everyone has two different encryption keys: a private one and a public one. Your private key is a random number that you generate and keep secret. It is used for decrypting messages and generating digital signatures.

Your public key is derived from your private key and, as the name suggests, is designed to be publicly distributed. It’s used for encrypting messages to you and generating digital signatures. Your address (where people sent transactions to) on the blockchain is typically derived from your public key.

The security of public key cryptography is based on two things. The first is the secrecy of your private key. If someone can guess or steal your private key, they have complete control of your account on the blockchain. This allows them to perform transactions on your behalf and decrypt data meant for you. The most common way that blockchain is “hacked” is people failing to protect their private key.

The other main assumption of public key cryptography is that the algorithms used are secure. Public key cryptography is based off of mathematical “hard” problems, where performing an operation is much easier than reversing it. For example, it’s relatively easy to multiply two numbers together but hard to factor the result. Similarly, it’s easy to perform exponentiation but hard to calculate logarithms. As a result, it’s possible to create schemes where computers are capable of performing the easy operation but not the hard one.

The security of these “hard” problems are why you’ll often see articles about quantum computers breaking blockchain. Due to how quantum computers work, factoring and logarithms aren’t much harder than multiplication and exponentiation, so traditional public key cryptography no longer works. However, other problems exist that are still “hard” for quantum computers, so the threat of quantum computers to blockchain can be fixed with a simple upgrade.

**How Blockchains are Put Together**

As its name suggests, the blockchain is a collection of blocks that are chained together to create a continuous whole. In this section, we explore how this works.

**Blocks**

![Diagram explaining blockchaik block structure and relationship](https://ghostvolt.com/assets/img/articles/chains.png)

The purpose of the blockchain is to act as a distributed ledger that stores data in a secure fashion. The blocks are the place where this data is stored.

The image above illustrates the basic structure of a block in a blockchain. We’ll talk about every part of this image throughout the series, but for now focus on the green sections. Each green piece represents a transaction within the block. While a transaction may represent a literal transaction (i.e. a transfer of value) on blockchains like Bitcoin, this is not the only option. As we’ll see later, smart contract platforms store other things (like computer code) as transactions as well.

The security of the blocks in the digital ledger depends on the security of public key cryptography. Every transaction and block in the blockchain is digitally signed by its creator. This allows anyone with access to the blockchain to easy validate that every transaction is authenticated (i.e. sent by someone who owns the associated account) and has not been modified since creation. The integrity and authenticity of the blocks in the chain is also assured by the digital signature of the block creator.


# Introduction

A block in a blockchain is a group or collection of information. The information is added to the block in a blockchain, by connecting it with other blocks in the chronological order and creating a chain of blocks linked together. Let’s take the example of Google spreadsheet or MS Excel (Windows). This spreadsheet is shared among different computer networks, where everyone has a copy. The spreadsheet contains data and information of transactions made by individuals. Anyone with a copy can access that spreadsheet but no one can edit or change it. This is how the blockchain works. It uses blocks, whereas spreadsheet works with “rows” and “columns”.

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FOF7JcnjM4NLk0X9HyQ1o%2FBlockchain.webp?alt=media&amp;token=5e8e52fe-cd2b-471e-9229-f022c30ebbe8" alt=""><figcaption></figcaption></figure>

The blockchain is a *distributed ledger.* This means that a ledger is spread across the network between all peers in the network, and each peer holds a copy of the complete ledger. Some key properties that make blockchain far superior and better than the traditional system of information ledgering.


# What is a Blockchain?

A blockchain is a digital database or ledger shared across a computer network's nodes that stores information electronically. Its most recognized use is in cryptocurrency systems such as Bitcoin, where it acts as a secure and decentralized record of transactions.&#x20;

Unlike traditional databases, blockchain structures data in blocks that hold sets of information. These blocks are linked to the previous block to form a chain of data that is irreversible and exact in chronological order. While databases use tables to structure data, a blockchain creates a tamper-proof timeline of data through its decentralized implementation.&#x20;

Each block in the chain is assigned a timestamp upon addition to the chain, creating an accurate record of transactions.

### How does a Blockchain work? <a href="#how-does-a-blockchain-work-hardbreak" id="how-does-a-blockchain-work-hardbreak"></a>

A blockchain is a decentralized digital ledger that stores information in blocks that are linked together in a secure and transparent manner. Here is a simplified overview of how a blockchain works:

1. A transaction is initiated by a user on the network. This transaction can involve the transfer of cryptocurrency or other digital assets, the execution of a smart contract, or any other operation that the blockchain is designed to support.
2. The transaction is broadcasted to the network of nodes, which are computers that maintain copies of the blockchain.
3. The nodes validate the transaction using a consensus mechanism, which is a set of rules that governs how transactions are verified and added to the blockchain. This mechanism could be proof-of-work, proof-of-stake, or another system depending on the specific blockchain.
4. Once the transaction is validated, it is packaged into a block along with other validated transactions. This block is then added to the existing chain of blocks, creating a new link in the blockchain.
5. Each block in the blockchain contains a cryptographic hash of the previous block, forming an unbreakable chain of data that is tamper-proof and secure.
6. The blockchain is distributed across the network of nodes, ensuring that every node has a copy of the entire blockchain. This makes the blockchain resistant to attacks and failures because there is no central point of control or failure.
7. Users can view the blockchain to see all transactions and the current state of the network. Because the blockchain is transparent, anyone can verify the integrity of the data stored in it.

#### Transparency <a href="#transparency-hardbreak" id="transparency-hardbreak"></a>

Due to the decentralized nature of Bitcoin's blockchain, transactions can be openly viewed by either running a personal node or using blockchain explorers, which enable people to view transactions occurring in real-time. Each node has its own copy of the blockchain, which is updated as new blocks are confirmed and added. Consequently, one can track the movement of Bitcoin. For instance, in the past, exchanges have been hacked, and those who kept Bitcoin on the exchange lost everything. Although the hacker might be completely anonymous, the stolen Bitcoins are easily traceable. If they were to be moved or spent, it would be noticeable. Nevertheless, records saved in the Bitcoin blockchain (as well as most others) are encrypted, ensuring that only the record owner can decrypt it to expose their identity (using a public-private key pair). Therefore, blockchain users can remain anonymous while maintaining transparency.

#### Is the Blockchain Secure? <a href="#is-blockchain-secure-hardbreak" id="is-blockchain-secure-hardbreak"></a>

Blockchain technology maintains decentralized security and trust by storing new blocks linearly and chronologically. Once a block is added to the blockchain, altering the contents becomes extremely difficult unless the network reaches a consensus to do so. Each block contains its own hash and the hash of the previous block, along with a timestamp. Hash codes are created by a mathematical function, and any edits to the information result in a change to the hash code.&#x20;

If a hacker attempts to alter a blockchain, their copy of the chain would no longer match the rest of the network's copies. For such an attack to be successful, the hacker would need to simultaneously control and alter 51% or more of the copies of the blockchain, which would be insurmountably expensive and likely fruitless. Any drastic alterations to the blockchain would be noticed by network members, who would then hard fork off to a new version of the chain that has not been affected.&#x20;

Ultimately, attacking the network is far less economically incentivized than participating in it.

#### How are Blockchains used? <a href="#how-are-blockchains-used-hardbreak" id="how-are-blockchains-used-hardbreak"></a>

The blockchain technology is not only used to store data about monetary transactions but also for other types of transactions. Many companies, including Walmart, Pfizer, AIG, Siemens, and Unilever, have incorporated blockchain into their operations. For instance, IBM has developed its Food Trust blockchain to trace the journey of food products from their origin to their final destination. This is because the food industry has seen various outbreaks of diseases, and using blockchain enables companies to track the route of a food product and identify the source of contamination. This way, companies can act faster to prevent the spread of diseases and save lives. There are many other practical applications of blockchain in different industries.

#### Banking and Finance <a href="#banking-and-finance-hardbreak" id="banking-and-finance-hardbreak"></a>

The integration of blockchain technology into banking operations could potentially offer significant benefits. Unlike traditional banking systems, which operate during business hours and can take one to three days to verify transactions, blockchain technology operates 24/7 and can process transactions in as little as 10 minutes.&#x20;

This means that consumers could see their transactions processed much faster, regardless of holidays or the time of day. Additionally, blockchain could enable faster and more secure exchange of funds between banks. In industries like stock trading, where settlement and clearing can take up to three days, the use of blockchain could significantly reduce costs and risks for banks.

#### Currency <a href="#currency-hardbreak" id="currency-hardbreak"></a>

Blockchain is the foundation for cryptocurrencies like Bitcoin, which eliminate the need for a central authority. Under the current central authority system, a user’s currency and data are vulnerable to their bank or government.&#x20;

A bank hack or collapse, or living in a country with an unstable government, can jeopardize a user’s currency value. These risks inspired the creation of Bitcoin, which operates across a network of computers, reducing risk and fees while providing a more stable currency for those in unstable financial infrastructures.&#x20;

Cryptocurrency wallets offer savings and payment options, especially for those without state identification, allowing access to wealth storage otherwise unattainable.

#### Healthcare <a href="#healthcare-hardbreak" id="healthcare-hardbreak"></a>

Healthcare providers have the potential to utilize blockchain technology to securely store their patients' medical records. Whenever a medical record is created and authenticated, it can be written into the blockchain, giving patients the assurance that the record is immutable. Personal health records can be encrypted and stored on the blockchain using a private key, ensuring that they can only be accessed by authorized individuals, thus maintaining privacy.

#### Property Records <a href="#property-records-hardbreak" id="property-records-hardbreak"></a>

Recording property rights is a burdensome and inefficient process that requires physical deeds to be delivered to a government employee at the local recording office, manually entered into the county's central database and public index, and reconciled with claims to the property in case of a dispute. This process is not only time-consuming but also prone to human error, making tracking property ownership less efficient.&#x20;

However, blockchain technology can potentially eliminate the need for scanning documents and tracking down physical files by storing and verifying property ownership on the blockchain. In war-torn or financially unstable areas where there is little to no government or financial infrastructure, it can be nearly impossible to prove ownership of a property.&#x20;

By leveraging blockchain, a transparent and clear timeline of property ownership could be established, allowing people in these areas to prove ownership of their property.

#### Smart Contracts <a href="#smart-contracts-hardbreak" id="smart-contracts-hardbreak"></a>

A smart contract is a computer code that can be built into the blockchain to facilitate, verify, or negotiate a contract agreement. Smart contracts operate under a set of conditions to which users agree. When those conditions are met, the terms of the agreement are automatically carried out.

Say, for example, that a potential tenant would like to lease an apartment using a smart contract. The landlord agrees to give the tenant the door code to the apartment as soon as the tenant pays the security deposit. Both the tenant and the landlord would send their respective portions of the deal to the smart contract, which would hold onto and automatically exchange the door code for the security deposit on the date when the lease begins. If the landlord doesn’t supply the door code by the lease date, then the smart contract refunds the security deposit. This would eliminate the fees and processes typically associated with the use of a notary, a third-party mediator, or attorneys.

#### Supply Chains <a href="#supply-chains-hardbreak" id="supply-chains-hardbreak"></a>

As in the IBM Food Trust example, suppliers can use blockchain to record the origins of materials that they have purchased. This would allow companies to verify the authenticity of not only their products but also common labels such as “Organic,” “Local,” and “Fair Trade.”

As reported by Forbes, the food industry is increasingly adopting the use of blockchain to track the path and safety of food throughout the farm-to-user journey.4

#### Voting <a href="#voting-hardbreak" id="voting-hardbreak"></a>

As mentioned above, blockchain could be used to facilitate a modern voting system. Voting with blockchain carries the potential to eliminate election fraud and boost voter turnout, as was tested in the November 2018 midterm elections in West Virginia.5 Using blockchain in this way would make votes nearly impossible to tamper with. The blockchain protocol would also maintain transparency in the electoral process, reducing the personnel needed to conduct an election and providing officials with nearly instant results. This would eliminate the need for recounts or any real concern that fraud might threaten the election.

### Benefits of the Blockchain <a href="#benefits-of-blockchains-hardbreak" id="benefits-of-blockchains-hardbreak"></a>

#### Accuracy of the Chain <a href="#benefits-of-blockchains-hardbreak" id="benefits-of-blockchains-hardbreak"></a>

Transactions on the blockchain network are approved by a network of thousands of computers. This removes almost all human involvement in the verification process, resulting in less human error and an accurate record of information. Even if a computer on the network were to make a computational mistake, the error would only be made to one copy of the blockchain. For that error to spread to the rest of the blockchain, it would need to be made by atleast 51% of the network’s computers - a near impossibility for a large and growing network the size of Bitcoin’s.6

#### Cost Reductions <a href="#cost-reductions-hardbreak" id="cost-reductions-hardbreak"></a>

Blockchain technology removes the requirement for third-party verification, which is usually associated with costs for consumers, such as paying a bank to verify a transaction, a notary to sign a document, or a minister to perform a marriage. Transactions conducted through credit cards result in a small fee for business owners because banks and payment-processing companies are responsible for processing those transactions. In contrast, Bitcoin and other decentralized cryptocurrencies do not rely on a central authority, thus minimizing transaction fees.

#### Decentralization <a href="#decentralization-hardbreak" id="decentralization-hardbreak"></a>

In contrast to traditional databases, blockchain does not rely on a central storage location for its data. Instead, the information is distributed across a network of computers, with each computer maintaining a copy of the blockchain. Whenever a new block is added to the blockchain, every computer on the network updates its version of the blockchain to reflect the change. This decentralized approach makes it extremely difficult to tamper with the blockchain, as a hacker would need to gain control of a majority of the network's computers in order to make any changes to the data. Additionally, even if a hacker were able to compromise a single copy of the blockchain, the rest of the network's copies would remain intact and uncompromised.

#### Efficient Transactions <a href="#efficient-transactions-hardbreak" id="efficient-transactions-hardbreak"></a>

Transactions placed through a central authority can take up to a few days to settle. If you attempt to deposit a check on Friday evening, for example, you may not actually see funds in your account until Monday morning. Whereas financial institutions operate during business hours, usually five days a week, blockchain is working 24 hours a day, seven days a week, and 365 days a year. Transactions can be completed in as little as 10 minutes and can be considered secure after just a few hours. This is particularly useful for cross-border trades, which usually take much longer because of time zone issues and the fact that all parties must confirm payment processing.

#### Private Transactions <a href="#private-transactions-hardbreak" id="private-transactions-hardbreak"></a>

Many blockchain networks operate as public databases, meaning that anyone with an Internet connection can view a list of the network’s transaction history. Although users can access details about transactions, they cannot access identifying information about the users making those transactions. It is a common misperception that blockchain networks like bitcoin are anonymous, when in fact they are only confidential.

When a user makes a public transaction, their unique code—called a public key, as mentioned earlier—is recorded on the blockchain. Their personal information is not. If a person has made a Bitcoin purchase on an exchange that requires identification, then the person’s identity is still linked to their blockchain address—but a transaction, even when tied to a person’s name, does not reveal any personal information.

#### Secure Transactions <a href="#secure-transactions-hardbreak" id="secure-transactions-hardbreak"></a>

Once a transaction is recorded, its authenticity must be verified by the blockchain network. Thousands of computers on the blockchain rush to confirm that the details of the purchase are correct. After a computer has validated the transaction, it is added to the blockchain block. Each block on the blockchain contains its own unique hash, along with the unique hash of the block before it. When the information on a block is edited in any way, that block’s hash code changes—however, the hash code on the block after it would not. This discrepancy makes it extremely difficult for information on the blockchain to be changed without notice.

#### Transparency <a href="#transparency-hardbreak-.1" id="transparency-hardbreak-.1"></a>

Most blockchains are entirely open-source software. This means that anyone and everyone can view its code. This gives auditors the ability to review cryptocurrencies like Bitcoin for security. This also means that there is no real authority on who controls Bitcoin’s code or how it is edited. Because of this, anyone can suggest changes or upgrades to the system. If a majority of the network users agree that the new version of the code with the upgrade is sound and worthwhile, then Bitcoin can be updated.

#### Banking the Unbanked <a href="#banking-the-unbanked-hardbreak" id="banking-the-unbanked-hardbreak"></a>

Perhaps the most profound facet of blockchain and Bitcoin is the ability for anyone, regardless of ethnicity, gender, or cultural background, to use it. According to The World Bank, an estimated 1.7 billion adults do not have bank accounts or any means of storing their money or wealth.7 Nearly all of these individuals live in developing countries, where the economy is in its infancy and entirely dependent on cash.

These people often earn a little money that is paid in physical cash. They then need to store this physical cash in hidden locations in their homes or other places of living, leaving them subject to robbery or unnecessary violence. Keys to a bitcoin wallet can be stored on a piece of paper, a cheap cell phone, or even memorized if necessary. For most people, it is likely that these options are more easily hidden than a small pile of cash under a mattress.

Blockchains of the future are also looking for solutions to not only be a unit of account for wealth storage but also to store medical records, property rights, and a variety of other legal contracts.

#### Who Invented Blockchain?  Blockchain technology was first outlined in 1991 by Stuart Haber and W. Scott Stornetta, two mathematicians who wanted to implement a system where document timestamps could not be tampered with.1 In the late 1990s, Cypherpunk Nick Szabo proposed using a blockchain to secure a digital payments system, known as bit gold (which was never implemented). <a href="#who-invented-blockchain-hardbreak" id="who-invented-blockchain-hardbreak"></a>


# Types of Blockchain

Types of blockchain

There are 4 types of blockchain:

* Public blockchain.
* Private blockchain.
* Hybrid blockchain.
* Consortium blockchain.

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2Fmm0B6nHGfv1X6jmhm9KR%2Ftype.jpeg?alt=media&amp;token=fe60c0b2-fabc-4a3b-94d8-766001b76236" alt=""><figcaption><p>Types of Blockchain</p></figcaption></figure>

### **1. Public blockchain**

These blockchains are completely open based on the idea of decentralization. They don’t have any restrictions. Anyone with a computer and the internet can participate in the network.

* As the name suggests, this blockchain is open to the public, which means it is not owned by anyone.
* Anyone with internet access and a computer with high-quality hardware can participate in this public blockchain.
* All the computers in the network hold copies of other nodes or blocks present in the network
* In this public blockchain, we can also verify transactions or records

**Advantages:**

* **The algorithm detects no fraud, so it is trustworthy.** Participants need not worry about the other nodes in the network
* **Secure:** This blockchain is large in size as it is open to the public. At a large size, there is a greater distribution of records
* **In addition, it is a secure platform to ensure your transaction is handled properly, you do not have to reveal your identity or name.**
* **Decentralized:** There is no single platform that maintains the network, instead every user has a copy of the ledger

**Disadvantages:**

* **Processing:** The rate of the transaction process is very slow, due to its large size. Verification of each node is a very time-consuming process.
* **Proof of work consumes a lot of energy.** It requires high-quality computer hardware to participate in the network
* **Acceptance:** There is no central authority, so governments are forced to implement the technology faster.

**They can be used to replace traditional financial systems because they are secured with proof of work or proof of stake.** The more advanced side of this blockchain is the smart contract that enables this blockchain to support decentralization. The Bitcoin and Ethereum blockchains are examples of public blockchains.

### **2. Private blockchain**

These blockchains are not as decentralized as the public blockchain. Only selected nodes can participate in the process, making it more secure than others.

* These are not as open as a public blockchain.
* They are only available to certain authorized users.
* These blockchains are operated in a closed network.
* Several people within a company/organization are allowed to participate in this kind of network.

**Advantages:**

* **Its small size results in a high transaction rate.** Each node's verification takes less time.
* **We are able to modify the scalability of the system.** You can manually set the network size.
* **As a result of confidentiality concerns, privacy has increased.**
* **Having only a few users access the transaction improves the network's performance.**

**Disadvantages:**

* Nodes of this type are limited, so manipulating them is possible. It is more difficult to secure these blockchains.
* Since it's centrally managed, trust building is one of its main disadvantages. A company can use this to commit malpractice.
* There are only a few nodes in the blockchain system, so if any of them go offline, the whole system can be compromised.

**A blockchain can be a great asset to secure information without exposing it to the public eye with proper security and maintenance.** In addition to internal audits, voting, and asset management, companies use them to track company assets. There are several types of private blockchains, such as Hyperledger and Corda.

### **3. Hybrid Blockchain** <a href="#id-3.-hybrid-blockchain" id="id-3.-hybrid-blockchain"></a>

A mixed blockchain contains parts that are controlled by one organization and parts that are made accessible to the public as a public blockchain.

Public and private blockchains are combined in it.

System permissions are granted and revoked.

Smart contracts provide access to information for users

No transaction can be altered by a primary entity even if it owns a hybrid blockchain

**Advantages**:

1. This blockchain is most advantageous due to its hybrid nature. 51% of users are unable to access the network, so it cannot be hacked
2. Several nodes verify the transaction, which makes transactions inexpensive. Therefore, there is a reduction in computational cost since all the nodes are not involved in verification.
3. Its architecture is highly customizable while maintaining integrity, security, and transparency.
4. The operation allows the participant in the blockchain to choose which transaction to make public, as well as which transactions can be made private.

**Disadvantages**:

1. Efficiency: Not everyone has the means to implement a hybrid blockchain. As far as maintenance is concerned, the organization also has some difficulties.
2. It is possible to hide information from the user because of transparency. An organization's decision as to whether to grant access to the hybrid blockchain depends on the organization's policies.
3. As this blockchain has a closed ecosystem, there are no incentives for users to join the network.

**The solution provides a greater solution for the health care industry, government, real estate, and financial services.** It allows public access to data while shielding it from private disclosure. Blockchains that combine Blockchains and Cryptocurrencies are Ripple and XRP.

### **4. Cryptocurrency Consortium**

The approach solves the needs of the organization creatively. This blockchain validates the transaction and also initiates or receives transactions.

* It is also called Federated Blockchain.
* Organizations can use this method to solve their problems.
* Public and private parts of the site are both available.
* Unlike the first type, this type involves more than one organization managing the blockchain.

**Advantages:**

* **Verification is faster because there are fewer users.** Organizations will benefit from the high speed of this.
* **It can be decentralized at every level with multiple organizations taking part.** Security is increased by decentralized authority.
* **The information of the checked blocks is not disclosed to the public.** It can be accessed by any blockchain member.
* **Various blockchains provide varying levels of flexibility.** Decisions can be taken faster because it is not an extremely large decision.

**Disadvantages:**

* **It is less flexible because it has the approval of all members.** The interest visions of one or more organizations can differ because they are involved in the same project.
* **A corrupt organization can use it to hack into the system.** The information that organizations hide from their users may be classified as proprietary.
* **If few nodes are compromised, there is a greater chance of a blockchain being vulnerable**

**There is high potential in businesses, banks, and other payment processors for this technology.** The food tracking system for the organizations frequently collaborates with their sectors, making it the ideal solution for them to use. The consortium Blockchains Tendermint and Multichain are examples.


# Consensus Mechanism

## Consensus Mechanism

**What is consensus?**&#x41; consensus is a general agreement. An example would be a group of people going to the cinema. Whenever there is no disagreement about a film choice, a consensus is reached. If there is disagreement, the group must have the means to decide which film to see. There is a possibility that the group will eventually split in extreme cases.Ethereum's blockchain is formalized, and reaching consensus is defined as at least 66% of network nodes agreeing on the global state.**What is consensus mechanism?**&#x41;s a whole, consensus mechanisms refer to the protocols, incentives, and ideas that allow a network of nodes to agree on the state of a blockchain.Ethereum uses a proof-of-stake-based consensus mechanism that derives its crypto-economic security from a set of rewards and penalties applied to capital locked by stakers. It creates an extremely high cost to attack the Bitcoin network and encourages stakeholder to operate honest validators.Then, there is a protocol that governs how honest validators are selected to propose or validate blocks, process transactions and vote for their view of the head of the chain. In the rare situations where multiple blocks are in the same position near the head of the chain, there is a fork-choice mechanism that selects blocks that make up the 'heaviest' chain, measured by the number of validators that voted for the blocks weighted by their staked ether balance.To achieve consensus, some concepts are not explicitly outlined in code, such as out-of-band social coordination as a last line of defense against network attacks.These components together form the consensus mechanism.**TYPES OF CONSENSUS MECHANISMSProof-of-work based**Like Bitcoin, Ethereum once used a proof-of-work (PoW) based consensus protocol.**Block creation**The validation process creates blocks. For each slot, a validator is randomly selected to propose the block. 'Execution payloads' are requested from both consensus and execution clients. They wrap this in consensus data to form a block, which they send to other nodes on the Ethereum network. This block production is rewarded in ETH. In rare cases when multiple possible blocks exist for a single slot, or nodes hear about blocks at different times, the fork choice algorithm picks the block that forms the chain with the greatest weight of attestations (where weight is the number of validators attesting scaled by their ETH balance).**Security**The network is secure due to the fact that it would require 51% of the network's computing power to create a fraudulent chain. This would require such huge investments in equipment and energy; you're likely to spend more than you'd gain.**Proof-of-stake based**Ethereum uses a proof-of-stake (PoS)-based consensus algorithm.**Block creation**Proof-of-stake is done by validators who have staked ETH to participate in the system. A validator is chosen at random to create new blocks, share them with the network and earn rewards. Instead of needing to do intense computational work, you simply need to have staked your ETH in the network. This is what incentivises healthy network behaviour.**Security**A proof-of-stake system is crypto-economically secure because an attacker trying to control the chain must destroy a massive amount of ETH. A system of rewards incentivizes individual stakers to behave honestly, and penalties disincentivize stakers from acting maliciously.


# Bitcoin

Introduction:-

The blockchain is a distributed, public ledger that contains the history of every bitcoin transaction. Anyone can download a copy of the blockchain, and it can be inspected to trace the path of bitcoins from one bitcoin transaction to another. It should be noted that while there is a record of every bitcoin transaction ever made, these transactions are not inherently linked to real life identities. For this reason, Bitcoin is considered pseudonymous.

Bitcoins themselves are not files stored on your computer's hard drive like MP3s or PDFs. Rather "owning bitcoins", means owning a bitcoin address, which has a balance recorded on the blockchain. What it means to own a bitcoin address is to control the associated Private Key, and therefore allow the signing of transactions.

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FxEBnATohAQMlVaN71RHy%2Fbitcoin-cryptocurrency.jpeg?alt=media&amp;token=bdb2c03a-e928-41a9-8f58-ffcf106d4ebc" alt=""><figcaption></figcaption></figure>

**The Bitcoin blockchain is an amalgamation of Bitcoin**&#x20;

[BTC](https://www.blockchain.com/explorer)

![tickers down](https://cointelegraph.com/assets/img/tickers/tickers_down.svg)[$45,791 ](https://www.blockchain.com/explorer)and blockchain. A person or a group of people known as Satoshi Nakamoto created the Bitcoin protocol in 2008 to decentralize control of money when centralized entities had failed the world. A publication called the Bitcoin white paper outlined a set of computational rules that determined a new type of distributed database: the blockchain. The network was launched in January 2009.

The most well-known cryptocurrency, Bitcoin, is the one for which blockchain technology was created. Like the United States dollar, a cryptocurrency is a digital means of exchange that uses encryption techniques to oversee the establishment of monetary units and verify financial transfers.

The Bitcoin blockchain refers to the data stored in “blocks” of information that are then linked together in a permanent “chain.” A block is a collection of Bitcoin transactions from a specific period. Stacks of blocks are stockpiled on top of each other, with each new block relying on the previous ones. As a result, a chain of blocks is formed, giving rise to the word “blockchain.”

Every time a new block is added, it makes the previous blocks unmodifiable. This ensures that each block is more secure over time, and it is an example of how Bitcoin technology is changing how banking and financial transactions are being made.&#x20;

Bitcoin blockchain, however, is much more than cryptocurrency: It is the technology that most cryptocurrencies are built on, including Bitcoin. The Bitcoin blockchain is unique because it ensures that all transactions are accurate. Every action in the blockchain is recorded and there is nothing that is left out of the network. Once an action is recorded and stored in one of the information blocks, it is time-stamped and secured, and the entire record is available to anyone in the system.

The Bitcoin blockchain is also decentralized, meaning it is not stored in one master computer or controlled by one company. It is distributed on many computers that are in the network.

In the Bitcoin blockchain, there are codes called a hash. A hash is unique to each block in the blockchain. Hashing allows every network user to identify each block and directs them to move in the chain since every block has its own hash and a previous block's hash.

With the latter in mind, the critical parts of the blockchain include records, block, hash and chain. Block records and transactional records are the two types of records in the blockchain. A block contains the most recent Bitcoin transactions that have not yet been recorded in any previous block. Transaction records include the asset, price and ownership data that are recorded, approved and settled across all nodes in seconds.&#x20;

In essence, a hash is a fixed-length string generated after transforming any length of input data in the blockchain network, a block is similar to a page in a ledger or record book and a chain refers to blocks linked together in a network.

### Short story of Bitcoin blockchain <a href="#contentref_0" id="contentref_0"></a>

The idea of blockchain technology was introduced in 1991 by Stuart Haber and W. Scott Stornetta in their paper “How to Time-Stamp a Digital Document.” In this paper, they explained the use of a continuous chain of timestamps to record information securely.

Bitcoin was created largely to facilitate the exchange of Bitcoin cryptocurrency. However, early adopters and inventors rapidly discovered that it had far greater potential. With this in mind, they designed Bitcoin's blockchain to store more than just data on the token's movement.

Bitcoin technology uses peer-to-peer (P2P) transactions, making it possible to function without any bank or third party to manage each financial movement. It allows online payments to be sent directly from one party to another without going through any financial institution.

The term peer-to-peer means that the computers that are part of the network are equal to each other, that there are no “special” nodes and that all nodes share the burden of providing network services. It is made up of thousands of Bitcoin nodes that run the protocol. The protocol is responsible for establishing and safeguarding the blockchain.

The formation of a peer-to-peer network is possible because users' data is related to the person or entity they are interacting with, and they are in charge of keeping the distributed network up and running. The information regarding the individual or entity is then passed from their Bitcoin wallet to their location and IP address, which represents peer-to-peer Bitcoin interaction.

### What is needed to make the Bitcoin blockchain work? <a href="#contentref_1" id="contentref_1"></a>

Bitcoin represents a digital, trustless form of money, alongside a movement to decentralize financial services. Before Bitcoin, there was a need for a trusted third party to keep a ledger — the record-keeping system of a company's or person's financial data — to record who owned how much. Everyone has a copy of this ledger with the Bitcoin network, so there is no need for third parties.

Every Bitcoin transaction happens in the Bitcoin blockchain network, which is the digital space where Bitcoin mining and hash power generation occur. Hashing power is the processing power used by your computer or hardware to perform and solve various hashing algorithms. These algorithms are used to create new cryptocurrencies and allow them to trade with one another. This process is called mining.

Usually, Bitcoin owners purchase their cryptocurrency supply through a cryptocurrency exchange, a platform that facilitates transactions of Bitcoin and other cryptocurrencies. The decentralized ledger is what makes the blockchain network. The latter shows that Bitcoin is a piece of software, a set of processes in which participants perform different tasks.

A blockchain is a digital ledger of duplicated transactions distributed across the blockchain's network of computer systems. Each block on the chain contains several transactions, and whenever a new transaction occurs on the blockchain, a record of that transaction is added to the ledger of each participant.

This distributed database is managed by multiple participants using a technology called distributed ledger technology (DLT). Blockchain is a type of DLT in which transactions are recorded using an immutable cryptographic signature known as a hash. The transactions are then organized into blocks. Each new block includes a hash of the preceding one, effectively chaining them together, which is why distributed ledgers are commonly referred to as blockchains.

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2Fs0uKJuu7mchUUUrybd91%2Fbitcoin%20transaction%20.webp?alt=media&amp;token=1a56b5ee-c40b-40e1-949a-808ff2a3908b" alt=""><figcaption></figcaption></figure>

The blockchain works as a ledger, tracking every Bitcoin transaction, and is self-verifying, meaning that the entire network of nodes — different computers participating in the network — will constantly check and secure every movement. Here is where the “miners” come into the game: Their computers do the heavy lifting of maintaining the chain and thus, receive Bitcoin as a reward. These rules, collectively, are the Bitcoin protocol.

Bitcoin miners refer to the high-powered computers solving complex math problems to mint a coin. Miners are network-dedicated machines that verify all transactions and block any malicious actors. Bitcoin miners compile as many transactions as possible into a block, then verify the block and add it to the chain of previous blocks using a mathematical method. For providing their computing power to the network, miners are paid in newly minted Bitcoin.

### How does the Bitcoin blockchain work? <a href="#contentref_2" id="contentref_2"></a>

A blockchain is a type of database which is a collection of information stored on a computer system electronically. What is kept in databases, information or data is usually structured in a table format that makes it easier to search and filter information. Databases are designed to store large amounts of information that can be accessed, filtered and edited easily and quickly by many users at any time.&#x20;

To do this, extensive databases house data on servers that are made of potent computers. Those servers can be built using hundreds and hundreds of computers. Why? To have the computational storage and power needed for many users to access the database simultaneously. This is the difference from a database too, let's say, a storage cloud-like drive.&#x20;

Here’s how a blockchain differs from a database. The first difference is how data is structured. A database structures data into tables, while a blockchain collects information into groups, known as blocks, that hold data sets. Each block has a specific storage capacity that is chained onto the previous filled block when it gets filled, forming a chain of data. That's why it's called the blockchain: Millions of blocks filled with data are chained together.

This system means that every blockchain is a database that is more complex since it creates an irreversible chainline of data when implemented in a decentralized system. When one block is filled, it is unchangeable and becomes part of a timeline, and so, each block on the chain has an exact timestamp when added to the chain.

Thus, the goal of the blockchain is to allow digital information to be recorded and distributed, but not edited. That's why it is not a database per se; no one can change it once it is filled and chained. With the appearance of Bitcoin technology, blockchain had its first actual application.

### Reducing risks <a href="#contentref_3" id="contentref_3"></a>

Using a blockchain network comes with a lot of advantages. First, the accuracy of the chain. Transactions that are part of the blockchain have to be approved by thousands of thousands of computers. This removes all human involvement in the verification, which means there are fewer human errors, as well as a more accurate record of information.

But, what if one of the computers in the network makes a computational mistake? The error would only be in one copy of the blockchain. For it to spread, at least 51% of the network would need to have the same mistake, which is very unlikely.

Another advantage is that blockchain eliminates the need for third-party verifiers. Any member of the Bitcoin network can check and verify the blockchain at any time.

Blockchain data is decentralized, which means that it is not stored in a central location but instead copied and spread across a vast network of computers. This makes it very hard for anyone to tamper with the data since a kicker, for example, would need access to all of the networks to compromise it fully.

Finally, an instrumental part of the blockchain is that, although anyone with an internet connection can see the list of the network's transaction history and access details about transactions, no one can access identifying information about the users that are making those transactions. Also, every time a transaction is recorded, it is verified by the network, meaning that the thousands of computers that compose it confirm if the details of the purchase are correct.&#x20;

### Blockchain vs. banks <a href="#contentref_4" id="contentref_4"></a>

Blockchain works very differently from a traditional bank since it is 100% decentralized and it relies on thousands of computers to verify its transactions. This means it runs 24/7, every day of the year. The most significant advantage of all of the Bitcoin blockchain is its transparency because the blockchain acts as a public ledger for every transaction made in the Bitcoin network.

Other differences are that the speed of the transactions is as little as 15 minutes or as much as over an hour, depending on the network's congestion. While card payments and check deposits can take from 24 to 72 hours.

The Bitcoin blockchain has variable fees, usually ranging from $0 to $50. While the fee is unrelated to the amount being transferred, it is determined by network circumstances at the moment and the transaction's data size. Because a block on the Bitcoin blockchain may only hold one megabyte (MB) of data, the number of transactions included in a single block is limited.&#x20;

Another difference is in the way of making transactions. While the blockchain allows anyone with an internet connection to make a transfer, banks need you to have an account, a mobile phone, or a computer.

All of these differences make blockchain technology a great disruptor of traditional finances and the banking industry. They are tamper-proof and decentralized, set-in-stone chains that not only reduce costs but create a transparent network in which users can feel empowered and safe.

### The limitations of the blockchain  <a href="#contentref_5" id="contentref_5"></a>

Although the blockchain comes with many benefits, like everything, it has its downsides. The first is that the blockchain can slow down when there are too many users on the network. It is also harder to scale due to its consensus method of work.

Another limitation is that data within the blockchain is immutable, you cannot go back and alter the previous block once it is written. Some may view it as an imitation that requires self-maintenance, which means that users have to maintain their own wallets or else they can lose access.&#x20;

A big limitation is that blockchain technology is still not mature. Also, it doesn´t offer interoperability with other blockchains and other financial systems, and is hard to integrate into legacy systems.

### Technical advances <a href="#contentref_6" id="contentref_6"></a>

#### Lightning Network <a href="#contentref_7" id="contentref_7"></a>

The Lightning Network (LN) permits participants to transfer BTC between each other without any fees using their digital wallets. A second layer is added to the Bitcoin network to enable transactions between parties off of the blockchain, which is called off-chain transactions. A second layer boosts throughput without compromising any of the original blockchain's decentralization or security features.

Lightning Network creates payment channels between two users in a distributed database so they can transact with each other, without all the other users receiving their information, defining off-chain transactions.

It is considered a game-changer in the cryptocurrency world since it has been designed to speed up transaction processing and decrease associated costs of the Bitcoin blockchain. It was conceived in 2015 and is being further developed and activated.&#x20;

However, researchers have cautioned that as the Lightning Network grows, it will become a more appealing target for attackers. Bitcoin on the developing payment network might be stolen if users aren't careful and it may be hard to ensure the safety of assets in the future.

According to experts from the Hebrew University of Jerusalem, Bitcoin that is currently locked in the Lightning Network payments channel, which is currently roughly $9 million in Bitcoin, might be [looted](https://www.forbes.com/sites/billybambrough/2020/07/09/bitcoins-lightning-network-is-struggling-to-overcome-fundamental-issues/?sh=5f8b3f615f77) by attackers. While the flaw has the potential to be serious, the researchers are optimistic that it is fixable in the long run.

#### SegWit <a href="#contentref_8" id="contentref_8"></a>

Segregated Witness, or SegWit, refers to a process change in how Bitcoin maintains transaction data in the blockchain. Segregate means to separate and witnesses are the transaction signatures. It was created to renew the way in which data is stored on Bitcoin's blockchain. This allows the network to hold more transactions in a single block, enhancing transaction throughput. SegWit went active on Bitcoin in August 2017 after the code for the update was released in 2015.

SegWit increases the block size limit of a blockchain by removing signature data from Bitcoin transactions. When parts of a transaction are removed, space gets freed and so does capacity to add more transactions to the chain.

SegWit not only improved Bitcoin's transaction processing speed but also solved a weakness in the protocol that allowed nodes to tamper with transaction malleability problems (TXIDs) on the network. By removing what is known as “signature data” or “the witness data” from the input field of a block, Segwit increased the number of transactions that could fit into a block and fixed the transaction malleability flaw.

On the Bitcoin network, the SegWit update was introduced as a soft fork in August 2017. A soft fork is a backward-compatible update that allows upgraded nodes to communicate with non-upgraded nodes. A soft fork usually includes a new rule that does not conflict with the existing ones. However, due to the high cost of running a node (especially in developing countries), the upgrade was put on hold on November 8, 2017.

#### Taproot <a href="#contentref_9" id="contentref_9"></a>

Bitcoin Core developer Greg Maxwell proposed the Taproot improvement in January 2018. The 90% criterion of blocks mined with a support signal from miners was met three years later on June 12, 2021. It means that 1,815 of the 2,016 blocks mined throughout the two-week time frame had some encoded data left by miners to demonstrate their support for the upgrade.&#x20;

Taproot is a soft fork that improves Bitcoin's scripts to enhance privacy and increase anonymity on the network. When a user does not use Taproot, anyone can detect transactions. When using Taproot, they can “cloak” their transactions. Taproot even makes it possible to hide that a Bitcoin script ran at all. As of October 2020, Taproot is merged with the Bitcoin Core library.&#x20;

One of the most significant changes to the network is the substitution of Schnorr signatures for Bitcoin's current elliptic curve digital signature technique (ECDSA). The ECDSA technique generates public keys from randomly generated private keys, which makes it impossible to determine a private key from a Bitcoin address or public key. Moreover, the Schnorr signature will free up space and bandwidth on the Bitcoin network by making transactions faster and smaller.&#x20;

By permitting discrete log contracts (DLCs), the Schnorr signature can help simplify complex smart contracts on the Bitcoin blockchain. The DLCs are a proposal to add a smart contract implementation to Bitcoin, allowing the establishment of simple, safe and easy-to-use blockchain oracles.

It may also aid in the scaling of layer-two payment channels such as the Lightning Network, which allows for immediate transactions on the Bitcoin network.


# Ethereum

### WHAT IS A BLOCKCHAIN? <a href="#what-is-a-blockchain" id="what-is-a-blockchain"></a>

A blockchain is a public database that is updated and shared across many computers in a network.

"Block" refers to data and state being stored in consecutive groups known as "blocks". If you send ETH to someone else, the transaction data needs to be added to a block to be successful.

"Chain" refers to the fact that each block cryptographically references its parent. In other words, blocks get chained together. The data in a block cannot change without changing all subsequent blocks, which would require the consensus of the entire network.

Every computer in the network must agree upon each new block and the chain as a whole. These computers are known as "nodes". Nodes ensure everyone interacting with the blockchain has the same data. To accomplish this distributed agreement, blockchains need a consensus mechanism.

Ethereum uses a [proof-of-stake-based consensus mechanism](https://ethereum.org/developers/docs/consensus-mechanisms/pos). Anyone who wants to add new blocks to the chain must stake ETH - the native currency in Ethereum - as collateral and run validator software. These "validators" can then be randomly selected to propose blocks that other validators check and add to the blockchain. There is a system of rewards and penalties that strongly incentivize participants to be honest and available online as much as possible.

If you would like to see how blockchain data is hashed and subsequently appended to the history of block references, be sure to check out [this demo(opens in a new tab)](https://andersbrownworth.com/blockchain/blockchain) by Anders Brownworth and watch the accompanying video below.

**Watch Anders explain hashes in blockchains:**

[**https://youtu.be/\_160oMzblY8**](https://youtu.be/_160oMzblY8)

**WHAT IS ETHEREUM?**

Ethereum is a blockchain with a computer embedded in it. It is the foundation for building apps and organizations in a decentralized, permissionless, censorship-resistant way.

In the Ethereum universe, there is a single, canonical computer (called the Ethereum Virtual Machine, or EVM) whose state everyone on the Ethereum network agrees on. Everyone who participates in the Ethereum network (every Ethereum node) keeps a copy of the state of this computer. Additionally, any participant can broadcast a request for this computer to perform arbitrary computation. Whenever such a request is broadcast, other participants on the network verify, validate, and carry out ("execute") the computation. This execution causes a state change in the EVM, which is committed and propagated throughout the entire network.

Requests for computation are called transaction requests; the record of all transactions and the EVM's present state gets stored on the blockchain, which in turn is stored and agreed upon by all nodes.

Cryptographic mechanisms ensure that once transactions are verified as valid and added to the blockchain, they can't be tampered with later. The same mechanisms also ensure that all transactions are signed and executed with appropriate "permissions" (no one should be able to send digital assets from Alice's account, except for Alice herself).

### WHAT IS ETHER? <a href="#what-is-ether" id="what-is-ether"></a>

**Ether (ETH)** is the native cryptocurrency of Ethereum. The purpose of ETH is to allow for a market for computation. Such a market provides an economic incentive for participants to verify and execute transaction requests and provide computational resources to the network.

Any participant who broadcasts a transaction request must also offer some amount of ETH to the network as a bounty. The network will award this bounty to whoever eventually does the work of verifying the transaction, executing it, committing it to the blockchain, and broadcasting it to the network.

The amount of ETH paid corresponds to the resources required to do the computation. These bounties also prevent malicious participants from intentionally clogging the network by requesting the execution of infinite computation or other resource-intensive scripts, as these participants must pay for computation resources.

ETH is also used to provide crypto-economic security to the network in three main ways: 1) it is used as a means to reward validators who propose blocks or call out dishonest behavior by other validators; 2) It is staked by validators, acting as collateral against dishonest behavior—if validators attempt to misbehave their ETH can be destroyed; 3) it is used to weigh 'votes' for newly proposed blocks, feeding into the fork-choice part of the consensus mechanism.

### WHAT ARE SMART CONTRACTS? <a href="#what-are-smart-contracts" id="what-are-smart-contracts"></a>

In practice, participants don't write new code every time they want to request a computation on the EVM. Rather, application developers upload programs (reusable snippets of code) into EVM state, and users make requests to execute these code snippets with varying parameters. We call the programs uploaded to and executed by the network smart contracts.

At a very basic level, you can think of a smart contract like a sort of vending machine: a script that, when called with certain parameters, performs some actions or computation if certain conditions are satisfied. For example, a simple vendor smart contract could create and assign ownership of a digital asset if the caller sends ETH to a specific recipient.

Any developer can create a smart contract and make it public to the network, using the blockchain as its data layer, for a fee paid to the network. Any user can then call the smart contract to execute its code, again for a fee paid to the network.

Thus, with smart contracts, developers can build and deploy arbitrarily complex user-facing apps and services such as: marketplaces, financial instruments, games, etc.


# Accounts

## ETHEREUM ACCOUNTS: <a href="#top" id="top"></a>

An Ethereum account is an entity with an ether (ETH) balance that can send transactions on Ethereum. Accounts can be user-controlled or deployed as smart contracts.

### PREREQUISITES <a href="#prerequisites" id="prerequisites"></a>

To help you better understand this page, we recommend you first read through our [introduction to Ethereum](https://ethereum.org/developers/docs/intro-to-ethereum).

### ACCOUNT TYPES <a href="#types-of-account" id="types-of-account"></a>

Ethereum has two account types:

* Externally-owned account (EOA) – controlled by anyone with the private keys
* Contract account – a smart contract deployed to the network, controlled by code. Learn about [smart contracts](https://ethereum.org/developers/docs/smart-contracts)

Both account types have the ability to:

* Receive, hold and send ETH and tokens
* Interact with deployed smart contracts

#### Key differences <a href="#key-differences" id="key-differences"></a>

**Externally-owned**

* Creating an account costs nothing
* Can initiate transactions
* Transactions between externally-owned accounts can only be ETH/token transfers
* Made up of a cryptographic pair of keys: public and private keys that control account activities

**Contract**

* Creating a contract has a cost because you're using network storage
* Can only send transactions in response to receiving a transaction
* Transactions from an external account to a contract account can trigger code which can execute many different actions, such as transferring tokens or even creating a new contract
* Contract accounts don't have private keys. Instead, they are controlled by the logic of the smart contract code

### AN ACCOUNT EXAMINED <a href="#an-account-examined" id="an-account-examined"></a>

Ethereum accounts have four fields:

* `nonce` – A counter that indicates the number of transactions sent from an externally-owned account or the number of contracts created by a contract account. Only one transaction with a given nonce can be executed for each account, protecting against replay attacks where signed transactions are repeatedly broadcast and re-executed.
* `balance` – The number of wei owned by this address. Wei is a denomination of ETH and there are 1e+18 wei per ETH.
* `codeHash` – This hash refers to the *code* of an account on the Ethereum virtual machine (EVM). Contract accounts have code fragments programmed in that can perform different operations. This EVM code gets executed if the account gets a message call. It cannot be changed, unlike the other account fields. All such code fragments are contained in the state database under their corresponding hashes for later retrieval. This hash value is known as a codeHash. For externally owned accounts, the codeHash field is the hash of an empty string.
* `storageRoot` – Sometimes known as a storage hash. A 256-bit hash of the root node of a Merkle Patricia trie that encodes the storage contents of the account (a mapping between 256-bit integer values), encoded into the trie as a mapping from the Keccak 256-bit hash of the 256-bit integer keys to the RLP-encoded 256-bit integer values. This trie encodes the hash of the storage contents of this account, and is empty by default.

<figure><img src="https://3495787697-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F3iD8qFVyjPp1N1FbL3AL%2Fuploads%2FjSZfI94A8nCo8YmQdEaL%2Faccounts.png?alt=media&amp;token=f9211dfd-a561-41e4-ab6b-f753571aee3d" alt=""><figcaption><p><em>Diagram adapted from</em> <a href="https://takenobu-hs.github.io/downloads/ethereum_evm_illustrated.pdf"><em>Ethereum EVM illustrated(opens in a new tab)</em></a></p></figcaption></figure>

### EXTERNALLY-OWNED ACCOUNTS AND KEY PAIRS <a href="#externally-owned-accounts-and-key-pairs" id="externally-owned-accounts-and-key-pairs"></a>

An account is made up of a cryptographic pair of keys: public and private. They help prove that a transaction was actually signed by the sender and prevent forgeries. Your private key is what you use to sign transactions, so it grants you custody over the funds associated with your account. You never really hold cryptocurrency, you hold private keys – the funds are always on Ethereum's ledger.

This prevents malicious actors from broadcasting fake transactions because you can always verify the sender of a transaction.

If Alice wants to send ether from her own account to Bob’s account, Alice needs to create a transaction request and send it out to the network for verification. Ethereum’s usage of public-key cryptography ensures that Alice can prove that she originally initiated the transaction request. Without cryptographic mechanisms, a malicious adversary Eve could simply publicly broadcast a request that looks something like “send 5 ETH from Alice’s account to Eve’s account,” and no one would be able to verify that it didn’t come from Alice.

### ACCOUNT CREATION <a href="#account-creation" id="account-creation"></a>

When you want to create an account most libraries will generate you a random private key.

A private key is made up of 64 hex characters and can be encrypted with a password.

Example:

`fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd036415f`

The public key is generated from the private key using the [Elliptic Curve Digital Signature Algorithm(opens in a new tab)](https://wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm). You get a public address for your account by taking the last 20 bytes of the Keccak-256 hash of the public key and adding `0x` to the beginning.

The following example shows how to use a signing tool called [Clef(opens in a new tab)](https://geth.ethereum.org/docs/tools/clef/introduction) to generate a new account. Clef is an account management and signing tool that comes bundled with the Ethereum client, [Geth(opens in a new tab)](https://geth.ethereum.org/). The `clef newaccount` command creates a new key pair and saves them in an encrypted keystore.

```
> clef newaccount --keystore <path>
Please enter a password for the new account to be created:
> <password>
------------
INFO [10-28|16:19:09.156] Your new key was generated       address=0x5e97870f263700f46aa00d967821199b9bc5a120
WARN [10-28|16:19:09.306] Please backup your key file      path=/home/user/go-ethereum/data/keystore/UTC--2022-10-28T15-19-08.000825927Z--5e97870f263700f46aa00d967821199b9bc5a120
WARN [10-28|16:19:09.306] Please remember your password!
Generated account 0x5e97870f263700f46aa00d967821199b9bc5a120
```

[Geth documentation(opens in a new tab)](https://geth.ethereum.org/docs)

It is possible to derive new public keys from your private key but you cannot derive a private key from public keys. This means it's vital to keep a private key safe and, as the name suggests, **PRIVATE**.

You need a private key to sign messages and transactions which output a signature. Others can then take the signature to derive your public key, proving the author of the message. In your application, you can use a javascript library to send transactions to the network.

### CONTRACT ACCOUNTS: <a href="#contract-accounts" id="contract-accounts"></a>

Contract accounts also have a 42 character hexadecimal address:

Example:

`0x06012c8cf97bead5deae237070f9587f8e7a266d`

The contract address is usually given when a contract is deployed to the Ethereum Blockchain. The address comes from the creator's address and the number of transactions sent from that address (the “nonce”).

### VALIDATOR KEYS <a href="#validators-keys" id="validators-keys"></a>

There is also another type of key in Ethereum, introduced when Ethereum switched from proof-of-work to proof-of-stake based consensus. These are 'BLS' keys and they are used to identify validators. These keys can be efficiently aggregated to reduce the bandwidth required for the network to come to consensus. Without this key aggregation the minimum stake for a validator would be much higher.

### A NOTE ON WALLETS <a href="#a-note-on-wallets" id="a-note-on-wallets"></a>

An account is not a wallet. An account is the keypair for a user-owned Ethereum account. A wallet is an interface or application that lets you interact with your Ethereum account.


# Solidity

## What is Solidity Programming:

Dapps otherwise referred to as Decentralized Applications are applications built on the open-source, peer-to-peer network of Ethereum Blockchain which uses smart contracts and front-end user interfaces to create decentralized platforms.

Developing a Dapp, like any other app, requires programming and executing code on the system. Solidity programming stands apart from the other programming languages and is the programming language of choice in Ethereum.&#x20;

Solidity is a brand-new programming language developed by Ethereum, the second-largest cryptocurrency market by capitalization.&#x20;

So if you are interested in exploring more about Solidity Programming and its concepts, then you are at the right place. In this tutorial on Solidity Programming, you will cover various important components of Solidity Programming.

### What is Solidity Programming? <a href="#what_is_solidity_programming" id="what_is_solidity_programming"></a>

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

* It's used to create smart contracts that implement business logic and generate a chain of transaction records in the blockchain system.
* It acts as a tool for creating machine-level code and compiling it on the Ethereum Virtual Machine (EVM).
* It has a lot of similarities with C and [C++](https://www.simplilearn.com/c-plus-plus-programming-for-beginners-article) and is pretty simple to learn and understand. For example, a “main” in C is equivalent to a “contract” in Solidity.

Like other programming languages, Solidity programming also has variables, functions, classes, arithmetic operations, string manipulation, and many other concepts.

Like other programming languages, Solidity programming also has variables, functions, classes, arithmetic operations, string manipulation, and many other concepts.

<img src="https://www.simplilearn.com/ice9/free_resources_article_thumb/Solidity_Programming_1.png" alt="Solidity_Programming_1" height="165" width="400">

### Evolution of Solidity Programming <a href="#evolution_of_solidity_programming" id="evolution_of_solidity_programming"></a>

Solidity is a relatively new language that is rapidly growing.

* Solidity is currently the core language on Ethereum and other private blockchains operating on competing platforms, such as Monax and its [Hyperledger](https://www.simplilearn.com/tutorials/blockchain-tutorial/hyperledger-fabric) Burrow blockchain which uses Tendermint for consensus.&#x20;
* SWIFT has created a proof of concept that runs on Burrow and uses Solidity.

<img src="https://www.simplilearn.com/ice9/free_resources_article_thumb/Solidity_Programming_2.jfif" alt="Solidity_Programming_2." height="506" width="900">

### What are EVM and Smart Contracts? <a href="#what_are_evm_and_smart_contracts" id="what_are_evm_and_smart_contracts"></a>

#### EVM or Ethereum Virtual Machine&#x20;

* The Ethereum Virtual Machine (EVM) provides a runtime environment for Ethereum smart contracts.
* It is primarily concerned with ensuring the security and execution of untrusted programs through the use of an international network of public nodes.
* EVM is specialized in preventing Denial-of-Service attacks and certifies that the programs do not have access to each other's state, as well as establishing communication, with no possible interference.

<img src="https://www.simplilearn.com/ice9/free_resources_article_thumb/Solidity_Programming_3.png" alt="Solidity_Programming_3" height="343" width="524">

#### Smart Contracts&#x20;

* Smart contracts refer to high-level program codes compiled into EVM before being posted to the Ethereum blockchain for execution.
* It enables you to conduct trustworthy transactions without the involvement of a third party; these transactions are traceable and irreversible.
* Programming languages commonly used to create and write smart contracts are Serpent, Solidity, Mutan, and LLL.

<img src="https://www.simplilearn.com/ice9/free_resources_article_thumb/Solidity_Programming_4.png" alt="Solidity_Programming_4." height="425" width="800">

### Data Types of Solidity Programming <a href="#data_types_of_solidity_programming" id="data_types_of_solidity_programming"></a>

It supports all the common [data types](https://www.simplilearn.com/what-is-data-article) seen in other OOP languages, such as,

* Boolean - The Boolean data type returns ‘1' when the condition is true and ‘0' when it is false, depending on the status of the condition.
* Integer - You can sign or unsign integer values in Solidity. It also supports runtime exceptions and the ‘uint8' and ‘uint256' keywords.
* String - Single or double quotes can denote a string.
* Modifier - Before executing the code for a smart contract, a modifier often verifies that any condition is rational.
* Array - The syntax of Solidity programming is like that of other OOP languages, and it supports both single and multidimensional arrays.

Apart from that, Solidity programming allows you to "Map" data structures with enums, operators, and hash values to return values stored in specific storage places.

<img src="https://www.simplilearn.com/ice9/free_resources_article_thumb/Solidity_Programming_5.png" alt="Solidity_Programming_5." height="425" width="424">

### How to Get Started With Solidity Programming? <a href="#how_to_get_started_with_solidity_programming" id="how_to_get_started_with_solidity_programming"></a>

#### Version Pragma

<img src="https://www.simplilearn.com/ice9/free_resources_article_thumb/Solidity_Programming_6.png" alt="Solidity_Programming_6" height="84" width="325">

* Pragmas are directives to the compiler about how to handle the code. Every line of solidity source code should begin with a "version pragma," which specifies which version of the solidity compiler to use.
* This prevents the code from being incompatible with future compiler versions that may introduce changes.

#### The Contract Keyword

<img src="https://www.simplilearn.com/ice9/free_resources_article_thumb/Solidity_Programming_7.png" alt="Solidity_Programming_7" height="111" width="246">

* The contract keyword declares a contract that encapsulates the code.

#### State/Declare Variables

<img src="https://www.simplilearn.com/ice9/free_resources_article_thumb/Solidity_Programming_84.png" alt="Solidity_Programming_8" height="113" width="257">

* State variables are written on the Ethereum Blockchain and are permanently maintained in contract storage.
* The line uint public var1 declares a state variable of type uint named var1 (unsigned integer of 256 bits), it is very similar to adding a slot in a database.

#### A Function Declaration

<img src="https://www.simplilearn.com/ice9/free_resources_article_thumb/Solidity_Programming_9.png" alt="Solidity_Programming_9" height="96" width="377">

* This is a function named “set” of access modifier type public which takes a variable a and variable b of data type uint as a parameter.
* This was an example of a simple smart contract that updates the value of var1 and var2. Anyone with access to the Ethereum blockchain can use the set function to change the value of var1 and var2.
* By adding the values of the variables var1 and var2, it can calculate the variable sum.
* It will retrieve and print the value of the state variable sum using the “get” function.

### How to Execute the Code <a href="#how_to_execute_the_code" id="how_to_execute_the_code"></a>

You can execute a Solidity Program in two ways -&#x20;

1. Offline Mode
2. Online Mode

#### Offline Mode&#x20;

To operate a Solidity smart contract in Offline mode, it must meet three conditions and follow four essential actions:

* **Conditions**

1. Download and install node.js.
2. Install [Truffle](https://www.trufflesuite.com/truffle) globally.
3. Install [ganache-cli](https://www.trufflesuite.com/ganache).

<img src="https://www.simplilearn.com/ice9/free_resources_article_thumb/Solidity_Programming_10.png" alt="Solidity_Programming_10" height="206" width="380">

* **Actions**

1. Create a truffle project and set up a development network for it.
2. Develop and deploy a smart contract for it.
3. From the Truffle console, interact with the smart contract.
4. Create tests to evaluate Solidity's primary features.

#### Online Mode&#x20;

In the Online Mode, the Remix IDE is typically used to compile and run Solidity smart contracts.

<img src="https://www.simplilearn.com/ice9/free_resources_article_thumb/Solidity_Programming_11.png" alt="" height="400" width="420">

### Advantages of Solidity Programming <a href="#advantages_of_solidity_programming" id="advantages_of_solidity_programming"></a>

Apart from the primary functionality of Solidity Programming, there are many other features provided by Solidity programming that cause it to have an edge over other Ethereum based languages.

* Apart from fundamental data types, Solidity programming also allows complex data types and member variables.
* It provides an Application Binary Interface (ABI) to enable type safety. If the compiler discovers a data type mismatch for any variable, the ABI generates an error.
* It refers to the ‘Natural Language Specification,' which is used to turn user-centric specifications into language that machines can understand.

### Conclusion <a href="#conclusion" id="conclusion"></a>

In this tutorial, you came across everything about Solidity Programming and its concepts like how it evolved, what EVM and Smart Contracts are, what the Data Types in Solidity Programming are, and what its advantages are.

Do you have any questions for us? Please  make sure that you share them with us in the comments section of this Solidity Programming article; our experts will review and revert to you on them very soon.&#x20;


# Proof of Stake

The Proof-of-Stake mechanism in a blockchain is used to create new blocks and process transactions. A consensus mechanism validates and maintains the security of entries in a distributed database. Using cryptocurrency as an example, we call the database a blockchain-so a consensus mechanism secures the blockchain.

#### Key Takeaways <a href="#key-takeaways" id="key-takeaways"></a>

* Proof-of-stake (POS) is a cryptography technique that rewards cryptocurrency owners for staked coins that are used to validate block transactions.
* To validate and add new blocks to a blockchain, Proof-of-Stake (POS) was created to replace Proof-of-Work (POW).
* Mining mechanisms require miners to solve cryptographic puzzles, while PoS mechanisms require validators to stake tokens to earn transaction fees.
* It is more difficult for a network to be attacked with Proof-of-Stake (POS), since it structures compensation so that attack is less beneficial.
* Block writers on the blockchain are picked at random, with stake positions having higher odds.

### Goals of Proof-of-Stake <a href="#goals-of-proof-of-stake" id="goals-of-proof-of-stake"></a>

Proof-of-stake (PoS) has several advantages over proof-of-work (PoW). One of the biggest advantages is that it reduces network congestion and environmental sustainability concerns. PoW encourages individuals to seek ways to gain an advantage, which can lead to high energy consumption and other associated costs. In contrast, PoS substitutes staking for computational power, which reduces energy consumption and makes mining less energy-intensive. PoS allows an individual's mining ability to be randomly determined by the network, eliminating the need for massive farms of single-purpose hardware to gain an advantage. Peercoin was the first cryptocurrency to adopt the PoS method, followed by Nxt, Blackcoin, and ShadowCoin.

#### Proof-of-Stake Security <a href="#proof-of-stake-security" id="proof-of-stake-security"></a>

Proof-of-stake (PoS) has been marketed as a solution to the energy consumption and centralization concerns of proof-of-work (PoW). However, there are concerns about the possibility of a 51% attack in a PoS network, which is when an individual or group owns 51% or more of the cryptocurrency staked and can potentially alter the blockchain with that majority.

While this is a legitimate concern, it is very expensive to control 51% of staked cryptocurrency, making it less likely to occur. In addition, the honest validators in a PoS network could refuse to accept the altered blockchain if a 51% attack did occur.

Most PoS systems also include additional security features as part of their design, although they are not always advertised to avoid potential vulnerabilities being exploited. Overall, blockchain and PoS mechanisms are naturally secure, and PoS offers a more energy-efficient and environmentally sustainable alternative to PoW.


# Transactions

The term transaction refers to the transfer of funds between two accounts. The payload can be binary data or ether.

Blockchain transactions are transfers of value. Transactions are when one person gives another a certain amount of cryptocurrency they own.

For crypto transactions on the blockchain, you need a wallet, a program that keeps track of your crypto and enables you to transact with it, and which is linked to the blockchain. An individual wallet is protected by a special cryptographic method based on a pair of unique but connected keys: a private key and a public key.

For a user to receive funds, a public key (also known as an address) must be shared. Contrary to public keys, private keys must be kept secret, just like the pin number on your bank card, since they authorize the spending of funds.

By using their wallet, users can authorize, sign, and transfer value to new owners. After broadcasting, the transaction is added to the blockchain.

A transaction consists of three main components:

The term transaction refers to the transfer of funds between two accounts. The payload can be binary data or ether.

Blockchain transactions are transfers of value. Transactions are when one person gives another a certain amount of cryptocurrency they own.

For crypto transactions on the blockchain, you need a wallet, a program that keeps track of your crypto and enables you to transact with it, and which is linked to the blockchain. An individual wallet is protected by a special cryptographic method based on a pair of unique but connected keys: a private key and a public key.

For a user to receive funds, a public key (also known as an address) must be shared. Contrary to public keys, private keys must be kept secret, just like the pin number on your bank card, since they authorize the spending of funds.

By using their wallet, users can authorize, sign, and transfer value to new owners. After broadcasting, the transaction is added to the blockchain.

A transaction consists of three main components:

* **The input:** Alice’s private coin address, where she is currently holding the coins she wants to spend.
* **The output:** Bob’s public key or coin address.
* **Amounts:** the amount of coins Alice wants to spend.


# Gas

### What Is Gas ? <a href="#what-is-gas" id="what-is-gas"></a>

To complete a transaction or execute a contract on the Ethereum blockchain platform, a gas fee is required. In the cryptocurrency ether (ETH), fees are calculated in tiny fractions, known as gwei (10-9 ETH). Transactions are carried out using gas to pay validators for their resources.

The exact price of the gas is determined by supply, demand, and network capacity at the time of the transaction.

#### KEY TAKEAWAYS <a href="#key-takeaways" id="key-takeaways"></a>

* Transactions on the Ethereum blockchain require gas, which is the cost of performing a transaction.
* The price of gas depends on supply and demand for network validation requests.
* Prices for transactions are determined by the gas limit and the gas price.
* Gwei are tiny fractions of ETH or ETH. are used to calculate transaction prices.

### Understanding Gas in Ethereum <a href="#understanding-gas-in-ethereum" id="understanding-gas-in-ethereum"></a>

In order to compensate miners for their efforts in maintaining and securing the blockchain, gas was introduced in the form of a reward. Staking ETH and participating in validation became more profitable after the proof of stake algorithm was introduced in September 2022.

"Gas limit" refers to the maximum amount of work you expect a validator to do on a particular transaction. Higher gas limits usually mean the user believes the transaction will require more effort. A "gas price" is the price per unit of work. Hence, the transaction cost is the gas limit times the gas price. A tip is often added to the gas price (the more you pay, the faster your transaction is completed). Those who estimate their gas limit lower will be placed lower in the queue due to their lower priority.

Transaction fees are similar to the fees you pay when you wire money. In exchange for using the service provider's network, you pay them.

Validators on the Ethereum network are awarded this fee for verifying blocks and verifying transactions on the network.

It is also important to bear in mind that gas prices are determined by supply and demand for transactions - if the network is congested, gas prices might be high. Alternatively, if there isn't much traffic, they may be low.

### Gas and the Ethereum Virtual Machine (EVM) <a href="#gas-and-the-ethereum-virtual-machine-evm" id="gas-and-the-ethereum-virtual-machine-evm"></a>

Platforms and systems like Ethereum are designed so that others can develop more use cases for blockchains and cryptocurrencies. Because applications can be created for it, it is commonly called the Ethereum Virtual Machine. Like a cloud application, the EVM runs blockchain-based applications within a virtual machine.

EVM has been used to create a wide range of decentralized applications, cryptocurrencies, and tokens. Gas fees are required for cryptocurrencies built on the Ethereum blockchain, since it is part of the EVM. In the Ethereum blockchain, DAI is one of the most popular tokens. As it uses the Ethereum blockchain, users have to pay gas fees in gwei to conduct transactions.


# Layer2 Blockchain

Layer 2 (L2) blockchain refers to a secondary protocol or framework built on top of an existing blockchain (usually a Layer 1 or L1 blockchain) to enhance scalability, reduce transaction costs, and improve overall performance. The term "Layer 2" signifies that it operates at a higher level than the base blockchain layer.

Here are some key characteristics and features associated with Layer 2 blockchains:

1. **Scalability:** One of the primary purposes of Layer 2 solutions is to address scalability issues that might be present in the underlying Layer 1 blockchain. By offloading certain types of transactions or computations to Layer 2, the network can handle a larger number of transactions per second.
2. **Reduced Transaction Costs:** Layer 2 solutions often aim to decrease transaction fees by processing certain transactions off-chain or in a more efficient manner. This can make blockchain applications more cost-effective for users.
3. **Fast Confirmation Times:** Layer 2 solutions can provide faster confirmation times for transactions compared to the base layer. This is achieved by leveraging various consensus mechanisms or cryptographic techniques that may not be feasible on the main blockchain.
4. **Interoperability:** Layer 2 solutions can be designed to maintain interoperability with the Layer 1 blockchain, allowing assets to be moved seamlessly between the two layers. This interoperability is crucial for maintaining consistency and enabling users to benefit from the security of the underlying blockchain.
5. **Examples of Layer 2 Solutions:**
   * **Sidechains:** Separate blockchains that run in parallel to the main blockchain but are interoperable with it.
   * **State Channels:** Off-chain channels where participants can transact privately and only interact with the main blockchain in case of disputes or final settlement.
   * **Plasma:** A framework for creating scalable and secure decentralized applications (DApps) on the Ethereum blockchain.
6. **Security:** Layer 2 solutions often leverage the security of the underlying Layer 1 blockchain. They rely on the main chain for certain security assurances, such as finality and immutability.

&#x20;The significant differences between L1 and L2 networks lies in their role and focus on the blockchain:

![L1 vs L2 chains](https://s3.amazonaws.com/assets.coingecko.com/app/public/ckeditor_assets/pictures/5284/content_Main_Table_%2820%29.png)


# Side Chain

## What is a Side-chain?

A sidechain is a separate blockchain that runs independent of Ethereum and is connected to Ethereum Mainnet by a two-way bridge. Sidechains can have separate block parameters and consensus algorithms, which are often designed for efficient processing of transactions. Using a sidechain involves trade-offs, though, as they do not inherit Ethereum's security properties. Unlike layer 2 scaling solutions, sidechains do not post state changes and transaction data back to Ethereum Mainnet.Sidechains also sacrifice some measure of decentralization or security to achieve high throughput (scalability trilemma). Ethereum is, however, committed to scaling without compromising on decentralization and security as outlined in its vision statement for upgrades.

**How do sidechains work?**

Sidechains are independent blockchains, with different histories, development roadmaps, and design considerations. While a sidechain may share some surface-level similarities with Ethereum, it has several distinctive features.**Consensus algorithms**One of the qualities that make sidechains unique (i.e., different from Ethereum) is the consensus algorithm used. Sidechains don't rely on Ethereum for consensus and can choose alternative consensus protocols that suit their needs. Some examples of consensus algorithms used on sidechains include:Proof-of-authorityDelegated proof-of-stakeByzantine fault tolerance.Like Ethereum, sidechains have validating nodes that verify and process transactions, produce blocks, and store the blockchain state. Validators are also responsible for maintaining consensus across the network and securing it against malicious attacks.**Block parameters**Ethereum places limits on block times (i.e., the time it takes to produce new blocks) and block sizes (i.e., the amount of data contained per block denominated in gas). Conversely, sidechains often adopt different parameters, such as faster block times and higher gas limits, to achieve high throughput, fast transactions, and low fees.While this has some benefits, it has critical implications for network decentralization and security. Block parameters, like fast block times and big block sizes, increase the difficulty of running a full node—leaving a few "supernodes" responsible for securing the chain. In such a scenario, the possibility of validator collusion or a malicious takeover of the chain increases.For blockchains to scale without harming decentralization, running a node must be open to everyone—not necessarily parties with specialized hardware. This is why efforts are underway to ensure everyone can run a full node on the Ethereum network.**EVM compatibility**Some sidechains are EVM-compatible and are able to execute contracts developed for the Ethereum Virtual Machine (EVM). EVM-compatible sidechains support smart contracts written in Solidity, as well as other EVM smart contract languages, which means smart contracts written for Ethereum Mainnet will also work on EVM-compatible sidechains.This means if you want to use your dapp on a sidechain, it's just a matter of deploying your smart contract to this sidechain. It looks, feels, and acts just like Mainnet—you write contracts in Solidity, and interact with the chain via the sidechains RPC.Because sidechains are EVM-compatible, they are considered a useful scaling solution for Ethereum-native dapps. With your dapp on a sidechain, users can enjoy lower gas fees and faster transactions, especially if Mainnet is congested.However, as explained previously, using a sidechain involves significant trade-offs. Each sidechain is responsible for its security and doesn't inherit Ethereum's security properties. This increases the possibility of malicious behavior which can affect your users or put their funds at risk.**Asset movement**In order for a separate blockchain to become a sidechain to Ethereum Mainnet it needs the ability to facilitate the transfer of assets from and to Ethereum Mainnet. This interoperability with Ethereum is achieved using a blockchain bridge. Bridges use smart contracts deployed on Ethereum Mainnet and a sidechain to control the bridging of funds between them.While bridges help users move funds between Ethereum and the sidechain, the assets are not physically moved across the two chains. Instead, mechanisms that typically involve minting and burning are used for transferring value across chains. More on how bridges work.

**Pros and cons of sidechains**

The technology underpinning sidechains is well-established and benefits from extensive research and improvements in design.Sidechains trade off some measure of decentralization and trustlesness for scalability.Sidechains support general computation and offer EVM compatibility (they can run Ethereum-native dapps).A sidechain uses a separate consensus mechanism and doesn't benefit from Ethereum's security guarantees.Sidechains use different consensus models to efficiently process transactions and lower transaction fees for users.Sidechains require higher trust assumptions (e.g., a quorum of malicious sidechain validators can commit fraud).EVM-compatible sidechains allow dapps to expand their ecosystem.


# Rollup

Rollups are L2 chains that facilitate computations outside the main blockchain. The transfer of transaction details takes place after a certain interval, hence offering the necessary backup for maintaining records. Besides, rollups can manage transactions with minimal interference to the main chain. Therefore, they can ensure transactions are processed faster and at minimal costs. Optimistic and zero-knowledge are the common types of rollups.


# Ramestta SDK

{% hint style="info" %}
Coming soon
{% endhint %}


# Rama.js

## Installation

Rama.js is made up of a main library and an Ethereum library:

### Main library[¶](https://docs.polygon.technology/tools/matic-js/installation/#main-library) <a href="#main-library" id="main-library"></a>

The main library has the core logic and provides different APIs. The user interacts mostly with this library.

```
npm i @ramestta/ramajs
```

### Ethereum library[¶](https://docs.polygon.technology/tools/matic-js/installation/#ethereum-library) <a href="#ethereum-library" id="ethereum-library"></a>

The Ethereum library allows us to use any favorite ether library. It is injected into ramajs using plugins.

matic.js supports two popular library -

1. [Web3.js](https://web3js.readthedocs.io/)
2. [Ethers](https://docs.ethers.io/)

#### Web3.js[¶](https://docs.polygon.technology/tools/matic-js/installation/#web3js) <a href="#web3js" id="web3js"></a>

```
npm install @ramestta/rama-web3
```

#### ethers[¶](https://docs.polygon.technology/tools/matic-js/installation/#ethers) <a href="#ethers" id="ethers"></a>

```
npm install @maticnetwork/rama-ethers
```


# Plasma


# RAMA20

{% hint style="info" %}
Coming soon
{% endhint %}


# RAMA721

{% hint style="info" %}
Coming soon
{% endhint %}


# Common Methods

{% hint style="info" %}
Coming soon
{% endhint %}


# POS


# RAMA20

{% hint style="info" %}
Coming soon
{% endhint %}


# RAMA721

{% hint style="info" %}
Coming soon
{% endhint %}


# RAMA1155

{% hint style="info" %}
Coming soon
{% endhint %}


# Common Methods

{% hint style="info" %}
Coming soon
{% endhint %}


# setProofApi

You will see some of the APIs with **faster** suffix, which makes the process faster. It does so by using proof generation api in the backend which can be hosted by anyone.

Ramestta has hosted the proof generation api which can be used by anyone. The API url is - <https://proof-generator.ramestta.com/>

The `setProofApi` can be used to set the proof api url.

```
import { setProofApi } from '@ramestta/ramajs'

setProofApi("https://proof-generator.ramestta.com/");
```

👉 We recommend to host the proof API by yourself which will give you better performance. The default api provided by Ramestta might have performance issue as it is being used by multiple people.

Here is proof api repo link - <https://github.com/Ramestta-Blockchain/proof-generation-api>

After you have deployed the api, you can set the api url in rama.js by using `setProofApi`.

e.g - if you have deployed the proof api and the base url is - `https://xyz.com/`, then you need to set base url in `setProofApi`

```
import { setProofApi } from '@ramestta/ramajs'

setProofApi("https://xyz.com/");
```

{% hint style="info" %}
We recommend using faster API's, because some API's particularly where proof is being generated does a lot of RPC calls and it might be very slow with public RPC's.
{% endhint %}


