Advanced

Overview

Ride is a straightforward, developer-friendly functional programming language for smart contracts and decentralized applications (dApps) on the DecentralChain blockchain. Ride is a strong statically-typed, lazy, functional, expression-based compiled programming language. It is designed for building developer-friendly decentralized applications (dApps).

Scripts

DecentralChain smart contracts are scripts written in Ride. Scripts can be assigned to accounts or tokens (assets). An account with a script assigned to it becomes a dApp or smart account. An asset with a script assigned to it becomes a smart asset.

Script functionality depends on its type:

  • dApp script enables you to define сallable functions that can perform various actions on the blockchain and a verifier function that allows or denies transactions and orders that are sent on behalf of the dApp account.

  • Account script allows or denies transactions and orders that are sent on behalf of the account.

  • Asset script allows or denies transactions involving the asset.

Not Turing Complete

Ride is NOT Turing Complete and its execution engine (virtual machine) doesn’t have any concept of loops. Also, there are a number of limitations by design, helping to ensure execution is secure and straightforward. Because of the lack of loops it’s not always possible to implement the necessary logic within a single script call. However, Ride recognizes that iterations are necessary and has implemented them as FOLD macros. It is still possible to perform Turing-complete computations if the algorithm is split into several functions (or even several smart contracts) and invoked sequentially using several transactions.

Blockchain Operation

Ride is created specifically for execution within a blockchain environment and optimized for this purpose. Since the blockchain is a distributed ledger, located on many computers all around the world, there is no way to access the filesystem or display anything in the console. Instead, Ride functions can read data from the blockchain:

  • Entries in account data storages (both dApp or smart account and any other account).

  • Balances of accounts.

  • Parameters of tokens.

  • The current blockchain height.

  • Headers of blocks.

  • Transfer transactions (by transaction ID).

Predictable Computational Cost

The complexity is defined for each Ride function and operator. The complexities of the used functions and operators make up the script complexity. There are no loops in Ride, so the script complexity can be calculated in advance. The maximum script complexity is limited. Due to these limitations, DecentralChain has low and predictable fees for script execution.

Try it yourself

You can try out Ride in REPL both online at https://waves-ide.com/.

Getting Started/Syntax Basics

Directives

Every Ride script should start with directives for the compiler. The directives define the script format and available functions, structures and variables. Directive format is as follows:

{-# DIRECTIVE_NAME VALUE #-}

Directive List

There are three types of directives, with different possible values.

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ACCOUNT #-}

{-# STDLIB_VERSION 5 #-} sets the version of the standard library. The latest version currently in production is 5.

{-# CONTENT_TYPE DAPP #-} sets the type of the file you’re working on. There are different content types, DAPP and EXPRESSION. The DAPP type allows you to define functions and finish execution with certain actions which result in account balances, asset properties, and entries in the dApp account data storage. The EXPRESSION type should always return a boolean value, since it’s used as a predicate for transaction validation.

{-# SCRIPT_TYPE ACCOUNT #-} sets the entity type we want to add to the script to change its default behavior. Ride scripts can be attached to either an ACCOUNT or ASSET.

Examples

For a dApp script:

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ACCOUNT #-}

For an account script:

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE EXPRESSION #-}
{-# SCRIPT_TYPE ACCOUNT #-}

For an asset script:

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE EXPRESSION #-}
{-# SCRIPT_TYPE ASSET #-}

Not all combinations of directives are correct. The example below will not work, because DAPP content type is allowed only for accounts:

# Wrong example, will not work

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ASSET #-}

Definitions

A definition is a linking of the name to the value or to the function body.

Examples

Linking the name to the value.

let x = 5 + 5

Linking the name to the function body.

func f(x: Int) = {
 x + 5
}

Expressions

An expression is a combination of one or more constants, variables, operators and function calls.

Expression Result

An expression result is a value, which is obtained by the fold of the syntactic tree of the expression. Ride interprets the expression and calculates its result.

Expression Type

An expression type is a data type of the expression result.

Examples

The expression that consists of a single constant.

7

The expression that consists of a single variable.

7 + x * size("apple")

The expression that consists of the constant \(7\), operators + and *, variable x and the size function call.

7 + x * size("apple")

Constants

A constant is a value that cannot be changed by the program during its execution.

Examples

Below \(7\) and «apple» are constants.

7 + x + size("apple")

Data Types

Data Types

Data type name

Ride keyword

Big Integer

BigInt

Boolean

Boolean

Byte array

ByteVector

Integer

Int

String

String

Empty value

Unit

List

List

Tuple

Union

Structure

Arbitrary type

Any

For each value, depending on the data type, the weight is determined. The weight is used in limitations on creating and comparing values. For more information see the data weight.

Any

Any is an arbitrary data type. It is a common supertype of all types: an Any type value can be a string, a number, unit, a structure, a list, a tuple, etc.

func findString(a: Any) = {
 match a {
   case a: String => a
   case a: List[Any] =>
     match a[0] {
       case b: String => b
       case _ => throw("Data is not a string")
     }
   case _ => throw("Data is not a string")
 }
}

BigInt

BigInt is a special numeric data type designed to handle values outside the range of Int and to perform high accuracy calculations. BigInt variable has a size of \(64\) bytes (\(512\) bits) and contains an integer between \(–2511\) to \(2511–1\), inclusive. The weight of the value is \(64\). A BigInt variable can only be used inside a script. A callable function does not accept arguments of BigInt type and does not return a value of BigInt type. You can pass a big integer value as a string, then use the parseBigInt or parseBigIntValue functions.

BigInt Operations

The following operators support BigInt values:

  • Arithmetic operators: +, -, *, /, %, unary minus.

  • Comparison operators: <, >, <=, and >=.

  • Equality operators: == and !=.

BigInt Functions

The following functions operate BinInt values:

Boolean

Boolean is a data type that can have only the values true or false.

ByteVector

ByteVector is a data type for byte array.

To assign a value to a ByteVector variable, you can use a string in Base16, Base58, or Base64 with the appropriate prefix:

let a = base16'52696465'
let b = base58'8t38fWQhrYJsqxXtPpiRCEk1g5RJdq9bG5Rkr2N7mDFC'
let c = base64'UmlkZQ=='

This method, unlike the fromBase16String, fromBase58String, and fromBase64String functions, does not increase the complexity of the script, since decoding is performed by the compiler. To convert integer, boolean, boolean and string values to a byte array use toBytes function:

let a = 42.toBytes()
let b = true.toBytes()
let c = "Ride".toBytes()

For more byte array functions, see the Built-in Functions.

ByteVector Limitations

The maximum size of a ByteVector variable is \(32,767\) bytes. Exception: the bodyBytes field of transaction structure. You can pass this value as an argument to the rsaVerify и sigVerify verification functions (but cannot concatenate with other byte arrays in case the limit is exceeded).

Int

Int is an integer data type. The integer variable has the size of 8 bytes and stores an integer from \(-9,223,372,036,854,775,808\) to \(9,223,372,036,854,775,807\) inclusive.

let age = 42
let length = size("hello")

String

Strings are denoted only using double quotes. They are immutable, and for that reason, the substring function is very efficient: no copying is performed and no extra allocations are required. Strings are UTF-8 encoded.

let name = "Bob"   # use "double" quotes only
String Limitations

The maximum size of a String variable is \(32,767\) (\(1\) character can take up to \(4\) bytes).

String Functions

The built-in functions for working with strings are presented in the following articles:

  • String Functions

  • Converting Functions

Unit

Unit is an empty value data type. The empty value data type is similar to unit in Scala or to null in C#. Usually, built-in functions return unit value of type unit instead of null.

"String".indexOf("substring") == unit # true

Nothing

Nothing is the “bottom type” of Ride’s type system. No value can be of type nothing, but an expression of type nothing can be used everywhere. In functional languages, this is essential for support for throwing an exception:

2 + throw() # the expression compiles because
   # there's a defined function +(Int, Int).
     # The type of the second operand is Nothing,
     # which complies to any required type

List

The list data type may contain elements of various types, including nested lists. The maximum number of list items is \(1000\). The nesting depth is not limited. A list doesn’t have any fields, but there are functions and operators in the Standard library that make it easier to work with fields.

  • To prepend an element to an existing list, use the cons function or :: operator

  • To append an element, use the :+ operator

  • To concatenate \(2\) lists, use the ++ operator

let list = [16, 10, 1997, "birthday"]
let last = list[(list.size() - 1)] # "birthday", postfix call of size() function

let initList = [16, 10]                   # init value
let newList = cons(1997, initList)        # [1997, 16, 10]
let newList2 = 1997 :: initList           # [1997, 16, 10]
let newList2 = initList :+ 1              # [16, 10, 1]
let newList2 = [4, 8, 15, 16] ++ [23, 42]     # [4 8 15 16 23 42]
List Operations

Lists support concatenation as well as adding items to the beginning and the end.

List Operations

Operation

Symbol

Complexity

Concatenation

++

\(4\)

Adding the element to the end of the list (the list is on the left, the element is on the right)

:+

\(1\)

Adding the element to the beginning of the list (the element is on the left, the list is on the right)

\(2\)

Operation to be used:

nil :+ 1 :+ 2 :+ 3

Result: [1, 2, 3]

Operation to be used:

1 :: 2 :: 3 :: nil

Result: [1, 2, 3]

Operation to be used:

let intList  = [1, 2]             # List[Int]
let strList  = ["3", "4"]         # List[String]
let joined   = intList ++ strList # List[Int|String]
joined

Result: [1, 2, «3», «4»]

Operation to be used:

let appended = joined :+ true     # List[Boolean|Int|String]
appended

Result: [1, 2, «3», «4», true]

Operation to be used:

let nested = intList :: joined  # List[Int|List[Int]|String]
nested

Result: [[1, 2], 1, 2, «3», «4»]

List Functions

The built-in list functions are presented in the list functions article. Operations on a list can be implemented via the FOLD macro. The size of the list must be known in advance.

List as Function Argument

A list, including nested one, can be a function argument:

func foo(arg: List[String|Unit]) = {
...
}

foo(["Ride","DecentralCoins",unit])
func bar(arg: List[List[Int]]) = {
...
}

bar([[1],[],[5,7]])

A callable function can take a list as an argument, but nested lists are not allowed. Here’s an example:

@Callable(i)
func join(strings: List[String|Int]) = {
 let a = match strings[0] {
   case n:Int => toString(n)
   case s:String => s
 }
 let b = match strings[1] {
   case n:Int => toString(n)
   case s:String => s
 }
 let c = match strings[2] {
   case n:Int => toString(n)
   case t:String => t
 }
 [
   StringEntry(toBase58String(i.caller.bytes), a + "_" + b + "_" + c)
 ]
}

Invoke Script transaction example:

{
 "type": 16,
 ...
 "call": {
   "function": "join",
   "args": [
    {
     "type": "list",
     "value": [
     {
       "type": "string",
       "value": "Ride"
     },
     {
       "type": "integer",
       "value": 5
     },
     {
       "type": "string",
       "value": "DecentralCoins"
     }
     ]
    }
   ]
 },
 ...
}

Tuple

A tuple is an ordered collection of elements. Elements can be of any type. The tuple can contain from \(2\) to \(22\) elements.

Let’s see some tuples:

let x=("Hello DecentralChain",42,true)
x._2

Result: \(42\)

And this one also:

let (a,b,c)=x
c

Result: true

Union

Union is a data type that unites \(2\) or more data types. Union can combine primitive types, lists, tuples, structures. This type is a very convenient way to work with abstractions. Union(String | Unit) shows that the value is an intersection of these types.

To get a value of a particular type from a Union, you can use:

let valueFromBlockchain = getString("3PHHD7dsVqBFnZfUuDPLwbayJiQudQJ9Ngf", "someKey") # Union(String | Unit)

The simplest example of Union types is given below (please bear in mind that defining custom user types in dApp code will be supported in future versions):

type Human : { firstName: String, lastName: String, age: Int}
type Cat : {name: String, age: Int }

Let’s see anoter example where each element of a List[Int|String] is a string or an integer.

let aList   = [1, 2, "DecentralCoins"]               # List[Int|String]
let bList   = [true,false]                  # List[Boolean]
let joined  = aList ++ bList                # List[Boolean|Int|String]

Pattern Matching

Let’s revisit the example above:

type Human : { firstName: String, lastName: String, age: Int}
type Cat : {name: String, age: Int }

Union(Human | Cat) is an object with one field, age, but we can use pattern matching like this:
Human | Cat => { age: Int }

This is designed to check a value against value type:

let t = ...               # Cat | Human
t.age                     # OK
t.name                    # Compiler error
let name = match t {      # OK
 case h: Human => h.firstName
 case c: Cat   => c.name
}

Type matching

This is a mechanism for knowing the type of a transaction:

let amount = match tx {              # tx is a current outgoing transaction
 case t: TransferTransaction => t.amount
 case m: MassTransferTransaction => m.totalAmount
 case _ => 0
}

There are different types of transactions, if a transaction is TransferTransaction or MassTransferTransaction we use the corresponding field, while in all other cases, we will get \(0\).

Variables

These are declared and initialized with the let keyword.

let a = "Bob"
let b = 1

In Ride, you can only declare a variable along with a value assignment. The = sign must be followed by an expression. The value of the variable is the expression result. Ride variables are immutable: the value of a variable cannot be changed after it is defined. Ride is strongly typed and the variable’s type is inferred from the value. Ride allows you to define variables globally, inside any function, or even inside a variable definition.

func lazyIsGood() = {
 let a = "Bob"
 let b = {
    let x = 1
    "Alice"
   }
 true
}

Lazy Variables

Let keyword defines a variable with lazy evaluation: the value of a variable is evaluated the first time it is used. Let’s see an example:

let a = 42                 # Integer variable definition
let b = "Ride!"  # String variable definition

Ride allows you to define variables globally, inside any function, or even inside a variable definition.

func lazyIsGood() = {
 let c = {
    let d = 1
    true
   }
 c
}

The function above returns true, but variable d won’t be initialized because unused lazy variables are not evaluated. Since a function is a definition and not an expression, you can assign a function value to a variable but not the function itself.

let result = lazyIsGood()  # result is true

Strict Variables

The strict keyword defines a variable with strict (eager) evaluation. Unlike lazy variables defined with let, a strict variable is evaluated immediately when script execution reaches it, that is, before the next expression. Strict variables can only be used inside another definition, for example, inside the body of a function. A strict variable will not be evaluated if it is defined inside another definition that is not used: for example, inside a function that has not been called. Strict variables are suitable for dApp-to-dApp invocation as they ensure executing callable functions and applying their actions in the right order. Let’s see an example:

func foo() = {
  ...
  strict balanceBefore = wavesBalance(this).regular
  strict z = invoke(dapp2,"bar",args,[AttachedPayment(unit,100000000)])
  strict balanceAfter = wavesBalance(this).regular

  if(balanceAfter < balanceBefore) then ... else...
}

In this example, balanceBefore and balanceAfter may differ because payments to dApp2 and actions performed by the bar callable function can affect the balance.

Built-in Variables

The Standard library defines built-in variables that can be used in scripts.

Built-in Variables

#

Name

Description

\(1\)

Buy

Order type.

\(2\)

1) CEILING. 2) DOWN. 3) FLOOR. 4) HALFEVEN. 5) HALFUP.

Rounding methods used in the math functions fraction, log, pow.

\(3\)

height

Blockchain height at the script execution time.

\(4\)

lastBlock

Information about the last block of the blockchain at the script execution time.

\(5\)

nil

Variable that contains an empty list. The variable is used for creating lists. For example, instead of: let a = [5,6].

\(6\)

1) NOALG. 2) MD5. 3) SHA1. 4) SHA224. 5) SHA256. 6) SHA384. 7) SHA512. 8) SHA3224. 9) SHA3256. 10) SHA3384. 11) SHA3512.

Variables that are passed as the first parameter to the rsaVerify function.

\(7\)

Sell

Order type.

\(8\)

this

1) For a dApp script or an account script: the address structure. 2) For an asset script: the asset structure.

\(9\)

tx

Transaction or order.

\(10\)

unit

Variable that contains an object of Unit type.

Operators

Arithmetic Operators

Arithmetic Operators

Operator

Description

Addition

Subtraction

Multiplication

/

Division

%

Remainder

The / operator uses the FLOOR rounding method.

Comparison Operators

Comparison Operators

Operator

Description

<

Less than

>

Greater than

<=

Less than or equal

>=

Greater than or equal

Equality Operators

Equality Operators

Operator

Description

==

Equality

!=

Inequality

Local Definition Operators

Local Definition Operators

Operator

Description

func

Function local definition.

let

Lazy definition of a variable.

strict

Strict definition of a variable.

Conditional Operators

Conditional Operators

Operator

Description

if-then-else

Conditional statement.

match-case

Spot a type from union.

List Operators

List Operators

Operator

Description

++

Concatenation.

:+

Adding the element to the end of the list.

::

Adding the element to the beginning of the list.

See examples of the list article.

Unary Operators

Unary Operators

Operator

Description

Unary minus

!

Logical negation

Logical Operators

Logical Operators

Operator

Description

&&

Logical AND

||

Logical OR

Match-Case

match-case operator is used to spot a certain type from union or any type . The spotting is required to perform certain operations. Let’s review the following example.

match tx {
 case _: TransferTransaction|ExchangeTransaction => t.amount > 100 && sigVerify(tx.bodyBytes, tx.proofs[0], tx.senderPublicKey)
 case _ => false
}

In this example, if:

  • The type of transaction is transfer transaction or exchange transaction.

  • Amount field value is greater than \(100\).

Then it will be sent to the blockchain. If the transaction has a different type and/or amount field value is lesser than 100, then it will be rejected.

Possible Issue

Let’s review the following code.

