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
otherTransferUplcAst

Returns

any

Inherited from

UplcTerm.transfer

Helios API/ API Reference/ Classes/

UplcConst

Plutus-core const term (i.e. a literal in conventional sense)

Hierarchy

Index

Constructors

constructor

new UplcConst(value)

Parameters

NameType
valueUplcValue

Overrides

UplcTerm.constructor

Properties

value

Readonly value: UplcValue

Accessors

flatSize

get flatSize(): number

Returns

number

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/

UplcData

Base class for Plutus-core data classes (not the same as Plutus-core value classes!)

Hierarchy

Index

Constructors

constructor

new UplcData()

Inherited from

CborData.constructor

Accessors

memSize

get memSize(): number

Estimate of memory usage during validation

Returns

number

Methods

isSame

isSame(other): boolean

Compares the schema jsons

Parameters

NameType
otherUplcData

Returns

boolean

toCbor

toCbor(): number[]

Returns

number[]

Inherited from

CborData.toCbor

toCborHex

toCborHex(): string

Returns

string

Inherited from

CborData.toCborHex

toSchemaJson

toSchemaJson(): string

Returns

string

transfer

transfer(other): any

Parameters

NameType
otherTransferUplcAst

Returns

any

fromCbor

Static fromCbor(bytes): UplcData

Parameters

NameType
bytesstring | number[]

Returns

UplcData

Helios API/ API Reference/ Classes/

UplcDataValue

UplcValue that wraps a UplcData instance.

Implements

Hierarchy

Implements

Index

Constructors

constructor

new UplcDataValue(site, data)

Parameters

NameType
siteSite
dataUplcData

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

Same number of header bits as UplcByteArray

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): UplcDataValue

Parameters

NameType
newSiteSite

Returns

UplcDataValue

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

unwrap

Static unwrap(data): UplcData

Parameters

NameType
dataUplcData | UplcDataValue

Returns

UplcData

Helios API/ API Reference/ Classes/

UplcDelay

Plutus-core delay term.

Hierarchy

Index

Constructors

constructor

new UplcDelay(site, expr)

Parameters

NameType
siteSite
exprUplcTerm

Overrides

UplcTerm.constructor

Properties

expr

Readonly expr: 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
otherTransferUplcAst

Returns

any

Inherited from

UplcTerm.transfer

Helios API/ API Reference/ Classes/

UplcError

Plutus-core error term

Hierarchy

Index

Constructors

constructor

new UplcError(site, msg?)

Parameters

NameType
siteSite
msg?string

Overrides

UplcTerm.constructor

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
otherTransferUplcAst

Returns

any

Inherited from

UplcTerm.transfer

Helios API/ API Reference/ Classes/

UplcForce

Plutus-core force term

Hierarchy

Index

Constructors

constructor

new UplcForce(site, expr)

Parameters

NameType
siteSite
exprUplcTerm

Overrides

UplcTerm.constructor

Properties

expr

Readonly expr: 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
otherTransferUplcAst

Returns

any

Inherited from

UplcTerm.transfer

Helios API/ API Reference/ Classes/

UplcInt

Primitive equivalent of IntData.

Implements

Hierarchy

Implements

Index

Constructors

constructor

new UplcInt(site, value, signed?)

Parameters

NameTypeDescription
siteSite
valuebigintsupposed to be arbitrary precision
signed?booleanunsigned is only for internal use

Overrides

UplcValueImpl.constructor

Properties

signed

Readonly signed: boolean

value

Readonly value: bigint

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, 7 for simple int, (7 + 1)*ceil(n/7) for large int

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): UplcInt

Parameters

NameType
newSiteSite

Returns

UplcInt

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

toSigned

toSigned(): UplcInt

Unapplies zigzag encoding

Returns

UplcInt

Example

(new UplcInt(Site.dummy(), 1n, false)).toSigned().int == -1n

toUnsigned

toUnsigned(): UplcInt

Applies zigzag encoding

Returns

UplcInt

Example

(new UplcInt(Site.dummy(), -1n, true)).toUnsigned().int == 1n

Example

(new UplcInt(Site.dummy(), -1n, true)).toUnsigned().toSigned().int == -1n

Example

(new UplcInt(Site.dummy(), -2n, true)).toUnsigned().toSigned().int == -2n

Example

(new UplcInt(Site.dummy(), -3n, true)).toUnsigned().toSigned().int == -3n

Example

(new UplcInt(Site.dummy(), -4n, true)).toUnsigned().toSigned().int == -4n

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

bytesToBigInt

Static bytesToBigInt(bytes): bigint

Combines a list of Plutus-core bytes into a bigint (leading bit of each byte is ignored). Differs from bytesToBigInt in utils.js because only 7 bits are used from each byte.

Parameters

NameType
bytesnumber[]

Returns

bigint

new

Static new(value): UplcInt

Constructs a UplcInt without requiring a Site

Parameters

NameType
valuenumber | bigint

Returns

UplcInt

newSignedTerm

Static newSignedTerm(site, value): UplcConst

Creates a UplcInt wrapped in a UplcConst, so it can be used a term

Parameters

NameType
siteSite
valuebigint

Returns

UplcConst

parseRawByte

Static parseRawByte(b): number

Parses a single byte in the Plutus-core byte-list representation of an int

Parameters

NameType
bnumber

Returns

number

rawByteIsLast

Static rawByteIsLast(b): boolean

Returns true if 'b' is the last byte in the Plutus-core byte-list representation of an int.

Parameters

NameType
bnumber

Returns

boolean

Helios API/ API Reference/ Classes/

UplcLambda

Plutus-core lambda term

Hierarchy

Index

Constructors

constructor

new UplcLambda(site, expr, argName?)

Parameters

NameType
siteSite
exprUplcTerm
argName?null | string

Overrides

UplcTerm.constructor

Properties

expr

Readonly expr: 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
otherTransferUplcAst

Returns

any

Inherited from

UplcTerm.transfer

Helios API/ API Reference/ Classes/

UplcList

Plutus-core list value class. Only used during evaluation.

Implements

Hierarchy

Implements

Implemented by

Index

Constructors

constructor

new UplcList(site, itemType, items)

Parameters

NameType
siteSite
itemTypeUplcType
itemsUplcValue[]

Overrides

UplcValueImpl.constructor

Accessors

bool

get bool(): boolean

Returns

boolean

Implementation of

UplcList.bool

Inherited from

UplcValueImpl.bool

bytes

get bytes(): number[]

Returns

number[]

Implementation of

UplcList.bytes

Inherited from

UplcValueImpl.bytes

data

get data(): UplcData

Returns

UplcData

Implementation of

UplcList.data

Inherited from

UplcValueImpl.data

first

get first(): UplcValue

Returns

UplcValue

Implementation of

UplcList.first

Inherited from

UplcValueImpl.first

flatSize

get flatSize(): number

10 + nItemType type bits, value bits of each item (must be corrected by itemType)

Returns

number

Implementation of

UplcList.flatSize

int

get int(): bigint

Returns

bigint

Implementation of

UplcList.int

Inherited from

UplcValueImpl.int

itemType

get itemType(): UplcType

Returns

UplcType

Implementation of

UplcList.itemType

Inherited from

UplcValueImpl.itemType

length

get length(): number

Returns

number

Implementation of

UplcList.length

Inherited from

UplcValueImpl.length

list

get list(): UplcValue[]

Returns

UplcValue[]

Implementation of

UplcList.list

Inherited from

UplcValueImpl.list

memSize

get memSize(): number

Returns

number

Implementation of

UplcList.memSize

second

get second(): UplcValue

Returns

UplcValue

Implementation of

UplcList.second

Inherited from

UplcValueImpl.second

site

get site(): Site

Returns

Site

Implementation of

UplcList.site

Inherited from

UplcValueImpl.site

string

get string(): string

Returns

string

Implementation of

UplcList.string

Inherited from

UplcValueImpl.string

Methods

assertUnit

assertUnit(): UplcUnit

Returns

UplcUnit

Implementation of

UplcList.assertUnit

Inherited from

UplcValueImpl.assertUnit

copy

copy(newSite): UplcList

Parameters

NameType
newSiteSite

Returns

UplcList

Implementation of

UplcList.copy

isAny

isAny(): boolean

Returns

boolean

Implementation of

UplcList.isAny

Inherited from

UplcValueImpl.isAny

isData

isData(): boolean

Returns

boolean

Implementation of

UplcList.isData

Inherited from

UplcValueImpl.isData

isDataList

isDataList(): boolean

Returns

boolean

Implementation of

UplcList.isDataList

isDataMap

isDataMap(): boolean

Returns

boolean

Implementation of

UplcList.isDataMap

isList

isList(): boolean

Distinguishes a list from a map

Returns

boolean

Implementation of

UplcList.isList

Inherited from

UplcValueImpl.isList

isPair

isPair(): boolean

Distinguishes a pair from a mapItem

Returns

boolean

Implementation of

UplcList.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

UplcList.toFlatValue

Inherited from

UplcValueImpl.toFlatValue

toFlatValueInternal

toFlatValueInternal(bitWriter): void

Encodes value without type header

Parameters

NameType
bitWriterBitWriter

Returns

void

Implementation of

UplcList.toFlatValueInternal

Inherited from

UplcValueImpl.toFlatValueInternal

transfer

transfer(other): any

Parameters

NameType
otherTransferUplcAst

Returns

any

Implementation of

UplcList.transfer

typeBits

typeBits(): string

Returns

string

Implementation of

UplcList.typeBits

Inherited from

UplcValueImpl.typeBits

new

Static new(type, items): UplcList

Constructs a UplcList without requiring a Site

Parameters

NameType
typeUplcType
itemsUplcValue[]

Returns

UplcList

Helios API/ API Reference/ Classes/

UplcPair

Primitive pair value.

Implements

Hierarchy

Implements

Index

Constructors

constructor

new UplcPair(site, first, second)

Parameters

NameType
siteSite
firstUplcValue
secondUplcValue

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

16 additional type bits on top of #first and #second bits

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

key

get key(): UplcData

Returns

UplcData

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

value

get value(): UplcData

Returns

UplcData

Methods

assertUnit

assertUnit(): UplcUnit

Returns

UplcUnit

Implementation of

UplcValue.assertUnit

Inherited from

UplcValueImpl.assertUnit

copy

copy(newSite): UplcValue

Parameters

NameType
newSiteSite

Returns

UplcValue

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(first, second): UplcPair

Constructs a UplcPair without requiring a Site

Parameters

NameType
firstUplcValue
secondUplcValue

Returns

UplcPair

newTerm

Static newTerm(site, first, second): UplcConst

Creates a new UplcBool wrapped with UplcConst so it can be used as a term.

Parameters

NameType
siteSite
firstUplcValue
secondUplcValue

Returns

UplcConst

Helios API/ API Reference/ Classes/

UplcProgram

Result of program.compile(). Contains the Untyped Plutus-Core AST, along with a code-mapping to the original source.

Index

Constructors

constructor

new UplcProgram(expr, properties?, version?)

Parameters

NameType
exprUplcTerm
properties?ProgramProperties
version?UplcInt[]

Accessors

expr

get expr(): UplcTerm

Returns

UplcTerm

mintingPolicyHash

get mintingPolicyHash(): MintingPolicyHash

Returns the MintingPolicyHash of the script. Throws an error if this isn't a minting policy.

Returns

MintingPolicyHash

properties

get properties(): ProgramProperties

Returns

ProgramProperties

site

get site(): Site

Returns

Site

src

get src(): string

Returns the IR source

Returns

string

stakingValidatorHash

get stakingValidatorHash(): StakingValidatorHash

Returns the StakingValidatorHash of the script. Throws an error if this isn't a staking validator script.

Returns

StakingValidatorHash

validatorHash

get validatorHash(): ValidatorHash

Returns the ValidatorHash of the script. Throws an error if this isn't a spending validator script.

Returns

ValidatorHash

versionString

get versionString(): string

Returns version of Plutus-core (!== Plutus script version!)

Returns

string

transferUplcAst

Static get transferUplcAst(): TransferUplcAst

Returns

TransferUplcAst

Methods

apply

apply(args): UplcProgram

Wrap the top-level term with consecutive UplcCall (not exported) terms.

Returns a new UplcProgram instance, leaving the original untouched.

Parameters

NameType
argsUplcValue[]

Returns

UplcProgram

  • a new UplcProgram instance

calcSize

calcSize(): number

Calculates the on chain size of the program (number of bytes).

Returns

number

hash

hash(): number[]

Returns

number[]

  • 28 byte hash

plutusScriptVersion

plutusScriptVersion(): string

Returns

string

profile

profile(args, networkParams): Promise<Profile>

Runs and profiles a UplcProgram. Needs the NetworkParams in order to calculate the execution budget.

Parameters

NameType
argsUplcValue[]
networkParamsNetworkParams

Returns

Promise<Profile>

The returned profile contains a breakdown of the execution cost per Uplc term type and per Uplc builtin function type.

run

run(args, callbacks?, networkParams?): Promise<RuntimeError | UplcValue>

Parameters

NameTypeDescription
argsnull | UplcValue[]if null the top-level term is returned as a value
callbacks?UplcRTECallbacks
networkParams?null | NetworkParams

Returns

Promise<RuntimeError | UplcValue>

runWithPrint

runWithPrint(args): Promise<[RuntimeError | UplcValue, string[]]>

