Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
The "Getting Started" section is to help new community members start developing on Secret Network using standard tools for Secret Contract development. The goal is to provide an easy guide to follow with step-by-step instructions. We will also review some of the unique characteristics of contracts on Secret Network, though we will keep things at a very high level.
Topics covered:
Setting up a development Environment
Compiling and Deploying a Secret Contract
Interacting with Contracts on the Secret Network
Breakdown of a Secret Contract (optional)
Most of the topics covered focus directly on Secret Network but are also relevant to other cosmos-based blockchains.
If at any point you have any trouble understanding or following along, join us on discord to get help from the community!
If you have suggestions, improvements, or corrections, let us know on GitHub!
Crates.io serves as a centralized repository for Rust packages, also known as "crates." When building applications or libraries with Rust, developers often need to use external libraries for functionality not provided by the standard library, many of which are included on Crates.io. Below is an example of how to import Secret Labs' crates, such as secret-cosmwasm-std
, a fork of the original cosmwasm-storage
repository adapted for use in SecretNetwork's Secret Contracts.
You can think of "crates" as individual packages or modules in Rust, while "dependencies" refer to external crates that your project relies on for additional functionality.
When developing a Rust project, you will often have dependencies on other crates. These dependencies can come from crates.io (the default Rust package registry), a Git repository (such as one hosted by Secret Labs!), or a local path on your system. The Rust package manager, Cargo, is responsible for managing these dependencies, ensuring that the correct versions are fetched and built, and handling transitive dependencies (i.e., the dependencies of your dependencies).
Crates: A crate is a package or a module in Rust containing code and resources, like libraries or applications. Crates are the building blocks of Rust projects and are intended to be easily shared and reused. A crate can be a binary (application) or a library. Each crate has a unique name and a Cargo.toml
file containing metadata, such as the crate's name, version, authors, and dependencies.
Dependencies: Dependencies refer to external crates that your Rust project or library relies on for additional functionality. These external crates are not part of your project's codebase but are required for your project to build and function correctly. Dependencies are declared in the Cargo.toml
file of your project under the [dependencies]
section.
Environment configuration instructions to get started developing on Secret Network.
Secret Contracts are written using the CosmWasm framework. CosmWasm contracts are written in Rust, which is later compiled to WebAssembly (or WASM for short). To write our first Secret Contract, we need to set up a development environment with all of the tools required so that you can upload, instantiate, and execute your smart contracts.
For a step-by-step Secret Network environment configuration video tutorial, follow along here 🎥. Otherwise, continue reading!
To follow along with the guide, we will be using git
, make
, rust
, and docker
.
Install git
:
Download the latest Git for Mac installer.
Follow the prompts to install Git.
Open a terminal and verify the installation was successful by typing git --version
Install make
:
Install git
and perl
(for Windows):
Go to https://git-scm.com/download/win and the download will start automatically. Note that this is a project called Git for Windows, which is separate from Git itself; for more information on it, go to https://gitforwindows.org.
Go to https://strawberryperl.com and download the recommended version for your system. StrawberryPerl is an open-source Perl environment for Windows; for more information, visit https://perl.org. Perl is used to build other dependencies that will be installed later.
Note: support for make
on Windows is limited, so we'll provide separate commands for Windows where necessary
Download and run rustup-init.exe
.
Download and run the Rust .msi installer
Having Trouble? You might need to restart your terminal, or run a command like:
source "$HOME/.cargo/env"
After installing Rust to configure the current shell
Cargo generate is the tool you'll use to create a smart contract project. Learn more about cargo-generate
here.
Docker is an open platform for developing, shipping, and running applications.
SecretCLI is a command-line tool that lets us interact with the Secret Network blockchain. It is used to send and query data as well as manage user keys and wallets.
Run the following commands in Powershell to download the latest version of SecretCLI and add it to your profile's PATH:
Afterwards, restart the terminal and test the installation with the following command:
For a more detailed and in-depth guide on SecretCLI installation and usage, check out the documentation here.
Now it's time to learn how to compile and deploy your first smart contract 🎉
Get started developing on Secret Network using the public testnet and secret.js
In the previous section, we learned how to upload, execute, and query a Secret Network smart contract using SecretCLI and Secret testnet. Now we are going to repeat this process, but we will be uploading, executing, and querying our smart contract on a public testnet using Secret.js.
Secret.js is a JavaScript SDK for writing applications that interact with the Secret Network blockchain.
Key features include:
Written in TypeScript and provided with type definitions.
Provides simple abstractions over core data structures.
Supports every possible message and transaction type.
Exposes every possible query type.
Handles input/output encryption/decryption for Secret Contracts.
Works in Node.js, modern web browsers and React Native.
By the end of this tutorial, you will learn how to:
Add the Secret Testnet to your keplr wallet (and fund your wallet with testnet tokens)
Optimize and compile your Secret Network smart contract
Upload and Instantiate your contract using Secret.js
Execute and Query your contract using Secret.js
Let's get started!
To follow along with the guide, we will be using npm,
git,
make,
rust,
and docker
. Follow the Setting Up Your Environment guide here if you need any assistance.
Additionally, you will need to have the Secret Testnet configured with your keplr wallet and also fund it with testnet tokens.
We will be working with a basic counter contract, which allows users to increment a counter variable by 1 and also reset the counter. If you've never worked with smart contracts written in Rust before that is perfectly fine.
The first thing you need to do is clone the counter contract from the Secret Network github repo. Secret Network developed this counter contract template so that developers have a simple structure to work with when developing new smart contracts, but we're going to use the contract exactly as it is for learning purposes.
Go to the folder in which you want to save your counter smart contract and run:
When you run the above code, it will name your contract folder directory "my-counter-contract". But you can change the name by altering the text that follows the --name
flag.
Start by opening the my-counter-contract
project folder in your text editor. If you navigate to my-counter-contract/src
you will seecontract.rs, msg.rs, lib.rs, and state.rs
—these are the files that make up our counter smart contract. If you've never worked with a Rust smart contract before, perhaps take some time to familiarize yourself with the code, although in this tutorial we will not be going into detail discussing the contract logic.
In your root project folder, ie my-counter-contract
, create a new folder. For this tutorial I am choosing to call the folder node
.
In your my-counter-contract/node
folder, create a new javascript file––I chose to name mine upload.js
.
Run npm init -y
to create a package.json file.
Add "type" : "module"
to your package.json file.
Install secret.js and dotenv: npm i secretjs@v1.15.0-beta.1 dotenv
Create a .env
file in your node
folder, and add the variable MNEMONIC
along with your wallet address seed phrase, like so:
Never use a wallet with actual funds when working with the testnet. If your seed phrase were pushed to github you could lose all of your funds. Create a new wallet that you use solely for working with the testnet.
Congrats! 🎉 You now have your environment configured to develop with secret.js.
Since we are not making any changes to the contract code, we are going to compile it exactly as it is. To compile the code, run make
build-mainnet-reproducible
in your terminal. This will take our Rust code and build a Web Assembly file that we can deploy to Secret Network. Basically, it just takes the smart contract that we've written and translates the code into a language that the blockchain can understand.
Run make build
from the terminal, or just GUI it up -
This will create a contract.wasm.gz
file in the root directory.
Now that we have a working contract and an optimized wasm file, we can upload it to the blockchain and see it in action. This is called storing the contract code. We are using a public testnet environment, but the same commands apply no matter which network you want to use - local, public testnet, or mainnet.
Start by configuring your upload.js
file like so:
You now have secret.js imported, a wallet
variable that points to your wallet address, and a contract_wasm
variable that points to the smart contract wasm file that we are going to upload to the testnet. The next step is to configure your Secret Network Client, which is used to broadcast transactions, send queries and receive chain information.
Note the chainId and the url that we are using. This chainId and url are for the Secret Network testnet. If you want to upload to LocalSecret or Mainnet instead, all you would need to do is swap out the chainId and url. A list of alternate API endpoints can be found here.
Now console.log(secretjs)
and run node upload.js
in the terminal of your my-counter-contract/node
folder to see that you have successfully connected to the Secret Network Client:
To upload a compiled contract to Secret Network, you can use the following code:
Run node upload.js
in your terminal to call the upload_contract()
function. Upon successful upload, a codeId and a contractCodeHash will be logged in your terminal:
Be sure to save the codeId
and contractCodeHash
as variables so you can access them in additional function calls.
In the previous step, we stored the contract code on the blockchain. To actually use it, we need to instantiate a new instance of it. Comment out upload_contract()
and then add instantiate_contract()
.
Note that there is an initMsg
which contains count:0
. You can make the starting count whatever you'd like (as well as the contract label
).
Run node upload.js
in your terminal to call the instantiate_contract()
function. Upon successful instantiation, a contractAddress will be logged in your terminal:
Be sure to save the contractAddress as a variable so you can access it in additional function calls.
Congrats 🎉! You just finished uploading and instantiating your first contract on a public Secret Network testnet! Now it's time to see it in action!
The way you interact with contracts on a blockchain is by sending contract messages. A message contains the JSON description of a specific action that should be taken on behalf of the sender, and in most Rust smart contracts they are defined in the msg.rs
file.
In our msg.rs
file, there are two enums: ExecuteMsg
, and QueryMsg
. They are enums because each variant of them represents a different message which can be sent. For example, the ExecuteMsg::Increment
corresponds to the try_increment
message in our contract.rs
file.
In the previous section, we compiled, uploaded and instantiated our counter smart contract. Now we are going to query the contract and also execute messages to update the contract state. Let's start by querying the counter contract we instantiated.
A Query Message is used to request information from a contract; unlike execute messages
, query messages do not change contract state, and are used just like database queries. You can think of queries as questions you can ask a smart contract.
Let's query our counter smart contract to return the current count. It should be 0, because that was the count we instantiated in the previous section. We query the count by calling the Query Message get_count {}
, which is defined in our msg.rs file. Comment out instantiate_contract()
and then add try_query_count()
.
The query returns:
Great! Now that we have queried the contract's starting count, let's execute an increment{}
message to modify the contract state.
An Execute Message is used for handling messages which modify contract state. They are used to perform contract actions.
Did you know? Messages aren't free! Each transaction costs a small fee, which represents how many resources were required to complete it. This cost is measured in gas units.
The counter contract consists of two execute messages: increment{}
, which increments the count by 1, and reset{}
, which resets the count to any i32
you want. The current count is 0, let's call the Execute Message increment{}
to increase the contract count by 1.
Nice work! Now we can query the contract once again to see if the contract state was successfully incremented by 1. The query returns:
Way to go! You have now successfully interacted with a Secret Network smart contract on the public testnet!
Congratulations! You completed the tutorial and successfully compiled, uploaded, deployed and executed a Secret Contract! The contract is the business logic that powers a blockchain application, but a full application contains other components as well. If you want to learn more about Secret Contracts, or explore what you just did more in depth, feel free to explore these awesome resources:
Millionaire's problem breakdown - explains how a Secret Contract works
CosmWasm Documentation - everything you want to know about CosmWasm
Secret.JS - Building a web UI for a Secret Contract
Learn how to use SecretCLI to handle messages to query and modify contract state.
The way you interact with contracts on a blockchain is by sending contract messages. A message contains the JSON description of a specific action that should be taken on behalf of the sender, and in most Rust smart contracts they are defined in the msg.rs
file.
In our msg.rs
file, there are two enums: ExecuteMsg
, and QueryMsg
. They are enums because each variant of them represents a different message which can be sent. For example, the ExecuteMsg::Increment
corresponds to the try_increment
message in our contract.rs
file.
In the previous section, we compiled, uploaded and instantiated our counter smart contract. Now we are going to query the contract and also execute messages to update the contract state. Let's start by querying the counter contract we instantiated.
A Query Message is used to request information from a contract; unlike execute messages
, query messages do not change contract state, and are used just like database queries. You can think of queries as questions you can ask a smart contract.
Let's query our counter smart contract to return the current count. It should be 1, because that was the count we instantiated in the previous section. We query the count by calling the Query Message get_count {}
, which is defined in our msg.rs file.
The query returns:
Great! Now that we have queried the contract's starting count, let's execute an increment{}
message to modify the contract state.
An Execute Message is used for handling messages which modify contract state. They are used to perform actual actions.
Did you know? Messages aren't free! Each transaction costs a small fee, which represents how many resources were required to complete it. This cost is measured in gas units.
The counter contract consists of two execute messages: increment{}
, which increments the count by 1, and reset{}
, which resets the count to any i32
you want. The current count is 1, let's call the Execute Message increment{}
to increase the contract count by 1:
Pro Tip: SecretCLI automatically encrypts transactions. Only the transaction sender can see the data being sent (and the result). You can think of this as how HTTPS protects your data in transit when accessing a web page.
SecretCLI will ask you to confirm the transaction before signing and broadcasting. Upon successful confirmation of the transaction, the terminal will return a transaction hash
representing your transaction:
Nice work! Now we can query the contract once again to see if the contract state was successfully incremented by 1:
The query returns:
Now, we will call one final execute message, reset{}
. This will reset the count to an i32
that we specify. I am going to reset the count to 0 by running the following code in SecretCLI:
Make sure your JSON message is formatted properly!
'{"reset": {"count": 0}}`
The query returns:
Way to go! You have now successfully interacted with a Secret Network smart contract using SecretCLI.
Congratulations! You completed the tutorial and successfully compiled, uploaded, deployed and executed a Secret Contract! The contract is the business logic that powers a blockchain application, but a full application contains other components as well. If you want to learn more about Secret Contracts, or explore what you just did more in depth, feel free to explore these awesome resources:
Millionaire's problem breakdown - explains how a Secret Contract works
CosmWasm Documentation - everything you want to know about CosmWasm
Secret.JS - Building a web UI for a Secret Contract
In this example, we will compile, upload, and instantiate our first smart contract using SecretCLI and Secret Testnet.
Now that you've set up your development environment, we are going to learn how to compile, upload, and instantiate a smart contract using SecretCLI in your testnet environment.
For a step-by-step Secret Network SecretCLI video tutorial, follow along here 🎥. Otherwise, continue reading!
We will be working with a basic counter contract, which allows users to increment a counter variable by 1 and also reset the counter. If you've never worked with smart contracts written in Rust before that is perfectly fine. By the end of this tutorial you will know how to upload and instantiate a Secret Network smart contract in your terminal using SecretCLI.
The first thing we need to do is clone the counter contract from the Secret Network github repo. Secret Network developed this counter contract template so that developers have a simple structure to work with when developing new smart contracts, but we're going to use the contract exactly as it is for learning purposes.
Go to the folder in which you want to save your counter smart contract and run:
When you run the above code, it will name your contract folder directory "my-counter-contract". But you can change the name by altering the text that follows the --name
flag.
Start by opening the my-counter-contract
project folder in your text editor. If you navigate to my-counter-contract/src
you will seecontract.rs, msg.rs, lib.rs, and state.rs
—these are the files that make up our counter smart contract. If you've never worked with a Rust smart contract before, perhaps take some time to familiarize yourself with the code, although in this tutorial we will not be going into detail discussing the contract logic.
Since we are not making any changes to the contract code, we are going to compile it exactly as it is. To compile the code, run make build-mainnet-reproducible
in your terminal. This will take our Rust code and build a Web Assembly file that we can deploy to Secret Network. Basically, it just takes the smart contract that we've written and translates the code into a language that the blockchain can understand.
Run make build
from the terminal, or just GUI it up -
This will create a contract.wasm.gz
file in the root directory.
Now that we have a working contract and an optimized wasm file, we can upload it to the blockchain and see it in action. This is called storing the contract code. We are using a testnet environment, but the same commands apply no matter which network you want to use - local, public testnet, or mainnet.
In order to store the contract code, we first must create a wallet address in order to pay for transactions such as uploading and executing the contract.
To interact with the blockchain, we first need to initialize a wallet. From the terminal run:
secretcli keys add myWallet
You can name your wallet whatever you'd like, for this tutorial I chose to name my wallet "myWallet"
You should now have access to a wallet with a unique name, address, and mnemonic, which you can use to upload the contract to the blockchain:
The wallet currently has zero funds, which you query by running this secretcli command (be sure to use your wallet address in place of mine)
To fund the wallet so that it can execute transactions, you can get testnet tokens from the faucet here.
Finally, we can upload our contract:
--from <name>
refers to which account (or wallet) is sending the transaction. Update <name> to your wallet address.
--gas 5000000
refers to the cost of the transaction we are sending. Gas is the unit of cost which we measure how expensive a transaction is.
--chain-id
refers to which chain we are uploading to, which in this case is for Secret testnet!
To verify whether storing the code has been successful, we can use SecretCLI to query the chain:
Which should give an output similar to the following:
In the previous step we stored the contract code on the blockchain. To actually use it, we need to instantiate a new instance of it.
instantiate 1
is the code_id that you created in the previous section
{"count": 1}
**** is the instantiation message. Here we instantiate a starting count of 1, but you can make it any i32 you want
--from <name>
**** is your wallet address
--label
is a mandatory field that gives the contract a unique meaningful identifier
Let's check that the instantiate command worked:
Now we will see the address of our deployed contract
Congratulations! You just finished compiling and deploying your first contract! Now it's time to see it in action!
Learn how to write a full stack decentralized React application utilizing a Secret smart contract and Secret.js
Yao's Millionaires' problem is a secure multi-party computation problem introduced in 1982 by computer scientist and computational theorist Andrew Yao. The problem discusses two millionaires, Alice and Bob, who are interested in knowing which of them is richer without revealing their actual wealth.
we will be working with demonstrates an example implementation that allows two millionaires to submit their net worth and determine who is richer, without revealing their actual net worth.
for the full stack application, on Secret testnet.
To interact with the dApp, you will need to have the Secret Testnet (pulsar-3) configured with your Keplr wallet and also fund it with testnet tokens. !
In this demo you will learn how to integrate the Secret Millionaire contract with a front end designed in React using Secret.Js. Let's get started!
Excluding the instantiation message, the Secret Millionaire smart contract is capable of executing three messages:
Submit net worth
Reset net worth
Query net worth
Thus, we need to design our frontend in an intuitive manner that will allow the user to execute these messages. By the end of this tutorial you will learn how to do the following:
Integrate Keplr wallet with React.js
Use secret.js to execute multiple transactions simultaneously (submit and reset net worth)
Use secret.js to query the updated Secret Millionaire smart contract
In fewer than 100 lines of code, you have the functionality to connect and disconnect a Keplr wallet and can now use this data in every other part of any dApp you choose to create.
Now that a user can connect to our front end, let's write some functions with Secret.js that execute the submit_net_worth()
and reset_net_worth()
functions.
This function takes in two objects, each representing a millionaire, and sends their name and net worth to the Millionaire smart contract using the broadcast
method of the secretjs
library. This method accepts an array of transactions to send to the blockchain and an options object. In this case, the options object specifies a gas limit of 300,000, which is the maximum amount of computational work the transactions are allowed to perform before they are halted. Now let's use React.js to fire this function every time a user clicks on a button.
The handleSubmit
function is a handler for a form submit event in our React application. This function takes user inputs (names and net worths of two millionaires), submits this data to the blockchain, queries the richer millionaire, and updates the UI accordingly:
e.preventDefault();
: This line stops the default form submission event in a web page (which would typically reload the page).
setMillionaire1({ name: name1, networth: networth1 });
and setMillionaire2({ name: name2, networth: networth2 });
: These two lines update the states of Millionaire1
and Millionaire2
respectively. setMillionaire1
and setMillionaire2
are state-setting functions from the useState React hook.
await submit_net_worth({ name: name1, networth: networth1 }, { name: name2, networth: networth2 });
: This line calls the submit_net_worth
function described above, passing two objects containing the names and net worths of two millionaires. It then waits for the function to finish.
await query_net_worth(myQuery);
: This line calls the query_net_worth
function and waits for the function to finish.
setRicherModalOpen(true);
and setShowRicherButton(false);
: These two lines update the states controlling whether a modal and a button are displayed in the UI. They hide a button and show a modal that presents the result of the query_net_worth
function.
alert("Please approve the transaction in keplr.");
: If any error is thrown during the execution of the function, it is caught, and an alert is shown to the user instructing them to approve the transaction in Keplr.
resetSubmit
resets the smart contract state back to 0:
Lastly, we need to be able to query the result of submitted transaction, namely, which millionaire is richer. This function queries the Millionaire contract to get information about who is richer among the previously submitted millionaires, stores the result in the myQuery
array, and then we can display information stored in myQuery
in our front end.
First, we use the queryContract
method of the compute
module from secretjs
library to send a query to the Millionaire contract. This method takes an object as its argument with the following properties:
contract_address
: The address of the smart contract to which the query is being sent.
query
: The query message to be sent to the contract. In this case, it's calling the who_is_richer
method of the contract, which returns information about the richer of the two millionaires.
code_hash
: The code hash of the contract to ensure that the contract code hasn't been tampered with.
The result of this query is stored in the query
variable.
The result of the query is then pushed onto the myQuery
array. This array stores the results of all queries made so far, and we can display this on our React front end.
This tutorial assumes that you've already learned how to to the Secret testnet and now you will learn how to connect your instantiated smart contract to a frontend library, namely, React.js.
In order to execute the Secret millionaire contract, users must first be able to connect to their Keplr wallet. To see a generalized approach to connecting to Keplr wallet with Secret.js, you can . However, for our application you will learn how to connect to Keplr with React.js so that the user's wallet can control every page of your app.
Before we proceed, review the )
function:
This function awaits , an asynchronous function which enables Secret Network on Keplr, retrieves the user's account information from Keplr, creates a Secret Network client with this information, and then sets the secretjs
instance and secretAddress
with these details so that we can then share this data with the rest of our application. Notice that when we establish the Secret Network client with Secret.js we are also specifying the url
and chainId
of the client, which in this case is the url
+ chainId
for Secret testnet:
CreateContext() is the React.js hook that allows us to share the Secret Network client (aka the user's wallet address) throughout the entire application.
such that when a millionaire's net worth is submitted, the contract saves the first two entries and then returns an error for subsequent attempts until a reset. The reset operation resets the contract's state back to its initial condition, where no millionaires are registered.
Because the Secret smart contract requires two millionaires to be submitted at any given time, it would be an improved UI experience if the user could submit two millionaires simultaneously, rather than having to execute two separate transactions. We are able to implement this functionality with Secret.js using and the broadcast
method:
You now have all of the tools you need to create a decentralized full stack application on Secret Network. In this tutorial you learned how to write React.js functions to connect to Keplr wallet, submit simultaneous transactions and reset net worth data, and query a Secret smart contract for the wealthier party. If you have further questions as you continue to develop on Secret Network, please at 1pmET.