# Get to Know re.al

## Overview

**re.al** is a modular Ethereum Layer-2 scaling platform that employs state-of-the-art cryptographic protocols to facilitate efficient transaction processing off the main chain while leveraging the security of an established blockchain.

**re.al** is dedicated to transforming the landscape of DeFi and RWAs, offering an unparalleled blend of security and efficiency with permissionless access to the deepest liquidity and feature set for this asset class.

Built with cutting-edge Arbitrum Orbit, **re.al** is engineered to address the core challenges of traditional blockchain systems by offering lightning-fast transaction speeds, drastically reduced gas costs, and enhanced throughput, all while maintaining the rigorous security standards of the Ethereum mainnet.

**re.al** is not just a technological implementation; it's a gateway to a new era of DeFi utility, where the tokenization of RWAs is more than a concept or trend, rather it becomes a practical, impactful reality and dominant use case for blockchain technology.

**re.al** is the optimal platform for users, developers and institutions looking to experience the true potential of RWAs.

## Ecosystem Vision

Unlock the potential of tokenized real world assets to revolutionize the way people invest and build wealth.

## Ecosystem Mission

Through tokenization and DeFi composability, we will redefine asset ownership and value creation, transforming the way RWAs are bought, sold, and leveraged on-chain.

## Ecosystem Purpose

To unleash the true power of DeFi on valuable, real world assets, giving them new powers and operability.

## Key Features and Benefits

* **Built for RWAs**: Dedicated chain and ecosystem for tokenized RWAs with the purpose of supporting builders and investors, launching with $40MM+ in tokenized RWAs at launch, with an established liquidity engine.
* **Yield Maximizing:** Both ETH and DAI natively accrue yield on the chain. 100% of chain revenues and a portion of revenue from each protocol deployed to the chain accrue to RWA, the first L2 token to share all protocol revenue with holders from Day 1.&#x20;
* **Modular Construction:** Many elements of **re.al** are modular, meaning we can deploy the best feature set for what our users and ecosystem need now while also updating and evolving the chain to meet new consumer and technology demands, always working towards greater decentralization.
* **Enhanced Throughput**: Accelerates transaction processing for high-demand applications.
* **Cost-Effective Transactions**: Aggregates transactions to optimize network fees.
* **EVM Compatibility**: Supports existing smart contract ecosystems and extends their capabilities making **re.al** the ideal playground for builders to explore new designs leveraging reliable off-chain yields.
* **Strategic Partnerships**: Aligns with reputable entities to bolster infrastructure reliability.
* **Interoperability**: Connects diverse blockchain networks, advancing a cohesive multi-chain strategy. Simple bridge in an out using the native **re.al** bridge or LayerZero.
* **Developer-Friendly Tools**: Maintains compatibility with popular developer tools to ensure a smooth transition.
* **User-Centric Features**: Innovates on user interaction for a frictionless experience and the ability to buy, trade, farm, borrow and leverage RWAs at launch


# Relationship to Arbitrum

**re.al** is a modular blockchain built using Arbitrum Orbit.&#x20;

From the start we'll benefit from Arbitrum's category-leading tech and features in the Nitro tech stack including interactive fraud proofs, advanced compression, EVM+ compatibility via Stylus, and continuous upgrades, feature additions, and improvements, incorporating the latest and greatest in Ethereum scaling technology.

Powered by a thesis of modularity, **re.al** will continue to evolve, meeting new consumer needs, integrating new technologies and seeking greater decentralization in core elements of the chain. Updates to chain components may or may not be provided by Arbitrum.

**re.al** will deploy using the Arbitrum Data Availability Committee (DAC) to expedite the settlement of transactions, lowering costs while still maintaining the security of Ethereum.


# Tokenized RWAs on re.al

Tokenized real-world assets (RWAs) represent a transformative development in the intersection of blockchain technology and traditional financial assets.

### What Are Tokenized RWAs?

Tokenized RWAs can be physical, tangible assets like real estate, art or precious metals, or financial instruments like US Treasuries, stocks, ETFs or derivatives, held in the real world and used to back digital representations of the assets (tokens) on a blockchain. Through tokenization, traditional assets benefit from the inherent advantages of blockchain technology, including transparency, security, liquidity and ease of transfer.

### Why Do Tokenized RWAs matter?

Tokenization imbues valuable real world assets with greater operability, including increased access, liquidity and composability.

Traditionally, investing in assets like real estate required significant capital, making them inaccessible to the average investor. Tokenization breaks down these financial barriers enabling a broader range of buyers to own and benefit of these assets. We believe this leads to a more inclusive financial ecosystem.

Tokenizing RWAs brings enhanced liquidity and global access to markets that are typically characterized by their illiquidity. Buying or selling a piece of real estate can be a lengthy and complex process. Yet tokenized real estate can be bought or sold in 15 seconds, just like any other crypto asset. Combined with the global nature of crypto markets, it's now easy for anyone, anywhere to access valuable RWAs, unencumbered by procedural or geographical restrictions.

Combined with DeFi primitives, tokenized RWAs can be used to build innovative financial products and services, maximizing the impact of some of the world's most established assets. One-click borrowing and leverage, concentrated liquidity provision and additional asset composability all give new utility to "old" assets. Simultaneously, some RWAs produce a consistent, uncorrelated source of yield that flows into the cryptoeconomy, a unique non-zero-sum benefit to all market participants.  &#x20;

**re.al** recognizes the power of RWAs to improve the cryptoeconomy and the financial standing of users world-wide which is why we've built **re.al,** crypto's largest, permissionless chain for tokenized RWAs.


# Arbitrum Orbit Overview

## Customizable and Decentralized

Arbitrum Orbit offers a groundbreaking and customizable toolkit for blockchain developers seeking to launch their own dedicated chains. It enables the creation of Arbitrum Rollup and AnyTrust chains, either as Layer 2 (L2) chains settling directly to Ethereum—like **re.al**—or as Layer 3 (L3) chains settling to any Ethereum L2, like Arbitrum One.

## Tailored Chain Architecture

At **re.al**, we have embraced the comprehensive capabilities offered by Arbitrum Orbit, selecting and integrating components that resonate with our specific requirements. This strategic choice allows us to incorporate custom components, including the planned migration to Celestia for our Data Availability (DA) solutions, which further ensures our chain architecture is perfectly aligned with our vision, operational needs and consumer demands while also maintaining overarching Ethereum alignment.&#x20;

### re.al's Configuration Choices with Arbitrum Orbit

We've utilized Arbitrum Orbit to configure our chain with the following options:

1. **Rollup**: This configuration posts complete transaction data directly onto Ethereum, ensuring maximum security and decentralization.
2. **AnyTrust**: This mode introduces a Data Availability Committee (DAC) for storing transaction data, balancing between performance and decentralization.

## Leveraging Arbitrum Nitro Technology

Orbit chains benefit from Arbitrum Nitro, the advanced technology stack that includes interactive fraud proofs, advanced compression, EVM+ compatibility via Stylus, and ongoing improvements. This ensures our chain is built on a solid foundation of the cutting-edge in Ethereum scaling technology.

## Key Advantages of re.al's Adoption of Arbitrum Orbit

* **Customization and Control**: Provides the ability to create a modular chain tailored to our exact use-case, with full control over its features and governance.
* **Extensive Customization Options**: From gas tokens to protocol logic, Orbit chains offer unparalleled flexibility to meet specific project needs.
* **Scalability and Performance**: Offers dedicated throughput and resources, eliminating the need to compete for space and computation on shared networks.
* **Security and Reliability**: Benefits directly from Ethereum's security model, while allowing for independent and decentralized governance.
* **EVM+ Compatibility**: Ensures smart contract compatibility with a wide range of programming languages (Solidity, Rust, C, C++) and tools, facilitating easy deployment and migration of smart contracts.
* **Gas Efficiency and Price Predictability**: Increases transaction efficiency and offers more stable gas pricing, enhancing the user experience.
* **Access Optionality**: Allows for varying degrees of openness, from fully **re.al's** fully permissionless environment to restricted spaces tailored to specific protocol needs .


# Block Explorer

The re.al block explorer provides a comprehensive and user-friendly interface for monitoring and analyzing network activities. It is designed to offer key insights and information beneficial for both regular users and developers. Features of the re.al block explorer include:

* **Address Balances**: Check the balance of any address on the network.
* **Transaction History**: View detailed transaction records.
* **Verified Contracts**: Access and review verified smart contract codes.
* **Smart Contract Code and Execution**: Examine the code and execution details of smart contracts.
* **Network Statistics**: Get up-to-date information on network performance.
* **Mining Information**: Monitor mining activities and related statistics.

