Secret Network
WebsiteDiscordGithub
  • 👋INTRODUCTION
    • Secret Network Introduction
    • Secret Network Techstack
      • Private transactions - A quick summary
      • Blockchain Technology
        • Cosmos Basics
        • Tendermint
        • Cosmos SDK
        • IBC
        • CosmWasm
      • Privacy Technology
        • Encryption - Key Management
          • Overview
          • Key Derivation & Encryption Techniques
          • The Initialization Of Secret Network
          • Full Node Boostrap
          • Contract State Encryption
          • Transaction Encryption
          • Consensus seed rotation
        • Trusted Execution Environments  (TEE) —  Intel SGX
          • How Secret Network Uses SGX
          • SGX-SPS Security & Reliabillity
          • Remote Attestation
          • Trusted & Untrusted Core
          • Sealing
        • Private smart contracts - overview
  • 💻Development
    • 🏠Getting Started
      • Setting Up Your Environment
        • Cargo.toml Best Practices (Crates vs Dependencies)
      • Compile and Deploy
      • Running the Application
      • Compile and Deploy on Secret testnet (best for Javascript devs)
      • Fullstack dApp Integration
    • 🤓Secret Contracts
      • Secret Contracts & CosmWasm
        • Framework overview
        • Secret Contract Components
          • Instantiation Message
          • Execution Message
          • Query Message
          • Deps/DepsMut
          • Storage
            • Prefixed Storage
            • Singleton
            • Keymap
            • Append Store
            • Best practices
        • CosmWasm vs Secret CosmWasm
      • Secret Tokens (SNIP-20)
      • Contract - module call
      • Secret contract - Design Space/Features
        • Secret Contracts introduction
        • Gas/Fee usage
        • TPS and scalability
        • Privacy Essentials
        • Access Control
          • Viewing Keys
          • Permits
        • Trusted and untrusted data
        • Secret-VRF - on-chain Randomness
        • Privacy design
          • Mitigate privacy risks - full guide
          • Gas Evaporation & Tracking
        • Confidential Computing Layer
        • Fiat/Crypto Onboarding
        • Account abstraction
        • Fee abstraction
        • Wallet support
        • Bridge (messaging/tokens)
        • IBC (Hooks, PFM, Wasm)
        • Price Oracles
        • Auto Restaking
      • Permissioned Viewing
        • Viewing Keys
        • Permits
      • Cross Contract Communication
      • Submessages
        • get_contract_code_hash
      • Randomness API - Secret VRF
        • Native On-chain randomness
        • Randomness over IBC
      • Execution Finalization
      • Factory Contracts
      • Contract Migration
        • Manual - < v1.11
        • Native - from v1.11
      • Cross-deploy Vanilla CW and Secret Contracts
      • Testing Secret Contracts
        • Unit Tests
        • Continuous Integration
        • Datatype Handling - Uint, floats etc.
    • 👀Secret Contract - Reference, Guides, Examples
      • Starter guide - Millionaire's Problem
      • Reference Contracts
      • Open source dApps
      • Tools & Libraries
        • Network interaction SDKs
          • Secret.js (JavaScript)
          • SecretPy (Python)
          • SecretK (Kotlin)
          • Secret.NET
            • Snippets
              • Deploying a Contract
              • Send Native Coin
              • Query a Contract
              • Create a new Wallet
              • Permits
              • SNIP20
              • SNIP721
          • Shade.Js
        • LocalSecret - Devnet docker
        • Smart contract - Tools/Utils
          • Secret Toolkit
          • CW-Plus
          • Fadroma - SC framework
          • Hidden Gems
          • Other
            • Secret IDE
            • Polar
    • 🖼️Frontend Development
      • Getting Started with SecretJS
        • Usage Examples
          • Sending Queries
          • Sending Messages
          • Contract Migration
          • Wallet Integrations
          • Query Permits
          • SNIP20 (SCRT Tokens)
          • SNIP721 (Secret NFTs)
      • Feegrant
        • Understanding Feegrant allowances
        • Grant allowances
        • Using grant allowances to execute transactions
        • Using the Fee Grant Faucet
    • 📬Deployment Addresses/ API Endpoints
      • Secret (SNIP 20) token contracts list
        • SNIP Asset naming guidelines
      • Connecting to the Network
        • API Endpoints Mainnet (Secret-4)
        • API Endpoints Testnet (Pulsar-3)
        • Usage examples
        • Comparison of endpoint types
      • Create your own SNIP-25 IBC Token
  • Secret AI
    • 🤝Introduction
    • 🏗️Architecture
    • 👩‍💻Secret AI SDK
      • Setting Up Your Environment
      • Running the Application
    • 🪙Economics
    • Smart Contract Reference
      • SubscriptionManager
      • WorkerManager
      • RewardsManager
  • 🌐SecretVM - Confidential Virtual Machines
    • 🤝Introduction
    • 🏗️Architecture
    • ☑️Attestation
      • What is Attestation
      • Obtaining Attestation Data
      • Attestation Report - Key Fields
      • Chain of Trust
    • 🏁Launching a SecretVM
    • 🛠️Managing SecretVM Lifecycle
    • ✅Verifying a SecretVM
      • 🐢Full Verification
      • 🐰Quick Verification
    • 👨‍💻SecretVM CLI
      • Getting started
      • Authentication Commands
      • Virtual Machine Commands
    • 💡Best Practices for Developers
    • 🔐Verifiable Message Signing
    • 📖Glossary
  • 🔓Confidential Computing Layer
    • 🧑‍🚀IBC Developer Toolkit
      • Basics
        • Overview
        • Cross-chain Messaging with IBC Hooks
          • Functions, Methods, and Data Structures
          • Typescript SDK
          • IBC-Hooks
        • IBC Relaying with Go Relayer
      • Usecases
        • Storing Encrypted Data on Secret Network
          • Key-Value store Developer Tutorial
        • Secret VRF for IBC with IBC-Hooks
        • Confidential Voting
        • Sealed Bid Auctions
      • Supported Networks
        • Mainnet
        • Testnet
    • 🤝Ethereum (EVM) Developer Toolkit
      • Basics
        • Overview
        • Connecting Metamask to Secret Network
        • SecretPath + Reown integration
        • Cross-chain Messaging
          • SecretPath
            • Architecture Overview
            • Detailed Architecture
            • SecretPath Developer Tutorials
            • Public EVM Gateway Architecture
            • How to deploy SecretPath on your chain
          • Axelar GMP
            • Architecture Overview
            • Axelar GMP Developer Tutorial
      • Usecases
        • Storing Encrypted Data on Secret Network
          • Key-Value store Developer Tutorial
        • Sealed Bid Auction
          • Sealed Bid Auction Developer Tutorial
        • Confidential Voting
          • Confidential Voting Developer Tutorial with SecretPath
        • VRF
          • Implementing VRF into any EVM Contract
          • VRF Developer Tutorial
          • Performance figures of SecretVRF vs competitors
          • Using encrypted payloads for VRF
          • Converting from Chainlink VRF to Secret VRF in four steps
        • Confidential Document Sharing
        • Tokens
          • From EVM to Secret
      • Supported Networks
        • EVM
          • EVM Mainnet
          • EVM Testnet
          • Gateway Contract ABI
        • Secret Gateway
          • SecretPath mainnet (secret-4) contracts
          • SecretPath testnet (pulsar-3) contracts
    • 🙌Solana Developer Toolkit
      • Usecases
        • Storing Encrypted Data on Secret Network
          • Key-value Store Developer Tutorial
        • VRF
          • VRF Developer Tutorial
      • Program IDs
        • Solana Mainnet & Testnet
        • Gateway Contract IDL
  • 🤫Overview, Ecosystem and Technology
    • 🚀Secret Network Overview
      • The SCRT coin
      • Private Tokens
      • Use Cases
        • Decentralized Finance (DeFi)
        • Art And Digital Media
        • Gaming
        • Data Privacy
        • Payments And Transactions
        • Communication
      • The technology
      • History
      • Roadmap (Core development)
        • Secret 2.0
      • Where To Buy SCRT?
      • Using the Testnet
    • 🐸Ecosystem Overview
      • Wallets
      • Applications
      • Explorers & tools
      • Funding
        • SCRT Labs Grants
        • Dilutive funding/VC raise
        • Community Pool
        • Developer bounties
          • SCRT Labs bounties [on-hold]
          • CCBL [on-hold]
          • CCR [On-hold]
        • Application specific
          • Shade Grants
      • Contributors & Entities
        • Validators
        • SCRT Labs
        • Secret Foundation
        • Secret Committees
          • Support
          • Governance
      • Secret Network Dictionary
  • 🔧Infrastructure
    • 🔓Use SecretCLI
      • Secretcli vs. Secretd
      • Install
      • Configuration
      • Address Types
      • Key Types
      • Generating Keys
      • Viewing Keys
      • Query Transactions
      • Send Tokens
      • Multisig Keys
      • Multisig Transactions
      • Transaction Broadcasting
      • Fees & Gas
      • Fee Distribution
      • Secret Contracts
      • Slashing
      • Minting
      • Delegating
      • Restake
      • Nodes
      • Governance
        • Creating Governance Proposals
        • Query Proposals
        • Deposits
        • Voting
    • 🔐Use Ledger hardware wallet
      • 🔐Ledger with SecretCLI
    • 🖥️Running a node/validator
      • Setting up a node/validator
        • Hardware setup
          • Hardware Compliance
          • VPS/Bare-Metal Compliance
            • Leaseweb Setup
            • PhoenixNAP Setup
            • Psychz Setup
            • nForce Setup
            • Vultr Setup
            • OVHCloud Setup
            • Microsoft Azure Setup
          • Patching your Node
          • Enclave verification
          • Registration troubleshooting
        • Testnet Setup
          • Install SGX
          • Install secretd
          • Setup Full Node
          • Testnet State Sync
          • Becoming a Testnet Validator
          • Installing CLI & Creating A New Address
        • Mainnet Setup
          • Install SGX
          • Install secretd
          • Setup Full Node
          • Quicksync / Snapshot
          • Statesync
          • Becoming A Validator
          • Installing CLI & Creating A New Address
      • Maintaining a node/validator
        • Slashing information
        • Migrating a Validator
        • Troubleshooting
        • Validator Backup
        • Server security
          • SSH authentication
          • Server configuration
          • Uncomplicated-Firewall (UFW)
          • Local CLI
        • Node Monitoring
          • Prometheus
            • Environment Preperation
            • Install Node Exporter
            • Install Prometheus
            • Configuring Prometheus
          • Grafana
            • Install Grafana
            • Grafana Dashboard
            • Next Steps
          • Docker
            • Install Docker
            • Configuration
            • Start Containers
            • Grafana Dashboard
            • Application Ports
            • Stop Containers
          • Goaccess
            • Install Goaccess
            • Setup Goaccess
        • Helpful commands
          • Query Validators
          • Bond Tokens
          • Withdraw Rewards
          • Query Delegations
          • Unbond Tokens
          • Query Unbonding-Delegations
          • Redelegate Tokens
          • Query Redelegations
          • Query Parameters
          • Query Pool
          • Query Delegations To Validator
      • API Noderunning
        • Running Multiple Nodes on the Same Server
        • Node Loadbalancing using Nginx
          • Setup Nginx
          • Example Nginx config
        • Using Auto heal to improve cluster uptime for Nginx
      • Sentry and Archive nodes
        • Mantlemint
        • Sentry Nodes
        • Archive Nodes
    • ⛓️IBC Relayers
      • Hermes
      • RLY
      • IBC channel database
    • 🆙Upgrade Instructions
      • v1.13
      • v1.12
      • v1.11
      • v1.10
      • v1.9
      • v1.8
      • v1.7
      • Shockwave Omega v1.6
      • v1.5
      • Shockwave Delta v1.4
      • Shockwave Delta v1.4 (Testnet)
      • Shockwave Alpha v1.3
      • Cosmovisor
      • Vulcan Network Upgrade (OLD)
    • ☠️Postmortems
      • SNIP-20 leaks
      • xApic
      • Secpk-Verifications Bloat
      • Earn Contract Exploit
      • Testnet Halt 95
    • ✍️Contribute to the documentation
      • Report Bugs
      • Suggest Enhancements
      • First Contribution Guide
      • Pull Request Templates
        • Update Documentation
        • Bug Fix
        • Improve Performance
        • Change Functionality
      • Style Guide
    • 🌊Versioning & Changelog
      • Secret Network v1.13
      • Secret Network v1.12
      • Secret Network v1.11
      • Secret Network v1.10
      • Secret network v1.9
      • Secret Network v1.7/1.8
      • Secret Network v1.6
      • Secret Network v1.5
      • Secret Network v1.4 (CosmWasm 1.0)
