Welcome to the Secret App Developer Quickstart Guide! Hopefully, this post will make it easy for you to develop and test privacy-preserving “secret contracts” on Secret Network. Here is a list of Secret Network resources, including our website, documentation, chat, forum, and wiki. Keep reading to learn about developing secret contracts, and try using a real secret app for private on-chain voting!

Secret Network enables distributed, private computation throughout a distributed system of nodes equipped with Trusted Execution Environments (TEEs). Leveraging secret contracts with encrypted inputs, outputs, and state, developers can build Secret Apps with new capabilities. Ultimately, this approach empowers all kinds of stakeholders to earn from value shared.

In this article, we introduce an evolving development guide, including the walkthrough of a demo application for Secret Voting. That means privacy-preserving smart contracts for securely tallying encrypted votes, calculating results without revealing anyone’s particular vote data.

Blockchain-based voting is primarily used for accountable governance of decentralized organizations. It may also be helpful to centralized institutions like the USPS, which recently filed a patent for a “secure voting system” involving blockchain technology. Still, current implementations of “on-chain” voting are weak: they expose user identity, so anyone can see how users voted. This makes governance processes vulnerable to bribery and manipulation. We can help solve that problem with Secret Voting!

Secret Contract Development Guide

Secret contracts are based on CosmWasm 0.10 (docs) which is the de facto standard for smart contracts running on Cosmos SDK blockchains. Secret Network implements a compute module used to store, query and instantiate secret contracts. Once stored on the blockchain, the contract has to be created (or instantiated) in order to execute its methods. If you're familiar with Solidity, you can think of this like migrating solidity code using Truffle, which handles the deployment of smart contracts on Ethereum.

Secret contracts are written in the Rust language and compiled to WebAssembly (WASM) binaries. Dependencies include the Rust compiler and toolchain, the cargo package manager, and the package to generate projects. You can check out the Rust book, rustlings course, examples and more at Rust-Lang.org 🦀

Getting Started

Setup the Secret Network Light Client

  1. Install secretcli
  2. Use version 0.8.1
  3. Configure secretcli
secretcli config node tcp://bootstrap.pub.testnet3.enigma.co:26657

secretcli config chain-id enigma-pub-testnet-4

secretcli config trust-node true

*note: our testnet chain-id is "enigma-pub-testnet-4" but our faucet and explorer domains currently include "testnet3" ~ apologies for any confusion!

Using the Rust Programming Language

Next, we will show you how to get started with Rust, if you haven’t already. The Rust programming language is reliable, performant, and it has a wonderful community!

Follow these steps to install Rust and its dependencies:

1) install Rust

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source $HOME/.cargo/env

2) add rustup target wasm32 for both stable and nightly

rustup default stable
rustup target list --installed
rustup target add wasm32-unknown-unknown
rustup install nightly
rustup target add wasm32-unknown-unknown --toolchain nightly

3) if using linux, install the standard build tools:

apt install build-essential

4) Cargo is the tool you will use to create a secret contract project:

https://doc.rust-lang.org/cargo

cargo install cargo-generate --features vendored-openssl

If you are having problems, try running cargo --version, and if your installed compiler is below 1.40, you might be getting compilation errors because of an outdated compiler. Run rustup update to upgrade to the newest toolchains, check cargo --version just in case, then run the install command again.

Resources for Secret Contract Devs

Developing Secret Contracts | Secret Network
Privacy is a Public Good

Testnet Explorer

https://explorer.pub.testnet3.enigma.co

Testnet Faucet

Secret Network Testnet Faucet
A token faucet for Cosmos Testnets.

Integrated Development Environments (IDEs)

These IDEs are known to work very well for developing Secret Contracts:

The programming language that wants to rescue the world from dangerous code
Rust, a language developed by Mozilla with enthusiastic backers across the software community, wants to save developers from making their biggest mistakes

Create your first Secret Contract

  1. Generate Your Project
  2. Compile a Secret Contract
  3. Deploy on Testnet
  4. Instantiate With Parameters

1 - Generate Your Project

cargo generate --git https://github.com/enigmampc/secret-template --name mysimplecounter

The git project above is a secret contract template that implements a simple counter. The contract is created with a parameter for the initial count and allows subsequent incrementing.

Next, change directory to the project you created and view the structure and files that were created:

cd mysimplecounter

You should have generated a directory with the project name with this structure:

Cargo.lock  Developing.md  LICENSE  Publishing.md  examples schema tests
Cargo.toml  Importing.md   NOTICE   README.md      rustfmt.toml    src

2 - Compile a Secret Contract

Use the following command to compile the Secret Contract, producing the wasm contract file. The Makefile uses wasm-opt, a WebAssembly optimizer.

npm i -g wasm-opt

make

3 - Deploy the Contract on Testnet

Upload the optimized contract.wasm to enigma-pub-testnet-3. You will need some test SCRT from the faucet:

Secret Network Testnet Faucet
A token faucet for Cosmos Testnets.
 secretcli tx compute store contract.wasm.gz --from <your account alias> -y --gas 1000000 --gas-prices=1.0uscrt

The result is a txhash ~ if you query it, you can see the code_id in the logs. In our case, it's 45. We will need the code_id to create an instance of the contract:

secretcli q tx 86FCA39283F0BD80A1BE42288506C47041BE2FEE5F6DB13F4652CD5594B5D875

Querying the Smart Contract Code
The following command lists any secret contract code:

