@iota/core
TypeScript icon, indicating that this package has built-in type declarations

1.0.0-beta.30 • Public • Published

@iota/core

Core functionality to interact with the IOTA network. Includes methods for:

  • Generating addresses
  • Creating, attaching and broadcasting transactions
  • Querying for transactions
  • Monitoring balances
  • Monitoring inclusion states and consistency of transactions
  • Promoting and reattaching pending transactions

Installation

Install using npm:

npm install @iota/core

or using yarn:

yarn add @iota/core

API Reference

core.composeApi([settings])

Summary: Creates an API object that's used to send requests to an IRI node.

Param Type Default Description
[settings] Object {} Connection settings.
[settings.network] Provider http-client Network provider
[settings.provider] string "http://localhost:14265" URI of an IRI node
[settings.attachToTangle] function attachToTangle Function that overrides the default attachToTangle endpoint
[settings.apiVersion] string | number 1 IOTA API version to use in the X-IOTA-API-Version HTTP header
[settings.requestBatchSize] number 1000 Maximum number of parameters that may be sent in batched API request for findTransactions, getBalances, getInclusionStates, and getTrytes

Returns: API - iota - API object to use to interact with an IRI node.
Example

const Iota = require('@iota/core`);

const iota = Iota.composeAPI({
 provider: 'https://nodes.devnet.thetangle.org:443'
});

core.addNeighbors(URIs, [callback])

Summary: Adds temporary neighbors to the connected IRI node.
Fulfil: number numberOfNeighbors - Number of neighbors that were added
Reject: Error error - One of the following errors:

  • INVALID_URI: Make sure that the URI is a string and starts with tcp://
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
URIs Array.<string> Comma-separated URIs of neighbor nodes that you want to add
[callback] Callback Optional callback function

This method adds temporary neighbors to the connected IRI node by calling the its addNeighbors endpoint.

These neighbors are removed when the node is restarted.

Related methods

To see statistics about the connected IRI node's neighbors, use the getNeighbors() method.

Example

addNeighbors(['tcp://148.148.148.148:15600'])
  .then(numberOfNeighbors => {
    console.log(`Successfully added ${numberOfNeighbors} neighbors`)
  }).catch(error => {
    console.log(`Something went wrong: ${error}`)
  })

core.attachToTangle(trunkTransaction, branchTransaction, minWeightMagnitude, trytes, [callback])

Summary: Connects the given transaction trytes into a bundle and sends them to the connected IOTA node to complete remote proof of work.
Fulfil: TransactionTrytes[] attachedTrytes - Array of transaction trytes in tail-first order. To attach these transactions to the Tangle, pass the trytes to the broadcastTransactions() method.
Reject: Error error - One of the following errors:

  • INVALID_TRUNK_TRANSACTION: Make sure that the hash contains 81 trytes
  • INVALID_BRANCH_TRANSACTION: Make sure that the hash contains 81 trytes
  • INVALID_MIN_WEIGHT_MAGNITUDE: Make sure that the minimum weight magnitude is at least the same as the one used for the branch and trunk transactions.
  • INVALID_TRANSACTION_TRYTES: Make sure the trytes can be converted to a valid transaction object
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
trunkTransaction Hash Trunk transaction hash
branchTransaction Hash Branch transaction hash
minWeightMagnitude number The minimum weight magnitude to use for proof of work. Note: This value must be at least the same as the minimum weight magnitude of the branch and trunk transactions.
trytes Array.<TransactionTrytes> Array of transaction trytes in head first order, which are returned by the prepareTransfers() method
[callback] Callback Optional callback function

This method uses the connected IRI node's attachToTangle endpoint to chain the given transaction trytes into a bundle and do proof of work.

By doing proof of work, this method overwrites the following transaction fields:

  • hash
  • nonce
  • attachmentTimestamp
  • attachmentTimestampLowerBound
  • attachmentTimestampUpperBound

Note: You can replace this method with your own custom one in the composeApi() method. For example, you may want to write a function that does local proof of work, using either the ccurl.interface.js NodeJS library, or the curl.lib.js library for browsers that support WebGL2.

Related methods

To attach the returned transaction trytes to the Tangle, use the broadcastTransactions() method to send them to a node.

You can get a trunk and branch transaction hash by calling the getTransactionsToApprove() method

Example

getTransactionsToApprove(depth)
  .then(({ trunkTransaction, branchTransaction }) =>
    attachToTangle(trunkTransaction, branchTransaction, minWeightMagnitude, trytes)
  )
  .then(attachedTrytes => {
    console.log(`Successfully did proof of work. Here are your bundle's transaction trytes: ${attachedTrytes}`)
  }).catch(error => {
    console.log(`Something went wrong: ${error}`)
  })

core.broadcastBundle(tailTransactionHash, [callback])

Summary: Resends all transactions in the bundle of a given tail transaction hash to the connected IRI node.
Fulfil: Transaction[] transactionObjects - Array of transaction objects
Reject: Error error - An error that contains one of the following:

  • INVALID_TRANSACTION_HASH: Make sure the tail transaction hash is 81 trytes long and its currentIndex field is 0
  • INVALID_BUNDLE: Check the tail transaction's bundle for the following:
    • Addresses in value transactions have a 0 trit at the end, which means they were generated using the Kerl hashing function
    • Transactions in the bundle array are in the same order as their currentIndex field
    • The total value of all transactions in the bundle sums to 0
    • The bundle hash is valid
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
tailTransactionHash Hash Tail transaction hash
[callback] Callback Optional callback function

This method uses the getBundle() method to get all transactions in the given tail transaction's bundle from the connected IRI node.

Then, those transactions are sent to the node again so that the node sends them to all of its neighbors.

You may want to use this method to improve the likelihood of your transactions reaching the rest of the network.

Note: To use this method, the node must already have your bundle's transaction trytes in its ledger.

Related methods

To create and sign a bundle of new transactions, use the prepareTransfers() method.

Example

broadcastBundle(tailHash)
  .then(transactionObjects => {
     console.log(`Successfully sent the following bundle to the node:)
     console.log(JSON.stringify(transactionObjects));
  })
  .catch(error => {
    console.log(`Something went wrong: ${error}`)
  })

core.broadcastTransactions(trytes, [callback])

Summary: Sends the given transaction trytes to the connected IRI node.
Fulfil: TransactionTrytes[] transactionTrytes - Array of transaction trytes that you just broadcast
Reject: Error error - An error that contains one of the following:

  • INVALID_ATTACHED_TRYTES: Make sure that the trytes include a proof of work
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
trytes Array.<TransactionTrytes> Transaction trytes that include proof of work
[callback] Callback Optional callback

This method sends the given transaction trytes to the connected IRI node, using its broadcastTransactions endpoint.

Note: Before calling this method, we recommend saving your transaction trytes in local storage. By doing so, you make sure that you can always reattach your transactions to the Tangle in case they remain in a pending state.

Related methods

The given transaction trytes must be in a valid bundle and must include a proof of work.

To create a valid bundle, use the prepareTransfers() method. For more information about what makes a bundles and transactions valid, see this guide.

To do proof of work, use one of the following methods:

Example

broadcastTransactions(trytes)
  .then(transactionTrytes => {
     console.log(`Successfully sent the following transaction trytes to the node:)
     console.log(JSON.stringify(transactionTrytes));
  })
  .catch(error => {
    console.log(`Something went wrong: ${error}`)
  })

core.checkConsistency(transactions, [options], [callback])

Summary: Checks if one or more transactions are consistent.
Fulfil: boolean isConsistent - Whether the given transactions are consistent
Reject: Error error - An error that contains one of the following:

  • INVALID_TRANSACTION_HASH: Make sure the tail transaction hashes are 81 trytes long and their currentIndex field is 0
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
  • Reason for inconsistency if the method was called with the options.rejectWithReason argument
Param Type Description
transactions Hash | Array.<Hash> One or more tail transaction hashes to check
[options] Object Options object
[options.rejectWithReason] boolean Return the reason for inconsistent transactions
[callback] Callback Optional callback function

This method finds out if a transaction has a chance of being confirmed, using the connected node's checkConsistency endpoint.

A consistent transaction is one where:

  • The node has the transaction's branch and trunk transactions in its ledger
  • The transaction's bundle is valid
  • The transaction's branch and trunk transactions are valid

For more information about what makes a bundles and transactions valid, see this article.

As long as a transaction is consistent it has a chance of being confirmed.

Related methods

If a consistent transaction is taking a long time to be confirmed, you can improve its chances, using the promoteTransaction() method.

If a transaction is inconsistent, it will never be confirmed. In this case, you can reattach the transaction, using the replayBundle() method.

Example

checkConsistency(transactions)
  .then(isConsistent => {
    isConsistent? console.log(All these transactions are consistent): console.log(One or more of these transactions are inconsistent);
  })
  .catch(err => {
    console.log(`Something went wrong: ${error}`);
  })

core.findTransactionObjects(query, [callback])

Summary: Searches the Tangle for transaction objects that contain all the given values in their transaction fields.
Fulfil: Transaction[] transactionObjects - Array of transaction objects, which contain fields that match the query object
Reject: Error error - An error that contains one of the following:

  • INVALID_SEARCH_KEY: Make sure that you entered valid query parameters
  • INVALID_HASH: Make sure that the bundle hashes are 81 trytes long
  • INVALID_TRANSACTION_HASH: Make sure that the approvee transaction hashes are 81 trytes long
  • INVALID_ADDRESS: Make sure that the addresses contain only trytes
  • INVALID_TAG: Make sure that the tags contain only trytes
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
query Object Query object
[query.addresses] Array.<Hash> Array of addresses to search for in transactions
[query.bundles] Array.<Hash> Array of bundle hashes to search for in transactions
[query.tags] Array.<Tag> Array of tags to search for in transactions
[query.approvees] Array.<Hash> Array of transaction hashes that you want to search for in transactions' branch and trunk transaction fields
[callback] Callback Optional callback function

This method uses the findTransactions() to find transactions with the given fields, then it uses the getTransactionObjects() method to return the transaction objects.

If you pass more than one query, this method returns only transactions that contain all the given fields in those queries.

Related methods

To find only transaction hashes, use the findTransactions() method.

Example

findTransactionObjects({ addresses: ['ADDRESS999...'] })
   .then(transactionObjects => {
     console.log(`Successfully found the following transactions:)
     console.log(JSON.stringify(transactionObjects));
  })
  .catch(error => {
    console.log(`Something went wrong: ${error}`)
  })

core.findTransactions(query, [callback])

Summary: * Searches the Tangle for the hashes of transactions that contain all the given values in their transaction fields.
Fulfil: Hash[] transactionHashes - Array of transaction hashes for transactions, which contain fields that match the query object
Reject: Error error - An error that contains one of the following:

  • INVALID_SEARCH_KEY: Make sure that you entered valid query parameters
  • INVALID_HASH: Make sure that the bundle hashes are 81 trytes long
  • INVALID_TRANSACTION_HASH: Make sure that the approvee transaction hashes are 81 trytes long
  • INVALID_ADDRESS: Make sure that the addresses contain only trytes
  • INVALID_TAG: Make sure that the tags contain only trytes
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
query Object Query object
[query.addresses] Array.<Hash> Array of addresses to search for in transactions
[query.bundles] Array.<Hash> Array of bundle hashes to search for in transactions
[query.tags] Array.<Tag> Array of tags to search for in transactions
[query.approvees] Array.<Hash> Array of transaction hashes that you want to search for in transactions' branch and trunk transaction fields
[callback] Callback Optional callback function

This method searches for transaction hashes by calling the connected IRI node's findTransactions endpoint.

If you pass more than one query parameter, this method returns only transactions that contain all the given fields in those queries.

Related methods

To find transaction objects, use the findTransactionObjects() method.

Example

findTransactions({ addresses: ['ADDRESS999...'] })
   .then(transactionHashes => {
     console.log(`Successfully found the following transactions:)
     console.log(JSON.stringify(transactionHashes));
  })
  .catch(error => {
    console.log(`Something went wrong: ${error}`)
  })

core.getAccountData(seed, options, [callback])

Summary: Searches the Tangle for transctions, addresses, and balances that are associated with a given seed.
Fulfil: AccountData accountData - Object that contains the following:

  • accountData.transfers: (deprecated) Array of transaction objects that contain one of the seed's addresses
  • accountData.transactions: Array of transaction hashes for transactions that contain one of the seed's addresses
  • accountData.addresses: Array of spent addresses
  • accountData.inputs: Array of input objects for any unspent addresses
    • accountData.inputs.address: The 81-tryte address (without checksum)
    • accountData.inputs.keyIndex: The key index of the address
    • accountData.inputs.security: Security level of the address
    • accountData.inputs.balance: Balance of the address
  • accountData.balance: The total balance of unspent addresses
    Reject: Error error - An error that contains one of the following:
  • INVALID_SEED: Make sure that the seed contains only trytes
  • INVALID_SECURITY_LEVEL: Make sure that the security level is a number between 1 and 3
  • INVALID_START_OPTION: Make sure that the options.start argument is greater than zero
  • INVALID_START_END_OPTIONS: Make sure that the options.end argument is not greater than the options.start argument by more than 1,000`
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Default Description
seed string The seed to use to generate addresses
options Object Options object
[options.start] number 0 The key index from which to start generating addresses
[options.security] number 2 The security level to use to generate the addresses
[options.end] number The key index at which to stop generating addresses
[callback] Callback Optional callback function

This method generates addresses for a given seed, and searches the Tangle for data about those addresses such as transactions, inputs, and total balance.

Note: The given seed is used to generate addresses on your local device. It is never sent anywhere.

If you don't pass an options.end argument to this method, it will continue to generate addresses until it finds an unspent one.

Note: The total balance does not include IOTA tokens on spent addresses.

Related methods

To find the balance of specific addresses, which don't have to belong to your seed, use the getBalances() method.

To find only inputs (objects that contain information about addresses with a postive balance), use the getInputs() method.

Example

getAccountData(seed)
  .then(accountData => {
    const { addresses, inputs, transactions, balance } = accountData
    console.log(`Successfully found the following transactions:)
    console.log(JSON.stringify(transactions));
  })
  .catch(error => {
    console.log(`Something went wrong: ${error}`)
  })