Powered by GitBook
On this page
  • Crosschain Contract Demo
  • Contract.rs
  • State.rs: Secret vs CosmWasm
  • How to cross-compilw on different chains

Was this helpful?

Edit on GitHub
Export as PDF
  1. Development
  2. Secret Contracts

Cross-deploy Vanilla CW and Secret Contracts

A description of building the same code for both vanilla CosmWasm and the Secret version.

PreviousNative - from v1.11NextTesting Secret Contracts

Last updated 7 months ago

Was this helpful?

Crosschain Contract Demo

The crosschain contract that we are examining can be cloned from . This repo is a demo of writing a simple voting contract that is intended to be deployed on multiple chains with different types of CosmWasm in a single codebase. This demo supports two types of CosmWasm: vanilla (i.e. original, like Terra or Juno supported) and secret (i.e. SecretNetwork supported).

The contract code uses conditional compilation and feature flags in Rust to support different configurations within a single codebase. If you navigate to , you will find two sets of imports for different features, either "secret" or "vanilla". The imports are conditionally compiled using #[cfg(feature = "…")] attributes. The "secret" feature uses the secret_std crate, whereas the "vanilla" feature uses the cosmwasm_std crate.

For more information about the feature differences of Standard CosmWasm vs the secret version please visit TLDR: No raw queries, iterators and upgradeability

