22 C
Kathmandu
Home Blockchain Guides Writing your first smart contract in Scilla (Zilliqa)

Writing your first smart contract in Scilla (Zilliqa)

  • N/R
  • N/R

Scilla — a programming language for writing smart contracts in Zilliqa Blockchain is not an easy language to master. The official documentation is itself too technical for a normal developer to understand. Therefore, in this article, I will try to explain how you can start writing your own smart contracts and deploy them in Zilliqa Blockchain. 

TOOLS:

1. IDE

I will be using Neo Savant IDE to write and test our smart contract. It can be accessed at: https://ide.zilliqa.com/

2. ZilPay Wallet (Optional)

ZilPay is a wallet that can be added as an extension in your web browser. The reason why I wrote it as optional is because you can simply use EmulatedEnv to test your smart contract before deploying it to the mainnet or the testnet.
You can download it from https://zilpay.xyz/ .

LET’S CODE:

I am going to write a simple FabCar contract to demonstrate CRUD operations in Scilla. In other words, users will be able to create, read, update and delete the Car asset. Keep in mind that this smart contract is only meant for learning purpose and not meant for real world applications.

Let’s open up the IDE and start coding. 

  1. Go to FILES and create a new contract. Give your contract a name. I’ll call it FabCar. The contract files have .scilla extension. 
  2. The contract starts with the scilla version. 
scilla_version 0

3. We need to define our own library to define variables and constants that can be used in our contract, however, they are not subject to state manipulations.
Your library name will be same as your contract name. In our case it is FabCar.

library FabCar

4. Define some constants and functions that you might need to use in your contract.

let one_msg =
fun (msg: Message) =>
let nil_msg = Nil {Message} in
Cons {Message} msg nil_msg
let not_owner_code  = Uint32 1
let create_car_code = Uint32 2
let car_exists_code = Uint32 3
let code_success = Uint32 4
let query_failed_code = Uint32 5
let car_not_found_code = Uint32 6

In Scilla, the functions inside the contracts are known as transitions. And the transitions can transmit data either by invoking an event or by sending message.send is used to send messages and it takes a list of messages. In the above code, we defined a library function-one_msg as a list of one message as required by our smart contract. We will discuss more about the messages in later part of this article. 

In the second part of the above code, we are declaring the error codes that we will be using for error handling in our contract. As you can see, the library variables are declared the following way: let <variable name> = <variable type> <value> . 

5. There are no structs or class in Scilla. But we can use type to define our own ADT (Algebraic Data Type *not to be confused with Abstract Data Type*).

type Make = | Make of String 
type Model = | Model of String
type Color = | Color of String
type CarOwner = | CarOwner of ByStr20
type Car = | Car of Make Model Color CarOwner

In the first line above, I have defined a type Make which can hold a string value. Similarly, I have defined the types Model, Color and CarOwner. Finally, I have a Car type which is made up of Make, Model Color and CarOwner. 

You can also just define a Car with primitive data types instead of defining types for other parameters. It would look something like this:

type Car = | Car of String String String ByStr20

Kinda difficult to read, right? 

6. Now comes the interesting part. We are going to define our Contract. Yay! 

contract FabCar
(owner: ByStr20)

We use the contract keyword followed by the contract name. Then we add the immutable contract parameters inside (). These immutable parameters are defined during the deployment of the contract and cannot be updated afterwards. Here we have owner of type ByStr20 so that we can have certain transactions that only owner of the contract can make. 

Syntax for defining the contract is contract <ContractName> (v_name1: v_type1, v_name2: v_type2 ..) . 

7. MUTABLE STATES: They are the mutable variables in the contract i.e. their value can can be updated with the functions(transitions). Mutable variables are called fields and are defined using the keyword field .

field cars: Map String Car
= Emp String Car

Since we are just going to store the state of the car, we’ll have an array of cars mapped to their car number as id which in this case will be a string of characters. Syntax for defining the field is field vname_1 : vtype_1 = expr_1 and syntax of defining map (associative array) is Map key value. Here, we are creating a map of String to Car and Emp creates an empty map.