Run a UplcProgram. The printed messages are part of the return value.

Parameters

NameType
argsnull | UplcValue[]

Returns

Promise<[RuntimeError | UplcValue, string[]]>

serialize

serialize(): string

Returns the JSON representation of the serialized program (needed by cardano-cli).

Returns

string

serializeBytes

serializeBytes(): number[]

Returns flat bytes of serialized script

Returns

number[]

toCbor

toCbor(): number[]

Returns the Cbor encoding of a script (flat bytes wrapped twice in Cbor bytearray).

Returns

number[]

toString

toString(): string

Returns

string

transfer

transfer<TInstance>(other): TInstance

Transfers a UplcProgram from an old version of Helios to a new version of Helios, keeping the script hash the same.

The main benefit for calling this method instead of serializing/deserializing is that the code mapping is maintained.

Type parameters

Name
TInstance

Parameters

NameType
otherTransferableUplcProgram<TInstance>

Returns

TInstance

versionTag

versionTag(): number

Returns 1 for PlutusScriptV1, 2 for PlutusScriptV2

Returns

number

fromCbor

Static fromCbor(bytes, properties?): UplcProgram

Parameters

NameType
bytesstring | number[]
properties?ProgramProperties

Returns

UplcProgram

fromFlat

Static fromFlat(bytes, properties?): UplcProgram

Parameters

NameType
bytesnumber[]
properties?ProgramProperties

Returns

UplcProgram

transferUplcProgram

Static transferUplcProgram(expr, properties, version): UplcProgram

Intended for transfer only

Parameters

NameType
exprany
propertiesProgramProperties
versionany[]

Returns

UplcProgram

Helios API/ API Reference/ Classes/

UplcString

Primitive string value.

Implements

Hierarchy

Implements

Index

Constructors

constructor

new UplcString(site, value)

Parameters

NameType
siteSite
valuestring

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

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): UplcString

Parameters

NameType
newSiteSite

Returns

UplcString

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): UplcString

Constructs a UplcStrin without requiring a Site

Parameters

NameType
valuestring

Returns

UplcString

newTerm

Static newTerm(site, value): UplcConst

Creates a new UplcString wrapped with UplcConst so it can be used as a term.

Parameters

NameType
siteSite
valuestring

Returns

UplcConst

Helios API/ API Reference/ Classes/

UplcTerm

Base class of Plutus-core terms

Hierarchy

Index

Constructors

constructor

new UplcTerm(site, type)

Parameters

NameType
siteSite
typenumber

Accessors

site

get site(): Site

Returns

Site

type

get type(): number

Returns

number

Methods

toString

toString(): string

Generic term toString method

Returns

string

transfer

transfer(other): any

Parameters

NameType
otherTransferUplcAst

Returns

any

Helios API/ API Reference/ Classes/

UplcType

Represents the typeBits of a UPLC primitive.

Index

Constructors

constructor

new UplcType(typeBits)

Parameters

NameType
typeBitsstring

Methods

isData

isData(): boolean

Returns

boolean

isDataPair

isDataPair(): boolean

Returns

boolean

isSameType

isSameType(value): boolean

Parameters

NameType
valueUplcValue

Returns

boolean

transfer

transfer(other): any

Parameters

NameType
otherTransferUplcAst

Returns

any

typeBits

typeBits(): string

Returns

string

fromNumbers

Static fromNumbers(lst): UplcType

Parameters

NameType
lstnumber[]

Returns

UplcType

newDataPairType

Static newDataPairType(): UplcType

Returns

UplcType

newDataType

Static newDataType(): UplcType

Returns

UplcType

Helios API/ API Reference/ Classes/

UplcUnit

Primitive unit value.

Implements

Hierarchy

Implements

Index

Constructors

constructor

new UplcUnit(site)

Parameters

NameType
siteSite

Inherited from

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

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): UplcUnit

Parameters

NameType
newSiteSite

Returns

UplcUnit

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(): UplcUnit

Constructs a UplcUnit without requiring a Site

Returns

UplcUnit

newTerm

Static newTerm(site): UplcConst

Creates a new UplcUnit wrapped with UplcConst so it can be used as a term

Parameters

NameType
siteSite

Returns

UplcConst

Helios API/ API Reference/ Classes/

UplcValueImpl

Base cass for UplcValue implementations.

Hierarchy

Index

Constructors

constructor

new UplcValueImpl(site)

Parameters

NameType
siteSite

Accessors

bool

get bool(): boolean

Returns

boolean

bytes

get bytes(): number[]

Returns

number[]

data

get data(): UplcData

Returns

UplcData

first

get first(): UplcValue

Returns

UplcValue

int

get int(): bigint

Returns

bigint

itemType

get itemType(): UplcType

Returns

UplcType

length

get length(): number

Returns

number

list

get list(): UplcValue[]

Returns

UplcValue[]

second

get second(): UplcValue

Returns

UplcValue

site

get site(): Site

Returns

Site

string

get string(): string

Returns

string

Methods

assertUnit

assertUnit(): UplcUnit

Returns

UplcUnit

isAny

isAny(): boolean

Returns

boolean

isData

isData(): boolean

Returns

boolean

isList

isList(): boolean

Distinguishes a list from a map

Returns

boolean

isPair

isPair(): boolean

Distinguishes a pair from a mapItem

Returns

boolean

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

toFlatValueInternal

toFlatValueInternal(bitWriter): void

Encodes value without type header

Parameters

NameType
bitWriterBitWriter

Returns

void

typeBits

typeBits(): string

Returns

string

Helios API/ API Reference/ Classes/

UplcVariable

Plutus-core variable ref term (index is a Debruijn index)

Hierarchy

Index

Constructors

constructor

new UplcVariable(site, index)

Parameters

NameType
siteSite
indexUplcInt

Overrides

UplcTerm.constructor

Properties

index

Readonly index: UplcInt

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
otherTransferUplcAst

Returns

any

Inherited from

UplcTerm.transfer

Helios API/ API Reference/ Classes/

UserError

UserErrors are generated when the user of Helios makes a mistake (eg. a syntax error).

Hierarchy

  • Error

    UserError

Index

Constructors

constructor