Contract.rs

Contract.rs defines several functions:

  1. instantiate: This function initializes the contract and sets the initial vote count for both options to 0. In this instance, it is the same for both Secret and vanilla CosmWasm.

  2. execute: This function processes the ExecuteMsg, which supports voting. It calls the vote_impl function to perform the vote.

  3. vote_impl: This function is implemented twice, once for each feature ("secret" and "vanilla"). It checks whether the voter has already voted, and if not, it updates the tally for the chosen option.

  4. query: This function processes QueryMsg, which supports two queries: getting the vote tallies (Tally) and getting a list of voters (Voters). For the Tally query, it returns the vote count for both options. For the Voters query, it calls the voters_query_impl function.

  5. voters_query_impl: This function is also implemented twice for each feature. It retrieves the voters list based on the provided page number.

Let's examine the differences in vote_impl based on which type of CosmWasm we are using. The overall structure and logic of the function are the same, but there are differences in the specific methods called on the VOTERS, OPTION_1, and OPTION_2 objects. These differences arise from the different crates used for the "secret" and "vanilla" features.

fn vote_impl: Secret

In the "secret" version of vote_impl:

  1. VOTERS.contains(deps.storage, &info.sender) is used to check if the voter already exists in the storage.

  2. VOTERS.insert(deps.storage, &info.sender, &1) is used to insert the voter into the storage.

