Skip to main content

API Reference - IOTA Client Library - Node.js binding

Node.js binding to the IOTA client library.

Installation#

  • Using NPM:
$ npm i @iota/client
  • Using yarn:
$ yarn add @iota/client

Requirements#

One of the following Node.js version: '10.x', '12.x', '14.x', '15.x', '16.x'

If there is no prebuilt binary available for your system you need Rust and Cargo, to build it yourself. Install them here.

Getting Started#

After you linked the library, you can create a Client instance and interface with it.

const { ClientBuilder } = require('@iota/client')const client = new ClientBuilder()    .node('https://api.lb-0.h.chrysalis-devnet.iota.cafe')    .build()client.getInfo().then(console.log).catch(console.error)

Connecting to a MQTT broker using raw ip doesn't work with TCP. This is a limitation of rustls.

API Reference#

ClientBuilder#

node(url): ClientBuilder#

Adds an IOTA node to the client pool.

ParamTypeDescription
urlstringA node URL

Returns the client builder instance for chained calls.

nodeAuth(url, authOptions): ClientBuilder#

Adds an IOTA node with authentication to the client pool.

ParamTypeDescription
urlstringA node URL
authOptions[NodeAuthOptions](#nodeauthoptions)Options for node authentication

Returns the client builder instance for chained calls.

primaryNode(url, [, authOptions]): ClientBuilder#

Add a node to always connect first to with optional authentication.

ParamTypeDescription
urlstringA node URL
authOptions[NodeAuthOptions](#nodeauthoptions)Options for node authentication

Returns the client builder instance for chained calls.

primaryPowNode(url, [, authOptions]): ClientBuilder#

Add a node to always connect first to when using remote PoW with optional authentication. Will overwrite the primary node for this case.

ParamTypeDescription
urlstringA node URL
authOptions[NodeAuthOptions](#nodeauthoptions)Options for node authentication

Returns the client builder instance for chained calls.

permanode(url, [, authOptions]): ClientBuilder#

Add a permanode.

ParamTypeDescription
urlstringA node URL
authOptions[NodeAuthOptions](#nodeauthoptions)Options for node authentication

Returns the client builder instance for chained calls.

nodes(urls): ClientBuilder#

Adds a list of IOTA nodes to the client pool.

ParamTypeDescription
urlstring[]An array of node URLs

Returns the client builder instance for chained calls.

nodePoolUrls(urls): ClientBuilder#

Adds a list of IOTA nodes from node pool URLs to the client pool.

ParamTypeDescription
urlstring[]An array of node pool URLs

Returns the client builder instance for chained calls.

network(networkName): ClientBuilder#

Set a network to get default nodes for it. Can be "testnet" or "mainnet". Nodes that don't belong to this network are ignored.

ParamTypeDescription
networkNamestringThe network

Returns the client builder instance for chained calls.

quorum(enabled): ClientBuilder#

Defines how many of nodes will be queried at the same time to check for quorum.

ParamTypeDescription
enabledbooleanDefine if quourm should be used or not

Returns the client builder instance for chained calls.

quorumSize(size): ClientBuilder#

Defines how many of nodes will be queried at the same time to check for quorum.

ParamTypeDescription
sizenumberThe number of nodes that will be queried

Returns the client builder instance for chained calls.

quorumThreshold(threshold): ClientBuilder#

Defines the minimum amount of nodes from the quorum pool that need to agree if we want to consider the result true.

ParamTypeDescription
thresholdnumberMinimum amount of nodes

Returns the client builder instance for chained calls.

brokerOptions(options): ClientBuilder#

Sets the options for the MQTT connection with the node.

ParamTypeDescription
options[BrokerOptions](#brokeroptions)The MQTT broker options

Returns the client builder instance for chained calls.

nodeSyncInterval(interval): ClientBuilder#

Sets the node syncing interval.

ParamTypeDescription
intervalnumberThe interval for the node syncing process

Returns the client builder instance for chained calls.

disableNodeSync(): ClientBuilder#

Disables the node syncing process. Every node will be considered healthy and ready to use.

Returns the client builder instance for chained calls.

requestTimeout(timeoutMs): ClientBuilder#

Sets the default HTTP request timeout.

ParamTypeDescription
timeoutnumberThe timeout in milliseconds

Returns the client builder instance for chained calls.

apiTimeout(api, timeoutMs): ClientBuilder#

Sets the HTTP request timeout for the specified API.

ParamTypeDescription
apiGetHealth | GetInfo | GetTips | PostMessage | GetOutput | GetMilestoneThe API to set the request timeout
timeoutnumberThe timeout in milliseconds

Returns the client builder instance for chained calls.

localPow(local): ClientBuilder#

Sets the PoW type.

ParamTypeDescription
localbooleanFlag determining if PoW should be done locally or remotely

Returns the client builder instance for chained calls.

build(): Client#

Builds the client instance.

Returns a Client instance.

Client#

networkInfo(): NetworkInfo#

Gets the cached network info.

Returns a NetworkInfo instance.

subscriber(): TopicSubscriber#

Gets a handle to the MQTT topic subscriber.

Returns a TopicSubscriber instance.

message(): MessageSender#

Initiates the builder to send messages.

Returns a MessageSender instance.

getUnspentAddress(seed): UnspentAddressGetter#

Get a valid unspent address.

ParamTypeDescription
seedstringThe hex-encoded seed to search

Returns a UnspentAddressGetter instance.

getAddresses(seed): AddressGetter#

Find addresses from the seed regardless of their validity.

ParamTypeDescription
seedstringThe hex-encoded seed to search

Returns a AddressGetter instance.

findMessages(indexationKeys, messageIds): Promise<Message[]>#

Finds all messages associated with the given indexation keys and message ids.

ParamTypeDescription
indexationKeysstring[]The list of indexations keys too search
messageIdsstring[]The list of message ids to search

Returns a promise resolving to the list of the found messages.

getBalance(seed: string): BalanceGetter#

Get balance on a given seed and its wallet account index.

ParamTypeDescription
seedstringThe hex-encoded seed to search

Returns a BalanceGetter instance.

getAddressBalances(addresses): Promise<AddressBalance[]>#

Get the balance in iotas for the given addresses.

ParamTypeDescription
addressesstring[]The list of addresses to search

Returns A promise resolving to the list of { address, balance } pairs.

generateMnemonic()#

Returns a random generated Bip39 mnemonic with the English word list.

Returns A String

mnemonicToHexSeed(mnemonic)#

Returns the seed hex encoded.

ParamTypeDescription
mnemonicstringBip39 mnemonic with words from the English word list.

Returns A String

bech32ToHex(bech32)#

Returns a parsed hex String from bech32.

ParamTypeDescription
bech32stringThe address Bech32 string

Returns A String

hexToBech32(hex, bech32_hrp (optional))#

Returns a parsed bech32 String from hex.

ParamTypeDescription
bech32stringThe address Bech32 string
bech32_hrpstringThe Bech32 hrp string

Returns A String

isAddressValid(address: string): boolean#

Checks if a given address is valid.

ParamTypeDescription
addressstringThe address Bech32 string

Returns A boolean.

getMessageId(message: string): boolean#

Returns the message id from a message.

ParamTypeDescription
messagestringThe message id

Returns the message id.

retry(messageId: string): Promise
#

Retries (promotes or reattaches) the message associated with the given id.

ParamTypeDescription
messageIdstringThe id of the message to retry

Returns A promise resolving to the new Message instance.

retryUntilIncluded(messageId: string[, interval: int, maxAttempts: int]): Promise
#

Retries (promotes or reattaches) the message associated with the given id until it's included in the Tangle. Default interval is 5 seconds and max_attempts is 10.

ParamTypeDescription
messageIdstringThe id of the message to retry
[options.interval]intThe interval in seconds in which we retry the message.
[options.maxAttempts]intThe maximum of attempts we retry the message.

Returns the message ids and Message of reattached messages.

consolidateFunds(seed: string, accountIndex: int, startIndex: int, endIndex: int): Promise#

Function to consolidate all funds from a range of addresses to the address with the lowest index in that range

ParamTypeDescription
seedstringThe seed
accountIndexintThe account index.
startIndexintThe lowest address index, funds will be consolidated to this address.
endIndexintThe address index until which funds will be consolidated

Returns the address to which the funds got consolidated, if any were available.

getInfo(): Promise
#

Gets information about the node.

Returns a promise resolving to the NodeInfoWrapper object.

getTips(): Promise<[string, string]>#

Gets two non-lazy tips.

Returns a promise resolving to an array of length 2 containing the message ids of the tips.

postMessage(message): Promise#

Submits a message.

ParamTypeDescription
message[MessageDto](#messagedto)The message to submit

Returns the message identifier.

getMessage(): MessageFinder#

Gets a message from its identifier.

Returns an instance of the MessageFinder for choices of response.

getOutput(outputId): Promise
#

Gets the UTXO outputs associated with the given output id.

ParamTypeDescription
outputIdstringThe id of the output to search

Returns a promise resolving to the associated OutputMetadata.

findOutputs(outputIds, addresses): Promise<OutputMetadata[]>#

Gets the UTXO outputs associated with the given output ids and addresses.

ParamTypeDescription
addressesstring[]The list of addresses to search
outputIdsstring[]The list of output ids to search

Returns a promise resolving to a list of OutputMetadata.

getAddressOutputs(address[, options]): Promise<string[]>#

Gets the UTXO outputs associated with the given address.

ParamTypeDescription
addressstringThe address Bech32 string
[options.includeSpent]booleanWhether the query should include spent outputs or not
[options.outputType]SignatureLockedSingle | SignatureLockedDustAllowanceThe output type filter

Returns a promise resolving to a list of output ids.

getAddressBalance(address): Promise
#

Gets the balance of the given address.

ParamTypeDescription
addressstringThe address Bech32 string

getMilestone(index): Promise
#

Gets the milestone by the given index.

ParamTypeDescription
indexnumberThe index of the milestone

Returns a promise resolving to the MilestoneMetadata.

getMilestoneUtxoChanges(index): Promise
#

Gets the utxo changes by the given milestone index.

ParamTypeDescription
indexnumberThe index of the milestone

Returns a promise resolving to the MilestoneUTXOChanges.

getReceipts(): Promise<Receipts[]>#

Get all receipts.

Returns a promise resolving to the Receipts.

getReceiptsMigratedAt(index): Promise<Receipts[]>#

Get all receipts for a given milestone index

ParamTypeDescription
indexnumberThe index of the milestone

Returns a promise resolving to the Receipts.

getTreasury(): Promise
#

Get the treasury amount.

Returns a promise resolving to the Treasury.

getIncludedMessage(): Promise
#

Get the included message of a transaction.

ParamTypeDescription
indexstringThe id of the transaction

Returns A promise resolving to the new Message instance.

reattach(messageId): Promise
#

Reattaches the message associated with the given id.

ParamTypeDescription
messageIdstringThe id of the message to reattach

Returns A promise resolving to the new Message instance.

promote(messageId): Promise
#

Promotes the message associated with the given id.

ParamTypeDescription
messageIdstringThe id of the message to promote

Returns A promise resolving to the new Message instance.

NetworkInfo#

FieldTypeDescription
networkstringThe network
networkIdnumberThe network hashed
bech32HRPstringBech32 HRP for this network
minPoWScorenumberThe network's minimum score for PoW
localPowbooleanWhether we are using local PoW or not

TopicSubscriber#

Possible topics:

milestones/latestmilestones/confirmed
messagesmessages/referencedmessages/indexation/{index}messages/{messageId}/metadatatransactions/{transactionId}/included-message
outputs/{outputId}
addresses/{address}/outputsaddresses/ed25519/{address}/outputs

topic(topic): TopicSubscriber#

Adds a topic to this manager instance.

ParamTypeDescription
topicstringA MQTT topic

Returns the topic subscriber instance for chained calls.

topics(topic): TopicSubscriber#

Adds a list of topics to this manager instance.

ParamTypeDescription
topicsstring[]An array of MQTT topics

Returns the topic subscriber instance for chained calls.

subscribe(cb): TopicSubscriber#

Subscribe to the provided topics.

ParamTypeDescription
cbfunctionThe topic handler callback in the form of (err, message) => {}

Returns the topic subscriber instance for chained calls.

unsubscribe(cb: Callback): TopicSubscriber#

Unsubscribes from the provided topics.

ParamTypeDescription
cbfunctionA callback executed when the unsubscribe is finished in the form of (err, message) => {}

Returns the topic subscriber instance for chained calls.

MessageSender#

Builder to create and submit messages to the Tangle.

index(index): MessageSender#

Sets the message indexation. This field is required for indexation payloads.

ParamTypeDescription
indexstring | number[] | Uint8ArrayThe indexation

Returns the message submit instance for chained calls.

data(data): MessageSender#

Sets the indexation data.

ParamTypeDescription
datastring | Uint8ArrayThe message's data

Returns the message submit instance for chained calls.

seed(seed): MessageSender#

Sets the transaction account seed. This field is required for transaction payloads.

ParamTypeDescription
seedstringThe hex-encoded seed of the account to spend

Returns the message submit instance for chained calls.

parents(messageId): MessageSender#

Sets 1-8 custom parent message ids.

ParamTypeDescription
messageIdstring[]The parents message ids

Returns the message submit instance for chained calls.

accountIndex(index): MessageSender#

Sets the account index. This field is required for transactions.

ParamTypeDescription
indexnumberThe account index

Returns the message submit instance for chained calls.

input(transactionId, index): MessageSender#

Adds an output to the transaction.

ParamTypeDescription
transactionIdstringThe transaction id
indexnumberThe input index

Returns the message submit instance for chained calls.

inputRange(start, end): MessageSender#

Defines the range in which to search for addresses fro custom inputs.

ParamTypeDescription
startnumberThe start index
endnumberThe end index

Returns the message submit instance for chained calls.

output(address, amount): MessageSender#

Adds an output to the transaction.

ParamTypeDescription
addressstringThe output address
amountnumberThe output amount

Returns the message submit instance for chained calls.

dustAllowanceOutput(address, amount): MessageSender#

Adds a dust allowance output to the transaction.

ParamTypeDescription
addressstringThe output address
amountnumberThe output amount

Returns the message submit instance for chained calls.

initialAddressIndex(index): MessageSender#

Sets the initial address index to search for balance. Defaults to 0 if the function isn't called.

ParamTypeDescription
indexnumberThe initial address index

Returns the message submit instance for chained calls.

submit(): Promise
#

Submits the message.

Returns a promise resolving to the message identifier.

UnspentAddressGetter#

Gets a valid unspent address associated with the seed.

accountIndex(index): UnspentAddressGetter#

Sets the account index. This field is required.

ParamTypeDescription
indexnumberThe account index

Returns the address getter instance for chained calls.

initialAddressIndex(index): UnspentAddressGetter#

Sets the initial address index. Defaults to 0 if the function isn't called.

ParamTypeDescription
indexnumberThe initial address index

Returns the address getter instance for chained calls.

get(): Promise<[Address, number]>#

Performs the operation.

Returns a promise resolving to the Address instance and its index.

AddressGetter#

Generates addresses with a given seed.

accountIndex(index): AddressGetter#

Sets the account index. This field is required.

ParamTypeDescription
indexnumberThe account index

Returns the address finder instance for chained calls.

range(start, end): AddressGetter#

Defines the range of addresses to get. Defaults to 0..20 if the function isn't called.

ParamTypeDescription
startnumberThe first address index
endnumberThe last address index

Returns the address finder instance for chained calls.

includeInternal(): AddressGetter#

Defines that public and internal address will be returned instead of only public addresses.

Returns the address finder instance for chained calls.

bech32Hrp(bech32Hrp): AddressGetter#

Defines the bech32Hrp for the bech32 encoded addresses, required when generating addresses offline(with disableNodeSync()).

ParamTypeDescription
bech32HrpstringThe bech32Hrp for the addresses

Returns the address finder instance for chained calls.

get(): Address[] | [Address, bool][]#

Performs the operation.

Returns an array of public Address instances or an array of arrays with an Address and a bool, where the bool defines whether it's an internal address or not.

BalanceGetter#

Gets balance on a given seed.

accountIndex(index): BalanceGetter#

Sets the account index. This field is required.

ParamTypeDescription
indexnumberThe account index

Returns the balance getter instance for chained calls.

initialAddressIndex(index): BalanceGetter#

Sets the initial address index. Defaults to 0 if the function isn't called.

ParamTypeDescription
indexnumberThe initial address index

Returns the balance getter instance for chained calls.

gapLimit(amount): BalanceGetter#

Sets the gapLimit to specify how many addresses will be checked each round. If gapLimit amount of addresses in a row have no balance the BalanceGetter will return. Defaults to 20 if the function isn't called.

ParamTypeDescription
gapLimitnumberThe initial address index

Returns the balance getter instance for chained calls.

get(): Promise#

Performs the operation.

Returns a promise resolving to the account balance.

MessageFinder#

Gets a message by indexation key or identifier.

initialAddressIndex(index): Promise<string[]/>#

ParamTypeDescription
indexstringThe indexation key

Gets a list of message identifiers associated with the given indexation key.

Returns a promise resolving to the list of associated ids.

data(id): Promise
#

Gets the message object associated with the given identifier.

ParamTypeDescription
idstringThe message identifier

Returns a Message object.

raw(id): Promise#

Gets the message raw data.

ParamTypeDescription
idstringThe message identifier

Returns the message raw data as string.

children(id): Promise<string[]>#

Gets the children of the given message.

ParamTypeDescription
idstringThe message identifier

Returns the list of message ids of the message children.

metadata(id): Promise
#

Gets the metadata of the given message.

ParamTypeDescription
idstringThe message identifier

Returns a MessageMetadata object.

BrokerOptions#

All fields are optional.

FieldTypeDescription
automaticDisconnectbooleanWhether the MQTT broker should be automatically disconnected when all topics are unsubscribed or not.
timeoutnumberMQTT connection timeout in secods
useWsbooleanDefines if websockets should be used (true) or TCP (false)
maxReconnectionAttemptsnumberDefines the maximum reconnection attempts before it returns an error
portnumberDefines the port to be used for the MQTT connection

NodeAuthOptions#

FieldTypeDescription
jwtstringOptional JSON Web Token.
basicAuthNamestringOptional name for basic authentication
basicAuthPasswordstringOptional password for basic authentication

Address#

FieldTypeDescription
datastringAddress as a Bech32 string

Message#

FieldTypeDescription
networkIdnumberNetwork identifier
parentsstring[]Message ids of the message references
payload[Payload](#payload)Message payload
noncenumberMessage nonce

MessageWrapper#

FieldTypeDescription
messageMessageMessage
messageIdstringThe message id

Payload#

FieldTypeDescription
data{ type: 'Transaction', data: TransactionPayload } | { type: 'Indexation', data: IndexationPayload } | { type: 'Milestone', data: MilestonePayload}Payload data
TransactionPayload#
FieldTypeDescription
essenceTransactionPayloadEssenceTransaction essence
unlock_blocksUnlockBlock[]Unlock blocks
  • TransactionPayloadEssence
FieldTypeDescription
inputsInput[]Inputs
outputsOutput[]Outputs
payloadPayload | undefinedPayload for chaining
  • Input
FieldTypeDescription
type'UTXO'Input type identifier
datastringThe associated output id
  • Output
FieldTypeDescription
typeSignatureLockedSingleOutput type identifier
data{ address: string, amount: number }The output definition
  • UnlockBlock
FieldTypeDescription
type'Signature' \| 'Reference'Unlock block type identifier
dataEd25519SignatureUnlockBlock | numberUnlock block data (signature type or reference index)
  • Ed25519SignatureUnlockBlock
FieldTypeDescription
public_keynumber[]Ed25519 public key
signaturenumber[]Ed25519 signature
IndexationPayload#
FieldTypeDescription
indexstringIndexation key
datanumber[]Indexation data as byte array
MilestonePayload#
FieldTypeDescription
essenceMilestoneEssenceMilestone essence
signaturesnumber[][]Milestone signatures
  • MilestoneEssence
FieldTypeDescription
indexnumberMilestone index
timestampnumberTimestamp
parentsstring[]Message ids of the messages the milestone references
merkleProofnumber[]Merkle proof
nextPoWScorenumberNext PoW score
nextPoWScoreMilestoneIndexnumberMilestone index at which the nextPoWScore will be used
publicKeysnumber[][]public keys

MessageDto#

FieldTypeDescription
parentsstring[] | undefinedMessage ids of the messages it references. getTips is used by default
payload[PayloadDto](#payloaddto)Message payload

PayloadDto#

FieldTypeDescription
dataTransactionPayloadDto | IndexationPayloadDtoPayload data
TransactionPayloadDto#
FieldTypeDescription
essenceTransactionPayloadEssenceDtoTransaction essence
unlockBlocksUnlockBlockDto[]Unlock blocks
  • TransactionPayloadEssenceDto
FieldTypeDescription
inputsstring[]Inputs
outputsOutput[]Outputs
payloadPayloadDto | undefinedPayload for chaining
  • OutputDto
FieldTypeDescription
addressstringOutput address
amountamountOutput amount
  • UnlockBlockDto
FieldTypeDescription
dataEd25519SignatureUnlockBlockDto | numberUnlock block data (signature type or reference index)
  • Ed25519SignatureUnlockBlockDto
FieldTypeDescription
publicKeynumber[]Ed25519 public key
signaturenumber[]Ed25519 signature
IndexationPayloadDto#
FieldTypeDescription
indexstringIndexation key
dataUint8ArrayIndexation data
AddressBalance#
FieldTypeDescription
addressstringBech32 encoded address
balancenumberAddress balance
dustAllowedbooleanDust allowed

MessageMetadata#

FieldTypeDescription
messageIdstringMessage identifier
parentsstring[]Message id of the messages it references
isSolidbooleanMessage solid state
shouldPromoteboolean | undefinedIndicates whether the message should be promoted or not
shouldReattachboolean | undefinedIndicates whether the message should be reattached or not
referencedByMilestoneIndexnumber | undefinedIndex of the milestone that references this message
ledgerInclusionStatestring | undefinedLedger inclusion state

NodeInfoWrapper#

FieldTypeDescription
urlstringNode url
nodeinfoNodeInfoNodeInfo

NodeInfo#

FieldTypeDescription
namestringNode name
versionstringNode version
isHealthybooleanNode health status
networkIdstringNode network identifier
bech32HRPstringBech32 HRP for this network
minPoWScorenumberMin PoW score
messagesPerSecondnumberNetwork stats: Messages per second in the network
referencedMessagesPerSecondnumberNetwork stats: Referenced messages per second
referencedRatenumberNetwork stats: referenced rate
latestMilestoneTimestampnumberTimestamp of the latest milestone
latestMilestoneIndexnumberIndex of the latest milestone
confirmedMilestoneIndexnumberIndex of the confirmed milestone
pruningIndexnumberPruning index
featuresstring[]List of node features

OutputMetadata#

FieldTypeDescription
messageIdstringId of the message associated with the output
transactionIdstringId of the transaction associated with the output
outputIndexnumberOutput index
isSpentbooleanOutput spent state
addressstringOutput address
amountnumberOutput amount

MilestoneMetadata#

FieldTypeDescription
milestoneIndexnumberMilestone index
messageIdstringId of the message associated with the milestone
timestampnumberMilestone timestamp

MilestoneUTXOChanges#

FieldTypeDescription
indexnumberMilestone index
createdOutputsstring[]OutputIds from new created outputs
consumedOutputsstring[]OutputIds from consumed outputs

Receipts#

FieldTypeDescription
receiptreceiptReceipt
milestoneIndexnumberMilestone index

Treasury#

FieldTypeDescription
milestoneIdstringMilestone id
amountnumberAmount