new UserError(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

Filled with CBOR hex representations of Datum, Redeemer and ScriptContext by validation scripts throwing errors during tx.finalize(); and Redeemer and ScriptContext by minting scripts throwing errors.

Returns

any

Methods

catch

Static catch<T>(fn, verbose?): undefined | T

Catches any UserErrors thrown inside 'fn()`. Dumps the error

Type parameters

Name
T

Parameters

NameType
fn() => T
verbose?boolean

Returns

undefined | T

isReferenceError

Static isReferenceError(e): boolean

Parameters

NameType
eError

Returns

boolean

isTypeError

Static isTypeError(e): boolean

Parameters

NameType
eError

Returns

boolean

Helios API/ API Reference/ Classes/

ValidatorHash

Represents a blake2b-224 hash of a spending validator script (first encoded as a CBOR byte-array and prepended by a script version byte).

Hierarchy

Index

Constructors

constructor

new ValidatorHash(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): ValidatorHash

Parameters

NameType
bytesstring | number[]

Returns

ValidatorHash

fromUplcData

Static fromUplcData(data): ValidatorHash

Parameters

NameType
dataUplcData

Returns

ValidatorHash

Helios API/ API Reference/ Classes/

Value

Represents a collection of tokens.

Hierarchy

Index

Constructors

constructor

new Value(props?, assets?)

Parameters

NameType
props?ValueProps
assets?null | Assets | AssetsProps

Overrides

HeliosData.constructor

Accessors

assets

get assets(): Assets

Gets the Assets contained in the Value.

Returns

Assets

lovelace

get lovelace(): bigint

Gets the lovelace quantity contained in the Value.

Returns

bigint

Methods

_toUplcData

_toUplcData(isInScriptContext?): MapData

Used when building script context

Parameters

NameType
isInScriptContext?boolean

Returns

MapData

add

add(other): Value

Adds two Value instances together. Returns a new Value instance.

Parameters

NameType
otherValue

Returns

Value

assertAllPositive

assertAllPositive(): Value

Throws an error if any of the Value entries is negative.

Used when building transactions because transactions can't contain negative values.

Returns

Value

  • returns this

dump

dump(): any

Returns

any

eq

eq(other): boolean

Checks if two Value instances are equal (Assets need to be in the same order).

Parameters

NameType
otherValue

Returns

boolean

ge

ge(other): boolean

Checks if a Value instance is strictly greater or equal to another Value instance. Returns false if any asset is missing.

Parameters

NameType
otherValue

Returns

boolean

gt

gt(other): boolean

Checks if a Value instance is strictly greater than another Value instance. Returns false if any asset is missing.

Parameters

NameType
otherValue

Returns

boolean

mul

mul(scalar): Value

Multiplies a Value by a whole number.

Parameters

NameType
scalarHInt | HIntProps

Returns

Value

setLovelace

setLovelace(lovelace): void

Mutates the quantity of lovelace in a Value.

Parameters

NameType
lovelaceHInt | HIntProps

Returns

void

sub

sub(other): Value

Substracts one Value instance from another. Returns a new Value instance.

Parameters

NameType
otherValue

Returns

Value

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

asset

Static asset(mph, tokenName, qty): Value

Parameters

Returns

Value

cleanConstructorArgs

Static cleanConstructorArgs(props, maybeAssets): [HInt | HIntProps, Assets | AssetsProps]

Parameters

NameType
propsValueProps
maybeAssetsnull | Assets | AssetsProps

Returns

[HInt | HIntProps, Assets | AssetsProps]

fromCbor

Static fromCbor(bytes): Value

Parameters

NameType
bytesnumber[]

Returns

Value

fromProps

Static fromProps(props): Value

Parameters

NameType
propsValue | ValueProps

Returns

Value

fromUplcCbor

Static fromUplcCbor(bytes): Value

Parameters

NameType
bytesstring | number[]

Returns

Value

fromUplcData

Static fromUplcData(data): Value

Converts a UplcData instance into a Value. Throws an error if it isn't in the right format.

Parameters

NameType
dataUplcData

Returns

Value

sum

Static sum(values): Value

Parameters

NameType
valuesValue[]

Returns

Value

Helios API/ API Reference/ Classes/

WalletHelper

High-level helper class for instances that implement the Wallet interface.

Index

Constructors

constructor

new WalletHelper(wallet, getUtxosFallback?)

Parameters

NameType
walletWallet
getUtxosFallback?(addr: Address[]) => Promise<TxInput[]>

Accessors

allAddresses

get allAddresses(): Promise<Address[]>

Concatenation of usedAddresses and unusedAddresses.

Returns

Promise<Address[]>

baseAddress

get baseAddress(): Promise<Address>

First Address in allAddresses.

Returns

Promise<Address>

changeAddress

get changeAddress(): Promise<Address>

First Address in unusedAddresses (falls back to last Address in usedAddresses if not defined).

Returns

Promise<Address>

refUtxo

get refUtxo(): Promise<null | TxInput>

First UTxO in utxos. Can be used to distinguish between preview and preprod networks.

Returns

Promise<null | TxInput>

Methods

calcBalance

calcBalance(): Promise<Value>

Returns

Promise<Value>

getUtxos

getUtxos(): Promise<TxInput[]>

Returns

Promise<TxInput[]>

isOwnAddress

isOwnAddress(addr): Promise<boolean>

Returns true if the PubKeyHash in the given Address is controlled by the wallet.

Parameters

NameType
addrAddress

Returns

Promise<boolean>

isOwnPubKeyHash

isOwnPubKeyHash(pkh): Promise<boolean>

Returns true if the given PubKeyHash is controlled by the wallet.

Parameters

NameType
pkhPubKeyHash

Returns

Promise<boolean>

pickCollateral

pickCollateral(amount?): Promise<TxInput>

Picks a single UTxO intended as collateral.

Parameters

NameTypeDescription
amount?bigint2 Ada should cover most things

Returns

Promise<TxInput>

pickUtxos

pickUtxos(amount, algorithm?): Promise<[TxInput[], TxInput[]]>

Pick a number of UTxOs needed to cover a given Value. The default coin selection strategy is to pick the smallest first.

Parameters

NameType
amountValue
algorithm?CoinSelectionAlgorithm

Returns

Promise<[TxInput[], TxInput[]]>

The first list contains the selected UTxOs, the second list contains the remaining UTxOs.

toJson

toJson(): Promise<any>

Returns

Promise<any>

Helios API/ API Reference/

Functions

bytesToHex

bytesToHex(bytes): string

Converts a list of uint8 bytes into its hexadecimal string representation.

Parameters

NameType
bytesnumber[]

Returns

string

Example

bytesToHex([0, 255, 52]) == "00ff34"

bytesToText

bytesToText(bytes): string

Decodes a list of uint8 bytes into a string using UTF-8 encoding.

Parameters

NameType
bytesnumber[]

Returns

string

Example

bytesToText([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]) == "hello world"

deserializeUplc

deserializeUplc(json): UplcProgram

Parses a plutus core program. Returns a UplcProgram instance.

Parameters

NameTypeDescription
jsonstring | { cborHex: string }a raw JSON string or a parsed JSON object

Returns

UplcProgram

deserializeUplcBytes

deserializeUplcBytes(bytes, properties?): UplcProgram

Deserializes a flat encoded UplcProgram.

Parameters

NameType
bytesnumber[]
properties?ProgramProperties

Returns

UplcProgram

extractScriptPurposeAndName

extractScriptPurposeAndName(rawSrc): null | [ScriptPurpose, string]

Quickly extract the script purpose header of a script source, by parsing only the minimally necessary characters.

Parameters

NameType
rawSrcstring

Returns

null | [ScriptPurpose, string]

Returns null if the script header is missing or syntactically incorrect. The first string returned is the script purpose, the second value returned is the script name.

hexToBytes

hexToBytes(hex): number[]

Converts a hexadecimal string into a list of bytes.

Parameters

NameType
hexstring

Returns

number[]

Example

hexToBytes("00ff34") == [0, 255, 52]

highlight

highlight(src): Uint8Array

Returns Uint8Array with the same length as the number of chars in the script. Each resulting byte respresents a different syntax category. This approach should be faster than a RegExp based a approach.

Parameters

NameType
srcstring

Returns

Uint8Array

hl

hl(a, ...b): string

Template string tag function that doesn't do anything and just returns the template string as a string. Can be used as a marker of Helios sources so that syntax highlighting can work inside JS/TS files.

Parameters

NameType
astring[]
...bany[]

Returns

string

Example

hl`hello ${"world"}!` == "hello world!"

textToBytes

textToBytes(str): number[]

Encodes a string into a list of uint8 bytes using UTF-8 encoding.

Parameters

NameType
strstring

Returns

number[]

Example

textToBytes("hello world") == [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

Helios API/ API Reference/

Interfaces

Helios API/ API Reference/ Interfaces/

Network

Blockchain query interface.

Implemented by

Index

Properties

getParameters

getParameters: () => Promise<NetworkParams>

Type declaration

▸ (): Promise<NetworkParams>

Returns the latest network parameters.

Returns

Promise<NetworkParams>

getUtxo

getUtxo: (id: TxOutputId) => Promise<TxInput>

Type declaration

▸ (id): Promise<TxInput>

Returns a single TxInput (that might already have been spent).

Parameters
NameType
idTxOutputId
Returns

Promise<TxInput>

getUtxos

getUtxos: (address: Address) => Promise<TxInput[]>

Type declaration

▸ (address): Promise<TxInput[]>

Returns a complete list of UTxOs at a given address.

Parameters
NameType
addressAddress
Returns

Promise<TxInput[]>

submitTx

submitTx: (tx: Tx) => Promise<TxId>

Type declaration

▸ (tx): Promise<TxId>

Submits a transaction to the blockchain and returns the id of that transaction upon success.

Parameters
NameType
txTx
Returns

Promise<TxId>

Helios API/ API Reference/ Interfaces/

PrivateKey

Implemented by

Index

Properties

derivePubKey

derivePubKey: () => PubKey

Type declaration

▸ (): PubKey

Generates the corresponding public key.

Returns

PubKey

sign

sign: (msg: number[]) => Signature

Type declaration

▸ (msg): Signature

Signs a byte-array payload, returning the signature.

Parameters
NameType
msgnumber[]
Returns

Signature

Helios API/ API Reference/ Interfaces/

UplcValue

UplcValue is passed around by Plutus-core expressions.

Implemented by

Index

Properties

assertUnit

assertUnit: () => UplcUnit

Type declaration

▸ (): UplcUnit

Returns

UplcUnit

bool

bool: boolean

bytes

bytes: number[]

copy

copy: (newSite: Site) => UplcValue

Type declaration

▸ (newSite): UplcValue

return a copy of the UplcValue at a different Site

Parameters
NameType
newSiteSite
Returns

UplcValue

data

data: UplcData

first

first: UplcValue

flatSize

flatSize: number

size taken up in serialized UPLC program (number of bits)

int

int: bigint

isAny

isAny: () => boolean

Type declaration

▸ (): boolean

Returns

boolean

isData

isData: () => boolean

Type declaration

▸ (): boolean

Returns

boolean

isList

isList: () => boolean

Type declaration

▸ (): boolean

Returns

boolean

isPair

isPair: () => boolean

Type declaration

▸ (): boolean

Returns

boolean

itemType

itemType: UplcType

length

length: number

only relevant for lists and maps

list

list: UplcValue[]

memSize

memSize: number

size in words (8 bytes, 64 bits) occupied in target node

second

second: UplcValue

site

site: Site

string

string: string

toFlatValue

toFlatValue: (bitWriter: BitWriter) => void

Type declaration

▸ (bitWriter): void

Parameters
NameType
bitWriterBitWriter
Returns

void

toFlatValueInternal

toFlatValueInternal: (bitWriter: BitWriter) => void

Type declaration

▸ (bitWriter): void

like toFlatValue(), but without the typebits

Parameters
NameType
bitWriterBitWriter
Returns

void

toString

toString: () => string

Type declaration

▸ (): string

Returns

string

transfer

transfer: (other: TransferUplcAst) => any

Type declaration

▸ (other): any

Parameters
NameType
otherTransferUplcAst
Returns

any

typeBits

typeBits: () => string

Type declaration

▸ (): string

Returns

string

Helios API/ API Reference/ Interfaces/

Wallet

An interface type for a wallet that manages a user's UTxOs and addresses.

Implemented by

Index

Properties

collateral

collateral: Promise<TxInput[]>

isMainnet

isMainnet: () => Promise<boolean>

Type declaration

▸ (): Promise<boolean>

Returns true if the wallet is connected to the mainnet.

Returns

Promise<boolean>

rewardAddresses

rewardAddresses: Promise<StakeAddress[]>

Returns a list of the reward addresses.

signData

signData: (addr: Address, sigStructure: string) => Promise<{ key: string ; signature: string }>

Type declaration

▸ (addr, sigStructure): Promise<{ key: string ; signature: string }>

Signs a message, returning an object containing the signature and key that can be used to verify/authenticate the message later.

Parameters
NameType
addrAddress
sigStructurestring
Returns

Promise<{ key: string ; signature: string }>

signTx

signTx: (tx: Tx) => Promise<Signature[]>

Type declaration

▸ (tx): Promise<Signature[]>

Signs a transaction, returning a list of signatures needed for submitting a valid transaction.

Parameters
NameType
txTx
Returns

Promise<Signature[]>

submitTx

submitTx: (tx: Tx) => Promise<TxId>

Type declaration

▸ (tx): Promise<TxId>

Submits a transaction to the blockchain and returns the id of that transaction upon success.

Parameters
NameType
txTx
Returns

Promise<TxId>

unusedAddresses

unusedAddresses: Promise<Address[]>

Returns a list of unique unused addresses which can be used to send UTxOs to with increased anonimity.

usedAddresses

usedAddresses: Promise<Address[]>

Returns a list of addresses which already contain UTxOs.

utxos

utxos: Promise<TxInput[]>

Returns a list of all the utxos controlled by the wallet.

Helios API/ API Reference/

Namespaces

Helios API/ API Reference/ Namespaces/

Cbor

Helper methods for (de)serializing data to/from Cbor.

Note: Each decoding method mutates the input bytes by shifting it to the following CBOR element.

Index

Functions

decodeBool

decodeBool(bytes): boolean

Parameters

NameType
bytesnumber[]

Returns

boolean

decodeBytes

decodeBytes(bytes): number[]

Parameters

NameType
bytesnumber[]

Returns

number[]

decodeConstr

decodeConstr(bytes, fieldDecoder): number

Parameters

NameType
bytesnumber[]
fieldDecoderDecoder

Returns

number

decodeConstrTag

decodeConstrTag(bytes): number

Parameters

NameType
bytesnumber[]

Returns

number

decodeHead

decodeHead(bytes): [number, bigint]

Parameters

NameType
bytesnumber[]

Returns

[number, bigint]

decodeIndefHead

decodeIndefHead(bytes): number

Parameters

NameType
bytesnumber[]

Returns

number

decodeInteger

decodeInteger(bytes): bigint

Parameters

NameType
bytesnumber[]

Returns

bigint

decodeList

decodeList(bytes, itemDecoder): void

Parameters

NameType
bytesnumber[]
itemDecoderDecoder

Returns

void

decodeMap

decodeMap(bytes, pairDecoder): void

Parameters

NameType
bytesnumber[]
pairDecoderDecoder

Returns

void

decodeNull

decodeNull(bytes): void

Parameters

NameType
bytesnumber[]

Returns

void

decodeObject

decodeObject(bytes, fieldDecoder): Set<number>

Parameters

NameType
bytesnumber[]
fieldDecoderDecoder

Returns

Set<number>

decodeTag

decodeTag(bytes): bigint

Parameters

NameType
bytesnumber[]

Returns

bigint

decodeTuple

decodeTuple(bytes, tupleDecoder): number

Parameters

NameType
bytesnumber[]
tupleDecoderDecoder

Returns

number

decodeUtf8

decodeUtf8(bytes): string

Parameters

NameType
bytesnumber[]

Returns

string

decodeUtf8Internal

decodeUtf8Internal(bytes): string

Parameters

NameType
bytesnumber[]

Returns

string

encodeBool

encodeBool(b): number[]

Parameters

NameType
bboolean

Returns

number[]

encodeBytes

encodeBytes(bytes, splitIntoChunks?): number[]

Parameters

NameType
bytesnumber[]
splitIntoChunks?boolean

Returns

number[]

encodeConstr

encodeConstr(tag, fields): number[]

Parameters

NameType
tagnumber
fieldsCborData[] | number[][]

Returns

number[]

encodeConstrTag

encodeConstrTag(tag): number[]

Parameters

NameType
tagnumber

Returns

number[]

encodeDefList

encodeDefList(list): number[]

Parameters

NameType
listCborData[] | number[][]

Returns

number[]

encodeDefListStart

encodeDefListStart(n): number[]

Parameters

NameType
nbigint

Returns

number[]

encodeHead

encodeHead(m, n): number[]

Parameters

NameType
mnumber
nbigint

Returns

number[]

encodeIndefHead

encodeIndefHead(m): number[]

Parameters

NameType
mnumber

Returns

number[]

encodeIndefList

encodeIndefList(list): number[]

Parameters

NameType
listCborData[] | number[][]

Returns

number[]

encodeIndefListEnd

encodeIndefListEnd(): number[]

Returns

number[]

encodeIndefListStart

encodeIndefListStart(): number[]

Returns

number[]

encodeInteger

encodeInteger(n): number[]

Parameters

NameType
nbigint

Returns

number[]

encodeList

encodeList(list): number[]

Parameters

NameType
listCborData[] | number[][]

Returns

number[]

encodeListInternal

encodeListInternal(list): number[]

Parameters

NameType
listCborData[] | number[][]

Returns

number[]

encodeMap

encodeMap(pairList): number[]

Parameters

NameType
pairList[number[] | CborData, number[] | CborData][]

Returns

number[]

encodeMapInternal

encodeMapInternal(pairList): number[]

Parameters

NameType
pairList[number[] | CborData, number[] | CborData][]

Returns

number[]

encodeNull

encodeNull(): number[]

Returns

number[]

encodeObject

encodeObject(object): number[]

Parameters

NameType
objectMap<number, number[] | CborData>

Returns

number[]

encodeTag

encodeTag(tag): number[]

Parameters

NameType
tagbigint

Returns

number[]

encodeTuple

encodeTuple(tuple): number[]

Parameters

NameType
tuplenumber[][]

Returns

number[]

encodeUtf8

encodeUtf8(str, split?): number[]

Parameters

NameType
strstring
split?boolean

Returns

number[]

isBytes

isBytes(bytes): boolean

Parameters

NameType
bytesnumber[]

Returns

boolean

isConstr

isConstr(bytes): boolean

Parameters

NameType
bytesnumber[]

Returns

boolean

isDefBytes

isDefBytes(bytes): boolean

Parameters

NameType
bytesnumber[]

Returns

boolean

isDefList

isDefList(bytes): boolean

Parameters

NameType
bytesnumber[]

Returns

boolean

isIndefBytes

isIndefBytes(bytes): boolean

Parameters

NameType
bytesnumber[]

Returns

boolean

isIndefList

isIndefList(bytes): boolean

Parameters

NameType
bytesnumber[]

Returns

boolean

isList

isList(bytes): boolean

Parameters

NameType
bytesnumber[]

Returns

boolean

isMap

isMap(bytes): boolean

Parameters

NameType
bytesnumber[]

Returns

boolean

isNull

isNull(bytes): boolean

Parameters

NameType
bytesnumber[]

Returns

boolean

isObject

isObject(bytes): boolean

Parameters

NameType
bytesnumber[]

Returns

boolean

isTuple

isTuple(bytes): boolean

Parameters

NameType
bytesnumber[]

Returns

boolean

isUtf8

isUtf8(bytes): boolean

Parameters

NameType
bytesnumber[]

Returns

boolean

Helios API/ API Reference/ Namespaces/

CoinSelection

Collection of common coin selection algorithms.

Index

Functions

selectExtremumFirst

selectExtremumFirst(utxos, amount, largestFirst): [TxInput[], TxInput[]]

Parameters

NameType
utxosTxInput[]
amountValue
largestFirstboolean

Returns

[TxInput[], TxInput[]]

  • [picked, not picked that can be used as spares]

selectLargestFirst

selectLargestFirst(utxos, amount): [TxInput[], TxInput[]]

  • Selects UTxOs from a list by iterating through the tokens in the given Value and picking the UTxOs containing the largest corresponding amount first.

Parameters

NameType
utxosTxInput[]
amountValue

Returns

[TxInput[], TxInput[]]

selectSmallestFirst

selectSmallestFirst(utxos, amount): [TxInput[], TxInput[]]

Selects UTxOs from a list by iterating through the tokens in the given Value and picking the UTxOs containing the smallest corresponding amount first. This method can be used to eliminate dust UTxOs from a wallet.

Parameters

NameType
utxosTxInput[]
amountValue

Returns

[TxInput[], TxInput[]]

Helios API/ API Reference/ Namespaces/

Crypto

The Helios Crypto namespace contains a collection of cryptography primitives.

These functions have been implemented as part of the Helios library in order to avoid external dependencies (there still isn't a standardized Javascript Crypto API that provides all the needed functionality).

Index

Functions

blake2b

blake2b(bytes, digestSize?): number[]

Calculates blake2b hash of a list of uint8 numbers (variable digest size). Result is also a list of uint8 numbers.

Parameters

NameTypeDescription
bytesnumber[]
digestSize?numberDefaults to 32. Can't be greater than 64.

Returns

number[]

List of uint8 numbers.

Example

bytesToHex(Crypto.blake2b([0, 1])) == "01cf79da4945c370c68b265ef70641aaa65eaa8f5953e3900d97724c2c5aa095"

Example

bytesToHex(Crypto.blake2b(textToBytes("abc"), 64)) == "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923"

decodeBase32

decodeBase32(encoded, alphabet?): number[]

Decodes a Base32 string into bytes.

Parameters

NameTypeDescription
encodedstring
alphabet?stringlist of chars, defaults to "abcdefghijklmnopqrstuvwxyz234567"

Returns

number[]

Example

bytesToText(Crypto.decodeBase32("my")) == "f"

Example

bytesToText(Crypto.decodeBase32("mzxq")) == "fo"

Example

bytesToText(Crypto.decodeBase32("mzxw6")) == "foo"

Example

bytesToText(Crypto.decodeBase32("mzxw6yq")) == "foob"

Example

bytesToText(Crypto.decodeBase32("mzxw6ytb")) == "fooba"

Example

bytesToText(Crypto.decodeBase32("mzxw6ytboi")) == "foobar"

decodeBech32

decodeBech32(addr): [string, number[]]

Decomposes a Bech32 checksummed string (eg. a Cardano address), and returns the human readable part and the original bytes Throws an error if checksum is invalid.

Parameters

NameType
addrstring

Returns

[string, number[]]

First part is the human-readable part, second part is a list containing the underlying bytes.

Example

bytesToHex(Crypto.decodeBech32("addr_test1wz54prcptnaullpa3zkyc8ynfddc954m9qw5v3nj7mzf2wggs2uld")[1]) == "70a9508f015cfbcffc3d88ac4c1c934b5b82d2bb281d464672f6c49539"

encodeBase32

encodeBase32(bytes, alphabet?): string

Encodes bytes in using Base32.

Parameters

NameTypeDescription
bytesnumber[]list of uint8 numbers
alphabet?stringlist of chars, defaults to "abcdefghijklmnopqrstuvwxyz234567"

Returns

string

Example

Crypto.encodeBase32(textToBytes("f")) == "my"

Example

Crypto.encodeBase32(textToBytes("fo")) == "mzxq"

Example

Crypto.encodeBase32(textToBytes("foo")) == "mzxw6"

Example

Crypto.encodeBase32(textToBytes("foob")) == "mzxw6yq"

Example

Crypto.encodeBase32(textToBytes("fooba")) == "mzxw6ytb"

Example

Crypto.encodeBase32(textToBytes("foobar")) == "mzxw6ytboi"

encodeBech32

encodeBech32(hrp, data): string

Creates a Bech32 checksummed string (eg. used to represent Cardano addresses).

Parameters

NameTypeDescription
hrpstringhuman-readable part (eg. "addr")
datanumber[]a list of uint8 bytes

Returns

string

Example

Crypto.encodeBech32("foo", textToBytes("foobar")) == "foo1vehk7cnpwgry9h96"

Example

Crypto.encodeBech32("addr_test", hexToBytes("70a9508f015cfbcffc3d88ac4c1c934b5b82d2bb281d464672f6c49539")) == "addr_test1wz54prcptnaullpa3zkyc8ynfddc954m9qw5v3nj7mzf2wggs2uld"

hmacSha2_256

hmacSha2_256(key, message): number[]

Hmac using sha2-256.

Parameters

NameType
keynumber[]
messagenumber[]

Returns

number[]

Example

bytesToHex(Crypto.hmacSha2_256(textToBytes("key"), textToBytes("The quick brown fox jumps over the lazy dog"))) == "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"

hmacSha2_512

hmacSha2_512(key, message): number[]

Hmac using sha2-512.

Parameters

NameType
keynumber[]
messagenumber[]

Returns

number[]

Example

bytesToHex(Crypto.hmacSha2_512(textToBytes("key"), textToBytes("The quick brown fox jumps over the lazy dog"))) == "b42af09057bac1e2d41708e48a902e09b5ff7f12ab428a4fe86653c73dd248fb82f948a549f7b791a5b41915ee4d1ec3935357e4e2317250d0372afa2ebeeb3a"

mulberry32

mulberry32(seed): NumberGenerator

A simple pseudo-random number generator for use in tests that requires some randomness but need to be deterministic (i.e. each test run gives the same result).

Parameters

NameType
seednumber

Returns

NumberGenerator

The returned function returns a new random number between 0 and 1 upon each call.

pbkdf2

pbkdf2(prf, password, salt, iters, dkLength): number[]

Password-Based Key Derivation Function 2.

Parameters

NameType
prf(key: number[], msg: number[]) => number[]
passwordnumber[]
saltnumber[]
itersnumber
dkLengthnumber

Returns

number[]

Example

bytesToHex(Crypto.pbkdf2(Crypto.hmacSha2_256, textToBytes("password"), textToBytes("salt"), 1, 20)) == "120fb6cffcf8b32c43e7225256c4f837a86548c9"

Example

bytesToHex(Crypto.pbkdf2(Crypto.hmacSha2_512, textToBytes("password"), textToBytes("salt"), 2, 20)) == "e1d9c16aa681708a45f5c7c4e215ceb66e011a2e"

rand

rand(seed): NumberGenerator

Alias for mulberry32.

Parameters

NameType
seednumber

Returns

NumberGenerator

The returned function returns a new random number between 0 and 1 upon each call.

sha2_256

sha2_256(bytes): number[]

Calculates sha2-256 (32bytes) hash of a list of bytes. Result is also a list of bytes.

Parameters

NameTypeDescription
bytesnumber[]List of uint8 numbers

Returns

number[]

List of uint8 numbers.

Example

bytesToHex(Crypto.sha2_256([0x61, 0x62, 0x63])) == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"

Example

Crypto.sha2_256(textToBytes("Hello, World!")) == [223, 253, 96, 33, 187, 43, 213, 176, 175, 103, 98, 144, 128, 158, 195, 165, 49, 145, 221, 129, 199, 247, 10, 75, 40, 104, 138, 54, 33, 130, 152, 111]

sha2_512

sha2_512(bytes): number[]

Calculates sha2-512 (64bytes) hash of a list of uint8 numbers. Result is also a list of uint8 number.

Parameters

NameTypeDescription
bytesnumber[]List of uint8 numbers

Returns

number[]

List of uint8 numbers.

Example

bytesToHex(Crypto.sha2_512([0x61, 0x62, 0x63])) == "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"

Example

bytesToHex(Crypto.sha2_512([])) == "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"

Example

bytesToHex(Crypto.sha2_512(textToBytes("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"))) == "204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445"

Example

bytesToHex(Crypto.sha2_512(textToBytes("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstuu"))) == "23565d109ac0e2aa9fb162385178895058b28489a6bc31cb55491ed83956851ab1d4bbd46440586f5c9c4b69c9c280118cbc55c71495d258cc27cc6bb25ee720"

sha3

sha3(bytes): number[]

Calculates sha3-256 (32bytes) hash of a list of uint8 numbers. Result is also a list of uint8 number.

Parameters

NameTypeDescription
bytesnumber[]List of uint8 numbers

Returns

number[]

List of uint8 numbers.

Example

bytesToHex(Crypto.sha3(textToBytes("abc"))) == "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532"

Example

bytesToHex(Crypto.sha3((new Array(136)).fill(1))) == "b36dc2167c4d9dda1a58b87046c8d76a6359afe3612c4de8a38857e09117b2db"

Example

bytesToHex(Crypto.sha3((new Array(135)).fill(2))) == "5bdf5d815d29a9d7161c66520efc17c2edd7898f2b99a029e8d2e4ff153407f4"

Example

bytesToHex(Crypto.sha3((new Array(134)).fill(3))) == "8e6575663dfb75a88f94a32c5b363c410278b65020734560d968aadd6896a621"

Example

bytesToHex(Crypto.sha3((new Array(137)).fill(4))) == "f10b39c3e455006aa42120b9751faa0f35c821211c9d086beb28bf3c4134c6c6"

verifyBech32

verifyBech32(encoded): boolean

Verifies a Bech32 checksum.

Parameters

NameType
encodedstring

Returns

boolean

Example

Crypto.verifyBech32("foo1vehk7cnpwgry9h96") == true

Example

Crypto.verifyBech32("foo1vehk7cnpwgry9h97") == false

Example

Crypto.verifyBech32("a12uel5l") == true

Example

Crypto.verifyBech32("mm1crxm3i") == false

Example

Crypto.verifyBech32("A1G7SGD8") == false

Example

Crypto.verifyBech32("abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lmqqqxw") == true

Example

Crypto.verifyBech32("?1ezyfcl") == true

Example

Crypto.verifyBech32("addr_test1wz54prcptnaullpa3zkyc8ynfddc954m9qw5v3nj7mzf2wggs2uld") == true

Helios API/ API Reference/ Namespaces/

Ed25519

The elliptic curve signature algorithm used by Cardano wallets.

Ported from: https://ed25519.cr.yp.to/python/ed25519.py.

ExtendedPoint implementation taken from: https://github.com/paulmillr/noble-ed25519.

Index

Functions

deriveBip32PublicKey

deriveBip32PublicKey(extendedKey): number[]

Similar to Ed25519.derivePublicKey, but doesn't hash the input key.

Parameters

NameType
extendedKeynumber[]

Returns

number[]

32 byte public key.

derivePublicKey

derivePublicKey(privateKey): number[]

Derive a public key from a private key. The private key can be any number of bytes (it's hashed internally). The returned public key is 32 bytes long.

Parameters

NameType
privateKeynumber[]

Returns

number[]

32 byte public key.

sign

sign(message, privateKey): number[]

Creates a 64 byte signature.

Parameters

NameType
messagenumber[]
privateKeynumber[]

Returns

number[]

64 byte signature.

signBip32

signBip32(message, extendedKey): number[]

Like Ed25519.sign, but doesn't hash the input key.

Parameters

NameType
messagenumber[]
extendedKeynumber[]

Returns

number[]

64 byte signature.

verify

verify(signature, message, publicKey): boolean

Returns true if the signature is correct.

Parameters

NameType
signaturenumber[]
messagenumber[]
publicKeynumber[]

Returns

boolean

Helios API/ API Reference/ Namespaces/

config

Mutable global config properties.

Index

Variables

AUTO_SET_VALIDITY_RANGE

Const AUTO_SET_VALIDITY_RANGE: boolean

The validity time range can be set automatically if a call to tx.time_range in a Helios script is detected. If false the validity range is still set automatically if not set manually but a warning is printed.

Default: false.

CHECK_CASTS

Const CHECK_CASTS: boolean

Check that from_data casts make sense during runtime, printing a warning if it doesn't. This ony impacts unsimplified UplcPrograms.

Default: false.

DEBUG

Const DEBUG: boolean

Global debug flag. Currently unused.

Default: false.

IGNORE_UNEVALUATED_CONSTANTS

Const IGNORE_UNEVALUATED_CONSTANTS: boolean

Ignore constants that can't be evaluated during compile-time.

Default: false.

IS_TESTNET

Const IS_TESTNET: boolean

If true, Address instances are assumed to be for a Testnet when constructing from hashes or raw bytes, otherwise for mainnet.

Default: true.

MAX_ASSETS_PER_CHANGE_OUTPUT

Const MAX_ASSETS_PER_CHANGE_OUTPUT: undefined

Maximum number of assets per change output. Used to break up very large asset outputs into multiple outputs.

Default: undefined (no limit).

N_DUMMY_INPUTS

Const N_DUMMY_INPUTS: number

Calculating the execution budget during tx building requires knowing all the inputs beforehand, which is very difficult because balancing is done after the budget is calculated. Instead we use at least 1 dummy input, which should act as a representative balancing input. For increased robustness we use 2 dummy inputs, one with Txid 0 and other with TxId ffff..., because eg. there are cases where the TxId is being printed, and a Txid of ffff... would overestimate the fee for that. This value must be '1' or '2'.

Default: 2.

Deprecated

STRICT_BABBAGE

Const STRICT_BABBAGE: boolean

If true, TxOutput is serialized using strictly the Babagge cddl format (slightly more verbose).

Default: false.

VALIDITY_RANGE_END_OFFSET

Const VALIDITY_RANGE_END_OFFSET: number

Upper offset wrt. the current system time when setting a transaction validity range automatically.

Default: 300 seconds.

VALIDITY_RANGE_START_OFFSET

Const VALIDITY_RANGE_START_OFFSET: number

Lower offset wrt. the current system time when setting a transaction validity range automatically.

Defaut: 90 seconds.

Functions

set

set(props): void

Modify the config properties

Parameters

NameType
propsObject
props.AUTO_SET_VALIDITY_RANGE?boolean
props.CHECK_CASTS?boolean
props.DEBUG?boolean
props.IGNORE_UNEVALUATED_CONSTANTS?boolean
props.IS_TESTNET?boolean
props.MAX_ASSETS_PER_CHANGE_OUTPUT?number
props.N_DUMMY_INPUTS?number
props.STRICT_BABBAGE?boolean
props.VALIDITY_RANGE_END_OFFSET?number
props.VALIDITY_RANGE_START_OFFSET?number

Returns

void

Helios API/ API Reference/

Types

AddressProps

Ƭ AddressProps: number[] | string

An array of bytes, a Bech32 encoded address, or the hexadecimal representation of the underlying bytes.

AssetClassProps

Ƭ AssetClassProps: string | [MintingPolicyHash | MintingPolicyHashProps, ByteArray | ByteArrayProps] | { mph: MintingPolicyHash | MintingPolicyHashProps ; tokenName: ByteArray | ByteArrayProps }

AssetsProps

Ƭ AssetsProps: [AssetClass | AssetClassProps, HInt | HIntProps][] | [MintingPolicyHash | MintingPolicyHashProps, [ByteArray | ByteArrayProps, HInt | HIntProps][]][]

ByteArrayProps

Ƭ ByteArrayProps: number[] | string

Cip30Handle

Ƭ Cip30Handle: Object

Convenience type for browser plugin wallets supporting the CIP 30 dApp connector standard (eg. Eternl, Nami, ...).

This is useful in typescript projects to avoid type errors when accessing the handles in window.cardano.

// refer to this file in the 'typeRoots' list in tsconfig.json

type Cip30SimpleHandle = {
  name: string,
  icon: string,
  enable(): Promise<helios.Cip30Handle>,
  isEnabled(): boolean
}

declare global {
  interface Window {
    cardano: {
      [walletName: string]: Cip30SimpleHandle
    };
  }
}

Type declaration

NameType
experimental{ getCollateral: () => Promise<string[]> }
experimental.getCollateral[object Object]
getCollateral() => Promise<string[]>
getNetworkId() => Promise<number>
getRewardAddresses() => Promise<string[]>
getUnusedAddresses() => Promise<string[]>
getUsedAddresses() => Promise<string[]>
getUtxos() => Promise<string[]>
signData(addr: string, sigStructure: string) => Promise<{ key: string ; signature: string }>
signTx(txHex: string, partialSign: boolean) => Promise<string>
submitTx(txHex: string) => Promise<string>

CoinSelectionAlgorithm

Ƭ CoinSelectionAlgorithm: (utxos: TxInput[], amount: Value) => [TxInput[], TxInput[]]

Type declaration

▸ (utxos, amount): [TxInput[], TxInput[]]

Returns two lists. The first list contains the selected UTxOs, the second list contains the remaining UTxOs.

Parameters
NameType
utxosTxInput[]
amountValue
Returns

[TxInput[], TxInput[]]

Cost

Ƭ Cost: Object

Type declaration

NameType
cpubigint
membigint

CostCount

Ƭ CostCount: Cost & { count: number }

CurvePoint

Ƭ CurvePoint<T>: Object

Type parameters

NameType
Textends CurvePoint<T>

Type declaration

NameType
add(other: T) => T
encode() => number[]
equals(other: T) => boolean
mul(scalar: bigint) => T

DatumHashProps

Ƭ DatumHashProps: HashProps

Decoder

Ƭ Decoder: (i: number, bytes: number[]) => void

Type declaration

▸ (i, bytes): void

Parameters
NameType
inumber
bytesnumber[]
Returns

void

HIntProps

Ƭ HIntProps: number | bigint

Deprecated

HashProps

Ƭ HashProps: number[] | string

LiveSlotGetter

Ƭ LiveSlotGetter: () => bigint

Type declaration

▸ (): bigint

Returns

bigint

Metadata

Ƭ Metadata: { map: [any, any][] } | any[] | string | number

The inner 'any' is also Metadata, but jsdoc doesn't allow declaring recursive types Metadata is essentially a JSON schema object

MintingPolicyHashProps

Ƭ MintingPolicyHashProps: HashProps

NetworkSliceUTxOs

Ƭ NetworkSliceUTxOs: Object

collectUtxos removes tx inputs from the list, and appends txoutputs sent to the address to the end.

Index signature

▪ [address: string]: TxInput[]

NumberGenerator

Ƭ NumberGenerator: () => number

Type declaration

▸ (): number

Function that generates a random number between 0 and 1

Returns

number

Profile

Ƭ Profile: Object

mem: in 8 byte words (i.e. 1 mem unit is 64 bits) cpu: in reference cpu microseconds size: in bytes builtins: breakdown per builtin terms: breakdown per termtype result: result of evaluation messages: printed messages (can be helpful when debugging)

Type declaration

NameType
builtins?{ [name: string]: CostCount; }
cpubigint
membigint
messages?string[]
result?RuntimeError | UplcValue
size?number
terms?{ [name: string]: CostCount; }

ProgramConfig

Ƭ ProgramConfig: Object

Type declaration

NameType
allowPosParamsboolean
invertEntryPointboolean

ProgramProperties

Ƭ ProgramProperties: Object

TODO: purpose as enum type

Type declaration

NameType
callsTxTimeRangeboolean
name?string
purposenull | ScriptPurpose

PropertyTest

Ƭ PropertyTest: (args: UplcValue[], res: UplcValue | RuntimeError, isSimplfied?: boolean) => boolean | { [x: string]: boolean; }

Type declaration

▸ (args, res, isSimplfied?): boolean | { [x: string]: boolean; }

Parameters
NameType
argsUplcValue[]
resUplcValue | RuntimeError
isSimplfied?boolean
Returns

boolean | { [x: string]: boolean; }

PubKeyHashProps

Ƭ PubKeyHashProps: HashProps

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.

PubKeyProps

Ƭ PubKeyProps: number[] | string

ScriptPurpose

Ƭ ScriptPurpose: "testing" | "minting" | "spending" | "staking" | "endpoint" | "module" | "unknown"

A Helios/Uplc Program can have different purposes

StakingValidatorHashProps

Ƭ StakingValidatorHashProps: HashProps

TransferUplcAst

Ƭ TransferUplcAst: Object

Needed by transfer() methods

Type declaration

NameType
transferByteArrayData(bytes: number[]) => any
transferConstrData(index: number, fields: any[]) => any
transferIntData(value: bigint) => any
transferListData(items: any[]) => any
transferMapData(pairs: [any, any][]) => any
transferSite(src: any, startPos: number, endPos: number, codeMapSite: null | any) => any
transferSource(raw: string, name: string) => any
transferUplcBool(site: any, value: boolean) => any
transferUplcBuiltin(site: any, name: string | number) => any
transferUplcByteArray(site: any, bytes: number[]) => any
transferUplcCall(site: any, a: any, b: any) => any
transferUplcConst(value: any) => any
transferUplcDataValue(site: any, data: any) => any
transferUplcDelay(site: any, expr: any) => any
transferUplcError(site: any, msg: string) => any
transferUplcForce(site: any, expr: any) => any
transferUplcInt(site: any, value: bigint, signed: boolean) => any
transferUplcLambda(site: any, rhs: any, name: null | string) => any
transferUplcList(site: any, itemType: any, items: any[]) => any
transferUplcPair(site: any, first: any, second: any) => any
transferUplcString(site: any, value: string) => any
transferUplcType(typeBits: string) => any
transferUplcUnit(site: any) => any
transferUplcVariable(site: any, index: any) => any

TransferableUplcProgram

Ƭ TransferableUplcProgram<TInstance>: Object

The constructor returns 'any' because it is an instance of TransferableUplcProgram, and the instance methods don't need to be defined here

Type parameters

Name
TInstance

Type declaration

NameType
transferUplcAstTransferUplcAst
transferUplcProgram(expr: any, properties: ProgramProperties, version: any[]) => TInstance

TxIdProps

Ƭ TxIdProps: HashProps

TxOutputIdProps

Ƭ TxOutputIdProps: string | [TxId | TxIdProps, HInt | HIntProps] | { txId: TxId | TxIdProps ; utxoId: HInt | HIntProps }

UInt64Fast

Ƭ UInt64Fast: [number, number]

TODO: switch to using UInt64Fast instead of UInt64 everywhere First entry: high Second entry: low

UplcRTECallbacks

Ƭ UplcRTECallbacks: Object

Type declaration

NameType
onEndCall(site: Site, rawStack: UplcRawStack) => Promise<void>
onIncrCost(name: string, isTerm: boolean, cost: Cost) => void
onPrint(msg: string) => Promise<void>
onStartCall(site: Site, rawStack: UplcRawStack) => Promise<boolean>

UplcRawStack

Ƭ UplcRawStack: [null | string, UplcValue][]

UserTypes

Ƭ UserTypes: Object

Interface for:

  • IRErrorExpr
  • IRCallExpr
  • IRFuncExpr
  • IRNameExpr
  • IRLiteralExpr

The copy() method is needed because inlining can't use the same IRNameExpr twice, so any inlineable expression is copied upon inlining to assure each nested IRNameExpr is unique. This is important to do even the the inlined expression is only called once, because it might still be inlined into multiple other locations that are eliminated in the next iteration.

flatSize returns the number of bits occupied by the equivalent UplcTerm in the final serialized UPLC program This is used to detect small IRFuncExprs and inline them

Index signature

▪ [name: string]: any

ValidatorHashProps

Ƭ ValidatorHashProps: HashProps

ValueGenerator

Ƭ ValueGenerator: () => UplcData

Type declaration

▸ (): UplcData

Returns

UplcData

ValueProps

Ƭ ValueProps: HInt | HIntProps | [HInt | HIntProps, Assets | AssetsProps] | { assets?: Assets | AssetsProps ; lovelace: HInt | HIntProps }

Helios API/ API Reference/

Variables

BIP32_HARDEN

Const BIP32_HARDEN: 2147483648

Used during Bip32PrivateKey derivation, to create a new Bip32PrivateKey instance with a non-publicly deriveable PubKey.

BIP39_DICT_EN

Const BIP39_DICT_EN: string[]

Standard English Bip39 dictionary consisting of 2048 words allowing wallet root keys to be formed by a phrase of 12, 15, 18, 21 or 24 of these words.

DEFAULT_UPLC_RTE_CALLBACKS

Const DEFAULT_UPLC_RTE_CALLBACKS: UplcRTECallbacks

Configures the Uplc evaluator to print messages to console.

VERSION

Const VERSION: "0.16.6"

Current version of the Helios library.

Helios CLI

This chapter explains how to use the helios-cli, and how to build and submit transactions using cardano-cli.

Note: helios-cli is work-in-progress and can only be used for simple operations (compiling, evaluating parameters, calculating script addresses).

Helios CLI/

Setup

This section explains how to:

These steps require the following dependencies:

  • node
  • npm
  • docker

Helios CLI/ Setup/

Install helios-cli

Dependencies:

  • node
  • npm

Install using npm:

$ sudo npm install -g @hyperionbt/helios-cli

Verify the installation using the following command:

$ helios version

Helios CLI/ Setup/

Install cardano-node

You will need a Linux environment with docker for this.

We have provided convenient docker containers for running cardano-node.

$ git clone https://github.com/Hyperion-BT/cardano-node-wrappers
$ cd cardano-node-wrappers

Build and start a cardano-node docker container (non-persistent):

$ make build-preprod

$ make run-preprod # non-persistent, just to check if it works

Or persistent:

$ make run-preprod-persistent # runs in background with a persistent data volume

Alternative you can choose preview.

These commands will automatically download IOG's latest cardano-node image, and then create a named docker volume for storing the blockchain state.

Check that the cardano-node container is running using the following command:

$ docker ps

Take note of the container id.

You can stop the container any time:

$ docker stop <container-id>

We recommend using docker stop and not docker rm -f as it allows cardano-node processes to receive the more graceful SIGTERM signal (instead of just SIGKILL).

You can clean up stopped containers if you are running low on system resources:

$ docker system prune

About 30 seconds after starting the cardano-node container, /ipc/node.socket should've been created and you can start using cardano-cli to query the blockchain. If you are restarting the cardano-node after a major upgrade (eg. an HFC) it could take much longer though (an hour or more). If you are impatient you should launch the cardano-node container using the docker run command without the -d flag. This way you can follow the (re)sync progress in your terminal.

Poll for the blockchain sync status using the following command:

$ docker exec <container-id> cardano-cli query tip --testnet-magic 1097911063

The first time it can take up to 10 hours for your cardano-node to fully synchronize.

Helios CLI/ Setup/

Wallet setup

Start an interactive shell in your cardano-node docker container:

$ docker exec -it <container-id> bash

Create the directory where we will store the wallet keys:

> mkdir -p /data/wallets

Create three wallets, each with an associated payment address:

> cd /data/wallets

> cardano-cli address key-gen \
  --verification-key-file wallet1.vkey \
  --signing-key-file wallet1.skey
> cardano-cli address build \
  --payment-verification-key-file wallet1.vkey \
  --out-file wallet1.addr \
  --testnet-magic $TESTNET_MAGIC_NUM
> cat wallet1.addr

addr_test1vqwj9w0...

> cardano-cli address key-gen \
  --verification-key-file wallet2.vkey \
  --signing-key-file wallet2.skey
> cardano-cli address build \
  --payment-verification-key-file wallet2.vkey \
  --out-file wallet2.addr \
  --testnet-magic $TESTNET_MAGIC_NUM

> cardano-cli address key-gen \
  --verification-key-file wallet3.vkey \
  --signing-key-file wallet3.skey
> cardano-cli address build \
  --payment-verification-key-file wallet3.vkey \
  --out-file wallet3.addr \
  --testnet-magic $TESTNET_MAGIC_NUM

Take note of the payment address of wallet 1.

Funding

Go to testnets.cardano.org/en/testnets/cardano/tools/faucet/ to add some funds.

After adding some funds, check the balance of the wallet 1's payment address:

> cardano-cli query utxo \
  --address $(cat /data/wallets/wallet1.addr) \
  --testnet-magic $TESTNET_MAGIC_NUM

...

The funding faucet is limited to one usage per day per user. So try to fund wallets 2 and 3 on other days.

Helios CLI/

Using helios-cli

Compiling

$ helios compile my_script.hl -o my_script.json

Optimization can be switched on using the --optimize (or -O) flag:

$ helios compile my_script.hl --optimize -o my_script.json

helios-cli automatically searches for modules in the current directory. Other directories can be included using the -I option:

$ helios compile my_script.hl -I ./my_modules/ -o my_script.json

Parameters can be set using the -D<param-name> <param-value> option:

$ helios compile my_script.hl -DMY_PARAM 100 -o my_script.json

Evaluating a parameter

$ helios eval my_script.hl MY_PARAM

Similar to the compile command, additional module directories can be included using -I.

Calculating a script address

helios-cli can calculate the address of a compiled script:

$ helios address my_script.json

For mainnet address the --mainnet (or -m) flag must be used:

$ helios address my_script --mainnet

Helios CLI/

Example: Always succeeds

Create a always_succeeds.hl script with the following code:

spending always_succeeds

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

Compile the Always Succeeds script into its JSON representation:

$ helios compile always_succeeds.hl

{"type": "PlutusScriptV2", "description": "", "cborHex" :"52510100003222253335734a0082930b0a5101"}

Start an interactive shell in the cardano-node container and copy the content of the JSON representing the script:

$ docker exec -it <container-id> bash

> mkdir -p /data/scripts
> cd /data/scripts

> echo '{
  "type": "PlutusScriptV2", 
  "description": "", 
  "cborHex": "52510100003222253335734a0082930b0a5101"
}' > always-succeeds.json

Generate the script address:

> cardano-cli address build \
  --payment-script-file /data/scripts/always-succeeds.json \
  --out-file /data/scripts/always-succeeds.addr \
  --testnet-magic $TESTNET_MAGIC_NUM

> cat /data/scripts/always-succeeds.addr

addr_test1wpfvdtcvnd6yknhve6pc2w999n4325pck00x3c4m9750cdch6csfq

We need a datum, which can be chosen arbitrarily in this case:

> DATUM_HASH=$(cardano-cli transaction hash-script-data --script-data-value "42")
> echo $DATUM_HASH

9e1199a988ba72ffd6e9c269cadb3b53b5f360ff99f112d9b2ee30c4d74ad88b

We also need to select some UTxOs as inputs to the transaction. At this point we should have one UTxO sitting in wallet 1. We can query this using the following command:

> cardano-cli query utxo \
  --address $(cat /data/wallets/wallet1.addr) \
  --testnet-magic $TESTNET_MAGIC_NUM

TxHash             TxIx  Amount
-------------------------------------------------------------
4f3d0716b07d75...  0     1000000000 lovelace + TxOutDatumNone

4f3d... is the transaction id. The UTxO id in this case is 4f3d...#0.

We now have everything we need to build a transaction and submit it.

Let's send 2 tAda (2 million lovelace) to the script address:

> TX_BODY=$(mktemp)
> cardano-cli transaction build \
  --tx-in 4f3d...#0 \
  --tx-out $(cat /data/scripts/always-succeeds.addr)+2000000 \
  --tx-out-datum-hash $DATUM_HASH \
  --change-address $(cat /data/wallets/wallet1.addr) \
  --testnet-magic $TESTNET_MAGIC_NUM \
  --out-file $TX_BODY \
  --babbage-era

Estimated transaction fee: Lovelace 167217

> TX_SIGNED=$(mktemp)
> cardano-cli transaction sign \
  --tx-body-file $TX_BODY \
  --signing-key-file /data/wallets/wallet1.skey \
  --testnet-magic $TESTNET_MAGIC_NUM \
  --out-file $TX_SIGNED

> cardano-cli transaction submit \
  --tx-file $TX_SIGNED \
  --testnet-magic $TESTNET_MAGIC_NUM

Transaction successfully submitted

If you check the wallet 1 payment address balance after a few minutes you will noticed that it has decreased by 2 tAda + fee. Note the left-over UTxO id, we will need it to pay fees when retrieving funds.

You can also try to check the balance of the script address:

> cardano-cli query utxo \
  --address $(cat /data/scripts/always-succeeds.addr) \
  --testnet-magic $TESTNET_MAGIC_NUM

...

The table should list at least one UTxO with your specific datum hash.

We can now try and get our funds back from the script by building, signing and submitting another transaction:

> PARAMS=$(mktemp) # most recent protocol parameters
> cardano-cli query protocol-parameters --testnet-magic $TESTNET_MAGIC_NUM > $PARAMS

> TX_BODY=$(mktemp)
> cardano-cli transaction build \
  --tx-in <fee-utxo> \ # used for tx fee
  --tx-in <script-utxo> \
  --tx-in-datum-value "42" \
  --tx-in-redeemer-value <arbitrary-redeemer-data> \
  --tx-in-script-file /data/scripts/always-succeeds.json \
  --tx-in-collateral <fee-utxo> \ # used for script collateral
  --change-address $(cat /data/wallets/wallet1.addr) \
  --tx-out $(cat /data/wallets/wallet1.addr)+2000000 \
  --out-file $TX_BODY \
  --testnet-magic $TESTNET_MAGIC_NUM \
  --protocol-params-file $PARAMS \
  --babbage-era

Estimated transaction fee: Lovelace 178405

> TX_SIGNED=$(mktemp)
> cardano-cli transaction sign \
  --tx-body-file $TX_BODY \
  --signing-key-file /data/wallets/wallet1.skey \
  --testnet-magic $TESTNET_MAGIC_NUM \
  --out-file $TX_SIGNED

> cardano-cli transaction submit \
  --tx-file $TX_SIGNED \
  --testnet-magic $TESTNET_MAGIC_NUM

Transaction successfully submitted

If you now check the balance of wallet 1 you should see two UTxOs, and the total value should be your starting value minus the two fees you paid.

Note that collateral is only paid if you submit a bad script. Cardano-cli does extensive checking of your script though, and should prevent you from submitting anything faulty. So collateral is only really paid by malicious users.

Helios CLI/

Example: Time lock

The always-succeeds contract in the previous section isn't very useful. Something that is still simple, but has real-world applications, is a time-lock contract. Actors send UTxOs to the time-lock address with a datum that contains a lock-until time. An optional nonce can be included in the datum to allow only the actors who know the nonce value to retrieve the UTxOs. The wallet from which the original UTxOs were sent is also able to retrieve the UTxOs at any time.

The Helios script:

spending time_lock

struct Datum {
    lockUntil: Time
    owner:     PubKeyHash // can't get this info from the ScriptContext
    nonce:     Int
}

func main(datum: Datum, _, ctx: ScriptContext) -> Bool {
    tx: Tx = ctx.tx;
    now: Time = tx.time_range.start;
    returnToOwner: Bool = tx.is_signed_by(datum.owner);

    (now > datum.lockUntil) || returnToOwner
}
// end-of-main, anything that comes after isn't part of the on-chain script

// MY_DATUM parameters
const LOCK_UNTIL = 0 // seconds since 1970, set by cli
const OWNER = PubKeyHash::new(#) // set by cli
const NONCE = 42 // can be set by cli

// Helios can evaluate MY_DATUM into a data-structure that can be used to build a transaction
const MY_DATUM = Datum{
  lockUntil: Time::new(LOCK_UNTIL*1000),  // needs to be in milliseconds
  owner:     OWNER, 
  nonce:     NONCE
}

UTxOs can be sent into the time-lock script arbitrarily as long as the datum has the correct format. UTxOs can be retrieved any time by the wallet that initiated the time-lock. UTxOs can be retrieved after the time-lock by anyone who knows the datum.

Once we have written the script, we generate its JSON representation using helios-cli, and then calculate the script address using cardano-cli:

$ helios compile time_lock.hl

{"type": "PlutusScriptV2", "description": "", "cborHex": "5..."}
$ docker exec -it <container-id> bash

> echo '{
  "type": "PlutusScriptV1",
  "description": "",
  "cborHex": "5...",
}' > /data/scripts/time-lock.json

> cardano-cli address build \
  --payment-script-file /data/scripts/time-lock.json \
  --out-file /data/scripts/time-lock.addr \
  --testnet-magic $TESTNET_MAGIC_NUM

> cat time-lock.addr

addr_test1...

For the datum we need the PubKeyHash of the initiating wallet (i.e. the owner):

$ docker exec -it <container-id> bash

> cardano-cli address key-hash --payment-verification-key-file /data/wallets/wallet1.vkey

1d22b9ff5fc...

We also need a lockUntil time, for example 5 minutes from now. Now we can build the datum:

$ helios eval time_lock.hl MY_DATUM \
  -DOWNER "000102030405060708090a0b0c0d0e0f101112131415161718191a1b" \
  -DLOCK_UNTIL $(($(date +%s) + 300)) \
  -DNONCE 12345

{"constructor": 0, "fields": [{"int": 16....}, {"bytes": "0001020304..."}, {"int": 12345}]}

Now let's send 2 tAda to the script address using the datum we just generated:

$ docker exec -it <container-id> bash

> cardano-cli query utxo \
  --address $(cat /data/wallets/wallet1.addr) \
  --testnet-magic $TESTNET_MAGIC_NUM

...
# take note of a UTxO big enough to cover 2 tAda + fees

> DATUM=$(mktemp)
> echo '{"constructor": 0, "fields": [{"int": 16....}, {"int": 42}]}' > $DATUM

> DATUM_HASH=$(cardano-cli transaction hash-script-data --script-data-file $DATUM)

> TX_BODY=$(mktemp)
> cardano-cli transaction build \
  --tx-in <funding-utxo> \
  --tx-out $(cat /data/scripts/time-lock.addr)+2000000 \
  --tx-out-datum-hash $DATUM_HASH \
  --change-address $(cat /data/wallets/wallet1.addr) \
  --testnet-magic $TESTNET_MAGIC_NUM \
  --out-file $TX_BODY \
  --babbage-era

Estimated transaction fee: Lovelace 167217

> TX_SIGNED=$(mktemp)
> cardano-cli transaction sign \
  --tx-body-file $TX_BODY \
  --signing-key-file /data/wallets/wallet1.skey \
  --testnet-magic $TESTNET_MAGIC_NUM \
  --out-file $TX_SIGNED

> cardano-cli transaction submit \
  --tx-file $TX_SIGNED \
  --testnet-magic $TESTNET_MAGIC_NUM

Transaction successfully submitted

Wait for the transaction to propagate through the network, and query the script address to see the locked UTxO(s).

First thing we should test is returning the UTxO(s) back to wallet 1. For that we use the following transaction:

> PARAMS=$(mktemp) # most recent protocol params
> cardano-cli query protocol-parameters --testnet-magic $TESTNET_MAGIC_NUM > $PARAMS

> TX_BODY=$(mktemp)
> cardano-cli transaction build \
  --tx-in <fee-utxo> \ # used for tx fee
  --tx-in <script-utxo \
  --tx-in-datum-file $DATUM \
  --tx-in-redeemer-value <arbitrary-redeemer-data> \
  --tx-in-script-file /data/scripts/time-lock.json \
  --tx-in-collateral <fee-utxo> \ # used for script collateral
  --invalid-before <current-slot-no> \
  --required-signer /data/wallets/wallet1.skey \
  --change-address $(cat /data/wallets/wallet1.addr) \
  --tx-out $(cat /data/wallets/wallet1.addr)+2000000 \
  --out-file $TX_BODY \
  --testnet-magic $TESTNET_MAGIC_NUM \
  --protocol-params-file $PARAMS \
  --babbage-era

Estimated transaction fee: Lovelace ...

> TX_SIGNED=$(mktemp)
> cardano-cli transaction sign \
  --tx-body-file $TX_BODY \
  --signing-key-file /data/wallets/wallet1.skey \
  --testnet-magic $TESTNET_MAGIC_NUM \
  --out-file $TX_SIGNED

> cardano-cli transaction submit \
  --tx-file $TX_SIGNED \
  --testnet-magic $TESTNET_MAGIC_NUM

Transaction successfully submitted

Note that this transaction build command differs slightly from the Always succeeds script:

  • --invalid-before <current-slot-no> is needed so the transaction is aware of the current time (via the start of the valid time-range). It might seem weird to specify (an approximation of) the current time at this point, as someone might try to cheat the time-lock by specifying a time far into the future. But the slot-leader checks the time-range as well, and rejects any transaction whose time-range doesn't contain the current slot.
  • --required-signer <wallet-private-key-file> is needed so that getTxSignatories(tx) doesn't return an empty list.

The second thing we must test is claiming the time-locked funds from another wallet (eg. wallet 2). Let's assume that the time-lock script still contains the 2 tAda sent by wallet 1, and that sufficient time has passed. Wallet 2 can claim the UTxO(s) using the following commands:

> PARAMS=$(mktemp) # most recent protocol params
> cardano-cli query protocol-parameters --testnet-magic $TESTNET_MAGIC_NUM > $PARAMS

> TX_BODY=$(mktemp)
> cardano-cli transaction build \
  --tx-in <fee-utxo> \ # used for tx fee
  --tx-in <script-utxo> \
  --tx-in-datum-file $DATUM \
  --tx-in-redeemer-value <arbitrary-redeemer-data> \
  --tx-in-script-file /data/scripts/time-lock.json \
  --tx-in-collateral <fee-utxo> \ # used for script collateral
  --invalid-before <current-slot-no> \
  --change-address $(cat /data/wallets/wallet2.addr) \
  --tx-out $(cat /data/wallets/wallet2.addr)+2000000 \
  --out-file $TX_BODY \
  --testnet-magic $TESTNET_MAGIC_NUM \
  --protocol-params-file $PARAMS \
  --babbage-era

Estimated transaction fee: Lovelace ...

> TX_SIGNED=$(mktemp)
> cardano-cli transaction sign \
  --tx-body-file $TX_BODY \
  --signing-key-file /data/wallets/wallet2.skey \
  --testnet-magic $TESTNET_MAGIC_NUM \
  --out-file $TX_SIGNED

> cardano-cli transaction submit \
  --tx-file $TX_SIGNED \
  --testnet-magic $TESTNET_MAGIC_NUM

Transaction successfully submitted

cardano-cli should give an error if you try to submit this transaction before the lockUntil time. After that time it should succeed, and wallet 2 will receive the time-locked UTxO(s).

Further reading

This chapter covers integrations, minting policies, exploits, compiler internals, some more complex scripts, and some recommendations for building dApps.

Still a work in progress...

Further reading/

Integrations

Further reading/ Integrations/

Different versions of Helios for on-chain vs. off-chain

If you have already launched your dApp to mainnet, and want to keep using exactly the same script hashes while also benefiting from improvements to the Helios off-chain API, you can install a second version of Helios alongside the version you want to keep using for compiling on-chain code.

Note: the Helios Webpack loader requires the version of the library you want to use for compiling on-chain code to be installed as "@hyperionbt/helios"

To install the latest version of Helios alongside the old verion, you must use an alias:

npm install helios-api@npm:@hyperionbt/helios

Alternatively you can also install a specific version of Helios using an alias:

npm install helios-api@npm:@hyperionbt/helios@^0.13.33

You can then import this aliased version of Helios in your Javascript/Typescript project:

import { UplcProgram } from "helios-api"

...

Transfering UplcProgram instances

In order to properly use an UplcProgram instance compiled by an older version of Helios you must transfer it (which ensures the script hash stays the same).

// old version of Helios used to compile the contract
import { Program } from "@hyperionbt/helios" 

// newest version of Helios
import { UplcProgram } from "helios-api" 

const src = `spending ...`

const uplcProgram = Program.new(src).compile(true).transfer(UplcProgram)

The transfer() method also transfers the code mapping wrt. the original Helios code.

The transfer() method is only available in versions of Helios >= v0.13.32.

Older versions of Helios

For versions of Helios <= v0.13.31 transfering can be achieved by serializing/deserializing the UplcProgram instance.

// old version of Helios used to compile the contract
import { Program } from "@hyperionbt/helios"

// newest version of Helios
import { UplcProgram } from "helios-api"

const src = `spending ...`

const uplcProgram = Program.new(src).compile(true)

const transferedUplcProgram = UplcProgram.fromCbor(uplcProgram.toCbor())

Further reading/ Integrations/

VSCode plugin

This plugin can be installed from within VSCode by searching for Helios and picking the plugin with the following caption: Helios language support for VS Code.

Currently this plugin only provides syntax highlighting for files ending with the .hl extension.

Contributing

The Helios IDE plugins repository can be found on github.

Third party language server

There is also a third party language server plugin with more advanced features like auto-complete (Helios versions <= 0.9 only). This plugin requires separate installation of the python language server. This plugin can be found within VSCode by searching for Helios Language Server.

Further reading/ Integrations/

Webpack loader

The Helios Webpack loader allows importing Helios scripts directly into Javascript/Typescript projects.

Features:

  • Catches Helios syntax and type errors during build time
  • Working with Helios sources directly allows using Helios IDE plugins
  • Automatically uses your current version of Helios (must be installed manually inside the repo where you configure webpack)
  • WiP: generates Typescript declarations for user-defined Helios types (Typescript declaration files are emitted inside the source directory)

Note: the Helios import syntax must use literal string relative paths instead of module names.

Example

A Helios module:

// common.hl
module common

struct Datum {
    secret: Int
}

struct Redeemer {
    guess: Int
}

A Helios validator:

// contract.hl
spending contract 

import { Datum, Redeemer } from "./common.hl"

func main(datum: Datum, redeemer: Redeemer, _) -> Bool {
    datum.secret == redeemer.guess
}

Typescript off-chain code:

// index.ts
import Program from "./contract.hl"

const program = new Program()

const uplcProgram = program.compile(true)

...

The imported Program has the same methods as helios.Program.

Installation and configuration

Install the loader:

npm install --save-dev @hyperionbt/helios-loader

Configure Webpack, for example:

// webpack.config.js
module.exports = {
	mode: "development",
	entry: "./index.ts",
	output: {
		path: __dirname + "/dist/"
	},
	module: {
		rules: [
		  	{
				test: /(?<!\.d)\.(ts|tsx)$/,
				exclude: /node_modules/,
				resolve: {
			  		extensions: [".ts", ".tsx"],
				},
				use: [
					"ts-loader",
                    // helios-loader AFTER ts-loader so it is able to 
                    //  import Helios scripts BEFORE ts-loader is called
					"@hyperionbt/helios-loader" 
				]
		  	},
			{
				test: /\.(hl|helios)$/,
				exclude: /node_modules/,
				use: [
					{
						loader: "@hyperionbt/helios-loader",
						options: {
                            // must be true when importing Helios scripts in Typescript
							emitTypes: true 
						}
					}
				]
			}
		]
	}
}

Contributing

The Helios Webpack loader repository can be found on github.

Further reading/

Exploits

Double satisfaction

If a smart contract simply checks that a given value is sent to an address, then that condition could be satisfied in another smart contract at the same time. The output is only sent once, but the condition is thus satisfied multiple times in the same transaction.

This can be avoided by enforcing that the output value is sent to the given address with a given datum tag.

Further reading/

Intermediate representation

Helios scripts aren't compiled directly to UPLC. Rather they are compiled into an Intermediate Representation (IR). This section describes the components of the IR and how the simplification process works. This can be useful information for auditors of the Helios code-base.

The Helios IR is a typeless variant of Helios, where high-level syntactic constructs have been replaced by low-level equivalents (represented a class hierarchy with IRExpr as a base class):

  • IRNameExpr
  • IRLiteralExpr
  • IRConstExpr
  • IRFuncExpr
  • IRCallExpr
    • IRCoreCallExpr
    • IRUserCallExpr
      • IRAnonCallExpr
        • IRFuncDefExpr
      • IRNestedAnonCallExpr
  • IRErrorCallExpr

The remaining part of this page describes the IR syntax.

IRNameExpr

Any word matching of the regular expression [_a-zA-Z][_a-zA-Z0-9]*, except the following keywords: const, error, true, false.

IRLiteralExpr

  • true or false for a literal Bool
  • ##[0-9a-f]* for literal Data
  • #[0-9a-f]* for a literal ByteArray
  • ".*" for a literal String
  • [0-9]+ for a literal Int

IRConstExpr

Emitted by Helios const statements.

const(<expr>)

IRFuncExpr

(<arg-name>, <arg-name>, ...) -> {
    <body-expr>
}

IRCallExpr

IRCoreCallExpr

__core__<builtin-name>(<arg-expr>, <arg-expr>, ...)

IRUserCallExpr

<expr>(<arg-expr>, <arg-expr>, ...)

IRAnonCallExpr

(<arg-name>, <arg-name>, ...) -> {
    <body-expr>
}(<arg-expr>, <arg-expr>, ...)

IRNestedAnonCallExpr

(<arg-name>, <arg-name>, ...) -> {
    <body-expr>
}(<arg-expr>, <arg-expr>, ...)(<call-arg-expr>, ...)

IRFuncDefExpr

(<fn-name>) -> {
    <rest-expr>
}(
    (<arg-name>, <arg-name>, ...) -> {
        <body-expr>
    }
)

IRErrorCallExpr

error(".*")

Further reading/ Intermediate representation/

IR simplication

Simplification of a compiled program is done at the IR level because it provides more context.

Simplification consists of the following steps:

  1. Evaluation of constants
  2. Simplify literals
  • Inline literals
  • Evaluate core calls with only literal args
  1. Simplify topology
  • Count all references
  • Inline definitions
  • Remove unused definitions
  • Combine nested functions
  • Eliminate cast/uncast function call combinations

Evaluation of constants

This is step is always performed (i.e. regardless of the value of simplify when calling compile()).

This step starts at the root of the syntax tree by calling evalConstants(), which is called recursively until IRConstExpr instances are found. A IRCallStack is filled with definitions in the process. IRConstExpr calls eval() recursively instead.

Note that all definitions must be added as deferred IRValue instances to the stack by IRAnonCallExpr, as they might be needed by inner IRConstExpr instances.

Simplify literals

Next we inline all literal arguments defined in higher scopes. Any IRCoreCallExpr instances with only literal arguments are also evaluated.

A single method is defined on IRExpr for this step: simplifyLiterals(map: Map<IRVariable, IRLiteralExpr>). The literals arguments of IRCallExpr must be simplified before the algorithm goes deeper in the AST. The literal arguments of IRAnonCallExpr are the ones that are inserted in the map passed to simplifyLiterals.

Many builtin functions (e.g. ifThenElse) can already be simplified if only some of the args are literals.

Simplify topology

Before starting this step, all references of each IRVariable must be registered.

Inline definitions

Care needs to be taken not to inline wherever there is recursion (i.e. loops).

Note: IRNameExpr instances can always be inlined.

Remove unused definitions

This is done inside IRAnonCallExpr instances.

Combine nested functions functions

(outer) -> {
  (inner) -> {
    ...
  }
}(a)(b)

Should be simplified to:

(outer, inner) -> {
  ...
}(a, b)

This is done inside IRNestedAnonCallExpr instances.

Further reading/

Minting native assets

One of Cardano's best features is supporting native multi-assets. These are user-created tokens on Cardano that have the same treatment as the native coin (Ada).

This might not seem like a big deal but this offers serious advantages over Ethereum tokens (ERC-20 and ERC-721). But to understand the benefits you have to understand how user-defined tokens work on non-UTxO blockchains.

ERC-20 Standard

On Ethereum, tokens are defined using the ERC-20 standard. In this standard tokens are managed by a contract that stores all of the token's metadata and all user balances in a mapping (hashmap) called _balances. All transfers of an ERC-20 token are function calls to the contract to modify the _balances.

Any error in the implementation of the ERC-20 standard can lead to the loss of user funds.

UTxO Native Assets

On Cardano and other eUTxO blockchains user-defined tokens are first-class. Tokens on Cardano are stored in token bundles which can contain Ada and any native asset. This allows Cardano to do in one transaction what would normally take multiple contract calls on Ethereum.

Note: A token bundle must always contain a minimum amount of Ada.

Minting Policies

Minting policies are a lot like spending scripts. These policies validate attempts to mint or burn a tokens of that policy.

There are a few key differences wrt. spending scripts:

  • Minting policies are not directly linked to any UTxO they are included in the minting transaction directly.
  • Minting policies take two arguments (the ScriptContext and the Redeemer), they have no input UTxO and therefore no Datum.

AssetClass

Native assets are identified by their AssetClass this is a combination of:

  • a MintingPolicyHash: the hash of the minting policy of the token. Sometimes referred to as the CurrencySymbol or the PolicyID.

  • a token name: this is used to distinguish different assets within the same policy (e.g. multiple NFTs using the same minting policy)

Note: The MintingPolicyHash of ADA is an empty ByteArray (#). Since nothing can hash to an empty string Ada is the only token that can't be minted/burned using a minting policy.

Further reading/ Minting native assets/

Signature based minting

This example shows a simple minting policy that allows minting tokens as long as the transaction is signed by an owner. The owner has a given PubKeyHash.

minting signed

const OWNER: PubKeyHash = PubKeyHash::new(#26372...)

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

Further reading/ Minting native assets/

Unique minting

NFTs (Non-Fungible tokens) are tokens resulting from a unique minting event. To make an NFT the minting policy must make sure that that policy can only be used once and that only one token can ever be minted. The token name for the NFT in this example will be called example_nft. Usually the amount of each token is restricted to 1.

There are two approaches for these kind of minting policies:

  • Deadline-based Approach
  • UTxO-based Approach

Deadline-based Approach

NFTs were available on Cardano before smart contracts (Mary Hardfork) and they were implemented using deadlines. The main idea is that the token can only be minted before a deadline which already passed. This ensures no new tokens will ever be minted. This is very easy to implement:

minting deadline_nft

const DEADLINE: Time = Time::new(1661665196132) // milliseconds since 1970


func main(_, ctx: ScriptContext) -> Bool {
	tx: Tx = ctx.tx;

    nft_assetclass: AssetClass = AssetClass::new(
		ctx.get_current_minting_policy_hash(),
		"example-nft".encode_utf8()
	);

    value_minted: Value = tx.minted;

    value_minted == Value::new(nft_assetclass, 1) && tx.time_range.start < DEADLINE
}

UTxO-Based Approach

This method is based on an example in the Plutus Pioneer Program. This approach takes advantage of the fact that all UTxOs have a unique TxOutputId. A UTxO's TxOutputId is made up of the transaction hash of the transaction that made the UTxO and the index of the UTxO in the outputs of that transaction. It's a builtin type that is defined as:

struct TxOutputId {
    tx_id: TxId
    index: Int
}

So with this approach, we specify in the minting policy that the transaction minting the NFT must spend a UTxO with a specific output ID. Since a UTxO can only be spent once this means the token can only be minted once.

minting utxo_nft

const OUTPUT_ID: TxOutputId = TxOutputId::new(TxId::new(#1213), 1)

func main(_, ctx: ScriptContext) -> Bool {
	tx: Tx = ctx.tx;

    nft_assetclass: AssetClass = AssetClass::new(
		ctx.get_current_minting_policy_hash(),
		"example-nft".encode_utf8()
	);

    value_minted: Value = tx.minted;

    value_minted == Value::new(nft_assetclass, 1) &&
    tx.inputs
        .any((input: TxInput) -> Bool {input.output_id == OUTPUT_ID})

}

Further reading/

Vesting contract

To put what we've done so far to use we're going to build a simple 'vesting' contract. This contract will lock up some tokens owned by an owner for a beneficiary that can't be claimed until after a deadline. The owner can get their funds back if the deadline has not passed yet

Datum

The datum stores the PubKeyHash of the beneficiary and creator's wallets and the vesting deadline is represented as a Time.

struct Datum {
    creator: PubKeyHash
    beneficiary: PubKeyHash
    deadline: Time
}

Note: The Time type represents a POSIX time and for more info Helios Builtins.

Redeemer

enum Redeemer {
    Cancel
    Claim
}

There are two cases when the validator should return true:

  • Cancel

    In this case, the 'owner' wishes to cancel the contract and get back their funds. For a 'Cancel' to succeed the following have to be checked

    • The owner signed the transaction.
    • The deadline hasn't passed.
  • Vesting Claim

    A 'Claim' occurs when the 'beneficiary' wishes to claim the tokens vested for them. For it to be valid the following have to be checked:

    • The beneficiary signed the transaction.
    • The deadline has passed.

main

func main(datum: Datum, redeemer: Redeemer, context: ScriptContext) -> Bool {
    tx: Tx = context.tx;
    now: Time = tx.time_range.start;

    redeemer.switch {
        Cancel => {
            // Check that deadline hasn't passed
            now < datum.deadline && 

            // Check that the owner signed the transaction
            tx.is_signed_by(datum.creator)
        },
        Claim => {
           // Check that deadline has passed.
           now > datum.deadline &&

           // Check that the beneficiary signed the transaction.
           tx.is_signed_by(datum.beneficiary)
        }
    }
}

Complete code

spending vesting

struct Datum {
    creator: PubKeyHash
    beneficiary: PubKeyHash
    deadline: Time
}

enum Redeemer {
    Cancel
    Claim
}

func main(datum: Datum, redeemer: Redeemer, context: ScriptContext) -> Bool {
    tx: Tx = context.tx;
    now: Time = tx.time_range.start;

    redeemer.switch {
        Cancel => {
            now < datum.deadline &&
            tx.is_signed_by(datum.creator)
        },
        Claim => {
           now > datum.deadline &&
           tx.is_signed_by(datum.beneficiary)
        }
    }
}

Further reading/

English auction

In this example, we will rewrite the English auction contract from the Plutus Pioneer's program in Helios.

This validator can be used to lock assets that are to be auctioned in a UTxO.

main

spending english_auction

struct Datum {
    seller:         PubKeyHash
    bid_asset:      AssetClass     // allow alternative assets (not just lovelace)
    min_bid:        Int
    deadline:       Time
    for_sale:       Value          // the asset that is being auctioned
    highest_bid:    Int            // initialized at 0, which signifies the auction doesn't yet have valid bids
    highest_bidder: PubKeyHash

    func update(self, highest_bid: Int, highest_bidder: PubKeyHash) -> Datum {
        self.copy(highest_bid: highest_bid, highest_bigger: highest_bidder)
    }
}

enum Redeemer {
    Close 
    Bid {
        bidder: PubKeyHash
        bid: Int
    }
}

func main(datum: Datum, redeemer: Redeemer, ctx: ScriptContext) -> Bool {
    tx: Tx = ctx.tx;

    now: Time = tx.time_range.start;

    validator_hash: ValidatorHash = ctx.get_current_validator_hash();

    redeemer.switch {
        Close => {
            if (datum.highest_bid < datum.min_bid) {
                // the forSale asset must return to the seller, what happens to any erroneous bid value is irrelevant
                tx
                  .value_sent_to(datum.seller)
                  .contains(datum.for_sale + datum.highest_bid) &&
                // Check that the deadline has passed
                now > datum.deadline                                    
            } else {
                // Check that the seller receives the highest bid
                tx
                  .value_sent_to(datum.seller)
                  .contains(Value::new(datum.bid_asset, datum.highest_bid))    &&
                // Check that highest bidder is given the token being auctioned
                tx
                  .value_sent_to(datum.highest_bidder)
                  .contains(datum.for_sale)                                    &&
                // Check that the deadline has passed
                now > datum.deadline                                    
            }
        },
        b: Bid => {
            if (b.bid < datum.min_bid) {
                false
            } else if (b.bid <= datum.highest_bid) {
                false
            } else {
                // first bid is placed by the auction creator
                expected_datum: Datum = datum.update(b.bid, b.bidder);

                // Check that new Auction UTxO contains the token for sale and the new bid
                tx
                  .value_locked_by_datum(validator_hash, expected_datum)
                  .contains(datum.for_sale + Value::new(datum.bid_asset, b.bid)) &&
                // Check that the old highest bidder is repayed
                tx
                  .value_sent_to(datum.highest_bidder)
                  .contains(Value::new(datum.bid_asset, datum.highest_bid))      &&
                // Check that the deadline hasn't passed
                now < datum.deadline
            }
        }
    }
}

Further reading/

Oracle pools (WiP)

Oracles post information on the blockchain periodically (eg. the ADA/USD exchange rate), and thanks to the recent Vasil upgrade it has become easier to use that information in smart contracts (eg. stable-coin contracts).

Of course relying on a single centralized oracle goes against the spirit of cryptocurrencies and blockchain technology, so oracles should be grouped in pools. An oracle pool is essentially a smart contract which periodically groups inputs from all participating oracles into a single UTxO. The participating oracles are also rewarded from the oracle pool contract.

A more complete description of oracle pools can be found (here)[https://github.com/Emurgo/Emurgo-Research/blob/master/oracles/Oracle-Pools.md].

Oracle pool design decisions

Membership

The first question we need to answer is who can be a member of the pool:

  1. new members can be voted in by existed members, malicious members can be voted out
  2. member performance is measured on-chain, and only the best performing X oracles can claim rewards, in case of a draw seniority wins, X can be changed by voting
  3. token-based membership

Of course the concept of individual 'members' doesn't really apply to an anonymous blockchain, as a single physical actor can control multiple memberships.

Membership based purely on voting allows the founder(s) to keep exerting strong control over the oracle pool. Initial membership distribution is also entirely obscured from the public. So closed or limited membership is probably a bad idea from a decentralization perspective.

Entry into the pool based on performance is essentially a time and resource intensive method of acquiring membership. Existing members will vote to keep the max number of members low, in order maximize individual rewards. To avoid that the max number of members might need to be fixed via the contract, but that way the contract loses a lot of flexibility.

Token-based membership is vulnerable to a 51% attack. An attacker could quietly acquire the majority of tokens. Any subsequent attack would instantly destroy all smart contracts relying on the oracle. Because oracle pools are expected to be critical infrastructure for DeFi on Cardano, such an attack must of course be avoided at all costs. So that means initial token distribution must be spread very well, for which several rounds of ISPOs can be used. There also needs to be high enough oracle operation reward, so the tokens are effectively staked and aren't floating around on exchanges.

Note that oracle pools with open membership are also vulnerable to 51% attacks, but that such attacks are made more difficult by the time-delay of requiring the membership.

For this example we will choose a token-based membership. So the first task will be minting the tokens (see (how-to guide to mintin)[tutorial_06-minting_policy_scripts.md]).

Data-point collection

Data-point submission happens in three phases.

An active oracle must own some oracle tokens. Every posting period it calculates the data-point and sends a UTxO into the oracle pool contract. The data-point is described in a conventional hash, along with salt. The posting UTxO must also contain the oracle tokens and sufficient collateral.

In a second phase each participating oracle resends the UTxO into the oracle pool contract, while adding a provable time-stamp to the datum.

In the last phase the datum is 'unhidden' by resending the UTxO into the oracle pool contract with an inline-datum. At this point the script can check if sufficient time has passed since unhiding. The 'unhidden' UTxO must also be registered in a special registration UTxO (of which there can be multiple for parallel posting).

Note that data-point submission also contains governance parameters.

Data-point aggregation

This is the most complex transaction of the oracle pool contract.

This transaction can be submitted after a predefined period after the first entry in one of the registration UTxOs.

In this transaction all 'unhidden' UTxOs, with a time-stamp lying in the correct range, are used to resend the data carrying UTxO into the script contract with the new data-point (inline-datum of course). The submitting oracle must use all the 'unhidden' UTxOs that have been registered in the registration UTxOs. A token-weighted median of the data-point is calculated. Any oracles that lie within a predefined range of the median receive rewards according to how many oracle tokens they own (the submitting transaction gets double the rewards). Any oracles that lie outside the predefined range lose their collateral to the contract. The registration UTxOs are emptied, and the oracle tokens/left-over collateral is sent back to the owners.

The uniqueness of each input UTxO datum must also be checked. Two or more UTxOs with the same datum are obviously colluding (they would've had to have picked the same salt) and lose their collateral.

The final data-point UTxO can also contain governance parameters, which are updated if there is a sufficient majority. One of these parameters is the number of registration UTxOs, for which additional ones need to be minted if the number increases, and superfluous ones need to burned if the number decreases.

The final data-point UTxO must be marked by a unique data-NFT.

Minting

The oracle pool described above requires minting 3 different kinds of tokens:

  1. oracle pool membership tokens (unique minting)
  2. a single data NFT (unique minting)
  3. registration NFT (non-unique minting/burning)

Governance parameters

  • submissionPeriod Duration (period in which the first two phases of data submission must be completed, unhiding must happen after this period)
  • unhidingPeriod Duration (period in which data-point UTxOs are unhidden and registered in registration UTxOs)
  • nRegistrationQueues Integer (number of registration UTxOs)
  • collateralPerMembershipToken Integer (collateral asset will probably be ADA)
  • validDataRange Integer (+- around the median, could be in 'points', so '1' is 1%)
  • governanceQuorum Integer (could be '75' for 75%)
  • postRewardForWholePool Integer (postReward asset will probably be ADA)
  • extraRewardForPoster Integer (could be '100' for 100% extra i.e. x2)

The datum of the data-point UTxO will contain the governance parameters and the data-point itself:

  • dataPoint Integer

This could be extended to multiple data-points at some, although makes (dis)incentives more difficult to calulate.

Other datums

Registration UTxO datum:

  • inputs []TxOutputId

Submission UTxO datum:

  • owner PubKeyHash
  • salt Integer
  • dataPoint Integer
  • all the governance parameters

The sometimes vastly differing datum types probably made it worthwhile to introduce union types:

enum Datum {
    Post {
        dataPoint: Integer,
        govParams: GovernanceParams
    }, 
    Submit {
        owner:     PubKeyHash,
        salt:      Integer,
        dataPoint: Integer,
        time:      Time,
        govParams: GovernanceParams
    },
    Queue {
        inputs: []TxOutputId
    }
}

Data constructors must have a unique order, and can only be used in a single union. The data constructor type can be referenced using the :: symbol (eg. Datum::Post).

Further reading/

dApp recommendations

No build tools

A lot of care went into making the Helios library as auditable as possible. Therefore we recommend for your dApp to use the library in its unminified form so users can audit the compiler more easily.

We also recommened using an client-side UI framework (like Preact/Htm), so that your dApp can be served directly to the client without needing a build-step.

Show contract button

The smart contracts used in the dApp should be viewable by the user.

Further reading/

Tx finalization

The Helios API can be used to build transactions. Finalization consist of the following steps:

  1. balancing of non-ADA assets
  2. calculation of script execution units (using a dummy fee set to the maximum possible value)
  3. setting collateral inputs and collateral output (using total execution budget calculated in previous step)
  4. iteratively calculate the min fee for the transaction and balance the lovelace