How to deploy a Smart Contract in RSK

This tutorial aims to help you install the required environment, code your first smart contract and deploy it to RSK network.

Index:

If you find something unclear, or have ideas on how to improve this or new tutorials? Found this useful? Want to help building more tutorials? Have ideas?, feel free to contact me!

Environment setup

This is very hard to standardize, there are several tools available, and more are coming every day, lot of compatibility issues, versions, different OSs, so, I will try to give (IMHO) the most easy to install and compatible environment I can.

Linux MacOS Windows
1. Visual Studio Code Debian/Ubuntu

Red Hat/Fedora/SUSE

macOS 10.9+ Win 7, 8, 10
2. VS Solidity Ext. http://juan.blanco.ws/solidity-contracts-in-visual-studio-code/
3. Truffle https://github.com/trufflesuite/truffle
4. Jaxx wallet https://jaxx.io/downloads.html

 

Tools

RSK has two networks, one is a development or test network (also known as testnet) and a production ready network (the mainnet).

To interact with the network, you must connect your application with a Node. You can find how to deploy a node and connect it to testnet or mainnet.

Public nodes

New! no installation or hardware required.

How to install a node

Linux
Java (Windows, Linux, MacOS)
Docker
Microsoft Azure Marketplace
Amazon Web Services Marketplace

In order to interact and see the network status, here you can find the links:

Tool \ Network Testnet Mainnet
Network status https://stats.testnet.rsk.co https://stats.rsk.co
Network explorer https://explorer.testnet.rsk.co/ https://explorer.rsk.co/
Faucet https://faucet.testnet.rsk.co N/A

The Testnet has a faucet that provides RBTC to run your Smart Contracts within the sandbox for free, the Mainnet does not, that would be like giving money for free in the real world Smile.

You will need to install all the required software specified in the previous section.

I present you your new IDE, Visual Studio Code, this is the initial screen:

demo 1

 

New project

Let’s start coding! Open Visual Studio Code. You can see the interface in the screenshot.

The first task is setting the environment folder. Its just a new empty folder that we are gonna use to host all our project files.

Click on “File” –> “Open folder…” and choose a convenient location.

As we are going to use the Command Line Interface that is not showed by default. Click in “View” –> “Integrated Terminal” to open it.

demo 2

The folder should be empty in order to start fresh.

To start coding, truffle help us by creating a template project with some magic on it.

On the command interface type:

truffle init

demo 3

This creates some folders and files as a template, we will focus our attention in.

  • “contracts” folder: where our contracts must be (*.sol files).
  • “migrations” folder: javascript migration code, this is executed on the deploy.
  • “truffle.js” file: truffle configuration file, we are going to configure our network to deploy the contract.

You should see the file tree as follows:

demo 4

Lets create our first Smart Contract just creating a new file called “HelloWorld.sol” inside the “contracts” folder.

demo 5

Open the file and paste the following code (updated at ago-2018):

pragma solidity ^0.4.4;

contract HelloWorld {

string greeting;

constructor() public {

greeting = "Hello smart world!";

}

function getGreeting () public view returns (string) {

return greeting;

}

function setGreeting(string _newGreeting) public returns (bool success) {

greeting = _newGreeting;

return true;

}

 

}

demo 6

Its a simple Smart Contract with only one variable that can be asked or replaced using the functions “getGreeting()” and “setGreeting(“some message”)” respectively.

 

Compile

Now we have our code done, let’s prepare the project to compile and deploy it.

Open the “1_initial_migration.js” file in the “migrations” folder, and add lines 2 and 6. The file should end like this:

var Migrations = artifacts.require("./Migrations.sol");

var HelloWorld = artifacts.require("./HelloWorld.sol");

module.exports = function(deployer) {

deployer.deploy(Migrations);

deployer.deploy(HelloWorld);

};

demo 7

This tells truffle how to deploy our code.

Next step is to compile the Smart Contracts running this command in the terminal:

truffle compile

demo 8

This operation compiles the Smart Contracts and creates one JSON file for each one. Open and see what’s inside our compiled Smart Contract (“HelloWorld.json” inside the new created “build/contracts” folder). Do you find some things interesting?

demo 9

 

In-memory blockchain

In order to avoid gas usage and long waits during our development process, truffle implements an in-memory blockchain that allow us to deploy and interact with our smart contracts.

To start the in-memory blockchain and connect the terminal to it, run this command:

truffle develop

demo 10