8. PROCEDURES and TRANSITIONS: Procedures are the functions that cannot be invoked via messages to the contract but can be called by another transition or procedure. Transitions can be invoked my sending message to the contract. Both Procedures and Transitions are used to change the state of the contract in the blockchain.

9. CREATE: Let’s create our first procedure createNewCar . 

procedure createNewCar(new_car : Car, car_number : String)
tempcars <- cars;
(*Check if car with that number already exists*)
carExists = builtin contains tempcars car_number;
match carExists with
| True =>
msg = {_tag: "";
_recipient: _sender;
_amount: Uint128 0;
code: car_exists_code
};
msgs = one_msg msg;
send msgs
| False =>
cars[car_number] := new_car;
msg = {_tag: "";
_recipient: _sender;
_amount: Uint128 0;
code: code_success};
msgs = one_msg msg;
send msgs
end
end

Our procedure contains two parameters: new_car with a type Car and car_number with a type String. In our first step, we will check if the car with the particular number exists in our map or not. If it does, it will throw out an error message with the error code. If the car does not already exist, a new car is added to the map with car_number as its key. Then it will send a code_success message.

match works in a similar way as select case statements in other programming languages but they are way powerful. A value passed is compared with other values and if it’s a match it executes the code inside that condition.

10. createCar Transition : We will now create our transition which will call createNewCar Procedure to create a new car and add it to the map. 

transition createCar(car_number: String, make: String, model: String, color: String, car_owner: ByStr20)
temp_make = Make make;
temp_model = Model model;
temp_color = Color color;
temp_owner = CarOwner car_owner;

new_car = Car temp_make temp_model temp_color temp_owner;
createNewCar new_car car_number
end

This is the transition that a user will call to create a new car. To create this transaction user will need to pass in several parameters. Then those parameters are type casted to the custom types we made. For example, we converted make of type String to make of type Make. It would have been way simpler if we did not use ADT for these small values, but we are doing it just for the sake of understanding the concept here. Also, before I forget-

Every statements excluding the last statement ends with a semicolon ; . And all procedures, transitions and match are ended with anend .

Now we can create a new_car of type Car by passing the elements we created above. Finally, a procedure createNewCar is called with the two parameters- new_car and car_number .

10. READ: Once we add any data to our blockchain, we should be able to read it. We will create a query transition called getCar that will give us the data of a car based on the car_number we pass. 

transition getCar(car_number: String)
tempCars <- cars;
getValue = builtin get tempCars car_number;
match getValue with
| Some v =>
e = {_eventname: "getCar"; msg: v};
event e
| None =>
msg = {_tag: "";
_recipient: _sender;
_amount: Uint128 0;
code: query_failed_code};
msgs = one_msg msg;
send msgs
end
end

Events( event) are similar to messages but they don’t invoke a transaction. It follows the following syntax: 

e = { _eventname : "e_name"; <entry>_2 ; <entry>_3 };
event e

11. UPDATE: UpdateCar will be almost similar to our CreateCar transition. Let’s make it a bit different and do all the operations inside the transition itself instead of calling a procedure. 

transition updateCar(car_number: String, make: String, model: String, color: String, car_owner: ByStr20)
tempcars <- cars;
exist = builtin contains tempcars car_number;
match exist with
| False =>
msg = {_tag: "";
_recipient: _sender;
_amount: Uint128 0;
code: car_not_found_code};
msgs = one_msg msg;
send msgs
| True =>
temp_make = Make make;
temp_model = Model model;
temp_color = Color color;
temp_owner = CarOwner car_owner;

new_car = Car temp_make temp_model temp_color temp_owner;

cars[car_number] := new_car;
msg = {_tag: ""; 
_recipient: _sender;
_amount: Uint128 0;
code: code_success};
msgs = one_msg msg;
send msgs
end
end

12. DELETE: Deleting is the simplest part of all. Of course, you can add some kind of authentication to allow only a valid person to create this transaction. 

transition removeCar(car_number: String)
delete cars[car_number]end

