Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
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.
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)
What won't be covered:
An in-depth guide to developing Secret Contracts - Secret By Example
Secret Network architecture - Secret Network Techstack
How to create a web UI for Secret Contracts - Secret.Js
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!
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:
In this example, we will compile, upload, and instantiate our first smart contract using SecretCLI and LocalSecret.
Now that you've set up your LocalSecret development environment, we are going to learn how to compile, upload, and instantiate a smart contract using SecretCLI in your LocalSecret testnet environment.
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.
Next, configure SecretCLI to work with LocalSecret by running the following code in your text editor terminal (this is assuming you already have an instance of LocalSecret running in docker, which we learned in the previous section)
Did you know? By default, SecretCLI tries to connect to a locally running network
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
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
and contract.wasm.gz
file in the root directory.
While we could upload this contract wasm file to the blockchain exactly as it is, instead we are going to follow best practices and optimize the wasm file. This just means we are going to reduce the size of the file so that it costs less gas to upload, which is critical when you eventually upload contracts to mainnet. Make sure you have an instance of LocalSecret running and then run the following code:
Optimize compiled wasm
You should now have an optimized contract.wasm.gz
file in your root directory, which is ready to be uploaded to the blockchain! Also note that the optimizer should have removed the contract.wasm
file from your 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 local 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, run:
Your wallet address should now have 1000000000 uscrt 🤯
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 LocalSecret!
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!
Environment configuration instructions to get started developing on Secret Network.
LocalSecret is a complete Secret Network testnet and ecosystem containerized with Docker. It simplifies the way secret contract developers test their contracts in a sandbox before they deploy them on a public testnet or mainnet (You can think of it like a local testnet that only you have access to).
There are 3 main tools we will use -
IDE - a development environment (usually VS Code or JetBrains CLion/IDEA with Rust support)
SecretCLI - a command-line tool to interact with the blockchain
LocalSecret - a local Secret Network chain set up for development purposes
We're going to install our environment manually so that you can code in a text editor of your choosing, but if you would prefer to work with JetBrains you can also configure your environment that way using the resources at the bottom of this page.
To follow along with the guide, we will be using git
, make
, rust
, and docker
.
Install git
:
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):
Note: support for make
on Windows is limited, so we'll provide separate commands for Windows where necessary
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
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:
Set the file name to secretcli
and set it as executable
Set the file name to secretcli
and set it as executable
An instance of LocalSecret requires approximately 2.5 GB of RAM to run. You may need to increase the resources available in your Docker settings.
The installation methods differ based on the processor architecture. This is because Secret Network makes use of Intel SGX to protect private data.
Now that you have docker installed, open the docker application and then in your terminal run:
Unfortunately, even LocalSecret inside a docker cannot be run on an M1 Mac. As a workaround, we recommend using a LocalSecret instance in a Gitpod environment.
This environment is set up in such a way that can be accessed remotely as well.
To connect, prepend the port number with the Gitpod URL. e.g., if my workspace is at https://scrtlabs-gitpoddevenv-shqyv12iyrv.ws-eu54.gitpod.io
then I would be able to connect to the RPC service at https://26657-scrtlabs-gitpoddevenv-shqyv12iyrv.ws-eu54.gitpod.io
To set up SecretCLI to connect to this environment, use the following commands
Congrats! You now have a containerized version of LocalSecret running inside docker! You should see blocks being created in real time:
Now it's time to learn how to compile and deploy your first smart contract 🎉
- explains the counter contract in depth
- explains how a Secret Contract works
- everything you want to know about CosmWasm
- Building a web UI for a Secret Contract
For a step-by-step Secret Network SecretCLI video tutorial, 🎥. Otherwise, continue reading!
We will be working with a basic , 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 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.
Secret Contracts are written using the . 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 LocalSecret development environment with all 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, 🎥. Otherwise, continue reading!
Download the latest .
Go to 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 .
Go to and download the recommended version for your system. StrawberryPerl is an open-source Perl environment for Windows; for more information, visit . Perl is used to build other dependencies that will be installed later.
Download and run .
Download and run
Cargo generate is the tool you'll use to create a smart contract project.
is an open platform for developing, shipping, and running applications.
Download secretcli
for your system .
Download secretcli
for your system .
For a more detailed and in-depth guide on SecretCLI installation and usage, check out the .
To get started, follow the instructions at the .
The amazing folks at created a prebuilt containerized environment containing an IDE (IntelliJ IDEA) that contains everything you need to get started. If you're comfortable with JetBrains IDEs, this may be a good choice for you.
To get started, visit , or just go for it and run the IDE from docker:
Then after a few seconds you will be able to access your in-browser IDE at .
Once the environment loads, clone the repository from
To know whether you have a Mac with an M1 chip or an Intel chip, click on the Apple logo located in the lefthand corner of your desktop and navigate to About This Mac/Overview, and confirm whether the processor is M1 or Intel. If you have an Intel chip, you can run LocalSecret in docker, otherwise, proceed with these set up instructions to learn how to .
Run an instance of LocalSecret in Gitpod by .
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.
The Secret smart contract 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.
This is the source code for the full stack application, and you can use the live dApp at this web address 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. Learn how to configure and fund your keplr wallet here!
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!
This tutorial assumes that you've already learned how to compile, upload, and instantiate a Secret smart contract to the Secret testnet and now you will learn how to connect your instantiated smart contract to a frontend library, namely, React.js.
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 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 review the Secret.js docs here. 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 ConnectWallet()
function:
This function awaits SetupKeplr()
, 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:
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.
See the completed file here. 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.
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.
The Secret Millionaire contract is designed 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 MsgExecuteContract and the broadcast
method:
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.
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 join the weekly Monday developer call on Discord at 12pmET.
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 LocalSecret. 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. Learn how to configure and fund your keplr wallet here.
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 mineindex.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 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
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
and contract.wasm.gz
file in the root directory.
While we could upload this contract wasm file to the blockchain exactly as it is, instead we are going to follow best practices and optimize the wasm file. This just means we are going to reduce the size of the file so that it costs less gas to upload, which is critical when you eventually upload contracts to mainnet. Make sure you have docker installed and then run the following code:
Optimize compiled wasm
You should now have an optimized contract.wasm.gz
file in your root directory, which is ready to be uploaded to the blockchain! Also note that the optimizer should have removed the contract.wasm
file from your 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 index.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.
When connecting to a local node, you must indicate a port, which is 1317
Now console.log(secretjs)
and run node index.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 index.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 index.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:
Secret University counter contract breakdown - explains the counter contract in depth
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