Introduction to Helios

Helios is a Javascript/Typescript SDK for the Cardano blockchain. Helios is all you need to build dApps on Cardano, including a simple smart contract language: the Helios language.

Example smart contract

// all Helios scripts begin with a script purpose
spending always_true 

// the spending entrypoint function accepts three arguments and 
//  contains the core validator logic
// 'main' returns true if a given UTxO is allowed to be spent
func main(_, _, _) -> Bool {
    // the Helios DSL is expression based
    true
}

Structure of this book

Before starting to use Helios to create smart contracts and build dApps it is important to understand Cardano's eUTxO model very well. If you don't yet, we recommend you read the Understanding eUTxOs preface first.

Chapter 1 covers the language, including a complete reference of the language builtins.

Chapter 2 covers how to use the Helios API to compile smart contracts, and create smart contract transactions, including a complete reference of the library exports.

Chapter 3 covers how to use the Helios CLI to build dApps, including a complete reference of the CLI commands.

Chapter 4 contains a variety of articles to help you become a better Cardano dApp architect.

Understanding the eUTxO model

Before we get into any coding we first need to understand how smart contracts work on Cardano and how Cardano differs from the more conventional account-based model.

Note: eUTxO is an abbreviation of extended Unspent Transaction Outputs

Account-based model vs eUTxO model

Smart contracts on Cardano are quite different from those on Ethereum.

Ethereum-style smart contracts (account-based)

When a transaction occurs on an account-based blockchain, the balance of the sender's account is directly decremented and that of the recipient is incremented, similar to how conventional bank accounts work.

Contracts interact with these balances and run via the EVM (Ethereum Virtual Machine). The EVM can be thought of as a global on-chain computer on which smart contracts take turns running, before their results are added to the chain.

Note: the data of all accounts on Ethereum are stored in a Merkle-Patricia trie, which is like a fancy hashmap. After all the transactions in a block are run, the root hash of the block trie is added to the chain.

The eUTxO model

In the eUTxO model tokens are stored in UTxOs. A UTxO is like (electronic)-cash where each individual bundle of bills (Ada and native-tokens) is stored separately.

A transaction in the UTxO model takes one or more UTxOs as transaction inputs, which are destroyed, and creates one or more UTxOs as transaction outputs.

Transactions in an account-based model mutate the data-points storing the total balances. This is very risky (regular banks are insured against this, and also have paper backups in case of mistakes, but blockchains have no such fallbacks). In the UTxO model only the "bills" that participate in a given transaction can potentially be affected (which is bad, but not catastrophic).

