Smart Contracts

The Real blockchain, a decentralized Layer 1 (L1) network, is designed to empower users, developers, and small and medium enterprises (SMEs) by enabling the tokenization of real-world assets (RWAs). A key feature of Real is its support for smart contracts, which are programmable agreements that automate and enforce actions on the blockchain. This page explains the concept of smart contracts, their purpose on Real, and how to use them to build applications and manage RWAs.


Smart Contracts

What Are Smart Contracts?

Smart contracts are self-executing programs stored on the blockchain that automatically enforce the terms of an agreement when predefined conditions are met. They are written in code, deployed to the Real blockchain, and executed by the network’s validators in a decentralized, trustless manner.

  • Code-Based Agreements: A smart contract contains rules and logic (e.g., "If user A sends 100 $REAL tokens, then transfer ownership of a tokenized RWA to user A").

  • Immutable and Transparent: Once deployed, a smart contract’s code cannot be altered, and its execution is visible to all network participants.

  • Automated Execution: Smart contracts run automatically when their conditions are met, eliminating the need for intermediaries.

How Do Smart Contracts Work on Real?

Real leverages CosmWasm, a secure and efficient framework for writing smart contracts in Rust, integrated into its Cosmos SDK-based architecture. Here’s how they function:

  1. Development: Developers write smart contracts in Rust, defining the logic for actions like token transfers, RWA tokenization, or staking.

  2. Deployment: The contract is compiled into WebAssembly (Wasm) bytecode and deployed to the Real blockchain using the Real CLI or a wallet.

  3. Interaction: Users or other smart contracts interact with the deployed contract by sending transactions (messages) to its address.

  4. Execution: The Real network’s validators execute the contract’s code in a sandboxed environment, ensuring security and consistency across all nodes.

  5. State Updates: The contract updates the blockchain state (e.g., transferring tokens, updating ownership) based on its logic.

Key Features of Smart Contracts on Real

  • Security: CosmWasm provides a sandboxed execution environment, protecting the network from malicious or buggy contracts.

  • Interoperability: Smart contracts on Real can interact with other contracts and Cosmos-based chains via the Inter-Blockchain Communication (IBC) protocol.

  • Gas Efficiency: Contracts are optimized for low gas usage, reducing transaction fees paid in $REAL tokens.

  • Flexibility: Developers can create complex logic for a wide range of use cases, from RWA tokenization to decentralized finance (DeFi).

What Are Smart Contracts For?

Smart contracts on Real enable a variety of use cases, particularly those related to tokenizing RWAs and building decentralized applications (dApps). Here are some primary purposes:

Tokenizing Real-World Assets (RWAs)

  • Purpose: Smart contracts automate the process of converting physical or intangible assets (e.g., real estate, inventory, invoices) into digital tokens on the Real blockchain.

  • Example: An SME can deploy a smart contract to tokenize a property, defining rules for fractional ownership, transfer restrictions, and compliance checks (e.g., KYC/AML).

  • Benefit: Automates ownership transfers, reduces paperwork, and ensures transparency for investors.

Automating Transactions and Workflows

  • Purpose: Smart contracts can automate repetitive or time-sensitive tasks, such as scheduled payments or vesting schedules.

  • Example: Schedule a monthly distribution of tokenized RWA shares to investors using a smart contract (see our Schedule Transaction Guide).

  • Benefit: Saves time and ensures timely execution without manual intervention.

Decentralized Finance (DeFi) Applications

  • Purpose: Smart contracts enable DeFi protocols like lending, borrowing, or liquidity pools using tokenized RWAs as collateral.

  • Example: A developer can create a lending platform where users stake tokenized real estate to borrow $REAL tokens.

  • Benefit: Expands financial opportunities for SMEs and investors in a trustless manner.

Governance and Voting

  • Purpose: Smart contracts can manage on-chain governance, allowing $REAL token holders to vote on proposals.

  • Example: A governance contract can tally votes and automatically implement changes (e.g., adjusting inflation rates) if a proposal passes.

  • Benefit: Ensures transparent and tamper-proof decision-making.

Custom dApps and Logic

  • Purpose: Developers can build custom dApps tailored to specific needs, such as RWA marketplaces, auction platforms, or subscription services.

  • Example: A marketplace dApp where users buy and sell tokenized RWAs, with the smart contract handling escrow and transfers.

  • Benefit: Enables innovation and expands the Real ecosystem.

How to Use Smart Contracts on Real

Real provides tools and resources to help developers write, deploy, and interact with smart contracts. Below is a step-by-step guide to get started.

