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
  • Overview
  • Getting Started
  • Configuring Environment
  • Upload the Key-value contract to Secret Network
  • Encrypt a payload
  • SecretPath - a deep dive
  • Summary

Was this helpful?

Edit on GitHub
Export as PDF
  1. Confidential Computing Layer
  2. Ethereum (EVM) Developer Toolkit
  3. Usecases
  4. Storing Encrypted Data on Secret Network

Key-Value store Developer Tutorial

Learn how to use SecretPath on EVM to encrypt payloads.

PreviousStoring Encrypted Data on Secret NetworkNextSealed Bid Auction

Last updated 3 months ago

Was this helpful?

Overview

SecretPath seamlessly handles encrypted payloads on the EVM, which means EVM developers can use SecretPath to encrypt and decrypt messages cross-chain with little-to-no Rust experience required.

Check out the Key Value store demo to see what you will build

This tutorial explains how to:

  1. Upload your own Key-value store contract on Secret Network

  2. Encrypt data on the EVM and transmit encrypted data cross-chain to Secret Network

  3. Connect your key value store contract to a React frontend.

After this tutorial, you will have the tools you need to use SecretPath to encrypt messages on any .

Getting Started

To get started, clone the EVM key value store repository:

git clone https://github.com/writersblockchain/evm-kv-store-demo.git

Configuring Environment

cd into secret-contract/node

cd secret-contract/node

Install the dependencies:

npm install

Upload the Key-value contract to Secret Network

 let init = {
    gateway_address: gatewayAddress,
    gateway_hash: gatewayHash,
    gateway_key: gatewayPublicKeyBytes,
  };
  • gatewayAddress is the SecretPath gateway contract address for testnet

  • gatewayHash is the SecretPath gateway contract hash for testnet

  • gatewayKey is public key used for SecretPath encryption on Secret testnet

To upload and instantiate the contract, run node upload:

node upload

Upon successful upload, a contractHash and address will be returned:

codeId:  5701
Contract_hash: "6311a3f85261fc720d9a61e4ee46fae1c8a23440122b2ed1bbcebf49e3e46ad2"
contract_address:  "secret1j0gpu6tlwnc9fw55wcfsfuml00kqpcnqz7dck7"

If you want to make any changes to the Secret smart contract before uploading it to Secret Network, you can do that too! Simply update the contract and then compile it by running make build-mainnet:

make build-mainnet

The compiled contract, called contract.wasm.gz, will be outputted in the secret-contract folder.

Encrypt a payload

Now that you have your key value store smart contract uploaded to Secret Network, let's use it to store encrypted messages passed from the EVM. Most of the ECDH cryptography has been abstracted away so there are only a few values you need to change.

cd into evm-kv-store-demo/kv-store-frontend:

cd evm-kv-store-demo/kv-store-frontend

Install the dependencies:

npm i
REACT_APP_SECRET_ADDRESS="secret1neeyum9p9h6u0d5jkxlqx9w5nrz49hzrr63jsw"
REACT_APP_CODE_HASH="6994d8ff9ed1af73ef4685a9f5c8a5568804afb5fa5ce49ec8496fb271a9760a"

That's it! You dApp is now connected to your Secret smart contract and ready to encrypt key value pairs. To start the application, run:

npm run start

Now that you have successfully uploaded a key-value contract to Secret Network and connected it to a React frontend, let's examine the code to understand how SecretPath passes encrypted data from the EVM to Secret Network.

When you create your cross-chain dApp, you simply need to format your data so that it can be transmitted successfully from the public SecretPath contract to the private SecretPath contract.

  // The function name of the function that is called on the private contract
  const handle = "store_value";

  // Data are the calldata/parameters that are passed into the contract
  const data = JSON.stringify({
    key: key,
    value: value,
    viewing_key: viewing_key
  });

handle is the name of the function that we are executing in our private Secret smart contract, and data is the data that we pass to the function that we are executing in the Secret contract, which in the case of the key value contract is key, value, and viewing_key.

Let's now look at the Secret Network contract that we uploaded to better understand the store_value function and how it uses the parameters key, value, and viewing_key.

Understanding the Private (Secret) Contract

 // determine which function to call based on the included handle
    let handle = msg.handle.as_str();
    match handle {
        "store_value" => store_value(deps, env, msg.input_values, msg.task, msg.input_hash),
        "retrieve_value" => retrieve_value(deps, env, msg.input_values, msg.task, msg.input_hash),
        "change_value" => change_value(deps, env, msg.input_values, msg.task, msg.input_hash),
        _ => Err(StdError::generic_err("invalid handle".to_string())),
    }

Since we pass the handle store_value from your dApp to your Secret contract, it knows to execute the store_value function!

Inside of the store_value function, we use the key, value, and viewing_key parameters that we pass from the EVM in order to create a key map with our key-value pairs:

let input: InputStoreMsg = serde_json_wasm::from_str(&input_values)
        .map_err(|err| StdError::generic_err(err.to_string()))?;
  
  // create a task information store
    let storage_item = StorageItem {
        value: input.value,
        viewing_key: input.viewing_key,
    };
    
  // map task to task info
    KV_MAP.insert(deps.storage, &input.key, &storage_item)?;

This data is encrypted and stored inside of your Secret smart contract. The data can now only be revealed with a query that uses the proper viewing_key:

const secretjs = new SecretNetworkClient({
                url: "https://pulsar.lcd.secretnodes.com",
                chainId: "pulsar-3",
            });

            const query_tx = await secretjs.query.compute.queryContract({
                contract_address: process.env.REACT_APP_SECRET_ADDRESS,
                code_hash: process.env.REACT_APP_CODE_HASH,
                query: {
                    retrieve_value: {
                        key: key,
                        viewing_key: viewingKey
                    }
                },
            });

Summary

In this tutorial, you've learned how to deploy a key-value store smart contract on Secret Network, encrypt and transmit messages from an EVM-compatible chain, and integrate the contract with a React frontend. Using SecretPath, you can now seamlessly handle encrypted payloads cross-chain with minimal Rust experience. By following the steps outlined, you're equipped to build decentralized applications that leverage SecretPath for secure, cross-chain communication and data storage.

In the node folder, open the upload.js file and review the instantiate message at :

These three parameters remain constant and must be passed for every Secret Network contract that implements SecretPath. They can be found for testnet.

Open and change the routing_contract and routing_code_hash to the address and code hash for your contract:

Congrats! You now have now deployed a fullstack cross-chain decentralized application that passes encrypted key-value pairs from the EVM and stores them on Secret Network

SecretPath - a deep dive

From a high-level, all that you need to know is there is a public SecretPath contract deployed on every EVM chain listed , which communicates with a private SecretPath contract deployed on Secret Network, and it is these public/private contract pairs that encrypt your data and pass messages from the EVM to Secret Network.

All of the data formatting for the public EVM contract happens in . This is almost entirely boilerplate code except for the variables and :

At, we have a match statement, which includes the handle "store_value":

You can view the frontend component for querying your Secret contract !

If you have any questions or run into any issues, post them on the and somebody will assist you shortly.

πŸ”“
🀝
πŸŽ‰
πŸŠβ€β™€οΈ
line 56
here
.env
here
submit.js
handle
data
line 109
πŸ˜„
here
Secret Developer Discord
πŸ˜„
here
EVM-compatible chain