Visit [Block Explorer](https://explorer.re.al/) for re.al.\
\
Production explorer to be added once the chain is deployed.


# Run a Node

Setup Real Permissionless RPC Node

## How to Run a re.al Node

This guide provides step-by-step instructions for running a **re.al** node on your local machine.

### Prerequisites

Before you begin, ensure you have the latest Docker image:

```plaintext
offchainlabs/nitro-node:v2.3.4-b4cc111
```

### Minimum Hardware Requirements

| Component | Minimum Requirement               |
| --------- | --------------------------------- |
| CPU       | 2-4 core CPU (For AWS: t3 xLarge) |
| RAM       | 8-16 GB                           |
| Disk      | Depends on traffic volume         |

#### Step 1: Create a directory for the chain

```bash
mkdir -p ~/tangbile-chain
```

#### Step 2: Run the node

```bash
docker run --rm -it  -v ~/tangible-chain:/home/user/.arbitrum \
  -p 0.0.0.0:8547:8547 \
  -p 0.0.0.0:8548:8548 \
  offchainlabs/nitro-node:v2.3.4-b4cc111 \
  --parent-chain.connection.url=https://eth.llamarpc.com \
   --parent-chain.blob-client.beacon-url=<your-beacon-mainnet-url> \
  --chain.id=111188 \
  --chain.name="real" \
  --http.api=net,web3,eth \
  --http.addr=0.0.0.0 \
  --execution.forwarding-target=https://real.drpc.org \
  --node.data-availability.enable \
  --node.data-availability.rest-aggregator.enable \
  --node.data-availability.rest-aggregator.urls=<your-dac-rest-url> \
  --node.feed.input.url=wss://real.drpc.org \
  --chain.info-json="[{\"chain-id\":111188,\"parent-chain-id\":1,\"parent-chain-is-arbitrum\":false,\"chain-name\":\"real\",\"chain-config\":{\"homesteadBlock\":0,\"daoForkBlock\":null,\"daoForkSupport\":true,\"eip150Block\":0,\"eip150Hash\":\"0x0000000000000000000000000000000000000000000000000000000000000000\",\"eip155Block\":0,\"eip158Block\":0,\"byzantiumBlock\":0,\"constantinopleBlock\":0,\"petersburgBlock\":0,\"istanbulBlock\":0,\"muirGlacierBlock\":0,\"berlinBlock\":0,\"londonBlock\":0,\"clique\":{\"period\":0,\"epoch\":0},\"arbitrum\":{\"EnableArbOS\":true,\"AllowDebugPrecompiles\":false,\"DataAvailabilityCommittee\":true,\"InitialArbOSVersion\":11,\"GenesisBlockNum\":0,\"MaxCodeSize\":24576,\"MaxInitCodeSize\":49152,\"InitialChainOwner\":\"0xbB0385FebfD25E01527617938129A34bD497331e\"},\"chainId\":111188},\"rollup\":{\"bridge\":\"0x39D2EEcC8B55f46aE64789E2494dE777cDDeED03\",\"inbox\":\"0xf538671ddd60eE54BdD6FBb0E309c491A7A2df11\",\"sequencer-inbox\":\"0x51C4a227D59E49E26Ea07D8e4E9Af163da4c87A0\",\"rollup\":\"0xc4F7B37bE2bBbcF07373F28c61b1A259dfe49d2a\",\"validator-utils\":\"0x2b0E04Dc90e3fA58165CB41E2834B44A56E766aF\",\"validator-wallet-creator\":\"0x9CAd81628aB7D8e239F1A5B497313341578c5F71\",\"deployed-at\":19446518}}]"
```

#### Step 3: Check the logs

```bash
INFO [07-02|06:00:56.125] created jwt file                         filename=/home/user/.arbitrum/jwtsecret
INFO [07-02|06:00:56.125] Running Arbitrum nitro node              revision=v2.3.4-b4cc111 vcs.time=2024-05-02T11:51:35-05:00
INFO [07-02|06:00:57.263] connected to l1 chain                    l1url=https://eth.llamarpc.com l1chainid=1
WARN [07-02|06:00:57.969] Getting file info                        error="stat : no such file or directory"
WARN [07-02|06:00:57.973] Getting file info                        error="stat /workspace/target/machines: no such file or directory"
WARN [07-02|06:00:57.974] Getting file info                        error="stat /home/user/machines: no such file or directory"
INFO [07-02|06:00:57.976] Using leveldb as the backing database
INFO [07-02|06:00:57.977] Allocated cache and file handles         database=/home/user/.arbitrum/real/nitro/l2chaindata cache=16.00MiB handles=16 readonly=true
INFO [07-02|06:00:57.977] Using leveldb as the backing database
INFO [07-02|06:00:57.977] Allocated cache and file handles         database=/home/user/.arbitrum/real/nitro/l2chaindata cache=2.00GiB handles=512
INFO [07-02|06:00:57.998] Using LevelDB as the backing database
INFO [07-02|06:00:58.019] Opened ancient database                  database=/home/user/.arbitrum/real/nitro/l2chaindata/ancient/chain readonly=false
INFO [07-02|06:00:58.019] Initializing                             ancients=0 genesisBlockNr=0
...
```

#### Step 4: Check the node status

```bash
curl -X POST http://localhost:8547/ \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}'
```

### Shutting Down the Node

To ensure the current state is saved properly, allow a graceful shutdown:

```bash
docker stop --time=300 $(docker ps -aq)
```


# Governance

## re.alDAO

The re.al ecosystem is open and fully composable, and we welcome any builders who wish to explore the power of tokenized RWAs on the chain.

re.al embraces the decentralized nature of the space and will support an active governance system on the chain.

re.al Governance will follow a primarily off-chain governance process:

* Discussions initiated by either the re.al core team or community members will be shared with the larger re.al community via forum discussion.
* Discussions with sufficient merit and support will progress into formal “RIP” proposals which are subsequently voted upon by veRWA holders.
* Approved proposals will be implemented per proposal terms, carried forward by members of the re.al core team, fulfilling the will of the community and voters.

This style of governance is considered "off-chain" because the result of the governance vote does not automatically trigger on-chain actions, such as the deployment of new code or the transfer of assets from one wallet to another.

## Governance Roadmap

### Q224

* Design the guiding principles, basic framework and process to manage governance, community discussion and proposal development and implementation on re.al
* Draft governance documentation

### Q324

* Revise and finalize governance documentation
* Codify governance systems in the re.al protocol docs
* Set-up key infrastructure and software to facilitate the governance system
* Share and promote governance set-up within the re.al community

### Q424

* Launch governance and open community forum for proposals

*All attempts will be made to accelerate governance implementation beyond the timeline presented above.*<br>


# Security

Prior to launch, re.al has undergone extensive auditing to ensure the security of contracts and safety of funds migrated to the chain.

The first was a private round of audits completed by the auditing firm Omniscia.

The second being a public round completed by the auditing firm Hacken.

Additional audits will continue to be added over time to demonstrate our continued focus on security and the reliability of the chain and protocol contracts.&#x20;

<table><thead><tr><th width="458">Audit (Issuer - Product)</th><th>Date Posted</th></tr></thead><tbody><tr><td><a href="https://drive.google.com/file/d/1uPZz9oKAsbLZbV_JzejL7hD3opyGWdKT/view?usp=sharing">Hacken - re.al DAI (plus ERC-20 bridge)</a></td><td>May 2, 2024</td></tr><tr><td><a href="https://drive.google.com/file/d/1UMYLKF1_vyEshz64limENYOTwykWk0d_/view?usp=sharing">Hacken - reETH and RWA (plus Native Bridge)</a></td><td>May 24, 2024</td></tr></tbody></table>


# Contracts & Addresses

### reETH Deployment (Ethereum)

<table><thead><tr><th width="258">Contract</th><th>Address</th></tr></thead><tbody><tr><td><code>reETH</code></td><td><code>0xC0Cc5eA00cAe0894B441E3B5a3Bb57aa92F15421</code></td></tr><tr><td><code>Minter</code></td><td><code>0x655756824385F8903AC8cFDa17B656cc26f7C7da</code></td></tr><tr><td><code>RealVault</code></td><td><code>0xFC1db08622e81b2AFd643318f6B8B79E9980A5e1</code></td></tr><tr><td><code>AssetsVault</code></td><td><code>0xf985E2c73d74BefF3C8c16EFC4fa5ab4cfb62294</code></td></tr><tr><td><code>StrategyManager</code></td><td><code>0x5Cba18d504D4158dC1A18C5Dc6BB2a30B230DdD8</code></td></tr><tr><td><code>SwapManager</code></td><td><code>0x4AC36E1Fa7daBeFEc885f30B163c571080b2c335</code></td></tr><tr><td><code>LidoStEthStrategy</code></td><td><code>0x679D4C1cC6855C57726BEA1784F578315d6431f6</code></td></tr></tbody></table>

### Dai Deployment (Ethereum)

<table><thead><tr><th width="258">Contract</th><th>Address</th></tr></thead><tbody><tr><td><code>L1DAIEscrow</code></td><td><code>0xf01B82b101fD8150D57DAdEc4Da8Cd5739A503A4</code></td></tr><tr><td><code>Bridger</code></td><td><code>0xbf2F26cadbC10C4d61ac7e424D514d79a12126f8</code></td></tr></tbody></table>

### Dai Deployment (re.al)

<table data-header-hidden><thead><tr><th width="261"></th><th></th></tr></thead><tbody><tr><td><code>L2DAI</code></td><td><code>0x75d0cBF342060b14c2fC756fd6E717dFeb5B1B70</code></td></tr></tbody></table>

### USDC Bridge Deployment

<table><thead><tr><th width="258">Contract</th><th>Address</th></tr></thead><tbody><tr><td><code>Vault</code> </td><td><code>0xBAa850bc2eCC6A4F356445f4A853281A42bD2fBb</code></td></tr><tr><td><code>Controller</code></td><td><code>0x7dfe5d23761B7a748e962003e0FC6b4559afED39</code></td></tr><tr><td><code>USDC</code></td><td><code>0xc518A88c67CECA8B3f24c4562CB71deeB2AF86B7</code></td></tr></tbody></table>

`Vault` currently deployed on Arbitrum, Base, Ethereum and Polygon.

### Multisigs

<table><thead><tr><th width="258">Owner</th><th>Address</th></tr></thead><tbody><tr><td><code>re.al Labs (re.al)</code></td><td><code>0x5111e9bCb01de69aDd95FD31B0f05df51dF946F4</code></td></tr><tr><td><code>re.al DAO (re.al)</code></td><td><code>0x946C569791De3283f33372731d77555083c329da</code></td></tr><tr><td><code>re.al DAO (ETH)</code></td><td><code>0xD47E2043C1eCbeF215D89EE667D09A7aA56823d4</code></td></tr></tbody></table>


# reETH: Native Token

## reETH on re.al

reETH is the native gas token to the chain. reETH is 100% backed by LSTs (liquid staking tokens) in the native bridge, so that all ETH bridged to **re.al** earns yield on the chain.

reETH is value-accruing, meaning it goes up in value vs ETH as ETH yield accrues to the token, similar to popular LSTs like wstETH or sfrxETH. The example below illustrates how value accrues to the token assuming a staking yield of 3%.

<table><thead><tr><th width="152">Time</th><th width="179" data-type="number">reETH Held</th><th>Staking Yield (est.)</th><th>reETH Value</th></tr></thead><tbody><tr><td>Day 0</td><td>1</td><td>3%</td><td>1 ETH</td></tr><tr><td>Day 365</td><td>1</td><td>3%</td><td>1.03 ETH</td></tr></tbody></table>

The reETH on **re.al** functions the same as ETH on Ethereum mainnet or any other Ethereum L2, with the exception that it accrues value from staking. Gas fees, token swaps, asset payments done in ETH on other chains will be completed in reETH on **re.al**, processed at significantly lower costs to the L1 due to the processing efficiencies of an L2.

Through the deployment of reETH, all ETH on the chain, no matter where it's held, earns staking yield for users. This unlocks new design opportunities and DeFi primitives in the **re.al** ecosystem while helping users maximize the value of their assets.&#x20;

{% hint style="info" %}
At any time, the reETH to ETH conversion rate can be found [here](https://etherscan.io/address/0x655756824385F8903AC8cFDa17B656cc26f7C7da#readContract#F1).
{% endhint %}

### How It Works:

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

{% hint style="info" %}
The vault, strategy manager and minter all sit in front of the bridge when the transaction destination is **re.al.**&#x20;
{% endhint %}

#### Vault

The RealETH Vault is responsible for managing deposit, withdrawal, and settlement processes using the ERC4626 standard. Serving as the fund buffering pool, it holds deposited ETH within the contract until a new settlement occurs, at which point the funds are deployed to the underlying strategy pool.

#### Minter

The Minter handles the minting and burning of reETH tokens. This function decouples reETH token minting from its underlying assets, allowing for independent adjustments to the assets and the circulation of issued reETH tokens. This separation ensures a higher level of token stability within the **re.al** ecosystem.

#### Strategy Pool

The Strategy Pool manages asset yield routes through a whitelist mechanism. This approach ensures a high level of asset compatibility, including staking pools, restaking protocols and more. Each individual strategy route within the pool isolates asset risks, preventing cross-contamination and maintaining the security of reETH assets.

#### Order of Operations

1. Users initiate a bridge transaction to **re.al**, to send ETH through the native bridge to the chain.
2. Prior to the bridge, ETH enters the **re.al** Vault and waits for the next epoch to be deployed in the strategy as per the portfolio allocation ratio. The ETH remains on the Ethereum L1 where it begins to earn staking yield.
3. The minter mints the incoming ETH using current share price of the vault to account for the generated yield and sends minted reETH through the bridge to the user's wallet on **re.al**.
4. When bridging out, the process is reversed, burning reETH and unstaking ETH from the vault. The user receives the reETH value in ETH on the destination chain.
5. Initially ETH will be 100% staked using Lido stETH and new strategies will be added as TVL expands, upon approval from the community via governance vote.

Upon bridging back, users have the option to redeem ETH by burning reETH. The vault conducts calculations to determine the precise ETH amount, factoring in the current share price along with accrued yield and principal amounts. Users are provided with two withdrawal choices:&#x20;

1. Standard withdrawal: 11 - 17 Days (7-day challenge period + LST redemption window)\
   The standard withdrawal option enables users to convert reETH into ETH by initiating a withdrawal request from the strategy and settling the user using the real Vault ETH buffer.
2. Swap withdrawal: 7 Days\
   Alternatively, users can choose the swap withdrawal option, which entails swapping strategy tokens on the Decentralized Exchange (DEX) based on the portfolio allocation ratio in the strategy manager. This route may incur additional transaction fees/slippage in the DEX transaction.

{% hint style="warning" %}
In a hurry? Try bridging out through $USTB or $MORE to any of the chains supporting those assets. The bridge UI will route those assets through the LayerZero cross-chain messaging protocol for settlement in under an hour.
{% endhint %}

## Transaction Fees

Compared to the Ethereum Layer 1, users can expect a significant reduction in gas fees on **re.al**.&#x20;

To make this possible, **re.al** batches transactions together, effectively spreading the cost of a single layer 1 transaction across multiple layer 2 transactions. This can also help to insulate the L2 from spikes to gas requirements on the L1 due to network congestion.

With the addition of modular DA currently provided by the Arbitrum Data Availability Committee (DCA) **re.al** provides an optimal combination of transaction security, speed (throughput) and cost.<br>


# Get Started

re.al is a Layer-2 scaling platform that employs state-of-the-art cryptographic protocols to facilitate efficient transaction processing off the main chain while leveraging the security of an established blockchain. It seamlessly integrates with the ecosystem's prevalent development frameworks.

Native bridge: <https://www.re.al/app/bridge/>\
\
"One-click" add the network to MetaMask using the button on [ChainList](https://chainlist.org/?search=re.al).

{% hint style="info" %}
Need gas fast? Send instantly with [gas.zip](https://www.gas.zip/).
{% endhint %}

### re.al Network Details

| Network Attribute |                                                                                      Value                                                                                     |
| ----------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
| chainID           |                                                                                     111188                                                                                     |
| Settlement Layer  |                                                                                    Ethereum                                                                                    |
| Currency          |                                                                                      reETH                                                                                     |
| RPC Urls          | <p><a href="https://tangible-real.gateway.tenderly.co/"><https://tangible-real.gateway.tenderly.co/></a></p><p><a href="https://real.drpc.org"><https://real.drpc.org></a></p> |
| Explorer          |                                                                            <https://explorer.re.al/>                                                                           |

[The public summary of the network can be found here. ](https://raas.gelato.network/rollups/details/public/real)

### re.al Network Configurations

Block gas limit: 32M\
Block time: 250ms\
Base fee: 0.2 gwei

### Ecosystem Overview:

{% embed url="<https://youtu.be/EC4wT-clb6A>" %}


# Asset Bridging

## Overview

Bridging assets to re.al is an essential process for users who wish to interact with the re.al network. This section provides a comprehensive guide on how to bridge your assets effectively.

### **Native Bridge: Ethereum to re.al**

The native bridge will transfer whitelisted assets between Ethereum and **re.al**. There is no charge to use the native bridge aside from gas.

The settlement time to bridge whitelisted assets back from **re.al** to the Ethereum L1 is 7 days. ETH bridged using the "instant swap" option will settle in 7 days, however the standard withdrawal on ETH adds an additional 7 - 11 days.&#x20;

Instant swap adds a swap transaction to exchange stETH for ETH to return ETH to the user on mainnet, where users may recoup less funds do to slippage. The standard withdrawal unstakes ETH from Lido and returns that to users 1:1.

**User must claim the token from bridge app after 7 days challenge period to receive token in their wallet.**

#### Whitelisted tokens at launch:

<table><thead><tr><th width="199">Token</th><th width="663">Address on re.al</th></tr></thead><tbody><tr><td><code>ETH</code></td><td>NA</td></tr><tr><td><code>DAI</code></td><td><code>0x75d0cBF342060b14c2fC756fd6E717dFeb5B1B70</code></td></tr><tr><td><code>WBTC</code></td><td><code>0x4deE73429D25E92E9c7e7e580e914820C3Abdc8D</code></td></tr><tr><td><code>USDT</code></td><td><code>0xDDF533a1Cd8376473Bfe5ae1d93b90e39e3D6faD</code></td></tr></tbody></table>

{% hint style="info" %}
Bridged ETH is staked to become [reETH](/get-started/reeth-native-token) on **re.al**, natively accruing yield.&#x20;

Bridged DAI is staked, natively rebasing on **re.al** accruing yield from the DAI savings rate.
{% endhint %}

### USDC Speed Bridge

A "lock & mint" bridge has been developed to enable expedited transfer of USDC between **re.al** and an expanding selection of key DeFi chains, including Arbitrum, Base and Polygon.

**The goal is to expedite the transfer of standardized DeFi assets between re.al and other major DeFi chains, improving capital flows and liquidity on the chain.**&#x20;

Native bridges on an ORU (optimistic roll-up) typically require a 7-day settlement bridging back to other chains. This solution allows USDC to move on and off our chain instantly.

"Bridged" USDC on **re.al** will be the only version of USDC on the chain. For the time being, USDC can only be bridged to **re.al** from Arbitrum, Base and Polygon.&#x20;

As additional inbound chains are added, the vaults on those chains will mint the same "bridged" USDC for users on **re.al** using LayerZero messaging, returning the native USDC when they bridge back out.

<table data-header-hidden><thead><tr><th width="261"></th><th></th></tr></thead><tbody><tr><td>Bridged <code>USDC</code> on <strong>re.al</strong></td><td><code>0xc518A88c67CECA8B3f24c4562CB71deeB2AF86B7</code></td></tr></tbody></table>

The bridge design includes standardized contracts from OpenZeppelin (ERC20) and LayerZero (cross-chain messaging.)

{% hint style="info" %}
Only the native USDC on [Arbitrum](https://arbiscan.io/token/0xaf88d065e77c8cc2239327c5edb3a432268e5831), [Base](https://basescan.org/token/0x833589fcd6edb6e08f4c7c32d4f71b54bda02913), [Ethereum](https://etherscan.io/token/0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48) and [Polygon](https://polygonscan.com/token/0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359) can be used to bridge into **re.al**.

These are the only chains where USDC can be sent to **re.al**.
{% endhint %}

#### Bridging In (Arbitrum example)

1. User initiates a USDC bridge transaction on Arbitrum to **re.al**
2. The USDC is deposited into a vault on Arbitrum
3. The vault sends a message to **re.al** using the LayerZero cross-chain messenger
4. USDC tokens are minted for the user on **re.al**

#### Bridging Out (Arbitrum example)

1. User initiates a USDC bridge transaction on **re.al** to Arbitrum&#x20;
2. Controller contract burns the user's bridged USDC
3. The controller uses LayerZero to send a message back to Arbitrum
4. The user's USDC is released from the vault on Arbitrum and transferred to their wallet

{% hint style="warning" %}
USDC coming in via one chain and out through another might trigger a situation where there is not enough liquidity in the vault to send the same amount of USDC back to the chain where it came in from.

Users will not be able to send more USDC to a specific chain than liquidity is available in the vault contract on that chain.
{% endhint %}

### Cross-Chain Ecosystem Assets (LayerZero OFTs)

Certain re.al ecosystem assets built as OFTs (LayerZero Omnichain Fungible Tokens) can feely move between multiple chains at no cost other than gas.

OFTs are burned on the source chain and minted on the destination chain, never held in a bridge contract.

Settlement times when OFTs are sent between chains are normally 30 min - 1 hour.

LayerZero endpoint information can be found [here](https://docs.layerzero.network/v1/developers/technical-reference/mainnet/mainnet-addresses#real).

#### **re.al cross-chain assets (OFTs):**

| Protocol        | Token          |
| --------------- | -------------- |
| Tangible        | `USTB` `wUKRE` |
| Arcana          | `arcUSD`       |
| Stack           | `MORE`         |
| Pearl (pending) | `PEARL`        |

### Step-by-Step Guide to Using the Official Bridge Portal

While there there two different bridge technologies underlying the Bridge Portal, the user is smartly routed through the appropriate system without the need to choose.&#x20;

ETH and DAI will route through the Native Bridge.

OFT ecosystem assets will route through the LayerZero technology.

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

1. Visit the official re.al Bridge Portal and connect your wallet.
2. Select your source chain and destination chain.
3. Choose eligible asset to move between seleected chains.
4. Input the amount of assets you want to bridge.
5. Confirm and sign the transaction with your wallet.

Wait for the bridging process to complete. The assets will then be available in your wallet on the re.al network.

After the transaction is confirmed, the bridged assets will reflect in your re.al wallet, allowing you to interact with the network and its dApps.

{% hint style="info" %}
The transaction times can vary based on network congestion and gas fees. Please ensure you have enough ETH in your wallet to cover the transaction fees.
{% endhint %}


# Network Guides and Videos

<table data-view="cards"><thead><tr><th data-card-target data-type="content-ref"></th><th data-hidden data-card-cover data-type="files"></th></tr></thead><tbody><tr><td><a href="/pages/3XtAldpSbLDDCJvlPfFw">/pages/3XtAldpSbLDDCJvlPfFw</a></td><td><a href="/files/x3YTl5sDA6FQJIlmWyuY">/files/x3YTl5sDA6FQJIlmWyuY</a></td></tr><tr><td><a href="/pages/SGTWkKvusHNapHaxjgFi">/pages/SGTWkKvusHNapHaxjgFi</a></td><td><a href="/files/mGty1gwCmQ64SF8BvT16">/files/mGty1gwCmQ64SF8BvT16</a></td></tr><tr><td><a href="/pages/i4mj9bLEyJReI6WLL0Rg">/pages/i4mj9bLEyJReI6WLL0Rg</a></td><td><a href="/files/sKB9aVq3wn9Ap2iWzzBd">/files/sKB9aVq3wn9Ap2iWzzBd</a></td></tr></tbody></table>


# How to Bridge to re.al

{% embed url="<https://youtu.be/ga7U8vdQkBI>" %}

## Bridge to re.al: Step-by-Step Guide

1. Make sure you are on the [Bridge page](https://www.re.al/app/bridge/).
2. Click on “Connect Wallet” and select your preferred wallet.
   1. In this demonstration, Metamask is selected. Note that using other wallets might result in different prompts in your wallet.
3. Confirm the connection in Metamask.
4. Input the amount of the tokens you want to bridge to re.al. You can select any token from the list of tokens, but make sure there is enough liquidity on re.al to swap that token. You can check this on [Pearl DEX](https://www.pearl.exchange/trade).
   1. Note that when you are bridging ETH to re.al, the tokens get staked through the bridging contract, giving back reETH. reETH is the native gas token on re.al, and it accrues yield like any other yield-bearing LST.
5. Start the bridging process. At this step you will need to sign 3 transactions. Make sure you have enough ETH on Ethereum to cover gas fees.
6. It will take about 15 minutes for the funds to show on re.al. You can monitor the current status of the transaction in the “Transactions” pop-up.


# How to Lock $RWA

{% embed url="<https://youtu.be/noUDcjpUIuA>" %}

## Lock $RWA: Step-by-Step Guide

1. Make sure you are on the [Lock & Claim page](https://www.re.al/app/lock-and-claim).
2. Click on “Connect Wallet” and select your preferred wallet.
   1. In this demonstration, Metamask is selected. Note that using other wallets might result in different prompts in your wallet.
3. On the left, input the amount of RWA you wish to lock.
4. On the right, select the lock duration from a minimum of 1 month to a max of 36 months. Longer locks result in higher veRWA voting power and more revenue sharing.
5. Now click on “Lock RWA”, approve the token spending and execute the transaction.
6. Your new veRWA position will show in the tab “My Locks”, where you can manage it through multiple actions:
   1. **Vesting:** Since the lock is designed to keep perpetually the duration set at the time of the locking, the position is not automatically vested. To actually start the vesting, you have to deposit the veRWA position into the vesting contract, and from that time it will take the lock duration to completely vest. When a veRWA position is deposited into the vesting contract, the voting power instantly goes to zero and the user does not receive rewards anymore.
   2. **Unlock:** If you don’t want to wait for the vesting period, you can unlock your position instantly by paying an unlock penalty. The unlock penalty is 50% at max lock duration (36 months), and reduces linearly based on the lock time remaining.
   3. **Extend:** If you selected less than the max lock duration, you can extend it whenever you want.
   4. **Merge:** If you have multiple veRWA positions, you can merge them into a combined lock. Note that the resulting lock will default to the lock period of the longer duration.
   5. **Split:** You can also split an existing lock into up to 12 new positions to manage them individually.
   6. **Transfer:** Finally, you can transfer your lock to a different wallet address.
7. When rewards start accruing, you can claim them from the [Lock & Claim page](https://www.re.al/app/lock-and-claim) or directly from the [My Balances page](https://www.re.al/app/my-balances).


# How to Bridge from re.al (to Ethereum and L2s)

{% embed url="<https://youtu.be/GrwmFPiSwo4>" %}

## Bridge out of re.al: Step-by-Step Guide

1. Make sure you are on the [Bridge page](https://www.re.al/app/bridge/).
2. Click on “Connect Wallet” and select your preferred wallet.
   1. In this demonstration, Metamask is selected. Note that using other wallets might result in different prompts in your wallet.
3. Confirm the connection in Metamask.
4. Input the amount of the tokens you want to bridge out, and select the destination chain. You can choose any token from the list of available tokens.
   1. If you want to bridge out to Ethereum or directly to other L2s in just 15-30 minutes, you can use tokens deployed as OFT such as USTB, MORE, and arcUSD. The available destination chains depend on where these OFTs are deployed.
      1. Bridge USTB to Ethereum Mainnet and unwrape for USDM, swap USDM on Curve
      2. Bridge MORE or arcUSD to Binance Smart Chain and swap for other tokens on [Thena](https://docs.re.al/get-started/network-guides-and-videos/www.thena.fi).
   2. Note that bridging out ETH to Ethereum will require a challenge period of about 7 days, since re.al is an optimistic rollup. After this initial challenge period, users can claim their withdrawal from the “Pending Transactions” tab, and decide whether to redeem ETH instantly, incurring swap fees on Ethereum mainnet, or complete the redeeming process from Lido, which will extend the process depending on the Lido protocol.
   3. Bridging out other tokens to Ethereum such as USDC, USDT, DAI, WBTC will require just the 7-day challenge period. After the challenge period, you will be able to claim the withdrawal from the “Pending Transactions” tab, receiving your tokens to Ethereum shortly after.
5. Start the bridging process. Approve token spending, and sign the bridging transaction. Make sure you have enough reETH on re.al to cover gas fees.
6. If you are bridging out OFTs it will take about 15-30 minutes for your tokens to show up on the selected chain. Current OFT exit options:


# Overview

The RWA token is the governance token to the **re.al** ecosystem. RWA will exist unlocked as RWA (ERC-20) and locked as veRWA (ERC-721). When locked into veRWA it will provide holders two primary benefits:

1. **Value Accrual:** Transaction fee revenue, RWA sales tax and revenue share from the protocols building on the chain will return to veRWA holders.
2. **Governance Rights:** Help determine the future of **re.al** through future governance votes

**$RWA is the first L2 token to comprehensively capture of the value of the chain and return it to holders.**

**All revenue to veRWA is distributed in** [**reETH**](/get-started/reeth-native-token)**.**

veRWA positions will eventually be traded in the Tangible veRWA Marketplace and future NFT marketplaces supporting **re.al** and veRWA.

<table><thead><tr><th width="291">Indicator</th><th>Details</th></tr></thead><tbody><tr><td>Ticker</td><td>RWA</td></tr><tr><td>Token Type</td><td>ERC-20, Native</td></tr><tr><td>Total Supply</td><td>33,303,472 at deployment</td></tr><tr><td>Inflation Schedule</td><td>Negative, deflationary tokenomics</td></tr><tr><td>Decimals</td><td>18</td></tr><tr><td>Contract Address</td><td><code>0x4644066f535Ead0cde82D209dF78d94572fCbf14</code></td></tr><tr><td>Chain</td><td><strong>re.al</strong></td></tr></tbody></table>

## Background

RWA is a migrated version of the TNGBL token, the governance token of TangibleDAO, and it inherits several features from its pervious iteration. However, the RWA token also includes several new mechanism including updated vote escrow contract tokenomics and a taxing system implemented on buys & sells.

All TNGBL tokens can migrate to RWA in a 1:1 exchange; the RWA supply will never exceed the total supply for TNGBL at the moment RWA deploys.

Users will not be forced to migrate and migration will not be deprecated prior to the last TNGBL unlock on April 13th, 2026. After that date, migration will only be closed through a governance vote.

[Full migration details here.](/rwa-token/migration)

TNGBL tokens can migrate their tokens to RWA via the migration page which will deploy when the chain goes live.

More details on the TNGBL token can be found in the [Tangible Docs](https://docs.tangible.store/tngbl-and-marketplace/tangible-token-tngbl).

## Tokenomics Overview

Locked veRWA is designed to [accrue revenue](/rwa-token/rwa-tokenomics) from the protocols building on **re.al**, with *all* protocols incentivized to send a share of their revenue to RWA token lockers. reETH transaction fees as well as a portion of the [sales tax](/rwa-token/rwa-tokenomics#taxing-system) on RWA trades will be shared with veRWA holders.&#x20;

Features:&#x20;

1. All chain revenues from **re.al** will be distributed proportionally to veRWA holders in reETH, based on voting power.&#x20;
2. No new RWA can be minted.
3. The entire supply of RWA, either locked or unlocked, is in circulation. There are no future team or VC unlocks.
4. RWA is deflationary. When veRWA positions are [unlocked early](/rwa-token/managing-verwa#unlock-early-penalty-unlock), a penalty is applied and those tokens are burned.
5. RWA's [locking mechanism](/rwa-token/rwa-tokenomics#voting-power-and-value-accrual) is similar to that of the Solidly aka ve(3,3) model, where the more RWA you have locked and the longer period you lock for, the greater the veRWA voting power.
6. veRWA remains [perpetually locked](/rwa-token/rwa-tokenomics#vesting-and-value-accrual) at the selected duration unless deposited into the [vesting contract](/rwa-token/contracts#votingescrowvesting). Once deposited into the vesting contract, voting power reduces linearly with the lock duration until it reaches zero, at which point the underlying  tokens can be removed.
7. &#x20;veRWA NFTs can be [split and merged](/rwa-token/managing-verwa), allowing users full flexibility over their positions.


# RWA Tokenomics

RWA is unique to other L2 network tokens in that it accrues value from both the protocols and transaction activity on the chain, a comprehensive representation of network value.

These funds are distributed back to veRWA holders, proportionate to their veRWA [voting power](#voting-power-and-value-accrual). For example, a user with .005% of the veRWA voting power will receive .005% of the  revenue collected by RWA.

**All veRWA revenue is distributed in reETH.**

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

## RWA Value Accrual

The chart below details the various revenue streams distributing back to veRWA.

<table><thead><tr><th width="152">Protocol</th><th width="226">Revenue Source</th><th>Distribution</th></tr></thead><tbody><tr><td><strong>re.al</strong></td><td>Transaction Fees</td><td>100% of reETH profit</td></tr><tr><td>Tangible</td><td>Baskets rental yield</td><td>10% of all incoming rental yield</td></tr><tr><td>Tangible</td><td>Marketplace Fees</td><td>1% - Real estate TNFT secondary sales<br>2.5% - Gold TNFT, veRWA secondary sales</td></tr><tr><td>Pearl</td><td>CAVIAR incentives</td><td>20% of CVR accrued incentives</td></tr><tr><td>Pearl</td><td>ALM Fees</td><td>10% of user rewards managed by Trident</td></tr><tr><td>Stack</td><td>MORE borrowing fees</td><td>50% of borrowing fees</td></tr><tr><td>Arcana</td><td>Delta-neutral trades</td><td>50% of revenue (5% of all trade profits)</td></tr></tbody></table>

*Last updated: October 15th, 2024*

## veRWA Details

<table><thead><tr><th width="295">Indicator</th><th>Details</th></tr></thead><tbody><tr><td>Ticker</td><td>veRWA</td></tr><tr><td>Token Type</td><td>ERC-720, Native (NFT)</td></tr><tr><td>Total supply</td><td>Cannot exceed supply of RWA</td></tr><tr><td>Contract Address</td><td><code>0xa7B4E29BdFf073641991b44B283FD77be9D7c0F4</code></td></tr><tr><td>Chain</td><td><strong>re.al</strong></td></tr></tbody></table>

## Voting Power and Value Accrual

Locking RWA into veRWA is required to get access to revenue share from **re.al**.

RWA can be locked for a period of 1 month to 36 months.

Longer locks result in higher veRWA voting power. The higher the veRWA voting power, the more **re.al** revenue that NFT is entitled. It also means a longer vesting period to unlock the underlying tokens. Shorter lock periods result in a faster vesting period, but reduce the voting power and subsequently the revenue share.

#### Calculating Voting Power:

`voting power = lockedAmount * vestingDuration / MAX_VESTING_DURATION`

`MAX_VESTING_DURATION = 93312000`

Max vesting duration calculated in seconds using the Solidity calculation of seconds/day = 86400

<table><thead><tr><th width="155">RWA TOKENS</th><th width="252">LOCK DURATION (MONTHS)</th><th width="189">VE VOTING POWER</th><th>REV SHARE %</th></tr></thead><tbody><tr><td>200</td><td>1</td><td>5.56</td><td>x</td></tr><tr><td>200</td><td>6</td><td>33.33</td><td>6x</td></tr><tr><td>200</td><td>12</td><td>66.67</td><td>12x</td></tr><tr><td>200</td><td>24</td><td>133.33</td><td>24x</td></tr><tr><td>200</td><td>36</td><td>200</td><td>36x</td></tr></tbody></table>

## Vesting and Value Accrual

veRWA positions are designed to maintain the voting power resulting from the lock amount (total tokens locked) and the lock duration. Unlike other vote escrow tokens, there is no need to relock to maintain voting power.&#x20;

To claim the underlying tokens in a veRWA position, the user must deposit the token into the [vesting contract](/rwa-token/contracts#votingescrowvesting). Once deposited, the token will undergo a vesting period, after which time the user can unlock and claim the underlying tokens on vesting completion. Vesting timing is analogous to lock duration. A one-year lock on a veRWA will take one year in the vesting contract to unlock.

{% hint style="danger" %}
**Users cannot vest and claim rewards at the same time.**

The vesting contract takes ownership over the veRWA and the vote power immediately goes to zero. Any fees that would normally accrue to the token are now distributed amongst all other unvested veRWA token positions.&#x20;
{% endhint %}

Vesting time accrued carries over even if the token is removed from the contract. A token can be deposited in the vesting contract for one week and then removed, reducing the lock duration/vote power by one week of vesting. At a later time, it can be redeposited and continue to vest having already accrued a week of vesting at an earlier date.

## Taxing System

RWA includes a taxing system that taxes buys & sells of unlocked RWA, it is not applied on pier-to-pier transfers.

The configurable fee launched with a 5% tax.&#x20;

On July 1st, the tax was reduced to 2%, eliminating the burn (2%) and liquidity provision (1%) while retaining the 2% distribution back to veRWA holders in reETH.

On September 16th, the tax was modified where the 2% fee charged on RWA swaps is permanently burned, instead of being distributed back to veRWA holders as reETH.

In the future, this fee may be reduced or removed entirely, changes approved via multisig transaction.

## Unclaimed Rewards

Any reETH which is unclaimed six months after its initial distribution to a veRWA account will be returned back to the revenue distributor and redistributed between all users. Only the amount of reETH which is unclaimed longer than six months will be redistributed, not the full claimable amount.


# Reporting veRWA APY

The RWA App includes a [dashboard](https://www.re.al/app/rwa-metrics) that gives users the opportunity to look at veRWA yield sources and current/historical veRWA APYs.

veRWA APYs are presented in a rolling seven-day average to reduce noise.

The APY figure assumes the veRWA yields are compounded back into veRWA, hence the utilization of APY vs APR.

Lastly, we’ve maintained the historical APY at the time it was accrued vs the data adjusting for the current price of RWA. For example, the same amount of accrued yield with RWA at $1 and RWA at $10 is going to show a much different APY. Our data preserves the APY as it was experienced with the RWA price at that time yield was distributed.

### APY methodology

**re.al** pulls the individual revenue streams for a time period, and voting power at time of each revenue event, computes returns based on that, and compounds them.  We then annualize based on the length of the selected time period.

In most cases this period is seven days. However the re.al enables users to see compounded annualized returns across multiple time periods. For example, if the user selects a one month period the data within the yield chart will update to show the compounded annualized returns for the previous month.

#### How it works:

1. **re.al** pulls the individual revenue streams for a time period
   1. Let's assume this is 30 days, and there are 100 revenue events each day, so 3,000 in total
2. **re.al** applies the current price and total voting power for each timestamp
   1. With 3,000 revenue events, there are potentially 3,000 different prices of RWA, and 3,000 different total voting power numbers
   2. In this case, 3,000 different returns are calculated
3. Returns are compound them for that time period
   1. &#x20;For example: (1 + ret1)(1 + ret2) ... (1 + retn) - 1
4. Lastly, returns are annualized i.e. (1 + return) ^ (365 / period) - 1


# Managing veRWA

All RWA transactions and asset management can be done on the RWA dApp on the **re.al** site, including buy and sell (swapping through the pools on Pearl), claim, lock, unlock and other management features.

### Claim Rewards

veRWA revenue is claimed in the RWA dApp on the **re.al** site. Proceeds accrue by block and can be claimed at any time. All rewards distributions to veRWA are paid in in reETH.&#x20;

The [account-based accrual](/rwa-token/rwa-tokenomics#account-based-accruals) system makes it easy to claim rewards as all veRWA NFTs held in one wallet will consolidate into one claim for the user, accessible on from the **re.al** dApp.

<figure><img src="/files/XLL4JPMHVq7ox0t0bej2" alt=""><figcaption><p>Claim Rewards in the dApp</p></figcaption></figure>

Proceeds left unclaimed for more than 180 days will be redistributed to other veRWA holders.&#x20;

### Locking

Locking RWA into veRWA entitles users to a percentage of **re.al** revenues proportional to the veRWA [voting power.](/rwa-token/rwa-tokenomics#voting-power-and-value-accrual)&#x20;

Locks can be created at any length of time between one and 36 months, with voting power going up proportionally based on lock duration.

Simply select the amount of RWA to lock and the duration to create a new veRWA position.

<figure><img src="/files/8kq4G7GQMfB6wSRB9Yq0" alt=""><figcaption><p>Lock RWA</p></figcaption></figure>

#### Extend Lock

veRWA locks can be extended at any time, up to the maximum 36 months, resulting in increased veRWA voting power.

Consequently, with increased duration and voting power, the [vesting period](#vesting-and-value-accrual) to unlock the underlying tokens also extends and the [unlock penalty](#unlock-early-penalty-unlock) increases.

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

#### Increase Locked Tokens (Merge)

To increase the number of RWA underling a veRWA position, the users must:

1. Create an additional new lock (example above) with the tokens they wish to add to the existing veRWA position
2. Merge the new veRWA into the existing veRWA

{% hint style="warning" %}
**The new lock will default to the higher lock duration of the two locks being merged.**

20 RWA locked for 36 months merged into 4,500 locked for one month will create a position of 4,520 RWA locked for 36 months.

The direction of the merge is irrelevant.
{% endhint %}

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

### Unlock Early (Penalty Unlock)

veRWA can be unlocked at any time, however the user will pay a penalty (fee) to access the underlying tokens early.  The unlock fee is 50% at 36 months and reduces linearly by block based on the lock time remaining.

<table data-full-width="false"><thead><tr><th width="176">veRWA LOCKED</th><th width="151">LOCK REMAIN</th><th width="108">PENALTY</th><th width="157">RWA RECEIVED</th><th>RWA BURNED</th></tr></thead><tbody><tr><td>200</td><td>36 months</td><td>50%</td><td>100</td><td>100</td></tr><tr><td>200</td><td>24 months</td><td>33.33%</td><td>133.33</td><td>66.67</td></tr><tr><td>200</td><td>12 months</td><td>16.67%</td><td>166.67</td><td>33.33</td></tr><tr><td>200</td><td>6 months</td><td>8.33%</td><td>183.33</td><td>16.67</td></tr><tr><td>200</td><td>1 months</td><td>1.39%</td><td>197.22</td><td>2.78</td></tr></tbody></table>

**RWA tokens forfeited to unlock early are burned and can never be minted again.**

<figure><img src="/files/o9PDmEM08fCWk7dka5X9" alt=""><figcaption><p>Unlock Early Transaction</p></figcaption></figure>

An alternative to unlocking early is [vesting](/rwa-token/rwa-tokenomics#vesting-and-value-accrual), which allows the user to withdraw the unlocked, underlying RWA after a vesting period that's equal to the lock duration. No rewards are accrued during vesting.

### Manage

Like other veNFTs, veRWA can be managed by the holder to suit their needs. The locked tokens can split (to sell or unlock a portion of the total position early), transferred to another wallet or user or merged to increase the lock amount.

## Delegating veRWA

veRWA can be delegated by its owner to other wallets which will now have the right to claim the revenue eligible to that veRWA.


# stRWA and wstRWA

stRWA is a liquid version of veRWA that rebases to distribute accrued yield, making veRWA liquid and composable with DeFi protocols.

stRWA is 100% backed by max-locked veRWA.

veRWA holders accrue value from the **re.al** and protocols deployed to it, these positions earn reETH rewards.

With stRWA, this reETH is collected, swapped for RWA, and distributed as daily rebases directly to stRWA holders' wallets.

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

### How It Works

1. Users can mint stRWA with unlocked RWA at <https://www.re.al/app/mint>&#x20;
   1. There is no fee to mint. Locked RWA (veRWA) cannot be used for minting.
2. &#x20;The RWA is max-locked into veRWA, which serves as the backing for stRWA.
3. As veRWA earns reETH yield, this is collected, swapped for RWA, and distributed as daily rebases.
   1. 80% of the RWA from reETH yield is merged into veRWA backing and distributed.
   2. 20% is burned, permanently reducing supply and increasing veRWA yield.
4. stRWA rebases daily to reflect new RWA merged into the backing and automatically distributes to holders wallets.
5. veRWA can be withdrawn from stRWA for a 3.5% fee, giving users full control of their max-locked veRWA position.

{% hint style="info" %}
Rebase and burn allocations are configurable, including the option to retain some yield to overcollateralize stRWA.
{% endhint %}

### Cross-Chain Compatibility

stRWA is natively cross-chain, powered by LayerZero's OFT technology.

When bridged across chains, stRWA is automatically wrapped into wstRWA, which accrues value instead of rebasing. That value can be unlocked by briding back to real where stRWA is received.


# RWA Rewards Program

The veRWA rewards program is officially live at <https://www.re.al/rewards>

**Our goal is to create the most transparent and value-driven airdrop campaign in DeFi, with rewards values that can be verified by any user.**

Recognizing the fatigue and frustration caused by long, opaque points systems, we've designed a program that offers clear and immediate insights into earnings, ensuring a fair and engaging experience for all participants.

**No more projecting FDV to calculate rewards value. Using the live trading price of $RWA, users can see the current dollar value of their rewards at any time. This makes it easy for users to calculate their personal program APR.**

Starting with the first block after 00:00 UTC on July 1st, our reporting algorithm will begin tracking on-chain TVL and wallet activity for the Season 1 rewards. The reporting algo can be reviewed at any time.

While users will need a referral link to join the program, all on-chain activity will be retroactively captured and credited to users upon sign-up. Referral links will be shared by ecosystem partners and supporters on Twitter, follow us for more info.


# Overview and Goals

The Rewards Program is designed to attract users to re.al and incentivize their active participation in the ecosystem. By offering 10% of RWA supply to new users, the program aims to foster a loyal user base that is invested in the long-term success of re.al.

Key Goals:

* Attract Liquidity: We aim to kickstart a thriving ecosystem by offering rewards for bridging to the chain and providing liquidity.
* Introduce Apps: Users can activate multipliers by engaging with different apps on re.al, allowing them to experience key features and benefits that could attract them for the long-term.&#x20;
* Reward Participants: Users who contribute to the ecosystem's growth will be rewarded with veRWA tokens, representing a share in decentralized governance.

**veRWA will be distributed in a locked position**, encouraging long-term commitment to the ecosystem. **To unlock the position, a portion of the RWA must be** [**burned**](https://docs.re.al/rwa-token/managing-verwa)**.** This permanently reduces supply and benefits remaining holders via increased yields. The veRWA unlock penalty discourages short-term speculative behavior while enhancing the value proposition for long-term holders.

[Learn more](/rwa-token/rwa-tokenomics) about veRWA tokenomics and ecosystem revenue sharing.


# Program Specifics

{% hint style="danger" %}
**US persons including US residents are not eligible to access or redeem points.**
{% endhint %}

The [Rewards Program](https://www.re.al/rewards) emphasizes transparency and real-time value tracking, ensuring participants always know the token total and dollar value of their rewards.

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

* 3.33 million RWA (10% of the total supply) will be distributed over an 8 month period.
* The first season will start on July 1st, and it will end on August 31st.
* 100% of the tokens will be distributed to users

{% hint style="warning" %}
5% of the Season 1 token supply will be allocated to a “pre-season,” rewarding early users/farmers who engaged with re.al prior to the Rewards Program launch on July 1st|. <br>

The team reserves the right to redistribute future multipliers at any time, impacting future rewards earnings, not past rewards accruals.
{% endhint %}

The tokens being tracked and their corresponding points multiplier will be kept up-to-date in the program UI. This ensures all users have full transparency into how rewards are calculated and where they can earn the most rewards.

<figure><img src="https://lh7-us.googleusercontent.com/docsz/AD_4nXc2aIeJgFmnS5STME0dkFiz_2xIQANF6YbpJpwoZ5QFNEm9eEXHvPlBx5YP2me8hHzCLQq5yJYLmPTUvz732ySIIqomCIvx6l6LyrXvl7Xy-Vv2wEI3kweLq-PRYR2leGsFqeRVS65Blci6DbjQqzFK6bSO?key=E8Cb8KF0R9qkNGZ-holCIg" alt=""><figcaption><p>NOTE: Please check the app for the latest updates on rewards and multipliers</p></figcaption></figure>

Our program is designed to be sybil-resistant and fair, rewarding users based on their TVL held on the chain and the value of their actions, with additional incentives for specific high-value transactions and activities.

## Season 2 Updates

**Up to 50% of daily Season 2 points will be allocated to blockspace rewards, distributed based on the amount of transaction fees paid.**

This allocation will be distributed to both individual users or contracts paying the transaction fees as well as the protocols and contracts responsible for necessitating the transaction.

How it works:

* Up to 50% of daily points will be allocated based on gas expenditure, starting with 1% on the first day of Season 2 and increasing over time as transactions increase.
* Half of that to users spending the gas, half to the protocols necessitating the transaction
* We will be scanning for all events on the chain and then allocating gas rewards (points) to the user or protocol wallets spending the transactions costs
* We will be excluding the genesis protocols (re.al, Tangible, Pearl, Stack, Arcana) from the protocol allocation, rewards will go exclusively to new protocols deploying onto the chain
* New protocols can connect with the team to register the contracts/events we’ll need to track in order to link those transactions back to the correct protocol as well as provide a wallet for rewards
* We’ll add new protocols to the leaderboard like we do with any other program participant, they’ll receive a referral code to onboard their users
* Protocols can determine if they want to redistribute rewards or keep them to build stake in the ecosystem and support ongoing activity through veRWA yields

Our goal is to make it easy for protocols to distribute earned points back to their users if they choose and will help with any integrations and endpoint development to make it easy for them to reflect rewards in their protocol.

The team reserves the right to remove points we determine to be accrued through system abuse. Transaction volume should have a productive impact on protocols or chain operations. Needlessly spamming the chain with transactions will result in forfeiture of points.


# Referrals

<figure><img src="https://lh7-us.googleusercontent.com/docsz/AD_4nXdC6v_PDQ9V1XsaX5cjFLIsx3RBGXP_Uw2bQY33znyjA5mjF6kzaB-0OBFfQTPWPNgVX0EnXpCrIIeRd0nC-hLIDWBcdC-1LraY_GzpeOyaAMFH62L6Rm63BdphAnor8Jy5EJuynamIsPneWUW5Ia8ThvRb?key=E8Cb8KF0R9qkNGZ-holCIg" alt=""><figcaption></figcaption></figure>

We believe that referrals can be a powerful tool for users to earn additional rewards and for re.al to gain broader exposure through their networks. Therefore, all participants in the program must be referred by another participant via a referral link.

For ecosystem participants with very large networks and reach, referring users is a highly lucrative initiative in itself and a fair exchange for the publicity they create for re.al.

The referral link used during sign-up ties your account to the user who referred you and entitles them to a distribution of 10% of the rewards you earn. This includes 10% of any points you may earn from referring other users. There are no additional tiers to the program, however this chain of distributing 10% of your total rewards back to the user who referred you can continue infinitely down the line.<br>


# Calculating Points

Transparency is paramount in this program, which is why the reporting algorithm is being shared publicly in addition to our disclosures on tokens and multiplier rewards.

Points will be calculated based on average time-weighted exposures over the holding period. Large positions held briefly will receive fewer points, and flash-loan transactions will earn zero points.

We will automatically monitor key protocols such as the [bridge](https://www.re.al/bridge) and [RWA app](https://www.re.al/app/), [Pearl](https://www.pearl.exchange), [Tangible](https://www.tangible.store), [Stack](https://www.stackmore.xyz), and [Arcana](https://www.arcana.finance). As new protocols deploy on re.al, they will be evaluated for inclusion in the rewards program based on their contributions to the chain.

All transfers will be scanned to calculate each user's average holdings, including rebases and new NFT mints. Swaps on Pearl will also be tracked, with rewards capped to discourage bot activity.

Points will be computed off-chain and verifiable by anyone. We reserve the right to adjust the algorithm or remove points from wallets that abuse the system. Point totals will be updated daily with all eligible on-chain activity receiving the correct share of points based on current multipliers.

Visit our [Discord](https://discord.com/invite/cKCCCFXvWj) for additional support on the program and follow us on [Twitter](https://twitter.com/real_rwa) for more updates on the growth of the re.al ecosystem.&#x20;

## Points Reporting Algo

Transparency is fundamental to our team and a critical component to what makes this rewards program unique. As such, the scraping tool used to identify and record user points can be reviewed at any time at this link:\
\
<https://github.com/re-al-Foundation/re-al-Points>

**Policy on Report Revisions:**

1. We will not correct the reports based on the particulars of any individual user's accrued points nor will we change the points for any individual wallet balance
2. If you believe we are miscalculating something fundamental, please open a ticket and we will explore
3. If systemic inaccuracies are discovered, we will adjust and recalculate for all users

We also reserve the right to adjust the algorithm and/or multipliers at any time. We will share those updates as they're made.


# Migration

## Token Exchange

**re.al** and the RWA token will launch in the coming weeks.

As part of this process, TNGBL token holders and locked TNGBL token holders (3,3+) will have the option to migrate to the RWA token, the governance token for **re.al**.

There are 2 types of TNGBL tokens, locked TNGBL  (3,3+ NFT) and unlocked TNGBL. The migration process will be similar for both tokens.

Users who migrate their 3,3+ NFT will receive a veRWA NFT with an identical locked balance. Users who migrate TNGBL tokens will receive RWA tokens at a 1-to-1 value.

The lock lengths will remain the same through the migration. I.e if you have a TNGBL 3,3+ NFT on Polygon with 34 months remaining on the lock, you will receive a veRWA NFT on **re.al** with 34 months remaining on the lock.&#x20;

The TNGBL token total and the end of the lock period will be the amount of RWA locked into the new veRWA. For example, a 3,3+ NFT with 1,000 TNGBL due at the end of the lock will migrate to a veRWA NFT with 1,000 RWA locked into the position.

**Please familiarize yourself with the** [**veRWA tokenomics**](/rwa-token/rwa-tokenomics#vesting-and-value-accrual) **prior to migration as they differ from TNGBL 3,3+.**

{% hint style="info" %}
Users will never be forced to migrate and can migrate over to RWA at any point.

Keep in mind revenue share will no longer distribute to TNGBL and TNGBL liquidity provided by the protocol will be removed to fund RWA liquidity on **re.al.**

The migration UI will be kept up indefinitely, unless a governance vote to close migration is passed, which can only be done after the final TNGBL locks have fully vested.&#x20;
{% endhint %}

## Migration Details

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

This ecosystem takes advantage of [LayerZero v1](https://layerzero.gitbook.io/docs/faq/what-is-layerzero-v1) to facilitate cross-chain messaging. The CrossChainMigrator contract will spark the migration by taking the current state of the migrated asset and transferring that state over to the new contracts on Real Chain.

The CrossChainMigrator will send a message to the LayerZero endpoint on Polygon to then be passed by their Relayer over to Real Chain where the message will be passed to the RealReceiver contract.


# Contracts

## Contracts & Addresses

#### re.al

<table><thead><tr><th width="283">Contract</th><th>Address</th></tr></thead><tbody><tr><td><code>API</code></td><td><code>0x42EfcE5C2DcCFD45aA441D9e57D8331382ee3725</code></td></tr><tr><td><code>DelegateFactory</code></td><td><code>0x4Bc715a61dF515944907C8173782ea83d196D0c9</code></td></tr><tr><td><code>RWAToken</code></td><td><code>0x4644066f535Ead0cde82D209dF78d94572fCbf14</code></td></tr><tr><td><code>RWAVotingEscrow</code></td><td><code>0xa7B4E29BdFf073641991b44B283FD77be9D7c0F4</code></td></tr><tr><td><code>RealReceiver</code></td><td><code>0x4CF64C6d51fFbF50A743C11fA800E40F7946Fc7f</code></td></tr><tr><td><code>RevenueDistributor</code></td><td><code>0x7a2E4F574C0c28D6641fE78197f1b460ce5E4f6C</code></td></tr><tr><td><code>RevenueStreamETH</code></td><td><code>0xf4e03D77700D42e13Cd98314C518f988Fd6e287a</code></td></tr><tr><td><code>RevenueStreamRWA</code></td><td><code>0x9D146A1C099adEE2444aFD629c04B4cbb5eE1539</code></td></tr><tr><td><code>RoyaltyHandler</code></td><td><code>0x164f1622207AaAbCd32839ED4B0d97c3387C2492</code></td></tr><tr><td><code>VotingEscrowVesting</code></td><td><code>0x2298963e41849a46A5b4aD199231edDD9ecce958</code></td></tr><tr><td><code>stRWA</code></td><td><code>0x154F5DB4950d2cd4a7Af425E11865215F90DdB07</code></td></tr><tr><td><code>stRWARebaseManager</code></td><td><code>0x33E10DD4794D0213cf65F2dde68dFd55f0D57baD</code></td></tr><tr><td><code>TokenSilo</code></td><td><code>0x1A9388A0fbA95A570583e036a3B1e6926613aE8d</code></td></tr></tbody></table>

#### Cross-Chain

<table data-header-hidden><thead><tr><th width="287"></th><th></th></tr></thead><tbody><tr><td><code>CrossChainMigrator (Polygon)</code></td><td><code>0x602B3fA8C9526dEA7FE44E99963faCF28DC67bbc</code></td></tr><tr><td><code>wstRWA (all non-re.al chains)</code></td><td><code>0x154F5DB4950d2cd4a7Af425E11865215F90DdB07</code></td></tr></tbody></table>

## CrossChainMigrator

#### Description

This contract inherits \`NonblockingLzAppUpgradeable\`. This contract handles migration of $TNGBL holders and 3,3+ NFT holders. This contract will spark a migration from Polygon to Tangible's new Real Chain. The migrators will receive the RWA or veRWA equivalent on Real Chain. This contract takes advantage of the LayerZero protocol to facilitate cross-chain messaging. When a migration occurs this contract will bottle up all the necessary information in the form of payload and send it to the local LayerZero endpoint.

#### Key Features

* On 3,3+ NFT migrations, the CrossChainMigrator contract will take the 3,3+ NFT into custody and send a message containing all of the current lock data to the RealReceiverNFT on Real Chain.
* Does support batch NFT migrations for any users who hold more than one 3,3+ NFT.
* On $TNGBL migrations, the CrossChainMigrator contract will burn the migrated $TNGBL tokens and send a message to the RealReceiverRWA on Real Chain to mint new tokens.

## RealReceiver

#### Description

This contract inherits \`NonblockingLzAppUpgradeable\` and facilitates the migration message from the source on Polygon to the migration method on the destination contract. This contract receives the cross-chain message in the form of a payload. The RealReceiver checks the payload to decide if the message is for a NFT or token migration and finishes the migration process by calling mint to the proper contract; Either VotingEscrowRWA or RWAToken.

#### Key Features

* Can receive a message from the local LayerZero endpoint.
* Will decode the received payload to decide which payload-type it was
* * NFT migration
  * Batch NFT migration
  * Or Token migration
* Will mint the proper token to the corresponding user.

## RevenueDistributor

#### Description

This is in charge of collecting all revenue. When it is called by a permissioned admin or gelato function, it will swap all revenue tokens to ETH then deposit all ETH into the RevenueStreamETH contract.

#### Key Features

* Collects all revenue in various revenue tokens
* When executed, will swap all revenue tokens to ETH before distributing it to the RevenueStreamETH contract where it can be claimed by stakeholders

## RevenueStreamETH

#### Description <a href="#description.3" id="description.3"></a>

This contract facilitates the distribution of claimable revenue to veRWA shareholders. This contract will facilitate the distribution of ETH revenue only.

#### Key Features <a href="#key-features.3" id="key-features.3"></a>

* Eligible stakeholders can claim their ETH revenue share from this contract.
* If revenue becomes expired, Tangible will send it back to the RevenueDistributor after 6 months of claimable revenue sitting.

## RWAToken

#### Description

ERC-20 contract for $RWA token. This contract facilitates any minting or transferring of $RWA tokens.

#### Key Features

* Implements a 5% tax on swaps.
* Allows an admin to blacklist a wallet from swapping tokens, or transferring tokens.
* Allows an admin to whitelist an address to exclude it from taxes.

## RoyaltyHandler <a href="#royaltyhandler" id="royaltyhandler"></a>

#### Description

Manages royalties accrued from $RWA swaps. The $RWA Token consists of a 5% swap tax. The taxed tokens will end up in this contract and distributed accordingly.

#### Key Features <a href="#key-features.5" id="key-features.5"></a>

* Royalties are distributed asynchronously to the following endeavors.
  * 40% of the RWA balance in the RoyaltyHandler will be burned
  * 40% of the RWA balance in the RoyaltyHandler will be used for revenue share and sent to the RevenueDistributor
  * 20% will be deposited into an RWA/WETH ALM contract for liquidity rebalancing
    * The LP tokens received from this deposit will be staked
* Distribute method to distribute royalties to the pre-determined places, mentioned above. This method is permissionless
* Allows an admin to update the % distribution

## RWAVotingEscrow

#### Description

An ERC-721 token contract that inherits VotesUpgradeable and assigns voting power based on the quantity of locked tokens and their vesting duration. It is designed to incentivize long-term holding and participation in governance. Locked token of choice is RWAToken.

#### Key Features

* ERC721 token representing locked tokens with vesting duration.
* Voting power calculation based on locked token amount and vesting duration.
* Functions to mint, burn, split, and merge locked token positions.
* Upgradeable contract design using UUPS pattern.

## VotingEscrowVesting

#### Description

The VotingEscrowVesting contract manages the vesting schedules for tokens locked in the VotingEscrow system. It allows users to deposit their VotingEscrow tokens, undergo a vesting period, and then either withdraw them back or claim the underlying locked tokens upon vesting completion.

#### Key Features

* Deposit VotingEscrow tokens to start their vesting schedule.
* Withdraw VotingEscrow tokens back to the depositor after the vesting period.
* Claim the underlying locked tokens upon vesting completion, burning the VotingEscrow token.
* Manage vesting schedules and track depositors' vested tokens.

## DelegateFactory

#### Description

This contract acts as a factory for creating Delegator contracts.

#### Key Features

* Uses the Upgradeable Beacon Proxy pattern.
* Deploys new delegator beacon proxies.
* Can delete delegators upon their expiration date

## Delegator

#### Description

This contract is used to delegate voting power of a single veRWA NFT to a specified account. This contract will be created by the DelegateFactory and will be assigned a delegatee. Upon creation, a veRWA NFT will be deposited and the voting power is delegated to the delegatee.

#### Key Features

* Holds a delegated NFT until revoked by the factory.


# RWA Technical

## CrossChainMigrator

### Key Methods

All migrate methods contain an extra parameter, \`\_airdropData\`. This argument is used in the event the migrator wants to receive an airdrop of native ETH on the destination chain. For more info on how to use this param: <https://layerzero.gitbook.io/docs/evm-guides/advanced/relayer-adapter-parameters>

msg.value for each migrate method must not be 0. It is used to specify (and pay) an amount of gas for consumption on the destination chain. You can get a gas quote from \`endpoint::estimateFees()\`.

#### **migrateNFT**

{% code overflow="wrap" %}

```javascript
function migrateNFT(uint256 _tokenId, address to, address payable refundAddress, address zroPaymentAddress, bytes calldata adapterParams) payable external;
```

{% endcode %}

Used to migrate a single PassiveIncome NFT from Polygon to Real chain. This method will take a user's PI NFT specified and send a message to the Polygon LayerZero endpoint to be later passed to the destination chain.

#### **migrateNFTBatch**

{% code overflow="wrap" %}

```javascript
function migrateNFTBatch(uint256[] memory _tokenIds, address to, address payable refundAddress, address zroPaymentAddress, bytes calldata adapterParams) payable external;
```

{% endcode %}

This method is used to migrate a batch of PassiveIncome NFTs from Polygon to Real chain. This method will take a user's PI NFTs specified and send a message to the Polygon LayerZero endpoint to be later passed to the destination chain for a batch migration.

#### **migrateTokens**

{% code overflow="wrap" %}

```javascript
function migrateTokens(uint256 _amountaddress to, address payable refundAddress, address zroPaymentAddress, bytes calldata adapterParams) payable external;
```

{% endcode %}

This method is used to migrate TNGBL tokens from Polygon to RWA on Real chain. This method will burn TNGBL tokens from the migrator then send a mintFor message to the RWA contract on Real chain.

## RealReceiver

### Key Methods

#### **lzReceive**

{% code overflow="wrap" %}

```javascript
function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;
```

{% endcode %}

LayerZero endpoint will invoke this function to deliver the message on the destination.

## RevenueDistributor

### Key Methods

#### **convertRewardToken**

{% code overflow="wrap" %}

```javascript
function convertRewardToken(address _token,uint256 _amount,address _target,bytes calldata _data) external;
```

{% endcode %}

Converts a specific revenue token to ETH and distributes it to the revenue stream.

#### **convertRewardTokenBatch**

{% code overflow="wrap" %}

```javascript
function convertRewardTokenBatch(address[] memory _token,uint256[] memory _amount,address[] memory _target,bytes[] memory calldata _data) external;
```

{% endcode %}

Converts a batch of revenue tokens to ETH and distribute to the revenue stream.

#### **addRevenueToken**

{% code overflow="wrap" %}

```javascript
function addRevenueToken(address _revToken) external;
```

{% endcode %}

This method is used to add a new supported revenue token.

#### **removeRevenueToken**

{% code overflow="wrap" %}

```javascript
function removeRevenueToken(address _revToken) external;
```

{% endcode %}

This method is used to remove an existing revenue token.

#### **setSelectorForTarget**

{% code overflow="wrap" %}

```javascript
function setSelectorForTarget(address _target, bytes4 _selector) external;
```

{% endcode %}

This method sets the verified function call for a \`\_target\`.

* Calldata cannot be used in conversion calls unless it’s added here.

#### **distributeStreamETH**

{% code overflow="wrap" %}

```javascript
function distributeStreamETH() external;
```

{% endcode %}

This method distributes an ETH revenue stream to the RevenueStreamETH contract.

## RevenueStreamETH

### Key Methods

#### **depositETH**

{% code overflow="wrap" %}

```javascript
function depositETH() payable external;
```

{% endcode %}

This method is used to deposit ETH into the contract to be claimed by shareholders.

#### **claimETH**

{% code overflow="wrap" %}

```javascript
function claimETH(address account) external returns (uint256 amount);
```

{% endcode %}

This method allows eligible VE shareholders to claim their ETH revenue rewards by account.

#### **claimable**

{% code overflow="wrap" %}

```javascript
function claimable(address account) external view returns (uint256 amount);
```

{% endcode %}

View method that returns an amount of ETH revenue that is claimable, given a specific \`account\`.

#### claimWithSignature

```javascript
function claimWithSignature(uint256 amount, uint256 currentIndex, uint256 indexes, uint256 deadline, bytes calldata signature) external;
```

This method allows a user to perform a claim with data that has been verified via a signature from the dedicated `signer` address.

**How is the `signature` generated?**\
The arguments given to the `claimWithSignature` function must be verified and signed by our designated signer wallet before that data can be passed into the method. When a claim is initiated by a user, the function params are first obtained via the `claimable` method and `lastClaimIndex`. This data is then signed by our node and passed back to the application so the user can complete the claim with the verified arguments.

## RWAVotingEscrow

### Key Methods

#### **mint**

{% code overflow="wrap" %}

```javascript
function mint(address _receiver, uint208 _lockedBalance, uint256 _duration) external returns (uint256 tokenId);
```

{% endcode %}

Mints a new VotingEscrow token representing a locked token position. The minting process locks a specified amount of tokens for a given vesting duration, assigning voting power accordingly.

#### **migrate**

{% code overflow="wrap" %}

```javascript
function migrate(address _receiver, uint256 _lockedBalance, uint256 _duration) external returns (uint256 tokenId);
```

{% endcode %}

This method is called by the RealReceiverNFT contract to fulfill the cross-chain migration from 3,3+ to veRWA.

#### **migrateBatch**

{% code overflow="wrap" %}

```javascript
function migrateBatch(address _receiver, uint256[] memory _lockedBalances, uint256[] memory _durations) external returns (uint256[] memory tokenIds);
```

{% endcode %}

This method is called by the RealReceiverNFT contract to fulfill the cross-chain migration of a batch of 3,3+ NFTs to veRWA NFTs.

#### **burn**

{% code overflow="wrap" %}

```javascript
function burn(address receiver, uint256 tokenId) external;
```

{% endcode %}

Burns a VotingEscrow token, releasing the locked tokens to the specified receiver. The burning process can only be done once the vesting duration has finished.

* If the lock duration remaining on lock is not 0, a penalty will be applied to the release of locked tokens.

#### **merge**

{% code overflow="wrap" %}

```javascript
function merge(uint256 tokenId, uint256 intoTokenId) external;
```

{% endcode %}

Merges two VotingEscrow tokens into one, combining their locked balances and vesting durations. The merge process adjusts the voting power based on the new combined balance and vesting duration.

#### **split**

{% code overflow="wrap" %}

```javascript
function split(uint256 tokenId, uint256[] calldata shares) external returns (uint256[] memory tokenIds);
```

{% endcode %}

Splits a VotingEscrow token into multiple tokens based on specified shares. The split process divides the locked balance and retains the original vesting duration for each new token.

#### **getPastTotalVotingPower**

{% code overflow="wrap" %}

```javascript
function getPastTotalVotingPower(uint256 timepoint) external view returns (uint256);
```

{% endcode %}

Returns the most recent checkpoint (given a timestamp) for total voting power.

#### **getPastVotingPower**

{% code overflow="wrap" %}

```javascript
function getPastVotingPower(uint256 tokenId, uint256 timepoint) external view returns (uint256);
```

{% endcode %}

Returns the most recent voting power checkpoint (given a timestamp) for a specific tokenId.

## VotingEscrowVesting

### Key Methods

#### **deposit**

{% code overflow="wrap" %}

```javascript
function deposit(uint256 tokenId) external nonReentrant;
```

{% endcode %}

Deposits a VotingEscrow token to start it's vesting schedule. The function records the vesting schedule, removes the token's voting power, and transfers the token to this contract for vesting.

#### **withdraw**

{% code overflow="wrap" %}

```javascript
function withdraw(address receiver, uint256 tokenId) external nonReentrant;
```

{% endcode %}

Withdraws a VotingEscrow token back to the depositor after the vesting period. The function restores the remaining vesting duration and transfers the token back to the depositor.

#### **claim**

{% code overflow="wrap" %}

```javascript
function claim(address receiver, uint256 tokenId) external nonReentrant;
```

{% endcode %}

Claims the underlying locked tokens of a vested VotingEscrow token, effectively burning the VotingEscrow token. The function can only be called once the vesting period has completed.

* If the remaining lock duration was not 0, will apply the early-burn penalty.

## DelegateFactory

### Key Methods

#### **deployDelegator**

{% code overflow="wrap" %}

```javascript
function deployDelegator(uint256 _tokenId, address _delegatee, uint256 _duration) external returns (address newDelegator);
```

{% endcode %}

This method allows a permissioned address to create a delegator contract.

#### **revokeExpiredDelegators**

{% code overflow="wrap" %}

```javascript
function revokeExpiredDelegators() external;
```

{% endcode %}

This method is used to fetch any expired Delegators, withdraw the delegated token from the Delegator, and delete its instance from the factory contract.

#### **expiredDelegatorExists**

{% code overflow="wrap" %}

```javascript
function expiredDelegatorExists() external view returns (bool exists);
```

{% endcode %}

This view method is used to fetch whether there exists any expired delegators.

## Delegator

### Key Methods

#### **depositDelegatorToken**

{% code overflow="wrap" %}

```javascript
function depositDelegatorToken(uint256 _tokenId) external;
```

{% endcode %}

This method is used to deposit a delegated veRWA NFT into this contract.

#### **withdrawDelegatedToken**

{% code overflow="wrap" %}

```javascript
function withdrawDelegatedToken() external;
```

{% endcode %}

This method is used to transfer the \`delegatedToken\` back to the \`creator\`.

<br>


# stRWA Technical

## Introduction

stRWA is a wrapped, rebasing version of veRWA. stRWA rebases to account for accrued reETH yield while burning a portion of RWA supply in the process.

stRWA is natively cross-chain, using LZ OFT technology.

Code: <https://github.com/re-al-Foundation/rwa-contracts/tree/dev/src/staking>

## Contracts

### stRWA.sol

This token is a cross-chain rebasing token. This token can only be minted in exchange for $RWA tokens. Once minted, the $RWA tokens will be locked into a veRWA position to begin accruing revenue. The revenue will be claimed and used to rebase; Distributing revenue amongst $stRWA holders.

### Notable Methods

#### **previewDeposit**

{% code overflow="wrap" %}

```javascript
function previewDeposit(uint256 assets) external pure returns (uint256)
```

{% endcode %}

Takes assets and returns an amount of shares that would be received if the amount assets was deposited.

#### **deposit**

{% code overflow="wrap" %}

```javascript
function deposit(uint256 assets, address receiver) external nonReentrant returns (uint256 shares)
```

{% endcode %}

Allows a user to deposit amount of RWA into this contract to receive shares amount of stRWA.

#### **previewRedeem**

{% code overflow="wrap" %}

```javascript
function previewRedeem(uint256 shares) external view returns (uint256)
```

{% endcode %}

Returns an amount of RWA tokens that would be redeemed if \`shares\` amount of stRWA tokens were used to redeem. Returns the amount of RWA in the form of a veRWA lock position. It takes the amount of RWA and splits it off from the master lock in the token silo. Takes into account the redemption fee.

#### **redeem**

{% code overflow="wrap" %}

```javascript
function redeem(uint256 shares, address receiver, address owner) external nonReentrant returns (uint256 tokenId, uint256 assets)
```

{% endcode %}

Allows a user to use a specified amount of stRWA to redeem a veRWA lock position of `assets` amount. Redeem X stRWA for Y RWA: X is provided. The Y RWA returned is in the form a single veRWA lock position.

#### **rebase**

{% code overflow="wrap" %}

```javascript
function rebase() external
```

{% endcode %}

This method will update the rebaseIndex based on the rewards collected in the TokenSilo. The rebase logic will calculate the % increase in the amount of RWA locked. Based on the % increase, we then increase the rebaseIndex by the same percentage.

## TokenSilo.sol

This is a periphery contract for stRWA and serves as the token silo for the veRWA token being used as collateral for stRWA holders. This contract contains mechanics for managing the masterTokenId, allowing stRWA holders to deposit more collateral or redeem from the master governance position. This contract also contains a rebaseHelper function to distribute rewards and return an amount used to rebase stRWA.

### Notable Methods

#### **depositAndLock**

{% code overflow="wrap" %}

```javascript
function depositAndLock(uint256 amount) external onlyStakedRWA
```

{% endcode %}

This method allows $RWA tokens to be added to the masterTokenId lock position. If there currently is not a token assigned to masterTokenId, a new token is minted with the $RWA tokens provided.

#### **redeemLock**

{% code overflow="wrap" %}

```javascript
function redeemLock(uint256 amount, address recipient) external onlyStakedRWA returns (uint256 tokenId, uint256 amountLocked));
```

{% endcode %}

This method allows a portion of the masterTokenId lock position to be split off and sent to a specified recipient.

#### **claim**

{% code overflow="wrap" %}

```javascript
function claim() external onlyFundsManager returns (uint256 claimed)
```

{% endcode %}

Allows the funds manager to claim any claimable rewards. The ETH rewards claimed will remain in this contract and are wrapped immediately.

#### convertRewardToken

{% code overflow="wrap" %}

```javascript
function convertRewardToken(address, uint256 amount, address target, bytes calldata data) external onlyFundsManager returns (uint256 amountOut)
```

{% endcode %}

Converts a specific amount of WETH to RWA. Contains a check to verify that the target address and selector are correct to avoid exploits. Follows the same interface as RevenueDistributor::convertRewardToken to allow for the w3f to be used without major revisions. This method will also trigger a rebase on the `stRWARebaseManager`.

#### **rebaseHelper**

{% code overflow="wrap" %}

```javascript
function rebaseHelper() external onlyStakedRWA returns (uint256)
```

{% endcode %}

This method is called by stRWA when a rebase occurs. This method will take all RWA in the contract and distribute it. Distribution will perform a burn of raw $RWA tokens and will lock the rest into the master position. The amount locked and designated for rebase will be returned and used to update the stRWA rebaseIndex.


# Start Building

## Quick Start

### Overview

re.al is a Layer-2 solution enhancing Ethereum, providing an EVM-compatible environment for seamless integration. It utilizes advanced cryptographic techniques for efficiency and inherits Ethereum's security.

### Connecting to re.al Testnet

{% hint style="warning" %}
**re.al Testnet and its related documentation are under active development.**

All feedback is welcome and highly appreciated. Please report errors or inconsistencies to a team member or as an issue on our [Issues Tracker](https://github.com/YourOrg/your-repo/issues), thank you.
{% endhint %}

To manually add the **re.al Testnet** network to your wallet, use the following details:

### Unreal Testnet Network Details

| Network Attribute |                   Value                   |
| ----------------- | :---------------------------------------: |
| chainID           |                   18232                   |
| Settlement Layer  |                  Holesky                  |
| Currency          |                   reETH                   |
| RPC Url           | <https://rpc.unreal-orbit.gelato.digital> |
| Explorer          |      <https://unreal.blockscout.com>      |

[The public summary of the testnet can be found here. ](https://raas.gelato.network/rollups/details/public/unreal)

To add the network to MetaMask, you can either enter the data above manually or use the link provided at the bottom of the re.al Testnet Block Explorer page.

### Bridging Assets to re.al Testnet

To start interacting with the re.al Testnet, you'll need to bridge your assets. Bridging assets involves transferring cryptocurrencies from one blockchain (Ethereum) to another (re.al Testnet). This process expands your asset's utility by enabling its use within the re.al ecosystem.

To bridge your assets to the re.al Testnet, follow this [link to the unreal network bridge.](https://bridge.gelato.network/bridge/unreal)

### Deploying Smart Contracts on re.al

The re.al provides a development environment that is designed to be familiar to those who have worked with Ethereum. It allows developers to deploy smart contracts using existing Ethereum tools and workflows, ensuring a smooth transition and a user experience characterized by higher throughput and reduced transaction costs.

To learn more about how to deploy your smart contracts to the re.al Testnet, refer to our comprehensive guide below.

[Deploy Smart Contracts on re.al Testnet ↗️](/build-on-re.al/smart-contracts)

### Support Channels

For support, developers can consult the community on platforms like StackExchange or join the official Discord server.


# Faucet

{% hint style="warning" %}
**re.al Testnet and its related documentation are under active development.**

All feedback is welcome and highly appreciated. Please report errors or inconsistencies to a team member or as an issue on our [Issues Tracker](https://github.com/YourOrg/your-repo/issues), thank you.
{% endhint %}

### Obtaining Testnet Tokens

To acquire testnet tokens for network transactions, utilize public faucets that distribute testnet ETH. After receiving testnet ETH, bridge them to the Layer-2 network using the provided bridge service.

### Connecting Wallet to Testnet

Configure your wallet to connect to the [Holesly testnet ](https://chainlist.org/chain/17000)where you can receive testnet ETH.

### Using Public Faucets

Access the following faucets to obtain testnet ETH:

[Holesky Faucet 1](https://holesky-faucet.pk910.de/)

Once you have the testnet ETH, proceed to [bridge them to the unreal network](https://bridge.gelato.network/bridge/unreal) for testing and development purposes.


# Smart Contracts

<table data-card-size="large" data-view="cards"><thead><tr><th></th><th></th></tr></thead><tbody><tr><td><a href="/pages/D7kH8XBS2LHyQoouuDlZ"><strong>Write a Contract</strong></a></td><td>This document explains how to automatically write any smart contract.</td></tr><tr><td><a href="/pages/iVuMzCCiGpeYxouewkqz"><strong>Deploy Using Hardhat</strong></a></td><td>In this tutorial, we will be using Hardhat to deploy a simple smart contract to the Custom Rollup Testnet.</td></tr><tr><td><a href="/pages/EtAQnNVI0rOBlGY9hKgc"><strong>Verify Contracts</strong></a></td><td>There are several ways to verify a contract, programmatically or manually on the UI.</td></tr></tbody></table>


# Write a Contract

This document explains how to automatically write any smart contract using the OpenZeppelin Wizard. The resulting smart contract code can either be integrated with Remix by Clicking the **Open in Remix** button, or copied to clipboard and pasted in the user's intended IDE.

## Getting Started

Navigate to the [OpenZeppelin Wizard](https://wizard.openzeppelin.com) in your browser. First thing to notice is the **Solidity Wizard** and **Cairo Wizard** buttons.

One can choose any of the following tabs to begin creating an out-of-box smart contract code in either Solidity (for EVM chains) or Cairolang (useful for Starknet). These are:

* ERC20: for writing an ERC-20 token smart contract
* ERC721: for writing an NFT token smart contract
* ERC1155: for writing an ERC-1155 token smart contract
* Governor: for creating a DAO
* Custom: for writing a customized smart contract

## Writing An NFT Contract

For illustration purpose, we will be creating a NFT smart contract. Suppose you wanted to create a `Mintable`, `Burnable` `ERC721` token and specify an appropriate license for it.

1. Select the **ERC721** tab.
2. Give your NFT a name and a symbol by filling the `Name` and `Symbol` fields.
3. Use the check-boxes on the left to select features of your token

* Put a tick on the `Mintable` check-box
* Put a tick on the `Auto Increment Ids` check-box, this ensures uniqueness of each minted NFT
* Put a tick on the `Burnable` check-box
* Either leave the **default MIT license** or type the license of your choice

Notice that new lines of code are automatically written each time a feature is selected.

## Voila! Contract Ready

With the resulting lines of code, you now have the NFT token contract written in Solidity. As mentioned above, this source code can now be ported to an IDE of your choice or opened directly in Remix.

The below figure depicts the auto-written NFT smart contract code.


# Deploy Using Hardhat

Hardhat is a popular smart contract development frameworks. In this tutorial, we will be using Hardhat to deploy a simple Counter smart contract to the Custom Rollup Testnet. We will explore the basics of creating a Hardhat project with a sample contract and a script to deploy it.

For the full instruction on how to use Hardhat, please refer to the [official Hardhat documentation](https://hardhat.org/getting-started/).

## Create New Project

Start with creating an npm project by going to an empty folder, running `npm init`, and following its instructions. You can use another package manager, like yarn, but Hardhat recommends you use npm 7 or later, as it makes installing Hardhat plugins simpler.

## Hardhat Smart Contract

To create the sample project, run `npx hardhat init` in your project folder:

* **Press** `<ENTER>` choose javascript, typescript or empty project
* **Press** `<ENTER>` to set the project root
* **Press** `<ENTER>` again to accept addition of `.gitignore`
* **Press** `<ENTER>` to install `hardhat @nomicfoundation/hardhat-toolbox`

## Create deployer account

* Create the `.env` file in your project root folder and add the following line:

```bash
ACCOUNT_PRIVATE_KEY='my private key'
```

* Populate the `.env` file with your private key. You can get your private key from Metamask. See the section below on how to get your private key from Metamask.

<details>

<summary>How to get your Private Key in Metamask</summary>

* Click the vertical 3 dots in the upper-right corner of Metamask window
* Select **Account details** and then click **Show private key**
* Enter your Metamask password to reveal the private key
* Copy the private key and paste it into the `.env` file.

</details>

{% hint style="danger" %}
**Do not commit your private key to a public repository!**

Verify that your .gitignore file contains `.env` to prevent your private key from being committed to a public repository.
{% endhint %}

## Configure Hardhat

* Open the `hardhat.config.js` file and paste the code below:

```js
require("dotenv").config();
require("@nomicfoundation/hardhat-toolbox");

module.exports = {
  solidity: "0.8.19",
  paths: {
    artifacts: "./src",
  },
  networks: {
    unreal: {
      url: `https://rpc.unreal.gelato.digital`,
      accounts: [process.env.ACCOUNT_PRIVATE_KEY],
    },
  },
};
```

```js
import { HardhatUserConfig } from "hardhat/config";
import "@nomicfoundation/hardhat-toolbox";
import * as dotenv from "dotenv";

dotenv.config({ path: __dirname + "/.env" });
const ACCOUNT_PRIVATE_KEY = process.env.ACCOUNT_PRIVATE_KEY || "";
console.log("PrivateKey set:", !!ACCOUNT_PRIVATE_KEY);

const config: HardhatUserConfig = {
  solidity: "0.8.19",
  paths: {
    artifacts: "./src",
  },
  networks: {
    unreal: {
      url: `https://rpc.unreal.gelato.digital`,
      accounts: [ACCOUNT_PRIVATE_KEY],
    },
  },
};

export default config;
```

## Write Smart Contract

{% hint style="info" %}
The existing smart contract code that comes with the sample project is a `Lock.sol` contract. Feel free to delete it or leave it.
{% endhint %}

* Create a new file, in the contracts folder, named `Counter.sol`:

```bash
touch contracts/Counter.sol
```

* Copy the below code and paste it in the `Counter.sol` contract code:

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

contract Counter {
uint256 currentCount = 0;

    function increment() public {
        currentCount = currentCount + 1;
    }

    function retrieve() public view returns (uint256){
        return currentCount;
    }
}
```

## Create Deploy Script

* Delete the content of the `scripts/deploy.js` file and add the code below:

```js
const hre = require("hardhat");

async function main() {
  const deployedContract = await hre.ethers.deployContract("Counter");
  await deployedContract.waitForDeployment();
  console.log(
    `Counter contract deployed to https://unreal.explorer.startale.com/address/${deployedContract.target}`
  );
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
```

## Compile Contract

* Install dotenv package: `npm install dotenv`
* Compile your contract code (i.e., go back to the project root in the CLI),

  ```bash
  npx hardhat compile
  ```

## Deploy Contract

* Run the deploy script:

  ```bash
  npx hardhat run scripts/deploy.js --network unreal
  ```

  ​Here's an output example:

  ```bash
  Counter contract deployed to https://unreal.explorer.startale.com/address/0x8731DC57f9C7e01f5Ba733E7a10692cA540862f8
  ```


# Verify Contracts

Once verified, a smart contract or token contract's source code becomes publicly available and verifiable, creating transparency and trust.

There are several ways to verify a contract, programmatically or manually on the UI.

## Verify on the UI

1. Go the the verify contract page (Other -> Verify Contract)
2. Enter in the contract address you received during deployment. The dropdown will show you several available verification options. Select the one you would like to use and continue.
   1. Solidity (Flattended source code)
   2. Solidity (Standard JSON Input)

### Solidity (Flattened Source Code)

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

1. Contract Address: The 0x address supplied on contract creation (added above)
2. Is Yul Contract: Select if the contract is coded in Yul for efficiency.
3. Include Nightly Builds: Select if you want to show nightly builds.
4. Compiler: derived from the first line in the contract pragma solidity X.X.X. Use the corresponding compiler version rather than the nightly build.
5. EVM Version: Select the correct EVM version if known, otherwise use default.
6. EVM Version: Select the correct EVM version if known, otherwise use default.
7. Enter the Solidity Contract Code: You may need to flatten your solidity code if it utilizes a library or inherits dependencies from another contract. We recommend hardhat or the POA solidity flattener. To flatten your contract using contract, run:

```bash
yarn hardhat flatten .\contracts\<your-contract>.sol > flattened.sol
```

8. Add Contract Libraries: Enter the name and 0x address for any required libraries called in the .sol file. You can add multiple contracts with the "+" button.
9. Click the Verify and Publish button.
10. If all goes well, you will see a checkmark next to Code in the code tab, and an additional tab called Read Contract. The contract name will now appear in BlockScout with any transactions related to your contract.

### Solidity (Standard JSON Input)

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

1. Include nightly builds. You can choose Yes or No depending on your compiler.
2. Compiler. Choose the compiler version used to compile your smart contract. If you selected yes for nightly builds, use the compiler version rather than the build.
3. Standard Input JSON. Upload your Standard Input JSON file. File should follows solidity format and all the sources must be in Literal Content format, not a URL.

Click the Verify & publish button and wait for the response.

## Verify Programmatically

You can use this repo to verify your contracts programmatically along with deploying them.

Repo Link: <https://github.com/gelatodigital/verify-simple-proxy>

In this repo, use the `deploy/` directory for deploying our contracts using the hardhat-deploy plugin. The deployment script deploys contracts in the `contracts/` directory.

Prior to deploying the contracts, make sure to add `customChain` to the hardhat.config.js file. This is necessary to verify the contracts on the custom chain.

```typescript
    customChains: [
      {
        network: "unreal",
        chainId: 18231,
        urls: {
          apiURL: "https://unreal.blockscout.com/api",
          browserURL: "https://unreal.blockscout.com",
        },
      },
    ],
  },
```

and add etherscan API key to the hardhat.config.js file.

```typescript
  etherscan: {
    apiKey: {
      unreal: "XXXX",
    },
  }

```

Here is how a sample deploy script looks like using hardhat-deploy:

```typescript
import { HardhatRuntimeEnvironment } from "hardhat/types";
import { DeployFunction } from "hardhat-deploy/types";
import { ethers, run } from "hardhat";
import {
  getImplementationAddress,
  getAdminAddress,
} from "@openzeppelin/upgrades-core";

const deployBeaconAndProxies: DeployFunction = async function (
  hre: HardhatRuntimeEnvironment
) {
  const { deployments, getNamedAccounts } = hre;
  const { deploy } = deployments;
  const { deployer } = await getNamedAccounts();

  // Deploy your contract with a Transparent Proxy
  const boxDeployment = await deploy("Box", {
    contract: "Box", // Replace with your actual contract name
    from: deployer,
    args: [], // Constructor arguments for your contract (if any)
    log: true,
    proxy: {
      owner: deployer,
      proxyContract: "OpenZeppelinTransparentProxy",
    },
  });

  console.log(boxDeployment.address, "Box (proxy) address");

  // Wait for 10 seconds to ensure Etherscan has indexed the contract
  await new Promise((resolve) => setTimeout(resolve, 10000));

  // Retrieve implementation and admin addresses
  const proxyAddress = boxDeployment.address;
  const implementationAddress = await getImplementationAddress(
    ethers.provider,
    proxyAddress
  );
  const adminAddress = await getAdminAddress(ethers.provider, proxyAddress);

  console.log(implementationAddress, "Box (implementation) address");
  console.log(adminAddress, "Box (admin) address");

  // Verify the implementation contract
  try {
    await run("verify:verify", {
      address: implementationAddress,
      constructorArguments: [], // Add constructor arguments of your implementation contract if any
    });
    console.log(`Verified implementation contract at ${implementationAddress}`);
  } catch (error) {
    console.error("Verification of implementation contract failed", error);
  }

  // Additional logic for verifying other contracts can be added here if needed
};

export default deployBeaconAndProxies;
deployBeaconAndProxies.tags = ["Box"];
```

To deploy the contracts, run:

```bash
npx hardhat deploy --network <network-name>
```

#### Output

```
PS C:\Users\aniru\OneDrive\Desktop\Gelato_internship\RaaS\verify-simple-proxy> npx hardhat deploy --network unreal
Nothing to compile
No need to generate any newer typings.
reusing "DefaultProxyAdmin" at 0xdDF2D006e3010e62c354508D42a2eA5910A88bD2
reusing "Box_Implementation" at 0x7b8d30c0F605fCa77F2ec04661C11c369f630753
0xe3689ABC2F6648BA8be68cE41620988C4e2708bd Box (proxy) address
0x7b8d30c0F605fCa77F2ec04661C11c369f630753 Box (implementation) address
0xdDF2D006e3010e62c354508D42a2eA5910A88bD2 Box (admin) address
The contract 0x7b8d30c0F605fCa77F2ec04661C11c369f630753 has already been verified on Etherscan.
https://unreal.blockscout.com/address/0x7b8d30c0F605fCa77F2ec04661C11c369f630753#code
Verified implementation contract at 0x7b8d30c0F605fCa77F2ec04661C11c369f630753
```


# Services

Here you will find common services and tools available to developers building dApps on the Custom Rollup, including sample configurations, and guides for many important elements of our infrastructure, including:

<table data-card-size="large" data-view="cards"><thead><tr><th></th><th data-hidden></th><th data-hidden></th></tr></thead><tbody><tr><td><a href="/pages/gRbOvubZz44BYtBtjYBJ"><strong>Account Abstraction</strong></a></td><td></td><td></td></tr><tr><td><a href="/pages/clqSP0ZEYbTdtyWaPLJV"><strong>Automation &#x26; Off-Chain Data</strong></a></td><td></td><td></td></tr><tr><td><a href="/pages/vd0tjrDTefQ35Q0BmqjX"><strong>Bridges</strong></a></td><td></td><td></td></tr><tr><td><a href="/pages/VPf5YN3g94zXFR8pWjza"><strong>Indexers</strong></a></td><td></td><td></td></tr><tr><td><a href="/pages/V2fum706VFn3PZAGUSQF"><strong>Oracles</strong></a></td><td></td><td></td></tr><tr><td><a href="/pages/EX6hh9bqQjPBmzpfInFb"><strong>Relay</strong></a></td><td></td><td></td></tr><tr><td><a href="/pages/vEwwVKl4QChzblRXDQnw"><strong>VRF</strong></a></td><td></td><td></td></tr><tr><td><a href="/pages/SxxEECF855IPMt0nYLBt"><strong>Wallet as a Service</strong></a></td><td></td><td></td></tr></tbody></table>


# Account Abstraction

{% hint style="warning" %}
Please note that this section is under active development.
{% endhint %}

## Overview

The Ethereum blockchain network has two central types of accounts: externally owned accounts (EOAs) and contract accounts. EOAs are controlled by users; meanwhile, contract accounts are managed by smart contract code. Both account types are essential for the Ethereum ecosystem. However, EOAs are required to interact with the network, as they are the only way for you to initiate transactions and execute smart contracts.

The problem with EOAs is their limitation to basic operations. And this restricts your options for interacting with the Ethereum blockchain. For example

* Poor Security: EOAs are secured by private keys, which are vulnerable to theft and loss.
* Lack of customization: We must initiate transactions from EOAs, which means that we can’t customize the transaction flow. For example, we can’t set up automatic payments or multi-factor authentication or define custom rules.
* Gas Payment: Account must hold ETH to pay for gas fees. This is a significant barrier to entry for new users.

## What are the benefits of Account Abstraction?

* Increased Security: We manage conventional Ethereum accounts using seed phrases and private keys. This can be problematic if a user loses their seed phrase or accidentally leaks their private key. With account abstraction you’re given more opportunities to implement additional options for both account recovery and authentication.
* Improved User Experience: With account abstraction, we can create smart contract wallets that can be used to implement a wide range of features. For example, we can create wallets that automatically pay for gas fees, wallets that require multi-factor authentication, and wallets that can be recovered using a social recovery mechanism.


# Safe Account Abstraction

The Safe{Core} Account Abstraction (AA) SDK aims to bring Account Abstraction to life by integrating Safe with Gelato Relay. This SDK helps developers to abstract the complexity of setting up a smart contract account.

**Account Abstraction Kit** The AA kit helps user ot create predeterministic smart contract wallets and execute gasless transactions with the Gelato Relay. The safe will only be deployed when the first transaction is sent.

**Protocol Kit** The Protocol Kit helps interact with the Safe contracts. It enables the creation of new Safe accounts, updating their configuration, and signing and executing transactions, among other features.

**Relay Kit** The Relay Kit relays Safe transactions, allowing you to get them sponsored by a third party or paid with any supported ERC-20 token.

## Safe AA SDKs

As part of the Gelato Raas AA offerings, we have deployed a custom safe-sdk creating following packages

| Package           | SDK                                 |
| ----------------- | ----------------------------------- |
| Safe Protocol Kit | gelato-raas-protocol-kit            |
| Safe AA Kit       | gelato-raas-account-abstraction-kit |
| Safe Relay Kit    | gelato-raas-relay-kit               |

This project showcase how to send Gasless Transactions through a Safe sponsoring the gas with [1Balance](https://docs.gelato.network/developer-services/1balance)

In following examples examples, it will be called the `increment()` method on this simple counter contract deployed on unreal <https://unreal.blockscout.com/address/0xEEeBe2F778AA186e88dCf2FEb8f8231565769C27>

## Quick Start

1. Clone the [safe](https://github.com/gelatodigital/gelato-raas-aa) repo
2. Install project dependencies:

```
yarn install
```

in the package.json we have already included gelato-raas-protocol-kit, gelato-raas-account-abstraction-kit and gelato-raas-relay-kit

```shell
  "gelato-raas-account-abstraction-kit": "^1.3.7",
  "gelato-raas-protocol-kit": "^1.3.6",
  "gelato-raas-relay-kit": "^1.3.7"
```

3. Create a .env file with your private config:

```shell
cp .env.example .env
```

You will need to input your Private Key **PK** and **GELATO\_RELAY\_API\_KEY** for sponsored transactions, you can get it at <https://app.gelato.network>

4. Call the method:

* Using 1Balance

  ```tyescript
   yarn aa1Balance
  ```

### Using 1Balance

```typescript
const safeTransactionData: MetaTransactionData = {
  to: targetAddress,
  data: nftContract.interface.encodeFunctionData("increment", []),
  value: "0",
  operation: OperationType.Call,
};

const safeAccountAbstraction = new AccountAbstraction(signer);
const sdkConfig: AccountAbstractionConfig = {
  relayPack,
};
await safeAccountAbstraction.init(sdkConfig);

const txConfig = {
  TO: targetAddress,
  DATA: safeTransactionData.data,
  VALUE: "0",
  // Options:
  GAS_LIMIT: gasLimit,
};

const predictedSafeAddress = await safeAccountAbstraction.getSafeAddress();
console.log({ predictedSafeAddress });

const isSafeDeployed = await safeAccountAbstraction.isSafeDeployed();
console.log({ isSafeDeployed });

const safeTransactions: MetaTransactionData[] = [
  {
    to: txConfig.TO,
    data: txConfig.DATA,
    value: txConfig.VALUE,
    operation: OperationType.Call,
  },
];
const options: MetaTransactionOptions = {
  gasLimit: txConfig.GAS_LIMIT,
  isSponsored: true,
};

const response = await safeAccountAbstraction.relayTransaction(
  safeTransactions,
  options
);
console.log(`https://relay.gelato.digital/tasks/status/${response} `);
```

### **Output**

```shell
$ ts-node src/aa-safe-gasless/aa1Balance.ts
{ predictedSafeAddress: '0x68D60c586763879c6614e2eFA709cCae708203c4' }
{ isSafeDeployed: true }
https://relay.gelato.digital/tasks/status/0xc34f62e1b057b298c144c79b3cc16e4e24bc2b1e91ce5cd7660f9b8c1791be91
```

## UI integration together with Web3Auth

Please visit the deployed react mini site on <https://gelato-raas-aa.web.app/?network=unreal> with a live implementation of web3Auth and safe on unreal

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

The code can be found at <https://github.com/gelatodigital/gelato-raas-aa-ui>


# Automation & Off-chain Data

## The Problem

In the realm of blockchain development, especially with decentralized applications (dApps), a significant challenge emerges in the form of limited auto-execution capabilities. Traditionally, smart contracts, despite their advanced functionalities, lack the inherent ability to initiate or call methods automatically. This limitation poses a hurdle in the seamless operation and scalability of blockchain applications.

## The Solution

To address this gap, automation solutions have been developed. These systems are designed to monitor both on-chain and off-chain data sources continuously. They are programmed to recognize specific predefined conditions. Once these conditions are met, the automation system springs into action, executing the necessary transactions without human intervention.

## Use cases

1. Auto Harvesting in DeFi: In decentralized finance applications, automation can manage yield farming strategies, harvesting rewards automatically when they reach a certain threshold, thereby optimizing the return on investment for users.
2. Limit Orders in Trading: Automated systems can execute trades when certain price points are hit, mirroring the functionality of limit orders in traditional trading but within a decentralized environment.

Read more about Gelato Web3 functions below!


# Gelato Web3 Functions

## Overview

Gelato's Web3 Functions is a powerful automation system designed to streamline and enhance Web3 operations. Web3 Functions serve as a comprehensive tool, enabling developers to effortlessly set up, manage, and automate their smart contract tasks. Determining your Needs

**Off-chain Data or Computation?** Sometimes, automation tasks require data that isn't readily available on the blockchain, or they might need computations that are better performed off-chain. In such cases, Typescript Functions should be the choice.

**All Checks On-chain?** If all the conditions necessary for your automation task can be directly verified on the blockchain, you have the option to select between Typescript Functions, Solidity Functions & Automated Transactions

## Triggers

1. Time Interval Description: Use this trigger to execute tasks at regular intervals, e.g., every 10 minutes or once every 24 hours. It's like setting a straightforward, recurring alarm.
2. Cron Expressions Description: This offers a more refined control compared to the Time Interval. With cron expressions, you can set tasks to run at specific moments, such as "every Tuesday at 3 PM" or "on the 1st of every month". It gives you precision in task scheduling.
3. On-Chain Event Description: Ideal for those wanting their tasks to respond dynamically to blockchain activities. Whenever a specified event occurs on the blockchain, this trigger springs your task into action. It's like a vigilant watcher, always ready to act.
4. Every Block Description: This function operates with the rhythm of the blockchain itself, executing your chosen function each time a new block is created.

## What to Execute?

### Typescript Functions

Typescript Functions are decentralized cloud functions that work similarly to AWS Lambda or Google Cloud, just for web3. They enable developers to execute on-chain transactions based on arbitrary off-chain data (APIs / subgraphs, etc) & computation. These functions are written in Typescript, stored on IPFS and run by Gelato.

### Solidity Functions

Solidity Functions are crucial for making on-chain tasks automatic and more efficient. They connect set conditions with specific actions in a smart contract, providing a straightforward method to turn user needs into automated processes. Consider them as a set of "if-then" rules: If certain conditions are met on the blockchain, then a specific function gets executed. This level of automation ensures that the decentralized application can operate with minimal manual intervention, providing a seamless user experience.

### Automated Transaction

Automated Transaction ensures that a specific function on the target smart contract gets reliably triggered. When you pre-define the inputs, it means that every time Gelato initiates the function call, it uses consistent, predetermined arguments.

## Quick Start

### Writing & Deploying Typescript Functions

1. Clone the hardhat-template repo

```shell
git clone web3-functions-hardhat-template
```

2. CD into the folder and install

```shell
cd web3-functions-hardhat-template && yarn install
```

3. Update the `index.ts` in one of the examples

```typescript
Web3Function.onRun(async (context: Web3FunctionContext) => {
  const { userArgs, multiChainProvider } = context;

  const provider = multiChainProvider.default();
  // Retrieve Last oracle update time
  const oracleAddress =
    (userArgs.oracle as string) ?? "0x71B9B0F6C999CBbB0FeF9c92B80D54e4973214da";

  // YOUR CUSTOM LOGIC
  .....

  // Return if nothing has to be pushed on-chain
    return { canExec: false, message: `Coingecko call failed` };

  // Return if tx has to be pushed on-chain
  return {
    canExec: true,
    callData: [
      {
        to: oracleAddress,
        data: oracle.interface.encodeFunctionData("updatePrice", [price]),
      },
    ],
  };
});
```

4. Deploy the Web3 Function to IPFS and create the Task

```shell
npx w3f deploy web3-functions/YOUR-FUNCTION/index.ts
```

Result:

```shell
$ npx w3f deploy web3-functions/YOUR-FUNCTION/index.ts
 ✓ Web3Function deployed to ipfs.
 ✓ CID: QmYMysfAhYYYrdhVytSTiE9phuoT49kMByktXSbVp1aRPx

To create a task that runs your Web3 Function every minute, visit:
> https://beta.app.gelato.network/new-task?cid=QmYMysfAhYYYrdhVytSTiE9phuoT49kMByktXSbVp1aRPx
✨  Done in 3.56s.
```

Finally, go to the [Gelato App](https://beta.app.gelato.app), create a new task, decide on the trigger, and input the CID.

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

### Writing & Deploying Solidity Functions

The central part of a solidity function is the **Checker**. A Checker acts as a bridge between conditions and smart contract executions. Its purpose? To check conditions and determine whether a task should be executed by Gelato. Every checker returns two main things:

* canExec (Boolean): Indicates if Gelato should execute the task.
* execData (Bytes): Contains the data that executors will use during execution.

Once you have deployed your checker, go to the [Gelato App](https://beta.app.gelato.app), create a new task, decide the trigger, and input the address of the checker contract and the method that does the check.


# Bridges

{% hint style="warning" %}
Please note that this section is under active development.
{% endhint %}

### What is a Bridge?

Bridges are a way to connect two different blockchains. They are a special type of smart contract that allows you to lock up tokens on one blockchain and mint the same amount of tokens on another blockchain. This is a very useful feature, as it allows you to transfer tokens between different blockchains. For example, you can transfer tokens from the Ethereum blockchain to the Arbitrum blockchain.


# Layer Zero

LayerZero is a messaging protocol, not a blockchain. Using smart contracts deployed on each chain, in combination with Decentralized Verifier Networks (DVNs) and Executors, LayerZero enables different blockchains to seamlessly interact with one another.

## Getting Started

To start sending omnichain messages with LayerZero, you only need to implement two functions:

* `_lzSend`: This function is used to send a message to a different chain.

```solidity
_lzSend(
  _dstEid, // the destination endpoint id
  _payload, // encoded message payload being sent
  _options, // message execution options
  MessagingFee(msg.value, 0), // the fee in native gas and ZRO token
  payable(msg.sender) // refund address in case of failed source message
);
```

* `_lzReceive`: This function is used to receive a message from a different chain.

```solidity
function _lzReceive(
  Origin calldata _origin, // struct containing srcEid, sender address, and the message nonce
  bytes32 _guid, // global message packet identifier
  bytes calldata payload, // encoded message being received
  address _executor, // the address of who executed the message
  bytes calldata _extraData // appended executor data for the call
) internal override {
  data = abi.decode(payload, (string)); // your receive logic here
}

```

LayerZero offers Contract Standards that simplify this implementation by providing out of the box message handling, interfaces for custom protocol configurations, and other quality of life improvements:

* [`OApp`](https://docs.layerzero.network/contracts/oapp): the base contract standard for omnichain messaging and configuration.
* [`OFT`](https://docs.layerzero.network/contracts/oft): the base contract standard for omnichain messaging and configuration.

### Prerequisites

1. You should first be familiar with writing and deploying contracts to your desired blockchains. This involves understanding the specific smart contract language and the deployment process for those chains.
2. A wallet set up and funded for the chains you'll be working with.

### Deploying your Contracts

To learn how to deploy your contracts, please refer to the [Deploying Contracts](/build-on-re.al/smart-contracts/deploy-using-hardhat) section.

To checkout endpoint addresses please refer to the [Endpoints](https://docs.layerzero.network/v1/developers/technical-reference/mainnet/mainnet-addresses#real) section in the LayerZero docs.

### Connecting your Contracts

To connect your contracts, call setPeer and pass the address of your destination contract as a bytes32 value, as well as the destination endpoint ID. If successful, you now should be setup to start sending cross-chain messages!

To go more in depth, please refer to the [Getting Started](https://docs.layerzero.network/contracts/getting-started) section in the layerzero docs.


# Indexers

## Understanding Blockchain Indexing

Blockchain technology, often likened to a digital ledger, securely records data in encrypted blocks distributed across a decentralized network. Each block in the chain not only contains a record of new transactions but also carries information from the preceding block. However, due to blockchain's sequential structure, the associated data is dispersed across numerous blocks without an inherent system for identifying or extracting specific, higher-level data.

Blockchain indexing steps in to address this. It allows users to efficiently search and filter through blockchain data, akin to how one might use Google, Bing, or other search engines to find information on the internet.

## Challenges in Indexing Blockchain Data

Indexing data within a decentralized infrastructure like blockchain presents several obstacles:

1. Absence of a Standard Query Language: Blockchain's immutable nature complicates direct data reading, as it lacks a built-in query language similar to SQL in traditional databases. To access even basic information such as a user's transaction history, one would have to examine each block individually.
2. Complexities in Data Retrieval: The node structure of blockchains, particularly those akin to Ethereum, complicates data retrieval. Historical records are typically spread across various events and stored in separate sections of a node. Limited access to these events in some public nodes can significantly slow down the query process.
3. Limitations of Existing APIs: The APIs currently available are often restricted to basic queries. These include range queries (such as records from a specific timeframe or a certain number of transactions) and top-k queries (which rank different data points relatively). This limitation hinders the ability to conduct more complex data analyses or searches.

## Subgraphs: A Key Solution

One of the most promising solutions to the challenges of indexing blockchain data is the use of subgraphs. Subgraphs are essentially predefined data structures that are designed to efficiently index and query data from a blockchain.

### What are Subgraphs?

Subgraphs are open-source APIs that allow developers to extract data from a blockchain and store it in a structured format. They are designed to be flexible, allowing developers to define the data they want to extract and how they want to store it. This flexibility enables subgraphs to be used for a wide range of applications, from simple data retrieval to more complex data analysis.

### Advantages of Subgraphs

1. Customized Data Views: Developers can create subgraphs tailored to their specific needs, focusing on the particular data they're interested in.
2. Real-time Data Updates: Subgraphs can update their indexed data in real-time with each new block on the blockchain, ensuring up-to-date information.
3. Decentralized and Open: Like blockchains, subgraphs can be hosted in a decentralized manner, promoting transparency and accessibility.

Read more about Goldsky Indexers below!


# Goldsky

## Install + log in

1. Create an account at [app.goldsky.com](https://app.goldsky.com).
2. Create an API key on the Settings page.
3. Install the Goldsky CLI:

   ```sh
   curl https://goldsky.com | sh
   ```
4. Log in with the API key created earlier:

   ```sh
   goldsky login
   ```

## Build and deploy

Deploy your subgraph in one of four ways:

### Build and deploy from source

```sh
cd <your-subgraph-directory>
graph build # Build your subgraph as normal.
goldsky subgraph deploy my-subgraph/1.0.0
```

## Build & Deploy from ABI and address

```sh
goldsky subgraph deploy your-subgraph-name/your-version --from-abi <path-to-config-file>
```

## Query Endpoint

Access data by querying the endpoints. Use the following command to list all your subgraphs, and open the “GraphQL API” links that get printed in your browser to query your data in the GraphQL playground.

```sh
goldsky subgraph list
```


# Oracles

## Overview

Blockchain oracles are third-party services or agents that provide smart contracts with external information and serve as bridges between blockchains and the external world. Because blockchains cannot access external data (outside of their network) due to their secure and deterministic nature, oracles are used to fetch, verify, and relay real-world data to smart contracts in a way that's trustworthy.

## Use Cases

### Decentralized Finance (DeFi)

Oracles provide price feeds, enabling DeFi platforms to calculate token values, manage collateral, and execute liquidations. By sourcing data from various exchanges and financial platforms, oracles contribute to the robustness of DeFi applications.

### Gaming

Blockchain-based gaming and betting platforms use oracles to determine the outcomes of events, such as sports matches or random number generation. By connecting to various data sources and verifying results, oracles ensure fair and transparent gaming experiences.

### Insurance

Oracles can be employed in the insurance industry to automate claims processing and underwriting. They can fetch data related to weather conditions, flight delays, or health records, enabling insurers to create parametric insurance products. This reduces fraud and ensures quicker payouts based on predefined triggers.

and much more...


# Redstone on re.al

## Current Price Feeds

So far we have deployed the GOLD (XAU) and GBP price feeds on Unreal with Chainlink interface adapter.

{% tabs %}
{% tab title="re.al" %}

| Price Feed | Contract address                                                                                                                     |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `GOLD`     | `coming soon...`                                                                                                                     |
| `GBP`      | [0x100c8e61aB3BeA812A42976199Fc3daFbcDD7272](https://explorer.re.al/address/0x100c8e61aB3BeA812A42976199Fc3daFbcDD7272?tab=contract) |

{% endtab %}

{% tab title="Unreal" %}

| Price Feed    | Contract address                                                                                                                 |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `GOLD`        | [`0x1e527C813E4FB23e5708044AE11Bf05B6873c7ba`](https://unreal.blockscout.com/address/0x1e527C813E4FB23e5708044AE11Bf05B6873c7ba) |
| `GBP`         | [`0xAb0290C2a2be0D2e8b77e8A7A97a0808D31e650D`](https://unreal.blockscout.com/address/0xAb0290C2a2be0D2e8b77e8A7A97a0808D31e650D) |
| {% endtab %}  |                                                                                                                                  |
| {% endtabs %} |                                                                                                                                  |

## Code Snippets

### Querying Prices

```typescript
const getLatestSignedPrice = async () => {
  return await sdk.requestDataPackages({
    dataServiceId: "redstone-primary-prod",
    uniqueSignersCount: 3,
    dataFeeds: ["XAU"],
    urls: ["https://oracle-gateway-1.a.redstone.finance"],
  });
};

const dataPackagesResponse = await getLatestSignedPrice();

const { dataPackage } = dataPackagesResponse["XAU"]![0];

const parsedPrice = parsePrice(dataPackage.dataPoints[0].value);
```

### Updating Price

```typescript
const wrappedAdapter =
  WrapperBuilder.wrap(priceFeedAdapter).usingDataPackages(dataPackagesResponse);
const { dataPackage } = dataPackagesResponse["ETH"]![0];
await wrappedAdapter.updateDataFeedsValues(dataPackage.timestampMilliseconds);
```


# Relay

## What is Relaying?

Relaying is a process that enhances user experience, particularly for new users, by removing some of the initial barriers to entry. It essentially involves a third party, known as a relayer, facilitating transactions for users. This service allows users to interact with on-chain applications such as DeFi platforms, NFT marketplaces, and blockchain-based games and much more without needing to possess the native cryptocurrency of the network for gas fees initially.

## Standard Transactions

In a standard Ethereum transaction, an ethereum user signs and sends the transaction themselves. This user controls the private key to an externally owned account (EOA) which they can use to sign a transaction and prove they have the right to spend the balance associated with that account address. For each transaction a user sends, there is an associated transaction fee, known as gas. Since Ethereum executes computation, each unit of computation has an associated gas cost, which deters malicious actors from overloading the network by requiring them to pay heavily for a potential attack. This is excellent news for Ethereum's security and helps keep the network consistent under load, but it comes at a hidden cost for onboarding new users.

## Onboarding Issues

How does a new user start interacting with exciting on-chain applications like DeFi, NFTs, or gaming? They will always need the native token to pay for gas on every network, even if the network has very cheap gas fees like Polygon. This requires the user to open an account at a centralised exchange, go through KYC, and buy crypto using fiat. This can be quite a process, even for the most skilled of degens out there, and it can deter new users from being onboarded to a dApp by increasing the latency between their initial excitement and the time it takes to actually get started. This is where relaying comes in! A relayer can help solve these issues by sending a transaction on behalf of the user.

## What is a Relayer?

We allow the user to send a transaction without a native token balance (it turns out relayers can be super nifty in loads of ways, for example, allowing a user who wants to swap a token to pay for the gas using the token being swapped!). Ideally, we would also like to still utilise the excellent security of a user signature, but for the transaction to be sent by a different EOA, one controlled by a relayer, who abstracts gas payment away from the user. This is a very import context shift to understand. We have shifted from a user signing and sending a transaction themselves, to a user signing a standardised message and passing that on to a relayer. This relayer will, first, verify the user's signature for security, and then pass their message along on-chain. Gelato Relay does exactly this by taking a user's message off-chain and subsequently building a meta-transaction which is executed on chain.

## Meta Transactions and EIP-712

A meta transaction is a regular ethereum transaction which contains the actual message to be delivered on-chain to a target contract within itself, hence the term meta. The outer transaction helps facilitate the first on-chain call which is sent by a relayer. The call is forwarded to the target contract using an intermediate smart contract (Gelato Relay), which in turn forwards the call using the inner transaction to deliver the relayed message.

To achieve gasless transactions securely, Gelato Relay makes use of the EIP-712 standard. EIP-712 allows for a standardised way to sign and hash typed structured data. This means the user can sign a message using their wallet without incurring a gas cost or interacting with the chain at all, and this signature can be verified on-chain, by the relayer, facilitating a gasless transaction with security built in. This message will include important information such as the transaction signer address, the target contract address, and the calldata payload used to target a specific function.


# Gelato Relay

## Introduction

Using Gelato Relay, we relay your user's transactions on-chain, enabling secure gasless transactions for an ultra-smooth UX for your app. This allows for a variety of new web3 experiences, as the user can now pay by only signing a message, or their transaction costs can be sponsored by the developer. As long as the gas costs are covered in one of the multiple payment methods that Gelato supports, we handle the rest reliably, quickly and securely.

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

## Prerequisites

* "node": ">=14.0.0"
* Basic JavaScript knowledge.
* ethers knowledge

## Getting started

### 1: Installation

Install the Gelato Relay SDK

```
yarn add @gelatonetwork/relay-sdk
```

### 2: Choose the Method

At this point, you will need to answer the following questions, which will determine the method to use when calling the Gelato Relay.

* Do you require user authentication? When the use-case requires to authenticate the original user, you will need to implement the ERC2771 method where the user will sign the payload, and the original user will be decoded on-chain from the callData replacing `msg.sender` through `_msgSender()`, please see additional info here.
* What is the funding strategy? When relaying a transaction, the Gelato Nodes are paying the gas fees. There are two different ways of paying the fees back to Gelato. Either creating a 1Balance account and deposit USDC on polygon that will pay for all of the transactions on all EVM chains Gelato is deployed; or transferring back to gelato the fees while the transaction is executing, we call these methods syncFee, more info can be found here, in this latter case, the target contract would need to inherit the "Gelato Relay Context" contracts, so the methods to query and transfer the fee to Gelato are available.

If you require user authentication and you want to pay the transactions with a 1Balance account, the method to use is the `sponsoredCallERC2771`.

If you require user authentication and you want every transaction to pay for itself, transferring by execution the fees to Gelato, the method to use is the `callWithSyncFeeERC2771`.

If you don't require user authentication and you want to pay the transactions with a 1Balance account, the method to use is the `sponsoredCall`.

If you don't require user authentication and you want every transaction to pay for itself, transferring the fees by execution to Gelato, the method to use is the `callWithSyncFee`.

### 3: Implementation

We will require three simple steps to implement Gelato Relay. Here, we are going to showcase the three steps required to implement the method `sponsoredCallERC2771`, which is the most used one.

#### **Step 1: Inherit Context Contract**

Depending on the method, you must inherit different contracts as they will provide other methods. In this case, we will have to inherit the `ERC2771Context`. The `ERC2771Context` provide us with the methods `_msgSender()` and `_msgData()` that will allow us to recover the original user sending the transaction.

```solidity
import {
    ERC2771Context
} from "@gelatonetwork/relay-context/contracts/vendor/ERC2771Context.sol";

contract CounterERC2771 is ERC2771Context {

    // ERC2771Context: setting the immutable trustedForwarder variable
    constructor(address trustedForwarder) ERC2771Context(trustedForwarder) {}

    function incrementContext() external {

        // Incrementing the counter mapped to the _msgSender!
        contextCounter[_msgSender()]++;

        // Emitting an event for testing purposes
        emit IncrementContextCounter(_msgSender());
    }
}
```

#### **Step 2: Import the relay SDK**

In your frontend/backend, you would need to import and instantiate the relay class.

```
import { GelatoRelay, SponsoredCallERC2771Request } from "@gelatonetwork/relay-sdk";
const relay = new GelatoRelay(API_KEY);
```

#### **Step 3: Send the payload to Gelato**

This is an example using Gelato's CounterERC2771.sol, which is deployed on these networks.

```
// Set up on-chain variables, such as target address
const counter = "0x00172f67db60E5fA346e599cdE675f0ca213b47b";
const abi = ["function incrementContext()"];
const provider = new ethers.BrowserProvider(window.ethereum);
const signer = provider.getSigner();
const user = signer.getAddress();

// Generate the target payload
const contract = new ethers.Contract(counter, abi, signer);
const { data } = await contract.incrementContext.populateTransaction();

// Populate a relay request
const request: CallWithERC2771Request = {
  chainId: (await provider.getNetwork()).chainId,
  target: counter;
  data: data;
  user: user;
};

// Without a specific API key, the relay request will fail!
// Go to https://relay.gelato.network to get a testnet API key with 1Balance.
// Send a relay request using Gelato Relay!
const relayResponse = await relay.sponsoredCallERC2771(request, provider, apiKey);
```

### Tracking your Request

When submitting your Gelato Relay requests, you'll receive a taskId in response. This taskId allows you to track the status of your request in two primary ways:

1. WebSocket Subscriptions: This is the recommended and most efficient method. By subscribing via WebSocket, the Gelato backend will automatically push updates for all your tasks to your Relay SDK client. To start receiving these updates, you must register a callback function, which will be triggered every time one of your tasks gets updated. Detailed implementation can be found here.
2. Polling for Updates: Alternatively, you can periodically query the Gelato task status API for updates. If you're using the Gelato Relay SDK, the getTaskStatus method makes this easy. Detailed implementation can be found here.


# VRF

## Introduction

Randomness is a crucial element in many online multiplayer games, especially when it comes to things like loot drops, matchmaking, and other important gameplay mechanics in blockchain games.

To achieve this randomness, many games rely on a cryptographic function called a Verifiable Random Function (VRF).

## What is Verifiable Random Function (VRF)

A Verifiable Random Function (VRF) is a cryptographic function that takes a secret key and an input string as input and returns a random output string. The key property of a VRF is that the output is verifiable, meaning that anyone can verify that the output was indeed generated from the input and the secret key, without needing to know the secret key themselves.

This is useful in applications that require random inputs, such as games and other cryptographic protocols, where it is important that the randomness is fair and cannot be manipulated by any party.

Many top NFT teams have for example, used a VRF to ensure minted tokens are randomly assigned jpegs and that rares are verifiably assigned to random token #’s.


# Gelato VRF

## Gelato VRF and Trustworthy Randomness

* **Mechanism**: Uses Drand, a decentralized source for random numbers.
* **Benefits**: Provides genuine, verifiable random values for blockchain applications.

## Applications of Gelato VRF

* **Gaming and Gambling**: For fair outcomes in online games and decentralized gambling.
* **Decentralized Finance (DeFi)**: Random selections for lotteries in DeFi protocols.
* **NFT Generation**: Random trait generation for unique digital assets.
* **Protocol Decision Making**: Randomized selections for validators or jurors.

<figure><img src="/files/3WwbyfwgHBQg2h39Pmmx" alt=""><figcaption></figcaption></figure>

### Steps to Set Up Gelato VRF

1. **Set Up Development Environment**: Install either Foundry or Hardhat.
2. **Install Gelato VRF Contracts**: Use specific commands for Hardhat or Foundry.
3. **Inherit `GelatoVRFConsumerBase` Contract**: Incorporate it into your contract.
4. **Request Randomness**: Call `_requestRandomness()` function.
5. **Implement Callback Function**: Define how your contract handles the randomness response.
6. **Include `dedicated msg.sender`**: Essential for contract security and function.

## Quick Start

### Step 1: Set Up Your Development Environment

Make sure you have Hardhat or Foundry ready for use.

### Step 2: Install Gelato VRF Contracts

For Hardhat, clone the repository and set up the environment. For Foundry, use the `forge install` command.

### Step 3: Inherit GelatoVRFConsumerBase Contract

Create a contract that inherits from GelatoVRFConsumerBase.

```solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

import {GelatoVRFConsumerBase} from "./GelatoVRFConsumerBase.sol";

contract YourContract is GelatoVRFConsumerBase {
    // Your contract's code
}
```

### Step 4: Request Randomness

To request randomness, call the \_requestRandomness() function. You should protect the call since it will take from your 1Balance. The data argument will be passed back to you by the W3F.

```typescript
    function requestRandomness(bytes memory data) external {
        require(msg.sender == ...);
        uint64 requestId = _requestRandomness(data);
    }
```

### Step 5: Implement Callback Function

```typescript
    function _fulfillRandomness(
        bytes32 randomness,
        uint64 requestId,
        bytes memory data,
    ) internal override {
    }
}
```

### Step 6: Include Dedicated msg.sender

When you're ready to deploy your Gelato VRF-compatible contract, an important step is to include the dedicated msg.sender as a constructor parameter. This ensures that your contract is set up to work with the correct operator for fulfilling the randomness requests.. It's crucial for ensuring that only authorized requests are processed.

```solidity
// SPDX-License-Identifier: MIT
pragma solidity 0.8.18;

import {GelatoVRFConsumerBase} from "./GelatoVRFConsumerBase.sol";

contract YourContract is GelatoVRFConsumerBase {
    constructor(address operator)
        GelatoVRFConsumerBase(operator) {
        // Additional initializations
    }

    // The rest of your contract code
}
```


# Wallet as a Service

## Overview

Wallet as a Service (WaaS) is essentially a modern solution for managing digital assets, tailored for businesses and institutions. It's like having a digital wallet, but with advanced features and security designed for professional use.

At its core, WaaS provides a secure and scalable way to handle cryptocurrencies and other digital assets. It's designed to be flexible, catering to the needs of various businesses, regardless of their size.

## Key Features

1. Ease of Use and Security: It strikes a balance between being user-friendly and maintaining high security, ensuring that managing digital assets is straightforward without compromising safety.
2. Integration with Multiple Blockchains: WaaS allows for seamless connection with various blockchain networks. This means businesses can manage different types of digital assets across different blockchains all in one place.
3. Key Recovery System: One of the challenges with digital wallets is the risk of losing access keys. WaaS typically includes a system for recovering these keys, adding an extra layer of safety and peace of mind.
4. Low-Cost Fees: It's designed to be cost-effective, minimizing the expenses associated with digital asset management.

WaaS offers a comprehensive digital wallet solution that addresses the main challenges of modern digital asset management, combining ease of use, security, efficient blockchain integration, a reliable key recovery system, and affordability.


# Privy

## Quickstart

The Privy React Auth SDK simplifies user authentication in React apps, providing tools for various login methods and user management.

### 1. Installation

Install the SDK using npm:

```bash
npm install @privy-io/react-auth
```

### 2. Get API Keys

Retrieve your Privy app ID from the developer console.

### 3. Setting up your App

You have to define a custom chain configuration in so it can be used with PrivyProvider

```typescript
import { defineChain } from "viem-15";
export const config = {
  unreal: {
    privyConfig: defineChain({
      id: 18231,
      network: "unreal",
      name: "Unreal",
      nativeCurrency: {
        name: "unreal Ether",
        symbol: "ETH",
        decimals: 18,
      },
      rpcUrls: {
        public: {
          http: ["https://rpc.unreal.gelato.digital"],
        },
        default: {
          http: ["https://rpc.unreal.gelato.digital"],
        },
      },
      blockExplorers: {
        default: {
          name: "Block Scout",
          url: "https://unreal.blockscout.com/",
        },
      },
      contracts: {
        multicall3: {
          address: "0xca11bde05977b3631167028862be2a173976ca11",
          blockCreated: 31317,
        },
      },
      testnet: true,
    }),
    privyId: "YOUR_PRIVY_ID",
    zeroDevId: "ZERODEV_ID",
    simpleCounter: "0x47A9064a8D242860ABb43FC8340B3680487CC088",
  },
};
```

```javascript
// Example for NextJS
import { PrivyProvider } from "@privy-io/react-auth";
// ... other imports

function MyApp({ Component, pageProps }) {
  // ... setup
  return (
    <PrivyProvider appId="your-app-id" /* ...other config */>
      {/* ... rest of your app */}
    </PrivyProvider>
  );
}

// Example for Create React App
import { PrivyProvider } from "@privy-io/react-auth";
// ... other imports

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <PrivyProvider appId="your-app-id" defaultChain: config[raasNetwork].privyConfig,
                supportedChains: [config[raasNetwork].privyConfig], /* ...other config */>
      <App />
    </PrivyProvider>
  </React.StrictMode>
);
```

### Just `usePrivy`!


# Web3Auth

## What is Web3Auth?

Web3Auth is a pluggable wallet infrastructure for Web3 wallets and applications. It streamlines the onboarding of both mainstream and crypto native users in under a minute by providing experiences that they're most comfortable with. With support for all OAuth based logins systems, web & mobile native platforms, Web3Auth provides a seamless onboarding experience for your users.

### What does Web3Auth do?

By integrating Web3Auth into your decentralized application (dApp) or blockchain wallet, you can significantly streamline the user onboarding process, making it an effortless and straightforward experience for your users. At the same time, Web3Auth allows you to retain the non-custodial characteristic of your wallet management system, which means users maintain full control and ownership of their cryptographic wallets, reinforcing the principles of privacy and security inherent in blockchain technology. For more information about Web3Auth check out their [official documentation](https://web3auth.io/docs/what-is-web3auth)

### Live Implementation on unreal

Please visit the deployed react mini site on [https://gelato-raas-aa.web.app/?network=unreal ](<https://gelato-raas-aa.web.app/?network=unreal >)with a live implementation of web3Auth and safe on unreal

The code can be found at <https://github.com/gelatodigital/gelato-raas-aa-ui>

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


