Chapter 2: Intermediate

Lesson 6: Utility Functions

In the previous lesson, we saw the declaration of not_owner_code, and the zero codes in the library of our contract.

These are essentially utility functions that return the value that we defined. In this case 0 and 1 respectively.

We can similarly declare utility functions in the library to abstract some repeated logic from our transactions. This will make our code code cleaner and easier to follow.

Here we create an add function which accepts two arguments and returns the sum.

We can then use it in our transitions as required.

Note that these functions can only perform pure operations. This means that the function returns identical results for the same input. Also, they do not have side effects, i.e., they do not mutate any value, and instead only operate upon the arguments and return the result.

In the next lesson, we will see a great way in which we can utilise this feature using a common function called one_msg.

1

2

let zero = Uint128 0
let not_owner_code = Uint32 1

We have a task for you!

  • In the library section of the code, define a library function one_msg to construct a list consisting of one message.
  • Your Workspace

    Show Solution

    Solution

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    scilla_version 0
    import BoolUtils
    library SocialMediaPayment
    (* Start typing from the line below. Create the one_msg utility function as instructed. *)
    let one_msg =
    fun (msg: Message) =>
    let nil_msg = Nil {Message} in
    Cons {Message} msg nil_msg
    let zero = Uint128 0
    let not_owner_code = Uint32 1
    contract SocialMediaPayment (owner: ByStr20)
    transition deposit()
    sender_is_owner = builtin eq _sender owner;
    match sender_is_owner with
    | False =>
    | True =>
    end
    end
    scilla_version 0
    import BoolUtils
    
    library SocialMediaPayment
    (* Start typing from the line below. Create the one_msg utility function as instructed. *)
    
    
    let zero = Uint128 0
    let not_owner_code = Uint32 1
    
    contract SocialMediaPayment (owner: ByStr20)
    
    transition deposit()
      sender_is_owner = builtin eq _sender owner;
      match sender_is_owner with
      | False =>
    
      | True =>
    
      end
    end
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21