secretcli query compute list-code

[
{
"id": 45,
"creator": "secret1ddhvtztgr9kmtg2sr5gjmz60rhnqv8vwm5wjuh",
"data_hash": "E15E697E5EB2144C1BF697F1127EDF1C4322004DA7F032209D2D445BCAE46FE0",
"source": "",
"builder": ""
}
]

4 - Instantiate the Secret Contract

To create an instance of this project we must also provide some JSON input data, a starting count, you should change the label to be something unique, which can then be referenced by label instead of contract address for convenience:

INIT="{\"count\": 100000000}"
CODE_ID=45
secretcli tx compute instantiate $CODE_ID "$INIT" --from <your account alias> --label "my counter" -y

With the contract now initialized, we can find its address:

secretcli query compute list-contract-by-code $CODE_ID

Our instance: secret1htxt8p8lu0v53ydsdguk9pc0x9gg060k7x4qxr

We can query the contract state:

CONTRACT=secret1htxt8p8lu0v53ydsdguk9pc0x9gg060k7x4qxr
secretcli query compute query $CONTRACT "{\"get_count\": {}}"

And we can increment our counter! 🎉

secretcli tx compute execute $CONTRACT "{\"increment\": {}}" --from <your account alias>

Project Structure

The source directory has these files:

contract.rs  lib.rs  msg.rs  state.rs

Developers can modify contract.rs for custom logic. The main Secret Contract entry points are the init, handle, and query functions:

`init`

This function is the constructor of your contract, and it is only called once in the lifecycle of the contract. For the simple counter example, init just initializes the storage of the current count and the signer/owner of the instance being initialized.

Example invocation using secretcli:

secretcli tx compute instantiate "$CODE_ID" "$INPUT_MSG" --label "$UNIQUE_LABEL" --from "$MY_KEY"

`handle`

We also define handle, a generic handler for all functions writing to storage and providing an environment, so the counter can be incremented and reset.

Example invocation using secretcli:

secretcli tx compute execute "$CONTRACT_ADDRESS" "$INPUT_ARGS" --from "$MY_KEY" # Option A
secretcli tx compute execute --label "$LABEL" "$INPUT_ARGS" --from "$MY_KEY" # Option B

`query`

Generally, query is the implementation of read-only queries. Queries run over the current blockchain state but don't incur fees and don't have access to msg.sender. They are still metered by a gas limit that is set on the executing node. We have a query for each function reading state. For the simple counter, we only have query_count, returning the counter state.

Example invocation using secretcli:

secretcli q compute query "$CONTRACT_ADDRESS" "$INPUT_ARGS"

The state.rs file defines the State struct, used for storing the contract data, the only information persisted between multiple contract calls. The msg.rs file is where the InitMsg parameters are specified (like a constructor), the types of Query (GetCount) and Handle[r] (Increment) messages, along with any custom structs for each query response.

Secret Apps

A “Secret App” is a decentralized application with built-in computational and programmable data privacy. Secret Apps are usually made of the following components:

  • Secret Contract deployed on the Secret Network
  • Front-end app connected to the Secret Network using SecretJS

SecretJS interacts with a REST API exposed by nodes in the Secret Network. This REST API / HTTPS server is commonly referred to as LCD Server.

Secret Voting App

This demo application, created by Taariq Levack, is a great example of a building block that you might use in your own Secret DAO! Privacy for on-chain voting is necessary to mitigate collusion. Think about why most elections use private ballots. If users can prove which option they voted for, there might be increased risk of bribery. Secret Voting is a reasonable solution that might be used in a variety of organizations.

Try it out!

https://levackt.github.io/voting-app

To use the Secret Voting app, you will need some testnet SCRT. First, grab your testnet address in the top-left corner before navigating to the faucet. After you get there, paste your copied testnet address (automatically generated for demo purposes) from the Secret Voting app. Next, verify that you are human using reCAPTCHA, then click “send me tokens” to receive 1000 testnet SCRT. Return to the app to stake and create your first poll.

This platform allows users to create polls with parameters like participation threshold (quorum) and vote duration. Once a poll is created, any participant can stake SCRT to vote on the poll in a privacy-preserving manner. This means users can prove they voted and results can be tallied. However, all votes will remain encrypted forever.

Staking means depositing testnet SCRT into the Secret Voting contract in order to gain more voting power. Initially, you will have 0 SCRT as your total voting power. Click the stake button and try depositing more. You can easily withdraw, but no more than is actively staked in a poll. Once the poll ends you’re free to withdraw.

Review the code:

https://github.com/levackt/voting-app/tree/secret

Privacy Model of Secret Contracts

Here is a WIP document from Enigma’s dev team, highlighting key aspects of the privacy model for Secret Contracts. Please review this new document, as it is intended to help engineers understand the best practices for developing contracts with secure privacy features. You might also be interested in the Secret Network encryption specs:

Encryption | Secret Network
Privacy is a Public Good

Secret Network Dev Committee

https://learn.scrt.network/committees.html#devs-committee

If you’re interested in getting more involved in our community of developers, you might enjoy participating in the dev committee. Join us for weekly discussions about improving documentation, answering questions related to developing secret contracts, exploring specific use cases, building secret applications, and more!

Fill out this form to let us know how and why you’re hoping to contribute.

To discuss Secret Network and Secret Apps, visit our community channels:
Forum | Secret Chat | Twitter | Telegram | Discord