Of course a UTxO chain can emulate account-based chains (by storing all tokens in a single UTxO) and account-based chains can emulate UTxO chains (by spreading a user's balance over many different accounts).

Components of a UTxO on Cardano

UTxOs have 3 main components:

  • an address
  • tokens (Ada and other native assets)
  • a datum

Address

The address of a UTxO determines the owner (i.e. who has the right to spend it).

A user's balance is calculated by summing all UTxOs sitting at addresses owned by that user.

An address can either be derived from the hash of a user's public key (PubKeyHash in Helios), or the hash of a validator script (ValidatorHash in Helios). In the latter case the script effectively becomes the owner of the UTxO.

Tokens

Each UTxO contains some tokens, which represent value on the blockchain. Tokens have positive value due to scarcity (tokens can't be duplicated) and utility (eg. Ada being used to pay transaction fees).

Datum

The datum is data that is attached to UTxOs. A datum represents the state of a smart contract, and is immutable (smart contract state can change though, by spending old UTxOs and creating new ones).

The 'e' (extended) in eUTxO comes from the datum. The Bitcoin UTxO model doesn't have datums, giving Bitcoin scripts very limited capabilities. Extending the UTxO model, as done by Cardano and Ergo, gives an eUTxO model the same capabilities as an account-based model, while benefitting from a much safer approach to transactions (because a global state isn't being accessed/mutated).

Validator scripts

A validator script is a function that is evaluated when a transaction attempts to spend a UTxO locked at that script's address. This function takes 3 arguments:

  • the datum attached to the UTxO
  • some data provided by the user who created the transaction (the redeemer)
  • details about the transaction (the script context)

The validator script then calculates whether or not the UTxO is allowed to be spent (essentially returning a boolean result).

Separating the validation logic from the transaction building/submitting logic makes it much easier to audit the trusted part of eUTxO dApps.

Helios is all about writing these validator scripts.

Note: a UTxO can only be spent once. In every transaction all input UTxOs are destroyed, and new output UTxOs are created.

Note: a valid transaction must satisfy the following conditions:

  • the transaction must be balanced: the total amount of tokens in the transaction inputs must be equal to those in the transaction outputs (minus the fees, plus the minted tokens).
  • the validators for all the transaction inputs must evaluate to true.

Pros and cons of the eUTxO Model

Pros

  • Deterministic transaction fees

    eUTxO smart contract evaluation is deterministic. This means that you can calculate the resource usage of a transaction before posting it to the blockchain. The transaction fees for a transaction can thus be calculated deterministically off-chain.

    The transaction fees of account-based blockchains depend on network load, and can vary a lot.

  • Transaction fees not charged upon failure

    The determinism of the eUTxO model means that transaction success can be determined before posting. Transaction failure is still possible due to contention, but this is a very cheap check, and no fee is charged.

    Transaction failure on account-based blockchains results in losing the fee, as significant processing power might've been used before encountering the failure condition.

  • Easier to audit

    Auditing of eUTxO smart contracts is much easier because only the validation function needs to be audited, which has a very locally-scoped nature.

  • Concurrency

    Due to monetary value being naturally spread over many UTxOs, a UTxO blockchain can be compared to an extremely sharded account-based blockchain (some smart contracts might require a centralized data-point though, and won't allow concurrent interactions, see contention).

  • Better for layer 2

    The local nature of UTxOs allows reusing validation logic in layer 2 scaling solutions such as state channels (see hydra).

  • Simpler

    Though not immediately obvious, eUTxO smart contracts are often much simpler than an equivalent Solidity smart contract (this will become apparant when you start to use Helios).

Cons

  • Contention

    If eUTxO contracts aren't designed properly they can encounter contention problems. Contention occurs when two or more transactions try to spend the same UTxO. If this happens only one of the transactions will succeed, and the others will fail (resulting in an unpleasant user experience).

    This is usually not an issue on Ethereum because the EVM handles ordering smart contract calls.

    Note: there are ways to avoid contention, by for example taking advantage of the parallel nature of UTxOs (see SundaeSwap's scooper model)

Further reading

If you feel like you still don't fully understand the eUTxO model, we recommend you keep reading:

Changelog

This page documents breaking changes and major features of major version releases

v0.14

Language

API

  • program.parameters accepts namespaced const names
  • program.parameters acceps names prefixed with ? to avoid errors if parameter doesn't exist

v0.13

Language

API

  • helios.Int renamed to helios.HInt
  • helios.HeliosString renamed to helios.HString
  • helios.HeliosMap renamed to helios.HMap
  • helios.List renamed to helios.HList
  • program.changeParam() deprecated

The Helios language

The Helios language is a purely functional programming language, with a simple curly braces syntax. It is inspired by Go and Rust.

Tenets

  • Readability is more important than writeability
  • Easily auditable, it should be easy to spot malicious code
  • Opinionated, there should be only one obvious way of doing things

Structure of this chapter

In this chapter we will refer to the Helios language simply as Helios.

We start this chapter by explaining the basic syntax of Helios, and then move onto higher level concepts like functions, structs and enums.

This chapter ends with a complete reference of the Helios builtins.

Helios language/

Comments

Helios comments are C-like.

Single-line comments

Single-line comments use two forward slashes (//):

spending always_succeeds

func main(_, _, _) -> Bool {
	// This is a comment.
	true
}

Multi-line and inline comments

Multi-line and inline comments use /* ... */:

spending always_succeeds

func main(_, _, _ /* inline comment */) -> Bool {
	/*
		This is a multi-line comment.
	*/
	true
}

Helios language/

Variables

Variables in Helios can be defined inside function bodies using assignment expressions, and at the top-level of a script using const statements.

Assignment

Inside a function body, variables are defined using assignment expressions:

my_number: Int = 42; ...

Here my_number has value 42, and has type Int.

Assignment expressions must be followed by another expression, separated by a semicolon (;).

Note: Int is Helios' only number type, and represents an unbounded integer.

Note: the assignment expression above can be seen as syntactic sugar for the following anonymous function call: ((my_number: Int) -> {...})(42).

Note: an assignment expression can alternatively be seen as a ternary operator: ... = ... ; ...

Reassignment

A variable can be reassigned (though all values in Helios are immutable).

my_number: Int = 42;

...

my_number = 0 // reassignment

The new value must have the same type. You can reassign a variable inside nested scopes, effectively shadowing the original value. You can also reassign function arguments.

Note: the value of an assignment in a nested scope isn't available in the outer scopes.

const statements

Variables can also be defined at the top-level of a script, or inside struct or enum blocks, with const statements:

const AGE: Int = 123

const statements can be changed using the Helios API (see parameterized contracts).

Note: the right-hand side of const can contain complex expressions and even function calls. The compiler is smart enough to evaluate these at compile-time.

const without right-hand-side

The right-hand-side of a const statement can be omitted, in which case it must be set using the Helios API before compiling (see program.parameters):

const MY_PARAMETER: ValidatorHash

Type annotations

Assignment expressions usually include a type annotation. For literal right-hand sides, type annotations are optional:

list_of_ints = []Int{1, 1, 2, 3, 5}; ...

// instead of the more verbose:

list_of_ints: []Int = []Int{1, 1, 2, 3, 5}; ...

Note: const statements always have a type annotation. The type of the right-hand-side is never inferred.

Helios language/

Primitive types

Helios has 5 primitive types:

  • Int (unbounded integer)
  • Real (fixed point real number)
  • Bool (true or false)
  • String (utf-8 text)
  • ByteArray (array of uint8 numbers)

Int

Helios' Int type represents an unbounded integer (like Haskell's Integer type).

// Helios supports common integer literals:
my_decimal = 17;
my_binary  = 0b10001;
my_hex     = 0x11;
my_octal   = 0o121; ...

Large literal integers can be delimited with underscores at power-of-3 positions to improve readability:

my_large_decimal = 1_000_000; ...

More information about the Int type can be found here.

Real

Helios' Real type represents a fixed point real number with 6 decimal places. Real is designed for calculations involving relative fees.

fee = 0.0001 // 0.01%

Similar to Int, underscores can be used at power-of-3 positions to improve readability:

fee = 0.000_1 // 0.01%

More information about the Real type can be found here.

Bool

The Bool type has two possible literal values: true or false.

Booleans are used throughout validator scripts, and the return type of a validator script is a boolean. The simplest validator script body is just a literal boolean:

func main(_, _, _) -> Bool {
    true
}

The equality (==) and inequality (!=) operators, returning boolean results, are defined on all builtin and user types:

func main(_, _, ctx: ScriptContext) -> Bool {
    ctx == ctx // always true
}

More information about the Bool type can be found here.

String

A literal Helios string uses double quotes ("..."):

my_message = "Hello world"; ...

Similar to all other values in Helios, strings are immutable and have a fixed length.

Strings cannot grow after definition. Concatenating two strings creates a new string:

string_1 = "Hello";
string_2 = " world";
result: String = string_1 + string_2; ... // "Hello world"

More information about the String type can be found here.

ByteArray

The ByteArray type, as you've likely guessed, represents an array of bytes. A literal ByteArray is either a hexadecimal sequence prefixed by #, or a UTF-8 string prefixed by b:

my_bytes = #48656c6c6f20776f726c64; ...
my_bytes = b"Hello world"

All builtin and user types can be converted into a ByteArray using the builtin serialize method:

cbor_bytes: ByteArray = 123.serialize(); ... // cbor encoding of 123

More information about the ByteArray type can be found here.

Note: a ByteArray can be empty, so the following is valid syntax: my_bytes = #; ...

Helios language/

Container types

Helios has 3 container types:

  • List (linked list)
  • Map (association list of key-value pairs)
  • Option (equivalent to Maybe in Haskell)
  • Tuple (fixed list with heterogenous item types)

List

Helios has a builtin linked list type, similar to Haskell's List. The syntax for a list type is []ItemType where ItemType is a parameter type that represents the type of the contained items. The ItemType can be any type except a function type.

List literals have a syntax similar to Go:

my_ints = []Int{1, 2, 3, 4, 5};

x: Int = some_ints.get(2); ...   // x == 3

Note: lists aren't indexed with [...]. Instead the get method can be used. Indices are 0-based.

More information about lists can be found here.

Map

A Map in Helios is internally represented as a list of key-value pairs. Both key and value can have any type except a function type. Uniqueness of keys isn't guaranteed.

A Map has a type syntax and a literal syntax similar to Go:

// either side of the colon can be an arbitrary expression 
//  that evaluates to the correct type
my_map = Map[String]Int{
    "zero": 0,
    "one":  1,
    "two":  2
}; ... 

print(my_map.get("zero").show()); ... // prints '0'

More information about maps can be found here.

Option

The Option type is a builtin enum with type syntax Option[SomeType]. It is internally defined as:

enum Option[SomeType] {
    Some { some: SomeType }
    None
}

An Option is instantiated like any other enum:

some_int = Option[Int]::Some{42};

none_int = Option[Int]::None; ...

If you expect Some, you can assign, and even destructure, using the correct type annotation. Helios will automatically turn the assignment into a runtime type assertion (any enum can take advantage of this):

Option[Int]::Some{my_int} = option; ...

More information about Option can be found here.

Tuple

A tuple is a collection of two or more items which can have different types.

my_tuple = (1, "hello", true)

Tuples are convenient when returning multiple values from a function:

func my_pair(a: Int) -> (Int, Int) {
    (a+1, a+2)
}

Tuples can contain anything, including functions. The contents of a tuple can be accessed through destructuring, or via getters:

(my_number: Int, my_string: String, my_bool: Bool) = my_tuple;

my_number_alt: Int = my_tuple.first;
my_string_alt: String = my_tuple.second;
my_bool_alt: Bool = my_tuple.third

Note: tuples in Helios are limited to 5 entries. The getters are named first, second, third, fourth and fifth.

Note: although tuples can be used as fields in structs/enums this is not recommended as it can become unclear what the meaning is of the tuples items, and there is also a performance penalty to doing so.

Nested literal constructors

If a literal List, Map, or Option contains other literal constructors, the types of those literal constructors can be omitted.

struct Pair {
  a: Int
  b: Int
}
...
list = []Pair{{0, 0}, {1, 1}, {2, 2}};
map = Map[Pair]Pair{{0, 0}: {0, 0}, {1, 1}: {1, 1}, {2, 2}: {2, 2}};
nested_list = [][]Pair{{{0, 0}, {1, 1}, {2, 2}}, {{0, 0}, {1, 1}, {2, 2}}};
option = Option[Pair]::Some{{0, 0}}

Helios language/

Branching

Helios has conventional if-else syntax for branching:

if (tag == 0) {
    23
} else if (tag == 1) {
    42
} else {
	0
}

The last expression in each branch block is implicitly returned (much like Rust).

if-else can be used like any other expression:

x: Int = 
	if (true) {
		42
	} else {
		24
	}; ...

Helios language/

print, error, assert

There are three builtin void functions. These can be used to define higher level user-defined void functions.

Void functions can't be used in assignments.

print

For debugging purposes, Helios has a special print expression. print(...) takes a String argument:

func main() -> Bool {
	print("Hello world");
	true
}

Note: print expressions are useful when debugging scripts. They are however eliminated by the compiler when compiling scripts optimized for production.

error

Helios has a special error builtin, which can be used to throw errors inside branches of if-else expressions, and cases of switch expressions. At least one branch or case must be non-error-throwing for the if-else or switch expression to return a non-void value.

if (cond) {
    true
} else {
    error("my error message")
}
x.switch{
    Buy => true,
    Sell => error("my error message")
}

assert

The builtin assert function throws an error if a given expression evaluates to false.

assert(condition, "should be true"); ...

Helios language/

Functions

All Helios functions are pure, which means they don't have side effects (except throwing errors) and always return the same result when given the same arguments.

Function statements are defined using the func keyword. Helios has no return statement, the last expression in a function is implicitly returned (like in Rust):

func add(a: Int, b: Int) -> Int {
    a + b 
}

A function can call itself recursively:

func fib(n: Int) -> Int {
    // the branches of an if/else expresion return values
    if (n < 1) {
        1
    } else {
        fib(n - 1) + fib(n - 2)
    }
}

Note:: a function can only reference itself when recursing. Helios doesn't support hoisting, so mutual recursion by referring to functions defined after the current function in the top-scope isn't possible (for struct and enum methods this is however possible):

01 func a(n: Int) -> Int {
02     b(n)                   // ReferenceError: 'b' undefined
03 }
04
05 func b(n: Int) -> Int {
06     a(n)                   // ok
07 }

More detailed information can be found on the following pages:

Helios language/ Functions/

Multiple return values

A Helios function can return multiple values using tuples:

func swap(a: Int, b: Int) -> (Int, Int) {
    (b, a)
}

You can assign to multiple return values using tuple destructuring:

(a: Int, b: Int) = swap(10, 20); ... // a==20 && b==10

Some of the multiple return values can be discarded with an underscore (_):

(a: Int, _) = swap(10, 20); ...

Automatic unpacking of tuples

Tuples are automatically unpacked during a function call, in a way that matches the type signature of the function being called:

(a: Int, b: Int) = swap(swap(10, 20)); // a==10 && b==20

Helios language/ Functions/

Void functions

Functions that are composed of only print, error, assert, and if-else/switch expressions there-of, return void (()). These kinds of functions can't be called in assignments.

func assert_even(n: Int) -> () {
    assert(n % 2 == 0, "not even")
}

The syntax for calling user-defined void functions is the same as for print, error and assert:

spending my_validator

func main(_, _, ctx: ScriptContext) -> Bool {
    assert_even(ctx.outputs.length);
    ...
}

Helios language/ Functions/

Anonymous functions

Helios also supports anonymous function expressions. Anonymous function expressions are basically function statements without the func keyword:

// type of 'is_even' can be inferred
is_even = (n: Int) -> Bool { n % 2 == 0 }; ...

The return type of anonymous functions is optional:

is_even = (n: Int) -> { n % 2 == 0 }; ...

Note: function statements can be referenced by their name, returning a function value. This should be preferred to using anonymous functions, as it is more readable.

Helios language/ Functions/

Unused arguments

All named function arguments must be used in the function definition. This can be inconvenient when defining callbacks where you want to ignore some of the arguments. For this situation you can use an underscore (_):

// sort a map by only comparing the keys
map.sort((a_key: ByteArray, _, b_key: ByteArray, _) -> Bool {
    a_key < b_key
})

Underscores are most commonly used to ignore either the datum, redeemer, or the ScriptContext, in the main function of a validator script.

Helios language/ Functions/

Optional arguments

Some function arguments can be made optional by specifying default values:

func incr(a: Int, b: Int = 1) -> Int {
    a + b
}

Optional arguments must come after non-optional arguments.

The type signature of a function with optional arguments differs from a regular function:

fn: (Int, ?Int) -> Int = incr

Helios language/ Functions/

Named arguments

Similar to literal constructor fields, function arguments can be named in a call:

func sub(a: Int, b: Int) -> Int {
    a - b
}

sub(b: 1, a: 2) // == 1

A function call can't mix named arguments with positional arguments.

Named arguments are mostly used when calling the copy() method.

Helios language/ Functions/

Function values

Functions are first-class citizens in Helios and can be used as values. This means:

1. Functions can be passed as arguments

even_numbers: []Int = ([]Int{1, 2, 3, 4, 5, 6}).filter(is_even); ... // [2, 4, 6]; 

2. Functions can be returned

add_a = (a: Int) -> (Int) -> Int { (b: Int) -> {a + b} }; ...

Note: functions aren't entirely first-class to be precise. Functions can't be stored in containers, nor in structs/enums.

Helios language/ Functions/ The following is a more involved example of a function in Helios.

Example: Collatz sequence

A Collatz sequence starts with a given number, n, and calculates the next number in the sequence using the following rules:

  1. if n == 1 the sequence ends
  2. if n is even the next number is n / 2
  3. if n is odd the next number is (n * 3) + 1

Curiously the Collatz sequence always converges to 1, regardless the starting number.

The following function generates the Collatz sequence as a (reversed) list of integers:

// eg. collatz(10, []Int{}) == []Int{10, 5, 16, 8, 4, 2, 1}
func collatz(n: Int, sequence: []Int) -> []Int {
	updated_sequence: []Int = sequence.prepend(n);

    // Rule (1)
    if (n == 1) {
		updated_sequence

    // Rule (2)
    } else if (n % 2 == 0) {
        collatz(n / 2, updated_sequence)

    // Rule (3)
    } else {
        collatz(n * 3 + 1, updated_sequence)
    }
}

Helios language/

Operators

The following operators are defined on many of the builtins:

OperatorPrecedenceTypeAssociativity
... (...)9callleft-to-right
.9memberleft-to-right
-8unaryright-to-left
+8unaryright-to-left
!8unaryright-to-left
%7binaryleft-to-right
/7binaryleft-to-right
*7binaryleft-to-right
-6binaryleft-to-right
+6binaryleft-to-right
>=5binaryleft-to-right
>5binaryleft-to-right
<=5binaryleft-to-right
<5binaryleft-to-right
!=4binaryleft-to-right
==4binaryleft-to-right
&&3binaryleft-to-right
||2binaryleft-to-right
|1binaryleft-to-right
...=...;...0ternaryN/A

Note: == and != do a deep comparison and are defined automatically on all user-defined and builtin types.

Pipe operator

The pipe operator (|) applies a function value on the right to a value on the left:

func filter_even(lst: []Int) -> []Int {
    lst.filter((item: Int) -> {item%2 == 0})
}

even: []Int = []Int{1,2,3,4} | filter_even; // []Int{2, 4}

If the pipe operator is followed by a binary operator, that binary operator is treated as a partially applied function:

x: Int = 1 + 2 | * 3; // 9

This can be especially convenient in cases with long chains.

Helios language/

User defined types

Helios allows you to define structs and enums. Both allow defining methods so you can use OOP to structure your code.

Helios language/ User-defined types/

Structs

A struct in Helios is a named grouping of types (sometimes called a product type). They are similar to structs in other languages (e.g. C, Go and Rust):

// example of a Rational (fractional type)
struct Rational {
    top:    Int
    bottom: Int
}

Note: a struct can't be empty and must have at least one field.

Instantiating a struct

A struct can be instantiated using the following literal syntax:

const x: Rational = Rational { 1, 3 }

The fields can also be named:

const x: Rational = Rational { bottom: 3, top: 1 }

CIP 68 tags

Regular Helios structs are internally implemented as data-lists.

This internal data-list format isn't convenient for datums that are intended for public reading/writing. For such applications it is recommended to use the CIP 68 data-map format.

Helios will automatically use the CIP 68 format internally if any struct field is tagged. The tags are internally converted into the data-map keys.

struct TaggedRational {
    top:    Int "@top"     // the tag can be any valid utf-8 string
    bottom: Int "@bottom"
}

Any missing tags default to the field name:

struct TaggedRational {
    top:    Int "@top"
    bottom: Int         // data-map key will be "bottom"
}

Field tagging isn't available for enum variants.

Helios language/ User-defined types/

Enums

Enums are used to represent types that have multiple variants (sometimes called tagged unions or sum types). These are useful for datums and redeemers.

Example of an enum:

enum Redeemer {
	Cancel
	Buy { buyer: PubKeyHash }
}

// instantiating an enum:
const my_redeemer = Redeemer::Buy { PubKeyHash::new(#...) } 
// type of 'my_redeemer' is inferred

Note: the OOP analogy of an enum is an abstract class, and the enum variants can be thought of as concrete implementations (i.e. child classes).

Note: enum variants without fields don't use braces.

switch

A switch expression is used to perform different actions depending on the enum variant. It is similar to a switch statement in C or Go (and dissimilar to a match expression in Rust, as Helios doesn't support pattern-matching):

enum Datum {
	// each variant has a syntax similar to a struct
    Submission{...} 
    Queue{...}
    Post{...}
}

func main(datum: Datum) -> Bool {
	datum.switch {
		x: Submission => { 
			... // expression must use x
		},
		Queue => {
			... // x not used, so can't be declared
		},
		_ => true // default must come last if all sub-types of Datum aren't handled explicitely
		// braces surrounding the cases are optional
	}
}

Data

Data can be thought of as a special builtin enum with 5 members:

A switch expression over Data can use any of these as case types:

data.switch{
	i: Int => ...,
	b: ByteArray => ...,
	l: []Data => ...,
	m: Map[Data]Data => ...,
	e: MyEnum => ... 
}

or

data.switch{
	i: Int => ...,
	b: ByteArray => ...,
	l: []Data => ...,
	m: Map[Data]Data => ...,
	(index: Int, fields: []Data) => ... 
}

Note: the default _ case can also be used as a substitute for any of these cases.

Note: besides the builtin types only one enum type can be used in a Data switch, and structs/enum-members can't be used. If an enum is used then (Int, []Data) can't be used.

Helios language/ User-defined types/

Destructuring

Switch cases and assignments have special syntax for destructuring user-defined structs and enum members.

Destructuring in Helios has the following properties:

  • can be arbitrarily nested
  • is positional (names of the fields don't matter)

Note: destructuring is not pattern matching.

Destructuring assignment

testing destructure_pair

struct Pair {
    first:  Int
    second: Int
}

func main() -> Bool {
    p = Pair{1, 2};
    Pair{a, _} = p;
    a == 1
}

You can also assign a name to any intermediate value when destructuring:

pair: Pair{a, _} = p; ...

Optionally you can include the type when destructuring a field:

pair: Pair{a: Int, _} = p; ...

Destructuring an enum instance into an enum variant will create a runtime type assertion:

Option[Int]::Some{a} = option; ... // throws runtime error if option is None

Destructuring an enum member in a switch case

The same syntax as above can be used in switch cases. Destructuring some builtin enums is also possible (WiP).

option.switch{
    None => ...,
    Some{item} => doSomething(item)
}

Nested destructuring

Nested destructuring requires the type of the nested struct to be specified.

spending my_validator

struct Rational {
    top: Int
    bottom: Int
}

enum Redeemer {
    Sell{price: Rational}
    Buy{price: Rational}
}

...

func main(_, r: Redeemer, _) -> Bool {
    r.switch{
        Sell{Rational{top, bottom}} => doSomething(top, bottom),
        Buy{Rational{top, _}} => doSomething2(top)
    }
}

Nested destructuring is also possible in assignments.

Helios language/ User-defined types/

Methods

You can define methods for structs and enums. The syntax for this is similar to many OOP languages: methods are defined by placing func statements inside a struct or enum block:

struct Rational {
    top:    Int
    bottom: Int

    // 'self' implicitely has type 'Rational'
    func add(self, rhs: Rational) -> Rational {
        top:    Int = (self.top * rhs.bottom) + (rhs.top * self.bottom);
        bottom: Int = self.bottom * rhs.bottom;

        Rational { top, bottom }
    }
}

const example_rational = Rational { 7, 21 }

const result: Rational = example_rational.add(example_rational)

Methods are accessed using a . (i.e. a dot). Methods cannot modify self as all Helios values are immutable (instead they should return new instantations of the own type).

Note: self is a reserved word and can only be used for the first argument of a method. The self argument can't have a type annotation and is always implicitely typed.

Note: methods within the same struct or enum scope can call eachother in any order (mutual recursion).

Methods can be used as values

A method is syntactic sugar for a curried function (a function that returns a function) that takes self as it's first argument:

// the following:
rational_1.add(rational_2); ...
// desugars into: __user__Rational_add(rational_1)(rational_2)
//  of type (Rational) -> (Rational) -> Rational

A method value is a function, and can be seen as a closure over self:

// 'rational_1.add' returns a function of type ((Rational) -> Rational) 
//   which can be used just like any other function value
add_to_rational_1: (Rational) -> Rational = rational_1.add; ...

// Note: add_to_rational_1(rational_2) == rational_1.add(rational_2)

Helios language/ User-defined types/ Methods/

Associated functions and constants

Associated functions (aka static methods) and constants are just like regular functions or constants but are also namespaced by a type, for example Rational::new(top, bottom).

Defining associated functions and constants

Associated functions are defined just like methods but without the self argument. Associated constants are simply const statements inside a struct or enum block:

struct Rational {
    top:    Int
    bottom: Int

	// associated const
	const PI = Rational { 355, 113 }

	// associated function
	func new(top: Int, bottom: Int) -> Rational {
		Rational { top, bottom }
	}
}

Using associated functions and constants

Associated functions and constants are namespaced by the type they are associated with and can be referenced using a double colon (::) just like in Rust. For example:

half: Rational = Rational::new(1, 2); ...

Helios language/ User-defined types/ Methods/

Automatic methods

The following (associated) methods and operators are automatically defined on all user and builtin types (except function types).

==, !=

The equality and inequality operators are automatically defined on every type (except function types).

copy

Instantiates a copy of the underlying value, with some of the fields changed.

This method has the same number of arguments as the number of fields in the user-defined struct or enum-variant. Each argument of copy has the same name as the corresponding field and is optional (see named arguments).

struct Pair {
    first:  Int
    second: Int
}

...

pair = Pair{1, 2};

pair.copy(second: 3) // == Pair{1, 3}

from_data

from_data is an associated function that is automatically defined on every user-type, and thus from_data is a reserved name that can't be used for other methods.

from_data converts a typeless Data into something typed.

MyType::from_data(data: Data) -> MyType

If you set CHECK_CASTS to true, a warning will be printed if the structure of data doesn't match the type.

is_valid_data

Deep check that the given data matches the expected format.

MyType::is_valid_data(data: Data) -> Bool

serialize

The serialize method is automatically defined on every user-type, and thus serialize is a reserved name that can't be used for other methods.

serialize serializes the underlying data using cbor encoding.

my_instance.serialize() -> ByteArray

Note: when debugging you can inspect the output of print(x.serialize().show()) using this cbor tool.

show

The show method returns a string representation of underlying instance, which is convenient when debugging.

my_instance.show() -> String

Note: usually you will use print(x.show()) instead of print(x.serialize().show()) when debugging.

Helios language/ User-defined types/ Methods/ The following is a complete example of a struct with both associated functions and regular methods.

Example: Rational

struct Rational {
    top:    Int
    bottom: Int

    // associated const
    const PI = Rational{ 355, 113 }

    // associated function
    func new(top: Int, bottom: Int) -> Rational {
        Rational { top, bottom }
    }

    // regular method
    func add(self, rhs: Rational) -> Rational {
        top:    Int = (self.top * rhs.bottom) + (rhs.top * self.bottom);
        bottom: Int = self.bottom * rhs.bottom;

        Rational { top, bottom }
    }

}

const rational_1 = Rational::PI // 355/113 or 3.14159...
const rational_2 = Rational::new(1, 2) // 1/2 or 0.5
const rational_3: Rational = rational_1.add(rational_2) // 823/226 or 3.64159...

Helios language/

Generics

Helios supports generic type parameters for functions, structs, and enums. The syntax for generics is similar to lists, Map and Option.

Generic functions

Example:

func deserialize[A](a: Data) -> A {
    A::from_data(a)
}

When calling a function, the type parameters are infered wherever possible. In this example however A can't be inferred and must be specified before calling the function:

my_bool: Bool = deserialze[Bool](my_bool_data); ...

The type parameter can optionally be constrained with a typeclass, for example with the builtin Valuable typeclass:

func get_value[V: Valuable](v: V) -> Value {
    v.value
}

Generic structs and enums

User types like structs and enums can also have generic type parameters. For example:

struct Pair[A, B] {
    a: A
    b: B
}

When instantiating such a generic type, type inference isn't available, and the field types must be specified explicitly:

my_pair = Pair[Int, Int]{1, 2}; ...

An example of a generic enum:

enum BinaryTree[A] {
    Leaf { value: A }

    Node {
        value: A
        left:  BinaryTree[A]
        right: BinaryTree[A]
    }
}

Similar to generic functions, the type parameters of generic structs and enums can be constrained using typeclasses.

Note: all type parameters must be used in the fields of the struct or enum, not just in the methods.

Note: generic structs and enums can contain generic methods with additional type parameters.

Type classes

Typeclasses are used to constrain a type parameter of a generic function or user-type.

User-defined typeclasses aren't yet possible, there are however three builtin typeclasses:

  • Any (matches any data-type or function-type)
  • empty (this is the default, matches any data-type, but not function-types)
  • Valuable (matches any type with the .value -> Value getter, so TxInput, TxOutput, and Value itself)

Helios language/

Structure of a script

Helios validator scripts have a function called main that returns a boolean (true or false) when validating the spending of a UTxO.

For a spending validator, main takes three arguments:

  • Datum: data stored on-chain that is linked to the locked UTxO (not avaiable for minting/staking scripts)
  • Redeemer: data specified by the user attempting to spend the locked UTxO
  • ScriptContext: information about the transaction spending the locked UTxO

The datum and the redeemer can be of any type, but the last argument must always have type ScriptContext.

The structure of a validator script looks as follows:

// --- (1) ---
spending my_validator       

// --- (2) ---
struct MyDatum {..}           

// --- (3) ---
enum MyRedeemer {..}          
                            
// --- (4) ---
func main(datum: MyDatum, redeemer: MyRedeemer, ctx: ScriptContext) -> Bool {
    ...                  
}

// --- (5) ---
const MY_DATUM = MyDatum {...}

Script purpose (1)

In Helios all scripts start with a script purpose, followed by the name of the script. There are 5 script purposes:

  • spending
  • minting
  • staking
  • testing
  • module

On this page we are only concerned with the spending script purpose:

spending my_validator

...

module is covered in the next section.

Note: the name of each Helios source is registered in the global scope, so these names can't be used by statements, nor for the lhs of assignments. So eg. the entrypoint script can't be named main as that would conflict with the entrypoint function.

Datum (2)

Each UTxO locked at a script address will also have an associated datum. The script can choose to use the datum as part of the spending validation, or it can choose to ignore the datum using an underscore (_) if it is irrelevant.

The datum can have any type.

Redeemer (3)

Each UTxO used as an input for a transaction also has a redeemer attached. This is data specified by the user attempting to spend that UTxO. The script can again choose to use or ignore the redeemer using an underscore (_) if it is irrelevant to the validation.

The redeemer can have any type.

main function (4)

The main function (4) of a validator script accepts up to three optional arguments and returns a Bool:

  • datum (2)
  • redeemer (3)
  • script context
spending my_validator

...

// redeemer is ignored
func main(datum: MyDatum, _, context: ScriptContext) -> Bool {
    ...
}

...

Most of the data needed for writing useful validators is contained in the ScriptContext.

Data generators and test functions (5)

After the main function you can define functions and constants for:

  • generating data structures (eg. datums or redeemers)
  • testing the main function

The API has special functionality for working with these:

  • program.parameters an object that evaluates/sets any top-level constant in a Helios source

Some compiler restrictions are lifted in this part of the script:

  • not all names need to be used (relevant for function arguments and assignments)
  • structs can be empty

Helios language/ Structure of a script/ The following example is the most trivial possible script.

Example: always_succeeds

This basic script allows locked UTxOs to be spent any way the user wants:

spending always_succeeds

func main(_, _, _) -> Bool {
    true
}

You must use an underscore (_) for unused arguments. In this case all three arguments of main are ignored by using an underscore.

Helios language/ Structure of a script/

Parameterized Contracts

Parameterizing contracts allows dApp developers to create separate instances of a Helios program.

In Helios, this is done by re-binding one or more top-level const PARAM_NAME = ... declarations.

After re-binding any const parameters to a different value, the resulting program will have a different contract address.

Example

In this example OWNER is a parameter.

spending my_validator

const OWNER = PubKeyHash::new(#)

func main(_, _, ctx: ScriptContext) -> Bool {
    ctx.tx.is_signed_by(OWNER)
}

The parameter can be changed before compiling to the final Uplc format:

const program = helios.Program.new(src);

program.parameters.OWNER = new helios.PubKeyHash("...");

const uplcProgram = program.compile();

Many Helios API types can be used when rebinding the parameters. Also the user-defined types are available through program.types. Besides using Helios API types, Javascript primitive objects (i.e. JSON-like) can be used to re-bind a parameter in some cases.

Contrast with Datum

Attaching Datum data structures to specific UTxOs is another way that a validator or other program can have varying behavior.

Using Datum causes those explicit details to be included in UTxOs (and/or in transactions consuming them). Transactions spending the UTxOs held at the same script address can each access and use those various Datum details. Noteably, any interested party can trivially query to discover all the various UTxOs held at a single contract address.

By contrast, two different instances of a parameterized contract, otherwise identical, will have separate addresses where UTxOs can be held. UTxO's don't need to explicitly contain the parameter values.

Querying for UTxO's in separate instances of a parameterized contract is also possible, but requires the interested party to have sufficient knowledge of those separate instance addresses, or other publicly-visible attributes of the target transactions.

Note that any parameterized contract can also use per-UTxO Datum values, as needed.

Helios language/

Modules

Helios top-level statements can be placed in modules and can then be imported by other Helios sources. Modules can be made available during compile-time by including them in a list as the second argument of the Program constructor.

import

import statements in Helios are similar to Javascript/Typescript:

import { 
    ImportedName1 as NewName1,
    ImportedName2
} from MyModule

The imported names act as if the original statements were defined in the source where they are imported.

Note: currently every top-level statement is public and exported by default, including other import statements.

Namespace import

Entire modules can also be imported directly as a namespace.

import MyModule

...

MyModule::MyStruct{...}

Namespaces can be nested:

import MyModule

...

MyModule::MySubModule::MyStruct{...}

The import {...} from ... syntax can also be used to unwrap submodules:

import { MySubModule as RenamedSubModule } from MyModule

...

RenamedSubModule::MyStruct{...}

Webpack

When using the Webpack loader you must use relative paths instead of module names when importing:

import { 
    ImportedName1 as NewName1,
    ImportedName2
} from "<rel-path-to-module>.hl"

The Webpack loader currently doesn't support importing namespaces using relative paths (WiP).

Helios language/

Builtins

This section contains a reference of all the Helios builtins.

Primitive types

Container types

Type classes

Money types

Time types

  • Duration (i.e. the difference of two Time instances)
  • Time
  • TimeRange (i.e. a period bound by two Time instances)

Hash and cryptography types

Transaction types

Helios language/ Builtins/

Address

Represents a Cardano address.

Associated functions

from_bytes

Decodes raw address bytes (see CIP 19). IS_TESTNET must be set to false for this to work for mainnet addresses.

Address::from_bytes(bytes: ByteArray) -> Address

from_data

Address::from_data(data: Data) -> Address

from_hex

Decodes the hexadecimal encoded bytes of a raw address (see CIP 19). IS_TESTNET must be set to false for this to work for mainnet addresses.

Address::from_hex(hex: String) -> Address

new

Construct a new Address from a Credential and an optional StakingCredential:

Address::new(
    credential: Credential, 
    staking_credential: Option[StakingCredential]
) -> Address

Getters

credential

Get the payment Credential of an Address:

address.credential -> Credential

staking_credential

Get the StakingCredential of an Address:

address.staking_credential -> Option[StakingCredential]

Operators

==

Address == Address -> Bool

!=

Address != Address -> Bool

Methods

serialize

address.serialize() -> ByteArray

show

Alias for to_hex.

address.show() -> String

to_bytes

Returns the raw address bytes (see CIP 19). IS_TESTNET must be set to false for this to return a raw mainnet addresses.

address.to_bytes() -> ByteArray

to_hex

Encodes the raw address bytes as a hexadecimal String (see CIP 19). IS_TESTNET must be set to false for this to return a raw mainnet addresses.

address.to_hex() -> String

Helios language/ Builtins/

Any

Any is a special type class that can be used to constrain a generic type parameter. Any matches any data-type or any function-type.

The list.fold() and map.fold() methods use Any to allow the value being folded over to be of either function or data type.

The default empty type class matches only data-types (which is what is usually needed).

Helios language/ Builtins/

AssetClass

Represents a unique token on the blockchain using its MintingPolicyHash and its token name (as a ByteArray).

Associated functions and constants

ADA

Lovelace AssetClass (empty MintingPolicyHash and empty token name ByteArray):

AssetClass::ADA -> AssetClass

new

Constructs a new AssetClass using a MintingPolicyHash and a token name ByteArray:

AssetClass::new(
    mph: MintingPolicyHash, 
    token_name: ByteArray
) -> AssetClass

from_data

AssetClass::from_data(data: Data) -> AssetClass

Getters

mph

asset_class.mph -> MintingPolicyHash

token_name

asset_class.token_name -> ByteArray

Operators

==

AssetClass == AssetClass -> Bool

!=

AssetClass != AssetClass -> Bool

Methods

serialize

asset_class.serialize() -> ByteArray

show

Returns the hexadecimal representation of the MintingPolicyHash and the token name, separated by a period (.).

asset_class.show() -> String

Helios language/ Builtins/

Bool

Represents a boolean value (true/false).

bool_true  = true;
bool_false = false; ...

Associated functions

and

Doesn't evaluate the second argument if the first argument evaluates to false.

Bool::and(fn_a: () -> Bool, fn_b: () -> Bool) -> Bool

or

Doesn't evaluate the second argument if the first argument evaluates to true.

Bool::or(fn_a: () -> Bool, fn_b: () -> Bool) -> Bool

from_data

Bool::from_data(data: Data) -> Bool

Operators

!

Boolean not operator.

!Bool -> Bool

==

Bool == Bool -> Bool

!=

The boolean inequality operator can also be used as an xor operator.

Bool != Bool -> Bool

&&

Boolean and operator. Right argument is only evaluated if left argument is true.

Internally left and right arguments are wrapped with anonymous functions and Bool::and is called.

Bool && Bool -> Bool

||

Boolean or operator. Right argument is only evaluated if left argument is false.

Internally left and right arguments are wrapped with anonymous functions and Bool::or is called.

Bool || Bool -> Bool

Methods

serialize

bool.serialize() -> ByteArray

show

false is turned into "false", and true is turned into "true".

bool.show() -> String

to_int

false is turned into 0, and true is turned into 1.

bool.to_int() -> Int

trace

Prints a message while returning the Bool value itself. This can be convenient when debugging the outcome of a script.

bool.trace(msg: String) -> Bool

The msg is prefixed to either "true" or "false".

Helios language/ Builtins/

ByteArray

Represents an array of bytes (i.e. an array of uint8 numbers).

byte_array = #213212; ...

Note: in Haskell/Plutus this is called a ByteString, but we thought that that was too ambiguous, so we chose ByteArray instead.

Associated functions

from_data

ByteArray::from_data(data: Data) -> ByteArray

parse

Parses a hexadecimal encoded ByteArray.

ByteArray::parse(hex: String) -> String

Getters

length

Returns the number of bytes in the ByteArray.

byte_array.length -> Int 

Operators

==

ByteArray == ByteArray -> Bool

!=

ByteArray != ByteArray -> Bool

>=

ByteArray >= ByteArray -> Bool

>

The lhs is greater-than the rhs if the first rhs byte, that isn't equal to the corresponding lhs byte, is smaller than that byte. Returns true if all common bytes are equal, but the rhs is shorter than the lhs.

ByteArray > ByteArray -> Bool

<=

ByteArray <= ByteArray -> Bool

<

The lhs is less-than the rhs if the first rhs byte, that isn't equal to the corresponding lhs byte, is greater than that byte. Returns false if the rhs is empty.

ByteArray < ByteArray -> Bool

+

Concatenation of two ByteArrays.

ByteArray + ByteArray -> ByteArray

Methods

blake2b

Calculates the blake2b-256 hash of a ByteArray. The result is 32 bytes long.

byte_array.blake2b() -> ByteArray

decode_utf8

Turns a valid sequence of utf-8 bytes into a String. Throws an error if the ByteArray isn't valid utf-8.

byte_array.decode_utf8() -> String

ends_with

Checks if a ByteArray ends with a given suffix.

byte_array.ends_with(suffix: ByteArray) -> Bool

prepend

Prepends an Int byte, returning a new ByteArray.

Modulo 256 is applied internally to the byte before prepending.

byte_array.prepend(byte: Int) -> ByteArray

serialize

byte_array.serialize() -> ByteArray

sha2

Calculates the sha2-256 hash of a ByteArray. The result is 32 bytes long.

byte_array.sha2() -> ByteArray

sha3

Calculates the sha3-256 hash of a ByteArray. The result is 32 bytes long.

byte_array.sha3() -> ByteArray

show

Converts a ByteArray into its hexadecimal representation.

byte_array.show() -> String

slice

byte_array.slice(start: Int, end: Int) -> ByteArray

starts_with

Checks if a ByteArray starts with a given prefix.

byte_array.starts_with(prefix: ByteArray) -> Bool

Helios language/ Builtins/

Credential

Represents the non-staking part of an Address. Internally represented as an enum with two variants:


Example instantiation:

pubkey_credential: Credential::PubKey = Credential::new_pubkey(PubKeyHash::new(#...));

validator_credential: Credential::Validator = Credential::new_validator(ValidatorHash::new(#...)); ...

Associated functions

new_pubkey

Credential::new_pubkey(pkh: PubKeyHash) -> Credential::PubKey

new_validator

Credential::new_validator(vh: ValidatorHash) -> Credential::Validator

from_data

Credential::from_data(data: Data) -> Credential

Getters

hash

Get the underlying hash.

pubkey_credential.hash -> PubKeyHash

validator_credential.hash -> ValidatorHash

Operators

==

Credential == Credential -> Bool

!=

Credential != Credential -> Bool

Methods

serialize

credential.serialize() -> ByteArray

Helios language/ Builtins/

Data

Represents type-less data, as returned by the OutputDatum.get_inline_data(). Can be cast directly into any other type using from_data, or indirectly using switch.

Getters

tag

Gets tag index of ConstrData. Throws an error if not ConstrData.

data.tag -> Int

Operators

==

Data == Data -> Bool

!=

Data != Data -> Bool

Methods

serialize

data.serialize() -> ByteArray

Helios language/ Builtins/

DatumHash

Opaque ByteArray that represents the hash of a datum.

Associated functions

new

DatumHash::new(bytes: ByteArray) -> DatumHash

from_data

DatumHash::from_data(data: Data) -> DatumHash

Getters

bytes

datum_hash.bytes -> ByteArray

Operators

==

DatumHash == DatumHash -> Bool

!=

DatumHash != DatumHash -> Bool

>=

DatumHash >= DatumHash -> Bool

>

DatumHash > DatumHash -> Bool

<=

DatumHash <= DatumHash -> Bool

<

DatumHash < DatumHash -> Bool

Methods

serialize

datum_hash.serialize() -> ByteArray

show

Hexadecimal representation of a DatumHash.

datum_hash.show() -> String

Helios language/ Builtins/

DCert

Represents an enum of staking related actions:

  • Register: register a StakingCredential
  • Deregister: deregister a StakingCredential
  • Delegate: delegate a StakingCredential to a pool
  • RegisterPool: register a pool
  • RetirePool: deregister a pool

Associated functions

from_data

DCert::from_data(data: Data) -> DCert

new_register

DCert::new_register(credential: StakingCredential) -> DCert::Register

new_deregister

DCert::new_deregister(credential: StakingCredential) -> DCert::Deregister

new_delegate

DCert::new_delegate(
	delegator: StakingCredential, 
	pool_id: PubKeyHash
) -> DCert::Delegate

new_register_pool

DCert::new_register_pool(
	pool_id: PubKeyHash, 
	pool_vfr: PubKeyHash
) -> DCert::RegisterPool

new_retire_pool

DCert::new_retire_pool(
	pool_id: PubKeyHash, 
	epoch: Int
) -> DCert::RetirePool

Getters

DCert::Register

credential

register_dcert.credential -> StakingCredential

DCert::Deregister

credential

deregister_dcert.credential -> StakingCredential

DCert::Delegate

delegator

delegate_dcert.delegator -> StakingCredential

pool_id

delegate_dcert.pool_id -> PubKeyHash

DCert::RegisterPool

pool_id

register_pool_dcert.pool_id -> PubKeyHash

pool_vrf

register_pool_dcert.pool_vrf -> PubKeyHash

DCert::RetirePool

pool_id

retire_pool_dcert.pool_id -> PubKeyHash

epoch

retire_pool_dcert.epoch -> Int

Operators

==

DCert == DCert -> Bool

!=

DCert != DCert -> Bool

Methods

serialize

dcert.serialize() -> ByteArray

Helios language/ Builtins/

Duration

The difference of two Time values is a Duration value. Only a Duration can be added to a Time (two Time values can't be added).

Associated functions and constants

new

Instantiate a Duration from a number of milliseconds.

Duration::new(milliseconds: Int) -> Duration

from_data

Duration::from_data(data: Data) -> Duration

SECOND

1000 milliseconds.

Duration::SECOND -> Duration

MINUTE

60000 milliseconds.

Duration::MINUTE -> Duration

HOUR

3600000 milliseconds.

Duration::HOUR -> Duration

DAY

86400000 milliseconds.

Duration::DAY -> Duration

WEEK

604800000 milliseconds.

Duration::WEEK -> Duration

Operators

==

Duration == Duration -> Bool

!=

Duration != Duration -> Bool

>=

Duration >= Duration -> Bool

>

Duration > Duration -> Bool

<=

Duration <= Duration -> Bool

<

Duration < Duration -> Bool

+

Duration + Duration -> Duration

-

Duration - Duration -> Duration

*

Duration * Int -> Duration

/

A Duration divided by a Duration is an Int.

Duration / Duration -> Int

A Duration divided by an Int is a Duration.

Duration / Int -> Duration

%

Modulo operator that calculates remainder upon division.

Duration % Duration -> Duration

Methods

serialize

duration.serialize() -> ByteArray

show

Returns the string representation of the Duration in milliseconds.

duration.show() -> String

Helios language/ Builtins/

Int

This is an unbounded integer (like Haskell's Integer type).

Associated functions

from_base58

Decodes a String representing a base58 encoded Int.

Throws an error if the string contains an invalid character.

Int::from_base58(encoded: String) -> Int

from_big_endian

Converts a ByteArray into an Int. The last byte is multiplied by 1 before adding to the sum, the second-to-last byte is multiplied by 256 etc.

The returned Int is always positive.

Int::from_big_endian(bytes: ByteArray) -> Int

from_data

Int::from_data(data: Data) -> Int

from_little_endian

Converts a ByteArray into an Int. The first byte is multiplied by 1 before adding to the sum, the second byte is multiplied by 256 etc.

The returned Int is always positive.

Int::from_little_endian(bytes: ByteArray) -> Int

max

Returns the greater of two numbers.

Int::max(a: Int, b: Int) -> Int

min

Returns the lesser of two numbers.

Int::min(a: Int, b: Int) -> Int

parse

Parses a string representation of an integer of the form ((-)?[1-9][0-9]*)|0 (i.e. a non zero-padded integer). Throws an error if the string representation of the integer doesn't respect this format. Note that -0 isn't allowed, so zeros can only be represented by a single 0 digit.

Int::parse(string: String) -> Int

sqrt

Calculates the square root of an integer. The result is truncated if it can't be represented by a whole number. Throws an error if the input number is negative.

Int::sqrt(a: Int) -> Int

Operators

==

Int == Int -> Bool

!=

Int != Int -> Bool

>=

Int >= Int -> Bool

>

Int > Int -> Bool

<=

Int <= Int -> Bool

<

Int < Int -> Bool

+

Int + Int -> Int

-

Int - Int -> Int

*

Int * Int -> Int

/

Int / Int -> Int

%

Modulo operator that returns the remainder after division.

Int % Int -> Int

Methods

abs

Removes the sign, returning a positive Int.

int.abs() -> Int

bound

Bounds an Int if it falls outside a range. This builtin function doesn't check if the range is sensible.

int.bound(low: Int, high: Int) -> Int

bound_min

Bounds an Int to be greater or equals to a given minimum value.

int.bound_min(low: Int) -> Int

bound_max

Bounds an Int to be less or equals to a given maximum value.

int.bound_max(high: Int) -> Int

decode_zigzag

Decodes a zigzag encoded Int. Throws an error if the Int is negative.

unsigned_int.decode_zigzag() -> Int

encode_zigzag

Applies zigzag encoding to the Int, returning a positive Int.

signed_int.encode_zigzag() -> Int

serialize

int.serialize() -> ByteArray

show

Returns decimal representation of integer.

int.show() -> String

to_base58

Encodes the Int as a base58 String.

Throws an error if the Int is negative.

int.to_base58() -> String

to_big_endian

Encodes the Int as a big endian ByteArray.

Throws an error if the Int is negative.

int.to_big_endian() -> ByteArray

to_bool

Turns 0 into false, and any other integer into true.

int.to_bool() -> Bool

to_little_endian

Encodes the Int as a little endian ByteArray.

Throws an error if the Int is negative.

int.to_little_endian() -> ByteArray

to_hex

Returns the hexadecimal representation of the Int.

int.to_hex() -> String

to_real

Converts the Int to the fixed point Real representation.

int.to_real() -> Real

Helios language/ Builtins/

List

Helios linked-list type.

The syntax for a list type uses empty brackets followed by a type parameter: []ItemType.

Example:

example: []Int = []Int{1, 2, 3, 4, 5}; ...

Looping over multiple lists at once can be done with a recursive function call:

func add_element_wise(a: []Int, b: []Int) -> []Int {
    if (a.is_empty()) {
        []Int{}
    } else {
        add_element_wise(a.tail, b.tail).prepend(a.head + b.head)
    }
}

Associated functions

from_data

[]ItemType::from_data(data: Data) -> []ItemType

new

Creates a new list of length n, where every contained item is determined by fn(i: Int) (i is the 0-based index of the item).

[]ItemType::new(n: Int, fn: (i: Int) -> ItemType) -> []ItemType

new_const

Creates a new list of length n, where very contained item is the same.

[]ItemType::new_const(n: Int, item: ItemType) -> []ItemType

Getters

length

Returns the length of a list.

list.length -> Int

Returns the first item in a list. Throws an error if the list is empty.

list.head -> ItemType

tail

Returns the list items following the first item. Throws an error if the list is empty.

list.tail -> []ItemType

Note: tail doesn't return the last item in a list but returns everything after head as a new list.

Operators

==

[]ItemType == []ItemType -> Bool

!=

[]ItemType != []ItemType -> Bool

+

List concatenation

[]ItemType + []ItemType -> []ItemType

Methods

all

Returns true if all of the items in the list satisfy the predicate.

list.all(predicate: (ItemType) -> Bool) -> Bool

any

Returns true if any of the items in the list satisfy the predicate.

list.any(predicate: (ItemType) -> Bool) -> Bool

drop

Drops list items counting from the beginning, returning the rest of the list. Throws an error if n is negative or larger than the length of the list.

list.drop(n: Int) -> []ItemType

drop_end

Drops list items counting from the end, returning the non-dropped part of the list. Throws an error if n is negative or larger than the length of the list.

This method is more efficient than calling list.take(list.length - n) (if the list length isn't already known).

list.drop_end(n: Int) -> []ItemType

filter

Returns a list of all the items in the old list that satisfy the predicate.

list.filter(predicate: (ItemType) -> Bool) -> []ItemType

find

Returns the first item in the list that satisfies the predicate. Throws an error if no item satisfies the predicate.

list.find(predicate: (ItemType) -> Bool) -> ItemType

find_safe

Returns the first item in the list that satisfies the predicate, wrapped in an Option. Returns a Option[ItemType]::None if no items match the predicate.

list.find_safe(predicate: (ItemType) -> Bool) -> Option[ItemType]

flatten

Only defined for nested lists, i.e. [][]NestedItemType.

nested_list: [][]NestedItemType = ...;

nested_list.flatten() -> []NestedItemType

fold

Folds a list into a single value by continuosly applying the binary function to the items of the list.

list.fold[ReducedType: Any](
    reducer: (ReducedType, ItemType) -> ReducedType, 
    init: ReducedType
) -> ReducedType

fold_lazy

Fold that allows breaking the loop before reaching the end of the list. Can also be used to fold from the last to the first entry of the list instead of the other way around.

list.fold_lazy[ReducedType: Any](
    reducer: (item: ItemType, next: () -> ReducedType) -> ReducedType,
    final: ReducedType
) -> ReducedType

fold2

Folds a list into two values.

list.fold2[ReducedType1: Any, ReducedType2: Any](
    reducer: (ReducedType1, ReducedType2, ItemType) -> (ReducedType1, ReducedType2),
    init1: ReducedType1,
    init2: ReducedType2
) -> (ReducedType1, ReducedType2)

fold2_lazy

Fold into two values, while allowing breaking the loop before reaching the end of the list.

list.fold2_lazy[ReducedType1: Any, ReducedType2: Any](
    reducer: (item: ItemType, next: () -> (ReducedType1, ReducedType2)) -> (ReducedType1, ReducedType2),
    init1: ReducedType1,
    init2: ReducedType2
) -> (ReducedType1, ReducedType2)

for_each

Print or assert something for each item. Returns void.

list.for_each(fn: (item: ItemType) -> ()) -> ()

get

Returns the item at the given position in the list (0-based index). Throws an error if the index is out of range.

list.get(index: Int) -> ItemType

Note: get(n) has to iterate until it encounters the n-th item, so this method is O(n) and not O(1).

get_singleton

Asserts that the list contains precisely one item, and returns that item.

list.get_singleton() -> ItemType

is_empty

Returns true if the list is empty.

list.is_empty() -> Bool

join

Only defined for []String and []ByteArray. join() takes an optional separator (defaults to the empty String or the empty ByteArray).

string_list.join(separator: String = "") -> String

bytearray_list.join(separator: ByteArray = #) -> ByteArray

map

Transforms each item of a list.

list.map[NewItemType](mapper: (ItemType) -> NewItemType) -> []NewItemType

map_option

Transforms and filters a list in one call.

list.map_option[NewItemType](mapper: (ItemType) -> Option[NewItemType]) -> []NewItemType

prepend

Creates a new list by prepending an item to the old list.

list.prepend(item: ItemType) -> []ItemType

serialize

list.serialize() -> ByteArray

set

Creates a new list, replacing an item at an index. Throws an error if the index is out of range.

list.set(index: Int, item: ItemType) -> []ItemType

show

Returns a string representation of the list and its content. This can be useful for debugging.

list.show() -> String

sort

Sorts the list using insertion sort.

list.sort((a: ItemType, b: ItemType) -> Bool) -> []ItemType

split_at

Splits the list at an index. Throws an error if the index is out of range.

list.split_at(index: Int) -> ([]ItemType, []ItemType)

sum

Only defined for []Int and []Real.

int_list.sum() -> Int
real_list.sum() -> Real

take

Takes the first n items from the list. Throws an error if n is negative or larger than the length of the list.

list.take(n: Int) -> []ItemType

take_end

Takes the last n items from the list. Throws an error if n is negative or larger than the length of the list.

This method is more efficient than calling list.drop(list.length - n) (if the list length isn't already known).

list.take_end(n: Int) -> []ItemType

Helios language/ Builtins/

Map

List of key-value pairs. The insertion order of the key-value pairs matters.

Note: a Map is internally not implemented as a hash-table, so keys aren't guaranteed to be unique.

The map type syntax takes two type parameters: Map[KeyType]ValueType.

Example:

my_map = Map[String]Int{"zero": 0, "one": 1, "two": 2};
print(my_map.get("zero").show()); ... // prints "0"

Associated functions

from_data

Map[KeyType]ValueType::from_data(data: Data) -> Map[KeyType]ValueType

Getters

head

Get the key and the value of the first entry.

map.head -> (KeyType, ValueType)

head_key

Returns the key of the first entry in the Map. Throws an error if the Map is empty.

map.head_key -> KeyType

head_value

Returns the value of the first entry in the Map. Throws an error if the Map is empty.

map.head_value -> ValueType

length

Returns the number of items in a map.

map.length -> Int

tail

Returns the entries after the first entry as a new Map. Throws an error if the Map is empty.

map.tail -> Map[KeyType]ValueType

Operators

==

Map[KeyType]ValueType == Map[KeyType]ValueType -> Bool

Note: because Plutus-Core handles Map as a list, the entries must be in the same order for == to return true.

!=

Map[KeyType]ValueType != Map[KeyType]ValueType -> Bool

+

Concatenation of two maps.

Map[KeyType]ValueType + Map[KeyType]ValueType -> Map[KeyType]ValueType

Methods

all

Returns true if all map entries satisfy the predicate.

map.all(predicate: (KeyType, ValueType) -> Bool) -> Bool

any

Returns true if any map entry satisfies the predicate.

map.any(predicate: (KeyType, ValueType) -> Bool) -> Bool

delete

Removes all entries with the given key. Doesn't throw an error if the key isn't found.

map.delete(key: KeyType) -> Map[KeyType]ValueType

filter

map.filter(predicate: (KeyType, ValueType) -> Bool) -> Map[KeyType]ValueType

find

Returns the key and value of the first entry that matches the predicate. Throws an error if none found.

map.find(predicate: (KeyType, ValueType) -> Bool) -> (KeyType, ValueType)

find_safe

Returns a callback (that returns the found key-value pair) and a Bool. Calling the callback if the returned Bool is false throws an error.

map.find_safe(
    predicate: (KeyType, ValueType) -> Bool
) -> (() -> (KeyType, ValueType), Bool)

find_key

Returns the first key that matches the predicate. Throws an error if none found.

map.find_key(predicate: (KeyType) -> Bool) -> KeyType

find_key_safe

Returns an Option containing the first key that matches the predicate, or Option[KeyType]::None if none found.

map.find_key_safe(predicate: (KeyType) -> Bool) -> Option[KeyType]

find_value

Returns the first value that matches the predicate. Throws an error if none found.

map.find_value(predicate: (ValueType) -> Bool) -> ValueType

find_value_safe

Returns an Option containing the first value that matches the predicate, or Option[ValueType]::None if none found.

map.find_value_safe(predicate: (ValueType) -> Bool) -> Option[ValueType]

fold

map.fold[ReducedType: Any](
    reducer: (ReducedType, KeyType, ValueType) -> ReducedType, 
    init: ReducedType
) -> ReducedType

fold_lazy

Fold that allows breaking the loop before reaching the end of the map. Can also be used to fold from the last to the first entry of the Map instead of the other way around.

map.fold_lazy[ReducedType: Any](
    reducer: (KeyType, ValueType, next: () -> ReducedType) -> ReducedType,
    final: ReducedType
) -> ReducedType

for_each

Print or assert something for each map entry. Returns void.

map.for_each(fn: (key: KeyType, value: ValueType) -> ()) -> ()

get

Returns the value of the first entry in the map that matches the given key. Throws an error of the key isn't found.

map.get(key: KeyType) -> ValueType

get_safe

Returns the value of the first entry in the map that matches the given key (wrapped in an option). Returns Option[ValueType]::None if the key isn't found.

map.get_safe(key: KeyType) -> Option[ValueType]

is_empty

Returns true if the Map is empty.

map.is_empty() -> Bool

map

Creates a new Map by transforming the Map keys and values.

map.map[NewKeyType, NewValueType](
    mapper: (KeyType, ValueType) -> (NewKeyType, NewValueType)
) -> Map[NewKeyType]NewValueType

prepend

Prepends a key-value pair to the beginning of the Map, creating a new Map.

map.prepend(key: KeyType, value: ValueType) -> Map[KeyType][ValueType]

serialize

map.serialize() -> ByteArray

set

Sets the first entry with given key to a new value. This entry is appended to end of the Map if the key isn't found.

map.set(key: KeyType, value: ValueType) -> Map[KeyType]ValueType

show

Returns a string representation of the map and its content. This can be useful for debugging.

map.show() -> String

sort

Sorts the map using insertion sort. The comparison function should return true if a and b are in the correct order.

map.sort(
    compare: (
        key_a: KeyType, value_a: ValueType, 
        key_b: KeyType, value_b: ValueType
    ) -> Bool
) -> Map[KeyType]ValueType

update

Changes the value of the first entry matching a given key. Throws an error if the key isn't found.

map.update(
    key: KeyType,
    n: (old_value: ValueType) -> ValueType
) -> Map[KeyType]ValueType

update_safe

Changes the values of all entries matching a given key. Doesn't throw an error if the key isn't found.

map.update_safe(
    key: KeyType, 
    fn: (old_value: ValueType) -> ValueType
) -> Map[KeyType]ValueType

Helios language/ Builtins/

MintingPolicyHash

Opaque ByteArray that represents the hash of a minting policy script.

Example:

mph = MintingPolicyHash::new(#...); ...

Associated functions

new

MintingPolicyHash::new(bytes: ByteArray) -> MintingPolicyHash

from_data

MintingPolicyHash::from_data(data: Data) -> MintingPolicyHash

from_script_hash

Casts the generic ScriptHash type into MintingPolicyHash.

MintingPolicyHash::from_script_hash(hash: ScriptHash) -> MintingPolicyHash

Getters

bytes

mph.bytes -> ByteArray

Operators

==

MintingPolicyHash == MintingPolicyHash -> Bool

!=

MintingPolicyHash != MintingPolicyHash -> Bool

>=

MintingPolicyHash >= MintingPolicyHash -> Bool

>

MintingPolicyHash > MintingPolicyHash -> Bool

<=

MintingPolicyHash <= MintingPolicyHash -> Bool

<

MintingPolicyHash < MintingPolicyHash -> Bool

Methods

serialize

mph.serialize() -> ByteArray

show

Hexadecimal representation of MintingPolicyHash.

mph.show() -> String

Helios language/ Builtins/

Option

Option[SomeType] is an enum used to represent an optional value. Its type syntax takes one type parameter. An option has two variants:

  • Some
  • None

Example:

option_some: Option[Int] = Option[Int]::Some{42};
option_none: Option[Int] = Option[Int]::None; ...

Associated functions

from_data

Option[SomeType]::from_data(data: Data) -> Option[SomeType]

Getters

Option[SomeType]::Some

some

Returns content of Option[SomeType]::Some.

option_some.some -> SomeType

Note: this getter doesn't exist on Option[SomeType]::None.

Operators

==

Option[SomeType] == Option[SomeType] -> Bool

!=

Option[SomeType] != Option[SomeType] -> Bool

Methods

map

Maps None to None and Some to Some.

option.map[NewSomeType](
    fn: (some: OldSomeType) -> NewSomeType
) -> Option[NewSomeType]

serialize

option.serialize() -> ByteArray

show

Returns a string representation of the option, and, in case of Some, its content. This can be useful for debugging.

option.show() -> String

unwrap

Returns the value wrapped by Some. Throws an error if None.

option.unwrap() -> SomeType

Helios language/ Builtins/

OutputDatum

Represents that datum data of a TxOutput instance.

OutputDatum is an enum with 3 variants:

  • None
  • Hash
  • Inline

Associated functions

from_data

OutputDatum::from_data(data: Data) -> OutputDatum

new_hash

Construct a new OutputDatum::Hash instance.

OutputDatum::new_hash(datum_hash: DatumHash) -> OutputDatum::Hash

new_inline

Construct a new OutputDatum::Inline instance from any value that is not a function.

OutputDatum::new_inline(any: AnyType) -> OutputDatum::Inline

new_none

Construct a new OutputDatum::None instance.

OutputDatum::new_none() -> OutputDatum::None

Getters

OutputDatum

get_inline_data

Short-hand for output_datum.switch{inline: Inline => inline.data, _ => error("not an inline datum")}:

output_datum.get_inline_data() -> Data

OutputDatum::Hash

hash

hash_output_datum.hash -> DatumHash

OutputDatum::Inline

data

inline_output_datum.data -> Data

Use the from_data associated function, which is automatically defined on every type, to turn Data into another type.

Operators

==

OutputDatum == OutputDatum -> Bool

!=

OutputDatum != OutputDatum -> Bool

Methods

get_inline_data

Throws an error if the OutputDatum instance isn't Inline.

output_datum.get_inline_data() -> Data

serialize

output_datum.serialize() -> ByteArray

Helios language/ Builtins/

PubKey

Opaque ByteArray that represents a Ed25519 public key.

A PubKey is 32 bytes long. A PubKeyHash is the blake2b-224 hash of a PubKey. Sadly there is no on-chain way of calculating the PubKeyHash from a PubKey (only blake2b-256 is available on-chain).

Example instantiation:

pub_key: PubKey = PubKey::new(#...); ...

Associated functions

new

PubKey::new(bytes: ByteArray) -> PubKey

from_data

PubKey::from_data(data: Data) -> PubKey

Operators

==

PubKey == PubKey -> Bool

!=

PubKey != PubKey -> Bool

Methods

serialize

pub_key.serialize() -> ByteArray

show

Hexadecimal representation of a PubKey.

pub_key.show() -> String

verify

Verify the signature of a message (using Ed25519).

pub_key.verify(message: ByteArray, signature: ByteArray) -> Bool

The signature is expected to be 64 bytes long.

Helios language/ Builtins/

PubKeyHash

Opaque ByteArray that represents the hash of a PubKey.

The first part of a regular payment address (i.e. not witnessed by a script) is a PubKeyHash.

Example instantiation:

pkh: PubKeyHash = PubKeyHash::new(#...); ...

Associated functions

new

PubKeyHash::new(bytes: ByteArray) -> PubKeyHash

from_data

PubKeyHash::from_data(data: Data) -> PubKeyHash

Getters

bytes

pkh.bytes -> ByteArray

Operators

==

PubKeyHash == PubKeyHash -> Bool

!=

PubKeyHash != PubKeyHash -> Bool

>=

PubKeyHash >= PubKeyHash -> Bool

>

PubKeyHash > PubKeyHash -> Bool

<=

PubKeyHash <= PubKeyHash -> Bool

<

PubKeyHash < PubKeyHash -> Bool

Methods

serialize

pkh.serialize() -> ByteArray

show

Hexadecimal representation of a PubKeyHash.

pkh.show() -> String

Helios language/ Builtins/

Real

This is a fixed point real number type with 6 decimal places. Real is designed for use in calculations involving relative fees.

real = 0.001 // 0.1%

Associated functions

from_data

Real::from_data(data: Data) -> Real

sqrt

Calculates the square root of a Real number. The result has a maximal error of 0.000001. Throws an error if the input number is negative.

Real::sqrt(a: Real) -> Real

Operators

Note: any binary operator defined for Real can use Int as either the lhs or rhs.

==

Real == Real -> Bool

!=

Real != Real -> Bool

>=

Real >= Real -> Bool

>

Real > Real -> Bool

<=

Real <= Real -> Bool

<

Real < Real -> Bool

+

Real + Real -> Real

-

Real - Real -> Real

*

Real * Real -> Real

/

Real / Real -> Real

Methods

abs

Returns the absolute value.

Real.abs() -> Real

ceil

Rounds up, returning an Int.

real.ceil() -> Int

floor

Rounds down, returning an Int.

real.floor() -> Int

round

Rounds towards nearest whole number, returning an Int.

real.round() -> Int

trunc

Rounds towards zero, returning an Int.

real.trunc() -> Int

serialize

real.serialize() -> ByteArray

show

real.show() -> String

Helios language/ Builtins/

ScriptContext

The ScriptContext contains all the metadata related to a signed Cardano transaction and is often an important argument of the validator script main function.

It wraps the Tx type and provides some extra methods.

Associated functions

from_data

ScriptContext::from_data(data: Data) -> ScriptContext

new_certifying

Construct a ScriptContext instance with a staking/certifying ScriptPurpose. Only available after main, see script structure.

Throws an error if the current script purpose isn't staking or testing.

ScriptContext::new_certifying(
    tx:    Tx,
    dcert: DCert
) -> ScriptContext

new_minting

Construct a ScriptContext instance with a minting ScriptPurpose. Only available after main, see script structure.

Throws an error if the current script purpose isn't minting or testing.

ScriptContext::new_minting(
    tx:  Tx,
    mph: MintingPolicyHash
) -> ScriptContext

new_rewarding

Construct a ScriptContext instance with a staking/rewarding ScriptPurpose. Only available after main, see script structure.

Throws an error if the current script purpose isn't staking or testing.

ScriptContext::new_rewarding(
    tx: Tx,
    sc: StakingCredential
) -> ScriptContext

new_spending

Construct a ScriptContext instance with a spending ScriptPurpose. Only available after main, see script structure.

Throws an error if the current script purpose isn't spending or testing.

ScriptContext::new_spending(
    tx:        Tx,
    output_id: TxOutputId
) -> ScriptContext

Getters

tx

Get the Tx data structure.

ctx.tx -> Tx

Operators

==

ScriptContext == ScriptContext -> Bool

!=

ScriptContext != ScriptContext -> Bool

Methods

serialize

Returns the cbor-serialization of the ScriptContext.

ctx.serialize() -> ByteArray

get_spending_purpose_output_id

Returns the TxOutputId of the current UTxO being spent.

Can only be called in spending purpose scripts, and throws an error otherwise.

ctx.get_spending_purpose_output_id() -> TxOutputId

get_current_input

Returns the current UTxO being spent as a TxInput.

Can only be called in spending purpose scripts, and throws an error otherwise.

ctx.get_current_input() -> TxInput

get_cont_outputs

Returns the outputs sent back to the current validator script.

Can only be called in spending purpose scripts, and throws an error otherwise.

ctx.get_cont_outputs() -> []TxOutput

get_current_validator_hash

Returns the ValidatorHash of the current script.

Can only be called in spending purpose scripts, and throws an error otherwise.

ctx.get_current_validator_hash() -> ValidatorHash

get_current_minting_policy_hash

Returns the MintingPolicyHash of the minting policy being evaluated.

Can only be called in minting purpose scripts, and throws an error otherwise.

ctx.get_current_minting_policy_hash() -> MintingPolicyHash

get_staking_purpose

Returns the current StakingPurpose (Rewarding or Certifying).

Can only be called in staking purpose scripts, and throws an error otherwise.

ctx.get_staking_purpose() -> StakingPurpose

Helios language/ Builtins/

ScriptHash

Opaque ByteArray that represents either a ValidatorHash, a MintingPolicyHash, or a StakingValidatorHash.

This is returned by the TxOutput.ref_script_hash getter (a reference script can be any of the above script types).

Associated functions

from_data

ScriptHash::from_data(data: Data) -> ScriptHash

Getters

bytes

script_hash.bytes -> ByteArray

Operators

==

ScriptHash == ScriptHash -> Bool

!=

ScriptHash != ScriptHash -> Bool

Methods

serialize

script_hash.serialize() -> ByteArray

Helios language/ Builtins/

ScriptPurpose

Each redemption in a transaction has a ScriptPurpose with the following 4 variants:

  • Minting
  • Spending
  • Rewarding
  • Certifying

ScriptPurpose::Rewarding and ScriptPurpose::Certifying are identical to StakingPurpose::Rewarding and StakingPurpose::Certifying respectively, but the use cases are different. StakingPurpose is used for switching between rewarding and certifying within a given staking script. ScriptPurpose is used to see what other scripts are being used in the same transaction (see tx.redeemers).

Associated functions

from_data

ScriptPurpose::from_data(data: Data) -> ScriptPurpose

new_minting

ScriptPurpose::new_minting(mph: MintingPolicyHash) -> ScriptPurpose::Minting

new_spending

ScriptPurpose::new_spending(output_id: TxOutputId) -> ScriptPurpose::Spending

new_rewarding

ScriptPurpose::new_rewarding(staking_credential: StakingCredential) -> ScriptPurpose::Rewarding

new_certifying

ScriptPurpose::new_certifying(dcert: DCert) -> ScriptPurpose::Certifying

Getters

ScriptPurpose::Minting

policy_hash

Returnt the MintingPolicyHash of the UTxO whose minting or burning is being validated.

minting_script_purpose.policy_hash -> MintingPolicyHash

ScriptPurpose::Spending

output_id

Returns the TxOutputId of the UTxO whose spending is being validated.

spending_script_purpose.output_id -> TxOutputId

ScriptPurpose::Rewarding

credential

Returns the StakingCredential for which rewards are being withdrawn.

rewarding_script_purpose.credential -> StakingCredential

ScriptPurpose::Certifying

dcert

Returns the current stake certifying action as a DCert.

certifying_script_purpose.dcert -> DCert

Operators

==

ScriptPurpose == ScriptPurpose -> Bool

!=

ScriptPurpose != ScriptPurpose -> Bool

Methods

serialize

script_purpose.serialize() -> ByteArray

Helios language/ Builtins/

StakingCredential

Represents the staking part of an Address.

StakingCredential is an enum with 2 variants:

  • Hash
  • Ptr

Associated functions

new_hash

Constructs a new StakingCredential from StakingHash (which in turn is an enum that represents a PubKeyHash or a StakingValidatorHash).

StakingCredential::new_hash(staking_hash: StakingHash) -> StakingCredential::Hash

new_ptr

StakingCredential::new_ptr(a: Int, b: Int, c: Int) -> StakingCredential::Ptr

from_data

StakingCredential::from_data(data: Data) -> StakingCredential

Getters

StakingCredential::Hash

hash

Get the underlying StakingHash.

staking_credential_hash.hash -> StakingHash

The following example code can be used to extract the underlying StakingValidatorHash:

staking_credential.switch{
  h: Hash => h.hash.switch{
    v: Validator => v.hash,
    _ => error("not a StakingHash::Validator")
  }, 
  _ => error("not a StakingCredential::Hash")
}

Operators

==

StakingCredential == StakingCredential -> Bool

!=

StakingCredential != StakingCredential -> Bool

Methods

serialize

staking_credential.serialize() -> ByteArray

Helios language/ Builtins/

StakingHash

An enum with two variants:


Example instantiation:

stakekey_stakinghash: StakingHash::StakeKey = StakingHash::new_stakekey(PubKeyHash::new(#...));

validator_stakinghash: StakingHash::Validator = StakingHash::new_validator(StakingValidatorHash::new(#...)); ...

Associated functions

new_stakekey

StakingHash::new_stakekey(skh: PubKeyHash) -> StakingHash::StakeKey

new_validator

StakingHash::new_validator(svh: StakingValidatorHash) -> StakingHash::Validator

from_data

StakingHash::from_data(data: Data) -> StakingHash

Getters

hash

Get the underlying hash.

stakekey_stakinghash.hash -> PubKeyHash

validator_stakinghash.hash -> StakingValidatorHash

Operators

==

StakingHash == StakingHash -> Bool

!=

StakingHash != StakingHash -> Bool

Methods

serialize

stakinghash.serialize() -> ByteArray

Helios language/ Builtins/

StakingPurpose

A staking purpose script has a StakingPurpose, which is an enum with 2 variants:

  • Rewarding
  • Certifying

Associated functions

from_data

StakingPurpose::from_data(data: Data) -> StakingPurpose

Getters

StakingPurpose::Rewarding

credential

Returns the StakingCredential for which rewards are being withdrawn.

rewarding_staking_purpose.credential -> StakingCredential

StakingPurpose::Certifying

dcert

Returns the current stake certifying action as a DCert.

certifying_staking_purpose.dcert -> DCert

Operators

==

StakingPurpose == StakingPurpose -> Bool

!=

StakingPurpose != StakingPurpose -> Bool

Methods

serialize

staking_purpose.serialize() -> ByteArray

Helios language/ Builtins/

StakingValidatorHash

Opaque ByteArray that represents the hash of a staking script.

Associated functions

new

StakingValidatorHash::new(bytes: ByteArray) -> StakingValidatorHash

from_data

StakingValidatorHash::from_data(data: Data) -> StakingValidatorHash

from_script_hash

Casts the generic ScriptHash type into StakingValidatorHash.

StakingValidatorHash::from_script_hash(hash: ScriptHash) -> StakingValidatorHash

Getters

bytes

staking_validator_hash.bytes -> ByteArray

Operators

==

StakingValidatorHash == StakingValidatorHash -> Bool

!=

StakingValidatorHash != StakingValidatorHash -> Bool

>=

StakingValidatorHash >= StakingValidatorHash -> Bool

>

StakingValidatorHash > StakingValidatorHash -> Bool

<=

StakingValidatorHash <= StakingValidatorHash -> Bool

<

StakingValidatorHash < StakingValidatorHash -> Bool

Methods

serialize

staking_validator_hash.serialize() -> ByteArray

show

Hexadecimal representation of the StakingValidatorHash.

staking_validator_hash.show() -> String

Helios language/ Builtins/

String

Represents a piece of utf-8 text.

string: String = "Woah!"; ...

Associated functions

from_data

String::from_data(data: Data) -> String

is_valid_utf8

Method that checks if a ByteArray contains a valid utf-8 encoded string.

String::is_valid_utf8(bytes: ByteArray) -> Bool

Operators

==

String == String -> Bool

!=

String != String -> Bool

+

String concatenation.

String + String -> String

Methods

encode_utf8

Turns a String into a sequence of utf-8 bytes.

string.encode_utf() -> ByteArray

ends_with

Checks if a String ends with a given suffix.

string.ends_with(suffix: String) -> Bool

serialize

string.serialize() -> ByteArray

show

Returns the string wrapped with quotes. This is useful when debugging.

string.show() -> String

starts_with

Checks if a String starts with a given prefix.

string.starts_with(prefix: String) -> Bool

Helios language/ Builtins/

Time

Represents POSIX time in milliseconds (time since 1970/01/01 00:00:00 UTC).

Associated functions

new

Time::new(millis_since_1970: Int) -> Time

from_data

Time::from_data(data: Data) -> Time

Operators

==

Time == Time -> Bool

!=

Time != Time -> Bool

>=

Time >= Time -> Bool

>

Time > Time -> Bool

<=

Time <= Time -> Bool

<

Time < Time -> Bool

+

Time + Duration -> Time

-

Subtracting a Duration from a Time is like adding a negative Duration.

Time - Duration -> Time

The difference of two Time instances is a Duration.

Time - Time -> Duration

Methods

serialize

time.serialize() -> ByteArray

show

Decimal representation of the underlying raw Int.

time.show() -> String

Helios language/ Builtins/

TimeRange

This represents a range of time using a pair of Time values, or open ends.

Associated functions and constants

ALWAYS

Represents a TimeRange going from negative to positive infinity, thus contains all possible Time values.

TimeRange::ALWAYS -> TimeRange

NEVER

Represents TimeRange going from positive to negative infinity. It contains nothing as it's an impossible range.

TimeRange::NEVER -> TimeRange

from

Returns a TimeRange that contains all Time values from start onwards.

TimeRange::from(start: Time) -> TimeRange

to

Returns a TimeRange that contains all Time values before end.

TimeRange::to(end: Time) -> TimeRange

new

Returns a TimeRange that contains all Time values between start and end.

TimeRange::new(start: Time, end: Time) -> TimeRange

from_data

TimeRange::from_data(data: Data) -> TimeRange

Getters

start

Returns the start Time of a TimeRange. Throws an error if start is non-finite.

time_range.start -> Time

end

Returns the end Time of a TimeRange. Throws an error if end is non-finite.

time_range.end -> Time

Operators

==

TimeRange == TimeRange -> Bool

!=

TimeRange != TimeRange -> Bool

Methods

contains

Returns true if a TimeRange contains the given time.

time_range.contains(time: Time) -> Bool

is_before

Returns true if the end of a TimeRange is before the given time. Always returns false if the end of the TimeRange is positive infinity.

time_range.is_before(time: Time) -> Bool

is_after

Returns true if the start of a TimeRange is after the given time. Always returns false if the start of the TimeRange is negative infinity.

time_range.is_after(time: Time) -> Bool

serialize

time_range.serialize() -> ByteArray

show

time_range.show() -> String

Helios language/ Builtins/

Tx

Represents a balanced transaction.

Associated functions

from_data

Tx::from_data(data: Data) -> Tx

new

Construct a Tx instance. Only available after main, see script structure.

Tx::new(
    inputs:      []TxInput,
    ref_inputs:  []TxInput,
    outputs:     []TxOutput,
    fee:         Value,
    minted:      Value,
    dcerts:      []DCert,
    withdrawals: Map[StakingCredential]Int,
    time_range:  TimeRange,
    signatories: []PubKeyHash,
    redeemers:   Map[ScriptPurpose]AnyType,
    datums:      Map[DatumHash]AnyType,
    id:          TxId
) -> Tx

Note: the value type of the redeemers and datums fields can be any type when instantiating a new Tx instance. But when getting the redeemers and the datums the value type is actually Data (see redeemers and datums).

Getters

inputs

Returns the list of TxInputs of the transaction.

tx.inputs -> []TxInput

ref_inputs

Returns the list of reference inputs (as []TxInput) of the transaction.

tx.ref_inputs -> []TxInput

outputs

Returns the list of TxOutputs of the transaction.

tx.outputs -> []TxOutput

fee

Returns the fee Value paid for the transaction.

tx.fee -> Value

minted

Returns the Value minted by the transaction.

tx.minted -> Value

dcerts

Returns the list of DCerts of the transaction (i.e. list of staking certifying actions).

tx.dcerts -> []DCert

withdrawals

Returns a map of staking reward withdrawals. The map value Ints are lovelace quantities.

tx.withdrawals -> Map[StakingCredential]Int

time_range

Returns the valid TimeRange of the transaction. This TimeRange must contain the current time.

tx.time_range -> TimeRange

Note: we can't access the current time from within the validator script because it would lead to differing evaluation results as the tx propagates across the network. Instead we can use tx.time_range as an approximation of the current time.

signatories

Returns the list of explicit transaction signers as []PubKeyHash.

tx.signatories -> []PubKeyHash

redeemers

Returns all the redeemers of the transaction as a map with ScriptPurpose keys, and Data values. This allows more complex interactions between different scripts being used in the same transaction.

tx.redeemers -> Map[ScriptPurpose]Data

datums

Returns a Map of DatumHashes to raw Data. This can be used to get the datum content of any TxInput that doesn't use inline datums.

tx.datums -> Map[DatumHash]Data

id

Returns the hash of the current transaction as TxId.

tx.id -> TxId

Operators

==

Tx == Tx -> Bool

!=

Tx != Tx -> Bool

Methods

serialize

tx.serialize() -> ByteArray

is_signed_by

Returns true if the transaction was signed by the given pubkeyhash.

tx.is_signed_by(pubkeyhash: PubKeyHash) -> Bool

find_datum_hash

Returns the DatumHash of datum data used in one the UTxO inputs.

tx.find_datum_hash(data: AnyType) -> ByteArray

get_datum_data

Returns the datum Data of a TxOutput. Throws an error if no datum is attached to the output.

tx.get_datum_data(output: TxOutput) -> Data

outputs_sent_to

Returns the TxOutputs sent to a regular payment address.

tx.outputs_sent_to(pkh: PubKeyHash) -> []TxOutput

outputs_sent_to_datum

Returns the TxOutputs sent to a regular payment address tagged with the given datum (datum tagging can be used to prevent double satisfaction exploits).

tx.outputs_sent_to_datum(
    pkh: PubKeyHash, 
    datum: AnyType, 
    is_inline: Bool
) -> []TxOutput

outputs_locked_by

Returns the TxOutputs being locked at the given script address.

tx.outputs_locked_by(script_hash: ValidatorHash) -> []TxOutput

outputs_locked_by_datum

Returns the TxOutputs being locked at the given script address with the given datum.

tx.outputs_locked_by_datum(
    script_hash: ValidatorHash, 
    datum: AnyType, 
    is_inline: Bool
) -> []TxOutput

value_paid_to

Returns the output Value sent to a generic payment address, with a specific inline datum.

tx.value_paid_to[InlineDatumDataType](
    address: Address,
    datum: InlineDatumDataType
) -> Value

value_sent_to

Returns the output Value sent to a regular payment address.

tx.value_sent_to(addr: PubKeyHash) -> Value

value_sent_to_datum

Returns the output Value sent to a regular payment address tagged with the given datum (datum tagging can be used to prevent double satisfaction exploits).

tx.value_sent_to_datum(
    addr: PubKeyHash, 
    datum: AnyType, 
    is_inline: Bool
) -> Value

value_locked_by

Returns the output Value being locked at the given script address.

tx.value_locked_by(script_hash: ValidatorHash) -> Value

value_locked_by_datum

Returns the output Value being locked at the given script address with the given datum.

tx.value_locked_by_datum(
    script_hash: ValidatorHash, 
    datum: AnyType, 
    is_inline: Bool
) -> Value

Helios language/ Builtins/

TxId

This is a type-safe wrapper around ByteArray representing the hash of a transaction.

Associated functions

new

TxId::new(bytes: ByteArray) -> TxId

from_data

TxId::from_data(data: Data) -> TxId

Getters

tx_id.bytes -> ByteArray

Operators

==

TxId == TxId -> Bool

!=

TxId != TxId -> Bool

>=

TxId >= TxId -> Bool

>

TxId > TxId -> Bool

<=

TxId <= TxId -> Bool

<

TxId < TxId -> Bool

Methods

serialize

tx_id.serialize() -> ByteArray

show

Hexadecimal representation of a TxId.

tx_id.show() -> String

Helios language/ Builtins/

TxInput

Represents a transaction input.

Associated functions

from_data

TxInput::from_data(data: Data) -> TxInput

new

Construct a TxInput instance. Only available after main, see script structure.

TxInput::new(
    output_id: TxOutputId,
    output:    TxOutput
) -> TxInput

Getters

address

Shortcut for tx_input.output.address:

tx_input.address -> Address

datum

Shortcut for tx_input.output.datum:

tx_intput.datum -> OutputDatum

output_id

Returns the TxOutputId of the underlying UTxO.

tx_input.output_id -> TxOutputId

output

Returns the underlying UTxO as a TxOutput.

tx_input.output -> TxOutput

value

Shortcut for tx_input.output.value:

tx_intput.value -> Value

Operators

==

TxInput == TxInput -> Bool

!=

TxInput != TxInput -> Bool

Methods

serialize

tx_input.serialize() -> ByteArray

Helios language/ Builtins/

TxOutput

Represents a transaction output.

Associated functions

from_data

TxOutput::from_data(data: Data) -> TxOutput

new

Construct a TxOutput instance.

TxOutput::new(
    address: Address,
    value:   Value,
    datum:   OutputDatum
) -> TxOutput

Getters

address

Returns the Address at which the TxOutput is located.

tx_output.address -> Address

value

Returns the Value locked in the TxOutput.

tx_output.value -> Value

datum

Returns the datum of the TxOutput as an OutputDatum.

tx_output.datum -> OutputDatum

ref_script_hash

Returns the ScriptHash of the optional reference script attached to the TxOutput.

tx_output.ref_script_hash -> Option[ScriptHash]

Operators

==

TxOutput == TxOutput -> Bool

!=

TxOutput != TxOutput -> Bool

Methods

serialize

tx_output.serialize() -> ByteArray

Helios language/ Builtins/

TxOutputId

Represents the unique ID of a UTxO. It's composed of the transaction ID (TxId) of the transaction that created that UTxO, and of the index (Int) of that UTxO in the outputs of that transaction.

Associated functions

new

TxOutputId::new(tx_id: TxId, index: Int) -> TxOutputId

from_data

TxOutputId::from_data(data: Data) -> TxOutputId

Getters

index

Index of the UTxO in the producing transaction:

tx_output_id.index -> Int

tx_id

TxId of the producing transaction:

tx_output_id.tx_id -> TxId

Operators

==

TxOutputId == TxOutputId -> Bool

!=

TxOutputId != TxOutputId -> Bool

>=

First compares bytes of TxId, then compares index.

TxOutputId >= TxOutputId -> Bool

>

First compares bytes of TxId, then compares index.

TxOutputId > TxOutputId -> Bool

<=

First compares bytes of TxId, then compares index.

TxOutputId <= TxOutputId -> Bool

<

First compares bytes of TxId, then compares index.

TxOutputId < TxOutputId -> Bool

Methods

serialize

tx_output_id.serialize() -> ByteArray

Helios language/ Builtins/

ValidatorHash

Opaque ByteArray that represents the hash of a validator script.

The first part of a script address is formed by a ValidatorHash.

Associated functions

new

ValidatorHash::new(bytes: ByteArray) -> ValidatorHash

from_data

ValidatorHash::from_data(data: Data) -> ValidatorHash

from_script_hash

Casts the generic ScriptHash type into ValidatorHash.

ValidatorHash::from_script_hash(hash: ScriptHash) -> ValidatorHash

Getters

bytes

validator_hash.bytes -> ByteArray

Operators

==

ValidatorHash == ValidatorHash -> Bool

!=

ValidatorHash != ValidatorHash -> Bool

>=

ValidatorHash >= ValidatorHash -> Bool

>

ValidatorHash > ValidatorHash -> Bool

<=

ValidatorHash <= ValidatorHash -> Bool

<

ValidatorHash < ValidatorHash -> Bool

Methods

serialize

validator_hash.serialize() -> ByteArray

show

Hexadecimal representation of the ValidatorHash.

validator_hash.show() -> String

Helios language/ Builtins/

Valuable

A type class that matches a type with the following interface:

a.value -> Value

Implicitly all automatic data type methods are also matched: ==, !=, from_data and serialize.

This type class is implemented by TxInput, TxOutput and Value. Value::sum() uses this type class to be able to sum the Value contained in a list of any of these types.

Helios language/ Builtins/

Value

The Value type represents monetary value as a token bundle (internally represented as a Map[MintingPolicyHash]Map[ByteArray]Int)

Note: 1 ADA is equal to 1 million Lovelace

Note: You might find yourself comparing the output of value.get() to a number in order to check if value contains something, but in that case it is usually better to use the value.contains() method instead.

Associated functions and constants

ZERO

An empty Value.

Value::ZERO -> Value

lovelace

Returns a Value containing only lovelace.

Value::lovelace(amount: Int) -> Value

new

Returns a Value containing an amount of a given AssetClass.

Value::new(asset_class: AssetClass, amount: Int) -> Value

from_data

Value::from_data(data: Data) -> Value

from_map

Instantiates a Value using a raw map.

Value::from_map(raw_value: Map[MintingPolicyHash]Map[ByteArray]Int) -> Value

sum

Sums any list with items that implement the Valuable type class.

Value::sum[V: Valuable](list: []V) -> Value

For example:

Value::sum(list: []Value) -> Value

Getters

value

Returns self. Allows Value to implement the Valuable type class, which in turn allows using Value::sum() associated method for a list of Value.

value.value -> Value

Operators

==

Returns true if two Values are the same.

Value == Value -> Bool

Note: the assets and tokens must also be in the same order for == to return true.

!=

Value != Value -> Bool

>=

Strict greater-equals comparison. If every lhs token has a greater-or-equals amount than the equivalent rhs token then >= returns true. If any rhs token has a greater amount than the equivalent lhs token then >= returns false.

Value >= Value -> Bool

>

Strict greater-than comparison. If every lhs token has a greater amount than the equivalent rhs token then > returns true. If any rhs token has a greater-or-equals amount than the equivalent lhs token then > returns false.

Value > Value -> Bool

<=

Strict less-equals comparison. If every lhs token has a smaller-or-equals amount than the equivalent rhs token then <= returns true. If any rhs token has a smaller amount than the equivalent lhs token, or doesn't exist in lhs, then <= returns false.

Value <= Value -> Bool

<

Strict less-than comparison. If every lhs token has a smaller amount than the equivalent rhs token then < returns true. If any rhs token has a smaller-or-equals amount than the equivalent lhs token, or doesn't exist in lhs, then < returns false.

Value < Value -> Bool

+

Value + Value -> Value

-

Subtracts two Value instances. Note that negative token amounts are possible.

Value - Value -> Value

*

Value * Int -> Value

/

Value / Int -> Value

Methods

contains

Alias for >= (where lhs is self).

value.contains(other_value: Value) -> Bool

contains_policy

Returns true if a given MintingPolicyHash is in a Value.

value.contains_policy(mph: MintingPolicyHash) -> Bool

get

Returns the amount of the given AssetClass in a Value. Throws error if the AssetClass isn't found.

value.get(asset_class: AssetClass) -> Int

get_assets

Returns a new Value with the lovelace removed.

value.get_assets() -> Value

get_lovelace

Returns the amount of lovelace in a Value. Returns 0 if there isn't any.

value.get_lovelace() -> Int

get_safe

Like get, but returns 0 instead of throwing an error if the given AssetClass isn't found.

value.get_safe(asset_class: AssetClass) -> Int

get_policy

Returns a map of tokens of the given MintingPolicyHash in a Value. Throws an error if the MintingPolicyHash isn't found.

value.get_policy(mph: MintingPolicyHash) -> Map[ByteArray]Int

is_zero

Checks if a Value is empty.

value.is_zero() -> Bool

serialize

value.serialize() -> ByteArray

show

Returns a formatted String showing all the assets contained in a Value.

value.show() -> String

to_map

Returning the underlying Map:

value.to_map() -> Map[MintingPolicyHash]Map[ByteArray]Int

Helios API

This chapter covers how to compile Helios sources and how to build Cardano transactions using the Helios Javascript/Typescript library.

Helios API/

Setup of the Helios Library

The Helios library is platform agnostic and can be used in many different ways.

Webpage script tag

<script src="https://helios.hyperion-bt.org/<version>/helios.js" type="module" crossorigin></script>

Module with CDN URL

Helios can be imported as a module using our CDN. This is supported by Deno and most modern browsers:

import * as helios from "https://helios.hyperion-bt.org/<version>/helios.js"

// or only the necessary parts (recommended as you get more acquainted with the library)
import { Program } from "https://helios.hyperion-bt.org/<version>/helios.js"

Alternatively you can use "helios" as a placeholder for the URL and, if not using any builder-tools, specify the module URL in an importmap (currently only supported by Chrome):

// in you javascript file
import * as helios from "helios"
<!-- in your html file -->
<script type="importmap">
    {
        "imports": {
            "helios": "https://helios.hyperion-bt.org/<version>/helios.js"
        }
    }
</script>

The examples in this chapter will use the placeholder approach.

npm

Install the latest version of the library using the following command:

$ npm i @hyperionbt/helios

Or install a specific version:

$ npm i @hyperionbt/helios@<version>

In your Javascript/Typescript file:

import { Program } from "@hyperionbt/helios"

We don't yet recommend installing the Helios library globally, as the API is still changing frequently.

Helios API/ Setup/

Deno as a VSCode language server

To use Deno as a VSCode language server you must first install the Deno CLI. Assuming you have access to a Linux-linux terminal:

$ curl -fsSL https://deno.land/x/install/install.sh | sh

This should download the deno binary to $HOME/.deno/bin/deno. Either add this directory to your PATH, or copy the binary to the system-wide bin directory:

$ sudo cp $HOME/.deno/bin/deno /usr/local/bin/deno

Make sure the .vscode/settings.json file points to the correct deno binary. For example:

{
    "deno.enable": true,
    "deno.path": "/usr/local/bin/deno"
}

External modules must be cached by Deno before you can benefit from their type annotations.

Cache external modules using the following command:

$ deno cache --reload my_entry_point.js

Helios API/

Compiling Helios sources

The recommended way to compile Helios sources is to use the library directly. This approach makes it easier to maintain a single-source-of-truth version of your contract in client-side dApps.

First step is to write your contract as a js literal string. For example:

const src = `
spending always_succeeds

func main(_, _, _) -> Bool {
    true
}`

Then you can create a Helios Program instance:

// at top of js file
import * as helios from "helios"
...
const program = helios.Program.new(src)

The Program instantiation will perform syntax and type checking, but won't actually do the compilation into the on-chain format. For that you need to call the compile method first:

const simplify = true

const myUplcProgram = program.compile(simplify)

Note: If simplify is true the resulting program is optimized for production. If simplify is false no optimizations are performed and print expressions aren't removed, which makes the resulting program more suitable for debugging.

Here myUplcProgram is an instance of UplcProgram (uplc stands for Untyped PLutus Core). A UplcProgram instance has methods for running, profiling, hashing, and serializing the contained Plutus-Core program.

Now you can serialize the UplcProgram into a JSON string that can be used by cardano-cli:

console.log(myUplcProgram.serialize())

// prints '{"type": PlutusScriptV2, "description": "", "cborHex": ...}'

When building transactions with Helios the UplcProgram instance is used directly when attaching scripts.

Helios API/

Generating datums and redeemers

Smart contract transactions include datum and redeemer data. You can generate these data structures using Helios.

Let's look at the following Helios script (as a literal string inside a js file):

const src = `
spending owner_only

struct Datum {
    owner: PubKeyHash
}

func main(datum: Datum, _, ctx: ScriptContext) -> Bool {
    ctx.tx.is_signed_by(datum.owner)
}

const MY_DATUM = Datum {
    PubKeyHash::new(#...)
}`

Remember that after the main function you can define data generators and test functions (see script structure).

MY_DATUM in this example can be evaluated using the API:

// at top of js file
import * as helios from "helios"
...
const program = helios.Program.new(src)

const myDatum = program.parameters["MY_DATUM"]

Here myDatum is a UplcValue instance. UplcValue is the internal (unexported) base class of every Helios value. To get the underlying data we can use the data getter:

const myDatumData = myDatum.data

Note: the UplcValue data getter doesn't work for booleans as booleans are always kept in their primitive Plutus-Core form for performance reasons.

Here myDatumData is a UplcData instance. UplcData is equivalent to the BuiltinData type in Plutus.

To create a JSON string that can be used by cardano-cli we can use the toSchemaJson method:

console.log(myDatumData.toSchemaJson())

// prints '{"constructor": 0, "fields": [...]}'

Helios API/

Building transactions

Besides compiling and generating data structures the Helios library can also be used to build transactions.

In this section we assume the Helios library has been imported in the following way:

import * as helios from "helios"

Tx

A new Tx instance acts as a transaction builder, using builder pattern methods.

const tx = new helios.Tx()

Overview

Helios API/ Building transactions/

Transaction inputs

Each transaction input is an instance of the TxInput class. A TxInput represents a TxOutputId and, when building a new transaction, also contains the underlying TxOutput.

const utxo = new helios.TxInput(
    helios.TxOutputId.fromHex("...", 0n),
    new helios.TxOutput(...) // TxOutput with address, value and datum fields
)

Spending a regular UTxO

Spending a regular UTxO (i.e. non-script UTxO), is done with the addInput method:

tx.addInput(utxo)

Spending a script UTxO

Spending a UTxO locked at a script address is also done with addInput, but requires specifying a redeemer:

// program.evalParam("...").data can be used directly as 'redeemerData'
tx.addInput(utxo, redeemerData)

The corresponding script must be also be attached to such a transaction:

// 'uplcProgram' is an instance of UplcProgram (i.e. result of helios.Program.new(...).compile(...))
tx.attachScript(uplcProgram)

Helios API/ Building transactions/

Transaction outputs

Each transaction output is an instance of the TxOutput class. A TxOutput contains an Address, a Value, and, optionally, a Datum field.

Example: TxOutput instance without a datum

const output = new helios.TxOutput(
    helios.Address.fromBech32("addr_test..."),
    new helios.Value(1000000n), // 1 tAda == 1 million lovelace
)

Example: TxOutput instance with an inline datum

const outputWithDatum = new helios.TxOutput(
    helios.Address.fromBech32("addr_test..."),
    new helios.Value(1000000n),
    helios.Datum.inline(...), // result from program.evalParam("...").data can be used directly as an argument for Datum.inline()
)

Adding a TxOutput to a Tx

A TxOutput can be added to the transaction with the addOutput method:

tx.addOutput(output)

Multiple outputs at once with the addOutputs method:

tx.addOutputs(outputs)

Helios API/ Building transactions/

Collateral

Some UTxOs must be added as collateral to the transaction in case the transaction interacts with smart contracts:

tx.addCollateral(utxo)

Note: the collateral is only lost if the transaction fails once submitted. There are however plenty of checks that happen before the transaction is submitted to the blockchain mem-pool, so such a situation is very unlikely.

Note: since v0.12.6 of Helios, setting the collateral is no longer necessary. If unset, the collateral (and collateral return) is set automatically inside tx.finalize().

Helios API/ Building transactions/

Explicit signers

Explicit signers are actors who approve the transaction without necessarily sending or receiving UTxOs.

Only these explicit signers appear in the tx.signatories field.

Signers are identified by their PubKeyHash:

tx.addSigner(helios.PubKeyHash.fromHex("..."))

Helios API/ Building transactions/

Minting

Tokens can be minted using the mintTokens method. The UplcProgram of the corresponding minting policy must also be attached:

tx
    .mintTokens(
        uplcProgram.mintingPolicyHash, 
        [["my_first_nft", 1n], ["my_second_nft", 1n]], 
        redeemerData // can be generated using program.evalParam("...").data
    )
    .attachScript(uplcProgram)

Note: the transaction building methods can be chained.

Helios API/ Building transactions/

Finalizing

Before signing the serialized transaction using a wallet, the transaction must be finalized. The finalization process calculates the transaction fee, balances the transaction, and checks min collateral and min lovelace deposit requirements.

Finalization requires the most recent network parameters (see below), a change address for balancing, and optionally some additional UTxOs that will be used if the inputs specified by the user don't contain enough lovelace to cover the fees and deposits:

// async because scripts are evaluated asyncronously

await tx.finalize(networkParams, changeAddress, extraUTxOs)

Note: finalize is asynchronous because script evaluation is asynchronous. Script evaluation is asynchronous so that interactive debuggers can easily step through the evaluation process.

Network parameters

The finalization process require downloading the latest network parameters. For example, for the preview testnet:

// in an async context

const networkParams = new helios.NetworkParams(
    await fetch("https://d1t0d7c2nekuk0.cloudfront.net/preview.json")
        .then(response => response.json())
)

Note: we've set up a CDN with daily updated raw network parameters:

Helios API/ Building transactions/

Signing and submitting a transactions

Signing

The finalized transaction can be signed by a wallet, for example using the CIP 30 dApp connector:

// in an async context

const response = await walletHandle.signTx(helios.bytesToHex(tx.toCbor()), true)

// extract the deserialized signatures
const signatures = helios.TxWitnesses.fromCbor(helios.hexToBytes(response)).signatures

tx.addSignatures(signatures)

Note: the bytesToHex and hexToBytes functions are provided by the Helios library as convenient and unambiguous ways to convert a byte-array between string hexadecimal format and raw lists of bytes.

Submitting

After adding the wallet signatures to the transaction, the transaction can be submitted:

// in async context

// returns the hash of the tx
await walletHandle.submitTx(helios.bytesToHex(tx.toCbor()))

Helios API/

Example: PicoSwap

This section walks you through building a minimal marketplace dApp using Helios. The full demo is hosted here.

Only the Helios-specific parts are covered (i.e. not the UI, not the wallet interaction, and not the blockchain queries). This example is intended as an alternate introduction to the Helios API, and shouldn't be seen as an authoritative guide on how to write secure dApps.

We assume here that the library has been imported in the following way:

import * as helios from "helios"

Overview

Helios API/ Example: PicoSwap/

Main script

The source of the validator script can be placed in a js literal string:

const mainScript = `
spending picoswap

// Note: each input UTxO must contain some lovelace, so the datum price will be a bit higher than the nominal price
// Note: public sales are possible when a buyer isn't specified
 
struct Datum {
    seller: PubKeyHash
    price:  Value              
    buyer:  Option[PubKeyHash]
    nonce:  Int // double satisfaction protection
 
    func seller_signed(self, tx: Tx) -> Bool {
        tx.is_signed_by(self.seller)
    }
 
    func buyer_signed(self, tx: Tx) -> Bool {
        self.buyer.switch{
            None    => true,
            s: Some => tx.is_signed_by(s.some)
        }
    }
 
    func seller_received_money(self, tx: Tx) -> Bool {
        // protect against double satisfaction exploit by datum tagging the output using a nonce
        tx.value_sent_to_datum(self.seller, self.nonce, false) >= self.price
     }
 }
 
func main(datum: Datum, _, ctx: ScriptContext) -> Bool {
    tx: Tx = ctx.tx;
 
    // sellers can do whatever they want with the locked UTxOs
    datum.seller_signed(tx) || (
        // buyers can do whatever they want with the locked UTxOs, as long as the sellers receive their end of the deal
        datum.buyer_signed(tx) && 
        datum.seller_received_money(tx)
    )
}`

We recommend including a Show script or Show contract button in every dApp so users can easily audit the smart contract logic they are interacting with.

Helios API/ Example: PicoSwap/

Generating datums

We can use the following Helios code to generate datums:

const datumScript = `
const SELLER_BYTES   = # // must be 28 bytes long
const PRICE_LOVELACE = 0
const BUYER_BYTES    = # // must be 0 or 28 bytes long
const NONCE          = 0

const DATUM = Datum{
    seller: PubKeyHash::new(SELLER_BYTES),
    price:  Value::lovelace(PRICE_LOVELACE),
    buyer:  if (BUYER_BYTES.length == 0) {
                Option[PubKeyHash]::None
            } else {
                Option[PubKeyHash]::Some{PubKeyHash::new(BUYER_BYTES)}
            },
    nonce:  NONCE
}`

Before generating a datum with evalParam, we concatenate mainScript with datumScript and change the values of the input parameters:

/**
 * @param {helios.Address} seller
 * @param {bigint} price
 * @returns {helios.UplcData}
 */
function generatePublicSaleDatum(seller, price) {
    // public sale, don't set the buyer bytes
    return helios.Program.new(mainScript + datumScript)
        .changeParam("SELLER_BYTES",   JSON.stringify(seller.pubKeyHash.bytes))
        .changeParam("PRICE_LOVELACE", price.toString())
        .changeParam("NONCE",          (Math.random()*1000000).toString())
        .evalParam("DATUM").data
}

Note: the program.changParam() method takes as a second argument a JSON string, or a UplcValue (i.e. the result of a evalParam call). It doesn't take an arbitrary object however, as that might get confused for the internals of a UplcValue.

Helios API/ Example: PicoSwap/

Contract helper class

Before describing PicoSwap's smart contract end-points, it is helpful to define a Contract class that can be instantiated for each set of UTxOs locked at the script address having the same datum.

class Contract {
    /**
     * @param {helios.ConstrData} datum - not a helios.Datum instance!
     * @param {helios.UTxO[]} utxos
     */
    constructor(datum, utxos) {
        this.datum = datum
        this.utxos = utxos
    }

    get seller() {
        return new helios.PubKeyHash(this.datum.fields[0].bytes)
    }

    get sellerAddress() {
        // true -> testnet
        return helios.Address.fromPubKeyHash(true, this.seller)
    }

    get price() {
        return helios.Value.fromData(this.datum.fields[1])
    }

    get forSale() {
        return helios.UTxO.sumValue(this.utxos)
    }

    get nonce() {
        return this.datum.fields[3].int
    }
}

Note: ConstrData is one of the 5 child-types of UplcData. The other UplcData child-types are: IntData, ByteArrayData, ListData and MapData.

Grouping the contract UTxOs and extracting the inline datum data is left as an exercise to the reader.

Helios API/ Example: PicoSwap/

Creating a new sale

A new sale is created by sending funds (the forSale assets) to the contract address with the appropriate datum.

The following function creates a transaction that represents a new sale:

/**
 * @param {helios.Value} forSale
 * @param {bigint} price - in lovelace
 * @returns {Promise<helios.Tx>} - the finalized, but unsigned transaction
 */
async function createNewSaleTx(forSale, price) {
    const uplcProgram = helios.Program.new(mainScript).compile(true)

    const forSaleUtxos = /* code that picks some utxos that cover the 'forSale' value */
    const changeAddress = /* code that picks the changeAddress */

    // create the forSale output that will be locked at the script address
    const output = new helios.TxOutput(
        helios.Address.fromValidatorHash(
            true, // true -> testNet
            uplcProgram.validatorHash
        ),
        forSale,
        helios.Datum.inline(generatePublicSaleDatum(changeAddress, price)) // changeAddress is also the seller address
    )

    // the output might not contain any lovelace, that must be corrected (and the price in the datum must be increased accordingly)
    output.correctLovelace(networkParams, (output) => {
        // increase the price by the min amount of lovelace needed as a deposit
        output.setDatum(
            helios.Datum.inline(
                generatePublicSaleDatum(
                    changeAddress, 
                    price + output.value.lovelace
                )
            )
        );
    })    

    return await ((new helios.Tx())
        .addInputs(forSaleUtxos)
        .addOutput(output)
        .finalize(networkParams, changeAddress)
    )
}

Helios API/ Example: PicoSwap/

Canceling a sale

A seller can cancel a sale before it is fulfilled.

The following function creates the cancel transaction:

/**
 * @param {Contract} contract - instantiated elsewhere
 * @returns {Promise<helios.Tx>} - finalized but unsigned transaction
 */
async function cancelSaleTx(contract) {
    const uplcProgram = helios.Program.new(mainScript).compile(true)

    const feeUtxos = /* code that picks the utxos with which the tx fee will be paid */
    const changeAddress = /* code that picks the change address */

    // we must add the seller as an explicit signer, some collateral and attach the script
    return await ((new helios.Tx())
        .addInputs(feeUtxos)
        .addInputs(contract.utxos, new helios.IntData(42n)) // dummy redeemer
        // send all the contract utxos back to the seller (i.e. back to the changeAddress)
        .addOutputs(contract.utxos.map(utxo => new helios.TxOutput( 
            changeAddress, utxo.origOutput.value
        )))
        .addSigner(contract.seller)
        .addCollateral(feeUtxos[0]) // assume one of the feeUtxos is big enough to be used as collateral
        .attachScript(uplcProgram)
        .finalize(networkParams, changeAddress)
    )
}

Helios API/ Example: PicoSwap/

Buying for-sale assets

Anyone can buy the assets locked in the script by sending the price Value to the seller.

The following function creates the buy transaction:

/**
 * @param {Contract} contract - instantiated elsewhere
 * @returns {Promise<helios.Tx>} - finalized but unsigned transaction
 */
async function buyTx(contract) {
    const uplcProgram = helios.Program.new(mainScript).compile(true)

    const paymentUtxos = /* code that picks the utxos used for payment */
    const changeAddress = /* code that picks the change address */
    
    return await ((new helios,Tx())
        .addInputs(paymentUtxos)
        .addInputs(contract.utxos, new helios.IntData(42n)) // dummy redeemer
        .attachScript(uplcProgram)
        .addOutput(new helios.TxOutput( // send 'price' to seller
            contract.sellerAddress,
            contract.price,
            helios.Datum.hashed(new helios.IntData(contract.nonce)) // nonce that protects agains double satisfaction exploit
        ))
        .addOutputs(contract.utxos.map( // send for-sale assets to buyer
            // preserve the number of UTxOs
            utxo => new helios.TxOutput(changeAddress, utxo.value)
        ))
        .addCollateral(/* code that picks collateral UTxOs */)
        .finalize(networkParams, changeAddress)
    )
}

Helios API/

API Reference

This section contains a complete reference of all the classes, functions, interfaces, types and variables exported by the Helios library.

Typescript annotations are used to document types.

Overview

Classes

Functions

Interfaces

Types

Variables

Helios API/ API Reference/

Classes

Helios API/ API Reference/ Classes/

Address

Wrapper for Cardano address bytes. An Address consists of three parts internally:

  • Header (1 byte, see CIP 19)
  • Witness hash (28 bytes that represent the PubKeyHash or ValidatorHash)
  • Optional staking credential (0 or 28 bytes)

Hierarchy

Index

Constructors

constructor

new Address(bytesOrBech32String)

Parameters

NameType
bytesOrBech32Stringstring | number[]

Overrides

HeliosData.constructor

Accessors

bytes

get bytes(): number[]

Returns

number[]

hex

get hex(): string

Converts a Address into its hexadecimal representation.

Returns

string

pubKeyHash

get pubKeyHash(): null | PubKeyHash

Returns the underlying PubKeyHash of a simple payment address, or null for a script address.

Returns

null | PubKeyHash

stakingHash

get stakingHash(): null | PubKeyHash | StakingValidatorHash

Returns the underlying PubKeyHash or StakingValidatorHash, or null for non-staked addresses.

Returns

null | PubKeyHash | StakingValidatorHash

validatorHash

get validatorHash(): null | ValidatorHash

Returns the underlying ValidatorHash of a script address, or null for a regular payment address.

Returns

null | ValidatorHash

Methods

dump

dump(): any

Returns

any

eq

eq(other): boolean

Parameters

NameType
otherAddress

Returns

boolean

toBech32

toBech32(): string

Converts an Address into its Bech32 representation.

Returns

string

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

HeliosData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

HeliosData.toCborHex

toHex

toHex(): string

Converts a Address into its hexadecimal representation.

Returns

string

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

HeliosData.toSchemaJson

dummy

Static dummy(): Address

Returns a dummy address (based on a PubKeyHash with all null bytes)

Returns

Address

fromBech32

Static fromBech32(str): Address

Converts a Bech32 string into an Address.

Parameters

NameType
strstring

Returns

Address

fromCbor

Static fromCbor(bytes): Address

Deserializes bytes into an Address.

Parameters

NameType
bytesnumber[]

Returns

Address

fromHash

Static fromHash(hash, isTestnet?): Address

Constructs an Address using either a PubKeyHash (i.e. simple payment address) or ValidatorHash (i.e. script address), without a staking hash.

Parameters

NameTypeDescription
hashPubKeyHash | ValidatorHash
isTestnet?booleanDefaults to config.IS_TESTNET

Returns

Address

fromHashes

Static fromHashes(hash, stakingHash?, isTestnet?): Address

Constructs an Address using either a PubKeyHash (i.e. simple payment address) or ValidatorHash (i.e. script address), in combination with an optional staking hash (PubKeyHash or StakingValidatorHash).

Parameters

NameTypeDescription
hashPubKeyHash | ValidatorHash
stakingHash?null | PubKeyHash | StakingValidatorHash
isTestnet?booleanDefaults to config.IS_TESTNET

Returns

Address

fromHex

Static fromHex(hex): Address

Constructs an Address using a hexadecimal string representation of the address bytes. Doesn't check validity.

Parameters

NameType
hexstring

Returns

Address

fromProps

Static fromProps(props): Address

Parameters

NameType
propsAddress | AddressProps

Returns

Address

fromUplcData

Static fromUplcData(data, isTestnet?): Address

Parameters

NameType
dataUplcData
isTestnet?boolean

Returns

Address

isForTestnet

Static isForTestnet(address): boolean

Returns true if the given Address is a testnet address.

Parameters

NameType
addressAddress

Returns

boolean

Helios API/ API Reference/ Classes/

AssetClass

Represents a MintingPolicyHash combined with a token name.

Hierarchy

Index

Constructors

constructor

new AssetClass(props)

Intelligently converts arguments.

The format for single argument string is ".".

Parameters

NameType
propsAssetClassProps

Overrides

HeliosData.constructor

Accessors

mintingPolicyHash

get mintingPolicyHash(): MintingPolicyHash

Returns

MintingPolicyHash

tokenName

get tokenName(): ByteArray

Returns

ByteArray

ADA

Static get ADA(): AssetClass

Returns

AssetClass

Methods

_toUplcData

_toUplcData(): ConstrData

Used when generating script contexts for running programs

Returns

ConstrData

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

HeliosData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

HeliosData.toCborHex

toFingerprint

toFingerprint(): string

Cip14 fingerprint This involves a hash, so you can't use a fingerprint to calculate the underlying policy/tokenName.

Returns

string

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

HeliosData.toSchemaJson

fromCbor

Static fromCbor(bytes): AssetClass

Deserializes bytes into an AssetClass.

Parameters

NameType
bytesnumber[]

Returns

AssetClass

fromProps

Static fromProps(props): AssetClass

Parameters

NameType
propsAssetClass | AssetClassProps

Returns

AssetClass

fromUplcCbor

Static fromUplcCbor(bytes): AssetClass

Parameters

NameType
bytesstring | number[]

Returns

AssetClass

fromUplcData

Static fromUplcData(data): AssetClass

Parameters

NameType
dataUplcData

Returns

AssetClass

Helios API/ API Reference/ Classes/

Assets

Represents a list of non-Ada tokens.

Hierarchy

Index

Constructors

constructor

new Assets(props?)

Note: the assets are normalized by removing entries with 0 tokens, and merging all entries with the same MintingPolicyHash and token name.

Parameters

NameTypeDescription
props?AssetsPropsEither a list of AssetClass/quantity pairs, or a list of MintingPolicyHash/tokens pairs (where each tokens entry is a bytearray/quantity pair).

Overrides

CborData.constructor

Accessors

mintingPolicies

get mintingPolicies(): MintingPolicyHash[]

Returns a list of all the minting policies.

Returns

MintingPolicyHash[]

nTokenTypes

get nTokenTypes(): number

Returns

number

Methods

_toUplcData

_toUplcData(): MapData

Used when generating script contexts for running programs

Returns

MapData

add

add(other): Assets

Parameters

NameType
otherAssets

Returns

Assets

addComponent

addComponent(mph, tokenName, qty): void

Mutates 'this'.

Parameters

Returns

void

addTokens

addTokens(mph, tokens): void

Mutates 'this'. Throws error if mph is already contained in 'this'.

Parameters

Returns

void

allPositive

allPositive(): boolean

Returns

boolean

assertAllPositive

assertAllPositive(): void

Throws an error if any contained quantity <= 0n

Returns

void

assertSorted

assertSorted(): void

Returns

void

dump

dump(): any

Returns

any

eq

eq(other): boolean

Parameters

NameType
otherAssets

Returns

boolean

ge

ge(other): boolean

Parameters

NameType
otherAssets

Returns

boolean

get

get(mph, tokenName): bigint

Parameters

Returns

bigint

getTokenNames

getTokenNames(mph): ByteArray[]

Parameters

Returns

ByteArray[]

getTokens

getTokens(mph): [ByteArray, HInt][]

Returns empty if mph not found

Parameters

NameType
mphMintingPolicyHash

Returns

[ByteArray, HInt][]

gt

gt(other): boolean

Strict gt, if other contains assets this one doesn't contain => return false

Parameters

NameType
otherAssets

Returns

boolean

has

has(mph, tokenName): boolean

Parameters

Returns

boolean

isZero

isZero(): boolean

Returns

boolean

mul

mul(scalar): Assets

Parameters

NameType
scalarHInt | HIntProps

Returns

Assets

normalize

normalize(): void

Removes zeros and merges duplicates. In-place algorithm. Keeps the same order as much as possible.

Returns

void

removeZeroes

removeZeroes(): void

Mutates 'this'

Returns

void

sort

sort(): void

Makes sure minting policies are in correct order, and for each minting policy make sure the tokens are in the correct order Mutates 'this'

Returns

void

sub

sub(other): Assets

Parameters

NameType
otherAssets

Returns

Assets

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

CborData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

CborData.toCborHex

fromCbor

Static fromCbor(bytes): Assets

Parameters

NameType
bytesnumber[]

Returns

Assets

fromProps

Static fromProps(props): Assets

Parameters

NameType
propsAssets | AssetsProps

Returns

Assets

Helios API/ API Reference/ Classes/

Bip32PrivateKey

Ed25519-Bip32 extendable PrivateKey.

Implements

Implements

Index

Constructors

constructor

new Bip32PrivateKey(bytes)

Parameters

NameType
bytesnumber[]

Accessors

bytes

get bytes(): number[]

Returns

number[]

Methods

derive

derive(i): Bip32PrivateKey

Parameters

NameType
inumber

Returns

Bip32PrivateKey

derivePath

derivePath(path): Bip32PrivateKey

Parameters

NameType
pathnumber[]

Returns

Bip32PrivateKey

derivePubKey

derivePubKey(): PubKey

Returns

PubKey

Implementation of

PrivateKey.derivePubKey

sign

sign(message): Signature

Parameters

NameType
messagenumber[]

Returns

Signature

Example

(new Bip32PrivateKey([0x60, 0xd3, 0x99, 0xda, 0x83, 0xef, 0x80, 0xd8, 0xd4, 0xf8, 0xd2, 0x23, 0x23, 0x9e, 0xfd, 0xc2, 0xb8, 0xfe, 0xf3, 0x87, 0xe1, 0xb5, 0x21, 0x91, 0x37, 0xff, 0xb4, 0xe8, 0xfb, 0xde, 0xa1, 0x5a, 0xdc, 0x93, 0x66, 0xb7, 0xd0, 0x03, 0xaf, 0x37, 0xc1, 0x13, 0x96, 0xde, 0x9a, 0x83, 0x73, 0x4e, 0x30, 0xe0, 0x5e, 0x85, 0x1e, 0xfa, 0x32, 0x74, 0x5c, 0x9c, 0xd7, 0xb4, 0x27, 0x12, 0xc8, 0x90, 0x60, 0x87, 0x63, 0x77, 0x0e, 0xdd, 0xf7, 0x72, 0x48, 0xab, 0x65, 0x29, 0x84, 0xb2, 0x1b, 0x84, 0x97, 0x60, 0xd1, 0xda, 0x74, 0xa6, 0xf5, 0xbd, 0x63, 0x3c, 0xe4, 0x1a, 0xdc, 0xee, 0xf0, 0x7a])).sign(textToBytes("Hello World")).bytes == [0x90, 0x19, 0x4d, 0x57, 0xcd, 0xe4, 0xfd, 0xad, 0xd0, 0x1e, 0xb7, 0xcf, 0x16, 0x17, 0x80, 0xc2, 0x77, 0xe1, 0x29, 0xfc, 0x71, 0x35, 0xb9, 0x77, 0x79, 0xa3, 0x26, 0x88, 0x37, 0xe4, 0xcd, 0x2e, 0x94, 0x44, 0xb9, 0xbb, 0x91, 0xc0, 0xe8, 0x4d, 0x23, 0xbb, 0xa8, 0x70, 0xdf, 0x3c, 0x4b, 0xda, 0x91, 0xa1, 0x10, 0xef, 0x73, 0x56, 0x38, 0xfa, 0x7a, 0x34, 0xea, 0x20, 0x46, 0xd4, 0xbe, 0x04]

Implementation of

PrivateKey.sign

fromBip39Entropy

Static fromBip39Entropy(entropy, force?): Bip32PrivateKey

Parameters

NameType
entropynumber[]
force?boolean

Returns

Bip32PrivateKey

random

Static random(random?): Bip32PrivateKey

Generate a Bip32PrivateKey from a random number generator. This is not cryptographically secure, only use this for testing purpose

Parameters

NameType
random?NumberGenerator

Returns

Bip32PrivateKey

Helios API/ API Reference/ Classes/

BitWriter

BitWriter turns a string of '0's and '1's into a list of bytes. Finalization pads the bits using '0*1' if not yet aligned with the byte boundary.

Index

Constructors

constructor

new BitWriter()

Methods

pop

pop(n): string

Pop n bits of the end

Parameters

NameType
nnumber

Returns

string

Helios API/ API Reference/ Classes/

BlockfrostV0

Blockfrost specific implementation of Network.

Implements

Implements

Index

Constructors

constructor

new BlockfrostV0(networkName, projectId)

Constructs a BlockfrostV0 using the network name (preview, preprod or mainnet) and your Blockfrost project_id.

Parameters

NameType
networkName"preview" | "preprod" | "mainnet"
projectIdstring

Accessors

networkName

get networkName(): string

Returns

string

Methods

dumpMempool

dumpMempool(): Promise<void>

Allows inspecting the live Blockfrost mempool.

Returns

Promise<void>

getLatestEpoch

getLatestEpoch(): Promise<any>

Returns

Promise<any>

getParameters

getParameters(): Promise<NetworkParams>

Returns

Promise<NetworkParams>

Implementation of

Network.getParameters

getUtxo

getUtxo(id): Promise<TxInput>

If the UTxO isn't found an error is throw with the following message format: "UTxO <txId.utxoId> not found".

Parameters

NameType
idTxOutputId

Returns

Promise<TxInput>

Implementation of

Network.getUtxo

getUtxos

getUtxos(address): Promise<TxInput[]>

Gets a complete list of UTxOs at a given Address. Returns oldest UTxOs first, newest last.

Parameters

NameType
addressAddress

Returns

Promise<TxInput[]>

Implementation of

Network.getUtxos

hasUtxo

hasUtxo(utxo): Promise<boolean>

Used by BlockfrostV0.resolve().

Parameters

NameType
utxoTxInput

Returns

Promise<boolean>

submitTx

submitTx(tx): Promise<TxId>

Submits a transaction to the blockchain.

Parameters

NameType
txTx

Returns

Promise<TxId>

Implementation of

Network.submitTx

resolve

Static resolve(utxoOrWallet, projectIds): Promise<BlockfrostV0>

Connects to the same network a given Wallet or the given TxInput (preview, preprod or mainnet).

Throws an error if a Blockfrost project_id is missing for that specific network.

Parameters

NameType
utxoOrWalletTxInput | Wallet
projectIdsObject
projectIds.mainnet?string
projectIds.preprod?string
projectIds.preview?string

Returns

Promise<BlockfrostV0>

resolveUsingUtxo

Static resolveUsingUtxo(refUtxo, projectIds): Promise<BlockfrostV0>

Throws an error if a Blockfrost project_id is missing for that specific network.

Parameters

NameType
refUtxoTxInput
projectIdsObject
projectIds.mainnet?string
projectIds.preprod?string
projectIds.preview?string

Returns

Promise<BlockfrostV0>

resolveUsingWallet

Static resolveUsingWallet(wallet, projectIds): Promise<BlockfrostV0>

Connects to the same network a given Wallet is connected to (preview, preprod or mainnet).

Throws an error if a Blockfrost project_id is missing for that specific network.

Parameters

NameType
walletWallet
projectIdsObject
projectIds.mainnet?string
projectIds.preprod?string
projectIds.preview?string

Returns

Promise<BlockfrostV0>

Helios API/ API Reference/ Classes/

ByteArray

Helios ByteArray type

Deprecated

Hierarchy

Index

Constructors

constructor

new ByteArray(props)

Parameters

NameType
propsByteArrayProps

Overrides

HeliosData.constructor

Accessors

bytes

get bytes(): number[]

Returns

number[]

hex

get hex(): string

Hexadecimal representation.

Returns

string

Methods

eq

eq(other): boolean

Parameters

NameType
otherByteArray | ByteArrayProps

Returns

boolean

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

HeliosData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

HeliosData.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

HeliosData.toSchemaJson

fromCbor

Static fromCbor(bytes): ByteArray

Parameters

NameType
bytesnumber[]

Returns

ByteArray

fromProps

Static fromProps(props): ByteArray

Parameters

NameType
propsByteArray | ByteArrayProps

Returns

ByteArray

fromUplcCbor

Static fromUplcCbor(bytes): ByteArray

Parameters

NameType
bytesstring | number[]

Returns

ByteArray

fromUplcData

Static fromUplcData(data): ByteArray

Parameters

NameType
dataUplcData

Returns

ByteArray

Helios API/ API Reference/ Classes/

ByteArrayData

Plutus-core bytearray data class. Wraps a regular list of uint8 numbers (so not Uint8Array)

Hierarchy

Index

Constructors

constructor

new ByteArrayData(bytes)

Parameters

NameType
bytesnumber[]

Overrides

UplcData.constructor

Accessors

hex

get hex(): string

Returns

string

memSize

get memSize(): number

Estimate of memory usage during validation

Returns

number

Inherited from

UplcData.memSize

Methods

isSame

isSame(other): boolean

Compares the schema jsons

Parameters

NameType
otherUplcData

Returns

boolean

Inherited from

UplcData.isSame

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

UplcData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

UplcData.toCborHex

toHex

toHex(): string

Returns

string

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

UplcData.toSchemaJson

transfer

transfer(other): any

Parameters

NameType
otherTransferUplcAst

Returns

any

Inherited from

UplcData.transfer

fromCbor

Static fromCbor(bytes): ByteArrayData

Parameters

NameType
bytesnumber[]

Returns

ByteArrayData

Overrides

UplcData.fromCbor

fromString

Static fromString(s): ByteArrayData

Applies utf-8 encoding

Parameters

NameType
sstring

Returns

ByteArrayData

memSizeInternal

Static memSizeInternal(bytes): number

Calculates the mem size of a byte array without the DATA_NODE overhead.

Parameters

NameType
bytesnumber[]

Returns

number

Helios API/ API Reference/ Classes/

CborData

Base class of any Cbor serializable data class Also

Hierarchy

Index

Constructors

constructor

new CborData()

Methods

toCbor

toCbor(): number[]

Returns

number[]

toCborHex

toCborHex(): string

Returns

string

Helios API/ API Reference/ Classes/

Cip30Wallet

Implementation of Wallet that lets you connect to a browser plugin wallet.

Implements

Implements

Index

Constructors

constructor

new Cip30Wallet(handle)

Constructs Cip30Wallet using the Cip30Handle which is available in the browser window.cardano context.

const handle: helios.Cip30Handle = await window.cardano.eternl.enable()
const wallet = new helios.Cip30Wallet(handle)

Parameters

NameType
handleCip30Handle

Accessors

collateral

get collateral(): Promise<TxInput[]>

Returns

Promise<TxInput[]>

Implementation of

Wallet.collateral

rewardAddresses

get rewardAddresses(): Promise<StakeAddress[]>

Gets a list of unique reward addresses which can be used to UTxOs to.

Returns

Promise<StakeAddress[]>

Implementation of

Wallet.rewardAddresses

unusedAddresses

get unusedAddresses(): Promise<Address[]>

Gets a list of unique unused addresses which can be used to UTxOs to.

Returns

Promise<Address[]>

Implementation of

Wallet.unusedAddresses

usedAddresses

get usedAddresses(): Promise<Address[]>

Gets a list of addresses which contain(ed) UTxOs.

Returns

Promise<Address[]>

Implementation of

Wallet.usedAddresses

utxos

get utxos(): Promise<TxInput[]>

Gets the complete list of UTxOs (as TxInput instances) sitting at the addresses owned by the wallet.

Returns

Promise<TxInput[]>

Implementation of

Wallet.utxos

Methods

isMainnet

isMainnet(): Promise<boolean>

Returns true if the wallet is connected to the mainnet.

Returns

Promise<boolean>

Implementation of

Wallet.isMainnet

signData

signData(addr, sigStructure): Promise<{ key: string ; signature: string }>

Sign a data payload with the users wallet.

Parameters

NameTypeDescription
addrAddressA Cardano address object
sigStructurestringThe message to sign, in string format.

Returns

Promise<{ key: string ; signature: string }>

Implementation of

Wallet.signData

signTx

signTx(tx): Promise<Signature[]>

Signs a transaction, returning a list of signatures needed for submitting a valid transaction.

Parameters

NameType
txTx

Returns

Promise<Signature[]>

Implementation of

Wallet.signTx

submitTx

submitTx(tx): Promise<TxId>

Submits a transaction to the blockchain.

Parameters

NameType
txTx

Returns

Promise<TxId>

Implementation of

Wallet.submitTx

Helios API/ API Reference/ Classes/

ConstrData

Represents a tag index and a list of UplcData fields.

Hierarchy

Index

Constructors

constructor

new ConstrData(index, fields)

Parameters

NameType
indexnumber
fieldsUplcData[]

Overrides

UplcData.constructor

Accessors

memSize

get memSize(): number

Estimate of memory usage during validation

Returns

number

Inherited from

UplcData.memSize

Methods

isSame

isSame(other): boolean

Compares the schema jsons

Parameters

NameType
otherUplcData

Returns

boolean

Inherited from

UplcData.isSame

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

UplcData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

UplcData.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

UplcData.toSchemaJson

transfer

transfer(other): any

Parameters

NameType
otherTransferUplcAst

Returns

any

Inherited from

UplcData.transfer

fromCbor

Static fromCbor(bytes): ConstrData

Parameters

NameType
bytesnumber[]

Returns

ConstrData

Overrides

UplcData.fromCbor

Helios API/ API Reference/ Classes/

DCert

A DCert represents a staking action (eg. withdrawing rewards, delegating to another pool).

Hierarchy

Index

Constructors

constructor

new DCert(certType)

Parameters

NameType
certTypenumber

Overrides

CborData.constructor

Accessors

certType

get certType(): number

Get certificate type.

Returns

number

credentialType

get credentialType(): number

Get stake credential type.

Returns

number

stakeHash

get stakeHash(): PubKeyHash | StakingValidatorHash

Get stake hash.

Returns

PubKeyHash | StakingValidatorHash

Methods

dump

dump(): any

Returns

any

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

CborData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

CborData.toCborHex

toData

toData(): ConstrData

Returns

ConstrData

typeToCbor

typeToCbor(): number[]

Returns

number[]

fromCbor

Static fromCbor(raw): DCert

Parameters

NameType
rawstring | number[]

Returns

DCert

fromJson

Static fromJson(json): DCert

Create a DCert from a given json parameter.

Parameters

NameType
jsonstring | { credential: { hash: string ; type: 0 | 1 } ; poolHash?: string ; type: 0 | 2 | 1 }

Returns

DCert

fromUplcData

Static fromUplcData(data): DCert

Parameters

NameType
dataUplcData

Returns

DCert

Helios API/ API Reference/ Classes/

Datum

Represents either an inline datum, or a hashed datum.

Inside the Helios language this type is named OutputDatum in order to distinguish it from user defined Datums, But outside helios scripts there isn't much sense to keep using the name 'OutputDatum' instead of Datum.

Hierarchy

Index

Constructors

constructor

new Datum()

Inherited from

CborData.constructor

Accessors

data

get data(): null | UplcData

Returns

null | UplcData

hash

get hash(): DatumHash

Returns

DatumHash

Methods

dump

dump(): any

Returns

any

isHashed

isHashed(): boolean

Returns

boolean

isInline

isInline(): boolean

Returns

boolean

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

CborData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

CborData.toCborHex

toData

toData(): ConstrData

Returns

ConstrData

fromCbor

Static fromCbor(bytes): Datum

Parameters

NameType
bytesnumber[]

Returns

Datum

fromUplcData

Static fromUplcData(data): null | Datum

Parameters

NameType
dataUplcData

Returns

null | Datum

hashed

Static hashed(data): Datum

Constructs a HashedDatum. The input data is hashed internally.

Parameters

Returns

Datum

inline

Static inline(data): Datum

Parameters

Returns

Datum

Helios API/ API Reference/ Classes/

DatumHash

Represents a blake2b-256 hash of datum data.

Hierarchy

  • Hash

    DatumHash

Index

Constructors

constructor

new DatumHash(props)

Parameters

NameType
propsHashProps

Inherited from

Hash.constructor

Properties

bytes

Readonly bytes: number[]

Inherited from

Hash.bytes

Accessors

hex

get hex(): string

Hexadecimal representation.

Returns

string

Inherited from

Hash.hex

Methods

eq

eq(other): boolean

Parameters

NameType
otherHash

Returns

boolean

Inherited from

Hash.eq

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

Hash.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

Hash.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

Hash.toSchemaJson

compare

Static compare(a, b): number

Parameters

NameType
aHash
bHash

Returns

number

Inherited from

Hash.compare

fromCbor

Static fromCbor(bytes): Hash

Used internally for metadataHash and scriptDataHash

Parameters

NameType
bytesnumber[]

Returns

Hash

Inherited from

Hash.fromCbor

fromHex

Static fromHex(str): Hash

Might be needed for internal use

Parameters

NameType
strstring

Returns

Hash

Inherited from

Hash.fromHex

fromProps

Static fromProps(props): Hash

Parameters

NameType
propsHash | HashProps

Returns

Hash

Inherited from

Hash.fromProps

fromUplcCbor

Static fromUplcCbor(bytes): DatumHash

Parameters

NameType
bytesstring | number[]

Returns

DatumHash

fromUplcData

Static fromUplcData(data): DatumHash

Parameters

NameType
dataUplcData

Returns

DatumHash

Helios API/ API Reference/ Classes/

Ed25519PrivateKey

Implements

Hierarchy

Implements

Index

Constructors

constructor

new Ed25519PrivateKey(bytes)

Parameters

NameType
bytesstring | number[]

Overrides

HeliosData.constructor

Accessors

bytes

get bytes(): number[]

Returns

number[]

hex

get hex(): string

Returns

string

Methods

derivePubKey

derivePubKey(): PubKey

Returns

PubKey

Implementation of

PrivateKey.derivePubKey

extend

extend(): Ed25519PrivateKey

NOT the Ed25519-Bip32 hierarchial extension algorithm (see ExtendedPrivateKey below)

Returns

Ed25519PrivateKey

sign

sign(message): Signature

Parameters

NameType
messagenumber[]

Returns

Signature

Implementation of

PrivateKey.sign

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

HeliosData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

HeliosData.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

HeliosData.toSchemaJson

random

Static random(random): Ed25519PrivateKey

Generate a private key from a random number generator. This is not cryptographically secure, only use this for testing purpose

Parameters

NameType
randomNumberGenerator

Returns

Ed25519PrivateKey

  • Ed25519 private key is 32 bytes long

Helios API/ API Reference/ Classes/

FuzzyTest

Helper class for performing fuzzy property-based tests of Helios scripts.

Index

Constructors

constructor

new FuzzyTest(seed?, runsPerTest?, simplify?, printMessages?)

The simplify argument specifies whether optimized versions of the Helios sources should also be tested.

Parameters

NameTypeDescription
seed?number
runsPerTest?number
simplify?booleanIf true then also test the simplified program
printMessages?boolean-

Methods

ascii

ascii(minLength?, maxLength?): ValueGenerator

Returns a generator for strings with ascii characters from 32 (space) to 126 (tilde).

Parameters

NameType
minLength?number
maxLength?number

Returns

ValueGenerator

asciiBytes

asciiBytes(minLength?, maxLength?): ValueGenerator

Returns a generator for bytearrays containing only valid ascii characters

Parameters

NameType
minLength?number
maxLength?number

Returns

ValueGenerator

bool

bool(): ValueGenerator

Returns a generator for booleans, wrapped with ConstrData

Returns

ValueGenerator

bytes

bytes(minLength?, maxLength?): ValueGenerator

Returns a generator for bytearrays

Parameters

NameType
minLength?number
maxLength?number

Returns

ValueGenerator

constr

constr(tag, ...fieldGenerators): ValueGenerator

Returns a generator for tagged constr

Parameters

NameType
tagnumber | NumberGenerator
...fieldGeneratorsValueGenerator[]

Returns

ValueGenerator

int

int(min?, max?): ValueGenerator

Returns a generator for whole numbers between min and max, wrapped with IntData

Parameters

NameType
min?number
max?number

Returns

ValueGenerator

list

list(itemGenerator, minLength?, maxLength?): ValueGenerator

Returns a generator for lists

Parameters

NameType
itemGeneratorValueGenerator
minLength?number
maxLength?number

Returns

ValueGenerator

map

map(keyGenerator, valueGenerator, minLength?, maxLength?): ValueGenerator

Returns a generator for maps

Parameters

NameType
keyGeneratorValueGenerator
valueGeneratorValueGenerator
minLength?number
maxLength?number

Returns

ValueGenerator

newRand

newRand(): NumberGenerator

Returns

NumberGenerator

object

object(...itemGenerators): ValueGenerator

Returns a generator for objects

Parameters

NameType
...itemGeneratorsValueGenerator[]

Returns

ValueGenerator

option

option(someGenerator, noneProbability?): ValueGenerator

Returns a generator for options

Parameters

NameType
someGeneratorValueGenerator
noneProbability?number

Returns

ValueGenerator

rawBool

rawBool(): () => boolean

Returns a generator for booleans,

Returns

fn

▸ (): boolean

Returns a generator for booleans,

Returns

boolean

rawBytes

rawBytes(minLength?, maxLength?): () => number[]

Returns a generator for number[]

Parameters

NameType
minLength?number
maxLength?number

Returns

fn

▸ (): number[]

Returns a generator for number[]

Returns

number[]

rawInt

rawInt(min?, max?): () => bigint

Returns a gernator for whole numbers between min and max

Parameters

NameType
min?number
max?number

Returns

fn

▸ (): bigint

Returns a gernator for whole numbers between min and max

Returns

bigint

real

real(min?, max?): ValueGenerator

Parameters

NameType
min?number
max?number

Returns

ValueGenerator

reset

reset(): void

Returns

void

string

string(minLength?, maxLength?): ValueGenerator

Returns a generator for strings containing any utf-8 character.

Parameters

NameType
minLength?number
maxLength?number

Returns

ValueGenerator

test

test(argGens, src, propTest, nRuns?, simplify?): Promise<void>

Perform a fuzzy/property-based test-run of a Helios source. One value generator must be specified per argument of main.

Throws an error if the propTest fails.

The propTest can simply return a boolean, or can return an object with boolean values, and if any of these booleans is false the propTest fails (the keys can be used to provide extra information).

Parameters

NameType
argGensValueGenerator[]
srcstring
propTestPropertyTest
nRuns?number
simplify?boolean

Returns

Promise<void>

  • throws an error if any of the property tests fail

testParams

testParams(paramGenerators, paramArgs, src, propTest, nRuns?, simplify?): Promise<void>

Parameters

NameType
paramGeneratorsObject
paramArgsstring[]
srcstring
propTestPropertyTest
nRuns?number
simplify?boolean

Returns

Promise<void>

utf8Bytes

utf8Bytes(minLength?, maxLength?): ValueGenerator

Returns a generator for bytearrays the are also valid utf8 strings

Parameters

NameTypeDescription
minLength?numberlength of the string, not of the bytearray!
maxLength?numberlength of the string, not of the bytearray!

Returns

ValueGenerator

Helios API/ API Reference/ Classes/

HInt

Helios Int type

Deprecated

Hierarchy

Index

Constructors

constructor

new HInt(rawValue)

Parameters

NameType
rawValueHIntProps

Overrides

HeliosData.constructor

Accessors

value

get value(): bigint

Returns

bigint

Methods

add

add(other): HInt

Parameters

NameType
otherHInt | HIntProps

Returns

HInt

dump

dump(): string

Returns

string

eq

eq(other): boolean

Parameters

NameType
otherHInt | HIntProps

Returns

boolean

ge

ge(other): boolean

Parameters

NameType
otherHInt | HIntProps

Returns

boolean

gt

gt(other): boolean

Parameters

NameType
otherHInt | HIntProps

Returns

boolean

le

le(other): boolean

Parameters

NameType
otherHInt | HIntProps

Returns

boolean

lt

lt(other): boolean

Parameters

NameType
otherHInt | HIntProps

Returns

boolean

mul

mul(other): HInt

Parameters

NameType
otherHInt | HIntProps

Returns

HInt

neq

neq(other): boolean

Parameters

NameType
otherHInt | HIntProps

Returns

boolean

sub

sub(other): HInt

Parameters

NameType
otherHInt | HIntProps

Returns

HInt

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

HeliosData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

HeliosData.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

HeliosData.toSchemaJson

fromCbor

Static fromCbor(bytes): HInt

Parameters

NameType
bytesnumber[]

Returns

HInt

fromProps

Static fromProps(props): HInt

Parameters

NameType
propsHInt | HIntProps

Returns

HInt

fromUplcCbor

Static fromUplcCbor(bytes): HInt

Parameters

NameType
bytesstring | number[]

Returns

HInt

fromUplcData

Static fromUplcData(data): HInt

Parameters

NameType
dataUplcData

Returns

HInt

Helios API/ API Reference/ Classes/

Hash

Base class of all hash-types

Hierarchy

Index

Constructors

constructor

new Hash(props)

Parameters

NameType
propsHashProps

Overrides

HeliosData.constructor

Properties

bytes

Readonly bytes: number[]

Accessors

hex

get hex(): string

Hexadecimal representation.

Returns

string

Methods

eq

eq(other): boolean

Parameters

NameType
otherHash

Returns

boolean

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

HeliosData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

HeliosData.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

HeliosData.toSchemaJson

compare

Static compare(a, b): number

Parameters

NameType
aHash
bHash

Returns

number

fromCbor

Static fromCbor(bytes): Hash

Used internally for metadataHash and scriptDataHash

Parameters

NameType
bytesnumber[]

Returns

Hash

fromHex

Static fromHex(str): Hash

Might be needed for internal use

Parameters

NameType
strstring

Returns

Hash

fromProps

Static fromProps(props): Hash

Parameters

NameType
propsHash | HashProps

Returns

Hash

Helios API/ API Reference/ Classes/

HashedDatum

Inside helios this type is named OutputDatum::Hash in order to distinguish it from the user defined Datum, but outside helios scripts there isn't much sense to keep using the name 'OutputDatum' instead of Datum

Hierarchy

Index

Constructors

constructor

new HashedDatum(hash, origData?)

Parameters

NameType
hashDatumHash
origData?null | UplcData

Overrides

Datum.constructor

Accessors

data

get data(): null | UplcData

Returns

null | UplcData

Inherited from

Datum.data

hash

get hash(): DatumHash

Returns

DatumHash

Inherited from

Datum.hash

Methods

dump

dump(): any

Returns

any

Inherited from

Datum.dump

isHashed

isHashed(): boolean

Returns

boolean

Inherited from

Datum.isHashed

isInline

isInline(): boolean

Returns

boolean

Inherited from

Datum.isInline

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

Datum.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

Datum.toCborHex

toData

toData(): ConstrData

Returns

ConstrData

Inherited from

Datum.toData

fromCbor

Static fromCbor(bytes): Datum

Parameters

NameType
bytesnumber[]

Returns

Datum

Inherited from

Datum.fromCbor

fromData

Static fromData(data): HashedDatum

Constructs a HashedDatum. The input data is hashed internally.

Parameters

NameType
dataUplcData

Returns

HashedDatum

fromUplcData

Static fromUplcData(data): null | Datum

Parameters

NameType
dataUplcData

Returns

null | Datum

Inherited from

Datum.fromUplcData

hashed

Static hashed(data): Datum

Constructs a HashedDatum. The input data is hashed internally.

Parameters

Returns

Datum

Inherited from

Datum.hashed

inline

Static inline(data): Datum

Parameters

Returns

Datum

Inherited from

Datum.inline

Helios API/ API Reference/ Classes/

HeliosData

Base-type of all data-types that exist both on- and off-chain, and map directly to Helios instances.

Deprecated

Hierarchy

Index

Constructors

constructor

new HeliosData()

Inherited from

CborData.constructor

Methods

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

CborData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

CborData.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

Helios API/ API Reference/ Classes/

IROptimizerState

State that must be maintained over optimization iterations

Index

Constructors

constructor

new IROptimizerState()

Accessors

commonExprCount

get commonExprCount(): number

Returns

number

Methods

incrCommonExprCount

incrCommonExprCount(): void

Returns

void

Helios API/ API Reference/ Classes/

IntData

Represents an unbounded integer (bigint).

Hierarchy

Index

Constructors

constructor

new IntData(value)

Parameters

NameType
valuebigint

Overrides

UplcData.constructor

Accessors

memSize

get memSize(): number

Estimate of memory usage during validation

Returns

number

Inherited from

UplcData.memSize

value

get value(): bigint

Returns

bigint

Methods

isSame

isSame(other): boolean

Compares the schema jsons

Parameters

NameType
otherUplcData

Returns

boolean

Inherited from

UplcData.isSame

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

UplcData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

UplcData.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

UplcData.toSchemaJson

transfer

transfer(other): any

Parameters

NameType
otherTransferUplcAst

Returns

any

Inherited from

UplcData.transfer

fromCbor

Static fromCbor(bytes): IntData

Parameters

NameType
bytesnumber[]

Returns

IntData

Overrides

UplcData.fromCbor

Helios API/ API Reference/ Classes/

KoiosV0

Koios network interface.

Implements

Implements

Index

Constructors

constructor

new KoiosV0(networkName)

Parameters

NameType
networkName"preview" | "preprod" | "mainnet"

Methods

getParameters

getParameters(): Promise<NetworkParams>

Returns

Promise<NetworkParams>

Implementation of

Network.getParameters

getUtxo

getUtxo(id): Promise<TxInput>

Parameters

NameType
idTxOutputId

Returns

Promise<TxInput>

Implementation of

Network.getUtxo

getUtxos

getUtxos(address): Promise<TxInput[]>

Parameters

NameType
addressAddress

Returns

Promise<TxInput[]>

Implementation of

Network.getUtxos

hasUtxo

hasUtxo(utxo): Promise<boolean>

Used by KoiosV0.resolveUsingUtxo().

Parameters

NameType
utxoTxInput

Returns

Promise<boolean>

submitTx

submitTx(tx): Promise<TxId>

Parameters

NameType
txTx

Returns

Promise<TxId>

Implementation of

Network.submitTx

resolveUsingUtxo

Static resolveUsingUtxo(refUtxo): Promise<KoiosV0>

Parameters

NameType
refUtxoTxInput

Returns

Promise<KoiosV0>

Helios API/ API Reference/ Classes/

ListData

Represents a list of other UplcData instances.

Hierarchy

Index

Constructors

constructor

new ListData(items)

Parameters

NameType
itemsUplcData[]

Overrides

UplcData.constructor

Accessors

memSize

get memSize(): number

Estimate of memory usage during validation

Returns

number

Inherited from

UplcData.memSize

Methods

isSame

isSame(other): boolean

Compares the schema jsons

Parameters

NameType
otherUplcData

Returns

boolean

Inherited from

UplcData.isSame

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

UplcData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

UplcData.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

UplcData.toSchemaJson

transfer

transfer(other): any

Parameters

NameType
otherTransferUplcAst

Returns

any

Inherited from

UplcData.transfer

fromCbor

Static fromCbor(bytes): ListData

Parameters

NameType
bytesnumber[]

Returns

ListData

Overrides

UplcData.fromCbor

Helios API/ API Reference/ Classes/

MapData

Represents a list of pairs of other UplcData instances.

Hierarchy

Index

Constructors

constructor

new MapData(pairs)

Parameters

NameType
pairs[UplcData, UplcData][]

Overrides

UplcData.constructor

Accessors

memSize

get memSize(): number

Estimate of memory usage during validation

Returns

number

Inherited from

UplcData.memSize

Methods

isSame

isSame(other): boolean

Compares the schema jsons

Parameters

NameType
otherUplcData

Returns

boolean

Inherited from

UplcData.isSame

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

UplcData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

UplcData.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

UplcData.toSchemaJson

transfer

transfer(other): any

Parameters

NameType
otherTransferUplcAst

Returns

any

Inherited from

UplcData.transfer

fromCbor

Static fromCbor(bytes): MapData

Parameters

NameType
bytesnumber[]

Returns

MapData

Overrides

UplcData.fromCbor

Helios API/ API Reference/ Classes/

MintingPolicyHash

Represents a blake2b-224 hash of a minting policy script

Note: to calculate this hash the script is first encoded as a CBOR byte-array and then prepended by a script version byte.

Hierarchy

Index

Constructors

constructor

new MintingPolicyHash(props)

Parameters

NameType
propsHashProps

Inherited from

ScriptHash.constructor

Properties

bytes

Readonly bytes: number[]

Inherited from

ScriptHash.bytes

Accessors

hex

get hex(): string

Hexadecimal representation.

Returns

string

Inherited from

ScriptHash.hex

Methods

eq

eq(other): boolean

Parameters

NameType
otherHash

Returns

boolean

Inherited from

ScriptHash.eq

toBech32

toBech32(): string

Encodes as bech32 string using 'asset' as human readable part

Returns

string

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

ScriptHash.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

ScriptHash.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

ScriptHash.toSchemaJson

compare

Static compare(a, b): number

Parameters

NameType
aHash
bHash

Returns

number

Inherited from

ScriptHash.compare

fromCbor

Static fromCbor(bytes): MintingPolicyHash

Parameters

NameType
bytesnumber[]

Returns

MintingPolicyHash

Overrides

ScriptHash.fromCbor

fromHex

Static fromHex(str): MintingPolicyHash

Parameters

NameType
strstring

Returns

MintingPolicyHash

Overrides

ScriptHash.fromHex

fromProps

Static fromProps(props): MintingPolicyHash

Parameters

NameType
propsHashProps | MintingPolicyHash

Returns

MintingPolicyHash

Overrides

ScriptHash.fromProps

fromUplcCbor

Static fromUplcCbor(bytes): MintingPolicyHash

Parameters

NameType
bytesstring | number[]

Returns

MintingPolicyHash

fromUplcData

Static fromUplcData(data): MintingPolicyHash

Parameters

NameType
dataUplcData

Returns

MintingPolicyHash

Helios API/ API Reference/ Classes/

MintingRedeemer

Base-type of SpendingRedeemer and MintingRedeemer

Hierarchy

Index

Constructors

constructor

new MintingRedeemer(mph, mphIndex, data, exUnits?)

Parameters

NameType
mphnull | MintingPolicyHash
mphIndexnumber
dataUplcData
exUnits?Cost

Overrides

Redeemer.constructor

Accessors

cpuCost

get cpuCost(): bigint

Returns

bigint

Inherited from

Redeemer.cpuCost

data

get data(): UplcData

Returns

UplcData

Inherited from

Redeemer.data

memCost

get memCost(): bigint

Returns

bigint

Inherited from

Redeemer.memCost

mphIndex

get mphIndex(): number

Returns

number

profile

get profile(): Profile

Returns

Profile

Inherited from

Redeemer.profile

programName

get programName(): null | string

Returns

null | string

Inherited from

Redeemer.programName

Methods

dump

dump(): any

Returns

any

Inherited from

Redeemer.dump

dumpInternal

dumpInternal(): any

Returns

any

Inherited from

Redeemer.dumpInternal

estimateFee

estimateFee(networkParams): bigint

Parameters

NameType
networkParamsNetworkParams

Returns

bigint

Inherited from

Redeemer.estimateFee

setProfile

setProfile(profile): void

Parameters

NameType
profileProfile

Returns

void

Inherited from

Redeemer.setProfile

setProgramName

setProgramName(name): void

Parameters

NameType
namestring

Returns

void

Inherited from

Redeemer.setProgramName

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

Redeemer.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

Redeemer.toCborHex

toCborInternal

toCborInternal(type, index): number[]

type: 0 -> spending 1 -> minting 2 -> certifying 3 -> rewarding

Parameters

NameType
typenumber
indexnumber

Returns

number[]

Inherited from

Redeemer.toCborInternal

toScriptPurposeData

toScriptPurposeData(body): ConstrData

Parameters

NameType
bodyTxBody

Returns

ConstrData

Inherited from

Redeemer.toScriptPurposeData

updateIndex

updateIndex(body): void

Parameters

NameType
bodyTxBody

Returns

void

Inherited from

Redeemer.updateIndex

fromCbor

Static fromCbor(bytes): Redeemer

Parameters

NameType
bytesnumber[]

Returns

Redeemer

Inherited from

Redeemer.fromCbor

Helios API/ API Reference/ Classes/

NativeScript

Helios supports Cardano native scripts. See Tx.attachScript() for how NativeScript can be used when building a transaction.

NativeScript allows creating basic multi-signature and time-based validators. This is a legacy technology, but can be cheaper than using Plutus.

Hierarchy

Index

Constructors

constructor

new NativeScript(type)

Parameters

NameType
typenumber

Overrides

CborData.constructor

Accessors

mintingPolicyHash

get mintingPolicyHash(): MintingPolicyHash

A NativeScript can be used both as a Validator and as a MintingPolicy

Returns

MintingPolicyHash

validatorHash

get validatorHash(): ValidatorHash

A NativeScript can be used both as a Validator and as a MintingPolicy

Returns

ValidatorHash

Methods

hash

hash(): number[]

Calculates the blake2b-224 (28 bytes) hash of the NativeScript.

Note: a 0 byte is prepended before to the serialized CBOR representation, before calculating the hash.

Returns

number[]

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

CborData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

CborData.toCborHex

toJson

toJson(): any

Returns

any

typeToCbor

typeToCbor(): number[]

Returns

number[]

fromCbor

Static fromCbor(raw): NativeScript

Parameters

NameType
rawstring | number[]

Returns

NativeScript

fromJson

Static fromJson(json): NativeScript

Parameters

NameType
jsonany

Returns

NativeScript

Helios API/ API Reference/ Classes/

NetworkEmulator

A simple emulated Network. This can be used to do integration tests of whole dApps. Staking is not yet supported.

Implements

Implements

Index

Constructors

constructor

new NetworkEmulator(seed?)

Instantiates a NetworkEmulator at slot 0. An optional seed number can be specified, from which all emulated randomness is derived.

Parameters

NameType
seed?number

Accessors

currentSlot

get currentSlot(): bigint

Returns

bigint

Methods

createUtxo

createUtxo(wallet, lovelace, assets?): void

Creates a UTxO using a GenesisTx.

Parameters

NameType
walletSimpleWallet
lovelacebigint
assets?Assets

Returns

void

createWallet

createWallet(lovelace?, assets?): SimpleWallet

Creates a new SimpleWallet and populates it with a given lovelace quantity and assets. Special genesis transactions are added to the emulated chain in order to create these assets.

Parameters

NameType
lovelace?bigint
assets?Assets

Returns

SimpleWallet

dump

dump(): void

Returns

void

getParameters

getParameters(): Promise<NetworkParams>

Returns

Promise<NetworkParams>

Implementation of

Network.getParameters

getUtxo

getUtxo(id): Promise<TxInput>

Throws an error if the UTxO isn't found

Parameters

NameType
idTxOutputId

Returns

Promise<TxInput>

Implementation of

Network.getUtxo

getUtxos

getUtxos(address): Promise<TxInput[]>

Parameters

NameType
addressAddress

Returns

Promise<TxInput[]>

Implementation of

Network.getUtxos

initNetworkParams

initNetworkParams(networkParams): NetworkParams

Creates a new NetworkParams instance that has access to current slot (so that the Tx validity range can be set automatically during Tx.finalize()).

Parameters

NameType
networkParamsNetworkParams

Returns

NetworkParams

isConsumed

isConsumed(utxo): boolean

Parameters

NameType
utxoTxInput

Returns

boolean

submitTx

submitTx(tx): Promise<TxId>

Parameters

NameType
txTx

Returns

Promise<TxId>

Implementation of

Network.submitTx

tick

tick(nSlots): void

Mint a block with the current mempool, and advance the slot by a number of slots.

Parameters

NameType
nSlotsbigint

Returns

void

warnMempool

warnMempool(): void

Returns

void

Helios API/ API Reference/ Classes/

NetworkParams

Wrapper for the raw JSON containing all the current network parameters.

NetworkParams is needed to be able to calculate script budgets and perform transaction building checks.

The raw JSON can be downloaded from the following CDN locations:

These JSONs are updated every 15 minutes.

Index

Constructors

constructor

new NetworkParams(raw, liveSlotGetter?)

Parameters

NameType
rawany
liveSlotGetter?null | LiveSlotGetter

Accessors

liveSlot

get liveSlot(): null | bigint

Returns

null | bigint

maxTxFee

get maxTxFee(): bigint

Tx balancing picks additional inputs by starting from maxTxFee. This is done because the order of the inputs can have a huge impact on the tx fee, so the order must be known before balancing. If there aren't enough inputs to cover the maxTxFee and the min deposits of newly created UTxOs, the balancing will fail.

Returns

bigint

raw

get raw(): any

Returns

any

stakeAddressDeposit

get stakeAddressDeposit(): bigint

Returns

bigint

Methods

slotToTime

slotToTime(slot): bigint

Calculates the time (in milliseconds in 01/01/1970) associated with a given slot number.

Parameters

NameType
slotbigint

Returns

bigint

timeToSlot

timeToSlot(time): bigint

Calculates the slot number associated with a given time. Time is specified as milliseconds since 01/01/1970.

Parameters

NameTypeDescription
timebigintMilliseconds since 1970

Returns

bigint

Helios API/ API Reference/ Classes/

NetworkSlice

Implements

Implements

Index

Constructors

constructor

new NetworkSlice(params, utxos)

Parameters

NameType
paramsNetworkParams
utxosNetworkSliceUTxOs

Methods

getParameters

getParameters(): Promise<NetworkParams>

Returns

Promise<NetworkParams>

Implementation of

Network.getParameters

getUtxo

getUtxo(id): Promise<TxInput>

Parameters

NameType
idTxOutputId

Returns

Promise<TxInput>

Implementation of

Network.getUtxo

getUtxos

getUtxos(addr): Promise<TxInput[]>

Parameters

NameType
addrAddress

Returns

Promise<TxInput[]>

Implementation of

Network.getUtxos

submitTx

submitTx(tx): Promise<TxId>

Parameters

NameType
txTx

Returns

Promise<TxId>

Implementation of

Network.submitTx

toJson

toJson(): any

Returns

any

fromJson

Static fromJson(obj): NetworkSlice

Parameters

NameType
objany

Returns

NetworkSlice

init

Static init(network, addresses): Promise<NetworkSlice>

Parameters

NameType
networkNetwork
addressesAddress[]

Returns

Promise<NetworkSlice>

Helios API/ API Reference/ Classes/

Program

Helios root object

Index

Constructors

constructor

new Program()

Accessors

config

get config(): ProgramConfig

Returns

ProgramConfig

name

get name(): string

Returns

string

parameters

get parameters(): Object

Alternative way to get the parameters as HeliosData instances

Returns

Object

set parameters(arg): void

Use proxy for setting

Parameters

NameType
argObject

Returns

void

purpose

get purpose(): ScriptPurpose

Returns

ScriptPurpose

types

get types(): UserTypes

Returns

UserTypes

Methods

compile

compile(simplify?): UplcProgram

Parameters

NameType
simplify?boolean

Returns

UplcProgram

dumpIR

dumpIR(optimized?, annotate?): string

Returns the Intermediate Representation AST of the program.

Parameters

NameTypeDescription
optimized?booleanif true, returns the IR of the optimized program
annotate?booleanadd internal type information annotations to the returned AST

Returns

string

evalParam

evalParam(name): UplcValue

Doesn't use wrapEntryPoint

Parameters

NameTypeDescription
namestringcan be namespace: "Type::ConstName" or "Module::ConstName" or "Module::Type::ConstName"

Returns

UplcValue

toString

toString(): string

Returns

string

new

Static new(mainSrc, moduleSrcs?, validatorTypes?, config?): Program

Creates a new program.

Parameters

NameTypeDescription
mainSrcstring
moduleSrcs?string[]optional sources of modules, which can be used for imports
validatorTypes?Object-
config?ProgramConfig

Returns

Program

Helios API/ API Reference/ Classes/

PubKey

Hierarchy

Index

Constructors

constructor

new PubKey(props)

Parameters

NameType
propsPubKeyProps

Overrides

HeliosData.constructor

Accessors

bytes

get bytes(): number[]

Returns

number[]

hex

get hex(): string

Hexadecimal representation.

Returns

string

pubKeyHash

get pubKeyHash(): PubKeyHash

Can also be used as a Stake key hash

Returns

PubKeyHash

Methods

dump

dump(): string

Returns

string

hash

hash(): number[]

Returns

number[]

isDummy

isDummy(): boolean

Returns

boolean

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

HeliosData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

HeliosData.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

HeliosData.toSchemaJson

dummy

Static dummy(): PubKey

Returns

PubKey

fromCbor

Static fromCbor(bytes): PubKey

Parameters

NameType
bytesnumber[]

Returns

PubKey

fromProps

Static fromProps(props): PubKey

Parameters

NameType
propsPubKey | PubKeyProps

Returns

PubKey

fromUplcCbor

Static fromUplcCbor(bytes): PubKey

Parameters

NameType
bytesstring | number[]

Returns

PubKey

fromUplcData

Static fromUplcData(data): PubKey

Parameters

NameType
dataUplcData

Returns

PubKey

Helios API/ API Reference/ Classes/

PubKeyHash

Represents a blake2b-224 hash of a PubKey

Note: A PubKeyHash can also be used as the second part of a payment Address, or to construct a StakeAddress.

Hierarchy

  • Hash

    PubKeyHash

Index

Constructors

constructor

new PubKeyHash(props)

Parameters

NameType
propsHashProps

Inherited from

Hash.constructor

Properties

bytes

Readonly bytes: number[]

Inherited from

Hash.bytes

Accessors

hex

get hex(): string

Hexadecimal representation.

Returns

string

Inherited from

Hash.hex

Methods

eq

eq(other): boolean

Parameters

NameType
otherHash

Returns

boolean

Inherited from

Hash.eq

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

Hash.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

Hash.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

Hash.toSchemaJson

compare

Static compare(a, b): number

Parameters

NameType
aHash
bHash

Returns

number

Inherited from

Hash.compare

dummy

Static dummy(): PubKeyHash

Returns

PubKeyHash

fromCbor

Static fromCbor(bytes): Hash

Used internally for metadataHash and scriptDataHash

Parameters

NameType
bytesnumber[]

Returns

Hash

Inherited from

Hash.fromCbor

fromHex

Static fromHex(str): Hash

Might be needed for internal use

Parameters

NameType
strstring

Returns

Hash

Inherited from

Hash.fromHex

fromProps

Static fromProps(props): Hash

Parameters

NameType
propsHash | HashProps

Returns

Hash

Inherited from

Hash.fromProps

fromUplcCbor

Static fromUplcCbor(bytes): PubKeyHash

Parameters

NameType
bytesstring | number[]

Returns

PubKeyHash

fromUplcData

Static fromUplcData(data): PubKeyHash

Parameters

NameType
dataUplcData

Returns

PubKeyHash

Helios API/ API Reference/ Classes/

Redeemer

Base-type of SpendingRedeemer and MintingRedeemer

Hierarchy

Index

Constructors

constructor

new Redeemer(data, profile?)

Parameters

NameType
dataUplcData
profile?Profile

Overrides

CborData.constructor

Accessors

cpuCost

get cpuCost(): bigint

Returns

bigint

data

get data(): UplcData

Returns

UplcData

memCost

get memCost(): bigint

Returns

bigint

profile

get profile(): Profile

Returns

Profile

programName

get programName(): null | string

Returns

null | string

Methods

dump

dump(): any

Returns

any

dumpInternal

dumpInternal(): any

Returns

any

estimateFee

estimateFee(networkParams): bigint

Parameters

NameType
networkParamsNetworkParams

Returns

bigint

setProfile

setProfile(profile): void

Parameters

NameType
profileProfile

Returns

void

setProgramName

setProgramName(name): void

Parameters

NameType
namestring

Returns

void

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

CborData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

CborData.toCborHex

toCborInternal

toCborInternal(type, index): number[]

type: 0 -> spending 1 -> minting 2 -> certifying 3 -> rewarding

Parameters

NameType
typenumber
indexnumber

Returns

number[]

toScriptPurposeData

toScriptPurposeData(body): ConstrData

Parameters

NameType
bodyTxBody

Returns

ConstrData

updateIndex

updateIndex(body): void

Parameters

NameType
bodyTxBody

Returns

void

fromCbor

Static fromCbor(bytes): Redeemer

Parameters

NameType
bytesnumber[]

Returns

Redeemer

Helios API/ API Reference/ Classes/

RemoteWallet

Implements

Implements

Index

Constructors

constructor

new RemoteWallet(isMainnet, usedAddresses, unusedAddresses, utxos)

Parameters

NameType
isMainnetboolean
usedAddressesAddress[]
unusedAddressesAddress[]
utxosTxInput[]

Accessors

collateral

get collateral(): Promise<TxInput[]>

Returns

Promise<TxInput[]>

Implementation of

Wallet.collateral

rewardAddresses

get rewardAddresses(): Promise<StakeAddress[]>

Returns

Promise<StakeAddress[]>

Implementation of

Wallet.rewardAddresses

unusedAddresses

get unusedAddresses(): Promise<Address[]>

Returns

Promise<Address[]>

Implementation of

Wallet.unusedAddresses

usedAddresses

get usedAddresses(): Promise<Address[]>

Returns

Promise<Address[]>

Implementation of

Wallet.usedAddresses

utxos

get utxos(): Promise<TxInput[]>

Returns

Promise<TxInput[]>

Implementation of

Wallet.utxos

Methods

isMainnet

isMainnet(): Promise<boolean>

Returns

Promise<boolean>

Implementation of

Wallet.isMainnet

signData

signData(addr, message): Promise<{ key: string ; signature: string }>

Parameters

NameType
addrAddress
messagestring

Returns

Promise<{ key: string ; signature: string }>

Implementation of

Wallet.signData

signTx

signTx(tx): Promise<Signature[]>

Parameters

NameType
txTx

Returns

Promise<Signature[]>

Implementation of

Wallet.signTx

submitTx

submitTx(tx): Promise<TxId>

Parameters

NameType
txTx

Returns

Promise<TxId>

Implementation of

Wallet.submitTx

fromJson

Static fromJson(obj): RemoteWallet

Parameters

NameType
objany

Returns

RemoteWallet

Helios API/ API Reference/ Classes/

RootPrivateKey

Implements

Implements

Index

Constructors

constructor

new RootPrivateKey(entropy)

Parameters

NameType
entropynumber[]

Accessors

bytes

get bytes(): number[]

Returns

number[]

entropy

get entropy(): number[]

Returns

number[]

Methods

derive

derive(i): Bip32PrivateKey

Parameters

NameTypeDescription
inumberchildIndex

Returns

Bip32PrivateKey

derivePath

derivePath(path): Bip32PrivateKey

Parameters

NameType
pathnumber[]

Returns

Bip32PrivateKey

derivePubKey

derivePubKey(): PubKey

Returns

PubKey

Implementation of

PrivateKey.derivePubKey

deriveSpendingKey

deriveSpendingKey(accountIndex?, i?): Bip32PrivateKey

Parameters

NameType
accountIndex?number
i?number

Returns

Bip32PrivateKey

deriveSpendingRootKey

deriveSpendingRootKey(accountIndex?): Bip32PrivateKey

Parameters

NameType
accountIndex?number

Returns

Bip32PrivateKey

deriveStakingKey

deriveStakingKey(accountIndex?, i?): Bip32PrivateKey

Parameters

NameType
accountIndex?number
i?number

Returns

Bip32PrivateKey

deriveStakingRootKey

deriveStakingRootKey(accountIndex): Bip32PrivateKey

Parameters

NameType
accountIndexnumber

Returns

Bip32PrivateKey

sign

sign(message): Signature

Parameters

NameType
messagenumber[]

Returns

Signature

Implementation of

PrivateKey.sign

toPhrase

toPhrase(dict?): string[]

Parameters

NameType
dict?string[]

Returns

string[]

fromPhrase

Static fromPhrase(phrase, dict?): RootPrivateKey

Parameters

NameType
phrasestring[]
dict?string[]

Returns

RootPrivateKey

isValidPhrase

Static isValidPhrase(phrase, dict?): boolean

Parameters

NameType
phrasestring[]
dict?string[]

Returns

boolean

Helios API/ API Reference/ Classes/

RuntimeError

Used for errors thrown during Uplc evaluation

Hierarchy

  • Error

    RuntimeError

Index

Constructors

constructor

new RuntimeError(message?)

Parameters

NameType
message?string

Inherited from

Error.constructor

Properties

message

message: string

Inherited from

Error.message

name

name: string

Inherited from

Error.name

stack

Optional stack: string

Inherited from

Error.stack

Accessors

context

get context(): any

Returns

any

Helios API/ API Reference/ Classes/

ScriptHash

Base class of MintingPolicyHash, ValidatorHash and StakingValidatorHash

Hierarchy

Index

Constructors

constructor

new ScriptHash(props)

Parameters

NameType
propsHashProps

Inherited from

Hash.constructor

Properties

bytes

Readonly bytes: number[]

Inherited from

Hash.bytes

Accessors

hex

get hex(): string

Hexadecimal representation.

Returns

string

Inherited from

Hash.hex

Methods

eq

eq(other): boolean

Parameters

NameType
otherHash

Returns

boolean

Inherited from

Hash.eq

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

Hash.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

Hash.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

Hash.toSchemaJson

compare

Static compare(a, b): number

Parameters

NameType
aHash
bHash

Returns

number

Inherited from

Hash.compare

fromCbor

Static fromCbor(bytes): Hash

Used internally for metadataHash and scriptDataHash

Parameters

NameType
bytesnumber[]

Returns

Hash

Inherited from

Hash.fromCbor

fromHex

Static fromHex(str): Hash

Might be needed for internal use

Parameters

NameType
strstring

Returns

Hash

Inherited from

Hash.fromHex

fromProps

Static fromProps(props): Hash

Parameters

NameType
propsHash | HashProps

Returns

Hash

Inherited from

Hash.fromProps

Helios API/ API Reference/ Classes/

Signature

Represents a Ed25519 signature.

Also contains a reference to the PubKey that did the signing.

Hierarchy

Index

Constructors

constructor

new Signature(pubKey, signature)

Parameters

NameType
pubKeynumber[] | PubKey
signaturenumber[]

Overrides

CborData.constructor

Accessors

bytes

get bytes(): number[]

Returns

number[]

pubKey

get pubKey(): PubKey

Returns

PubKey

pubKeyHash

get pubKeyHash(): PubKeyHash

Returns

PubKeyHash

Methods

dump

dump(): any

Returns

any

isDummy

isDummy(): boolean

Returns

boolean

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

CborData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

CborData.toCborHex

verify

verify(msg): void

Throws error if incorrect

Parameters

NameType
msgnumber[]

Returns

void

dummy

Static dummy(): Signature

Returns

Signature

fromCbor

Static fromCbor(bytes): Signature

Parameters

NameType
bytesnumber[]

Returns

Signature

Helios API/ API Reference/ Classes/

SimpleWallet

This wallet only has a single private/public key, which isn't rotated. Staking is not yet supported.

Implements

Implements

Index

Constructors

constructor

new SimpleWallet(network, privateKey)

Parameters

NameType
networkNetwork
privateKeyBip32PrivateKey

Accessors

address

get address(): Address

Returns

Address

collateral

get collateral(): Promise<TxInput[]>

Returns

Promise<TxInput[]>

Implementation of

Wallet.collateral

privateKey

get privateKey(): Bip32PrivateKey

Returns

Bip32PrivateKey

pubKey

get pubKey(): PubKey

Returns

PubKey

pubKeyHash

get pubKeyHash(): PubKeyHash

Returns

PubKeyHash

rewardAddresses

get rewardAddresses(): Promise<StakeAddress[]>

Not yet implemented.

Returns

Promise<StakeAddress[]>

Implementation of

Wallet.rewardAddresses

unusedAddresses

get unusedAddresses(): Promise<Address[]>

Returns

Promise<Address[]>

Implementation of

Wallet.unusedAddresses

usedAddresses

get usedAddresses(): Promise<Address[]>

Assumed wallet was initiated with at least 1 UTxO at the pubkeyhash address.

Returns

Promise<Address[]>

Implementation of

Wallet.usedAddresses

utxos

get utxos(): Promise<TxInput[]>

Returns

Promise<TxInput[]>

Implementation of

Wallet.utxos

Methods

isMainnet

isMainnet(): Promise<boolean>

Returns

Promise<boolean>

Implementation of

Wallet.isMainnet

signData

signData(addr, message): Promise<{ key: string ; signature: string }>

Not yet implemented.

Parameters

NameType
addrAddress
messagestring

Returns

Promise<{ key: string ; signature: string }>

Implementation of

Wallet.signData

signTx

signTx(tx): Promise<Signature[]>

Simply assumed the tx needs to by signed by this wallet without checking.

Parameters

NameType
txTx

Returns

Promise<Signature[]>

Implementation of

Wallet.signTx

submitTx

submitTx(tx): Promise<TxId>

Parameters

NameType
txTx

Returns

Promise<TxId>

Implementation of

Wallet.submitTx

Helios API/ API Reference/ Classes/

Site

Each Token/Expression/Statement has a Site, which encapsulates a position in a Source

Index

Constructors

constructor

new Site(src, startPos, endPos?, codeMapSite?)

Parameters

NameType
srcSource
startPosnumber
endPos?number
codeMapSite?null | Site

Accessors

codeMapSite

get codeMapSite(): null | Site

Returns

null | Site

endPos

get endPos(): number

Returns

number

endSite

get endSite(): null | Site

Returns

null | Site

src

get src(): Source

Returns

Source

startPos

get startPos(): number

Returns

number

Methods

getFilePos

getFilePos(): [number, number, number, number]

Calculates the column,line position in 'this.#src'

Returns

[number, number, number, number]

  • [startLine, startCol, endLine, endCol]

merge

merge(other): Site

Parameters

NameType
otherSite

Returns

Site

referenceError

referenceError(info?): UserError

Returns a ReferenceError

Parameters

NameType
info?string

Returns

UserError

setCodeMapSite

setCodeMapSite(site): void

Parameters

NameType
siteSite

Returns

void

setEndSite

setEndSite(site): void

Parameters

NameType
sitenull | Site

Returns

void

syntaxError

syntaxError(info?): UserError

Returns a SyntaxError

Parameters

NameType
info?string

Returns

UserError

toString

toString(): string

Returns

string

transfer

transfer(other): any

Parameters

NameType
otherTransferUplcAst

Returns

any

typeError

typeError(info?): UserError

Returns a TypeError

Parameters

NameType
info?string

Returns

UserError

dummy

Static dummy(): Site

Returns

Site

Helios API/ API Reference/ Classes/

Source

A Source instance wraps a string so we can use it cheaply as a reference inside a Site. Also used by VSCode plugin

Index

Constructors

constructor

new Source(raw, name)

Parameters

NameType
rawstring
namestring

Accessors

errors

get errors(): Error[]

Returns

Error[]

Methods

throwErrors

throwErrors(): void

Returns

void

transfer

transfer(other): any

Parameters

NameType
otherTransferUplcAst

Returns

any

Helios API/ API Reference/ Classes/

SpendingRedeemer

Base-type of SpendingRedeemer and MintingRedeemer

Hierarchy

Index

Constructors

constructor

new SpendingRedeemer(input, inputIndex, data, exUnits?)

Parameters

NameType
inputnull | TxInput
inputIndexnumber
dataUplcData
exUnits?Cost

Overrides

Redeemer.constructor

Accessors

cpuCost

get cpuCost(): bigint

Returns

bigint

Inherited from

Redeemer.cpuCost

data

get data(): UplcData

Returns

UplcData

Inherited from

Redeemer.data

inputIndex

get inputIndex(): number

Returns

number

memCost

get memCost(): bigint

Returns

bigint

Inherited from

Redeemer.memCost

profile

get profile(): Profile

Returns

Profile

Inherited from

Redeemer.profile

programName

get programName(): null | string

Returns

null | string

Inherited from

Redeemer.programName

Methods

dump

dump(): any

Returns

any

Inherited from

Redeemer.dump

dumpInternal

dumpInternal(): any

Returns

any

Inherited from

Redeemer.dumpInternal

estimateFee

estimateFee(networkParams): bigint

Parameters

NameType
networkParamsNetworkParams

Returns

bigint

Inherited from

Redeemer.estimateFee

setProfile

setProfile(profile): void

Parameters

NameType
profileProfile

Returns

void

Inherited from

Redeemer.setProfile

setProgramName

setProgramName(name): void

Parameters

NameType
namestring

Returns

void

Inherited from

Redeemer.setProgramName

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

Redeemer.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

Redeemer.toCborHex

toCborInternal

toCborInternal(type, index): number[]

type: 0 -> spending 1 -> minting 2 -> certifying 3 -> rewarding

Parameters

NameType
typenumber
indexnumber

Returns

number[]

Inherited from

Redeemer.toCborInternal

toScriptPurposeData

toScriptPurposeData(body): ConstrData

Parameters

NameType
bodyTxBody

Returns

ConstrData

Inherited from

Redeemer.toScriptPurposeData

updateIndex

updateIndex(body): void

Parameters

NameType
bodyTxBody

Returns

void

Inherited from

Redeemer.updateIndex

fromCbor

Static fromCbor(bytes): Redeemer

Parameters

NameType
bytesnumber[]

Returns

Redeemer

Inherited from

Redeemer.fromCbor

Helios API/ API Reference/ Classes/

StakeAddress

Wrapper for Cardano stake address bytes. An StakeAddress consists of two parts internally:

  • Header (1 byte, see CIP 8)
  • Staking witness hash (28 bytes that represent the PubKeyHash or StakingValidatorHash)

Stake addresses are used to query the assets held by given staking credentials.

Index

Constructors

constructor

new StakeAddress(bytes)

Parameters

NameType
bytesnumber[]

Accessors

bytes

get bytes(): number[]

Returns

number[]

hex

get hex(): string

Converts a StakeAddress into its hexadecimal representation.

Returns

string

stakingHash

get stakingHash(): PubKeyHash | StakingValidatorHash

Returns the underlying PubKeyHash or StakingValidatorHash.

Returns

PubKeyHash | StakingValidatorHash

Methods

toBech32

toBech32(): string

Converts a StakeAddress into its Bech32 representation.

Returns

string

toCbor

toCbor(): number[]

Converts a StakeAddress into its CBOR representation.

Returns

number[]

toHex

toHex(): string

Converts a StakeAddress into its hexadecimal representation.

Returns

string

fromAddress

Static fromAddress(addr): StakeAddress

Convert a regular Address into a StakeAddress. Throws an error if the Address doesn't have a staking credential.

Parameters

NameType
addrAddress

Returns

StakeAddress

fromBech32

Static fromBech32(str): StakeAddress

Parameters

NameType
strstring

Returns

StakeAddress

fromCbor

Static fromCbor(bytes): StakeAddress

Parameters

NameType
bytesnumber[]

Returns

StakeAddress

fromHash

Static fromHash(isTestnet, hash): StakeAddress

Converts a PubKeyHash or StakingValidatorHash into StakeAddress.

Parameters

NameType
isTestnetboolean
hashPubKeyHash | StakingValidatorHash

Returns

StakeAddress

fromHex

Static fromHex(hex): StakeAddress

Doesn't check validity

Parameters

NameType
hexstring

Returns

StakeAddress

isForTestnet

Static isForTestnet(sa): boolean

Returns true if the given StakeAddress is a testnet address.

Parameters

NameType
saStakeAddress

Returns

boolean

Helios API/ API Reference/ Classes/

StakingValidatorHash

Represents a blake2b-224 hash of a staking script.

Note: before hashing, the staking script is first encoded as a CBOR byte-array and then prepended by a script version byte.

Hierarchy

Index

Constructors

constructor

new StakingValidatorHash(props)

Parameters

NameType
propsHashProps

Inherited from

ScriptHash.constructor

Properties

bytes

Readonly bytes: number[]

Inherited from

ScriptHash.bytes

Accessors

hex

get hex(): string

Hexadecimal representation.

Returns

string

Inherited from

ScriptHash.hex

Methods

eq

eq(other): boolean

Parameters

NameType
otherHash

Returns

boolean

Inherited from

ScriptHash.eq

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

ScriptHash.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

ScriptHash.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

ScriptHash.toSchemaJson

compare

Static compare(a, b): number

Parameters

NameType
aHash
bHash

Returns

number

Inherited from

ScriptHash.compare

fromCbor

Static fromCbor(bytes): Hash

Used internally for metadataHash and scriptDataHash

Parameters

NameType
bytesnumber[]

Returns

Hash

Inherited from

ScriptHash.fromCbor

fromHex

Static fromHex(str): Hash

Might be needed for internal use

Parameters

NameType
strstring

Returns

Hash

Inherited from

ScriptHash.fromHex

fromProps

Static fromProps(props): Hash

Parameters

NameType
propsHash | HashProps

Returns

Hash

Inherited from

ScriptHash.fromProps

fromUplcCbor

Static fromUplcCbor(bytes): StakingValidatorHash

Parameters

NameType
bytesstring | number[]

Returns

StakingValidatorHash

fromUplcData

Static fromUplcData(data): StakingValidatorHash

Parameters

NameType
dataUplcData

Returns

StakingValidatorHash

Helios API/ API Reference/ Classes/

Tx

Represents a Cardano transaction. Can also be used as a transaction builder.

Hierarchy

Index

Constructors

constructor

new Tx(body?, witnesses?, valid?, metadata?, validTo?, validFrom?)

Use Tx.new() instead of this constructor for creating a new Tx builder.

Parameters

NameType
body?TxBody
witnesses?TxWitnesses
valid?boolean
metadata?null | TxMetadata
validTo?null | bigint | Date
validFrom?null | bigint | Date

Overrides

CborData.constructor

Accessors

body

get body(): TxBody

Returns

TxBody

bodyHash

get bodyHash(): number[]

Returns

number[]

profileReport

get profileReport(): string

Returns

string

witnesses

get witnesses(): TxWitnesses

Returns

TxWitnesses

Methods

addCollateral

addCollateral(input): Tx

Add a UTxO instance as collateral to the transaction being built. Usually adding only one collateral input is enough. The number of collateral inputs must be greater than 0 if script witnesses are used in the transaction, and must be less than the limit defined in the NetworkParams.

Mutates the transaction. Only available during transaction building. Returns the transaction instance so build methods can be chained.

Parameters

NameType
inputTxInput

Returns

Tx

addDCert

addDCert(dcert): Tx

Add a DCert to the transactions being built. DCert contains information about a staking-related action.

TODO: implement all DCert (de)serialization methods.

Returns the transaction instance so build methods can be chained.

Parameters

NameType
dcertDCert

Returns

Tx

addInput

addInput(input, rawRedeemer?): Tx

Add a UTxO instance as an input to the transaction being built. Throws an error if the UTxO is locked at a script address but a redeemer isn't specified (unless the script is a known NativeScript).

Mutates the transaction. Only available during transaction building. Returns the transaction instance so build methods can be chained.

Parameters

NameType
inputTxInput
rawRedeemer?null | UplcData | HeliosData | UplcDataValue

Returns

Tx

addInputs

addInputs(inputs, redeemer?): Tx

Add multiple UTxO instances as inputs to the transaction being built. Throws an error if the UTxOs are locked at a script address but a redeemer isn't specified (unless the script is a known NativeScript).

Mutates the transaction. Only available during transaction building. Returns the transaction instance so build methods can be chained.

Parameters

NameType
inputsTxInput[]
redeemer?null | UplcData | HeliosData | UplcDataValue

Returns

Tx

addMetadata

addMetadata(tag, data): Tx

Add metadata to a transaction. Metadata can be used to store data on-chain, but can't be consumed by validator scripts. Metadata can for example be used for CIP 25.

Parameters

NameType
tagnumber
dataMetadata

Returns

Tx

addOutput

addOutput(output): Tx

Add a TxOutput instance to the transaction being built.

Mutates the transaction. Only available during transaction building. Returns the transaction instance so build methods can be chained.

Parameters

NameType
outputTxOutput

Returns

Tx

addOutputs

addOutputs(outputs): Tx

Add multiple TxOutput instances at once.

Mutates the transaction. Only available during transaction building. Returns the transaction instance so build methods can be chained.

Parameters

NameType
outputsTxOutput[]

Returns

Tx

addRefInput

addRefInput(input, refScript?): Tx

Add a TxInput instance as a reference input to the transaction being built. Any associated reference script, as a UplcProgram instance, must also be included in the transaction at this point (so the that the execution budget can be calculated correctly).

Mutates the transaction. Only available during transaction building. Returns the transaction instance so build methods can be chained.

Parameters

NameType
inputTxInput
refScript?null | UplcProgram

Returns

Tx

addRefInputs

addRefInputs(inputs): Tx

Add multiple TxInput instances as reference inputs to the transaction being built.

Mutates the transaction. Only available during transaction building. Returns the transaction instance so build methods can be chained.

Parameters

NameType
inputsTxInput[]

Returns

Tx

addSignature

addSignature(signature, verify?): Tx

Adds a signature created by a wallet. Only available after the transaction has been finalized. Optionally verifies that the signature is correct.

Parameters

NameTypeDescription
signatureSignature
verify?booleanDefaults to true

Returns

Tx

addSignatures

addSignatures(signatures, verify?): Tx

Adds multiple signatures at once. Only available after the transaction has been finalized. Optionally verifies each signature is correct.

Parameters

NameType
signaturesSignature[]
verify?boolean

Returns

Tx

addSigner

addSigner(hash): Tx

Add a signatory PubKeyHash to the transaction being built. The added entry becomes available in the tx.signatories field in the Helios script.

Mutates the transaction. Only available during transaction building. Returns the transaction instance so build methods can be chained.

Parameters

NameType
hashPubKeyHash

Returns

Tx

attachScript

attachScript(program): Tx

Attaches a script witness to the transaction being built. The script witness can be either a UplcProgram or a legacy NativeScript. A UplcProgram instance can be created by compiling a Helios Program. A legacy NativeScript instance can be created by deserializing its original CBOR representation.

Throws an error if script has already been added. Throws an error if the script isn't used upon finalization.

Mutates the transaction. Only available during transaction building. Returns the transaction instance so build methods can be chained.

Note: a NativeScript must be attached before associated inputs are added or tokens are minted.

Parameters

NameType
programUplcProgram | NativeScript

Returns

Tx

completeInputData

completeInputData(fn): Promise<void>

A serialized tx throws away input information This must be refetched from the network if the tx needs to be analyzed

Parameters

NameType
fn(id: TxOutputId) => Promise<TxOutput>

Returns

Promise<void>

dump

dump(params?): any

Parameters

NameTypeDescription
params?null | NetworkParamsIf specified: dump all the runtime details of each redeemer (datum, redeemer, scriptContext)

Returns

any

finalize

finalize(networkParams, changeAddress, spareUtxos?): Promise<Tx>

Executes all the attached scripts with appropriate redeemers and calculates execution budgets. Balances the transaction, and optionally uses some spare UTxOs if the current inputs don't contain enough lovelace to cover the fees and min output deposits.

Inputs, minted assets, and withdrawals are sorted.

Sets the validatity range automatically if a call to tx.time_range is detected in any of the attached Helios scripts.

Parameters

NameTypeDescription
networkParamsNetworkParams
changeAddressAddress
spareUtxos?TxInput[]might be used during balancing if there currently aren't enough inputs

Returns

Promise<Tx>

id

id(): TxId

Returns

TxId

isValid

isValid(slot): boolean

Used by emulator to check if tx is valid.

Parameters

NameType
slotbigint

Returns

boolean

mintTokens

mintTokens(mph, tokens, redeemer): Tx

Mint a list of tokens associated with a given MintingPolicyHash. Throws an error if the given MintingPolicyHash was already used in a previous call to mintTokens(). The token names can either by a list of bytes or a hexadecimal string.

Mutates the transaction. Only available during transaction building the transaction. Returns the transaction instance so build methods can be chained.

Also throws an error if the redeemer is null, and the minting policy isn't a known NativeScript.

Parameters

NameTypeDescription
mphHashProps | MintingPolicyHash
tokens[ByteArray | ByteArrayProps, HInt | HIntProps][]list of pairs of [tokenName, quantity], tokenName can be list of bytes or hex-string
redeemernull | UplcData | UplcDataValue

Returns

Tx

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

CborData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

CborData.toCborHex

toTxData

toTxData(networkParams): UplcData

Parameters

NameType
networkParamsNetworkParams

Returns

UplcData

validFrom

validFrom(slotOrTime): Tx

Set the start of the valid time range by specifying either a Date or a slot.

Mutates the transaction. Only available during building the transaction. Returns the transaction instance so build methods can be chained.

Note: since Helios v0.13.29 this is set automatically if any of the Helios validator scripts call tx.time_range.

Parameters

NameType
slotOrTimebigint | Date

Returns

Tx

validTo

validTo(slotOrTime): Tx

Set the end of the valid time range by specifying either a Date or a slot.

Mutates the transaction. Only available during transaction building. Returns the transaction instance so build methods can be chained.

Note: since Helios v0.13.29 this is set automatically if any of the Helios validator scripts call tx.time_range.

Parameters

NameType
slotOrTimebigint | Date

Returns

Tx

withoutMetadata

withoutMetadata(): Tx

Creates a new Tx without the metadata for client-side signing where the client can't know the metadata before tx-submission.

Returns

Tx

finalizeUplcData

Static finalizeUplcData(data, networkParams, changeAddress, spareUtxos, scripts): Promise<Tx>

Used by bundler for macro finalization

Parameters

NameTypeDescription
dataUplcData
networkParamsNetworkParams
changeAddressAddress
spareUtxosTxInput[]
scriptsObjectUplcPrograms can be lazy

Returns

Promise<Tx>

fromCbor

Static fromCbor(raw): Tx

Deserialize a CBOR encoded Cardano transaction (input is either an array of bytes, or a hex string).

Parameters

NameType
rawstring | number[]

Returns

Tx

new

Static new(): Tx

Create a new Tx builder.

Returns

Tx

Helios API/ API Reference/ Classes/

TxBody

inputs, minted assets, and withdrawals need to be sorted in order to form a valid transaction

Hierarchy

Index

Constructors

constructor

new TxBody()

Inherited from

CborData.constructor

Accessors

collateral

get collateral(): TxInput[]

Returns

TxInput[]

dcerts

get dcerts(): DCert[]

Returns

DCert[]

fee

get fee(): bigint

Returns

bigint

firstValidSlot

get firstValidSlot(): null | bigint

Returns

null | bigint

inputs

get inputs(): TxInput[]

Returns

TxInput[]

lastValidSlot

get lastValidSlot(): null | bigint

Returns

null | bigint

minted

get minted(): Assets

Returns

Assets

outputs

get outputs(): TxOutput[]

Returns

TxOutput[]

refInputs

get refInputs(): TxInput[]

Returns

TxInput[]

signers

get signers(): PubKeyHash[]

Returns

PubKeyHash[]

Methods

dump

dump(): any

Returns

any

sumInputAndMintedAssets

sumInputAndMintedAssets(): Assets

Returns

Assets

sumInputAndMintedValue

sumInputAndMintedValue(): Value

Throws error if any part of the sum is negative (i.e. more is burned than input)

Returns

Value

sumInputValue

sumInputValue(): Value

Returns

Value

sumOutputAssets

sumOutputAssets(): Assets

Returns

Assets

sumOutputValue

sumOutputValue(): Value

Returns

Value

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

CborData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

CborData.toCborHex

fromCbor

Static fromCbor(bytes): TxBody

Parameters

NameType
bytesnumber[]

Returns

TxBody

Helios API/ API Reference/ Classes/

TxChain

Helper that

Implements

Implements

Index

Constructors

constructor

new TxChain(network)

Parameters

NameType
networkNetwork

Methods

asWallet

asWallet(baseWallet): Wallet

Parameters

NameType
baseWalletWallet

Returns

Wallet

getParameters

getParameters(): Promise<NetworkParams>

Returns

Promise<NetworkParams>

Implementation of

Network.getParameters

getUtxo

getUtxo(id): Promise<TxInput>

Parameters

NameType
idTxOutputId

Returns

Promise<TxInput>

Implementation of

Network.getUtxo

getUtxos

getUtxos(addr): Promise<TxInput[]>

Parameters

NameType
addrAddress

Returns

Promise<TxInput[]>

Implementation of

Network.getUtxos

getUtxosInternal

getUtxosInternal(utxos, addrs): Promise<TxInput[]>

Parameters

NameType
utxosTxInput[]
addrsAddress[]

Returns

Promise<TxInput[]>

submitTx

submitTx(tx): Promise<TxId>

Parameters

NameType
txTx

Returns

Promise<TxId>

Implementation of

Network.submitTx

Helios API/ API Reference/ Classes/

TxId

Represents the hash of a transaction.

This is also used to identify an UTxO (along with the index of the UTxO in the list of UTxOs created by the transaction).

Hierarchy

Index

Constructors

constructor

new TxId(props)

Parameters

NameType
propsHashProps

Inherited from

Hash.constructor

Properties

bytes

Readonly bytes: number[]

Inherited from

Hash.bytes

Accessors

hex

get hex(): string

Hexadecimal representation.

Returns

string

Inherited from

Hash.hex

Methods

eq

eq(other): boolean

Parameters

NameType
otherHash

Returns

boolean

Inherited from

Hash.eq

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

Hash.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

Hash.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

Hash.toSchemaJson

compare

Static compare(a, b): number

Parameters

NameType
aHash
bHash

Returns

number

Inherited from

Hash.compare

dummy

Static dummy(fill?): TxId

Filled with 255 so that the internal show() function has max execution budget cost

Parameters

NameType
fill?number

Returns

TxId

fromCbor

Static fromCbor(bytes): Hash

Used internally for metadataHash and scriptDataHash

Parameters

NameType
bytesnumber[]

Returns

Hash

Inherited from

Hash.fromCbor

fromHex

Static fromHex(str): Hash

Might be needed for internal use

Parameters

NameType
strstring

Returns

Hash

Inherited from

Hash.fromHex

fromProps

Static fromProps(props): Hash

Parameters

NameType
propsHash | HashProps

Returns

Hash

Inherited from

Hash.fromProps

fromUplcCbor

Static fromUplcCbor(bytes): TxId

Parameters

NameType
bytesstring | number[]

Returns

TxId

fromUplcData

Static fromUplcData(data): TxId

Parameters

NameType
dataUplcData

Returns

TxId

Helios API/ API Reference/ Classes/

TxInput

TxInput base-type

Hierarchy

Index

Constructors

constructor

new TxInput(outputId, output?)

Parameters

NameTypeDescription
outputIdTxOutputId
output?null | TxOutputused during building, not part of serialization

Overrides

CborData.constructor

Properties

outputId

Readonly outputId: TxOutputId

Accessors

address

get address(): Address

Shortcut

Returns

Address

origOutput

get origOutput(): TxOutput

Backward compatible alias for TxInput.output

Returns

TxOutput

output

get output(): TxOutput

Returns

TxOutput

txId

get txId(): TxId

Returns

TxId

Deprecated

utxoIdx

get utxoIdx(): number

Returns

number

Deprecated

value

get value(): Value

Shortcut

Returns

Value

Methods

dump

dump(): any

Returns

any

eq

eq(other): boolean

Parameters

NameType
otherTxInput

Returns

boolean

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

CborData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

CborData.toCborHex

toFullCbor

toFullCbor(): number[]

Returns

number[]

fromCbor

Static fromCbor(rawBytes): TxInput

Parameters

NameType
rawBytesstring | number[]

Returns

TxInput

fromFullCbor

Static fromFullCbor(rawBytes): TxInput

Deserializes TxOutput format used by wallet connector

Parameters

NameType
rawBytesstring | number[]

Returns

TxInput

sumValue

Static sumValue(inputs): Value

Parameters

NameType
inputsTxInput[]

Returns

Value

Helios API/ API Reference/ Classes/

TxMetadata

Index

Constructors

constructor

new TxMetadata()

Accessors

keys

get keys(): number[]

Returns

number[]

Methods

add

add(tag, data): void

Parameters

NameType
tagnumber
dataMetadata

Returns

void

dump

dump(): any

Returns

any

toCbor

toCbor(): number[]

Returns

number[]

fromCbor

Static fromCbor(data): TxMetadata

Decodes a TxMetadata instance from Cbor

Parameters

NameType
datanumber[]

Returns

TxMetadata

Helios API/ API Reference/ Classes/

TxOutput

Represents a transaction output that is used when building a transaction.

Hierarchy

Index

Constructors

constructor

new TxOutput(address, value, datum?, refScript?)

Constructs a TxOutput instance using an Address, a Value, an optional Datum, and optional UplcProgram reference script.

Parameters

NameType
addressAddress
valueValue
datum?null | Datum
refScript?null | UplcProgram

Overrides

CborData.constructor

Accessors

address

get address(): Address

Get the Address to which the TxOutput will be sent.

Returns

Address

datum

get datum(): null | Datum

Get the optional Datum associated with the TxOutput.

Returns

null | Datum

refScript

get refScript(): null | UplcProgram

Returns

null | UplcProgram

value

get value(): Value

Get the Value contained in the TxOutput.

Returns

Value

Methods

calcMinLovelace

calcMinLovelace(networkParams): bigint

Each UTxO must contain some minimum quantity of lovelace to avoid that the blockchain is used for data storage.

Parameters

NameType
networkParamsNetworkParams

Returns

bigint

correctLovelace

correctLovelace(networkParams, updater?): void

Makes sure the TxOutput contains the minimum quantity of lovelace. The network requires this to avoid the creation of unusable dust UTxOs.

Optionally an update function can be specified that allows mutating the datum of the TxOutput to account for an increase of the lovelace quantity contained in the value.

Parameters

NameType
networkParamsNetworkParams
updater?null | (output: TxOutput) => void

Returns

void

dump

dump(): any

Returns

any

getDatumData

getDatumData(): UplcData

Returns

UplcData

setAddress

setAddress(addr): void

Mutation is handy when correctin the quantity of lovelace in a utxo

Parameters

NameType
addrAddress

Returns

void

setDatum

setDatum(datum): void

Mutation is handy when correctin the quantity of lovelace in a utxo

Parameters

NameType
datumDatum

Returns

void

setValue

setValue(val): void

Mutation is handy when correcting the quantity of lovelace in a utxo

Parameters

NameType
valValue

Returns

void

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

CborData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

CborData.toCborHex

toData

toData(): ConstrData

Returns

ConstrData

fromCbor

Static fromCbor(bytes): TxOutput

Parameters

NameType
bytesnumber[]

Returns

TxOutput

fromUplcData

Static fromUplcData(data): TxOutput

Parameters

NameType
dataUplcData

Returns

TxOutput

Helios API/ API Reference/ Classes/

TxOutputId

Id of a Utxo

Hierarchy

Index

Constructors

constructor

new TxOutputId(...args)

Parameters

NameType
...args[TxOutputIdProps] | [TxId, number | bigint]

Overrides

HeliosData.constructor

Accessors

txId

get txId(): TxId

Returns

TxId

utxoIdx

get utxoIdx(): number

Returns

number

Methods

_toUplcData

_toUplcData(): ConstrData

Returns

ConstrData

eq

eq(other): boolean

Parameters

NameType
otherTxOutputId

Returns

boolean

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

HeliosData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

HeliosData.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

Inherited from

HeliosData.toSchemaJson

cleanConstructorArgs

Static cleanConstructorArgs(props): [HashProps | TxId, HInt | HIntProps]

Parameters

NameType
propsTxOutputIdProps

Returns

[HashProps | TxId, HInt | HIntProps]

comp

Static comp(a, b): number

Parameters

Returns

number

dummy

Static dummy(): TxOutputId

Returns

TxOutputId

fromCbor

Static fromCbor(rawBytes): TxOutputId

Parameters

NameType
rawBytesstring | number[]

Returns

TxOutputId

fromProps

Static fromProps(props): TxOutputId

Parameters

NameType
propsTxOutputId | TxOutputIdProps

Returns

TxOutputId

fromUplcCbor

Static fromUplcCbor(bytes): TxOutputId

Parameters

NameType
bytesstring | number[]

Returns

TxOutputId

fromUplcData

Static fromUplcData(data): TxOutputId

Parameters

NameType
dataUplcData

Returns

TxOutputId

Helios API/ API Reference/ Classes/

TxRefInput

Use TxInput instead

Deprecated

Hierarchy

Index

Constructors

constructor

new TxRefInput(outputId, output?)

Parameters

NameTypeDescription
outputIdTxOutputId
output?null | TxOutputused during building, not part of serialization

Inherited from

TxInput.constructor

Properties

outputId

Readonly outputId: TxOutputId

Inherited from

TxInput.outputId

Accessors

address

get address(): Address

Shortcut

Returns

Address

Inherited from

TxInput.address

origOutput

get origOutput(): TxOutput

Backward compatible alias for TxInput.output

Returns

TxOutput

Inherited from

TxInput.origOutput

output

get output(): TxOutput

Returns

TxOutput

Inherited from

TxInput.output

txId

get txId(): TxId

Returns

TxId

Deprecated

Inherited from

TxInput.txId

utxoIdx

get utxoIdx(): number

Returns

number

Deprecated

Inherited from

TxInput.utxoIdx

value

get value(): Value

Shortcut

Returns

Value

Inherited from

TxInput.value

Methods

dump

dump(): any

Returns

any

Inherited from

TxInput.dump

eq

eq(other): boolean

Parameters

NameType
otherTxInput

Returns

boolean

Inherited from

TxInput.eq

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

TxInput.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

TxInput.toCborHex

toFullCbor

toFullCbor(): number[]

Returns

number[]

Inherited from

TxInput.toFullCbor

fromCbor

Static fromCbor(rawBytes): TxInput

Parameters

NameType
rawBytesstring | number[]

Returns

TxInput

Inherited from

TxInput.fromCbor

fromFullCbor

Static fromFullCbor(rawBytes): TxInput

Deserializes TxOutput format used by wallet connector

Parameters

NameType
rawBytesstring | number[]

Returns

TxInput

Inherited from

TxInput.fromFullCbor

sumValue

Static sumValue(inputs): Value

Parameters

NameType
inputsTxInput[]

Returns

Value

Inherited from

TxInput.sumValue

Helios API/ API Reference/ Classes/

TxWitnesses

Represents the pubkey signatures, and datums/redeemers/scripts that are witnessing a transaction.

Hierarchy

Index

Constructors

constructor

new TxWitnesses()

Inherited from

CborData.constructor

Accessors

datums

get datums(): ListData

Returns

ListData

profileReport

get profileReport(): string

Compiles a report of each redeemer execution. Only works after the tx has been finalized.

Returns

string

redeemers

get redeemers(): Redeemer[]

Returns

Redeemer[]

scripts

get scripts(): (UplcProgram | NativeScript)[]

Returns all the scripts, including the reference scripts

Returns

(UplcProgram | NativeScript)[]

signatures

get signatures(): Signature[]

Gets the list of Signature instances contained in this witness set.

Returns

Signature[]

Methods

dump

dump(params?, body?): any

Parameters

NameType
params?null | NetworkParams
body?null | TxBody

Returns

any

isNativeScript

isNativeScript(h): boolean

Parameters

Returns

boolean

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

CborData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

CborData.toCborHex

fromCbor

Static fromCbor(bytes): TxWitnesses

Parameters

NameType
bytesnumber[]

Returns

TxWitnesses

Helios API/ API Reference/ Classes/

UTxO

Use TxInput instead

Deprecated

Hierarchy

Index

Constructors

constructor

new UTxO(outputId, output?)

Parameters

NameTypeDescription
outputIdTxOutputId
output?null | TxOutputused during building, not part of serialization

Inherited from

TxInput.constructor

Properties

outputId

Readonly outputId: TxOutputId

Inherited from

TxInput.outputId

Accessors

address

get address(): Address

Shortcut

Returns

Address

Inherited from

TxInput.address

origOutput

get origOutput(): TxOutput

Backward compatible alias for TxInput.output

Returns

TxOutput

Inherited from

TxInput.origOutput

output

get output(): TxOutput

Returns

TxOutput

Inherited from

TxInput.output

txId

get txId(): TxId

Returns

TxId

Deprecated

Inherited from

TxInput.txId

utxoIdx

get utxoIdx(): number

Returns

number

Deprecated

Inherited from

TxInput.utxoIdx

value

get value(): Value

Shortcut

Returns

Value

Inherited from

TxInput.value

Methods

dump

dump(): any

Returns

any

Inherited from

TxInput.dump

eq

eq(other): boolean

Parameters

NameType
otherTxInput

Returns

boolean

Inherited from

TxInput.eq

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

TxInput.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

TxInput.toCborHex

toFullCbor

toFullCbor(): number[]

Returns

number[]

Inherited from

TxInput.toFullCbor

fromCbor

Static fromCbor(rawBytes): TxInput

Parameters

NameType
rawBytesstring | number[]

Returns

TxInput

Inherited from

TxInput.fromCbor

fromFullCbor

Static fromFullCbor(rawBytes): TxInput

Deserializes TxOutput format used by wallet connector

Parameters

NameType
rawBytesstring | number[]

Returns

TxInput

Inherited from

TxInput.fromFullCbor

sumValue

Static sumValue(inputs): Value

Parameters

NameType
inputsTxInput[]

Returns

Value

Inherited from

TxInput.sumValue

Helios API/ API Reference/ Classes/

UplcBool

JS/TS equivalent of the Helios language Bool type.

Implements

Hierarchy

Implements

Index

Constructors

constructor

new UplcBool(site, value)

Parameters

NameType
siteSite
valueboolean

Overrides

UplcValueImpl.constructor

Accessors

bool

get bool(): boolean

Returns

boolean

Implementation of

UplcValue.bool

Inherited from

UplcValueImpl.bool

bytes

get bytes(): number[]

Returns

number[]

Implementation of

UplcValue.bytes

Inherited from

UplcValueImpl.bytes

data

get data(): UplcData

Returns

UplcData

Implementation of

UplcValue.data

Inherited from

UplcValueImpl.data

first

get first(): UplcValue

Returns

UplcValue

Implementation of

UplcValue.first

Inherited from

UplcValueImpl.first

flatSize

get flatSize(): number

4 for type, 1 for value

Returns

number

Implementation of

UplcValue.flatSize

int

get int(): bigint

Returns

bigint

Implementation of

UplcValue.int

Inherited from

UplcValueImpl.int

itemType

get itemType(): UplcType

Returns

UplcType

Implementation of

UplcValue.itemType

Inherited from

UplcValueImpl.itemType

length

get length(): number

Returns

number

Implementation of

UplcValue.length

Inherited from

UplcValueImpl.length

list

get list(): UplcValue[]

Returns

UplcValue[]

Implementation of

UplcValue.list

Inherited from

UplcValueImpl.list

memSize

get memSize(): number

Returns

number

Implementation of

UplcValue.memSize

second

get second(): UplcValue

Returns

UplcValue

Implementation of

UplcValue.second

Inherited from

UplcValueImpl.second

site

get site(): Site

Returns

Site

Implementation of

UplcValue.site

Inherited from

UplcValueImpl.site

string

get string(): string

Returns

string

Implementation of

UplcValue.string

Inherited from

UplcValueImpl.string

Methods

assertUnit

assertUnit(): UplcUnit

Returns

UplcUnit

Implementation of

UplcValue.assertUnit

Inherited from

UplcValueImpl.assertUnit

copy

copy(newSite): UplcBool

Parameters

NameType
newSiteSite

Returns

UplcBool

Implementation of

UplcValue.copy

isAny

isAny(): boolean

Returns

boolean

Implementation of

UplcValue.isAny

Inherited from

UplcValueImpl.isAny

isData

isData(): boolean

Returns

boolean

Implementation of

UplcValue.isData

Inherited from

UplcValueImpl.isData

isList

isList(): boolean

Distinguishes a list from a map

Returns

boolean

Implementation of

UplcValue.isList

Inherited from

UplcValueImpl.isList

isPair

isPair(): boolean

Distinguishes a pair from a mapItem

Returns

boolean

Implementation of

UplcValue.isPair

Inherited from

UplcValueImpl.isPair

toFlatValue

toFlatValue(bitWriter): void

Encodes value with plutus flat encoding. Member function not named 'toFlat' as not to confuse with 'toFlat' member of terms.

Parameters

NameType
bitWriterBitWriter

Returns

void

Implementation of

UplcValue.toFlatValue

Inherited from

UplcValueImpl.toFlatValue

toFlatValueInternal

toFlatValueInternal(bitWriter): void

Encodes value without type header

Parameters

NameType
bitWriterBitWriter

Returns

void

Implementation of

UplcValue.toFlatValueInternal

Inherited from

UplcValueImpl.toFlatValueInternal

transfer

transfer(other): any

Parameters

NameType
otherTransferUplcAst

Returns

any

Implementation of

UplcValue.transfer

typeBits

typeBits(): string

Returns

string

Implementation of

UplcValue.typeBits

Inherited from

UplcValueImpl.typeBits

new

Static new(value): UplcBool

Constructs a UplcBool without requiring a Site

Parameters

NameType
valueboolean

Returns

UplcBool

newTerm

Static newTerm(site, value): UplcConst

Creates a new UplcBool wrapped with UplcConst so it can be used as a term.

Parameters

NameType
siteSite
valueboolean

Returns

UplcConst

Helios API/ API Reference/ Classes/

UplcBuiltin

Plutus-core builtin function ref term

Hierarchy

Index

Constructors

constructor

new UplcBuiltin(site, name)

Parameters

NameType
siteSite
namestring | number

Overrides

UplcTerm.constructor

Accessors

nArgs

get nArgs(): number

Returns

number

name

get name(): string

Returns

string

site

get site(): Site

Returns

Site

Inherited from

UplcTerm.site

type

get type(): number

Returns

number

Inherited from

UplcTerm.type

Methods

toString

toString(): string

Generic term toString method

Returns

string

Inherited from

UplcTerm.toString

transfer

transfer(other): any

Parameters

NameType
otherTransferUplcAst

Returns

any

Inherited from

UplcTerm.transfer

Helios API/ API Reference/ Classes/

UplcByteArray

Primitive equivalent of ByteArrayData.

Implements

Hierarchy

Implements

Index

Constructors

constructor

new UplcByteArray(site, bytes)

Parameters

NameType
siteSite
bytesnumber[]

Overrides

UplcValueImpl.constructor

Accessors

bool

get bool(): boolean

Returns

boolean

Implementation of

UplcValue.bool

Inherited from

UplcValueImpl.bool

bytes

get bytes(): number[]

Returns

number[]

Implementation of

UplcValue.bytes

Inherited from

UplcValueImpl.bytes

data

get data(): UplcData

Returns

UplcData

Implementation of

UplcValue.data

Inherited from

UplcValueImpl.data

first

get first(): UplcValue

Returns

UplcValue

Implementation of

UplcValue.first

Inherited from

UplcValueImpl.first

flatSize

get flatSize(): number

4 for header, 8 bits per byte, 8 bits per chunk of 256 bytes, 8 bits final padding

Returns

number

Implementation of

UplcValue.flatSize

int

get int(): bigint

Returns

bigint

Implementation of

UplcValue.int

Inherited from

UplcValueImpl.int

itemType

get itemType(): UplcType

Returns

UplcType

Implementation of

UplcValue.itemType

Inherited from

UplcValueImpl.itemType

length

get length(): number

Returns

number

Implementation of

UplcValue.length

Inherited from

UplcValueImpl.length

list

get list(): UplcValue[]

Returns

UplcValue[]

Implementation of

UplcValue.list

Inherited from

UplcValueImpl.list

memSize

get memSize(): number

Returns

number

Implementation of

UplcValue.memSize

second

get second(): UplcValue

Returns

UplcValue

Implementation of

UplcValue.second

Inherited from

UplcValueImpl.second

site

get site(): Site

Returns

Site

Implementation of

UplcValue.site

Inherited from

UplcValueImpl.site

string

get string(): string

Returns

string

Implementation of

UplcValue.string

Inherited from

UplcValueImpl.string

Methods

assertUnit

assertUnit(): UplcUnit

Returns

UplcUnit

Implementation of

UplcValue.assertUnit

Inherited from

UplcValueImpl.assertUnit

copy

copy(newSite): UplcByteArray

Parameters

NameType
newSiteSite

Returns

UplcByteArray

Implementation of

UplcValue.copy

isAny

isAny(): boolean

Returns

boolean

Implementation of

UplcValue.isAny

Inherited from

UplcValueImpl.isAny

isData

isData(): boolean

Returns

boolean

Implementation of

UplcValue.isData

Inherited from

UplcValueImpl.isData

isList

isList(): boolean

Distinguishes a list from a map

Returns

boolean

Implementation of

UplcValue.isList

Inherited from

UplcValueImpl.isList

isPair

isPair(): boolean

Distinguishes a pair from a mapItem

Returns

boolean

Implementation of

UplcValue.isPair

Inherited from

UplcValueImpl.isPair

toFlatValue

toFlatValue(bitWriter): void

Encodes value with plutus flat encoding. Member function not named 'toFlat' as not to confuse with 'toFlat' member of terms.

Parameters

NameType
bitWriterBitWriter

Returns

void

Implementation of

UplcValue.toFlatValue

Inherited from

UplcValueImpl.toFlatValue

toFlatValueInternal

toFlatValueInternal(bitWriter): void

Encodes value without type header

Parameters

NameType
bitWriterBitWriter

Returns

void

Implementation of

UplcValue.toFlatValueInternal

Inherited from

UplcValueImpl.toFlatValueInternal

transfer

transfer(other): any

Parameters

NameType
otherTransferUplcAst

Returns

any

Implementation of

UplcValue.transfer

typeBits

typeBits(): string

Returns

string

Implementation of

UplcValue.typeBits

Inherited from

UplcValueImpl.typeBits

Helios API/ API Reference/ Classes/

UplcCall

Plutus-core function application term (i.e. function call)

Hierarchy

Index

Constructors

constructor

new UplcCall(site, fn, arg)

Parameters

NameType
siteSite
fnUplcTerm
argUplcTerm

Overrides

UplcTerm.constructor

Properties

arg

Readonly arg: UplcTerm

fn

Readonly fn: UplcTerm

Accessors

site

get site(): Site

Returns

Site

Inherited from

UplcTerm.site

type

get type(): number

Returns

number

Inherited from

UplcTerm.type

Methods

toString

toString(): string

Generic term toString method

Returns

string

Inherited from

UplcTerm.toString

transfer

transfer(other): any

Parameters

NameType
other