Write Your First Smart Contract On Stratis Blockchain

Stratis platform is a blockchain platform for software developers and architects who want to build new blockchain applications or want to integrate Stratis blockchain in their existing applications.

Stratis blockchain is open source and supports templates for Visual Studio to build blockchain solutions using C# and .NET. Stratis provides different products like Full Node, Smart Contract, Sidechains, Identity, etc. If you want to learn more about Stratis blockchain head over to Introduction to Stratis Platform.

In this article, you'll learn how to configure the required tools to start the development with Stratis blockchain, write a simple smart contract in C#, and deploy and execute your first Smart Contract over the Stratis blockchain.

To complete this article, you must have a basic understanding of C# and .NET. If you are new to C# programming, please learn C# here - Programming C# for Beginners. You should also have basic knowledge of Blockchain and how it works. If you do not have a basic understanding of Blockchain, please read this What is Blockchain.

Prerequisites

Here are the prerequisites to complete this tutorial:

  1. Visual Studio 2019 Community or later version
  2. Stratis Smart Contract Template
  3. Sct tool
  4. Stratis FullNode
  5. Postman
  6. Swagger

Download and install Visual Studio 2019

We are going to use Visual Studio 2019 in this tutorial. Visual Studio Community 2019 edition is free to download. You may use any other editions of Visual Studio 2019 or later.

If you wish to install Visual Studio 2019, download, and install it from here.

Install Stratis Smart Contract Template

Stratis Smart Contract template is a Visual Studio project template that creates a sample Stratis smart contract project in Visual Studio. You can install the template using the below command in your Visual Studio command terminal.

dotnet new --install Stratis.SmartContracts.Templates.CLI

Once the above command is successful, it will install the Stratis Smart Contracts Visual Studio project template.

Once it's installed successfully, it should appear in the list of available templates.

Write Your First Smart Contract On Stratis Blockchain

You can find this template in the Visual Studio available templates too. This template will be available to you when you create a new project in Visual Studio. To find it, you can simply type “Stratis” in the search box. We will see how to create a Visual Studio smart contracts project using this template later in this tutorial.

Write Your First Smart Contract On Stratis Blockchain 

Quick Fix

If you cannot find the template in the list, enable the option from Tools > Options and look for the “Show all .NET Core templates in the New Project dialog” checkbox and check it.

Write Your First Smart Contract On Stratis Blockchain 

Click the OK button.

After enabling, you need to restart the Visual Studio instance. Then try to create a new project, you should see the Stratis Smart Contract Template in the list. As I said earlier, we will use this for Smart Contract development later in this article.

Sct tool

When we create Stratis smart contracts, we must validate that the smart contract is correct. The Smart Contract validation process is completed using the sct tool provided by Stratis.

Download that sct project from here and keep it in the directory where you can easily access it. We will see more about the validation process later in this article.

Stratis Full Node (Private Blockchain)

Now, here comes the most important part. We need to install Stratis Blockchain on the local development machine, Stratis Blockchain is Stratis Full Node. If you want to learn more about Stratis Full Node, check out here.

Please note

For development, it is preferable to use a local blockchain network to deploy and test the smart contracts. Once you deploy and tested and have a clear understanding of smart contracts and Stratis, then you can go ahead and deploy your smart contracts on Live Stratis public blockchain. Stratis public blockchain has two live chains, “testnet” and “mainnet”. The “testnet” is used to deploy your smart contracts for testing purposes and the “mainnet” is the live public blockchain that’s where you will deploy your real working product smart contracts. However, to deploy on mainnet blockchain, there is going to be a small fee in form of $STRAX. We will discuss these two chains later in this series.

A local blockchain network is a clone of the actual blockchain (aka mainnet) but it uses a different consensus mechanism. To make the development and learning easier, it provides the flexibility of simple execution and testing of smart contracts on the development machine without any outside miners or validators required.

To run the blockchain on a local machine for development, download the Stratis full node master branch from here.

And run the Stratis.CirrusMinerD project with the -devmode parameter as shown below,

cd StratisFullNode\src\Stratis.CirrusMinerD

dotnet run -devmode=miner

This runs a single block-producing node utilizing the PoA (Proof-of-Authority) consensus algorithm. Open http://localhost:38223/swagger in your machine and the list of APIs should be visible. Using these API endpoints, we can interact with the blockchain.

Write Your First Smart Contract On Stratis Blockchain 

All chain logs would appear in the terminal. You can find account and balance information there.

Write Your First Smart Contract On Stratis Blockchain 

