Skip to content
On this page

Utils โ€‹

This section includes a few util functions that can help you to ease the development.

Methods โ€‹

Convert mutez to nat โ€‹

Convert TMutez to TNat

python
sp.utils.mutez_to_nat(...)

Convert nat to mutez โ€‹

Convert TNat to TMutez

python
sp.utils.nat_to_mutez(n)    # sp.nat(1) => sp.mutez(1)
# or
sp.utils.nat_to_tez(n)      # sp.nat(1) => sp.mutez(1000000)

Convert string to bytes โ€‹

INFO

Compilation only

Encode a constant string as sp.TBytes.

python
sp.utils.bytes_of_string("A String") # => 0x4120537472696e67

Convert URL to metadata โ€‹

INFO

Compilation only

A Simple alias for sp.big_map({""ย : sp.utils.bytes_of_string(url)}).

python
sp.utils.metadata_of_url("ipfs://...")

Compare underlying address โ€‹

It returns a boolean that informs if an address A%foo has the same underlying address as A.

python
sp.verify(
    sp.utils.same_underlying_address(
        sp.address("KT1Tezooo1zzSmartPyzzSTATiCzzzyfC8eF%foo"),
        sp.address("KT1Tezooo1zzSmartPyzzSTATiCzzzyfC8eF")
    ),
    message = "Not the same underlying address"
)

Wrap entrypoint โ€‹

sp.utils.wrap_entry_point(name, entry_point)

A wrapper to prepare the a python function to be used as an update for entrypoint name (which must be a constant string).

python
def f(self):
    sp.verify(self.data.valid, "NOT VALID")

sp.utils.wrap_entry_point("ep", f)

Extract seconds from timestamp โ€‹

Extract seconds of type sp.TNat from a value of type sp.TTimestamp.

python
sp.utils.seconds_of_timestamp(sp.timestamp(100)) # 100

vector, matrix, cube โ€‹

There is no array in SmartPy because they are missing in Michelson, we usually use maps instead.

There are three helper functions:

sp.utils.vector(..), sp.utils.matrix(..) and sp.utils.cube(..) that take respectively a list, a list of lists and a list of lists of lists and return maps.

Callback entrypoint โ€‹

The decorator @sp.utils.view is used to define a callback entrypoint. A sugared version of @sp.entrypoint that receives a callback argument, then processes some logic to obtain the requested data and calls back the requester with a response.

Example โ€‹

python
@sp.utils.view(sp.TNat)
def getBalance(self, params):
    sp.result(self.data.balances[params].balance

This code above is a simpler version of the equivalent:

python
@sp.entrypoint
def getBalance(self, params):
    sp.set_type(sp.snd(params), sp.TContract(sp.TNat))
    response = self.data.balances[sp.fst(params)].balance
    sp.transfer(response, sp.tez(0), sp.snd(params))