#[cfg(feature = "secret")]
fn vote_impl(deps: DepsMut, info: MessageInfo, option: u64) -> StdResult<Response> {
    if VOTERS.contains(deps.storage, &info.sender) {
        return Err(StdError::generic_err("already voted"));
    }

    VOTERS.insert(deps.storage, &info.sender, &1 /* arbitrary value */)?;

    // Update tally
    match option {
        1 => OPTION_1.update(deps.storage, |tally| Ok(tally + 1))?,
        2 => OPTION_2.update(deps.storage, |tally| Ok(tally + 1))?,
        _ => return Err(StdError::generic_err("unsupported option")),
    };

    Ok(Response::default())
}

fn vote_impl: Vanilla CosmWasm

In the "vanilla" version of vote_impl:

  1. VOTERS.has(deps.storage, info.sender.clone()) is used to check if the voter already exists in the storage.

  2. VOTERS.save(deps.storage, info.sender, &1) is used to save the voter into the storage.

#[cfg(feature = "vanilla")]
fn vote_impl(deps: DepsMut, info: MessageInfo, option: u64) -> StdResult<Response> {
    if VOTERS.has(deps.storage, info.sender.clone()) {
        return Err(StdError::generic_err("already voted"));
    }

    VOTERS.save(deps.storage, info.sender, &1 /* arbitrary value */)?;

    // Update tally
    match option {
        1 => OPTION_1.update(deps.storage, |tally| Ok::<u128, StdError>(tally + 1))?,
        2 => OPTION_2.update(deps.storage, |tally| Ok::<u128, StdError>(tally + 1))?,
        _ => return Err(StdError::generic_err("unsupported option")),
    };

    Ok(Response::default())
}