Step 1: Set Up Your Development Environment

  1. Install Prerequisites:

  2. Fund Your Account:

Step 2: Write a Smart Contract

Create a simple smart contract to store and increment a counter. This example demonstrates the basics of CosmWasm on Real.

  1. Create a New Project:

    cargo new --lib real-counter-contract
    cd real-counter-contract
  2. Update Cargo.toml:

Add CosmWasm dependencies:

[package]
name = "real-counter-contract"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib", "rlib"]

[dependencies]
cosmwasm-std = "1.5.0"
cosmwasm-schema = "1.5.0"
serde = { version = "1.0", features = ["derive"] }
  1. Write the Contract: Replace src/lib.rs with the following code:

use cosmwasm_std::{
    entry_point, to_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult,
};
use cosmwasm_schema::{cw_serde, QueryResponses};

#[cw_serde]
pub struct InstantiateMsg {
    pub count: i32,
}

#[cw_serde]
pub enum ExecuteMsg {
    Increment {},
}

#[cw_serde]
#[derive(QueryResponses)]
pub enum QueryMsg {
    #[returns(GetCountResponse)]
    GetCount {},
}

#[cw_serde]
pub struct GetCountResponse {
    pub count: i32,
}

#[cw_serde]
pub struct State {
    pub count: i32,
}

const CONTRACT_STATE: cosmwasm_std::Item<State> = cosmwasm_std::Item::new("state");

#[entry_point]
pub fn instantiate(
    deps: DepsMut,
    _env: Env,
    _info: MessageInfo,
    msg: InstantiateMsg,
) -> StdResult<Response> {
    let state = State { count: msg.count };
    CONTRACT_STATE.save(deps.storage, &state)?;
    Ok(Response::new().add_attribute("method", "instantiate"))
}

#[entry_point]
pub fn execute(
    deps: DepsMut,
    _env: Env,
    _info: MessageInfo,
    msg: ExecuteMsg,
) -> StdResult<Response> {
    match msg {
        ExecuteMsg::Increment {} => {
            let mut state = CONTRACT_STATE.load(deps.storage)?;
            state.count += 1;
            CONTRACT_STATE.save(deps.storage, &state)?;
            Ok(Response::new().add_attribute("method", "increment"))
        }
    }
}

#[entry_point]
pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
    match msg {
        QueryMsg::GetCount {} => {
            let state = CONTRACT_STATE.load(deps.storage)?;
            to_binary(&GetCountResponse { count: state.count })
        }
    }
}

Step 3: Compile and Deploy the Smart Contract

  1. Compile the Contract:

    cargo build --release --target wasm32-unknown-unknown
  2. Optimize the Wasm File:

    cosmwasm-check target/wasm32-unknown-unknown/release/real_counter_contract.wasm
  3. Deploy to Real:

    • Store the contract:

      reald tx wasm store target/wasm32-unknown-unknown/release/real_counter_contract.wasm --from <YOUR_ADDRESS> --chain-id real-mainnet-1 --gas auto --fees 5000ureal

      Note the code_id (e.g., 1).

    • Instantiate the contract:

      reald tx wasm instantiate 1 '{"count": 0}' --from <YOUR_ADDRESS> --chain-id real-mainnet-1 --label "CounterContract" --gas auto --fees 5000ureal

      Note the contract_address (e.g., real1counter...).

Step 4: Interact with the Smart Contract

  • Increment the Counter:

    reald tx wasm execute <CONTRACT_ADDRESS> '{"increment": {}}' --from <YOUR_ADDRESS> --chain-id real-mainnet-1 --gas auto --fees 5000ureal
  • Query the Counter:

    reald query wasm contract-state smart <CONTRACT_ADDRESS> '{"get_count": {}}' --chain-id real-mainnet-1

    This returns the current count (e.g., {"count": 1} after one increment).

Step 5: Test and Iterate

Best Practices

  • Audit Contracts: Ensure your smart contracts are audited to prevent vulnerabilities that could lead to loss of funds or RWAs.

  • Optimize Gas Usage: Write efficient code to minimize transaction fees for users.

  • Test Thoroughly: Use the Testnet and Localnet to test edge cases and ensure your contract behaves as expected.

  • Document Your Code: Provide clear documentation for your smart contract’s functions and usage to help other developers integrate with it.


Need Help?

If you have questions about smart contracts on Real, reach out to our team:

Smart contracts on Real unlock the potential for automated, trustless interactions, from RWA tokenization to DeFi and beyond. Start building today and contribute to the Real ecosystem!

Last updated