As you can see from the above screen, initially your Stratis wallet has a balance of 100,000 tokens.

Postman

Postman is a popular API client that is used to call API endpoints.

Download and install Postman from here.

To use Postman, you need to create an account. We will use Postman to deploy our contract and execute contract methods.

To get all available methods on the Swagger page to the Postman, go to http://localhost:38223/swagger/v1/swagger.json save it as a JSON file, and import it to the Postman.

Write Your First Smart Contract On Stratis Blockchain

Write Your First Smart Contract On Stratis Blockchain 

This will create a new collection “Stratis Node API” in your workspace.

Write Your First Smart Contract On Stratis Blockchain 

 

Change base URL variable value to http://localhost:38223

Write Your First Smart Contract On Stratis Blockchain 

We have configured all required tools, now let’s create our first smart contract.

Step 1 - Development

Open a Visual Studio, select Stratis Smart Contract Template and create a project.

Write Your First Smart Contract On Stratis Blockchain

Write Your First Smart Contract On Stratis Blockchain 

Click Create button.

Once a project is created, you will land upon the page below. The MyContract is a simple contract. You can customize it to your needs.

Write Your First Smart Contract On Stratis Blockchain 

A smart contract stores the information in key-value pair. Using PersistentState we can store the information in a smart contract.

For our simple contract, we will create a smart contract that will modify the default contract to store the contract owner's information. Then after deployment, we’ll retrieve that smart contract owner information.

Here is the modified version of the MyContract.

public class MyContract : SmartContract  
{  
    public MyContract(ISmartContractState smartContractState)  
    : base(smartContractState)  
    {  
        SetOwner(Message.Sender);  
    }  
   
    private void SetOwner(Address owner)  
    {  
        PersistentState.SetAddress("owner", owner);  
    }  
   
    public Address GetOwner()  
    {  
        return PersistentState.GetAddress("owner");  
    }  
}  

The above contract has two methods, SetOwner and GetOwner to set and get the owner of the contract.

Things to notice,

  • The sender is the address currently interacting with the contract.
  • The owner property will set when the contract will be deployed.
  • The constructor will be called only once when the smart contract will be deployed.
  • PersistentState stores data in key-value format permanently to the state database.

Step 2 - Validating a smart contract

The validation process is a must to check the valid constraints used in a smart contract. The process ensures that a smart contract is free from the non-deterministic elements and additional constraints around the format of the contract are met.

We have already downloaded sct tool previously. Open a terminal and step into the sct project, and run the below commands.

cd src/Stratis.SmartContracts.Tools.Sct

dotnet run -- validate [Contract_PATH]

Example

dotnet run -- validate "D:\Project Repository\StratisSmartContract\MyContract.cs".

Write Your First Smart Contract On Stratis Blockchain 

If there any issue with a contract, it will appear in the response. Modify the contract base on errors and try to validate it again. If all looks fine, we are ready to go to the next step.

Write Your First Smart Contract On Stratis Blockchain 

Step 3 - Compiling a contract

Once a smart contract is validated, the next step is to compile a smart contract and generate a byte code. The smart contract byte code is the code that is deployed on a chain.

A contract can be compiled using the sct tool using the command below,

dotnet run -- validate [CONTRACT_PATH_HERE] -sb

If the compilation is successful, the output will be the compiled bytecode that looks like the following,

Write Your First Smart Contract On Stratis Blockchain 

Step 4 - Contract Deployment

Now, we are going to deploy our smart contract on the chain.

Contract deployment can be done using API endpoints. To deploy your contract, open the Postman collection and follow the API execution.

Load the wallet

The wallet is required for everything we do in blockchain, whether it is sending cryptocurrency to someone or deploy a contract. Stratis provides a predefine wallet for development. We will use that wallet to deploy our contract, but first, we need to load that wallet.

Go to wallet load API, provide the wallet name and password.

Write Your First Smart Contract On Stratis Blockchain 

If you receive an error in response, wait for a while and try again. The API should return a 200 status code.

Get Sender wallet address

An address is required to interact with a blockchain. One account can have multiple addresses. This private chain has some pre-configured wallet addresses with balance which we can use for creating transactions.

To get addresses with balance in the wallet, use the wallet addresses API. Provide the wallet name and account name.

Write Your First Smart Contract On Stratis Blockchain 

Here address “PEpYnf7Zv5u4pTDGmvYPT2vktpop2VeCqj” has some balance. We’ll use this address to send transactions whenever it will be required in our case.

