5.6.1 Java  Script
On this page:
stdlib Guarantees loader.mjs
canonicalize  Connector  Mode
get  Connector  Mode
get  Connector Standard Library
new  Account  From  Mnemonic
new  Test  Account
connect  Account
network  Account
get  Info
balance  Of
get  Network  Time
wait  Until  Time
wait Utilities
T_  Null
T_  Bool
T_  UInt256
T_  Bytes
T_  Address
T_  Array
T_  Tuple
T_  Object
Array_  set
big  Numberify
is  Big  Number
to  Hex
is  Hex
hex  To  String
hex  To  Big  Number
big  Number  To  Hex
uint256To  Bytes
bytes  Eq
random  UInt256
lt ETH.mjs
to  Wei
from  Wei
to  Wei  Big  Number ask.mjs
5.6.1 JavaScript

The Reach JavaScript backend produces a compilation output named "input.export.mjs" which exports an asynchronous function for each participant. This will normally be imported by writing:

import * as backend from './build/index.main.mjs';

Each function accepts three arguments: stdlib, ctc, and interact. These functions should be called by the frontend. For example, if a Reach program contains a participant named 'A' in the argument to Reach.App, then the JavaScript backend will include a function named A.

The stdlib argument is provided by either
  • the module @reach-sh/stdlib/ETH.mjs;

  • the module @reach-sh/stdlib/ALGO.mjs;

  • the module @reach-sh/stdlib/FAKE.mjs; or,

  • the async function loadStdlib from @reach-sh/stdlib/loader.mjs.

The ctc argument is the result of a call to acc.deploy or acc.attach.

The interact argument is an object matching the participant interact interface for the corresponding participant.

The JavaScript backend also provides an export named _version, which is a string representation of the Reach version used to compile the program. For example, the version of Reach used to produce this documentation would contain the string '0.1.2'.

Finally, the backend will provide an export named _Connectors, which is an opaque object representing the connectors this app was compiled to. Guarantees

This backend does not guarantee that values in a positive position in a participant interact interface, that are later passed to a negative position in a participant interact interface, will be identical, in the sense of JavaScript’s === operator, to the original value. In other words, this backend does not ensure that Reach programs are parametric over JavaScript values that they interact with.

Positive and negative are best understood by example with a function type: a positive position is supplied by the function, such as the result; while a negative position is supplied by the caller, such as the arguments. These notions generalize, however, to higher (and lower) order contexts. In the case of Reach, this means that non-function values in a participant interact interface are positive.

For example, if the Reach program,

 [["A", { get: Bytes, give: Fun([Bytes], Bool) }]],
 (A) => {
  A.only(() => {
   const x = interact.give(interact.get); });
  commit(); }); 

is given the interact object,

const x = "A string";
{ get: x,
  give: (str) => x === str } 

then it is not guaranteed that A will publish true, because the str given to give may not be identical to x. (However, they are bytesEq.) loader.mjs

The loader.mjs module exports the following functions that might help you write code that is portable to multiple consensus networks.

canonicalizeConnectorMode(string) => string

Expands a connector mode prefix to its full, canonical name. The canonical connector modes are:

'ETH-test-dockerized-geth'   // Default for ETH, ETH-test, and ETH-test-dockerized
'ETH-test-embedded-ganache'  // Default for ETH-test-embedded
'FAKE-test-embedded-mock'    // Default for FAKE, FAKE-test, and FAKE-test-embedded
'ALGO-test-dockerized-algod' // Default for ALGO, ALGO-test, and ALGO-test-dockerized

getConnectorMode() => string

Returns the canonicalized connector mode, based on the process.env.REACH_CONNECTOR_MODE environment variable. If the variable is missing or empty, it will return the canonicalized form of 'ETH'.

getConnector() => string

Returns the first piece of getConnectorMode(), which indicates the abbreviated name of the network being connected to. Connectors are one of the following: ['ETH', 'FAKE', 'ALGO'].

async loadStdlib(connectorMode) => stdlib

Returns a stlib based on the provided connectorMode string. You may omit the connectorMode argument, in which case getConnectorMode() will be used to select the correct stdlib. Standard Library

The stdlib modules export the following functions that might be used in this frontend:

async newAccountFromMnemonic() => acc 

Returns a Reach account abstraction for an account on the consensus network specified by the given mnemonic phrase. The details of the mnemonic phrase encoding are specified uniquely to the consensus network.

async newTestAccount(balance) => acc 

Returns a Reach account abstraction for a new account on the consensus network with a given balance of network tokens. This can only be used in private testing scenarios, as it uses a private faucet to issue network tokens.

async connectAccount(networkAccount) => acc 

Returns a Reach account abstraction for an existing account for the consensus network based on the connector-specific account specification provided by the networkAccount argument.

// network => networkAccount type
ETH        => ethers.Wallet
ALGO       => {addr: string, sk: UInt8Array(64)}

acc.networkAccount => networkAccount 

Returns the connector-specific account specification of a Reach account abstraction.