Here, car_number is passed as a parameter and the delete will delete a car with that car_number from the map. I’ll leave it up to you to check if the car exists in the map before performing an operation. 

13: CHECK AND DEPLOY: Once you are done typing your smart contract hit CHECK to see if there is any error in the code. Then you can SAVE and DEPLOY your contract. 

Make sure that you selected Simulated ENV on the top right side of your IDE window. Then click on Deploy. You should get a prompt asking for several initialization parameters like this: 

Just copy and paste your wallet address from the top of your IDE and hit Deploy Contract. If the deployment is successful, you should get something like this:

You should see list of deployed contracts on bottom left side of your IDE. You can click on it and a prompt should appear where you can invoke transitions in your contract.


I tried to make the tutorial as simple as possible. However, I have left out many important information to not overwhelm anyone who is trying to learn a new language. If you have any questions or suggestions just write it down in the comment below and I will try to answer them.

Cheers!

- Advertisement -
Bibek Poudel
Bibek is an original CDT member of RECAP blockchain. He focuses on the software development side.
- Advertisement -

Stay Connected

5,123FansLike
2FollowersFollow
35SubscribersSubscribe

Must Read

Bitcoin Moves 27% Downside After Touching Historical $42,000

Bitcoin price dipped to $30,000 zone today which accounts for more than 27% downfall from its all-time high $42,000. After Bitcoin crossed its previous...
- Advertisement -

Writing your first smart contract in Scilla (Zilliqa)

Scilla — a programming language for writing smart contracts in Zilliqa Blockchain is not an easy language to master. The official documentation is itself too technical...

Bitcoin कहिले किन्ने? कहिले बेच्ने? डेटा विश्लेषण र ट्रेडिगं जानकारी पढ्नुहोस्

Bitcoin को मूल्य दिन प्रतिदिन बढिरहेको छ; यस्तो बेला लगानीकर्ताहरुले ध्यान पुराउनुपर्छ । Bitcoin को मूल्य एकदमै अस्थिर छ, यसको मूल्य आज दोब्बर हुँदा...

Facebook र Alibaba भन्दा बहुमूल्य Bitcoin!

Bitcoin को मूल्य $४१,००० पुग्दा बिटक्वाइन अब फेसबुक र Tesla को बजार पूँजीकरण (market cap) भन्दा ठुलो बनेको छ। यसैले, यदि बिटकइनलाई एक संगठन...

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Related News

Bitcoin Moves 27% Downside After Touching Historical $42,000

Bitcoin price dipped to $30,000 zone today which accounts for more than 27% downfall from its all-time high $42,000. After Bitcoin crossed its previous...

Writing your first smart contract in Scilla (Zilliqa)

Scilla — a programming language for writing smart contracts in Zilliqa Blockchain is not an easy language to master. The official documentation is itself too technical...

Bitcoin कहिले किन्ने? कहिले बेच्ने? डेटा विश्लेषण र ट्रेडिगं जानकारी पढ्नुहोस्

Bitcoin को मूल्य दिन प्रतिदिन बढिरहेको छ; यस्तो बेला लगानीकर्ताहरुले ध्यान पुराउनुपर्छ । Bitcoin को मूल्य एकदमै अस्थिर छ, यसको मूल्य आज दोब्बर हुँदा...

Facebook र Alibaba भन्दा बहुमूल्य Bitcoin!

Bitcoin को मूल्य $४१,००० पुग्दा बिटक्वाइन अब फेसबुक र Tesla को बजार पूँजीकरण (market cap) भन्दा ठुलो बनेको छ। यसैले, यदि बिटकइनलाई एक संगठन...

Bitcoin को अन-चेन डाटा मूल्यको नयाँ उचाइ देखाउँदै !

Bitcoin को मूल्य Bull हरूले पूर्ण नियन्त्रणमा लिइरहेका छन्; उनीहरूले राता-रात यसको अघिल्लो सबै समयको उचाइ उछिन्दै नयाँ मूल्य स्थापित गरेकाछन्। $१४,००० बाट दौडिएको...
- Advertisement -