Smart Contract Deployment

A contract can be deployed using this endpoint. Here we have to pass bytecodes generated using the sct tool previously.

Go to SmartContract Wallet > select the endpoint /api/SmartContractWallet/create. Provide required information as below,

Write Your First Smart Contract On Stratis Blockchain 

Parameter Value Description
amount 0 STRAX amount sent to the contract.
contractCode   Byte code generated using sct tool
password password Wallet password
sender PEpYnf7Zv5u4pTDGmvYPT2vktpop2VeCqj Sender wallet address
walletName cirrusdev Wallet name
accountName account 0 Account name
outpoints null  
feeAmount 0.001 Fee amount
gasPrice 100 Gas price
gasLimit 100000 Gas Limit
parameters null Parameters to pass to the contract method. Our contract method doesn’t have any, hence passing null.

It will return a transaction hash in the response as below:

"89e7092c75e866566b6a9ff25bd63360d77c7e3bc0fb460a2ad2389c75e59e05"

Get Transaction Receipt

Using transaction hash, you can get transaction receipt which includes Gas Used in the transaction, From and To Addresses, Return Values, Logs, etc.

Find receipt API from the Smart Contracts folder in the collection. Provide transaction hash in the query parameter.

Write Your First Smart Contract On Stratis Blockchain 

Sample Response

{  
    "transactionHash": "89e7092c75e866566b6a9ff25bd63360d77c7e3bc0fb460a2ad2389c75e59e05",  
    "blockHash": "46409439dea5b9f30a80401e34432c90de07ee621c1df90d4a2bcb72be720141",  
    "postState": "49a66770d7702c31d57c9c3c46e20e104b1f682d64dd4fab1f9e6cd7535157e4",  
    "gasUsed": 12540,  
    "from": "PEpYnf7Zv5u4pTDGmvYPT2vktpop2VeCqj",  
    "to": null,  
    "newContractAddress": "PFHuKUFBYRYjoAfQ5aamqpzuETrd9hNAuE",  
    "success": true,  
    "returnValue": null,  
    "bloom": "000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000
0000000000",  
    "error": null,  
    "logs": []  
}  

Please note down this contract address, it will use it while interacting with the smart contract deployed.

Step 5 - Interacting with smart contract

There are two ways to interact with a contract.

  • Interacting with a contract through a transaction - a contract call
  • Interacting with a contract without a transaction - a local call

From Stratis documentation,

“A contract call uses a regular transaction that is broadcast to the network. The call parameters are encapsulated in the transaction and handled by the network in the same way as any other transaction. Every node in the network will execute a contract call. If a contract call modifies the state database, the global state is changed.

A local call does not require a transaction. Instead, it passes the call data directly to the local node and executes it on the local machine only. A local call runs against a copy of the state database. If the local call makes changes to the state, these changes are discarded after execution.

Local calls can be used to read the contract state without expending gas (to query the value of a property for example). A local call can also aid in estimating gas costs without needing to broadcast transactions to the main network.”

In our contract, we have already set the Owner value when deployed. Now, we will use a local call to read the value of the Owner.

Write Your First Smart Contract On Stratis Blockchain 

Parameters Value Description
contractAddress PFHuKUFBYRYjoAfQ5aamqpzuETrd9hNAuE Address received in response of receipt API
methodName GetOwner Contract method name
amount 0 STRAX amount send to the contract.
gasPrice 100 Gas price
gasLimit 100000 Gas Limit
sender PEpYnf7Zv5u4pTDGmvYPT2vktpop2VeCqj Sender address
parameters null Method parameters

The Response should contain the return value of the owner's address.

{  
    "internalTransfers": [],  
    "gasConsumed": {  
        "value": 10040  
    },  
    "revert": false,  
    "errorMessage": null,  
    "return": "PEpYnf7Zv5u4pTDGmvYPT2vktpop2VeCqj",  
    "logs": []  
}  

That’s all.

Congratulations! You’ve just completed the first step towards creating and deploying your smart contracts over Stratis blockchain.

Authors:

Thank you, Divyang Desai and Rohit Gupta for creating and testing the initial document.

Summary

Stratis Platform is a blockchain product that offers a set of tools to build blockchain-based distributed apps (dApps). In this tutorial, we learned how to set up and configure our local development machine to run Stratis Blockchain locally and create, deploy, and test a smart contract over the local blockchain.

In the next part of this tutorial, we will extend this smart contract application to build a real-world use case of smart contracts.

Reference


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.