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
    • 💡Best Practices for Developers
    • 📖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
  • Introduction
  • Our Multi Contract System
  • Designing the Manager Contract
  • Msg.rs
  • Contract.rs
  • Creating the WasmMsg
  • Executing the contract with Secret.js
  • Conclusion

Was this helpful?

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

Cross Contract Communication

Step-by-step guide on how to execute Secret Network smart contracts that communicate with each other

PreviousPermitsNextSubmessages

Last updated 6 months ago

Was this helpful?

Introduction

, we explored the creation of isolated smart contracts within the Secret Network ecosystem. To construct more intricate systems using smart contracts, it is essential to establish effective communication between them. This documentation will delve into the implementation of secure and efficient communication between secret contracts, allowing you to build powerful, interconnected applications on Secret Network.

Our Multi Contract System

In this tutorial, that can execute a counter smart contract that is already deployed to the Secret Testnet. Thus, we are working with two smart contracts:

  1. Manager Contract - which executes the Counter Contract

  2. Counter Contract - which is executed by the Manager Contract

By the end of this tutorial, you will understand how to implement the Increment() function on a Manager smart contract, which increments a counter smart contract by one every time the Increment function is called.

To follow along with this tutorial step-by-step, clone down the Secret Network counter template repo 😊

Designing the Manager Contract

We will be designing a Manager Smart Contract which can execute a Counter Contract that is deployed to the Secret testnet. Let's start by creating the message that we want to execute on the counter smart contract. In the src directory (which currently contains contract.rs, lib.rs, msg.rs and state.rs), create a counter.rs file and add the following:

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum CounterExecuteMsg {
    Increment {},
}

CounterExecuteMsg contains a single function Increment{}. This is the function we will call to increment the counter contract once we have completed designing our Manager smart contract.

Msg.rs

Now, navigate to the msg.rs file. Replace the existing code with the following:

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct InstantiateMsg {}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExecuteMsg {
    IncrementCounter { contract: String, code_hash: String },
}

Here we have an empty InstantiateMsg, as well as an enum ExecuteMsg, with a single variant, IncrementCounter, which contains two strings: contract and code_hash. This is the contract address and code hash of the counter contract, which we will be calling from the Manager contract.

What is the code hash?

Unlike other Cosmos chains, Secret Network requires the hash of the smart contract in addition to the address when executing calls to smart contracts.

Contract hashes are what binds a transaction to the specific contract code being called. Otherwise, it would be possible to perform a replay attack in a forked chain with a modified contract that decrypts and prints the input message.

Contract.rs

Now, navigate to the contract.rs file. Replace the execute entry point with the following:

#[entry_point]
pub fn execute(
    deps: DepsMut,
    env: Env,
    _info: MessageInfo,
    msg: ExecuteMsg,
) -> StdResult<Response> {
    match msg {
        ExecuteMsg::IncrementCounter {
            contract,
            code_hash,
        } => try_increment(deps, env, contract, code_hash),
    }
}

When the IncrementCounter variant is matched, the function calls the try_increment function, which contains two fields, contract and code_hash. The contract field is the address of the contract to be incremented, and the code_hash field is the code hash of the contract. This function contains the logic for incrementing the counter in our counter contract.

Remember the counter.rs file that we created earlier with the CounterExecuteMsg enum containing Increment{} ? 🤔 Now, in the try_increment() function, we are going to use a WasmMsg to call Increment{} in order to increment the counter contract.

A WasmMsg dispatches a call to another contract 
at a known address (with known ABI).

Creating the WasmMsg