The rest of the function, including the match statement for updating the vote tally, is the same between the two versions. Now let's examine the difference in querying functions between the two versions.

fn voters_query_impl: Secret

Vanilla CosmWasm Iterators are not supported on Secret Network because users cannot iterate over data stored by different users as there is no access to their dedicated encryption key. However, iteration is still possible on Secret Network through the use of the secret_toolkit for storage in place of cosmwasm_std.

In the "secret" version of voters_query_impl:

  • The VOTERS.paging_keys(deps.storage, page, PAGE_SIZE as u32)? method is used to retrieve a list of voters corresponding to the requested page. This method is specific to the secret_toolkit storage API and directly handles pagination.

#[cfg(feature = "secret")]
fn voters_query_impl(deps: Deps, page: u32) -> StdResult<QueryRes> {
    let voters = VOTERS.paging_keys(deps.storage, page, PAGE_SIZE as u32)?;
    Ok(QueryRes::Voters { voters })
}

fn voters_query_impl: Vanilla

In the "vanilla" version of voters_query_impl:

  • The VOTERS.keys(deps.storage, None, None, cosmwasm_std::Order::Ascending) method is used to retrieve an iterator over all the keys (voters) in the storage. Pagination is implemented manually in the function.

#[cfg(feature = "vanilla")]
fn voters_query_impl(deps: Deps, page: u32) -> StdResult<QueryRes> {
    use cosmwasm_std::Addr;

    let voters_iter = VOTERS.keys(deps.storage, None, None, cosmwasm_std::Order::Ascending); //.paging_keys(deps.storage, page, 20)?;
    let voters: Vec<Addr> = voters_iter
        .skip((page as usize) * PAGE_SIZE)
        .take(PAGE_SIZE)
        .filter(|v| v.is_ok())
        .map(|v| v.unwrap())
        .collect();
    Ok(QueryRes::Voters { voters: voters })
}

The main difference between the two implementations is that the Secret version relies on a secret_toolkit pagination method (paging_keys), whereas the Vanilla version manually implements pagination using iterator methods.

State.rs: Secret vs CosmWasm

The contract uses state_secret or state_vanilla modules for managing the state, depending on the selected feature. The state management includes saving the vote counts for each option and managing the list of voters. Let's examine the differences between state_secret.rs and state_vanilla.rs.

state_secret.rs

In the Secret version:

  1. The secret_std::Addr is used as the address type.

  2. The secret_toolkit::storage::Item and secret_toolkit::storage::Keymap types are used for storage management.

  3. The storage objects are initialized with Keymap::new and Item::new methods, passing the byte representation of the corresponding prefixes.

#![cfg(feature = "secret")]

use crate::state::{OPTION_1_PREFIX, VOTE_PREFIX};
use secret_std::Addr;
use secret_toolkit::storage::{Item, Keymap};

pub static VOTERS: Keymap<Addr, u8> = Keymap::new(VOTE_PREFIX.as_bytes());
pub static OPTION_1: Item<u128> = Item::new(OPTION_1_PREFIX.as_bytes());
pub static OPTION_2: Item<u128> = Item::new(OPTION_1_PREFIX.as_bytes());rust

state_vanilla.rs

In the Vanilla version:

  1. The cosmwasm_std::Addr is used as the address type.

  2. The cw_storage_plus::Item and cw_storage_plus::Map types are used for storage management.

  3. The storage objects are initialized with the Map::new and Item::new methods, passing the corresponding prefixes directly.

#![cfg(feature = "vanilla")]

use crate::state::{OPTION_1_PREFIX, VOTE_PREFIX};
use cosmwasm_std::Addr;
use cw_storage_plus::{Item, Map};

pub static VOTERS: Map<Addr, u8> = Map::new(VOTE_PREFIX);
pub static OPTION_1: Item<u128> = Item::new(OPTION_1_PREFIX);
pub static OPTION_2: Item<u128> = Item::new(OPTION_1_PREFIX);

Thus, the Secret version relies on the secret_std and secret_toolkit crates, while the Vanilla version uses the cosmwasm_std and cw_storage_plus crates. However, the overall purpose of the state management objects (VOTERS, OPTION_1, and OPTION_2) remains the same in both versions.

How to cross-compilw on different chains

# Building for Secret
make secret

# Building for Juno
make vanilla

💻
🤓
this repo
contract.rs
this page.