{-# STDLIB_VERSION 2 #-}
{-# CONTENT_TYPE EXPRESSION #-}
{-# SCRIPT_TYPE ACCOUNT #-}

match (tx) {
 case t: TransferTransaction|ExchangeTransaction|MassTransferTransaction|Order => false   # Prohibit any transfer of funds from the account

 case _ => sigVerify(...)
}

In this example we are using version 2 of Ride standard library, STDLIB_VERSION 2, and we want to reject any funds transfer from our account. In order to do this, we are returning false for:

  • TransferTransaction

  • ExchangeTransaction

  • MassTransferTransaction

Transactions of other types (for example transactions that do not transfer funds) are being sent to the blockchain. But Ride is developing rapidly, and new transaction types are emerging. Features of invoke script transaction which is not supported by Ride v2 include attaching payments to transfer tokens to the account of the called dApp. This means that the InvokeScriptTransaction won’t be caught by the first case. It will pass to the default branch case _ => and sent to blockchain. As a result, the funds could be transferred from the account instead of the transfers being prohibited like we wanted.

Solution

To prevent the reviewed issue, it is recommended to return false inside of the default case. Then for the entities, not listed in previous branches, sending information to the blockchain will be prohibited. Below is the sample of script which rejects any funds transfer from account, but allows all other transactions existing in Ride v2. Usage of case _ => false rejects any other transactions, not supported by the Ride v2 (i.e. invoke script transaction).

{-# STDLIB_VERSION 2 #-}
{-# CONTENT_TYPE EXPRESSION #-}
{-# SCRIPT_TYPE ACCOUNT #-}

match tx {
 case t: TransferTransaction|ExchangeTransaction|MassTransferTransaction|Order => false   # Prohibit any transfer of funds from the account
 case _: Transaction => sigVerify(tx.bodyBytes, tx.proofs[0], tx.senderPublicKey) # Allow all other known transaction types as long as the signature is correct
 case _ => false  # Reject all other (new, unknown) entity types, since they are not in the version of the language used at the moment
}

Functions

Functions in Ride are declared with func, function must be declared above the place of its usage. When declaring a function to the right of the «=» sign must be an expression. The value of the function is the expression result. Definition of the function with no parameters that returns an integer:

func main() = {
 3
}

Definition of a function with two parameters:

func main(amount: Int, name: String) = {
  throw()
}

Functions do have return types, this is inferred automatically by the compiler, so you don’t have to declare them. There is no return statement in the language because Ride is expression-based (everything is an expression), and the last statement is a result of the function.

func greet(name: String) = {
 "Hello, " + name
}

func add(a: Int, b: Int) = {
 func m(a:Int) = a
 m(a) + b
}

The type (Int, String, etc) comes after the argument’s name. As in many other languages, functions should not be overloaded. It helps to keep the code simple, readable and maintainable. Functions can be invoked in prefix and postfix order:

let list = [1, 2, 3]
let a1 = list.size()
let a2 = size(list)

let b1 = getInteger(this, "key")
let b2 = this.getInteger("key")

Annotations

Functions can be without annotations, but they can also be with @Callable or @Verifier annotations. Annotated functions are used only in scripts of type DAPP. Here’s an example of @Callable:

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ACCOUNT #-}

func getPayment(i: Invocation) = {
 if (size(i.payments) == 0)
   then throw("Payment must be attached")
   else {
     let pmt = i.payments[0]
     if (isDefined(pmt.assetId))
       then throw("This function accepts DecentralCoin tokens only")
       else pmt.amount
   }
}

@Callable(i)
func pay() = {
 let amount = getPayment(i)
 (
   [
     IntegerEntry(toBase58String(i.caller.bytes), amount)
   ],
   unit
 )
}

Annotations can bind some values to the function. In the example above, variable i was bound to the function pay and stored some fields of the invocation (the caller’s public key, address, payments attached to the invocation, fee, transaction ID etc.). Functions without annotations are not available from the outside. You can call them only inside other functions.

Here’s an example of @Verifier:

@Verifier(tx)
func verifier() = {
 match tx {
   case m: TransferTransaction => tx.amount <= 100 # can send up to 100 tokens
   case _ => false
 }
}

A function with the @Verifier annotation sets the rules for outgoing transactions of a decentralized application (dApp). Verifier functions cannot be called from the outside, but they are executed every time an attempt is made to send a transaction from a dApp. Verifier functions should always return a Boolean value as a result, depending on whether a transaction will be recorded to the blockchain or not.

Expression scripts (with directive {-# CONTENT_TYPE EXPRESSION #-} along with functions annotated by @Verifier should always return a boolean value. Depending on that value the transaction will be accepted (in case of true) or rejected (in case of false) by the blockchain.

@Verifier(tx)
func verifier() = {
 sigVerify(tx.bodyBytes, tx.proofs[0], tx.senderPublicKey)
}

The Verifier function binds variable tx, which is an object with all fields of the current outgoing transaction. A maximum of one @Verifier() function can be defined in each dApp script.

Callable Functions

The functions with the @Callable annotation become callable functions, since they can be called (or invoked) from other accounts: by an Invoke Script transaction or by a dApp. A callable function can perform actions: write data to the dApp data storage, transfer tokens from the dApp to other accounts, issue/release/burn tokens, and others. The result of a callable function is a tuple of two elements: a list of structures describing script actions and a value passed to the parent function in case of the dApp-to-dApp invocation.

@Callable(i)
func giveAway(age: Int) = {
 (
   [
     ScriptTransfer(i.caller, age, unit),
     IntegerEntry(toBase58String(i.caller.bytes), age)
   ],
   unit
 )
}

Every caller of giveAway function will receive as many Decentralites as their age. The ScriptTransfer structure sets the parameters of the token transfer. dApp also will store information about the fact of the transfer in its data storage. The IntegerEntry structure sets the parameters of the entry: key and value.

Built-in Functions

A built-in function is a function of the standard library .

Account Data Storage Functions

Learn more about account data storage.

Account Data Storage Functions

Name

Description

Complexity

getBinary(Address|Alias, String): ByteVector|Unit

Gets an array of bytes by key

\(10\)

getBinary(String): ByteVector|Unit

Gets an array of bytes by key from dApp’s own data storage

\(10\)

getBinaryValue(Address|Alias, String): ByteVector

Gets an array of bytes by key. Fails if there is no data

\(10\)

getBinaryValue(String): ByteVector

Gets an array of bytes by key from dApp’s own data storage. Fails if there is no data

\(10\)

getBoolean(Address|Alias, String): Boolean|Unit

Gets a boolean value by key

\(10\)

getBoolean(String): Boolean|Unit

Gets a boolean value by key from dApp’s own data storage

\(10\)

getBooleanValue(Address|Alias, String): Boolean

Gets a boolean value by key. Fails if there is no data

\(10\)

getBooleanValue(String): Boolean

Gets a boolean value by key from dApp’s own data storage. Fails if there is no data

\(10\)

getInteger(Address|Alias, String): Int|Unit

Gets an integer by key

\(10\)

getInteger(String): Int|Unit

Gets an integer by key from dApp’s own data storage

\(10\)

getIntegerValue(Address|Alias, String): Int

Gets an integer by key. Fails if there is no data

\(10\)

getIntegerValue(String): Int

Gets an integer by key from dApp’s own data storage. Fails if there is no data

\(10\)

getString(Address|Alias, String): String|Unit

Gets a string by key

\(10\)

getString(String): String|Unit

Gets a string by key from dApp’s own data storage

\(10\)

getStringValue(Address|Alias, String): String

Gets a string by key. Fails if there is no data

\(10\)

getStringValue(String): String

Gets a string by key from dApp’s own data storage. Fails if there is no data

\(10\)

isDataStorageUntouched(Address|Alias): Boolean

Checks if the data storage of a given account never contained any entries

\(10\)

getBinary(Address|Alias, String): ByteVector|Unit

Gets an array of bytes by key.

getBinary(addressOrAlias: Address|Alias, key: String): ByteVector|Unit

Parameters

Parameters

Parameter

Description

addressOrAlias: Address | Alias

Address or alias of the account.

key: String

Entry key.

getBinary(String): ByteVector|Unit

Gets an array of bytes by key from the dApp’s own data storage.

getBinary(key: String): ByteVector|Unit

Parameters

Parameters

Parameter

Description

key: String

Entry key.

getBinaryValue(Address|Alias, String): ByteVector

Gets an array of bytes by key. Fails if there is no data.

getBinaryValue(addressOrAlias: Address|Alias, key: String): ByteVector

Parameters

Parameters

Parameter

Description

addressOrAlias: Address | Alias

Address or alias of the account.

key: String

Entry key.

getBinaryValue(String): ByteVector

Gets an array of bytes by key from the dApp’s own data storage.

getBinaryValue(key: String): ByteVector

Parameters

Parameters

Parameter

Description

key: String

Entry key.

getBoolean(Address|Alias, String): Boolean|Unit

Gets a boolean value by key.

getBoolean(addressOrAlias: Address|Alias, key: String): Boolean|Unit

Parameters

Parameters

Parameter

Description

addressOrAlias: Address | Alias

Address or alias of the account.

key: String

Entry key.

getBoolean(String): Boolean|Unit

Gets a boolean value by key by key from the dApp’s own data storage.

getBoolean(key: String): Boolean|Unit

Parameters

Parameters

Parameter

Description

key: String

Entry key.

getBooleanValue(Address|Alias, String): Boolean

Gets a boolean value by key. Fails if there is no data.

getBooleanValue(addressOrAlias: Address|Alias, key: String): Boolean

Parameters

Parameters

Parameter

Description

addressOrAlias: Address | Alias

Address or alias of the account.

key: String

Entry key.

getBooleanValue(String): Boolean

Gets a boolean value by key from the dApp’s own data storage.

getBooleanValue(key: String): Boolean

Parameters

Parameters

Parameter

Description

key: String

Entry key.

getInteger(Address|Alias, String): Int|Unit

Gets an integer by key.

getInteger(addressOrAlias: Address|Alias, key: String): Int|Unit

Parameters

Parameters

Parameter

Description

addressOrAlias: Address | Alias

Address or alias of the account.

key: String

Entry key.

getInteger(String): Int|Unit

Gets an integer by key from the dApp’s own data storage.

getInteger(key: String): Int|Unit

Parameters

Parameters

Parameter

Description

key: String

Entry key.

getIntegerValue(Address|Alias, String): Int

Gets an integer by key. Fails if there is no data.

getIntegerValue(addressOrAlias: Address|Alias, key: String): Int

Parameters

Parameters

Parameter

Description

addressOrAlias: Address | Alias

Address or alias of the account.

key: String

Entry key.

getIntegerValue(String): Int

Gets an integer by key from the dApp’s own data storage.

getIntegerValue(key: String): Int

Parameters

Parameters

Parameter

Description

key: String

Entry key.

getString(Address|Alias, String): String|Unit

Gets a string by key.

getString(addressOrAlias: Address|Alias, key: String): String|Unit

Parameters

Parameters

Parameter

Description

addressOrAlias: Address | Alias

Address or alias of the account.

key: String

Entry key.

getString(String): String|Unit

Gets a string by key from the dApp’s own data storage.

getString(key: String): String|Unit

Parameters

Parameters

Parameter

Description

key: String

Entry key.

getStringValue(Address|Alias, String): String

Gets a string by key. Fails if there is no data.

getStringValue(addressOrAlias: Address|Alias, key: String): String

Parameters

Parameters

Parameter

Description

addressOrAlias: Address | Alias

Address or alias of the account.

key: String

Entry key.

getStringValue(String): String

Gets a string by key from the dApp’s own data storage.

getString(key: String): String

Parameters

Parameters

Parameter

Description

key: String

Entry key.

isDataStorageUntouched(Address|Alias): Boolean

Checks if the data storage of a given account never contained any entries. Returns false if there was at least one entry in the account data storage even if the entry was deleted.

isDataStorageUntouched(addressOrAlias: Address|Alias): Boolean

Parameters

Parameters

Parameter

Description

addressOrAlias: Address | Alias

Address or alias of the account.

Example

let addr = Address(base58'3N4iKL6ikwxiL7yNvWQmw7rg3wGna8uL6LU')
isDataStorageUntouched(addr) # Returns false
Blockchain Functions
Blockchain Functions

Name

Description

Complexity

addressFromRecipient(Address|Alias): Address

Gets the corresponding address of the alias

\(5\)

assetBalance(Address|Alias, ByteVector): Int

Gets account balance by token ID

\(10\)

assetInfo(ByteVector): Asset|Unit

Gets the information about a token

\(15\)

blockInfoByHeight(Int): BlockInfo|Unit

Gets the information about a block by the block height

\(5\)

calculateAssetId(Issue): ByteVector

Calculates ID of the token formed by the issue structure when executing the callable function

\(10\)

calculateLeaseId(Lease): ByteVector

Calculates ID of the lease formed by the lease structure when executing the callable function

\(1\)

scriptHash(Address|Alias): ByteVector|Unit

Returns BLAKE2b-256 hash of the script assigned to a given account

\(200\)

transactionHeightById(ByteVector): Int|Unit

Gets the block height of a transaction

\(20\)

transferTransactionById(ByteVector): TransferTransaction|Unit

Gets the data of a transfer transaction

\(60\)

wavesBalance(Address|Alias): BalanceDetails

Gets account balance in DecentralCoins

\(10\)

addressFromRecipient(Address|Alias): Address

Gets the corresponding address of the alias.

addressFromRecipient(AddressOrAlias: Address|Alias): Address

For a description of the return value, see the address article.

Parameters

Parameters

Parameter

Description

addressOrAlias: Address | Alias

Address or alias of the account.

Address or alias, usually tx.recipient

Example

let address = Address(base58'3NADPfTVhGvVvvRZuqQjhSU4trVqYHwnqjF')
addressFromRecipient(address)
assetBalance(Address|Alias, ByteVector): Int

Gets account balance by token ID.

assetBalance(addressOrAlias: Address|Alias, assetId: ByteVector): Int

Parameters

Parameters

Parameter

Description

addressOrAlias: Address | Alias

Address or alias of the account.

assetId: ByteVector

Token ID

assetInfo(ByteVector): Asset|Unit

Gets the information about a token (asset).

assetInfo(id: ByteVector): Asset|Unit

For a description of the return value, see the BlockInfo article.

Parameters

Parameters

Parameter

Description

id: ByteVector

Token ID

Example

let bitcoinId = base58'8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS'
let x = match assetInfo(bitcoinId) {
 case asset:Asset =>
   asset.decimals # 8
 case _ => throw("Can't find asset")
}
blockInfoByHeight(Int): BlockInfo|Unit

Gets the information about a block by the block height.

blockInfoByHeight(height: Int): BlockInfo|Unit

For a description of the return value, see the BlockInfo article.

Parameters

Parameters

Parameter

Description

height: Int

block height

Example

let x = match blockInfoByHeight(1234567) {
 case block:BlockInfo =>
   block.generator.toString() # "3P38Z9aMhGKAWnCiyMW4T3PcHcRaTAmTztH"
 case _ => throw("Can't find block")
}
calculateAssetId(Issue): ByteVector

Calculates ID of the token formed by the issue structure when executing the callable function.

calculateAssetId(issue: Issue): ByteVector

Parameters

Parameters

Parameter

Description

issue: Issue

Structure that sets the parameters of the token issue.

Example

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ACCOUNT #-}

@Callable(inv)
func issueAndId() = {
 let issue = Issue("CryptoRouble", "Description", 1000, 2, true)
 let id = calculateAssetId(issue)
 (
   [
     issue,
     BinaryEntry("id", id)
   ],
   unit
 )
}
calculateLeaseId(Lease): ByteVector

Calculates ID of the lease formed by the lease structure when executing the callable function.

calculateLeaseId(lease: Lease): ByteVector

Parameters

Parameters

Parameter

Description

lease: Lease

Structure that sets the lease parameters.

Example

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ACCOUNT #-}

@Callable(i)
func foo() = {
 let lease = Lease(Alias("merry"),100000000)
 let id = calculateLeaseId(lease)
 (
   [
     lease,
     BinaryEntry("lease", id)
   ],
   unit
 )
}
scriptHash(Address|Alias): ByteVector|Unit

Returns BLAKE2b-256 hash of the script assigned to a given account. Returns unit if there is no script. The function can be used to verify that the script is exactly the same as expected.

scriptHash(addressOrAlias: Address|Alias): ByteVector|Unit

Parameters

Parameters

Parameter

Description

addressOrAlias: Address | Alias

Address or alias of the account.

Example

let addr = Address(base58'3MxBZbnN8Z8sbYjjL5N3oG5C8nWq9NMeCEm')
scriptHash(addr) # Returns base58'G6ihnWN5mMedauCgNa8TDrSKWACPJKGQyYagmMQhPuja'
transactionHeightById(ByteVector): Int|Unit

Gets the block height of a transaction.

transactionHeightById(id: ByteVector): Int|Unit

Parameters

Parameters

Parameter

Description

id: ByteVector

ID of the transaction.

Example

let bitcoinId = base58'8LQW8f7P5d5PZM7GtZEBgaqRPGSzS3DfPuiXrURJ4AJS'
let x = match transactionHeightById(bitcoinId) {
 case h:Int => h # 257457
 case _ => throw("Can't find transaction")
}
transferTransactionById(ByteVector): TransferTransaction|Unit

Gets the data of a transfer transaction.

transferTransactionById(id: ByteVector): TransferTransaction|Unit

For a description of the return value, see the TransferTransaction article.

Parameters

Parameters

Parameter

Description

id: ByteVector

ID of the transfer transaction.

Example

let transferId = base58'J2rcMzCWCZ1P3SFZzvz9PR2NtBjomDh57HTcqptaAJHK'
let x = match transferTransactionById(transferId) {
 case ttx:TransferTransaction =>
   ttx.amount # 3500000000
 case _ => throw("Can't find transaction")
}
wavesBalance(Address|Alias): BalanceDetails

Gets all types of DecentralCoin balances. For description of balance types, see the account balance article.

wavesBalance(addressOrAlias: Address|Alias): BalanceDetails

Parameters

Parameters

Parameter

Description

addressOrAlias: Address | Alias

Address or alias of the account.

Byte Array Functions
Byte Array Functions

Name

Description

Complexity

drop(ByteVector, Int): ByteVector

Returns the byte array without the first N bytes

\(6\)

dropRight(ByteVector, Int): ByteVector

Returns the byte array without the last N bytes

\(6\)

size(ByteVector): Int

Returns the number of bytes in the byte array

\(1\)

take(ByteVector, Int): ByteVector

Returns the first N bytes of the byte array

\(6\)

takeRight(ByteVector, Int): ByteVector

Returns the last N bytes of the byte array

\(6\)

drop(ByteVector, Int): ByteVector

Returns the byte array without the first N bytes.

drop(xs: ByteVector, number: Int): ByteVector

Parameters

Parameters

Parameter

Description

xs: ByteVector

Byte array.

number: Int

N bytes.

Example

drop("Ride".toBytes(), 2)   # Returns the byte array without the first 2 bytes
drop(125.toBytes(), 2)      # Returns the byte array without the first 2 bytes
drop(base16'52696465', 3)   # Returns the byte array without the first 3 bytes
drop(base58'37BPKA', 3)     # Returns the byte array without the first 3 bytes
drop(base64'UmlkZQ==', 3)   # Returns the byte array without the first 3 bytes
dropRight(ByteVector, Int): ByteVector

Returns the byte array without the last N bytes.

dropRight(xs: ByteVector, number: Int): ByteVector

Parameters

Parameters

Parameter

Description

xs: ByteVector

Byte array.

number: Int

N bytes.

Example

dropRight("Ride".toBytes(), 2)  # Returns the byte array without the last 2 bytes
dropRight(125.toBytes(), 2)     # Returns the byte array without the last 2 bytes
dropRight(base16'52696465', 3)  # Returns the byte array without the last 3 bytes
dropRight(base58'37BPKA', 3)    # Returns the byte array without the last 3 bytes
dropRight(base64'UmlkZQ==', 3)  # Returns the byte array without the last 3 bytes
size(ByteVector): Int

Returns the number of bytes in the byte array.

size(byteVector: ByteVector): Int

Parameters

Parameters

Parameter

Description

xs: ByteVector

Byte array.

Example

size("Hello".toBytes())         # Returns 5
size("Hello world".toBytes())   # Returns 11
size(64.toBytes())              # Returns 8 because all integers in Ride take 8 bytes
size(200000.toBytes())          # Returns 8 because all integers in Ride take 8 bytes
size(base58'37BPKA')            # Returns 4
take(ByteVector, Int): ByteVector

Returns the first N bytes of the byte array.

take(xs: ByteVector, number: Int): ByteVector

Parameters

Parameters

Parameter

Description

xs: ByteVector

Byte array.

number: Int

N bytes.

Example

take(base58'37BPKA', 0) # Returns the empty byte array
take(base58'37BPKA', 1) # Returns the byte array consisting of first byte of initial byte array
take(base58'37BPKA', 15) # Returns whole byte array
take(base58'37BPKA', -10) # Returns the empty byte array
takeRight(ByteVector, Int): ByteVector

Returns the last N bytes of the byte array.

takeRight(xs: ByteVector, number: Int): ByteVector

Parameters

Parameters

Parameter

Description

xs: ByteVector

Byte array.

number: Int

N bytes.

Example

takeRight(base58'37BPKA', 2) # Returns the last 2 bytes of the byte array
Converting Functions
Converting Functions

Name

Description

Complexity

addressFromPublicKey(ByteVector): Address

Gets the corresponding address of the account public key `

\(63\)

parseBigInt(String): BigInt|Unit

Converts the string representation of a number to its big integer equivalent

\(65\)

parseBigIntValue(String): BigInt

Converts the string representation of a number to its big integer equivalent. Fails if the string cannot be parsed

\(65\)

parseInt(String): Int|Unit

Converts the string representation of a number to its integer equivalent

\(2\)

parseIntValue(String): Int

Converts the string representation of a number to its integer equivalent. Fails if the string cannot be parsed

\(2\)

toBigInt(ByteVector): BigInt

Converts an array of bytes to a big integer

\(65\)

toBigInt(ByteVector, Int, Int): BigInt

Converts an array of bytes starting from a certain index to a big integer

\(65\)

toBigInt(Int): BigInt

Converts an integer to a big integer

\(1\)

toBytes(Boolean): ByteVector

Converts a boolean to an array of bytes

\(1\)

toBytes(Int): ByteVector

Converts an integer to an array of bytes

\(1\)

toBytes(String): ByteVector

Converts a string to an array of bytes

\(8\)

toBytes(BigInt): ByteVector

Converts a big integer to an array of bytes

\(65\)

toInt(BigInt): Int

Converts a big integer to an integer. Fails if the number cannot be converted

\(1\)

toInt(ByteVector): Int

Converts an array of bytes to an integer

\(1\)

toInt(ByteVector, Int): Int

Converts an array of bytes to an integer starting from a certain index

\(1\)

toString(Address): String

Converts an address to a string

\(10\)

toString(Boolean): String

Converts a boolean to a string

\(1\)

toString(Int): String

Converts an integer to a string

\(1\)

toString(BigInt): String

Converts a big integer to a string

\(65\)

toUtf8String(ByteVector): String

Converts an array of bytes to a UTF-8 string

\(7\)

transferTransactionFromProto(ByteVector): TransferTransaction|Unit

Deserializes transfer transaction

\(5\)

addressFromPublicKey(ByteVector): Address

Gets the corresponding address of the account public key.

addressFromPublicKey(publicKey: ByteVector): Address

For a description of the return value, see the address article.

Parameters

Parameters

Parameter

Description

publicKey: ByteVector

Public key.

Example

let address = addressFromPublicKey(base58'J1t6NBs5Hd588Dn7mAPytqkhgeBshzv3zecScfFJWE2D')
parseBigInt(String): BigInt|Unit

Converts the string representation of a number to its big integer equivalent.

parseBigInt(str: String): BigInt|Unit

Parameters

Parameters

Parameter

Description

str: String

String to parse.

parseBigIntValue(String): BigInt

Converts the string representation of a number to its big integer equivalent. Fails if the string cannot be parsed.

parseBigIntValue(str: String): BigInt

Parameters

Parameters

Parameter

Description

str: String

String to parse.

parseInt(String): Int|Unit

Converts the string representation of a number to its integer equivalent.

parseInt(str: String): Int|Unit

Parameters

Parameters

Parameter

Description

str: String

String to parse.

Example

parseInt("10") # Returns 10
parseInt("010") # Returns 10
parseInt("Ride") # Returns Unit
parseInt("10.30") # Returns Unit
parseIntValue(String): Int

Converts the string representation of a number to its integer equivalent. Fails if the string cannot be parsed.

parseIntValue(str: String): Int

Parameters

Parameters

Parameter

Description

str: String

String to parse.

Example

parseIntValue("10") # Returns 10
parseIntValue("010") # Returns 10
parseIntValue("Ride") # Error while parsing string to integer
parseIntValue("10.30") # Error while parsing string to integer
parseIntValue("20 DecentralCoins") # Error while parsing string to integer
toBigInt(ByteVector): BigInt

Converts an array of bytes to a big integer using the big-endian byte order.

toBigInt(bin: ByteVector): BigInt

Parameters

Parameters

Parameter

Description

bin: ByteVector

Array of bytes to convert.

toBigInt(ByteVector, Int, Int): BigInt

Converts an array of bytes starting from a certain index to a big integer using the big-endian byte order.

toBigInt(bin: ByteVector, offset: Int, size: Int): BigInt

Parameters

Parameters

Parameter

Description

bin: ByteVector

Array of bytes to convert.

offset: Int

Index to start from.

size: Int

Number of bytes (subarray length) to convert.

toBigInt(Int): BigInt

Converts an integer to a big integer.

toBigInt(n: Int): BigInt

Parameters

Parameters

Parameter

Description

n: Int

Integer to convert.

toBytes(Boolean): ByteVector

Converts a boolean value to an array of bytes.

toBytes(b: Boolean): ByteVector

Parameters

Parameters

Parameter

Description

b: Boolean

Boolean to convert.

Example

toBytes(true) # Returns base58'2'
toBytes(false) # Returns base58'1'
toBytes(Int): ByteVector

Converts an integer to an array of bytes using the big-endian byte order.

toBytes(n: Int): ByteVector

Parameters

Parameters

Parameter

Description

n: Int

Integer to convert.

Example

toBytes(10) # Returns base58'1111111B'
toBytes(String): ByteVector

Converts a string to an array of bytes.

toBytes(s: String): ByteVector

Parameters

Parameters

Parameter

Description

str: String

String to convert.

Example

toBytes("Ride") # Returns base58'37BPKA'
toBytes(BigInt): ByteVector

Converts a big integer to an array of bytes using the big-endian byte order.

toBytes(n: BigInt): ByteVector

Parameters

Parameters

Parameter

Description

n: BigInt

Big integer to convert.

toInt(BigInt): Int

Converts a big integer to an integer. Fails if the number cannot be converted.

toInt(n: BigInt): Int

Parameters

Parameters

Parameter

Description

n: BigInt

Big integer to convert.

toInt(ByteVector): Int

Converts an array of bytes to an integer using the big-endian byte order.

toInt(bin: ByteVector) : Int

Parameters

Parameters

Parameter

Description

bin: ByteVector

Array of bytes to convert.

Example

toInt(base58'1111111B') # Returns 10
toInt(ByteVector, Int): Int

Converts an array of bytes to an integer starting from a certain index using the big-endian byte order.

toInt(bin: ByteVector, offset: Int): Int

Parameters

Parameters

Parameter

Description

bin: ByteVector

Array of bytes to convert.

offset: Int

Index to start from.

Example

let bytes = toBytes("Ride")
toInt(bytes, 2) # Returns 7234224039401641825
toInt(bytes, 6) # Index out of bounds
toString(Address): String

Converts an array of bytes of an address to a string.

toString(addr: Address): String

Parameters

Parameters

Parameter

Description

addr: Address

Address to convert.

Example

let address = Address(base58'3NADPfTVhGvVvvRZuqQjhSU4trVqYHwnqjF')
toString(address) # Returns "3NADPfTVhGvVvvRZuqQjhSU4trVqYHwnqjF"
toString(Boolean): String

Converts a boolean value to a string.

toString(b: Boolean): String

Parameters

Parameters

Parameter

Description

b: Boolean

Boolean to convert.

Example

toString(true) # Returns "true"
toString(false) # Returns "false"
toString(Int): String

Converts an integer to a string.

toString(n: Int): String

Parameters

Parameters

Parameter

Description

n: Int

Integer to convert.

Example

toString(10) # Returns "10"
toString(BigInt): String

Converts a big integer to a string.

toString(n: BigInt): String

Parameters

Parameters

Parameter

Description

n: BigInt

Big integer to convert.

toUtf8String(ByteVector): String

Converts an array of bytes to a UTF-8 string. Fails if the array of bytes cotains an invalid UTF-8 sequence.

toUtf8String(u: ByteVector): String

Parameters

Parameters

Parameter

Description

u: ByteVector

Array of bytes to convert.

Example

let bytes = toBytes("Ride")
toUtf8String(bytes) # Returns "Ride"
transferTransactionFromProto(ByteVector): TransferTransaction|Unit

Deserializes transfer transaction: converts protobuf-encoded binary format specified in transaction.proto to a TransferTransaction structure. Returns unit if deserialization failed.

transferTransactionFromProto(b: ByteVector): TransferTransaction|Unit

For a description of the return value, see the TransferTransaction article.

Parameters

Parameters

Parameter

Description

b: ByteVector

Transfer transaction in protobuf-encoded binary format.

Example

let transfer = base64'Cr4BCFQSIA7SdnwUqEBY+k4jUf9sCV5+xj0Ry/GYuwmDMCdKTdl3GgQQoI0GIPLIyqL6LSgDwgaHAQoWChT+/s+ZWeOWzh1eRnhdRL3Qh9bxGRIkCiBO/wEBhwH/f/+bAWBRMv+A2yiAOUeBc9rY+UR/a4DxKBBkGkcaRYCcAQAB//9/AX9//0695P8EiICAfxgBgIkefwHYuDmA//83/4ABJgEBAf8d9N+8AAERyo1/j3kAGn/SAb7YIH8y/4CAXg=='
let x = match transferTransactionFromProto(transfer) {
 case ttx:TransferTransaction =>
   ttx.amount # 3500000000
 case _ => throw("Can't find transaction")
}
dApp-to-dApp Invocation Functions
dApp-to-dApp Invocation Functions

Name

Description

Complexity

invoke(Address|Alias, String, List[Any], List[AttachedPayments]): Any

Invokes a dApp callable function, with reentrancy restriction

\(75\)

reentrantInvoke(Address|Alias, String, List[Any], List[AttachedPayments]): Any

Invokes a dApp callable function, without reentrancy restriction

\(75\)

invoke(Address|Alias, String, List[Any], List[AttachedPayments]): Any

Invokes a dApp callable function, with reentrancy restriction.

invoke(dApp: Address|Alias, function: String, arguments: List[Any], payments: List[AttachedPayments]): Any

Any means any valid type. You can extract a particular type from it using as[T] and exactAs[T] macros or the match … case operator, see the any article.

The invoke function can be used by a callable function of a dApp script, but not by a verifier function, account script or asset script.

Via the invoke function, the callable function can invoke a callable function of another dApp, or another callable function of the same dApp, or even itself, and then use the invocation results in subsequent operations. For details, see the dApp-to-dApp invocation article.

To ensure executing callable functions and applying their actions in the right order, initialize a strict variable by the return value of an invoke function.

The invocation can contain payments that will be transferred from the balance of the parent dApp to the balance of the invoked dApp. Payments are forbidden if the dApp invokes itself.

If a payment token is a smart asset, the asset script verifies the invoke as if it was InvokeScriptTransaction with the following fields:

  • DApp, payments, function, args indicated in the invoke function.

  • Sender, senderPublicKey of the dApp that performs the invocation.

  • Id, timestamp, fee, feeAssetId indicated in the original invoke script transaction.

  • Version = 0;

If the asset script denies the action, the Invoke Script transaction is either discarded or saved on the blockchain as failed, see the transaction validation article.

Reentrancy Restriction

The invocation stack generated by the invoke function must not contain invocations of the parent dApp after invocation of another dApp. Let the parent dApp A invokes dApp B using the invoke function. Regardless of whether dApp B uses invoke or reentrantInvoke, the following invocation stacks will fail:

→ dApp A
  → dapp B
      → dApp A
→ dApp A
  → dapp B
     → dApp C
        → dApp A

The following invocation stacks are valid:

→ dApp A
  → dapp A
     → dapp A
→ dApp N
  → dapp A
  → dApp A
→ dapp N
  → dapp A
     → dapp B
  → dapp B
     → dapp A
     → dapp C
Parameters

Parameter

Description

dApp: Address | Alias

Address or alias of a dApp to invoke.

function: String | Unit

Name of a callable function. Unit for a default function invocation.

arguments: List [Any]

Parameters of a callable function.

payments: List [AttachedPayment]

Payments to transfer from the parent dApp to the invoked dApp, up to \(10\).

Example

A user sends an invoke script transaction that invokes the callable function foo of dApp1. The foo function invokes the bar function of dApp2 passing the number a and attaching a payment of 1 USDN. The bar function transfers \(1\) DecentralCoin to dApp1 and returns the doubled number a. The foo function writes to dApp1 data storage:

  • The value returned by bar.

  • The new balance of dApp2 (reduced by \(1\) DecentralCoin transferred to dApp1).

dApp1:

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ACCOUNT #-}

@Callable(i)
func foo(dapp2: String, a: Int, key1: String, key2: String) = {
  strict res = invoke(addressFromStringValue(dapp2),"bar",[a],[AttachedPayment(base58'DG2xFkPdDwKUoBkzGAhQtLpSGzfXLiCYPEzeKH2Ad24p',1000000)])
  match res {
    case r : Int =>
     (
       [
         IntegerEntry(key1, r),
         IntegerEntry(key2, wavesBalance(addressFromStringValue(dapp2)).regular)
       ],
       unit
     )
    case _ => throw("Incorrect invoke result")
  }
}

dApp2:

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ACCOUNT #-}

@Callable(i)
func bar(a: Int) = {
 (
   [
       ScriptTransfer(i.caller, 100000000, unit)
   ],
   a*2
 )
}
reentrantInvoke(Address|Alias, String, List[Any], List[AttachedPayments]): Any

Invokes a dApp callable function. The only difference from the invoke function above is that there is no reentrancy restriction for the parent dApp that uses reentrantInvoke. However, if the parent dApp is invoked again and this time uses the invoke function, the parent dApp cannot be invoked again in this invocation stack.

For example, the invocation stack:

→ dApp A
  → dapp B
     → dApp A
        → dApp C
           → dApp A
  • Is valid if dApp A invokes both dApp B and dApp C via the reentrantInvoke function;

  • Fails if dApp A invokes dApp B via the reentrantInvoke function and invokes dApp C via the invoke function.

reentrantInvoke(dApp: Address|Alias, function: String, arguments: List[Any], payments: List[AttachedPayments]): Any
Data Transaction Functions

The functions listed below retrieve data by key from the data transaction structure or from any list of data entries.

Data Transaction Functions

Name

Description

Complexity

getBinary(List[], String): ByteVector|Unit

Gets a binary value from a list of data entires by key

\(10\)

getBinary(List[], Int): ByteVector|Unit

Gets a binary value from a list of data entires by index

\(4\)

getBinaryValue(List[], String): ByteVector

Gets a binary value from a list of data entires by key. Fails if there is no data

\(10\)

getBinaryValue(List[], Int): ByteVector

Gets a binary value from a list of data entires by index. Fails if there is no data

\(4\)

getBoolean(List[], String): Boolean|Unit

Gets a boolean value from a list of data entires by key

\(10\)

getBoolean(List[], Int): Boolean|Unit

Gets a boolean value from a list of data entires by index

\(4\)

getBooleanValue(List[], String): Boolean

Gets a boolean value from a list of data entires by key. Fails if there is no data

\(10\)

getBooleanValue(List[], Int): Boolean

Gets a boolean value from a list of data entires by index. Fails if there is no data

\(4\)

getInteger(List[], String): Int|Unit

Gets an integer value from a list of data entires by key

\(10\)

getInteger(List[], Int): Int|Unit

Gets an integer value from a list of data entires by index

\(4\)

getIntegerValue(List[], String): Int

Gets an integer value from a list of data entires by key. Fails if there is no data

\(10\)

getIntegerValue(List[], Int): Int

Gets an integer value from a list of data entires by index. Fails if there is no data

\(4\)

getString(List[], String): String|Unit

Gets a string value from a list of data entires by key

\(10\)

getString(List[], Int): String|Unit

Gets a string value from a list of data entires by index

\(4\)

getStringValue(List[], String): String

Gets a string value from a list of data entires by key. Fails if there is no data

\(10\)

getStringValue(List[], Int): String

Gets a string value from a list of data entires by index. Fails if there is no data

\(4\)

getBinary(List[], String): ByteVector|Unit

Gets a binary value from a list of data entires by key.

getBinary(data: List[BinaryEntry|BooleanEntry|IntegerEntry|StringEntry], key: String): ByteVector|Unit

Parameters

Parameters

Parameter

Description

data: List []

List of data entries, usually tx.data.

key: String

Key.

getBinary(List[], Int): ByteVector|Unit

Gets a binary value from a list of data entires by index.

getBinary(data: List[BinaryEntry|BooleanEntry|IntegerEntry|StringEntry], index: Int): ByteVector|Unit

Parameters

Parameters

Parameter

Description

data: List []

List of data entries, usually tx.data.

index: Int

Index.

getBinaryValue(List[], String): ByteVector

Gets a binary value from a list of data entires by key. Fails if there is no data.

getBinaryValue(data: List[BinaryEntry|BooleanEntry|IntegerEntry|StringEntry], key: String): ByteVector

Parameters

Parameters

Parameter

Description

data: List []

List of data entries, usually tx.data.

key: String

Key.

getBinaryValue(List[], Int): ByteVector

Gets a binary value from a list of data entires by index. Fails if there is no data.

getBinaryValue(data: List[BinaryEntry|BooleanEntry|IntegerEntry|StringEntry], index: Int): ByteVector

Parameters

Parameters

Parameter

Description

data: List []

List of data entries, usually tx.data.

index: Int

Index.

getBoolean(List[], String): Boolean|Unit

Gets a boolean value from a list of data entires by key.

getBoolean(data: List[BinaryEntry|BooleanEntry|IntegerEntry|StringEntry], key: String): Boolean|Unit

Parameters

Parameters

Parameter

Description

data: List []

List of data entries, usually tx.data.

key: String

Key.

getBoolean(List[], Int): Boolean|Unit

Gets a boolean value from a list of data entires by index.

getBoolean(data: List[BinaryEntry|BooleanEntry|IntegerEntry|StringEntry], index: Int): Boolean|Unit

Parameters

Parameters

Parameter

Description

data: List []

List of data entries, usually tx.data.

index: Int

Index.

getBooleanValue(List[], String): Boolean

Gets a boolean value from a list of data entires by key. Fails if there is no data.

getBooleanValue(data: List[BinaryEntry|BooleanEntry|IntegerEntry|StringEntry], key: String): Boolean

Parameters

Parameters

Parameter

Description

data: List []

List of data entries, usually tx.data.

key: String

Key.

getBooleanValue(List[], Int): Boolean

Gets a boolean value from a list of data entires by index. Fails if there is no data.

getBooleanValue(data: List[BinaryEntry|BooleanEntry|IntegerEntry|StringEntry], index: Int): Boolean

Parameters

Parameters

Parameter

Description

data: List []

List of data entries, usually tx.data.

index: Int

Index.

getInteger(List[], String): Int|Unit

Gets integer from a list of data entires by key.

getInteger(data: List[BinaryEntry|BooleanEntry|IntegerEntry|StringEntry], key: String): Int|Unit

Parameters

Parameters

Parameter

Description

data: List []

List of data entries, usually tx.data.

key: String

Key.

getInteger(List[], Int): Int|Unit

Gets an integer value from a list of data entires by index.

getInteger(data: List[BinaryEntry|BooleanEntry|IntegerEntry|StringEntry], index: Int): Int|Unit

Parameters

Parameters

Parameter

Description

data: List []

List of data entries, usually tx.data.

index: Int

Index.

getIntegerValue(List[], String): Int

Gets an integer value from a list of data entires by key. Fails if there is no data.

getIntegerValue(data: List[BinaryEntry|BooleanEntry|IntegerEntry|StringEntry], key: String): Int

Parameters

Parameters

Parameter

Description

data: List []

List of data entries, usually tx.data.

key: String

Key.

getIntegerValue(List[], Int): Int

Gets an integer value from a list of data entires by index. Fails if there is no data.

getIntegerValue(data: List[BinaryEntry|BooleanEntry|IntegerEntry|StringEntry], index: Int): Int

Parameters

Parameters

Parameter

Description

data: List []

List of data entries, usually tx.data.

index: Int

Index.

getString(List[], String): String|Unit

Gets a string value from a list of data entires by key.

getString(data: List[BinaryEntry|BooleanEntry|IntegerEntry|StringEntry], key: String): String|Unit

Parameters

Parameters

Parameter

Description

data: List []

List of data entries, usually tx.data.

key: String

Key.

getString(List[], Int): String|Unit

Gets a string value from a list of data entires by key.

getString(data: List[BinaryEntry|BooleanEntry|IntegerEntry|StringEntry], index: Int): String|Unit

Parameters

Parameters

Parameter

Description

data: List []

List of data entries, usually tx.data.

index: Int

Index.

getStringValue(List[], String): String

Gets a string value from a list of data entires by key. Fails if there is no data.

getStringValue(data: List[BinaryEntry|BooleanEntry|IntegerEntry|StringEntry], key: String): String

Parameters

Parameters

Parameter

Description

data: List []

List of data entries, usually tx.data.

key: String

Key.

getStringValue(List[], Int): String

Gets a string value from a list of data entires by index. Fails if there is no data.

getStringValue(data: List[BinaryEntry|BooleanEntry|IntegerEntry|StringEntry], index: Int): String

Parameters

Parameters

Parameter

Description

data: List []

List of data entries, usually tx.data.

index: Int

Index.

Decoding Functions
Decoding Functions

Name

Description

Complexity

addressFromString(String): Address|Unit

Decodes address from base58 string

\(1\)

addressFromStringValue(String): Address

Decodes address from base58 string. Fails if the address cannot be decoded

\(1\)

fromBase16String(String): ByteVector

Decodes base16 string to an array of bytes

\(10\)

fromBase58String(String): ByteVector

Decodes base58 string to an array of bytes

\(1\)

fromBase64String(String): ByteVector

Decodes base64 string to an array of bytes

\(40\)

addressFromString(String): Address|Unit

Decodes address from base58 string.

addressFromString(string: String): Address|Unit

For a description of the return value, see the address article.

Parameters

Parameters

Parameter

Description

string: string

String to decode.

Example

let address = addressFromString("3NADPfTVhGvVvvRZuqQjhSU4trVqYHwnqjF")
addressFromStringValue(String): Address

Decodes address from base58 string. Fails if the address cannot be decoded.

addressFromStringValue(string: String): Address

For a description of the return value, see the address article.

Parameters

Parameters

Parameter

Description

string: string

String to decode.

Example

let address = addressFromStringValue("3NADPfTVhGvVvvRZuqQjhSU4trVqYHwnqjF")
fromBase16String(String): ByteVector

Decodes a base16 string to an array of bytes.

fromBase16String(str: String): ByteVector

Parameters

Parameters

Parameter

Description

string: string

String to decode.

Example

let bytes = fromBase16String("52696465")
fromBase58String(String): ByteVector

Decodes a base58 string to an array of bytes.

fromBase58String(str: String): ByteVector

Parameters

Parameters

Parameter

Description

string: string

String to decode.

Example

let bytes = fromBase58String("37BPKA")
fromBase64String(String): ByteVector

Decodes a base64 string to an array of bytes.

fromBase64String(str: String): ByteVector

Parameters

Parameters

Parameter

Description

string: string

String to decode.

Example

let bytes = fromBase64String("UmlkZQ==")
Encoding Functions
Encoding Functions

Name

Description

Complexity

toBase16String(ByteVector): String

Encodes array of bytes to base16 string

\(10\)

toBase58String(ByteVector): String

Encodes array of bytes to base58 string

\(3\)

toBase64String(ByteVector): String

Encodes array of bytes to base64 string

\(35\)

toBase16String(ByteVector): String

Encodes an array of bytes to a base16 string.

toBase16String(bytes: ByteVector): String

Parameters

Parameters

Parameter

Description

bytes: ByteVector

Array of bytes to encode.

Example

toBase16String("Ride".toBytes()) # Returns "52696465"
toBase16String(base16'52696465') # Returns "52696465"
toBase58String(ByteVector): String

Encodes an array of bytes to a base58 string.

toBase58String(bytes: ByteVector): String

Parameters

Parameters

Parameter

Description

bytes: ByteVector

Array of bytes to encode.

Example

toBase58String("Ride".toBytes()) # Returns "37BPKA"
toBase58String(base58'37BPKA')  # Returns "37BPKA
toBase64String(ByteVector): String

Encodes an array of bytes to a base64 string.

toBase64String(bytes: ByteVector): String

Parameters

Parameters

Parameter

Description

bytes: ByteVector

Array of bytes to encode.

Example

toBase64String("Ride".toBytes()) # Returns "UmlkZQ=="
toBase64String(base64'UmlkZQ==') # Returns "UmlkZQ=="
Exception Functions
Exception Functions

Name

Description

Complexity

throw()

Raises an exception

\(1\)

throw(String)

Raises an exception with a message

\(1\)

The return type of throw is nothing. There is no exception handling in Ride: after an exception has been thrown, the script execution fails. The transaction can be either discarded or saved on the blockchain as failed, see the transaction validation article for details.

throw()

Raises an exception.

throw(String)

Raises an exception with a message.

throw(err: String)

Parameters

Parameters

Parameter

Description

err: String

The exception message.

Hashing Functions
Hashing Functions

Name

Description

Complexity

blake2b256(ByteVector): ByteVector

Range of functions. Hash an array of bytes using BLAKE2b-256

\(10–200\)

keccak256(ByteVector): ByteVector

Range of functions. Hash an array of bytes using Keccak-256

\(10–200\)

sha256(ByteVector): ByteVector

Range of functions. Hash an array of bytes using SHA-256

\(10–200\)

blake2b256(ByteVector): ByteVector

Range of functions that hash an array of bytes using BLAKE2b-256.

blake2b256

Name

Max data size

Complexity

blake2b256(bytes: ByteVector): ByteVector

\(150\) kB

\(200\)

blake2b256_16Kb(bytes: ByteVector): ByteVector

\(16\) kB

\(10\)

blake2b256_32Kb(bytes: ByteVector): ByteVector

\(32\) kB

\(25\)

blake2b256_64Kb(bytes: ByteVector): ByteVector

\(64\) kB

\(50\)

blake2b256_128Kb(bytes: ByteVector): ByteVector

\(128\) kB

\(100\)

Parameters

Parameters

Parameter

Description

bytes: ByteVector

The array of bytes to encode. Maximum size: 1) For blake2b256_<N>Kb functions — N kB. 2) For blake2b256 function — 150 kB.

Example

blake2b256("Ride".toBytes())        # Returns 6NSWRz5XthhFVm9uVQHuisdaseQJfc4WMGajN435v3f4
blake2b256(125.toBytes())            # Returns H9emWhyMuyyjDmNkgx7jAfHRuy9icXK3uYJuVw6R1uuK
blake2b256(base16'52696465')   # Returns 6NSWRz5XthhFVm9uVQHuisdaseQJfc4WMGajN435v3f4
blake2b256(base58'37BPKA')       # Returns 6NSWRz5XthhFVm9uVQHuisdaseQJfc4WMGajN435v3f4
blake2b256(base64'UmlkZQ==')  # Returns 6NSWRz5XthhFVm9uVQHuisdaseQJfc4WMGajN435v3f4
keccak256(ByteVector): ByteVector

Range of functions that hash an array of bytes using Keccak-256.

keccak256

Name

Max data size

Complexity

keccak256(bytes: ByteVector): ByteVector»

\(150\) kB

\(200\)

keccak256_16Kb(bytes: ByteVector): ByteVector»

\(16\) kB

\(10\)

keccak256_32Kb(bytes: ByteVector): ByteVector»

\(32\) kB

\(25\)

keccak256_64Kb(bytes: ByteVector): ByteVector»

\(64\) kB

\(50\)

keccak256_128Kb(bytes: ByteVector): ByteVector»

\(128\) kB

\(100\)

Parameters

Parameters

Parameter

Description

bytes: ByteVector

The array of bytes to encode. Maximum size: 1) For keccak256_<N>Kb functions — N kB. 2) For keccak256 function — 150 kB.

Example

keccak256("Ride".toBytes())        # Returns 4qa5wNk4961VwJAjCKBzXiEvBQ2gBJoqDcLFRJTiSKpv
keccak256(125.toBytes())            # Returns 5UUkcH6Fp2E3mk7NSqSTs3JBP33zL3SB3yg4b2sR5gpF
keccak256(base16'52696465')   # Returns 4qa5wNk4961VwJAjCKBzXiEvBQ2gBJoqDcLFRJTiSKpv
keccak256(base58'37BPKA')       # Returns 4qa5wNk4961VwJAjCKBzXiEvBQ2gBJoqDcLFRJTiSKpv
keccak256(base64'UmlkZQ==')  # Returns 4qa5wNk4961VwJAjCKBzXiEvBQ2gBJoqDcLFRJTiSKpv
sha256(ByteVector): ByteVector

Range of functions that hash an array of bytes using SHA-256.

sha256

Name

Max data size

Complexity

sha256(bytes: ByteVector): ByteVector»

\(150\) kB

\(200\)

sha256_16Kb(bytes: ByteVector): ByteVector»

\(16\) kB

\(10\)

sha256_32Kb(bytes: ByteVector): ByteVector»

\(32\) kB

\(25\)

sha256_64Kb(bytes: ByteVector): ByteVector»

\(64\) kB

\(50\)

sha256_128Kb(bytes: ByteVector): ByteVector»

\(128\) kB

\(100\)

Parameters

Parameters

Parameter

Description

bytes: ByteVector

The array of bytes to encode. Maximum size: 1) For sha256_<N>Kb functions — N kB. 2) For sha256 function — 150 kB.

Example

sha256("Ride".toBytes())        # Returns 5YxvrKsjJtq4G325gRVxbXpkox1sWdHUGVJLnRFqTWD3
sha256(125.toBytes())            # Returns A56kbJjy7A4B9Pa5tUgRNvtCHSsZ7pZVJuPsLT2vtPSU
sha256(base16'52696465')   # Returns 5YxvrKsjJtq4G325gRVxbXpkox1sWdHUGVJLnRFqTWD3
sha256(base58'37BPKA')       # Returns 5YxvrKsjJtq4G325gRVxbXpkox1sWdHUGVJLnRFqTWD3
sha256(base64'UmlkZQ==')  # Returns 5YxvrKsjJtq4G325gRVxbXpkox1sWdHUGVJLnRFqTWD3
List Functions
List Functions

Name

Description

Complexity

cons(A, List[B]): List[A|B]

Inserts element to the beginning of the list

\(1\)

containsElement(List[T], T): Boolean

Check if the element is in the list

\(5\)

getElement(List[T], Int): T

Gets element from the list

\(2\)

indexOf(List[T], T): Int|Unit

Returns the index of the first occurrence of the element in the list

\(5\)

lastIndexOf(List[T], T): Int|Unit

Returns the index of the last occurrence of the element in the list

\(5\)

max(List[Int]): Int

Returns the largest element in the list of integers

\(3\)

max(List[BigInt]): BigInt

Returns the largest element in the list of big integers

\(192\)

min(List[Int]): Int

Returns the smallest element in the list of integers

\(3\)

min(List[BigInt]): BigInt

Returns the smallest element in the list of big integers

\(192\)

removeByIndex(List[T], Int): List[T]

Removes an element from the list by index

\(7\)

size(List[T]): Int

Returns the size of the list

\(2\)

A, B, T means any valid type.

cons(A, List[B]): List[A|B]

Inserts element to the beginning of the list.

cons(head:T, tail: List[T]): List[T]

Parameters

Parameters

Parameter

Description

head: T

Element

tail: List [T]

List

Example

cons("Hello", ["World", "."]) # Returns ["Hello", "World", "."]
cons(1, [2, 3, 4, 5]) # Returns [1, 2, 3, 4, 5]
containsElement(List[T], T): Boolean

Check if the element is in the list.

containsElement(list: List[T], element: T): Boolean

Parameters

Parameters

Parameter

Description

list: List [T]

List

element: T

Element to search for

getElement(List[T], Int): T

Gets the element from the list by index.

getElement(arr: List[T], pos: Int): T

Parameters

Parameters

Parameter

Description

arr: List [T]

List

pos: Int

Index of the element

Example

getElement(["Hello", "World", "."], 0)  # Returns "Hello"
getElement([false, true], 1) # Returns true
indexOf(List[T], T): Int|Unit

Returns the index of the first occurrence of the element in the list or unit if the element is missing.

indexOf(list: List[T], element: T): Int|Unit

Parameters

Parameters

Parameter

Description

list: List [T]

List

element: T

Element to locate

Example

let stringList = ["a","b","a","c"]
indexOf("a", stringList) # Returns 0
lastIndexOf(List[T], T): Int|Unit

Returns the index of the last occurrence of the element in the list or unit if the element is missing.

lastIndexOf(list: List[T], element: T): Int|Unit

Parameters

Parameters

Parameter

Description

list: List [T]

List

element: T

Element to locate

Example

let stringList = ["a","b","a","c"]
lastIndexOf("a", stringList) # Returns 2
max(List[Int]): Int

Returns the largest element in the list of integers. Fails if the list is empty.

max(List[Int]): Int

Parameters

Parameters

Parameter

Description

list: List [Int]

List

max(List[BigInt]): BigInt

Returns the largest element in the list of big integers. Fails if the list is empty.

max(List[BigInt]): BigInt

Parameters

Parameters

Parameter

Description

list: List [BigInt]

List

min(List[Int]): Int

Returns the smallest element in the list of integers. Fails if the list is empty.

min(List[Int]): Int

Parameters

Parameters

Parameter

Description

list: List [Int]

List

min(List[BigInt]): BigInt

Returns the smallest element in the list of big integers. Fails if the list is empty.

min(List[BigInt]): BigInt

Parameters

Parameters

Parameter

Description

list: List [BigInt]

List

removeByIndex(List[T], Int): List[T]

Removes an element from the list by index.

removeByIndex(list: List[T], index: Int): List[T]

Parameters

Parameters

Parameter

Description

list: List [T]

List

index: T

Index of the element

Example

removeByIndex(["Ride", 42, true], 1) # Returns ["Ride", true]
size(List[T]): Int

Returns the size of the list.

size(arr: List[T]): Int

Parameters

Parameters

Parameter

Description

arr: List [T]

List

Example

size(["Hello", "World", "."]) # Returns 3
Math Functions
Math Functions

Name

Description

Complexity

fraction(Int, Int, Int): Int

Multiplies and divides integers to avoid overflow

\(14\)

fraction(Int, Int, Int, Union): Int

Multiplies and divides integers to avoid overflow, applying the specified rounding method

\(17\)

fraction(BigInt, BigInt, BigInt): BigInt

Multiplies and divides bid integers to avoid overflow

\(128\)

fraction(BigInt, BigInt, BigInt, Union): BigInt

Multiplies and divides big integers to avoid overflow, applying the specified rounding method

\(128\)

log(Int, Int, Int, Int, Int, Union): Int

Calculates logarithm of a number with a base

\(100\)

log(BigInt, Int, BigInt, Int, Int, Union): BigInt

Calculates logarithm of a number to a given base with high accuracy

\(200\)

median(List[Int]): Int

Returns the median of a list of integers

\(20\)

median(List[BigInt]): BigInt

Returns the median of a list of big integers

\(160\)

pow(Int, Int, Int, Int, Int, Union): Int

Raises a number to a given power

\(100\)

pow(BigInt, Int, BigInt, Int, Int, Union): BigInt

Raises a number to a given power with high accuracy

\(200\)

fraction(Int, Int, Int): Int

Multiplies integers \(a\), \(b\) and divides the result by the integer \(c\) to avoid overflow.

Fraction \(a × b / c\) should not exceed the maximum value of the integer type \(9,223,372,036,854,755,807\).

The rounding method is DOWN, see rounding variables below.

fraction(a: Int, b: Int, c: Int): Int

Parameters

Parameters

Parameter

Description

a: Int

Integer a

b: Int

Integer b

c: Int

Integer c

Example

Lets assume that:

\(a = 100,000,000,000\),

\(b = 50,000,000,000,000\),

\(c = 2,500,000\).

The following formula, with operators * and /, fails due to overflow:

a * b / c #  overflow, because a × b exceeds max integer value

The fraction function with no overflow:

fraction(a, b, c) # Result: 2,000,000,000,000,000,000
fraction(Int, Int, Int, Union): Int

Multiplies integers \(a\), \(b\) and divides the result by the integer \(c\) to avoid overflow, applying the specified rounding method.

Fraction \(a × b / c\) should not exceed the maximum value of the integer type \(9,223,372,036,854,755,807\).

fraction(a: Int, b: Int, c: Int, round: DOWN|CEILING|FLOOR|HALFUP|HALFEVEN): Int

Parameters

Parameters

Parameter

Description

a: Int

Integer a

b: Int

Integer b

c: Int

Integer c

round: DOWN|CEILING|FLOOR|HALFUP|HALFEVEN

One of the rounding variables

fraction(BigInt, BigInt, BigInt): BigInt

Multiplies integers \(a\), \(b\) and divides the result by the integer \(c\) to avoid overflow, applying the specified rounding method.

Fraction \(a × b / c\) should not exceed the maximum value of the integer type \(9,223,372,036,854,755,807\).

fraction(a: BigInt, b: BigInt, c: BigInt): BigInt

Parameters

Parameters

Parameter

Description

a: BigInt

Big integer a

b: BigInt

Big integer b

c: BigInt

Big integer c

fraction(BigInt, BigInt, BigInt, Union): BigInt

Multiplies integers \(a\), \(b\) and divides the result by the integer \(c\) to avoid overflow, applying the specified rounding method.

Fraction \(a × b / c\) should not exceed the maximum value of the integer type \(9,223,372,036,854,755,807\).

fraction(a: BigInt, b: BigInt, c: BigInt, round: DOWN|CEILING|FLOOR|HALFUP|HALFEVEN): BigInt

Parameters

Parameters

Parameter

Description

a: BigInt

Big integer a

b: BigInt

Big integer b

c: BigInt

Big integer c

round: DOWN|CEILING|FLOOR|HALFUP|HALFEVEN

One of the rounding variables

log(Int, Int, Int, Int, Int, Union): Int

Calculates \(\log_b a\).

log(value: Int, vp: Int, base: Int, bp: Int, rp: Int, round: DOWN|CEILING|FLOOR|HALFUP|HALFEVEN): Int

In Ride, there is no data type with the floating point. That is why, for example, when you need to calculate \(\log_{2.7} 16.25\) then the number value \(= 1625\), vp \(= 2\) and the base \(= 27\), bp \(= 1\).

If the log function returns, for example, \(2807035420964590265\), and the parameter rp \(= 18\), then the result is \(2.807035420964590265\); in the number \(2807035420964590265\) the last \(18\) digits is a fractional part.

Parameters

Parameters

Parameter

Description

value: Int

Number a without decimal point.

vp: Int

Number of decimals of a.

base: Int

Logarithm base b without decimal point.

bp: Int

Number of decimals of b.

rp: Int

Number of decimals in the resulting value, from \(0\) to \(8\) inclusive. Specifies the accuracy of the calculated result.

round: DOWN|CEILING|FLOOR|HALFUP|HALFEVEN

One of the rounding variables.

Example

\(\log_{2.7} 16.25 = 2.807035421...\)

log(1625, 2, 27, 1, 2, HALFUP) # Function returns 281, so the result is: 2.81
log(1625, 2, 27, 1, 5, HALFUP) # Function returns 280703542, so the result is: 2.80704
log(0, 0, 2, 0, 0, HALFUP)     # Result: -Infinity
log(BigInt, Int, BigInt, Int, Int, Union): BigInt

Calculates \(\log_b a\) with high accuracy.

log(value: BigInt, ep: Int, base: BigInt, bp: Int, rp: Int, round: DOWN|CEILING|FLOOR|HALFUP|HALFEVEN): BigInt

Parameters

Parameters

Parameter

Description

value: BigInt

Number a without decimal point.

vp: Int

Number of decimals of a.

base: BigInt

Logarithm base b without decimal point.

bp: Int

Number of decimals of b.

rp: Int

Number of decimals in the resulting value, from \(0\) to \(18\) inclusive. Specifies the accuracy of the calculated result.

round: DOWN|CEILING|FLOOR|HALFUP|HALFEVEN

One of the rounding variables.

median(List[Int]): Int

Returns the median of the list of integers. Fails if the list is empty.

median(arr: List[Int]): Int

Parameters

Parameters

Parameter

Description

arr: List [Int]

List of integers

Example

median([1, 2, 3])         # Returns 2
median([2, 4, 9, 20])     # Returns 6
median([-2, -4, -9, -20]) # Returns -7
median(List[BigInt]): BigInt

Returns the median of a list of big integers. Fails if the list is empty or contains more than \(100\) elements.

median(arr: List[BigInt]): BigInt

Parameters

Parameters

Parameter

Description

arr: List [BigInt]

List of big integers

pow(Int, Int, Int, Int, Int, Union): Int

Calculates \(a^{b}\).

pow(base: Int, bp: Int, exponent: Int, ep: Int, rp: Int, round: DOWN|CEILING|FLOOR|HALFUP|HALFEVEN): Int

Parameters

Parameters

Parameter

Description

base: Int

Logarithm base b without decimal point.

bp: Int

Number of decimals of a.

exponent: Int

Exponent b without decimal point.

ep: Int

Number of decimals of b.

rp: Int

Number of decimals in the resulting value, from \(0\) to \(8\) inclusive. Specifies the accuracy of the calculated result.

round: DOWN|CEILING|FLOOR|HALFUP|HALFEVEN

One of the rounding variables.

Example

\(16.25^{2.7} = 1859,1057168...\)

pow(1625, 2, 27, 1, 2, HALFUP) # function returns 185911, so the result is: 1859.11
pow(1625, 2, 27, 1, 5, HALFUP) # function returns 185910572, so, the result is: 1859.10572
pow(BigInt, Int, BigInt, Int, Int, Union): BigInt

Calculates \(a^{b}\) with high accuracy.

pow(base: BigInt, bp: Int, exponent: BigInt, ep: Int, rp: Int, round: DOWN|CEILING|FLOOR|HALFUP|HALFEVEN): BigInt

Parameters

Parameters

Parameter

Description

base: BigInt

Logarithm base b without decimal point.

bp: Int

Number of decimals of a.

exponent: BigInt

Exponent b without decimal point.

ep: Int

Number of decimals of b.

rp: Int

Number of decimals in the resulting value, from \(0\) to \(18\) inclusive. Specifies the accuracy of the calculated result.

round: DOWN|CEILING|FLOOR|HALFUP|HALFEVEN

One of the rounding variables.

Rounding Variables

Below is the list of built-in rounding variables. The rounding variables are only used as the parameters of functions fraction, log, pow.

Parameters

Rounding Variables

Name

Description

DOWN

Rounds towards zero.

CEILING

Rounds towards positive infinity.

FLOOR

Rounds towards negative infinity.

HALFUP

Rounds towards the nearest integer; if the integers are equidistant, then rounds away from zero.

HALFEVEN

Rounds towards the nearest integer; if the integers are equidistant, then rounds towards the nearest even integer.

Example

Parameters

Input number/Rounding method

DOWN

CEILING

FLOOR

HALFUP

HALFEVEN

\(5.5\)

\(5\)

\(6\)

\(5\)

\(6\)

\(6\)

\(2.5\)

\(2\)

\(3\)

\(2\)

\(3\)

\(2\)

\(1.6\)

\(1\)

\(2\)

\(1\)

\(2\)

\(2\)

\(1.1\)

\(1\)

\(2\)

\(1\)

\(1\)

\(1\)

\(1.0\)

\(1\)

\(1\)

\(1\)

\(1\)

\(1\)

\(-1.0\)

\(-1\)

\(-1\)

\(-1\)

\(-1\)

\(-1\)

\(-1.1\)

\(-1\)

\(-1\)

\(-2\)

\(-1\)

\(-1\)

\(-1.6\)

\(-1\)

\(-1\)

\(-2\)

\(-2\)

\(-2\)

\(-2.5\)

\(-2\)

\(-2\)

\(-3\)

\(-3\)

\(-2\)

\(-5.5\)

\(-5\)

\(-5\)

\(-6\)

\(-6\)

\(-6\)

String Functions
String Functions

Name

Description

Complexity

contains(String, String): Boolean

Checks whether the string contains substring

\(3\)

drop(String, Int): String

Drops the first n characters of a string

\(20\)

dropRight(String, Int): String

Drops the last n characters of a string

\(20\)

indexOf(String, String): Int|Unit

Returns the index of the first occurrence of a substring

\(3\)

indexOf(String, String, Int): Int|Unit

Returns the index of the first occurrence of a substring after a certain index

\(3\)

lastIndexOf(String, String): Int|Unit

Returns the index of the last occurrence of a substring

\(3\)

lastindexOf(String, String, Int): Int|Unit

Returns the index of the last occurrence of a substring before a certain index

\(3\)

makeString(List[String], String): String

Concatenates list strings adding a separator

\(30\)

size(String): Int

Returns the size of a string

\(1\)

split(String, String): List[String]

Splits a string delimited by a separator into a list of substrings.

\(75\)

take(String, Int): String

Takes the first n characters from a string

\(20\)

takeRight(String, Int): String

Takes the last n characters from a string

\(20\)

contains(String, String): Boolean

Checks whether the string contains substring.

contains(haystack: String, needle: String): Boolean

Parameters

Parameters

Parameter

Description

haystack: String

String to search in.

needle: String

String to search for.

Example

"hello".contains("hell") # Returns true
"hello".contains("world") # Returns false
drop(String, Int): String

Drops the first n characters of a string.

drop(xs: String, number: Int): String

Parameters

Parameters

Parameter

Description

xs: String

The string.

number: Int

The number n.

Example

drop("Apple", 0) # Returns "Apple"
drop("Apple", 1) # Returns "pple"
drop("Apple", 3) # Returns "le"
drop("Apple", 5) # Returns an empty string
drop("Apple", 15) # Returns an empty string
dropRight(String, Int): String

Drops the last n characters of a string.

dropRight(xs: String, number: Int): String

Parameters

Parameters

Parameter

Description

xs: String

The string.

number: Int

The number n.

Example

dropRight("Apple", 0) # Returns "Apple"
dropRight("Apple", 1) # Returns "Appl"
dropRight("Apple", 3) # Returns "Ap"
dropRight("Apple", 5) # Returns an empty string
dropRight("Apple", 15) # Returns an empty string
indexOf(String, String): Int|Unit

Returns the index of the first occurrence of a substring.

indexOf(str: String, substr: String): Int|Unit

Parameters

Parameters

Parameter

Description

str: String

The string.

substr: String

The substring.

Example

indexOf("Apple","ple") # Returns 3
indexOf("Apple","le") # Returns 4
indexOf("Apple","e") # Returns 5
indexOf(String, String, Int): Int|Unit

Returns the index of the first occurrence of a substring after a certain index.

indexOf(str: String, substr: String, offset: Int): Int|Unit

Parameters

Parameters

Parameter

Description

str: String

The string.

substr: String

The substring.

offset: Int

The index.

Example

indexOf("Apple","ple", 1) # Returns 2
indexOf("Apple","le", 2) # Returns 3
indexOf("Apple","e", 3) # Returns 4
lastIndexOf(String, String): Int|Unit

Returns the index of the last occurrence of a substring.

lastIndexOf(str: String, substr: String): Int|Unit

Parameters

Parameters

Parameter

Description

str: String

The string.

substr: String

The substring.

Example

lastIndexOf("Apple","pp") # Returns 1
lastIndexOf("Apple","p") # Returns 2
lastIndexOf("Apple","s") # Returns unit
lastIndexOf(String, String, Int): Int|Unit

Returns the index of the last occurrence of a substring before a certain index.

lastIndexOf(str: String, substr: String, offset: Int): Int|Unit

Parameters

Parameters

Parameter

Description

str: String

The string.

substr: String

The substring.

offset: Int

The index.

Example

lastIndexOf("mamamama","ma",4) # Returns 4
lastIndexOf("mamamama","ma",3) # Returns 2
makeString(List[String], String): String

Concatenates list strings adding a separator.

makeString(arr: List[String], separator: String): String

Parameters

Parameters

Parameter

Description

arr: List [String]

List of strings to concatenate.

separator: String

Separator.

Example

makeString(["Apple","Orange","Mango"], " & ") # Returns "Apple & Orange & Mango"
size(String): Int

Returns the size of a string.

size(xs: String): Int

Parameters

Parameters

Parameter

Description

xs: String

The string.

Example

size("Ap") # Returns 2
size("Appl") # Returns 4
size("Apple") # Returns 5
split(String, String): List[String]

Splits a string delimited by a separator into a list of substrings.

split(str: String, separator: String): List[String]

Parameters

Parameters

Parameter

Description

str: String

The string.

separator: String

The separator.

Example

split("A.p.p.l.e", ".") # Returns ["A", "p", "p", "l", "e"]
split("Apple", ".") # Returns ["Apple"]
split("Apple", "") # Returns ["A", "p", "p", "l", "e"]
split("Ap.ple", ".") # Returns ["Ap","ple"]
take(String, Int): String

Takes the first n characters from a string.

take(xs: String, number: Int): String

Parameters

Parameters

Parameter

Description

xs: String

The string.

number: Int

The number n.

Example

take("Apple", 0) # Returns an empty string
take("Apple", 1) # Returns "A"
take("Apple", 3) # Returns "App"
take("Apple", 5) # Returns "Apple"
take("Apple", 15) # Returns "Apple"
take("Apple", -10) # Returns an empty string
takeRight(String, Int): String

Takes the last n characters from a string.

takeRight(xs: String, number: Int): String

Parameters

Parameters

Parameter

Description

xs: String

The string.

number: Int

The number n.

Example

takeRight("Apple", 0) # Returns an empty string
takeRight("Apple", 1) # Returns "A"
takeRight("Apple", 3) # Returns "ple"
takeRight("Apple", 5) # Returns "Apple"
takeRight("Apple", 15) # Returns "Apple"
Union Functions
Union Functions

Name

Description

Complexity

isDefined(T|Unit): Boolean

Checks if an argument is not unit

\(1\)

value(T|Unit): T

Gets a value from a union type argument. Fails if it is unit

\(2\)

valueOrElse(T|Unit, T): T

Returns a value from a union type argument if it’s not unit. Otherwise, returns the second argument

\(2\)

valueOrErrorMessage(T|Unit, String): T

Gets a value from a union type argument if it’s not unit. Otherwise, fails with the message specified in the second argument

\(2\)

isDefined(T|Unit): Boolean

Checks if an argument is not unit.

isDefined(a: T|Unit): Boolean

Parameters

Parameters

Parameter

Description

a: T|Unit

Argument to check.

value(T|Unit): T

Gets a value from a union type argument. Fails if it is unit.

value(a: T|Unit): T

Parameters

Parameters

Parameter

Description

a: T|Unit

Argument to return value from.

valueOrElse(T|Unit, T): T

Returns a value from a union type argument if it’s not unit. Otherwise, returns the second argument.

valueOrElse(t: T|Unit, t0: T): T

Parameters

Parameters

Parameter

Description

a: T|Unit

Argument to return value from.

t0: T

Returned if t is unit.

valueOrErrorMessage(T|Unit, String): T

Returns a value from a union type argument if it’s not unit. Otherwise, fails with the message specified in the second argument.

valueOrErrorMessage(a: T|Unit, msg: String): T

Parameters

Parameters

Parameter

Description

a: T|Unit

Argument to return value from.

msg: String

Error message.

Verification Functions
Verification Functions

Name

Description

Complexity

bn256groth16Verify(ByteVector, ByteVector, ByteVector): Boolean

Range of functions. Check zk-SNARK by groth16 protocol on the bn254 curve

\(800–1650\)

createMerkleRoot(List[ByteVector], ByteVector, Int) : ByteVector

Calculates the Merkle root hash for transactions of block

\(30\)

ecrecover(messageHash: ByteVector, signature: ByteVector)

Recovers public key from the message hash and the ECDSA digital signature

\(70\)

groth16Verify(ByteVector, ByteVector, ByteVector): Boolean

Range of functions. Check zk-SNARK by groth16 protocol on the bls12-381 curve

\(1200–2700\)

rsaVerify(digestAlgorithmType, ByteVector, ByteVector, ByteVector): Boolean

Range of functions. Check that the RSA digital signature is valid, i.e. it was created by the owner of the public key

\(500–1000\)

sigVerify(ByteVector, ByteVector, ByteVector): Boolean

Range of functions. Check that the Curve25519 digital signature is valid, i.e. it was created by the owner of the public key

\(47–200\)

bn256groth16Verify(ByteVector, ByteVector, ByteVector): Boolean

Range of functions. Check zk-SNARK by groth16 protocol on the bn254 curve. (Although the curve is called bn254 in the scientific literature, it is commonly referred to as bn256 in the code.)

bn256groth16Verify

Name

Max number of inputs

Complexity

bn256groth16Verify(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(16\)

\(1650\)

bn256groth16Verify_1inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(1\)

\(800\)

bn256groth16Verify_2inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(2\)

\(850\)

bn256groth16Verify_3inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(3\)

\(950\)

bn256groth16Verify_4inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(4\)

\(1000\)

bn256groth16Verify_5inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(5\)

\(1050\)

bn256groth16Verify_6inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(6\)

\(1100\)

bn256groth16Verify_7inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(7\)

\(1150\)

bn256groth16Verify_8inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(8\)

\(1200\)

bn256groth16Verify_9inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(9\)

\(1250\)

bn256groth16Verify_10inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(10\)

\(1300\)

bn256groth16Verify_11inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(11\)

\(1350\)

bn256groth16Verify_12inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(12\)

\(1400\)

bn256groth16Verify_13inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(13\)

\(1450\)

bn256groth16Verify_14inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(14\)

\(1550\)

bn256groth16Verify_15inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(15\)

\(1600\)

Parameters

Parameters

Parameter

Description

vk: ByteVector

Key for the check. Maximum size: 1) For bn256groth16Verify_<N>inputs function — \(256 + 32 × N\) bytes. 2) For bn256groth16Verify function — \(256 + 32 × 16 = 768\) bytes.

proof: ByteVector

Zero-knowledge proof. Fixed size: \(128\) bytes.

inputs: ByteVector

Zero-knowledge proof’s public inputs array. For example, array of UTXO hashes in case of shielded transactions. Maximum size: 1) For bn256groth16Verify_<N>inputs function – \(32 × N\) bytes. 2) For bn256groth16Verify function – \(512\) bytes.

createMerkleRoot(List[ByteVector], ByteVector, Int) : ByteVector

Calculates the Merkle root hash for transactions of block on the basis of the transaction hash and the sibling hashes of the Merkle tree. BLAKE2b-256 algorithm is used for hashing. To check for the transaction in the block, you need to compare the calculated hash with the transactionsRoot field in the block header. For more informtion see the transactions root hash.

createMerkleRoot(merkleProofs: List[ByteVector], valueBytes: ByteVector, index: Int): ByteVector

Parameters

Parameters

Parameter

Description

merkleProofs: List [ByteVector]

Array of sibling hashes of the Merkle tree. Up to \(16\) items, \(32\) bytes each.

valueBytes: ByteVector

Hash of transaction. Fixed size: \(32\) bytes. You can use blake2b256 function. The transaction must be hashed together with the signature.

index: Int

Index of the transaction in the block.

ecrecover(messageHash: ByteVector, signature: ByteVector)

Recovers public key from the message hash and the ECDSA digital signature based on the secp256k1 elliptic curve. Fails if the recovery failed. The public key is returned in uncompressed format (64 bytes). The function can be used to verify the digital signature of a message by comparing the recovered public key with the sender’s key.

ecrecover(messageHash: ByteVector, signature: ByteVector): ByteVector

Parameters

Parameters

Parameter

Description

messageHash: ByteVector

Keccak-256 hash of the message. Fixed size: \(32\).

signature: ByteVector

ECDSA digital signature. Fixed size: \(65\) bytes.

Example

Verify the transaction of the Ethereum blockchain using the following data:

  • The transaction.

  • The signature that is generated by the ecsign functions (r, s, and v bytes concatenation).

  • Sender public key.

func check(t: ByteVector, signature: ByteVector, publicKey: ByteVector) = {
 ecrecover(keccak256(t), signature) == publicKey
}
groth16Verify(ByteVector, ByteVector, ByteVector): Boolean

Range of functions. Check zk-SNARK by groth16 protocol.

groth16Verify

Name

Max number of inputs

Complexity

groth16Verify(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(16\)

\(2700\)

groth16Verify_1inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(1\)

\(1200\)

groth16Verify_2inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(2\)

\(1300\)

groth16Verify_3inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(3\)

\(1400\)

groth16Verify_4inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(4\)

\(1500\)

groth16Verify_5inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(5\)

\(1600\)

groth16Verify_6inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(6\)

\(1700\)

groth16Verify_7inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(7\)

\(1800\)

groth16Verify_8inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(8\)

\(1900\)

groth16Verify_9inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(9\)

\(2000\)

groth16Verify_10inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(10\)

\(2100\)

groth16Verify_11inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(11\)

\(2200\)

groth16Verify_12inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(12\)

\(2300\)

groth16Verify_13inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(13\)

\(2400\)

groth16Verify_14inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(14\)

\(2500\)

groth16Verify_15inputs(vk:ByteVector, proof:ByteVector, inputs:ByteVector): Boolean

\(15\)

\(2600\)

Parameters

Parameters

Parameter

Description

vk: ByteVector

Key for the check. Maximum size: 1) For groth16Verify_<N>inputs function — \(384 + 48 × N\) bytes. 2) For groth16Verify function — \(384 + 48 × 16 = 1152\) bytes.

proof: ByteVector

Zero-knowledge proof. Fixed size: \(192\) bytes.

inputs: ByteVector

Zero-knowledge proof’s public inputs array. For example, array of UTXO hashes in case of shielded transactions. Maximum size: 1) For groth16Verify_<N>inputs function – \(32 × N\) bytes. 2) For groth16Verify function – \(512\) bytes.

Example

groth16Verify(vk, proof, inputs)
rsaVerify(digestAlgorithmType, ByteVector, ByteVector, ByteVector): Boolean

Range of functions. Check that the RSA digital signature is valid, i.e. it was created by the owner of the public key.

rsaVerify

Name

Max message size

Complexity

rsaVerify(digest: digestAlgorithmType, message: ByteVector, sig: ByteVector, pub: ByteVector): Boolean

\(150\) kB

\(1000\)

rsaVerify_16Kb(digest: digestAlgorithmType, message: ByteVector, sig: ByteVector, pub: ByteVector): Boolean

\(16\) kB

\(500\)

rsaVerify_32Kb(digest: digestAlgorithmType, message: ByteVector, sig: ByteVector, pub: ByteVector): Boolean

\(32\) kB

\(550\)

rsaVerify_64Kb(digest: digestAlgorithmType, message: ByteVector, sig: ByteVector, pub: ByteVector): Boolean

\(64\) kB

\(625\)

rsaVerify_128Kb(digest: digestAlgorithmType, message: ByteVector, sig: ByteVector, pub: ByteVector): Boolean

\(128\) kB

\(750\)

The recommended RSA key module length is at least 2048 bits. Data can be hashed before signing using one of the following algorithms:

  • MD5

  • SHA-1

  • SHA-224

  • SHA-256

  • SHA-384

  • SHA-512

  • SHA3-224

  • SHA3-256

  • SHA3-384

  • SHA3-512

Parameters

Parameters

Parameter

Description

digest: digestAlgorithmType

The hashing algorithm applied to the data before signing. Acceptable values: 1) NOALG — data is not hashed. 2) MD5. 3) SHA1. 4) SHA224. 5) SHA256. 6) SHA384. 7) SHA512. 8) SHA3224. 9) SHA3256. 10) SHA3384. 11) SHA3512.

message: ByteVector

Signed data. Maximum size: 1) For rsaVerify_<N>Kb functions — \(N\) bytes. 2) For rsaVerify function — \(150\) bytes.

sig: ByteVector

Digital signature. Fixed size: \(25\) bytes.

pub: ByteVector

Binary public key. Fixed size: \(294\) bytes.

sigVerify(ByteVector, ByteVector, ByteVector): Boolean

Range of functions. Check that the Curve25519 digital signature is valid, i.e. it was created by the owner of the public key.

sigVerify

Name

Max message size

Complexity

sigVerify(message: ByteVector, sig: ByteVector, pub: ByteVector): Boolean

\(150\) kB

\(200\)

sigVerify_8Kb(message: ByteVector, sig: ByteVector, pub: ByteVector): Boolean

\(8\) kB

\(47\)

sigVerify_16Kb(message: ByteVector, sig: ByteVector, pub: ByteVector): Boolean

\(16\) kB

\(57\)

sigVerify_32Kb(message: ByteVector, sig: ByteVector, pub: ByteVector): Boolean

\(32\) kB

\(70\)

sigVerify_64Kb(message: ByteVector, sig: ByteVector, pub: ByteVector): Boolean

\(64\) kB

\(102\)

sigVerify_128Kb(message: ByteVector, sig: ByteVector, pub: ByteVector): Boolean

\(128\) kB

\(172\)

Parameters

Parameters

Parameter

Description

message: ByteVector

Signed data. Maximum size: 1) For sigVerify_<N>Kb functions — \(N\) bytes. 2) For sigVerify function — \(150\) bytes.

sig: ByteVector

Digital signature. Fixed size: \(25\) bytes.

pub: ByteVector

Binary public key. Fixed size: \(294\) bytes.

Exceptions

There is no exception handling in Ride: after an exception has been thrown, the script execution fails. The transaction can be either discarded or saved on the blockchain as failed, see the transaction validation article for details The throw function will terminate script execution immediately, with the provided text. There is no way to catch thrown exceptions.

throw("Here is exception text")

The idea of throw is to stop execution and send useful feedback to the user.

let a = 12
if (a != 100) then
 throw ("a is not 100, actual value is " + a.toString())
 else throw("A is 100")

Comments

To write comments use the pound sign.

let month = 7 # Sets the month

There are no multi-line comments.

Script Types

There are three types of scripts:

  • dApp script enables you to define сallable functions that can be called from other accounts, accept payments to the dApp, and perform various actions on the blockchain. Also dApp script can comprise a verifier function that allows or denies transactions and orders that are sent on behalf of the dApp account.

  • Account script allows or denies transactions and orders that are sent on behalf of the account (like a verifier function of a dApp script).

  • Asset script allows or denies transactions involving the asset.

Features of each script type are described in the table.

Script Types

#

dApp script

Account script

Asset script

Directives

{-# CONTENT_TYPE DAPP #-} {-# SCRIPT_TYPE ACCOUNT #-}

{-# CONTENT_TYPE EXPRESSION #-} {-# SCRIPT_TYPE ACCOUNT #-}

{-# CONTENT_TYPE EXPRESSION #-} {-# SCRIPT_TYPE ASSET #-}

Content

Set of definitions

Boolean expression

Boolean expression

this variable

Address structure containing dApp address

Address structure containing smart account address

Asset structure

Transaction or order that is checked

Check is performed by the verifier function only. Annotation of the function sets the name of the variable that contains the outgoing transaction or the order, for example: @Verifier(tx)

Built-in variable tx: Transaction|Order contains the outgoing transaction or the order

Build-in variable tx: Transaction contains the transaction involving the asset. Order check is not supported.

Proofs accessibility

1) Proofs of the outgoing transaction or the order are accessible to the verifier function. 2) Proofs of the invoke script transaction are inaccessible to the callable function

Accessible

Inaccessible

Blockchain data

1) Accessible to the callable function. 2) Accessible to the verifier function when checking a transaction. 3) Inaccessible to the verifier function when checking an order

1) Accessible when checking a transaction. 2) Inaccessible when checking an order

Accessible

dApp Script

dApp script enables you to define callable functions that can be called from other accounts by sending an invoke script transaction or by a dApp-to-dApp invocation. Callable functions can accept payments to the dApp and perform various actions on the blockchain. Also dApp script can comprise a verifier function that allows or denies transactions and orders that are sent on behalf of the dApp account. An account with a dApp script assigned to it is called a dApp.

dApp Script Format

The script code is composed of the following parts:

  • Directives

  • Auxiliary definitions

  • Callable function

  • Verifier function

_images/01_dApp-Script-Format.png
Directives

The dApp script should start with directives:

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ACCOUNT #-}

The above directives tell the compiler that:

  • The script uses the standard library version 5.

  • The script contains a set of definitions.

  • The script will be assigned to an account (not asset).

Auxiliary definitions

After the directives, you can define auxiliary variables and functions. These variables and functions are accessible within the entire script. Please note that functions without annotations cannot be called from other accounts. Let’s see an exaxmple:

let someConstant = 42
func doSomething() = {
 1+1
}
Callable Functions (dApp Script)

The callable function should be marked with the @Callable(i) annotation, where i is an invocation structure that contains fields of the script invocation that are accessible to the callable function. The variable name in the annotation is required even if the function does not use it. Callable function result is a set of script actions that are performed on the blockchain: adding/deleting/modifying entries to the account data storages, token transfers, issue/reissue/burning, and others. The result format and the available actions depend on the Standard library version used. For a detailed description, see the callable function article.

In the example below the callable function transfers 1 DecentralCoin to an account that called it and records the request information in the account data storage. If the same account tries to call the function again, the callable function throws an exception.

@Callable(i)
func faucet () = {
 let isKnownCaller =  match getBoolean(this, toBase58String(i.caller.bytes)) {
   case hist: Boolean =>
     hist
   case _ =>
     false
 }
 if (!isKnownCaller) then
 (
   [
     BooleanEntry(toBase58String(i.caller.bytes), true),
     ScriptTransfer(i.caller, 100000000, unit)
   ],
   unit
 )
 else throw("Can be used only once")
}
Verifier Function

Verifier function checks transactions and orders that are sent on behalf of the dApp account for compliance with the specified conditions (in other words it works similar to the account script). The verifier function should be marked with the @Verifier(tx) annotation, where tx is the transaction or the order that the function is currently checking. The variable name in the annotation is required even if the function does not use it. The verifier function has no arguments.Possible results of the verifier function are:

  • True (the transaction or the order is allowed),

  • False (the transaction or the order is denied),

  • An error (the transaction or the order is denied).

For a detailed description, see verifier function the article. Using the match … case operator, you can set up different conditions depending on the type of the transaction/order. For example, the following function allows transfer transactions and denies orders and other types of transactions.

@Verifier(tx)
func verify() = {
 match tx {
   case ttx:TransferTransaction => sigVerify(ttx.bodyBytes, ttx.proofs[0], ttx.senderPublicKey)
   case _ => false
 }
}

dApp script that has no verifier function performs default verification, that is, checking that the transaction or the order is indeed signed by this account.

Failed Transactions

If the callable function failed or threw an exception when a block generator adds the transaction to a block, such a transaction is saved on the blockchain and marked with the attribute «applicationStatus»: «script_execution_failed», provided that: There are two annotations: @Callable(i) and @Verifier(tx). The variable name in the annotation is required even if the function does not use it. An annotated function cannot be called inside a dApp script.

The transaction sender is charged a fee. The transaction doesn’t entail any other changes on the blockchain.

Data Accessible to dApp Script

Data accessible to the callable function:

  • Particular fields of the invocation, including payments, fee, sender address and public key. See the invocation article for the fields description. Proofs are inaccessible.

  • Blockchain data: current height, account balances, entries in account data storages, parameters of tokens, etc.

Data accessible to the verifier function:

  • Fields of the current verified transaction/order, including proofs. The built-in variable tx contains this transaction or order. The set of fields depends on the type of transaction/order, see the transaction structures chapter and order article.

  • Blockchain data: current height, account balances, entries in account data storages, parameters of tokens, etc.

Annotations

Annotation is a form of metadata that is added to a function of a dApp script. At the present moment, there are two annotations: @Callable(i) and @Verifier(tx). The variable name in the annotation is required even if the function does not use it. An annotated function cannot be called inside a dApp script.

@Callable(i)

Annotation of a callable function. Variable i contains an invocation structure representing certain fields of the invocation.

@Verifier(tx)

Annotation of a verifier function. Variable tx contains a structure of transaction or order sent from a dApp’s account.

Callable Function

Callable function is a dApp script function which can be invoked by a invoke script transaction or an invoke or reentrantInvoke functions (see details in the dApp-to-dApp invocation functions article).

  • Add, modify, delete dApp account data storage entries.

  • Transfer tokens.

  • Add, modify, delete dApp.

  • Issue tokens on behalf of the dApp, reissue and burn tokens.

  • Setup sponsorship.

  • Lease, cancel lease.

The callable function can return a value that is passed to the invoking function in case of the dApp-to-dApp invocation. The invocation can contain payments to dApp. Tokens obtained in these payments can be used in script actions performed by the callable function and in payments attached to nested invocations.

Annotation

The callable function should be marked with the @Callable(i) annotation, where i is an invocation structure that contains invocation fields that are available to the callable function. The variable name in the annotation is required even if the callable function does not use it.

Arguments

The callable function can have arguments of the following types:

Invocation Result

The callable function invocation result is a tuple of two elements: List of script actions. Actions are executed in the same order as the elements in the list. Return value that is passed to the invoking function in case of the dApp-to-dApp invocation.

Let’s see an example of invocation of an invocation result:

(
  [
    BooleanEntry("key1", true),
    IntegerEntry("key2", 42),
    StringEntry("key3", "some string"),
    BinaryEntry("key4", base58'encoded'),
    DeleteEntry("key5"),
    ScriptTransfer(Address(base58'3Ms8fSfAxBLDjKvNVgACRzQoBLCtCWxtawu'), 100, base58'someAssetid'),
    Issue("RegularToken", "This is an ordinary token", 10000, 2, true),
    Reissue("4ZzED8WJXsvuo2MEm2BmZ87Azw8Sx7TVC6ufSUA5LyTV", 1000, true),
    Burn("4ZzED8WJXsvuo2MEm2BmZ87Azw8Sx7TVC6ufSUA5LyTV", 1000)]
    SponsorFee("4ZzED8WJXsvuo2MEm2BmZ87Azw8Sx7TVC6ufSUA5LyTV", 300),
    Lease(Address(base58'3Mn5hzck8nYd52Ytd2ZjzoiQLVoMcn1VAs9',1000),
    LeaseCancel(base58'Pxaf8pGKHS5ufGhqjmwRRcHQtC9T3h4d1XaJMnkhR1Vt')
  ],
  42
)
Script Actions (Callable Function)

Script actions performed by the callable function are set by Ride structures.

Script Actions (Callable Function)

Ride structure that sets action

Description

BinaryEntry, BooleanEntry, IntegerEntry, StringEntry

Adding/modifying the entry. The type of structure must match the type of entry to be added/changed. 1) If there is no entry in the account data storage with the key specified in the structure, the entry will be added. 2) If the entry is present in the account data storage, it will be modified.

DeleteEntry

Entry deletion

Issue

Token issue

Reissue

Token reissue

Burn

Token burn

SponsorFee

Sponsorship setup

ScriptTransfer

Token transfer

Lease

Lease

LeaseCancel

Lease cancellation

Limitations (Callable Function)
  • The maximum total number of Issue, Reissue, Burn, SponsorFee, ScriptTransfer, Lease, LeaseCancelscript actions executed by all callable functions in a single transaction is \(30\).

  • The maximum total number of BinaryEntry, BooleanEntry, IntegerEntry, StringEntry, DeleteEntryscript actions executed by all callable functions in a single transaction is \(100\).

  • The maximum number of the payments to dApp in invocation is \(10\).

See also the limitations article.

Example

The example listed below is a wallet application which allows sending DecentralCoins to a certain address and withdrawing them (withdrawing others” DecentralCoins is prevented). There are two callable functions in the example(deposit and withdraw):

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ACCOUNT #-}

@Callable(i)
func deposit() = {
 let pmt =
   if i.payments.size() == 1 then
     i.payments[0]
   else throw("Attached payment is required")
 if (isDefined(pmt.assetId))
   then throw("Works with DecentralCoins only")
   else {
     let currentKey = toBase58String(i.caller.bytes)
     let currentAmount = match getInteger(this, currentKey) {
       case a:Int => a
       case _ => 0
     }
     let newAmount = currentAmount + pmt.amount
     (
       [
         IntegerEntry(currentKey, newAmount)
       ],
       unit
     )
   }
}

@Callable(i)
func withdraw(amount: Int) = {
 let currentKey = toBase58String(i.caller.bytes)
 let currentAmount = match getInteger(this, currentKey) {
   case a:Int => a
   case _ => 0
 }
 let newAmount = currentAmount - amount
 if (amount < 0)
   then throw("Can't withdraw negative amount")
   else if (newAmount < 0)
     then throw("Not enough balance")
     else (
       [
         IntegerEntry(currentKey, newAmount),
         ScriptTransfer(i.caller, amount, unit)
       ],
       unit
     )
}

@Verifier(tx)
func verify() = false
Threshold for Saving Failed Transactions

The Invoke Script transaction is saved on the blockchain and a fee is charged for it even if the dApp script or the asset script fails when a block generator adds the transaction to a block, provided that the sender’s signature or account script verification passed.

However, if the callable function failed or threw an exception before the complexity of performed calculations exceeded the threshold for saving failed transactions, the transaction is discarded and the fee is not charged.

Verifier Function

Verifier function is a function of dApp script that is responsible for verification of transactions and orders sent from a dApp account. The verifier function does the same as an account script. dApp script can have only one verifier function. The verifier function should be adorned with the @Verifier(tx) annotation, where tx: Transaction|Order is the transaction or the order that the function is currently checking. Verifier function has no arguments. Verifier function can have one of the following execution results:

  • True (the transaction or the order is allowed).

  • False (the transaction or the order is denied).

  • an error (the transaction or the order is denied).

dApp that has no verifier function performs default verification, that is, checking that the first proof of the transaction/order has the correct sender’s signature. The following function does the same as the default implementation:

@Verifier(tx)
func verify() = {
 sigVerify(tx.bodyBytes, tx.proofs[0], tx.senderPublicKey)
}

If the verifier function is defined, only verification by this function is performed, proofs are not checked additionally.

Example

dApp with the verifier function listed below only allows transfer transaction with an amount of token lower than 100. Orders and other transactions are denied. The match operator is used to specify verification rules depending on the type of the transaction/order.

@Verifier(tx)
func verify() = {
   match tx {
     case ttx:TransferTransaction => ttx.amount < 100 && sigVerify(ttx.bodyBytes, ttx.proofs[0], ttx.senderPublicKey)
     case _ => false
   }
}

See available fields for each transaction type in the transaction structures article.

Account Script

Account script verifies transactions and orders that are sent on behalf of the account. That is, the account script allows or denies the transaction or the order depending on whether it meets the specified conditions.

Account Script Format

The script code is composed of the following parts:

  • Directives

  • Auxiliary definitions

  • Boolean expression

_images/02_Account-Script-Format.png
Directives

The account script should start with directives:

{- # STDLIB_VERSION 5 # -}
{- # CONTENT_TYPE EXPRESSION # -}
{- # SCRIPT_TYPE ACCOUNT # -}

The above directives tell the compiler that:

  • The script uses the standard library version 5.

  • The script contains a boolean expression.

  • The script will be assigned to an account (not asset).

Auxiliary Definitions

After the directives, you can define auxiliary variables and functions. Let’s see an example:

let someConstant = 42
func doSomething () = {
 height + someConstant
}
Boolean Expression

The expression checks transactions and orders that are sent on behalf of the account for compliance with the specified conditions. If the conditions are not met, the transaction/order is denied. Possible results of evaluating the expression are:

  • True (the transaction or the order is allowed),

  • False (the transaction or the order is denied),

  • An error (the transaction or the order is denied).

Using the match … case, you can set up different conditions depending on the type of the transaction/order. For example, the following expression prohibits sending orders and changing the account script, and allows other transactions, provided that the array of confirmations (proofs) contains the correct signature of the account at position \(0\):

match tx {
 case t: Order | SetScriptTransaction => false
 case _ => sigVerify (tx.bodyBytes, tx.proofs [0], tx.senderPublicKey)
}

Data Accessible to Account Script

The following data can be used for checks:

  • Fields of the current verified transaction/order, including proofs. The built-in variable tx contains this transaction or order. The set of fields depends on the type of transaction/order, see the transaction structures chapter and order article.

  • Blockchain data: current height, account balances, entries in account data storages, parameters of tokens, etc.

Asset Script

Asset script verifies transactions within the asset (token), that is, allows or denies the transaction depending on the specified conditions. Asset with a script assigned to it is called a smart asset. Keep the following in mind:

  • The asset script can only verify transactions, but not orders.

  • If a token is issued without a script, then the script cannot be added later.

  • The script cannot be removed, so it is impossible to turn a smart asset into a regular one.

  • Smart asset cannot be a sponsored asset.

Asset Script Format

The script code is composed of the following parts:

  • Directives

  • Auxiliary definitions

  • Boolean expression

_images/03_Asset-Script-Format.png
Directives

The asset script should start with directives:

{- # STDLIB_VERSION 5 # -}
{- # CONTENT_TYPE EXPRESSION # -}
{- # SCRIPT_TYPE ACCOUNT # -}

The above directives tell the compiler that:

  • The script uses the standard library version 5.

  • The script contains a boolean expression.

  • The script will be assigned to an asset.

Auxiliary Definitions

After the directives, you can define auxiliary variables and functions. Let’s see an example:

let someConstant = 42
func doSomething () = {
 height + someConstant
}
Boolean Expression

The expression checks transactions and orders that are sent on behalf of the account for compliance with the specified conditions. If the conditions are not met, the transaction/order is denied. Possible results of evaluating the expression are:

  • True (the transaction or the order is allowed),

  • False (the transaction or the order is denied),

  • An error (the transaction or the order is denied).

Using the match … case, you can set up different conditions depending on the type of the transaction/order. For example, the following expression prohibits sending orders and changing the account script, and allows other transactions, provided that the array of confirmations (proofs) contains the correct signature of the account at position \(0\):

match tx {
 case t : SetAssetScriptTransaction => false
 case _ => true
}

Failed Transactions

If the asset script denies the Exchange transaction when a block generator adds the transaction to a block (provided that the sender signature verification or the account script verification passed), the transaction is saved on the blockchain but marked as failed («applicationStatus»: «script_execution_failed»). The sender of the transaction (matcher) is charged a fee. The transaction doesn’t entail any other changes in balances, in particular, the order senders don’t pay the matcher fee.

If the asset script denies the Invoke Script transaction when a block generator adds the transaction to a block (provided that the sender signature verification or the account script verification passed and the complexity of calculations performed by dApp script exceeded the threshold for saving failed transactions), the transaction is saved on the blockchain but marked as failed («applicationStatus»: script_execution_failed»). The transaction sender is charged a fee. The transaction doesn’t entail any other changes on the blockchain.

Data Accessible to Asset Script

The following data can be used for checks:

  • Fields of the current verified transaction, excluding proofs. The built-in variable tx contains this transaction. The set of fields depends on the type of transaction, see the transaction structures chapter.

  • Blockchain data: current height, account balances, entries in account data storages, parameters of tokens, etc.

Structures

All structures in Ride are built-in — you cannot create your own structures. All structures have constructors.

Let’s see an example of a code that creates an instance of the IntegerEntry structure and reads its key and value:

let data = IntegerEntry("Age", 33)
let key  = data.key
let val = data.value

Script Actions

Script actions are executed, that is, they make changes on the blockchain only if they are included in the resulting expression of the callable function. See more details in the callable function article.

Script Actions

Action

Description

BinaryEntry

Add or modify a binary entry of the account data storage.

BooleanEntry

Add or modify a boolean entry.

Burn

Burn a token.

DeleteEntry

Delete an entry.

IntegerEntry

Add or modify an integer entry.

Issue

Issue a token.

Lease

Lease.

LeaseCancel

Cancel lease.

Reissue

Reissue a token.

ScriptTransfer

Transfer a token.

SponsorFee

Set up a sponsorship.

StringEntry

Add or modify a string entry.

Available script actions depend on the standard library version used.

BinaryEntry

BinaryEntry is a structure that sets key and value of binary entry account data storage. Adding or changing an entry is performed only if the structure is included in the callable function result.

Constructor

BinaryEntry(key: String, value: ByteVector)

Fields

BinaryEntry Fields

#

Name

Data type

Description

\(1\)

key

String

Entry key. The maximum size is \(400\) bytes.

\(2\)

value

ByteVector

Entry value. The maximum size is \(5\) Kbytes.

BooleanEntry

BooleanEntry is a structure that sets the key and value of the account data storage boolean entry. Adding or changing an entry is performed only if the structure is included in the callable function result.

Constructor

BooleanEntry(key: String, value: Boolean)

Fields

BooleanEntry Fields

#

Name

Data type

Description

\(1\)

key

String

Entry key. The maximum size is \(400\) bytes.

\(2\)

value

Boolean

Entry value.

Burn

Burn is a structure that sets the parameters of the token burning. The token burning is performed only if the structure is included in the callable function result. If the token is a smart asset, the asset script verifies the Burn action as if it were BurnTransaction with the fee of \(0\) and the version of \(0\). If the asset script denies the action, then the transaction that invoked the dApp script is either denied or saved on the blockchain as failed, see the transaction validation.

Constructor

Burn(assetId: ByteVector, quantity: Int)

Fields

Burn Fields

#

Name

Data type

Description

\(1\)

assetId

ByteVector

ID of the token to burn.

\(2\)

quantity

Int

Amount of the token.

DeleteEntry

DeleteEntry is a structure that sets the parameters of deletion of entry from the account data storage. Deleting an entry is performed only if the structure is included in the callable function result.

Constructor

DeleteEntry(key: String)

Fields

DeleteEntry Fields

#

Name

Data type

Description

\(1\)

key

String

Entry key. The maximum size is \(400\) bytes.

Example

{-# STDLIB_VERSION 5 #-}
{-# SCRIPT_TYPE ACCOUNT #-}

@Callable(inv)
func default() = {
 (
   [
     DeleteEntry(inv.caller.toString())
   ],
   unit
 )
}

IntegerEntry

IntegerEntry is a structure that sets the key and value of account data storage integer entry. Adding or changing an entry is performed only if the structure is included in the callable function result.

Constructor

IntegerEntry(key: String, value: Int)

Fields

IntegerEntry Fields

#

Name

Data type

Description

\(1\)

key

String

Entry key. The maximum size is \(400\) bytes.

\(2\)

value

Int

Entry value.

Issue

Issue is a structure that sets the parameters of the token issue. The token issue is performed only if the structure is included in the callable function result. The minimum fee for an invoke script transaction is increased by \(1\) DecentralCoin for each issued asset that is not NFT. You can get the ID of the issued token using the calculateAssetId function.

Constructor

Issue(name: String, description: String, quantity: Int, decimals: Int, isReissuable: Boolean, compiledScript: Script|Unit, nonce: Int)

or

Issue(name: String, description: String, quantity: Int, decimals: Int, isReissuable: Boolean)

In the second case, compiledScript = unit and nonce = 0 values are inserted automatically.

Fields

Issue Fields

#

Name

Data type

Description

\(1\)

name

String

Token name.

\(2\)

description

String

Token description.

\(3\)

quantity

Int

Amount of the token. Set to \(1\) for NFT.

\(4\)

decimals

Int

Number of digits in decimal part. Set to \(0\) for NFT.

\(5\)

isReissuable

Boolean

Reissue ability flag. Set to \(0\) for NFT.

\(6\)

compiledScript

Script | Unit

Set it to unit. Smart asset issue is currently unavailable.

\(7\)

nonce

Int

Nonce that is used for token ID generation. If the callable function issues several tokens with the same parameters, you should use different nonce.

Example

Regular Token Issue

Issue("RegularToken", "This is an ordinary token", 10000, 2, true)

The structure sets the following parameters of token:

  • Name: RegularToken

  • Description: This is an ordinary token

  • Amount of tokens to issue: \(100\) (value of \(10 000\) is specified in the minimum fraction — “cents”)

  • Amount of decimals: \(2\)

  • Reissue ability: yes

Multiple Token Issue

(
 [
   Issue("RegularToken", "This is an ordinary token", 10000, 2, true, unit, 0),
   Issue("RegularToken", "This is an ordinary token", 10000, 2, true, unit, 1)
 ],
 unit
)

NFT Issue

Issue("UberToken", "The ultimate token.", 1, 0, false)

The structure sets the following parameters of token:

  • Name: UberToken

  • Description: The ultimate token.

  • Amount of tokens to issue: \(1\)

  • Amount of decimals: \(0\)

  • Reissue ability: no

Lease

Lease is a structure that sets the lease parameters. The lease is performed only if the structure is included in the callable function result. More about lease. You can get the lease ID using the calculateLeaseId function.

Constructor

Lease(recipient: Address|Alias, amount: Int, nonce: Int)

or

Lease(recipient: Address|Alias, amount: Int)

In the second case, nonce = \(0\) is inserted automatically.

Fields

Lease Fields

#

Name

Data type

Description

\(1\)

recipient

Address | Alias

Lessee address or alias.

\(2\)

amount

Int

Amount of DecentralCoins to lease (that is, amount of Decentralites multiplied by \(10^{8}\)).

\(7\)

nonce

Int

Nonce that is used for lease ID generation. If the callable function creates several leases with the same parameters, you should use different nonces.

Example

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ACCOUNT #-}

@Callable(i)
func foo() = {
 let lease = Lease(Alias("merry"),100000000)
 let id = calculateLeaseId(lease)
 (
   [
     lease,
     BinaryEntry("lease", id)
   ],
   unit
 )
}

LeaseCancel

LeaseCancel is a structure that sets the lease cancellation parameters. The lease cancellation is performed only if the structure is included in the callable function result.

Constructor

LeaseCancel(leaseId: ByteVector)

Fields

LeaseCancel Fields

#

Name

Data type

Description

\(1\)

leaseId

ByteVector

Lease ID

Reissue

Reissue is a structure that sets the parameters of the token reissue. The token reissue is performed only if the structure is included in the callable function result. The token reissue is only available for an asset that is issued by a dApp account. If the token is a smart asset, the asset script verifies the Reissue action as if it were ReissueTransaction with the fee of 0 and the version of 0. If the asset script denies the action, then the transaction that invoked the dApp script is either denied or saved on the blockchain as failed, see the transaction validation.

Constructor

Reissue(assetId: ByteVector, quantity: Int, isReissuable: Boolean)

Fields

Reissue Fields

#

Name

Data type

Description

\(1\)

assetId

ByteVector

ID of the token to reissue.

\(2\)

quantity

Int

Amount of the token.

\(3\)

isReissuable

Boolean

Reissue ability flag.

ScriptTransfer

ScriptTransfer is a structure that sets the parameters of the token transfer. The token transfer is performed only if the structure is included in the callable function result. If the token is a smart asset, the asset script verifies the ScriptTransfer action as if it were TransferTransaction with the fee of \(0\) and the version of \(0\). If the asset script denies the action, then the transaction that invoked the dApp script is either denied or saved on the blockchain as failed, see the transaction validation.

Constructor

ScriptTransfer(recipient: Address|Alias, amount: Int, asset: ByteVector|Unit)

Fields

ScriptTransfer Fields

#

Name

Data type

Description

\(1\)

recipient

Address | Alias

Address or the alias of a recipient of tokens.

\(2\)

amount

Int

Number of tokens.

\(3\)

asset

ByteVector | Unit

ID of the token.

SponsorFee

SponsorFee is a structure that sets up sponsorship. For information about sponsorship, see the sponsored fee article. The sponsorship setup is performed only if the structure is included in the resulting expression of the callable function. See details in the callable function article. The sponsorship setup is only available if the asset is issued by a dApp account (by the same script invocation as well) and is not a smart asset.

Constructor

SponsorFee(assetId: ByteVector, minSponsoredAssetFee: Int|Unit)

Fields

SponsorFee Fields

#

Name

Data type

Description

\(1\)

assetId

ByteVector

Asset ID

\(2\)

minSponsoredAssetFee

ByteVector | Unit

Amount of sponsored asset that is equivalent to 0.001 DecentralCoins, specified in the minimum fraction (“cent”) of the sponsored asset. unit — disable the sponsorship.

Example

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ACCOUNT #-}

@Callable(i)
func issueAndSponsor() = {
 let issue = Issue("Spring", "", 100000, 2, true, unit, 0)
 let id = calculateAssetId(issue)
 (
   [
     issue,
     SponsorFee(id, 300)
   ],
   unit
 )
}

The issueAndSponsor callable function issues an asset and enables sponsorship. The minimum fee in sponsored assets is \(3\) Spring.

StringEntry

StringEntry is a structure that sets key and value of account data storage string entry. Adding or changing an entry is performed only if the structure is included in the callable function result.

Constructor

BinaryEntry(key: String, value: String)

Fields

StringEntry Fields

#

Name

Data type

Description

\(1\)

key

String

Entry key. The maximum size is \(400\) bytes.

\(2\)

value

String

Entry value. The maximum size is \(5\) Kbytes.

Common Structures

Common Structures

Name

Description

Address

Account address.

Alias

Alias.

Asset

Token info.

AssetPair

Pair of tokens of an order within the order structure.

AttachedPayment

Payment attached to the script invocation and available to the callable function.

BalanceDetails

Account balance in DecentralCoins.

BlockInfo

Block header.

Invocation

Script invocation fields that the callable function can use.

Order

Order

Transfer

Transfer within the MassTransferTransaction structure.

Address

Structure of an address.

Constructor

Address(bytes: ByteVector)

Fields

Address Fields

#

Name

Data type

Description

\(1\)

bytes

ByteVector

Array of bytes of the address.

Example

Get all types of balance in DecentralCoins for the current account (in a dApp script or an account script):

wavesBalance(this)

For any account:

let address=base58'3N4iKL6ikwxiL7yNvWQmw7rg3wGna8uL6LU'
wavesBalance(Address(address))

Get an entry value by key from the account data storage:

let address2=base58'3N6dFJ6XBQsWz1VV1i5aW4CyYpVKc39MUGZ'
getBoolean(Address(address2),"allow_orders")

Convert the address that invoked the function to a base58 string:

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ACCOUNT #-}

@Callable(i)
func foo(question: String) = {
 let callerAddress = toBase58String(i.caller.bytes)
 ...
}

Check the recipient’s address in the transfer transaction:

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE EXPRESSION #-}
{-# SCRIPT_TYPE ACCOUNT #-}

# Bank dApp address
let BANK = base58'3MpFRn3X9ZqcLimFoqNeZwPBnwP7Br5Fmgs'

match (tx) {
 case t: TransferTransaction => addressFromRecipient(t.recipient).bytes == BANK
 case _ => false
}

Alias

Structure of an alias.

Constructor

Alias(alias: String)

Fields

Alias Fields

#

Name

Data type

Description

\(1\)

alias

String

Alias

Example

let alias = Alias("merry")
addressFromRecipient(alias)

Asset

Structure of a token. The structure is returned by the assetInfo built-in function.

Constructor

Asset(id: ByteVector, quantity: Int, decimals: Int, issuer: Address, issuerPublicKey: ByteVector, reissuable: Boolean, scripted: Boolean, minSponsoredFee: Int|Unit, name: String, description: String)

Fields

Asset Fields

#

Name

Data type

Description

\(1\)

id

ByteVector

Token ID.

\(2\)

quantity

Int

Amount of issued token, multiplied by \(10^{decimals}\). Up to \(9 223 372 036 854 775 806\).

\(3\)

decimals

Int

Number of decimal places, \(0\) to \(8\).

\(4\)

issuer

Address

Address of the account that issued a token.

\(5\)

issuerPublicKey

ByteVector

Public key of the account that issued a token.

\(6\)

reissuable

Boolean

true — token can be reissued, false — cannot be reissued.

\(7\)

scripted

Boolean

true — smart asset, false — regular token.

\(8\)

minSponsoredFee

Int | Unit

Amount of asset that is equivalent to \(0.001\) DecentralCoins (\(100,000\) Decentralites), specified in the minimum fraction (“cents”) of asset. See the Sponsored fee article. unit: sponsorship is disabled.

\(9\)

name

String

Token name, up to \(16\) characters.

\(10\)

description

String

Token description, up to \(1000\) characters.

Example

Get the account balance in a given asset:

let address=base58'3Mw48B85LvkBUhhDDmUvLhF9koAzfsPekDb'
let assetId=base58'GpxmxorKXLz1V7xootrvGyFgqP2tTTBib5HEm8QGZTHX'
assetBalance(Address(address), assetId)

AssetPair

Structure of a pair of tokens of an order within the order structure.

Constructor

AssetPair(amountAsset: ByteVector|Unit, priceAsset: ByteVector|Unit)

Fields

AssetPair Fields

#

Name

Data type

Description

\(1\)

amountAsset

ByteVector | Unit

The first token of a pair.

\(2\)

priceAsset

ByteVector | Unit

The second token of a pair.

Example

Get the account balance in a given asset:

let address=base58'3Mw48B85LvkBUhhDDmUvLhF9koAzfsPekDb'
let assetId=base58'GpxmxorKXLz1V7xootrvGyFgqP2tTTBib5HEm8QGZTHX'
assetBalance(Address(address), assetId)

AttachedPayment

Structure of a payment attached to the script invocation and available to the callable function. The structure is used in:

Constructor

AttachedPayment(assetId: ByteVector|Unit, amount: Int)

Fields

AttachedPayment Fields

#

Name

Data type

Description

\(1\)

assetId

ByteVector | Unit

ID of a token.

\(2\)

amount

Int

Payment amount.

BalanceDetails

Structure that contains DecentralCoins balances of account. The structure is returned by the wavesBalance built-in function. For description of balance types, see the account balance article.

Constructor

BalanceDetails(available: Int, regular: Int, generating: Int, effective: Int)

Fields

BalanceDetails Fields

#

Name

Data type

Description

\(1\)

available

Int

Available balance.

\(2\)

regular

Int

Regular balance.

\(3\)

generating

Int

Generating balance.

\(4\)

effective

Int

Effective balance.

All balances are given in Decentralites.

BlockInfo

Structure containing block headers. The structure is returned by the blockInfoByHeight built-in function.

Constructor

BlockInfo(timestamp: Int, height: Int, baseTarget: Int, generationSignature: ByteVector, generator: Address, generatorPublicKey: ByteVector, vrf: ByteVector|Unit)

Fields

BlockInfo Fields

#

Name

Data type

Description

\(1\)

timestamp

Int

Block timestamp.

\(2\)

height

Int

Block height.

\(3\)

baseTarget

Int

Base target.

\(4\)

generationSignature

ByteVector

Generation signature.

\(5\)

generator

Address

Address of the account that created a block.

\(6\)

generatorPublicKey

ByteVector

Public key of the account that created a block.

\(7\)

vrf

ByteVector | Unit

VRF for block version 5, unit otherwise.

Invocation

Structure that contains the fields of the script invocation that the callable function can use.

Constructor

Invocation(caller: Address, callerPublicKey: ByteVector, originCaller: Address, originCallerPublicKey: ByteVector, payments: List[AttachedPayment], transactionId: ByteVector, fee: Int, feeAssetId: ByteVector|Unit)

Fields

The field values depend on how the callable function is invoked. If the callable function is invoked by an invoke script transaction:

Invocation Fields 1

#

Name

Data type

Description

\(1\)

caller

Address

Address of the account that sent the invoke script transaction.

\(2\)

callerPublicKey

ByteVector

Public key of the account that sent the invoke script transaction.

\(3\)

originCaller

Address

Duplicates the caller field.

\(4\)

originCallerPublicKey

ByteVector

Duplicates the callerPublicKey field.

\(5\)

payments

List [AttachedPayment]

Payments indicated in the invoke script transaction.

\(6\)

transactionId

ByteVector

ID of the invoke script transaction.

\(7\)

fee

Int

Transaction fee.

\(8\)

feeAssetId

ByteVector | Unit

ID of the fee token.

If the callable function is invoked by the invoke or reentrantInvoke function (see the dApp-to-dApp invocation article):

Invocation Fields 2

#

Name

Data type

Description

\(1\)

caller

Address

Address of the dApp that invokes the callable function.

\(2\)

callerPublicKey

ByteVector

Public key of the dApp that invokes the callable function.

\(3\)

originCaller

Address

Address of the account that sent the Invoke Script transaction.

\(4\)

originCallerPublicKey

ByteVector

Public key of the account that sent the Invoke Script transaction.

\(5\)

payments

List [AttachedPayment]

Payments indicated in the invoke or reentrantInvoke function.

\(6\)

transactionId

ByteVector

ID of the Invoke Script transaction.

\(7\)

fee

Int

Transaction fee.

\(8\)

feeAssetId

ByteVector | Unit

ID of the fee token.

The originCaller, originCallerPublicKey, transactionId, fee, and feeAssetId values are the same for all dApp-to-dApp invocations within a single Invoke Script transaction.

Example

The following function checks that the first payment in the Invoke Script transaction is at least 1 DecentralCoin or 5 in the specified asset.

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE DAPP #-}
{-# SCRIPT_TYPE ACCOUNT #-}

func isPaymentOk(i: Invocation) = {
 let acceptableAssetId = base58'3JmaWyFqWo8YSA8x3DXCBUW7veesxacvKx19dMv7wTMg'
 if (size(i.payments) == 0) then {
   throw("Payment not attached")
 } else {
   let p = i.payments[0]
   match p.assetId {
     case assetId: ByteVector => assetId == acceptableAssetId && p.amount >= 500000000
     case _ => p.amount >= 100000000
   }
 }
}

@Callable(i)
func foo() = {
 if isPaymentOk(i) then ([],unit) else throw("Wrong payment amount or asset")
}

Order

Structure of an order dApp-to-dApp invocation. The structure is used:

Constructor

Order(id: ByteVector, matcherPublicKey: ByteVector, assetPair: AssetPair, orderType: Buy|Sell, price: Int, amount: Int, timestamp: Int, expiration: Int, matcherFee: Int, matcherFeeAssetId: ByteVector|Unit, sender: Address, senderPublicKey: ByteVector, bodyBytes: ByteVector, proofs: List[ByteVector])

Fields

Order Fields

#

Name

Data type

Description

\(1\)

id

ByteVector

ID of an order.

\(2\)

matcherPublicKey

ByteVector

Public key of a matcher.

\(3\)

assetPair

AssetPair

Pair of tokens.

\(4\)

orderType

Buy|Sell

Type of an order — selling or buying.

\(5\)

price

Int

Price of a token to exchange.

\(6\)

amount

Int

Number of tokens to exchange.

\(7\)

timestamp

Int

Unix time of the validation of an order by a matcher.

\(8\)

expiration

Int

Unix time when an uncompleted order will be cancelled.

\(9\)

matcherFee

Int

Transaction fee.

\(10\)

matcherFeeAssetId

ByteVector | Unit

Token of a transaction fee. It can only be DecentralCoins.

\(11\)

sender

Address

Address of the sender of an order.

\(12\)

senderPublicKey

ByteVector

Public key of the sender of an order.

\(13\)

bodyBytes

ByteVector

Array of bytes of an order.

\(14\)

proofs

List [ByteVector]

Array of proofs.

Example

The script below enables buying from a sender’s account:

  • Only the specified asset.

  • Only at a given price.

  • Only for DecentralCoins.

{-# STDLIB_VERSION 5 #-}
{-# CONTENT_TYPE EXPRESSION #-}
{-# SCRIPT_TYPE ACCOUNT #-}

let myAssetId = base58'8LLpj6yQLUu37KUt3rVo1S69j2gWMbgbM6qqgt2ac1Vb'

match tx {
  case o: Order =>
   let isDecentralChainPriceAsset = !isDefined(o.assetPair.priceAsset)
   let rightPair = (o.assetPair.amountAsset == myAssetId) && isDecentralChainPriceAsset
   sigVerify(o.bodyBytes, o.proofs[0], o.senderPublicKey)
   && rightPair
   && o.price == 500000
   && o.orderType == Buy
  case _ => false
}

Transfer

Structure of a single transfer within the MassTransferTransaction structure.

Constructor

Transfer(recipient: Address|Alias, amount: Int)

Fields

Transfer Fields

#

Name

Data type

Description

\(1\)

recipient

Address | Alias

Address of a recipient of tokens.

\(2\)

amount

Int

Number of tokens.

Transaction Structures

Tokenization

Tokenization

Transaction type ID

Name

Description

\(3\)

IssueTransaction

Structure of issue transaction.

\(5\)

ReissueTransaction

Structure of reissue transaction.

\(6\)

BurnTransaction

Structure of burn transaction.

\(15\)

SetAssetScriptTransaction

Structure of set asset script transaction.

\(17\)

UpdateAssetInfoTransaction

Structure of update asset info transaction.

IssueTransaction

Structure of an issue transaction.

Constructor

IssueTransaction(quantity: Int, name: String, description: String, reissuable: Boolean, decimals: Int, script: ByteVector|Unit, id: ByteVector, fee: Int, timestamp: Int, version: Int, sender: Address, senderPublicKey: ByteVector, bodyBytes: ByteVector, proofs: List[ByteVector])

Fields

IssueTransaction Fields

#

Name

Data type

Description

\(1\)

quantity

Int

Amount of the token.

\(2\)

name

String

Token name.

\(3\)

description

String

Token description.

\(4\)

reissuable

Boolean

Reissue ability flag.

\(5\)

decimals

Int

Number of digits in decimal part.

\(6\)

script

ByteVector | Unit

Script that must be set for the generated token.

\(7\)

id

ByteVector

Transaction ID.

\(8\)

fee

Int

Transaction fee.

\(9\)

timestamp

Int

Transaction timestamp.

\(10\)

version

Int

Transaction version.

\(11\)

sender

Address

Address of the transaction sender.

\(12\)

senderPublicKey

ByteVector

Account public key of the transaction sender.

\(13\)

bodyBytes

ByteVector

Transaction body bytes.

\(14\)

proofs

List [ByteVector]

Array of proofs.

ReissueTransaction

Structure of a reissue transaction.

Constructor

ReissueTransaction(quantity: Int, assetId: ByteVector, reissuable: Boolean, id: ByteVector, fee: Int, timestamp: Int, version: Int, sender: Address, senderPublicKey: ByteVector, bodyBytes: ByteVector, proofs: List[ByteVector])

Fields

ReissueTransaction Fields

#

Name

Data type

Description

\(1\)

quantity

Int

Amount of the token.

\(2\)

assetId

ByteVector

Token ID.

\(3\)

reissuable

Boolean

Reissue flag.

\(4\)

id

ByteVector

Transaction ID.

\(5\)

fee

Int

Transaction fee.

\(6\)

timestamp

Int

Transaction timestamp.

\(7\)

version

Int

Transaction version.

\(8\)

sender

Address

Address of the transaction sender.

\(9\)

senderPublicKey

ByteVector

Public key of the transaction sender.

\(10\)

bodyBytes

ByteVector

Transaction body bytes.

\(11\)

proofs

List [ByteVector]

Proofs.

BurnTransaction

Structure of an burn transaction.

Constructor

BurnTransaction(quantity: Int, assetId: ByteVector, id: ByteVector, fee: Int, timestamp: Int, version: Int, sender: Address, senderPublicKey: ByteVector, bodyBytes: ByteVector, proofs: List[ByteVector])

Fields

BurnTransaction Fields

#

Name

Data type

Description

\(1\)

quantity

Int

Amount of the token to burn.

\(2\)

assetId

ByteVector

ID of the token to burn.

\(3\)

id

ByteVector

Transaction ID.

\(4\)

fee

Int

Transaction fee.

\(5\)

timestamp

Int

Transaction timestamp.

\(6\)

version

Int

Transaction version.

\(7\)

sender

Address

Address of the transaction sender.

\(8\)

senderPublicKey

ByteVector

Public key of the transaction sender.

\(9\)

bodyBytes

ByteVector

Transaction body bytes.

\(10\)

proofs

List [ByteVector]

Array of proofs.

SetAssetScriptTransaction

Structure of an set asset script transaction.

Constructor

SetAssetScriptTransaction(script: ByteVector|Unit, assetId: ByteVector, id: ByteVector, fee: Int, timestamp: Int, version: Int, sender: Address, senderPublicKey: ByteVector, bodyBytes: ByteVector, proofs: List[ByteVector])

Fields

SetAssetScriptTransaction Fields

#

Name

Data type

Description

\(1\)

script

ByteVector | Unit

Asset script.

\(2\)

assetId

ByteVector

Token ID.

\(3\)

id

ByteVector

Transaction ID.

\(4\)

fee

Int

Transaction fee.

\(5\)

timestamp

Int

Transaction timestamp.

\(6\)

version

Int

Transaction version.

\(7\)

sender

Address

Address of the transaction sender.

\(8\)

senderPublicKey

ByteVector

Public key of the transaction sender.

\(9\)

bodyBytes

ByteVector

Transaction body bytes.

\(10\)

proofs

List [ByteVector]

Proofs.

UpdateAssetInfoTransaction

Structure of an update asset info transaction.

Constructor

UpdateAssetInfoTransaction(name: String, assetId: ByteVector, description: String, id: ByteVector, fee: Int, timestamp: Int, version: Int, sender: Address, senderPublicKey: ByteVector, bodyBytes: ByteVector, proofs: List[ByteVector])

Fields

UpdateAssetInfoTransaction Fields

#

Name

Data type

Description

\(1\)

name

String

Name of the token.

\(2\)

assetId

ByteVector

Token ID.

\(3\)

description

String

Description of the token.

\(4\)

id

ByteVector

Transaction ID.

\(5\)

fee

Int

Transaction fee.

\(6\)

timestamp

Int

Transaction timestamp.

\(7\)

version

Int

Transaction version.

\(8\)

sender

Address

Address of a transaction sender.

\(9\)

senderPublicKey

ByteVector

Account public key of a sender.

\(10\)

bodyBytes

ByteVector

Transaction body bytes.

\(11\)

proofs

List [ByteVector]

Array of proofs.

Usage

Usage

Transaction type ID

Name

Description

\(4\)

TransferTransaction

Structure of transfer transaction.

\(7\)

ExchangeTransaction

Structure of exchange transaction.

\(10\)

CreateAliasTransaction

Structure of create alias transaction.

\(11\)

MassTransferTransaction

Structure of mass transfer transaction.

\(12\)

DataTransaction

Structure of data transaction.

\(13\)

SetScriptTransaction

Structure of set script transaction.

\(16\)

InvokeScriptTransaction

Structure of invoke script transaction.

TransferTransaction

Structure of an transfer transaction.

Constructor

TransferTransaction(feeAssetId: ByteVector|Unit, amount: Int, assetId: ByteVector|Unit, recipient: Address|Alias, attachment: ByteVector, id: ByteVector, fee: Int, timestamp: Int, version: Int, sender: Address, senderPublicKey: ByteVector, bodyBytes: ByteVector, proofs: List[ByteVector])

Fields

TransferTransaction Fields

#

Name

Data type

Description

\(1\)

feeAssetId

ByteVector | Unit

Token to pay the commission.

\(2\)

amount

Int

Amount of tokens to transfer.

\(3\)

assetId

ByteVector | Unit

ID of a token.

\(4\)

recipient

Address | Alias

Address or alias of the recipient.

\(5\)

attachment

ByteVector

Arbitrary data attached to transfer. The maximum data size is \(140\) bytes.

\(6\)

id

ByteVector

Transaction ID.

\(7\)

fee

Int

Transaction fee.

\(8\)

timestamp

Int

Transaction timestamp.

\(9\)

version

Int

Transaction version.

\(10\)

sender

Address

Address of a transaction sender.

\(11\)

senderPublicKey

ByteVector

Account public key of a sender.

\(12\)

bodyBytes

ByteVector

Transaction body bytes.

\(13\)

proofs

List [ByteVector]

Array of proofs.

ExchangeTransaction

Structure of an exchange transaction.

Constructor

ExchangeTransaction(buyOrder: Order, sellOrder: Order, price: Int, amount: Int, buyMatcherFee: Int, sellMatcherFee: Int, id: ByteVector, fee: Int, timestamp: Int, version: Int, sender: Address, senderPublicKey: ByteVector, bodyBytes: ByteVector, proofs: List[ByteVector])

Fields

ExchangeTransaction Fields

#

Name

Data type

Description

\(1\)

buyOrder

Order

Token purchase order.

\(2\)

sellOrder

Order

Token sell order.

\(3\)

price

Int

Price of exchanging token.

\(4\)

amount

Int

Amount of exchanging tokens.

\(5\)

buyMatcherFee

Int

Matcher’s purchase fee.

\(6\)

sellMatcherFee

Int

Matcher’s sell fee.

\(7\)

id

ByteVector

Transaction ID.

\(8\)

fee

Int

Transaction fee.

\(9\)

timestamp

Int

Transaction timestamp.

\(10\)

version

Int

Transaction version.

\(11\)

sender

Address

Address of a transaction sender.

\(12\)

senderPublicKey

ByteVector

Account public key of a sender.

\(13\)

bodyBytes

ByteVector

Transaction body bytes.

\(14\)

proofs

List [ByteVector]

Array of proofs.

CreateAliasTransaction

Structure of a create alias transaction.

Constructor

CreateAliasTransaction(alias: String, id: ByteVector, fee: Int, timestamp: Int, version: Int, sender: Address, senderPublicKey: ByteVector, bodyBytes: ByteVector, proofs: List[ByteVector])

Fields

CreateAliasTransaction Fields

#

Name

Data type

Description

\(1\)

alias

String

Alias.

\(3\)

id

ByteVector

Transaction ID.

\(4\)

fee

Int

Transaction fee.

\(5\)

timestamp

Int

Transaction timestamp.

\(6\)

version

Int

Transaction version.

\(7\)

sender

Address

Address of the transaction sender.

\(8\)

senderPublicKey

ByteVector

Public key of the transaction sender.

\(9\)

bodyBytes

ByteVector

Transaction body bytes.

\(10\)

proofs

List [ByteVector]

Array of proofs.

MassTransferTransaction

Structure of a mass transfer transaction.

Constructor

MassTransferTransaction(assetId: ByteVector|Unit, totalAmount: Int, transfers: List[Transfer], transferCount: Int, attachment: ByteVector, id: ByteVector, fee: Int, timestamp: Int, version: Int, sender: Address, senderPublicKey: ByteVector, bodyBytes: ByteVector, proofs: List[ByteVector])

Fields

MassTransferTransaction Fields

#

Name

Data type

Description

\(1\)

assetId

ByteVector | Unit

Token ID.

\(2\)

totalAmount

Int

Amount of the token to be transferred.

\(3\)

transfers

List [Transfer]

Transfers.

\(4\)

transferCount

Int

Number of transfers.

\(5\)

attachment

ByteVector

Optional data attached to the transaction. This field is often used to attach a comment to the transaction. The maximum data size is \(140\) bytes.

\(6\)

id

ByteVector

Transaction ID.

\(7\)

fee

Int

Transaction fee.

\(8\)

timestamp

Int

Transaction timestamp.

\(9\)

version

Int

Transaction version.

\(10\)

sender

Address

Address of the transaction sender.

\(11\)

senderPublicKey

ByteVector

Public key of the transaction sender.

\(12\)

bodyBytes

ByteVector

Transaction body bytes.

\(13\)

proofs

List [ByteVector]

Proofs.

DataTransaction

Structure of a data transaction.

Constructor

DataTransaction(data: List[BinaryEntry|BooleanEntry|DeleteEntry|IntegerEntry|StringEntry], id: ByteVector, fee: Int, timestamp: Int, version: Int, sender: Address, senderPublicKey: ByteVector, bodyBytes: ByteVector, proofs: List[ByteVector])

Fields

DataTransaction Fields

#

Name

Data type

Description

\(1\)

data

List [BinaryEntry | BooleanEntry | DeleteEntry | IntegerEntry | StringEntry]

Transaction’s data array.

\(2\)

id

ByteVector

Transaction ID.

\(3\)

fee

Int

Transaction fee.

\(4\)

timestamp

Int

Transaction timestamp.

\(5\)

version

Int

Transaction version.

\(6\)

sender

Address

Address of a transaction sender.

\(7\)

senderPublicKey

ByteVector

Account public key of a sender.

\(8\)

bodyBytes

ByteVector

Transaction body bytes.

\(9\)

proofs

List [ByteVector]

Array of proofs.

SetScriptTransaction

Structure of a set script transaction.

Constructor

SetScriptTransaction(script: ByteVector|Unit, id: ByteVector, fee: Int, timestamp: Int, version: Int, sender: Address, senderPublicKey: ByteVector, bodyBytes: ByteVector, proofs: List[ByteVector])

Fields

SetScriptTransaction Fields

#

Name

Data type

Description

\(1\)

script

ByteVector | Unit

Account script or dApp script.

\(2\)

id

ByteVector

Transaction ID.

\(3\)

fee

Int

Transaction fee.

\(4\)

timestamp

Int

Transaction timestamp.

\(5\)

version

Int

Transaction version.

\(6\)

sender

Address

Address of the transaction sender.

\(7\)

senderPublicKey

ByteVector

Public key of the transaction sender.

\(8\)

bodyBytes

ByteVector

Transaction body bytes.

\(9\)

proofs

List [ByteVector]

Proofs.

InvokeScriptTransaction

Structure of an invoke script transaction.

Constructor

InvokeScriptTransaction(dApp: Address|Alias, payments: List[AttachedPayments], feeAssetId: ByteVector|Unit, function: String, args: List[Boolean|ByteVector|Int|String|List[Boolean|ByteVector|Int|String]], id: ByteVector, fee: Int, timestamp: Int, version: Int, sender: Address, senderPublicKey: ByteVector, bodyBytes: ByteVector, proofs: List[ByteVector])

Fields

InvokeScriptTransaction Fields

#

Name

Data type

Description

\(1\)

dApp

Address | Alias

Address or alias of the account which is calling a function.

\(2\)

payments

List [AttachedPayment]

Payments attached to the transaction.

\(3\)

feeAssetId

ByteVector | Unit

token to pay the commission.

\(4\)

function

String

Name of the callable function.

\(5\)

args

List [Boolean | ByteVector | Int | String | List [Boolean | ByteVector | Int | String]]

Parameters of the callable function.

\(6\)

id

ByteVector

Transaction ID.

\(7\)

fee

Int

Transaction fee.

\(8\)

timestamp

Int

Transaction timestamp.

\(9\)

version

Int

Transaction version.

\(10\)

sender

Address

Address of the transaction sender.

\(11\)

senderPublicKey

ByteVector

Account public key of the transaction sender.

\(12\)

bodyBytes

ByteVector

Transaction body bytes.

\(13\)

proofs

List [ByteVector]

Array of proofs.

Network

Network

Transaction type ID

Name

Description

\(8\)

LeaseTransaction

Structure of lease transaction.

\(9\)

LeaseCancelTransaction

Structure of lease cancel transaction.

\(14\)

SponsorFeeTransaction

Structure of sponsor fee transaction.

LeaseTransaction

Structure of a lease transaction.

Constructor

LeaseTransaction(amount: Int, recipient: Address|Alias, id: ByteVector, fee: Int, timestamp: Int, version: Int, sender: Address, senderPublicKey: ByteVector, bodyBytes: ByteVector, proofs: List[ByteVector])

Fields

LeaseTransaction Fields

#

Name

Data type

Description

\(1\)

amount

Int

Amount of the token to lease.

\(2\)

recipient

Address | Alias

Address or alias of the leasing recipient.

\(3\)

id

ByteVector

Transaction ID.

\(4\)

fee

Int

Transaction fee.

\(5\)

timestamp

Int

Transaction timestamp.

\(6\)

version

Int

Transaction version.

\(7\)

sender

Address

Address of a transaction sender.

\(8\)

senderPublicKey

ByteVector

Account public key of a sender.

\(9\)

bodyBytes

ByteVector

Transaction body bytes.

\(10\)

proofs

List [ByteVector]

Array of proofs.

LeaseCancelTransaction

Structure of a lease cancel transaction.

Constructor

LeaseCancelTransaction(leaseId: ByteVector, id: ByteVector, fee: Int, timestamp: Int, version: Int, sender: Address, senderPublicKey: ByteVector, bodyBytes: ByteVector, proofs: List[ByteVector])

Fields

LeaseCancelTransaction Fields

#

Name

Data type

Description

\(1\)

leaseId

ByteVector

Leasing ID.

\(2\)

id

ByteVector

Transaction ID.

\(3\)

fee

Int

Transaction fee.

\(4\)

timestamp

Int

Transaction timestamp.

\(5\)

version

Int

Transaction version.

\(6\)

sender

Address

Address of the transaction sender.

\(7\)

senderPublicKey

ByteVector

Public key of the transaction sender.

\(8\)

bodyBytes

ByteVector

Transaction body bytes.

\(9\)

proofs

List [ByteVector]

Proofs.

SponsorFeeTransaction

Structure of a sponsor fee transaction.

Constructor

SponsorFeeTransaction(assetId: ByteVector, minSponsoredAssetFee: Int|Unit, id: ByteVector, fee: Int, timestamp: Int, version: Int, sender: Address, senderPublicKey: ByteVector, bodyBytes: ByteVector, proofs: List[ByteVector])

Fields

SponsorFeeTransaction Fields

#

Name

Data type

Description

\(1\)

assetId

ByteVector

Token ID.

\(2\)

minSponsoredAssetFee

Int | Unit

Amount of asset that is equivalent to 0.001 DecentralCoins (100,000 Decentralites): an integer value specified in atomic units. unit – disable sponsorship.

\(3\)

id

ByteVector

Transaction ID.

\(4\)

fee

Int

Transaction fee.

\(5\)

timestamp

Int

Transaction timestamp.

\(6\)

version

Int

Transaction version.

\(7\)

sender

Address

Address of the transaction sender.

\(8\)

senderPublicKey

ByteVector

Public key of the transaction sender.

\(9\)

bodyBytes

ByteVector

Transaction body bytes.

\(10\)

proofs

List [ByteVector]

Proofs.

Genesis

Genesis

Transaction type ID

Name

Description

\(1\)

GenesisTransaction

Structure of genesis transaction.

GenesisTransaction

Structure of a genesis transaction.

Constructor

GenesisTransaction(amount: Int, recipient: Address|Alias, id: ByteVector, fee: Int, timestamp: Int, version: Int)

Fields

GenesisTransaction Fields

#

Name

Data type

Description

\(1\)

amount

Int

Amount of the token.

\(2\)

recipient

Address | Alias

Address or alias of the token recipient.

\(3\)

id

ByteVector

Transaction ID.

\(4\)

fee

Int

Transaction fee.

\(5\)

timestamp

Int

Transaction timestamp.

\(6\)

version

Int

Transaction version.

Iterations with FOLD<N>

FOLD<N> macro makes it possible to implement operations on a list of values such as sum, filter, map, zip, exists, etc. The macro behaves like the fold or reduce function in other programming languages.

FOLD<N>(list, start, foldFunc)
Iterations with FOLD

Parameter

Description

N

Maximum number of iterations, up to \(1000\).

list

List of values.

start

Initial value.

foldFunc

Combining function.

The combining function accepts two input parameters: the intermediate result and the next element of the list. Macro FOLD<N>(list, start, foldFunc) means:

  • Execute up to N iterations.

  • At each iteration: take the r-esult of the previous iteration (at the first iteration take the start value) and the next list item list, apply the foldFunc function to this pair.

  • Return the final result.

The value of N must be known in advance. If there are more elements in the list than specified in FOLD, the script fails. The complexity of FOLD<N> corresponds to the complexity of foldFunc multiplied by N plus extras. The FOLD<N> macro is a syntactic sugar; it is unwrapped by the compiler. Therefore, in particular, the size of the script increases linearly with N.

Sum

func sum(accum: Int, next: Int) = accum + next
let arr = [1,2,3,4,5]
FOLD<5>(arr, 0, sum)    # Result: 15

The expression

FOLD<5>(arr, 0, sum)

after compiling and decompiling will look like this:

let $list = arr
let $size = size($list)
let $acc0 = 0
if (($size == 0))
 then $acc0
 else {
   let $acc1 = sum($acc0, $list[0])
   if (($size == 1))
     then $acc1
     else {
       let $acc2 = sum($acc1, $list[1])
       if (($size == 2))
         then $acc2
         else {
           let $acc3 = sum($acc2, $list[2])
           if (($size == 3))
           then $acc3
             else {
               let $acc4 = sum($acc3, $list[3])
               if (($size == 4))
                 then $acc4
                 else {
                   let $acc5 = sum($acc4, $list[4])
                   if (($size == 5))
                     then $acc5
                     else {
                       let $acc6 = sum($acc5, $list[5])
                       throw("List size exceed 5")
                     }
                 }
             }
         }
     }
 }

Product

func mult(accum: Int, next: Int) = accum * next
let arr = [1,2,3,4,5]
FOLD<5>(arr, 1, mult)    # Result: 1204]

Filter

The following code composes an array consisting only of even elements of the original array:

func filterEven(accum: List[Int], next: Int) =
 if (next % 2 == 0) then accum :+ next else accum
let arr = [1,2,3,4,5]
FOLD<5>(arr, [], filterEven)    # Result: [2, 4]

Map

The following code inverts the array, reducing each element by \(1\):

func map(accum: List[Int], next: Int) = (next - 1) :: accum
let arr = [1, 2, 3, 4, 5]
FOLD<5>(arr, [], map)    # Result: [4, 3, 2, 1, 0]

dApp-to-App Invocation

A dApp callable function can invoke a callable function of another dApp, or another callable function of the same dApp, or even itself. The invocation is synchronous. The invoked function returns a value that the invoking function can use.

dApp-to-dApp invocation is processed as follows:

  • A user sends an Invoke Script transaction that invokes the callable function \(1\).

  • The callable function \(1\) invokes the callable function \(2\) via a strict variable initialized by the invoke or reentrantInvoke function.

  • The callable function \(2\) is executed; the script actions and return value are calculated.

  • The return value is assigned to the strict variable. The subsequent operations of callable function 1 are executed, taking into account script actions of callable function \(2\) (as if the actions were applied to the blockchain state).

  • Finally, the script actions of callable functions \(2\) and \(1\) are applied to the blockchain state.

Features

  • dApp-to-dApp invocations can be nested.

  • All invoked callable functions are executed within a single Invoke Script transaction.

  • A dApp-to-dApp invocation can contain payments that are transferred from the balance of the parent dApp to the balance of the invoked dApp.

  • Payments attached to a callable function invocation can be used in script actions and in payments attached to nested invocations.

Conditions

  • Both the parent and invoked dApp scripts use standard library version 5.

  • If the dApp invokes itself, the invocation must not contain payments.

  • The number of the invoke or reentrantInvoke function calls is up to 100 within a single Invoke Script transaction.

  • The maximum total number of Issue, Reissue, Burn, SponsorFee, ScriptTransfer, Lease, LeaseCancel script actions executed by all callable functions in a single transaction is \(30\).

  • The maximum total number of BinaryEntry, BooleanEntry, IntegerEntry, StringEntry, DeleteEntry script actions executed by all callable functions in a single transaction is \(100\).

  • The total complexity is limited by \(26,000\) for all callable functions and asset scripts of involved smart assets. The sender’s account script complexity is not included in that limit.

Strict Variable

strict keyword defines a variable with eager evaluation. Unlike lazy variables defined with let, a strict variable is evaluated immediately when script execution reaches it, that is, before the next expression.

Invoke and reentrantInvoke Functions

invoke(dApp: Address|Alias, function: String, arguments: List[Any], payments: List[AttachedPayments]): Any
reentrantInvoke(dApp: Address|Alias, function: String, arguments: List[Any], payments: List[AttachedPayments]): Any

Parameters:

Invoke and ReentrantInvoke Functions

Parameter

Description

dApp: Address|Alias

Address or alias of a dApp to invoke.

function: String|Unit

Name of a callable function. unit for a default function invocation.

arguments: List[Any]

Parameters of a callable function.

payments: List[AttachedPayment]

Payments to transfer from the parent dApp to the invoked dApp, up to \(10\).

strict z = invoke(dapp,foo,args,[AttachedPayment(unit,100000000)])

The return value is of type Any, which means any valid type. You can extract a particular type from it using as[T] and exactAs[T] macros or the match … case operator, see the any article.

The invoke and reentrantInvoke functions differ only in the reentrancy restriction. For details, see the dApp-to-dApp invocation function article.

Invocation Fields

For dApp-to-dApp invocation, the fields of invocation structure used by the invoked function are filled with the following values:

Invocation Fields

#

Name

Data type

Description

\(1\)

caller

Address

Address of the dApp that invokes the callable function.

\(2\)

callerPublicKey

ByteVector

Public key of the dApp that invokes the callable function.

\(3\)

originCaller

Address

Address of the account that sent the invoke script transaction.

\(4\)

originCallerPublicKey

ByteVector

Public key of the account that sent the invoke script transaction.

\(5\)

payments

List [AttachedPayment]

Payments indicated in the invoke or reentrantInvoke function.

\(6\)

transactionId

ByteVector

ID of the invoke script transaction.

\(7\)

fee

Int

Transaction fee.

\(8\)

feeAssetId

ByteVector | Unit

ID of the fee token.

Callable Function Result

In standard library version 5, a callable function result is a tuple of two elements:

  • List of script actions.

  • Return value that is passed to the invoking function.

Let’s see an example:

(
  [
    ScriptTransfer(i.caller,100,unit)
  ],
  42
)

In standard library version 4 or 3, there is no return value, so unit is implied.

For details, see the callable function article.

Updating Balance and Account Data Storage Entries

If the callable function invoked by the invoke or reentrantInvoke function performs script actions, the results of those actions are available to the invoking function:

  • If the invoked function adds an entry to the account’s data storage, the invoking function can obtain the entry after the invocation.

  • If the invoked function deletes an entry from the account’s data storage, the invoking function cannot obtain the entry after the invocation.

  • If the invoked function performs actions with tokens (transfer, issue/reissue/burn, and others) and the invoking function obtains balances after the invocation, it receives the updated balances.

Transaction Fail

If the callable function’s execution fails or throws an exception, the Invoke Script transaction could be rejected or saved on the blockchain as failed. This depends on whether the complexity of performed computations has exceeded the threshold for saving a failed transaction (currently \(1000\)). The complexity is summed up for all invocations.

Consider the example: callable function \(1\) performs computations of 800 complexity, then invokes callable function \(2\) which performs computations of 300 complexity and then fails. The complexity \(800 + 300\) has exceeded the threshold, so the transaction is saved as failed, and the sender is charged a fee.

If the total complexity of executed callable functions and asset scripts exceeds the limit of \(26,000\), the transaction is saved as failed as well. For example, if the complexity of executed callable functions is \(25,000\) in total, and there is a smart asset in script action whose script’s complexity is \(1500\).

In case of failure, no payments and script actions are applied to the blockchain state, even if some of the invoked functions are executed completely. The only state change the failed transaction entails is charging the fee.

Known Issue

If the invoke or reentrantInvoke function is called inside a function without annotation (that is, inside a function that cannot be invoked from outside the dApp), and the dApp script contains a verifier function, then an error occurs when trying to set such a script.

Limitations

Limitations

Limitation

Maximum value

dApp script size

\(32\) Kbytes.

Account script or asset script size

\(8\) Kbytes.

Complexity of account script

\(2000\)

Complexity of asset script

\(4000\)

Complexity of each callable function of dApp script

\(10,000\)

Total number of dApp-to-dApp invocations within a single Invoke Script transaction

\(100\)

Total complexity for all callable functions and asset scripts involved in an Invoke Script transaction. The sender’s account script complexity is not included in this limit

\(26,000\)

Complexity threshold for saving failed transactions: if the callable function failed with an error or throwing an exception before the threshold exceeded, the invoke script transaction is rejected and the fee is not charged

\(1000\)

Complexity of verifier function of dApp script

\(2000\)

Sender complexity threshold: if the complexity of an account script or the verifier function of a dApp script exceeds this limit, the minimum fee for a transaction sent from the account is increased by 0.004 DecentralCoins

\(200\)

Function name or variable name

\(255\) bytes

Size of String variable

\(32,767\) bytes

Size of ByteVector variable

\(32,767\) bytes (except bodyBytes field of transaction structure).

Data weight

See data weight.

Number of callable function arguments

\(22\)

Number of payments attached to an invocation

\(10\)

Total number of Issue, Reissue, Burn, SponsorFee, ScriptTransfer, Lease, and LeaseCancel script actions executed by all callable functions in a single transaction

\(30\)

Total number of BinaryEntry, BooleanEntry, DeleteEntry, IntegerEntry, StringEntry script actions executed by all callable functions in a single transaction

\(100\)

Total size of data written to the account data storage by all BinaryEntry, BooleanEntry, IntegerEntry, StringEntry script actions executed by a callable function

\(5\) Kbytes.

Total size of data written to the account data storage by all BinaryEntry, BooleanEntry, IntegerEntry, StringEntry script actions executed by all callable functions in a single transaction

\(15\) Kbytes.

Script Complexity

Script complexity is a dimensionless quantity that estimates computational resources needed to execute a script. The complexity of a script is estimated based on complexities of all the operators and functions it consists of. The complexity of the built-in functions is listed in the built-in functions article.

Limitations on script complexity are given in the limitations article.

Data Weight

The weight of each value approximately corresponds to its size in bytes. Weight is used in limitations on creating and comparing values.

Weight Calculation

Weight Calculation

Data type

Weight of value

BigInt

\(64\)

Boolean

\(1\)

ByteVector

Size in bytes.

Int

\(8\)

List

See weight of list below.

String

Size in bytes.

Structure

See weight of tuple or structure.

Tuple

See weight of tuple or structure.

Unit

\(40\)

Weight of List

The weight of the list is calculated as follows:

\(W_{list} = 20 + 20 × Q + W_{elems}\)

where:

  • \(Q\) is a number of elements.

  • \(W_{elems}\) is a total weight of elements.

Weight of Tuple or Structure

The weight of the tuple or structure is calculated as follows:

\(W_{struct} = 40 + 30 × Q + W_{fields}\)

where:

  • \(Q\) is a number of fields.

  • \(W_{fields}\) is a total weight of fields.

Weight Limitations

  • The maximum weight of the value is \(307200\).

  • A comparison of values is not allowed if the weight of each value exceeds \(13000\).

If the limitations are exceeded, the script fails.

Let’s consider an example, using the AssetPair structure:

AssetPair(amountAsset: ByteVector|Unit, priceAsset: ByteVector|Unit)

An asset ID is a ByteVector of \(32\) bytes, its weight is \(32\). If both assets in the pair are not DecentralCoins, then the weight of the AssetPair structure is:

\(W_{AssetPair} = 40 + 30 × 2 + (32 + 32) = 164\)

If one of the assets is DecentralCoin, then the corresponding field is of type Unit and its weight is \(40\). Then the weight of the AssetPair structure is:

\(W_{AssetPair} = 40 + 30 × 2 + (32 + 40) = 172\)

Ride Components

Parser

Parser checks the Ride script syntax, the presence of all the variables and functions used, and forms an abstract syntax tree that is used by compiler.

Compiler

Compiler generates executable script code based on an abstract syntax tree. The compiled script can be assigned to an account or asset.

Estimator

Estimator calculates the complexity of the compiled script.

Evaluator

Evaluator is a node component that executes the script in cases of sending a transaction from a smart account, an invoke script transaction, or transactions involving smart assets. Script execution is a part of transaction validation and transaction execution, that is, calculating new state of the blockchain as a result of transaction.

Decompiler

Decompiler converts script code from executable format to Ride code. Decompiler is used in DecentralChain Explorer to view an account script, dApp script or asset script.