In CosmWasm, a WasmMsg is an enum used to perform actions such as instantiating a new contract, executing a function on an existing contract, or sending tokens to a contract. Here are the main variants of WasmMsg:

  1. Instantiate: This variant is used to create a new instance of a Wasm smart contract. It contains the following fields:

    • code_id: The ID of the Wasm code to instantiate.

    • msg: The message to initialize the contract (usually a JSON object).

    • funds: The amount of tokens to send to the contract upon instantiation.

    • label: A human-readable label for the new contract instance.

    • admin: An optional address that, if provided, will have administrative privileges over the contract instance (e.g., for migration or update purposes).

  2. Execute: This variant is used to execute a function on an existing Wasm smart contract (and is the variant that we are calling in our contract) It contains the following fields:

    • contract_addr: The address of the contract to execute the function on.

    • msg: The message to be processed by the contract (usually a JSON object).

    • funds: The amount of tokens to send to the contract along with the execution message.

  3. Migrate: This variant is used to migrate an existing Wasm smart contract to a new code version. It contains the following fields:

    • contract_addr: The address of the contract to migrate.

    • new_code_id: The ID of the new Wasm code to migrate the contract to.

    • msg: The message to initialize the new code version (usually a JSON object).

In the counter.rs file, comment out or delete the existing execute functions and add the following:

pub fn try_increment(
    _deps: DepsMut,
    _env: Env,
    contract: String,
    code_hash: String,
) -> StdResult<Response> {
    let exec_msg = CounterExecuteMsg::Increment {};

    let cosmos_msg = WasmMsg::Execute {
        contract_addr: contract,
        code_hash: code_hash,
        msg: to_binary(&exec_msg)?,
        funds: vec![],
    };

    Ok(Response::new()
        .add_message(cosmos_msg)
        .add_attribute("action", "increment"))
}

The try_increment function creates a WasmMsg::Execute message to increment the counter in the specified smart contract and returns a Response object containing the message and an attribute. When the Response object is returned by the smart contract's execute function, the blockchain will execute the WasmMsg::Execute message, effectively incrementing the counter in the target contract.

Here's a breakdown of the code inside the function:

  1. let exec_msg = CounterExecuteMsg::Increment {};: This line creates a new CounterExecuteMsg enum instance with the Increment variant, which represents a message to increment the counter.

  2. let cosmos_msg = WasmMsg::Execute { ... };: This block creates a WasmMsg enum instance with the Execute variant. The Execute variant is used to execute our Counter smart contract. The contract_addr field is set to the contract parameter, the code_hash field is set to the code_hash parameter, the msg field is set to the binary representation of exec_msg, and the funds field is set to an empty vector, indicating no funds are sent with this message.

  3. Ok(Response::new() ... ): This block constructs a new Response object with the following:

    • .add_message(cosmos_msg): The cosmos_msg (a WasmMsg::Execute instance) is added to the response as a message to be executed after the current contract execution finishes.

    • .add_attribute("action", "increment"): An attribute with key "action" and value "increment" is added to the response. Attributes are used to store additional information about the operation and can be useful for indexing and querying transactions.

Executing the contract with Secret.js

Let's focus on how to write the increment function as seen below:

let increase_count = async () => {
  const tx = await secretjs.tx.compute.executeContract(
    {
      sender: wallet.address,
      contract_address: contractAddress,
      msg: {
        increment_counter: {
          contract: "secret1edd6prk0w55c27dkcxzuau8mvlwa2rghgwelqk",
          code_hash:
            "cf6c359e936ded4e18716aafdef4d880cc42e4d87c29ca88205ff38c1ddf6531",
        },
      },
      code_hash: contractCodeHash,
    },
    { gasLimit: 100_000 }
  );

  console.log(tx);
};

increase_count();

The secret.js function increase_countsends an increment_counter message (which is the message we defined in msg.rs) to our Counter smart contract. This message increments the counter contract via the WasmMsg that we defined in the increase_count function.

You can call this function by commenting out the other functions in index.js and running node index.js in the terminal (make sure you are in the secret-messages/manager/node directory).

Now, in your terminal, navigate to the secret/counter/node directory. Call the query_count function to see the current count of the counter contract. After using the manager contract to increment, it should now be incremented by one!

Conclusion

Congratulations, you have now created a Manager smart contract that interacts with a Counter smart contract on Secret Network! By designing a Multi-Contract System, you can enable secure and efficient communication between secret contracts, allowing for more intricate and interconnected decentralized applications.

You can view the which contains the upload, instantiation, and execution functions using secret.js.

💻
🤓
In previous sections
we will be designing a simple smart contract
here
completed code repo here