core.getBalances(addresses, [tips], [callback])

Summary: Gets the confirmed balances of the given addresses.
Fulfil: Balances balances - Object that contains the following:

  • balances.addresses: Array of balances in the same order as the addresses argument
  • balances.references: Either the transaction hash of the latest milestone, or the transaction hashes that were passed to the tips argument
  • balances.milestoneIndex: The latest milestone index that confirmed the balance
  • balances.duration: The number of milliseconds that it took for the node to return a response
    Reject: Error error - An error that contains one of the following:
  • INVALID_HASH: Make sure that the addresses contain only trytes
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
addresses Array.<Hash> Array of addresses
[tips] Array.<Hash> Array of past transaction hashes from which to calculate the balances of the addresses. The balance will be calculated from the latest milestone that references these transactions.
[callback] Callback Optional callback function

This method uses the connected IRI node's getBalances endpoint.

Any pending output transactions are not included in the balance. For example, if a pending output transaction deposits 10 Mi into an address that contains 50 Mi, this method will return a balance of 50 Mi not 60 Mi.

Related methods

To find the balance of all addresses that belong to your seed, use the getAccountData() method.

Example

getBalances([address])
  .then( balances => {
    console.log(`Balance of the first address: `$balances.balances[0])
    console.log(JSON.stringify(transactions));
  })
  .catch(error => {
    console.log(`Something went wrong: ${error}`)
}

core.getBundle(tailTransactionHash, [callback])

Summary: Searches the Tangle for a valid bundle that includes the given tail transaction hash.
Fulfil: Transaction[] bundle - Array of transaction objects that are in the bundle
Reject: Error error - An error that contains one of the following:

  • INVALID_TRANSACTION_HASH: Make sure the tail transaction hash is 81 trytes long
  • INVALID_TAIL_HASH: Make sure that the tail transaction hash is for a transaction whose currentIndex field is 0
  • INVALID_BUNDLE: Check the tail transaction's bundle for the following:
    • Addresses in value transactions have a 0 trit at the end, which means they were generated using the Kerl hashing function
    • Transactions in the bundle array are in the same order as their currentIndex field
    • The total value of all transactions in the bundle sums to 0
    • The bundle hash is valid
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
tailTransactionHash Hash Tail transaction hash
[callback] Callback Optional callback function

This method uses the traverseBundle() method to find all transactions in a bundle, validate them, and return them as transaction objects.

For more information about what makes a bundles and transactions valid, see this guide.

Related methods

To find transaction objects that aren't in the same bundle, use the getTransactionObjects() method.

Example

getBundle(tail)
   .then(bundle => {
    console.log(`Bundle found:)
    console.log(JSON.stringify(bundle));
  })
  .catch(error => {
    console.log(`Something went wrong: ${error}`)
   })

core.getInclusionStates(transactions, [callback])

Summary: Finds out if one or more given transactions are referenced by one or more other given transactions.
Fulfil: boolean[] states - Array of inclusion states, where true means that the transaction is referenced by the given transacions and false means that it's not.
Reject: Error error - An error that contains one of the following:

  • INVALID_TRANSACTION_HASH: Make sure that the transaction hashes are 81 trytes long
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
transactions Array.<Hash> Array of transaction hashes to check
[callback] Callback Optional callback function

This method uses the connected IRI node's getInclusionStates endpoint.

If the given tip transactions reference a given transaction, the returned state is true.

If the given tip transactions do not reference a given transaction, the returned state is false.

Example

getInclusionStates(transactions)
  .then(states => {
     for(let i = 0; i < states.length; i++){
         states? console.log(`Transaction ${i} is referenced by the given transactions`) :
         console.log(`Transaction ${i} is not referenced by the given transactions`);
     }
  })
  .catch(error => {
    console.log(`Something went wrong: ${error}`)
  });

core.getInputs(seed, [options], [callback])

Summary: Finds a seed's addresses that have a positive balance.
Fulfil: Inputs - Array that contains the following:

  • input.addresses: An address
  • input.keyIndex: The key index of the address
  • input.security: The security level of the address
  • input.balance: The amount of IOTA tokens in the address
  • inputs.totalBalance: The combined balance of all addresses
    Reject: Error error - An error that contains one of the following:
  • INVALID_SEED: Make sure that the seed contains only trytes
  • INVALID_SECURITY_LEVEL: Make sure that the security level is a number between 1 and 3
  • INVALID_START_OPTION: Make sure that the options.start argument is greater than zero
  • INVALID_START_END_OPTIONS: Make sure that the options.end argument is not greater than the options.start argument by more than 1,000`
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages `
  • INVALID_THRESHOLD: Make sure that the threshold is a number greater than zero
  • INSUFFICIENT_BALANCE: Make sure that the seed has addresses that contain IOTA tokens
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Default Description
seed string The seed to use to generate addresses
[options] Object Options object
[options.start] number 0 The key index from which to start generating addresses
[options.security] number 2 The security level to use to generate the addresses
[options.end] number The key index at which to stop generating addresses
[options.threshold] number The amount of IOTA tokens that you want to find
[callback] Callback Optional callback function

This method generates addresses for a given seed and finds those that have a positive balance.

Note: The given seed is used to generate addresses on your local device. It is never sent anywhere.

To find a certain amount of IOTA tokens and return only the addresses that, when combined, contain that amount, pass it to the options.threshold argument.

Related methods

You may want to use this method to find inputs for the prepareTransfers() method.

Example

getInputs(seed)
  .then(({ inputs, totalBalance }) => {
    console.log(`Your seed has a total of ${totalBalance} IOTA tokens \n` +
    `on the following addresses:`)
     for(let i = 0; i < inputs.length; i++) {
         console.log(`${inputs[i].address}: ${inputs[i].balance}`)
     }
  })
  .catch(error => {
    if (error.message === errors.INSUFFICIENT_BALANCE) {
       console.log('You have no IOTA tokens');
    }
  });

core.getNeighbors([callback])

Summary: Gets information and statistics about the connected IRI node's neighbors.
Fulfil: Neighbors neighbors - Array that contains the following:

  • neighbors.address: IP address of the neighbor
  • neighbors.domain: Domain name of the neighbor
  • neighbors.numberOfAllTransactions: Number of transactions in the neighbors ledger (including invalid ones)
  • neighbors.numberOfRandomTransactionRequests: Number of random tip transactions that the neighbor has requested from the connected node
  • neighbors.numberOfNewTransactions: Number of new transactions that the neighbor has sent to the connected node
  • neighbors.numberOfInvalidTransactions: Number of invalid transactions that the neighbor sent to the connected node
  • neighbors.numberOfStaleTransactions: Number of transactions that the neighbor sent to the connected node, which contain a timestamp that's older than the connected node's latest snapshot
  • neighbors.numberOfSentTransactions: Number of transactions that the connected node has sent to the neighbor
  • neighbors.numberOfDroppedSentPackets: Number of network packets that the neighbor dropped because its queue was full
  • neighbors.connectionType: The transport protocol that the neighbor uses to sent packets to the connected node
  • neighbors.connected: Whether the neighbor is connected to the node
    Reject: Error error - Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
[callback] Callback Optional callback function

This method uses the connected IRI node's getNeighbors endpoint to find information about the neighbors' activity.

All statistics are aggregated until the node restarts.

Related methods

To add neighbors to the node, use the addNeighbors() method.

Example

getNeighbors()
.then(neighbors => {
    console.log(`Node is connected to the following neighbors: \n`)
    console.log(JSON.stringify(neighbors));
})
.catch(error => {
    console.log(`Something went wrong: ${error}`);
});

core.getNewAddress(seed, [options], [callback])

Summary: Generates a new address for a given seed.
Fulfil: Hash|Hash[] address - A single new address or an array of new addresses
Reject: Error error - An error that contains one of the following:

  • INVALID_SEED: Make sure that the seed contains only trytes
  • INVALID_SECURITY_LEVEL: Make sure that the security level is a number between 1 and 3
  • INVALID_START_OPTION: Make sure that the options.start argument is greater than zero
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Default Description
seed string The seed to use to generate addresses
[options] Object Options object
[options.index] number 0 The key index from which to start generating addresses
[options.security] number 2 The security level to use to generate the addresses
[options.checksum] boolean false Deprecated
[options.total] number Deprecated
[options.returnAll] boolean false Deprecated
[callback] Callback Optional callback function

This method uses the connected IRI node's findTransactions endpoint to search every transactions in the Tangle for each generated address. If an address is found in a transaction, a new address is generated until one is found that isn't in any transactions.

Note: The given seed is used to generate addresses on your local device. It is never sent anywhere.

Note: Because of local snapshots, this method is not a reliable way of generating unspent addresses. Instead, you should use the account module to keep track of your spent addresses.

Related methods

To find out which of your addresses are spent, use the getAccountData() method.

Example

getNewAddress(seed)
  .then(address => {
    console.log(`Here's your new address: ${address})
  })
  .catch(error => {
    console.log(`Something went wrong: ${error}`);
  })

core.getNodeInfo([callback])

Summary: Gets information about the connected IRI node.
Fulfil: NodeInfo info - Object that contains the following information: info.appName: Name of the IRI network info.appVersion: Version of the IRI node software info.jreAvailableProcessors: Available CPU cores on the node info.jreFreeMemory: Amount of free memory in the Java virtual machine info.jreMaxMemory: Maximum amount of memory that the Java virtual machine can use info.jreTotalMemory: Total amount of memory in the Java virtual machine info.jreVersion: The version of the Java runtime environment info.latestMilestone: Transaction hash of the latest milestone info.latestMilestoneIndex: Index of the latest milestone info.latestSolidSubtangleMilestone: Transaction hash of the node's latest solid milestone info.latestSolidSubtangleMilestoneIndex: Index of the node's latest solid milestone info.milestoneStartIndex: Start milestone for the current version of the IRI node software info.lastSnapshottedMilestoneIndex: Index of the last milestone that triggered a local snapshot on the node info.neighbors: Total number of connected neighbors info.packetsQueueSize: Size of the node's packet queue info.time: Unix timestamp info.tips: Number of tips transactions info.transactionsToRequest: Total number of transactions that the node is missing in its ledger info.features: Enabled configuration options on the node info.coordinatorAddress: Address (Merkle root) of the Coordinator info.duration: Number of milliseconds it took to complete the request
Reject: Error error - Fetch error: The connected IOTA node's API returned an error. See the list of error messages

Param Type Description
[callback] Callback Optional callback function

This method uses the connected IRI node's getNodeInfo endpoint.

Related methods

To get statistics about the connected node's neighbors, use the getNeighbors() method.

Example

getNodeInfo()
  .then(info => console.log(JSON.stringify(info)))
  .catch(error => {
    console.log(`Something went wrong: ${error}`);
  })

core.getTransactionObjects(hashes, [callback])

Summary: Searches the Tangle for transactions with the given hashes and returns their contents as objects.
Fulfil: Transaction[] - Array of transaction objects
Reject: Error error - An error that contains one of the following:

  • INVALID_TRANSACTION_HASH: Make sure that the transaction hashes are 81 trytes long
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
hashes Array.<Hash> Array of transaction hashes
[callback] function Optional callback function

This method returns transaction objects in the same order as the given hashes. For example, if the node doesn't have any transactions with a given hash, the value at that index in the returned array is empty.

Related methods

To find all transaction objects in a specific bundle, use the getBundle() method.

Example

getTransactionObjects(transactionHashes)
  .then(transactionObjects => {
    console.log('Found the following transactions:');
    console.log(JSON.stringify(transactionObjects));
  })
  .catch(error => {
    console.log(`Something went wrong: ${error}`);
  });

core.getTransactionsToApprove(depth, [reference], [callback])

Summary: Gets two tip transaction hashes that can be used as branch and trunk transactions.
Fulfil: Object transactionsToApprove - An object that contains the following:

  • trunkTransaction: Transaction hash
  • branchTransaction: Transaction hash
    Reject: Error error - An error that contains one of the following:
  • INVALID_DEPTH: Make sure that the depth argument is greater than zero
  • INVALID_REFERENCE_HASH: Make sure that the reference transaction hash is 81 trytes long
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
depth number The depth at which to start the weighted random walk. The Trinity wallet uses a value of 3, meaning that the weighted random walk starts 3 milestones in the past.
[reference] Hash Optional transaction hash that you want the tip transactions to reference
[callback] Callback Optional callback function

This method gets two consistent tip transaction hashes that can be used as branch and trunk transactions by calling the connected IRI node's getTransactionsToApprove endpoint.

To make sure that the tip transactions also directly or indirectly reference another transaction, add that transaction's hash to the reference argument.

Related methods

You can use the returned transaction hashes to do proof of work on transaction trytes, using the attachToTangle() method.

Example

getTransactionsToApprove(3)
  .then(transactionsToApprove) => {
     console.log(Found the following transaction hashes that you can reference in a new bundle:);
     console.log(JSON.stringify(transactionsToApprove));
  })
  .catch(error => {
    console.log(`Something went wrong: ${error}`);
  })

core.getTrytes(hashes, [callback])

Summary: Gets the transaction trytes for the given transaction hashes.
Fulfil: Trytes[] transactionTrytes - Array of transaction trytes
Reject: Error{} error - An error that contains one of the following:

  • INVALID_TRANSACTION_HASH: Make sure that the transaction hashes are 81 trytes long
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
hashes Array.<Hash> Array of transaction hashes
[callback] Callback Optional callback function

This method uses the connected IRI node's getTrytes endpoint.

The transaction trytes include all transaction fields except the transaction hash.

Note: If the connected IRI node doesn't have the given transaction in its ledger, the value at the index of that transaction hash is either null or a string of 9s.

Related methods

To get transaction objects instead of trytes, use the getTransactionObjects() method.

Example

getTrytes(hashes)
  .then(trytes => {
  .then(transactionTrytes => {
    console.log(Found the following transaction trytes:);
    console.log(JSON.stringify(transactionTrytes));
  })
  .catch(error => {
    console.log(`Something went wrong: ${error}`);
  });

core.isPromotable(tail, [callback])

Summary: Checks if a given tail transaction hash can be promoted.
Fulfil: boolean isPromotable - Returns true if the transaction is promotable or false if not.
Reject: Error error - An error that contains one of the following:

  • INVALID_TRANSACTION_HASH: Make sure the tail transaction hashes are 81 trytes long and their currentIndex field is 0
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
tail Hash Tail transaction hash
[callback] Callback Optional callback function

To decide if a transaction can be promoted, this method makes sure that it's consistent and that the value of the transaction's attachmentTimestamp field is not older than the latest 6 milestones.

Related methods

If a transaction is promotable, you can promote it by using the promoteTransaction() method.

Example

isPromotable(tailTransactionHash)
  .then(isPromotable => {
    isPromotable? console.log(`${tailTransactionHash} can be promoted`):
    console.log(`${tailTransactionHash} cannot be promoted. You may want to reattach it.`);
  })
  .catch(error => {
    console.log(`Something went wrong: ${error}`);
  })

core.createPrepareTransfers([provider])

Summary: Creates a new prepareTransfers() method.

Param Type Description
[provider] Provider Optional provider object that the method should use to call the node's API endpoints. To create transactions offline, omit this parameter so that the returned function does not get your addresses and balances from the node. To create value transactions offline, make sure to pass input objects and a remainder address to the returned function.

Returns: function - prepareTransfers - A new prepareTransfers() function that uses your chosen Provider instance.
Example

const prepareTransfers = Iota.createPrepareTransfers();

const transfers = [
 {
   value: 1,
   address: 'RECEIVINGADDRESS...'
 }
];

prepareTransfers(seed, transfers, {
 inputs:[{address: 'ADDRESS...',
 keyIndex: 5,
 security: 2,
 balance: 50}],
 // Remainder will be 50 -1 = 49 IOTA tokens
 address: 'REMAINDERADDRESS...'
})
.then(bundleTrytes => {
 console.log('Bundle trytes are ready to be attached to the Tangle:');
 console.log(JSON.stringify(bundleTrytes));
})
.catch(error => {
 console.log(`Something went wrong: ${error}`);
});

core.prepareTransfers(seed, transfers, [options], [callback])

Summary: Creates and signs a bundle of valid transaction trytes, using the given arguments.
Fulfil: array bundleTrytes - Array of transaction trytes
Reject: Error error - An error that contains one of the following:

  • INVALID_SEED: Make sure that the seed contains only trytes
  • INVALID_TRANSFER_ARRAY: Make sure that any objects in the transfers argument are valid (for example that the addresses contain only trytes, the values are numbers)
  • INVALID_INPUT: Make sure that the options.inputs[] argument contains valid input objects
  • INVALID_REMAINDER_ADDRESS: If you used the createPrepareTransfers() method without a provider, make sure you entered an address in the options.remainderAddress argument
  • INSUFFICIENT_BALANCE: Make sure that the seed's addresses have enough IOTA tokens to complete the transfer
  • NO_INPUTS: Make sure that the options.inputs[] argument contains valid input objects
  • SENDING_BACK_TO_INPUTS: Make sure that none of the transfer.address arguments are in the `options.inputs[].address parameters
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Default Description
seed string The seed to use to generate addresses and sign transactions
transfers Transfers.<Transfer> Array of transfer objects
transfer.address Hash Address to which to send a transaction
transfer.value number Amount of IOTA tokens to send to the address
transfer.message string Message to include in the transaction. The message must include only ASCII characters.
transfer.tag string Up to 27 trytes to include in the transaction's obsoleteTag field
[options] Object Options object
[options.inputs] Array.<Input> Array of input objects, which contain information about the addresses from which to withdraw IOTA tokens
[options.inputs[].address] Hash One of the seed's addresses from which to withdraw IOTA tokens
[options.inputs[].keyIndex] number Key index of the address
[options.inputs[].security] number Security level of the address
[options.inputs[].balance] number Total balance of the address. The total balance is withdrawn and any remaining IOTA tokens are sent to the address in the options.remainderAddress field.
[options.remainderAddress] Hash Remainder address to send any remaining IOTA tokens (total value in the transfers array minus the total balance of the input addresses)
[options.security] number 2 Security level to use for calling the getInputs method to automatically select input objects
[callback] function Optional callback function

Properties

Name Type Description
[options.hmacKey] Hash HMAC key used for adding an HMAC signature to the transaction

This method creates a bundle, using the given arguments and uses the given seed to sign any transactions that withdraw IOTA tokens.

Note: The given seed is used to generate addresses and sign transactions on your local device. It is never sent anywhere.

Note: To create transactions offline, use the createPrepareTransfers without a provider argument.

After calling this method, we recommend saving the returned transaction trytes in local storage before sending them to a node. By doing so, you make sure that you can always reattach your transactions to the Tangle in case they remain in a pending state. Reattaching transactions is safer than creating and signing new transactions, which could lead to spent addresses.

Related methods

To attach the returned transaction trytes to the Tangle, you can use one of the following:

Example

const transfers = [
 {
   value: 1,
   address: 'RECEIVINGADDRESS...'
 }
];

prepareTransfers(seed, transfers)
.then(bundleTrytes => {
 console.log('Bundle trytes are ready to be attached to the Tangle:');
 console.log(JSON.stringify(bundleTrytes));
})
.catch(error => {
 console.log(`Something went wrong: ${error}`);
});

core.promoteTransaction(tail, depth, minWeightMagnitude, [spamTransfers], [options], [callback])

Summary: Promotes a given tail transaction.
Fulfil: Transaction[] transactions - Array of zero-value transaction objects that were sent
Reject: Error error - An error that contains one of the following:

  • INCONSISTENT_SUBTANGLE: In this case, promotion has no effect and a reattachment is required by calling the replayBundle() method
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Default Description
tail Hash Tail transaction hash
depth number The depth at which to start the weighted random walk. The Trinity wallet uses a value of 3, meaning that the weighted random walk starts 3 milestones in the past.
minWeightMagnitude number Minimum weight magnitude
[spamTransfers] Array {address: '9999...999', value:0, tag:'999...999',message: '999...999' } Array of transfer objects to use to promote the transaction
[options] Object Options object
[options.delay] number Delay in milliseconds before sending each zero-value transaction
[options.interrupt] boolean | function Either a boolean or a function that evaluates to a boolean to stop the method from sending transactions
[callback] Callback Optional callback function

This method promotes only consistent transactions by checking them with the checkConsistency() method.

Related methods

Use the isPromotable() method to check if a transaction can be promoted.

If a transaction can't be promoted, use the replayBundle() method to reattach it to the Tangle.

Example

iota.promoteTransaction('FOSJBUZEHOBDKIOJ9RXBRPPZSJHWMXCDFJLIJSLJG9HRKEEJGAHWATEVCYERPQXDWFHQRGZOGIILZ9999',
3,14)
.then(transactions => {
  console.log(`Promoted the tail transaction, using the following transactions: \n` +
  JSON.stringify(transactions));
})
.catch(error => {
    console.log(`Something went wrong: ${error}`);
})

core.removeNeighbors(uris, [callback])

Summary: Removes a list of neighbors from the connected IRI node.
Fulfil: number numberOfNeighbors - Number of neighbors that were removed
Reject: Error error - An error that contains one of the following:

  • INVALID_URI: Make sure that the URI is valid (for example URIs must start with udp:// or tcp://)
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
uris Array Array of neighbor URIs that you want to add to the node
[callback] Callback Optional callback function

This method removes a list of neighbors from the connected IRI node by calling its removeNeighbors endpoint.

These neighbors are re-added when the node is restarted.

Related methods

To see statistics about the connected IRI node's neighbors, use the getNeighbors() method.

Example

iota.addNeighbors(['tcp://148.148.148.148:15600'])
  .then(numberOfNeighbors => {
    console.log(`Successfully removed ${numberOfNeighbors} neighbors`)
  }).catch(error => {
    console.log(`Something went wrong: ${error}`)
  })

core.replayBundle(tail, depth, minWeightMagnitude, [callback])

Summary: Reattaches a bundle to the Tangle.
Fulfil: Transaction[] bundle - Array of transaction objects in the reattached bundle
Reject: Error error - An error that contains one of the following:

  • INVALID_DEPTH: Make sure that the depth argument is greater than zero
  • INVALID_MIN_WEIGHT_MAGNITUDE: Make sure that the minimum weight magnitude is at least the same as the original bundle
  • INVALID_TRANSACTION_HASH: Make sure the tail transaction hash is 81 trytes long and its currentIndex field is 0
  • INVALID_BUNDLE: Check the tail transaction's bundle for the following:
    • Addresses in value transactions have a 0 trit at the end, which means they were generated using the Kerl hashing function
    • Transactions in the bundle array are in the same order as their currentIndex field
    • The total value of all transactions in the bundle sums to 0
    • The bundle hash is valid
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
tail Hash Tail transaction hash
depth number The depth at which to start the weighted random walk. The Trinity wallet uses a value of 3, meaning that the weighted random walk starts 3 milestones in the past.
minWeightMagnitude number The minimum weight magnitude to use for proof of work. Note: This value must be at least the same as the minimum weight magnitude of the branch and trunk transactions.
[callback] Callback Optional callback function

This method reattaches a bundle to the Tangle by calling the sendTrytes() method.

You can call this function as many times as you need until one of the bundles becomes confirmed.

Related methods

Before you call this method, it's worth finding out if you can promote it by calling the isPromotable() method.

Example

iota.replayBundle(tailTransactionHash)
  .then(bundle => {
    console.log(`Successfully reattached ${tailTransactionHash}`);
    console.log(JSON.stringify(bundle));
  }).catch(error => {
    console.log(`Something went wrong: ${error}`)
  })

core.sendTrytes(trytes, depth, minWeightMagnitude, [reference], [callback])

Summary: Does tip selection and proof of work for a bundle of transaction trytes before sending the final transactions to the connected IRI node.
Fulfil: Transaction[] bundle - Array of transaction objects that you just sent to the node
Reject: Error error - An error that contains one of the following:

  • INVALID_TRANSACTION_TRYTES: Make sure the trytes can be converted to a valid transaction object
  • INVALID_DEPTH: Make sure that the depth argument is greater than zero
  • INVALID_MIN_WEIGHT_MAGNITUDE: Make sure that the minimum weight magnitude is at least the same as the original bundle
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
trytes Array.<Trytes> Array of prepared transaction trytes to attach, store, and send
depth number The depth at which to start the weighted random walk. The Trinity wallet uses a value of 3, meaning that the weighted random walk starts 3 milestones in the past.
minWeightMagnitude number The minimum weight magnitude to use for proof of work. Note: This value must be at least the same as the minimum weight magnitude of the branch and trunk transactions.
[reference] string Optional reference transaction hash
[callback] Callback Optional callback function

This method takes an array of transaction trytes that don't include a proof of work or

Then, the method calls the following to finalize the bundle and send it to the node:

Note: Before calling this method, we recommend saving your transaction trytes in local storage. By doing so, you make sure that you can always reattach your transactions to the Tangle in case they remain in a pending state.

Related methods

To create transaction trytes that don't include a proof of work or trunk and branch transactions, use the prepareTransfers() method.

Example

prepareTransfers(seed, transfers)
  .then(trytes => {
     return iota.sendTrytes(trytes, depth, minWeightMagnitude)
  })
  .then(bundle => {
    console.log(`Successfully attached transactions to the Tangle`);
    console.log(JSON.stringify(bundle));
  }).catch(error => {
    console.log(`Something went wrong: ${error}`)
  })

core.storeAndBroadcast(trytes, [callback])

Summary: Sends the given transaction trytes to the connected IRI node.
Fulfil: Trytes[] transactionTrytes - Attached transaction trytes
Reject: Error error - An error that contains one of the following:

  • INVALID_TRANSACTION_TRYTES: Make sure the trytes can be converted to a valid transaction object
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
trytes Array.<Trytes> Array of transaction trytes
[callback] Callback Optional callback function

This method uses the connected IRI node's broadcastTransactions and storeTransactions endpoints to send it the given transaction trytes.

Note: Before calling this method, we recommend saving your transaction trytes in local storage. By doing so, you make sure that you can always reattach your transactions to the Tangle in case they remain in a pending state.

Related methods

The given transaction trytes must be in a valid bundle and must include a proof of work.

To create a valid bundle, use the prepareTransfers() method. For more information about what makes a bundles and transactions valid, see this guide.

To do proof of work, use one of the following methods:

Example

storeAndBroadcast(trytes)
.then(transactionTrytes => {
    console.log(`Successfully sent transactions to the node`);
    console.log(JSON.stringify(transactionTrytes));
}).catch(error => {
    console.log(`Something went wrong: ${error}`)
})

core.storeAndBroadcast(trytes, [callback])

Summary: Stores the given transaction trytes on the connected IRI node.
Fullfil: Trytes[] transactionTrytes - Attached transaction trytes
Reject: Error error - An error that contains one of the following:

  • INVALID_TRANSACTION_TRYTES: Make sure the trytes can be converted to a valid transaction object
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Description
trytes Array.<Trytes> Array of transaction trytes
[callback] Callback Optional callback function

This method uses the connected IRI node's storeTransactions endpoint to store the given transaction trytes.

Note: Before calling this method, we recommend saving your transaction trytes in local storage. By doing so, you make sure that you can always reattach your transactions to the Tangle in case they remain in a pending state.

Related methods

The given transaction trytes must be in a valid bundle and must include a proof of work.

To create a valid bundle, use the prepareTransfers() method. For more information about what makes a bundles and transactions valid, see this guide.

To do proof of work, use one of the following methods:

Example

storeTransactions(trytes)
.then(transactionTrytes => {
    console.log(`Successfully stored transactions on the node`);
    console.log(JSON.stringify(transactionTrytes));
}).catch(error => {
    console.log(`Something went wrong: ${error}`)
})

core.traverseBundle(trunkTransaction, [bundle], [callback])

Summary: Gets all transaction in the bundle of a given tail transaction hash.
Fulfil: Transaction[] bundle - Array of transaction objects
Reject: Error error - An error that contains one of the following:

  • INVALID_TRANSACTION_HASH: Make sure the tail transaction hash is 81 trytes long -INVALID_TAIL_TRANSACTION: Make sure that the tail transaction hash is for a transaction whose currentIndex field is 0
  • INVALID_BUNDLE: Check the tail transaction's bundle for the following:
    • Addresses in value transactions have a 0 trit at the end, which means they were generated using the Kerl hashing function
    • Transactions in the bundle array are in the same order as their currentIndex field
    • The total value of all transactions in the bundle sums to 0
    • The bundle hash is valid
  • Fetch error: The connected IOTA node's API returned an error. See the list of error messages
Param Type Default Description
trunkTransaction Hash Tail transaction hash
[bundle] Hash [] Array of existing transaction objects to include in the returned bundle
[callback] Callback Optional callback function

Gets all transactions in the bundle of a given tail transaction hash, by traversing its trunkTransaction field.

Note: This method does not validate the bundle.

Related methods

To get and validate all transactions in a bundle, use the getBundle() method.

Example

traverseBundle(tailTransactionHash)
.then(bundle => {
    console.log(`Successfully found the following transactions in the bundle:`);
    console.log(JSON.stringify(bundle));
}).catch(error => {
    console.log(`Something went wrong: ${error}`)
})

core.generateAddress(seed, index, [security], [checksum])

Summary: Generates an address with a specific index and security level.
Throws:

  • errors.INVALID_SEED : Make sure that the seed contains only trytes
  • errors.INVALID_SECURITY_LEVEL : Make sure that the security level is a number between 1 and 3
Param Type Default Description
seed string The seed to use to generate the address
index number The key index to use to generate the address
[security] number 2 The security level to use to generate the address
[checksum] boolean false Whether to add the checksum

Generates an address, according to the given seed, index, and security level.

Note: This method does not check if the address is spent.

Related methods

To generate an address that has a lower probability of being spent, use the getNewAddress() method.

Returns: Hash - address - An 81-tryte address
Example

const myAddress = generateAddress(seed, 0);

Package Sidebar

Install

npm i @iota/core

Weekly Downloads

237

Version

1.0.0-beta.30

License

MIT

Unpacked Size

6.74 MB

Total Files

355

Last publish

Collaborators

  • tuditi
  • msarcevic
  • braniota
  • lmoe
  • domschiener
  • lexerr
  • martyniota
  • nothingismagick
  • laumair
  • iota_ci
  • rubenkoch
  • brord