This command returns lot of information. Some to highlight are the address:port where the blockchain is running (http://127.0.0.1:9545 in my case, this may vary, but don’t panic).

We can see also 10 account addresses with the corresponding Private Keys and the famous 12 words; Its convenient to write this down for future usage. Don’t send any money to this accounts, they are living just in your in-memory blockchain.

 

Deploy

Firstly, we are going to deploy our compiled Smart Contracts to our in-memory blockchain.

If you started this tutorial from this step, I recommend to go back one and open the in-memory blockchain console.

Once in the truffle develop console, just type and execute this command to deploy the contract:

migrate

demo 11

If you don’t see a result similar to the one in the screenshot, force the deploy using this command:

migrate –-reset

The command result gives:

  • Transaction Id
  • Contract address (important to call the contract)

That is all! You have your Smart Contract deployed!

 

Test your smart contract

With the Smart Contract deployed, now we need to test or interact with it. Truffle execute the migration file “1_initial_migration.js” mentioned before. It’s just javascript, so, we can see line by line what is running. In the second line we create a global variable called HelloWorld that contains the Smart Contract, type in the console and see the result:

HelloWorld

Now, we are going to interact with it, type line by line the following commands as showed in the image below:

var helloWorldContract

HelloWorld.deployed().then(function(contract){ helloWorldContract = contract; })

helloWorldContract.getGreeting.call().then(console.log)

This three lines creates a variable “helloWorldContract”, then reference the Smart Contract to this variable, and finally we use the variable to call the “getGreeting” function in the contract.

demo 12

The next step is writing/modify the greeting by calling the “setGreeting” function of the Smart Contract, typing and running the command:

helloWorldContract.setGreeting("RSK loves Tokyo!").then(console.log)

 

The result is quite different from the other calls, and the time between the call and answer may vary if you are running local or connected to a remote network. Because we are setting a variable, we need to run the Smart Contract through a transaction to the blockchain. The command result is the transaction receipt. You can see the blockNumber, transactionHash and gasUsed among other info.

If you are running this on a remote network (testnet or mainnet), you will find this transaction details in the explorer (see tools section).

demo 13

Now, the last step is calling the “getGreeting” function again to check our new greeting message!

demo 14

As you know, the Smart Contracts deployed to remote networks are executed by the real nodes participating in the network. It’s normal that the transaction have some delay in the execution, and maybe you will see the same first greeting message, give the network some time and run the command again.

 

Remote deploy

The last step is deploying our Smart Contract to a remote network. To do so, you need a node to interact with the network, refer yourself to the tools section in this tutorial to see how to install a node, or ask me the address if you are following this tutorial during a workshop or meetup. (join the RSK Ambassador Program)

Truffle needs to know about the network, so, let’s configure the network as showed below:

module.exports = {

// See <http://truffleframework.com/docs/advanced/configuration>

// to customize your Truffle configuration!

networks: {

aleRSK: {

gas : 2500000,

gasPrice : 1,

from : "0xsomeaddress",

host: "https://public-node.testnet.rsk.co/", //your node url, or the public node url

port: 4444,

network_id: "*" // Match any network id

}

}

};

 

Copy this code to the “truffle.js” configuration file.

demo 15

If you are using a public node, you need to create and unlock your address private key. Run the following commands in order (replace “password” with a random key):

var myAccount = web3.personal.newAccount('password')

web3.personal.unlockAccount(myAccount, "password");

myAccount

The last command returns your RSK Address.Copy and paste it on the configuration file (“from” variable).

Navigate to the testnet faucet (https://faucet.testnet.rsk.co), and paste your address to get some RBTC.

Back in the terminal, press CTRL + C + C to exit the console.

After that, run the migrate command as we learnt in the previous sections.

truffle migrate –reset --network aleRSK

Replace “aleRSK” with the name you want. Be sure its the same configured before in the “truffle.js” file.

Open the console connected to the remote network:

truffle console --network aleRSK

After that, test it using the same steps as in the “testing your smart contract” section.

demo 16

If you are here you’ve showed passion about the technology. Join our Global Community Slack and join the RSK Ambassador Program!

 

Video:

[Facebook] [Google] [LinkedIn] [Twitter] [Windows Live] [Email]
Tagged with: , , , ,
4 comments on “How to deploy a Smart Contract in RSK
  1. Anonymous says:

    Dumb question, but what exactly can the average Joe make with smart contracts? Also, what are the advantages of using RSK opposed to Ethereum?

  2. Alex says:

    Hi there. I am trying to deploy on testnet using the public node and i am not getting nowhere.
    This is my network section on truffle.js:

    “`
    rskTestnet: {
    host: ‘https://public-node.testnet.rsk.co/’,
    provider: new HDWalletProvider(mnemonic, ‘https://public-node.testnet.rsk.co/’),
    port: 443,
    network_id: 31
    }
    “`

  3. vivek bhandari says:

    Not sure if previous comment got posted.
    I am getting error while trying to connect to local rsk testnet node.

    viveks-mbp:rsk_tutorial vivekbhandari$ truffle migrate –reset –network aleRSKUsing network ‘aleRSK’.
    Running migration: 1_initial_migration.js
    Deploying Migrations… … undefined
    Error encountered, bailing. Network state unknown. Review successful transactions manually.
    Error: Local wallet is disabled in this node
    at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/errors.js:38:1)
    at /usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/requestmanager.js:86:1
    at /usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-migrate/index.js:225:1
    at /usr/local/lib/node_modules/truffle/build/webpack:/packages/truffle-provider/wrapper.js:134:1
    at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/we
    b3/httpprovider.js:128:1)
    at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2
    .js:64:1)
    at XMLHttpRequest._setReadyState (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:354:1)
    at XMLHttpRequest._onHttpResponseEnd (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:509:1)
    at IncomingMessage. (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:469:1)
    at IncomingMessage.emit (events.js:187:15)
    at endReadableNT (_stream_readable.js:1081:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
    viveks-mbp:rsk_tutorial vivekbhandari$

Leave a Reply

Your email address will not be published. Required fields are marked *

*