async acc.deploy(bin) => ctc 

Returns a Reach contract abstraction after deploying a Reach DApp contract based on the bin argument provided. This bin argument is the "input.mjs" module produced by the JavaScript backend.

async ctc.getInfo() => ctcInfo 

Returns an object that may be given to attach to construct a Reach contract abstraction representing this contract. This object may be stringified with JSON.stringify for printing and parsed again with JSON.parse without any loss of information.

async acc.attach(bin, ctcInfo) => ctc 

Returns a Reach contract abstraction based on a deployed Reach DApp contract provided in the ctcInfo argument and the bin argument. This bin argument is the "input.mjs" module produced by the JavaScript backend.

For convenience, if ctcInfo is an object with a getInfo method, it is called to extract the information; this means that the result of deploy is allowed as a valid input.

async balanceOf(acc) => amount 

Returns the balance of network tokens held by the account given by a Reach account abstraction provided by the acc argument.

async transfer(from:acc, to:acc, amount:BigNumber) => void 

Transfers amount network tokens from from to to, which are accounts, such as those returned by connectAccount.

async getNetworkTime() => time

Gets the current consensus network time. For ETH, ALGO, and FAKE, this is the current block number, represented as a BigNumber.

async waitUntilTime(time, onProgress)

Waits until the specified consensus network time. In isolated testing modes, which are REACH_CONNECTOR_MODEs $NET-test-dockerized-$IMPL and $NET-test-embedded-$IMPL for all valid $NET and $IMPL, this will also force time to pass on the network, usually by sending trivial transactions.

You may provide an optional onProgress callback, used for reporting progress, which may be called many times up until the specified time. It will receive an object with keys currentTime and targetTime,

async wait(timedelta, onProgress)

A convenience function for delaying by a certain time delta. The expression await wait(delta, onProgress) is the same as await waitUntilTime(add(await getNetworkTime(), delta), onProgress). Utilities

protect(t x) => x 

Asserts that value x has Reach type t. An exception is thrown if this is not the case.

T_Null => ReachType
T_Bool => ReachType
T_UInt256 => ReachType
T_Bytes => ReachType
T_Address => ReachType
T_Array(ReachType, number) => ReachType
T_Tuple([ReachType ...]) => ReachType
T_Object({Key: ReachType ...}) => ReachType
T_Data({Variant: ReachType ...}) => ReachType

Each of these represent the corresponding Reach type. See the table below for Reach types and their corresponding JavaScript representation:

// Reach  => JavaScript
Null      => null
Bool      => 'boolean'
UInt256   => 'BigNumber' or 'number'
Bytes     => 'string'
Address   => 'string'
Array     => array
Tuple     => array
Object    => object
Data      => ['variant', value] 

For example, the Reach type MInt = Data({None: Null, Some: UInt256}) inhabitant MInt.Some(42) is represented as ['Some', 42] in JavaScript.


Throws an exception if not given true.

Array_set(arr, idx, val) 

Returns a new array identical to arr, except that index idx is val.

bigNumberify(x) => uint256
isBigNumber(x) => bool

bigNumberify converts a JavaScript number to a BigNumber, the JavaScript representation of Reach’s uint256. isBigNumber checks if its input is a BigNumber.

toHex(x) => bytes
isHex(x) => bool
hexToString(bytes) => string
hexToBigNumber(bytes) => uint256
bigNumberToHex(uint256) => bytes
uint256ToBytes(uint256) => bytes
bytesEq(bytes, bytes) => bool 

These are additional conversion and comparison utilities.

keccak256(x) => uint256

Hashes the value.

randomUInt256() => uint256

Creates 256 random bits as a uint256.


A value suitable for use as a participant interact interface requiring a random function.

add(uint256, uint256) => uint256
sub(uint256, uint256) => uint256
mod(uint256, uint256) => uint256
mul(uint256, uint256) => uint256
div(uint256, uint256) => uint256 

Integer arithmetic on uint256.

eq(uint256, uint256) => bool
ge(uint256, uint256) => bool
gt(uint256, uint256) => bool
le(uint256, uint256) => bool
lt(uint256, uint256) => bool

Integer comparisons on uint256. ETH.mjs

The following exports are defined only in the Ethereum standard library.

toWei(ether) => wei
fromWei(wei) => ether
toWeiBigNumber(ether) => uint256

The functions convert amounts of Ethereum (ETH) to and from Wei, which is the base unit of Ethereum. ask.mjs

This backend also provides the helper module @reach-sh/stdlib/ask.mjs for constructing console interfaces to your frontends.

import * as ask from '@reach-sh/stdlib/ask.mjs';

It provides the following exports:

async ask(string, (string => result)) => result
yesno(string) => boolean
done() => null

ask is an asynchronous function that asks a question on the console and returns the first result that its second argument does not error on.

yesno is an argument appropriate to give as the second argument to ask that parses "Yes"/"No" answers.

done indicates that no more questions will be asked.