From 238b19121e70afe3fc26469313f9af09f2c8b798 Mon Sep 17 00:00:00 2001 From: Umair Sarfraz Date: Mon, 8 Jun 2020 22:28:43 +0500 Subject: [PATCH 1/2] feat: remove tips parameter from getInclusionStates IRI version 1.8.6 [removes](https://github.com/iotaledger/iri/pull/1685/files) tip parameter from getInclusionStates api call. This commit removes the support for tips parameter. getLatestInclusion() is also removed. getLatestInclusion() basically fetched the states by passing latest solid subtangle milestone. It is no longer necessary as IRI now uses latest subtangle milestone by default. Related: https://github.com/iotaledger/iri/issues/1851 --- packages/account/src/account.ts | 2 +- packages/account/src/preset.ts | 10 +- packages/bundle-validator/README.md | 54 +- packages/bundle/README.md | 132 +- packages/checksum/README.md | 82 +- packages/converter/README.md | 156 +- packages/core/README.md | 1749 +++++++++-------- packages/core/src/composeAPI.ts | 20 +- .../core/src/createGetBundlesFromAddresses.ts | 15 +- packages/core/src/createGetInclusionStates.ts | 43 +- packages/core/src/createGetLatestInclusion.ts | 73 - packages/core/src/createIsReattachable.ts | 4 +- packages/core/src/index.ts | 2 - .../integration/getInclusionStates.test.ts | 14 +- .../integration/nocks/getInclusionStates.ts | 1 - packages/extract-json/README.md | 47 +- packages/http-client/README.md | 108 +- packages/http-client/test/batchedSend.ts | 3 - .../test/isBatchableCommand.test.ts | 1 - packages/signing/README.md | 204 +- packages/transaction-converter/README.md | 83 +- packages/transaction/README.md | 343 +++- packages/types.ts | 1 - packages/unit-converter/README.md | 31 +- packages/validators/README.md | 78 +- 25 files changed, 1912 insertions(+), 1344 deletions(-) delete mode 100644 packages/core/src/createGetLatestInclusion.ts diff --git a/packages/account/src/account.ts b/packages/account/src/account.ts index 1d51fd4eb..acf66dae6 100644 --- a/packages/account/src/account.ts +++ b/packages/account/src/account.ts @@ -82,7 +82,7 @@ export interface Network { readonly getBalances: API['getBalances'] readonly getBalance: (address: Trytes) => Promise readonly getConsistency: API['checkConsistency'] - readonly getLatestInclusion: API['getLatestInclusion'] + readonly getInclusionStates: API['getInclusionStates'] readonly getTrytes: API['getTrytes'] readonly sendTrytes: API['sendTrytes'] readonly setSettings: API['setSettings'] diff --git a/packages/account/src/preset.ts b/packages/account/src/preset.ts index 4b98adadb..c64c3afb3 100644 --- a/packages/account/src/preset.ts +++ b/packages/account/src/preset.ts @@ -18,7 +18,7 @@ import { createFindTransactions, createGetBalances, createGetBundlesFromAddresses, - createGetLatestInclusion, + createGetInclusionStates, createGetTransactionsToApprove, createGetTrytes, createIsAddressUsed, @@ -76,14 +76,14 @@ export function networkAdapter({ provider }: NetworkParams): Network { const httpClient = createHttpClient({ provider }) const getBalances = createGetBalances(httpClient) const getTrytes = createGetTrytes(httpClient) - const getLatestInclusion = createGetLatestInclusion(httpClient) + const getInclusionStates = createGetInclusionStates(httpClient) return { getTrytes: hashes => (hashes.length > 0 ? getTrytes(hashes) : Promise.resolve([])), getBalance: (address): Promise => getBalances([address], 100).then(({ balances }) => balances[0]), getBalances, getConsistency: createCheckConsistency(httpClient), - getLatestInclusion: hashes => (hashes.length > 0 ? getLatestInclusion(hashes) : Promise.resolve([])), + getInclusionStates: hashes => (hashes.length > 0 ? getInclusionStates(hashes) : Promise.resolve([])), getBundlesFromAddresses: createGetBundlesFromAddresses(httpClient, 'lib'), findTransactions: createFindTransactions(httpClient), sendTrytes: createSendTrytes(httpClient), @@ -407,7 +407,7 @@ export function transactionAttachment(this: any, params: TransactionAttachmentPa getTransactionsToApprove, attachToTangle, getTrytes, - getLatestInclusion, + getInclusionStates, getConsistency, } = network @@ -439,7 +439,7 @@ export function transactionAttachment(this: any, params: TransactionAttachmentPa pastAttachments.map(trytes => tritsToTrytes(transactionHash(trytesToTrits(trytes)))) ) .then(pastAttachmentHashes => - getLatestInclusion(pastAttachmentHashes).tap(inclusionStates => { + getInclusionStates(pastAttachmentHashes).tap(inclusionStates => { if (inclusionStates.indexOf(true) > -1) { return persistence.del(['0', tritsToTrytes(bundleHash(bundle))].join(':')) } diff --git a/packages/bundle-validator/README.md b/packages/bundle-validator/README.md index 4e8866874..3690fed30 100644 --- a/packages/bundle-validator/README.md +++ b/packages/bundle-validator/README.md @@ -20,29 +20,53 @@ yarn add @iota/bundle-validator * [bundle-validator](#module_bundle-validator) - * [~validateSignatures(bundle)](#module_bundle-validator..validateSignatures) + * [.validateBundleSignatures(bundle)](#module_bundle-validator.validateBundleSignatures) - * [~isBundle(bundle)](#module_bundle-validator..isBundle) + * [.isBundle(bundle)](#module_bundle-validator.isBundle) - + -### *bundle-validator*~validateSignatures(bundle) +### *bundle-validator*.validateBundleSignatures(bundle) +**Summary**: Validates the signatures in a given bundle -| Param | Type | -| --- | --- | -| bundle | Array.<Transaction> | +| Param | Type | Description | +| --- | --- | --- | +| bundle | Array.<Transaction> | Transaction trytes | -Validates all signatures of a bundle. +This method takes an array of transaction trytes and checks if the signatures are valid. - +## Related methods -### *bundle-validator*~isBundle(bundle) +To get a bundle's transaction trytes from the Tangle, use the [`getBundle()`](#module_core.getBundle) method. -| Param | Type | -| --- | --- | -| bundle | Array.<Transaction> | +**Returns**: boolean - Whether the signatures are valid +**Example** +```js +let valid = Validator.validateBundleSignatures(bundle); +``` + + +### *bundle-validator*.isBundle(bundle) +**Summary**: Validates the structure and contents of a given bundle. + +| Param | Type | Description | +| --- | --- | --- | +| bundle | Array.<Transaction> | Transaction trytes | + +This method takes an array of transaction trytes and validates whether they form a valid bundle by checking the following: -Checks if a bundle is _syntactically_ valid. -Validates signatures and overall structure. +- 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 +## Related methods + +To get a bundle's transaction trytes from the Tangle, use the [`getBundle()`](#module_core.getBundle) method. + +**Returns**: boolean - bundle - Whether the bundle is valid +**Example** +```js +let bundle = Validator.isBundle(bundle); +``` diff --git a/packages/bundle/README.md b/packages/bundle/README.md index d4cd68255..3d7117358 100644 --- a/packages/bundle/README.md +++ b/packages/bundle/README.md @@ -21,79 +21,119 @@ yarn add @iota/bundle * [bundle](#module_bundle) - * [~createBundle([entries])](#module_bundle..createBundle) + * _static_ + * [.addEntry(entry, bundle)](#module_bundle.addEntry) - * [~addEntry(entry, bundle)](#module_bundle..addEntry) + * [.finalizeBundle(bundle)](#module_bundle.finalizeBundle) - * [~finalizeBundle(bundle)](#module_bundle..finalizeBundle) + * [.addSignatureOrMessage(bundle, signatureOrMessage, index)](#module_bundle.addSignatureOrMessage) - * [~addSignatureOrMessage(bundle, signatureOrMessage, index)](#module_bundle..addSignatureOrMessage) + * _inner_ + * [~createBundle([entries])](#module_bundle..createBundle) - * [~valueSum(bundle, offset, length)](#module_bundle..valueSum) + - +### *bundle*.addEntry(entry, bundle) +**Summary**: Adds the given transaction entry to a bundle array. +**Throws**: -### *bundle*~createBundle([entries]) +- errors.ILLEGAL\_TRANSACTION\_BUFFER\_LENGTH : Make sure that the `bundle` argument contains valid transaction trits +- errors.ILLEGAL\_SIGNATURE\_OR\_MESSAGE\_LENGTH : Make sure that the `entry.signatureOrMessage` argument contains 6,561 trits +- errors.ILLEGAL\_ADDRESS\_LENGTH : Make sure that the `entry.address` argument contains 243 trits +- errors.ILLEGAL\_VALUE\_LENGTH : Make sure that the `entry.value` argument contains 6,561 trits +- errors.ILLEGAL\_ISSUANCE\_TIMESTAMP\_LENGTH : Make sure that the `entry.timestamp` argument contains 81 trits -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| [entries] | Array.<BundleEntry> | [] | Entries of single or multiple transactions with the same address | -Creates a bundle with given transaction entries. +| Param | Type | Description | +| --- | --- | --- | +| entry | object | Transaction entry object | +| entry.address | Int8Array | An address in trits | +| entry.value | Int8Array | An amount of IOTA tokens in trits | +| [entry.signatureOrMessage] | Int8Array | Signature fragments or a message in trits | +| [entry.issuanceTimestamp] | Int8Array | Unix epoch in trits | +| [entry.tag] | Int8Array | (deprecated) | +| bundle | Int8Array | Bundle array to which to add the entry object | + +Adds transaction trits in the given entry object to a given bundle array. + +## Related methods + +See the [converter](https://github.com/iotaledger/iota.js/tree/next/packages/converter) package for methods that convert values to trits. + +**Returns**: Int8Array - A copy of the original bundle that also includes the added entries. +**Example** +```js +let bundle = new Int8Array(); + +bundle = Bundle.addEntry(bundle, { + address: Converter.trytesToTrits(outputAddress), + value: Converter.valueToTrits(value), + issuanceTimestamp: Converter.valueToTrits(Math.floor(Date.now() / 1000)); +}); +``` + + +### *bundle*.finalizeBundle(bundle) +**Summary**: Generates a bundle hash. +**Throws**: -**Returns**: Array.<Int8Array> - List of transactions in the bundle - +- errors.ILLEGAL\_TRANSACTION\_BUFFER\_LENGTH : Make sure that the `bundle` argument contains valid transaction trits -### *bundle*~addEntry(entry, bundle) | Param | Type | Description | | --- | --- | --- | -| entry | object | Entry of a single or multiple transactions with the same address. | -| entry.address | Int8Array | Address. | -| entry.value | Int8Array | Value to transfer in iotas. | -| [entry.signatureOrMessage] | Int8Array | Signature or message fragment(s). | -| [entry.timestamp] | Int8Array | Issuance timestamp (in seconds). | -| [entry.tag] | Int8Array | Optional Tag, **Deprecated**. | -| bundle | Int8Array | Bundle buffer. | +| bundle | Int8Array | Transaction trits | -Adds given transaction entry to a bundle. +This method takes an array of transaction trits, generates the bundle hash, and adds it to each transaction. -**Returns**: Int8Array - Bundle copy with new entries. - +## Related methods -### *bundle*~finalizeBundle(bundle) +See the [`addEntry()`](#module_bundle.addEntry) method for creating new bundles. -| Param | Type | Description | -| --- | --- | --- | -| bundle | Int8Array | Bundle transaction trits | +**Returns**: Int8Array - Transaction trits that include a bundle hash +**Example** +```js +const result = Bundle.finalizeBundle(bundle); +``` + -Finalizes a bundle by calculating the bundle hash. +### *bundle*.addSignatureOrMessage(bundle, signatureOrMessage, index) +**Summary**: Adds signature message fragments to transactions in a bundle. +**Throws**: -**Returns**: Int8Array - List of transactions in the finalized bundle - +- errors.ILLEGAL\_TRANSACTION\_BUFFER\_LENGTH : Make sure that the `bundle` argument contains valid transaction trits +- errors.ILLEGAL\_TRANSACTION\_INDEX : Make sure that the `index` argument is a number and that the bundle contains enough transactions +- errors.ILLEGAL\_SIGNATURE\_OR\_MESSAGE\_LENGTH : Make sure that the `signatureOrMessage` argument contains at least 6,561 trits -### *bundle*~addSignatureOrMessage(bundle, signatureOrMessage, index) | Param | Type | Description | | --- | --- | --- | -| bundle | Int8Array | Bundle buffer. | -| signatureOrMessage | Int8Array | Signature or message to add. | -| index | number | Transaction index as entry point for signature or message fragments. | +| bundle | Int8Array | Transaction trits | +| signatureOrMessage | Int8Array | Signature or message to add to the bundle | +| index | number | Transaction index at which to start adding the signature or message | -Adds signature message fragments to transactions in a bundle starting at offset. +This method takes an array of transaction trits, and add the given message or signature to the transactions, starting from the given index. -**Returns**: Int8Array - List of transactions in the updated bundle - +If the signature or message is too long to fit in a single transaction, it is split across the next transaction in the bundle, starting from the given index. -### *bundle*~valueSum(bundle, offset, length) +## Related methods -| Param | Type | Description | -| --- | --- | --- | -| bundle | Int8Array | Bundle buffer. | -| offset | number | Offset from the start of the bundle buffer. | -| length | number | Length of transactions in which values should be summed. | +See the [`addEntry()`](#module_bundle.addEntry) method for creating new bundles. + +**Returns**: Int8Array - Transaction trits that include a bundle hash. +**Example** +```js +const signature = Converter.trytesToTrits('SIGNATURE...') +bundle.set(Bundle.addSignatureOrMessage(bundle, signature, 1)); +``` + -Sums up transaction values in a bundle starting at offset. +### *bundle*~createBundle([entries]) +**Summary**: Creates a bundle array from the given transaction entries. + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [entries] | Array.<BundleEntry> | [] | Entries of single or multiple transactions with the same address | -**Returns**: number - Total value of 'length' transactions in the bundle starting at offset. +**Returns**: Array.<Int8Array> - List of transactions in the bundle diff --git a/packages/checksum/README.md b/packages/checksum/README.md index f8fd79ecd..deb9e9e90 100644 --- a/packages/checksum/README.md +++ b/packages/checksum/README.md @@ -17,37 +17,83 @@ yarn add @iota/checksum ## API Reference - + + +### *checksum*.addChecksum(input, [checksumLength], [isAddress]) +**Summary**: Generates a checksum and appends it to the given trytes. +**Throws**: + +- errors.INVALID\_ADDRESS : Make sure that the given address is 90 trytes long. +- errors.INVALID\_TRYTES : Make sure that the `input` argument contains only [trytes](https://docs.iota.org/docs/getting-started/0.1/introduction/ternary) +- errors.INVALID\_CHECKSUM\_LENGTH : Make sure that the `checksumLength` argument is a number greater than or equal to 3. If the `isAddress` argument is set to true, make sure that the `checksumLength` argument is 9. -### *checksum*~addChecksum(input, [checksumLength], [isAddress]) | Param | Type | Default | Description | | --- | --- | --- | --- | -| input | string | | Input trytes | -| [checksumLength] | number | 9 | Checksum trytes length | -| [isAddress] | boolean | true | Flag to denote if given input is address. Defaults to `true`. | +| input | string | | 81 trytes to which to append the checksum | +| [checksumLength] | number | 9 | Length of the checksum to generate | +| [isAddress] | boolean | true | Whether the input is an address | + +This method takes 81 trytes, which could be an address or a seed, generates the [checksum](https://docs.iota.org/docs/getting-started/0.1/clients/checksums) and appends it to the trytes. -Generates and appends the 9-tryte checksum of the given trytes, usually an address. +To generate a checksum that is less than 9 trytes long, make sure to set the `isAddress` argument to false. -**Returns**: string - Address (with checksum) - +## Related methods + +To generate an address, use the [`getNewAddress()`](#module_core.getNewAddress) method. + +**Returns**: string - The original trytes with an appended checksum. +**Example** +```js +let addressWithChecksum = Checksum.addChecksum('ADDRESS...'); +``` + + +### *checksum*.removeChecksum(input) +**Summary**: Removes the checksum from the given address. +**Throws**: + +- errors.INVALID\_ADDRESS : Make sure that the given address is 90 trytes long. -### *checksum*~removeChecksum(input) | Param | Type | Description | | --- | --- | --- | -| input | string | Input trytes | +| input | string | Address from which to remove the checksum | + +This method takes an address of 90 trytes, and removes the last 9 trytes to return the address without a checksum. -Removes the 9-trytes checksum of the given input. +## Related methods -**Returns**: string - Trytes without checksum - +To generate an address, use the [`getNewAddress()`](#module_core.getNewAddress) method. +To add a checksum to an address, use the [`addChecksum()`](#module_checksum.addChecksum) method. -### *checksum*~isValidChecksum(addressWithChecksum) +**Returns**: string - The original address without the appended checksum. +**Example** +```js +let addressWithoutChecksum = Checksum.removeChecksum('ADDRESS...'); +``` + + +### *checksum*.isValidChecksum(addressWithChecksum) +**Summary**: Validates the checksum of an address. +**Throws**: + +- errors.INVALID\_ADDRESS : Make sure that the given address is 90 trytes long. -| Param | Type | -| --- | --- | -| addressWithChecksum | string | -Validates the checksum of the given address trytes. +| Param | Type | Description | +| --- | --- | --- | +| addressWithChecksum | string | Address with a checksum | +This method takes an address of 90 trytes, and checks if the checksum is valid. + +## Related methods + +To generate an address, use the [`getNewAddress()`](#module_core.getNewAddress) method. +To add a checksum to an address, use the [`addChecksum()`](#module_checksum.addChecksum) method. + +**Returns**: boolean - Whether the checksum is valid. +**Example** +```js +let valid = Checksum.isValidChecksum('ADDRESS...'); +``` diff --git a/packages/converter/README.md b/packages/converter/README.md index b219116fb..b0e302dc7 100644 --- a/packages/converter/README.md +++ b/packages/converter/README.md @@ -24,108 +24,152 @@ yarn add @iota/converter * [.trytesToAscii(trytes)](#module_converter.trytesToAscii) - * [.trits(input)](#module_converter.trits) + * [.trytesToTrits(input)](#module_converter.trytesToTrits) - * [.trytes(trits)](#module_converter.trytes) + * [.tritsToTrytes(input)](#module_converter.tritsToTrytes) - * [.value(trits)](#module_converter.value) + * [.tritsToValue(input)](#module_converter.tritsToValue) - * [.fromValue(value)](#module_converter.fromValue) + * [.valueToTrits(input)](#module_converter.valueToTrits) ### *converter*.asciiToTrytes(input) +**Summary**: Converts ASCII characters to trytes. +**Throws**: + +- errors.INVALID\_ASCII\_CHARS : Make sure that the `input` argument contains only valid ASCII characters. + | Param | Type | Description | | --- | --- | --- | -| input | string | ascii input | +| input | string | ASCII input | -Converts an ascii encoded string to trytes. +This method converts ASCII characters to [trytes](https://docs.iota.org/docs/getting-started/0.1/introduction/ternary). -### How conversion works: +## Related methods -An ascii value of `1 Byte` can be represented in `2 Trytes`: +To convert trytes to ASCII characters, use the [`trytesToAscii()`](#module_converter.trytesToAscii) method. + +**Returns**: string - Trytes +**Example** +```js +let trytes = Converter.asciiToTrytes('Hello, where is my coffee?'); +``` + + +### *converter*.trytesToAscii(trytes) +**Summary**: Converts trytes to ASCII characters. +**Throws**: -1. We get the decimal unicode value of an individual ASCII character. +- errors.INVALID\_TRYTES : Make sure that the `trytes` argument contains only valid trytes (A-Z or 9). +- errors.INVALID\_ODD\_LENGTH : Make sure that the `trytes` argument contains an even number of trytes. -2. From the decimal value, we then derive the two tryte values by calculating the tryte equivalent -(e.g.: `100` is expressed as `19 + 3 * 27`), given that tryte alphabet contains `27` trytes values: - a. The first tryte value is the decimal value modulo `27` (which is the length of the alphabet). - b. The second value is the remainder of `decimal value - first value` devided by `27`. -3. The two values returned from Step 2. are then input as indices into the available -trytes alphabet (`9ABCDEFGHIJKLMNOPQRSTUVWXYZ`), to get the correct tryte value. +| Param | Type | Description | +| --- | --- | --- | +| trytes | string | An even number of trytes | -### Example: +This method converts trytes to ASCII characters. -Lets say we want to convert ascii character `Z`. +Because each ASCII character is represented as 2 trytes, the given trytes must be of an even length. -1. `Z` has a decimal unicode value of `90`. +## Related methods -2. `90` can be represented as `9 + 3 * 27`. To make it simpler: - a. First value is `90 % 27 = 9`. - b. Second value is `(90 - 9) / 27 = 3`. +To convert ASCII characters to trytes, use the [`asciiToTrytes()`](#module_converter.asciiToTrytes) method. -3. Our two values are `9` and `3`. To get the tryte value now we simply insert it as indices -into the tryte alphabet: - a. The first tryte value is `'9ABCDEFGHIJKLMNOPQRSTUVWXYZ'[9] = I` - b. The second tryte value is `'9ABCDEFGHIJKLMNOPQRSTUVWXYZ'[3] = C` +**Returns**: string - ASCII characters +**Example** +```js +let message = Converter.trytesToAscii('IOTA'); +``` + -Therefore ascii character `Z` is represented as `IC` in trytes. +### *converter*.trytesToTrits(input) +**Summary**: Converts trytes to trits. +**Throws**: -**Returns**: string - string of trytes - +- errors.INVALID\_TRYTES : Make sure that the `input` argument contains only valid trytes (A-Z or 9). -### *converter*.trytesToAscii(trytes) | Param | Type | Description | | --- | --- | --- | -| trytes | string | trytes | +| input | String \| number | Trytes | + +This method converts [trytes](https://docs.iota.org/docs/getting-started/0.1/introduction/ternary) to trits. + +## Related methods -Converts trytes of _even_ length to an ascii string +To convert ASCII characters to trytes, use the [`asciiToTrytes()`](#module_converter.asciiToTrytes) method. -**Returns**: string - string in ascii - +**Returns**: Int8Array - trits +**Example** +```js +let trits = Converter.trytesToTrits('IOTA'); +``` + + +### *converter*.tritsToTrytes(input) +**Summary**: Converts trits to trytes. +**Throws**: + +- errors.INVALID\_TRITS : Make sure that the `input` argument contains an array of trits. -### *converter*.trits(input) | Param | Type | Description | | --- | --- | --- | -| input | String \| Number | Tryte string or value to be converted. | +| input | String \| number | Trits | -Converts trytes or values to trits +This method converts [trits](https://docs.iota.org/docs/getting-started/0.1/introduction/ternary) to trytes. -**Returns**: Int8Array - trits - +## Related methods + +To convert trytes to ASCII characters, use the [`trytesToAscii()`](#module_converter.trytesToAscii) method. + +**Returns**: Int8Array - trytes +**Example** +```js +let trytes = Converter.tritsToTrytes(trits); +``` + -### *converter*.trytes(trits) +### *converter*.tritsToValue(input) +**Summary**: Converts trits to a number. -| Param | Type | -| --- | --- | -| trits | Int8Array | +| Param | Type | Description | +| --- | --- | --- | +| input | String \| number | Trits | -Converts trits to trytes +This method converts [trits](https://docs.iota.org/docs/getting-started/0.1/introduction/ternary) to a number. -**Returns**: String - trytes - +## Related methods -### *converter*.value(trits) +To convert trytes to trits, use the [`trytesToTrits()`](#module_converter.trytesToTrits) method. +To convert trits to trytes, use the [`tritsToTrytes()`](#module_converter.tritsToTrytes) method. -| Param | Type | -| --- | --- | -| trits | Int8Array | +**Returns**: Int8Array - number +**Example** +```js +let number = Converter.tritsToValue(trits); +``` + -Converts trits into an integer value +### *converter*.valueToTrits(input) +**Summary**: Converts trits to a number. - +| Param | Type | Description | +| --- | --- | --- | +| input | String \| number | Number | -### *converter*.fromValue(value) +This method converts a number to [trits](https://docs.iota.org/docs/getting-started/0.1/introduction/ternary). -| Param | Type | -| --- | --- | -| value | Number | +## Related methods -Converts an integer value to trits +To convert trits to trytes, use the [`tritsToTrytes()`](#module_converter.tritsToTrytes) method. **Returns**: Int8Array - trits +**Example** +```js +let trits = Converter.valueToTrits(9); +``` diff --git a/packages/core/README.md b/packages/core/README.md index 38b135386..ead40e96d 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -29,120 +29,63 @@ yarn add @iota/core * [.composeApi([settings])](#module_core.composeApi) - * [.createAddNeighbors(provider)](#module_core.createAddNeighbors) - - * [.addNeighbors(uris, [callback])](#module_core.addNeighbors) - - * [.createAttachToTangle(provider)](#module_core.createAttachToTangle) + * [.addNeighbors(URIs, [callback])](#module_core.addNeighbors) * [.attachToTangle(trunkTransaction, branchTransaction, minWeightMagnitude, trytes, [callback])](#module_core.attachToTangle) - * [.createBroadcastBundle(provider)](#module_core.createBroadcastBundle) - * [.broadcastBundle(tailTransactionHash, [callback])](#module_core.broadcastBundle) - * [.createBroadcastTransactions(provider)](#module_core.createBroadcastTransactions) - * [.broadcastTransactions(trytes, [callback])](#module_core.broadcastTransactions) - * [.createCheckConsistency(provider)](#module_core.createCheckConsistency) - * [.checkConsistency(transactions, [options], [callback])](#module_core.checkConsistency) - * [.createFindTransactionObjects(provider)](#module_core.createFindTransactionObjects) - * [.findTransactionObjects(query, [callback])](#module_core.findTransactionObjects) - * [.createFindTransactions(provider)](#module_core.createFindTransactions) - * [.findTransactions(query, [callback])](#module_core.findTransactions) - * [.createGetAccountData(provider)](#module_core.createGetAccountData) - * [.getAccountData(seed, options, [callback])](#module_core.getAccountData) - * [.createGetBalances(provider)](#module_core.createGetBalances) - - * [.getBalances(addresses, threshold, [tips], [callback])](#module_core.getBalances) - * [.createGetBundle(provider)](#module_core.createGetBundle) - * [.getBundle(tailTransactionHash, [callback])](#module_core.getBundle) - * [.createGetInclusionStates(provider)](#module_core.createGetInclusionStates) - - * [.getInclusionStates(transactions, tips, [callback])](#module_core.getInclusionStates) - - * [.createGetInputs(provider)](#module_core.createGetInputs) + * [.getInclusionStates(transactions, [callback])](#module_core.getInclusionStates) * [.getInputs(seed, [options], [callback])](#module_core.getInputs) - * [.createGetLatestInclusion(provider)](#module_core.createGetLatestInclusion) - - * [.getLatestInclusion(transactions, tips, [callback])](#module_core.getLatestInclusion) - - * [.createGetNeighbors(provider)](#module_core.createGetNeighbors) + * [.getLatestInclusion(transactions, [callback])](#module_core.getLatestInclusion) * [.getNeighbors([callback])](#module_core.getNeighbors) - * [.createGetNewAddress(provider)](#module_core.createGetNewAddress) - * [.getNewAddress(seed, [options], [callback])](#module_core.getNewAddress) - * [.createGetNodeInfo(provider)](#module_core.createGetNodeInfo) - * [.getNodeInfo([callback])](#module_core.getNodeInfo) - * [.createGetTips(provider)](#module_core.createGetTips) - * [.getTips([callback])](#module_core.getTips) - * [.createGetTransactionObjects(provider)](#module_core.createGetTransactionObjects) - * [.getTransactionObjects(hashes, [callback])](#module_core.getTransactionObjects) - * [.createGetTransactionsToApprove(provider)](#module_core.createGetTransactionsToApprove) - * [.getTransactionsToApprove(depth, [reference], [callback])](#module_core.getTransactionsToApprove) - * [.createGetTrytes(provider)](#module_core.createGetTrytes) - * [.getTrytes(hashes, [callback])](#module_core.getTrytes) - * [.createIsPromotable(provider, [depth])](#module_core.createIsPromotable) - * [.isPromotable(tail, [callback])](#module_core.isPromotable) * [.createPrepareTransfers([provider])](#module_core.createPrepareTransfers) * [.prepareTransfers(seed, transfers, [options], [callback])](#module_core.prepareTransfers) - * [.createPromoteTransaction(provider, [attachFn])](#module_core.createPromoteTransaction) - * [.promoteTransaction(tail, depth, minWeightMagnitude, [spamTransfers], [options], [callback])](#module_core.promoteTransaction) - * [.createRemoveNeighbors(provider)](#module_core.createRemoveNeighbors) - * [.removeNeighbors(uris, [callback])](#module_core.removeNeighbors) - * [.createReplayBundle(provider)](#module_core.createReplayBundle) - * [.replayBundle(tail, depth, minWeightMagnitude, [callback])](#module_core.replayBundle) - * [.createSendTrytes(provider)](#module_core.createSendTrytes) - * [.sendTrytes(trytes, depth, minWeightMagnitude, [reference], [callback])](#module_core.sendTrytes) - * [.createStoreAndBroadcast(provider)](#module_core.createStoreAndBroadcast) - * [.storeAndBroadcast(trytes, [callback])](#module_core.storeAndBroadcast) - * [.createStoreTransactions(provider)](#module_core.createStoreTransactions) - - * [.storeTransactions(trytes, [callback])](#module_core.storeTransactions) - - * [.createTraverseBundle(provider)](#module_core.createTraverseBundle) + * [.storeAndBroadcast(trytes, [callback])](#module_core.storeAndBroadcast) * [.traverseBundle(trunkTransaction, [bundle], [callback])](#module_core.traverseBundle) @@ -152,103 +95,96 @@ yarn add @iota/core ### *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 | | Network provider, defaults to `http-client`. | -| [settings.provider] | string | "http://localhost:14265" | Uri of IRI node | -| [settings.attachToTangle] | function | | Function to override [`attachToTangle`](#module_core.attachToTangle) with | -| [settings.apiVersion] | string \| number | 1 | IOTA Api version to be sent as `X-IOTA-API-Version` header. | -| [settings.requestBatchSize] | number | 1000 | Number of search values per request. | - -Composes API object from it's components +| [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`](#module_core.findTransactions), [`getBalances`](#module_core.getBalances), [`getInclusionStates`](#module_core.getInclusionStates), and [`getTrytes`](#module_core.getTrytes) | + +**Returns**: [API](#API) - iota - API object to use to interact with an IRI node. +**Example** +```js +const Iota = require('@iota/core`); - +const iota = Iota.composeAPI({ + provider: 'https://nodes.devnet.thetangle.org:443' +}); +``` + -### *core*.createAddNeighbors(provider) +### *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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| provider | Provider | Network provider | +| URIs | Array.<string> | Comma-separated URIs of neighbor nodes that you want to add | +| [callback] | Callback | Optional callback function | -**Returns**: function - [`addNeighbors`](#module_core.addNeighbors) - +This method adds temporary neighbors to the connected IRI node by calling the its +[`addNeighbors`](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference#addNeighbors) endpoint. -### *core*.addNeighbors(uris, [callback]) -**Fulfil**: number Number of neighbors that were added -**Reject**: Error -- `INVALID_URI`: Invalid uri -- Fetch error - -| Param | Type | Description | -| --- | --- | --- | -| uris | Array | List of URI's | -| [callback] | Callback | Optional callback | +These neighbors are removed when the node is restarted. -Adds a list of neighbors to the connected IRI node by calling -[`addNeighbors`](https://docs.iota.works/iri/api#endpoints/addNeighbors) command. -Assumes `addNeighbors` command is available on the node. +## Related methods -`addNeighbors` has temporary effect until your node relaunches. +To see statistics about the connected IRI node's neighbors, use the [`getNeighbors()`](#module_core.getNeighbors) method. **Example** ```js -addNeighbors(['udp://148.148.148.148:14265']) - .then(numAdded => { - // ... - }).catch(err => { - // ... +addNeighbors(['tcp://148.148.148.148:15600']) + .then(numberOfNeighbors => { + console.log(`Successfully added ${numberOfNeighbors} neighbors`) + }).catch(error => { + console.log(`Something went wrong: ${error}`) }) ``` - - -### *core*.createAttachToTangle(provider) - -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider | - -**Returns**: function - [`attachToTangle`](#module_core.attachToTangle) ### *core*.attachToTangle(trunkTransaction, branchTransaction, minWeightMagnitude, trytes, [callback]) -**Fulfil**: TransactionTrytes[] Array of transaction trytes with nonce and attachment timestamps -**Reject**: Error -- `INVALID_TRUNK_TRANSACTION`: Invalid `trunkTransaction` -- `INVALID_BRANCH_TRANSACTION`: Invalid `branchTransaction` -- `INVALID_MIN_WEIGHT_MAGNITUDE`: Invalid `minWeightMagnitude` argument -- `INVALID_TRANSACTION_TRYTES`: Invalid transaction trytes -- `INVALID_TRANSACTIONS_TO_APPROVE`: Invalid transactions to approve -- Fetch error +**Summary**: Connects the given transaction trytes into a bundle and sends them to the connected IOTA node to complete [remote proof of work](https://docs.iota.org/docs/getting-started/0.1/transactions/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()`](#module_core.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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| trunkTransaction | Hash | Trunk transaction as returned by [`getTransactionsToApprove`](#module_core.getTransactionsToApprove) | -| branchTransaction | Hash | Branch transaction as returned by [`getTransactionsToApprove`](#module_core.getTransactionsToApprove) | -| minWeightMagnitude | number | Number of minimum trailing zeros in tail transaction hash | -| trytes | Array.<TransactionTrytes> | List of transaction trytes | -| [callback] | Callback | Optional callback | +| trunkTransaction | Hash | Trunk transaction hash | +| branchTransaction | Hash | Branch transaction hash | +| minWeightMagnitude | number | The [minimum weight magnitude](https://docs.iota.org/docs/getting-started/0.1/network/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()`](#module_core.prepareTransfers) method | +| [callback] | Callback | Optional callback function | -Performs the Proof-of-Work required to attach a transaction to the Tangle by -calling [`attachToTangle`](https://docs.iota.works/iri/api#endpoints/attachToTangle) command. -Returns list of transaction trytes and overwrites the following fields: +This method uses the connected IRI node's [`attachToTangle`](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference#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` -This method can be replaced with a local equivalent such as -[`ccurl.interface.js`](https://github.com/iotaledger/ccurl.interface.js) in node.js, -[`curl.lib.js`](https://github.com/iotaledger/curl.lib.js) which works on WebGL 2 enabled browsers -or remote [`PoWbox`](https://powbox.devnet.iota.org/). +**Note:** You can replace this method with your own custom one in the [`composeApi()`](##module_core.composeApi) method. For example, you may want to write a function that does local proof of work, using either the [`ccurl.interface.js`](https://github.com/iotaledger/ccurl.interface.js) NodeJS library, +or the [`curl.lib.js`](https://github.com/iotaledger/curl.lib.js) library for browsers that support WebGL2. + +## Related methods -`trunkTransaction` and `branchTransaction` hashes are given by -[`getTransactionsToApprove`](#module_core.getTransactionsToApprove). +To attach the returned transaction trytes to the Tangle, use the [`broadcastTransactions()`](#module_core.broadcastTransactions) method to send them to a node. -**Note:** Persist the transaction trytes in local storage __before__ calling this command, to ensure -that reattachment is possible, until your bundle has been included. +You can get a trunk and branch transaction hash by calling the +[`getTransactionsToApprove()`](#module_core.getTransactionsToApprove) method **Example** ```js @@ -257,1130 +193,1203 @@ getTransactionsToApprove(depth) attachToTangle(trunkTransaction, branchTransaction, minWeightMagnitude, trytes) ) .then(attachedTrytes => { - // ... - }) - .catch(err => { - // ... + console.log(`Successfully did proof of work. Here are your bundle's transaction trytes: ${attachedTrytes}`) + }).catch(error => { + console.log(`Something went wrong: ${error}`) }) ``` - - -### *core*.createBroadcastBundle(provider) - -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider | - -**Returns**: function - [`broadcastBundle`](#module_core.broadcastBundle) ### *core*.broadcastBundle(tailTransactionHash, [callback]) -**Fulfil**: Transaction[] List of transaction objects -**Reject**: Error -- `INVALID_HASH`: Invalid tail transaction hash -- `INVALID_BUNDLE`: Invalid bundle -- Fetch error +**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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | | tailTransactionHash | Hash | Tail transaction hash | -| [callback] | Callback | Optional callback | +| [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. -Re-broadcasts all transactions in a bundle given the tail transaction hash. -It might be useful when transactions did not properly propagate, -particularly in the case of large bundles. +**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()`](#module_core.prepareTransfers) method. **Example** ```js broadcastBundle(tailHash) - .then(transactions => { - // ... + .then(transactionObjects => { + console.log(`Successfully sent the following bundle to the node:) + console.log(JSON.stringify(transactionObjects)); }) - .catch(err => { - // ... + .catch(error => { + console.log(`Something went wrong: ${error}`) }) ``` - - -### *core*.createBroadcastTransactions(provider) - -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider | - -**Returns**: function - [`broadcastTransactions`](#module_core.broadcastTransactions) ### *core*.broadcastTransactions(trytes, [callback]) -**Fulfil**: Trytes[] Attached transaction trytes -**Reject**: Error -- `INVALID_ATTACHED_TRYTES`: Invalid array of attached trytes -- Fetch error +**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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| trytes | Array.<TransactionTrytes> | Attached Transaction trytes | +| trytes | Array.<TransactionTrytes> | Transaction trytes that include proof of work | | [callback] | Callback | Optional callback | -Broadcasts an list of _attached_ transaction trytes to the network by calling -[`boradcastTransactions`](https://docs.iota.org/iri/api#endpoints/broadcastTransactions) command. -Tip selection and Proof-of-Work must be done first, by calling -[`getTransactionsToApprove`](#module_core.getTransactionsToApprove) and -[`attachToTangle`](#module_core.attachToTangle) or an equivalent attach method or remote -[`PoWbox`](https://powbox.testnet.iota.org/), which is a development tool. +This method sends the given transaction trytes to the connected IRI node, using its +[`broadcastTransactions`](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference#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. -You may use this method to increase odds of effective transaction propagation. +To create a valid bundle, use the `prepareTransfers()` method. For more information about what makes a bundles and transactions valid, see [this guide](https://docs.iota.org/docs/node-software/0.1/iri/concepts/transaction-validation). -**Note:** Persist the transaction trytes in local storage __before__ calling this command, to ensure -that reattachment is possible, until your bundle has been included. +To do proof of work, use one of the following methods: + +- [`attachToTangle()`](#module_core.attachToTangle) +- [`sendTrytes()`](#module_core.sendTrytes) **Example** ```js broadcastTransactions(trytes) - .then(trytes => { - // ... + .then(transactionTrytes => { + console.log(`Successfully sent the following transaction trytes to the node:) + console.log(JSON.stringify(transactionTrytes)); }) - .catch(err => { - // ... + .catch(error => { + console.log(`Something went wrong: ${error}`) }) ``` - + -### *core*.createCheckConsistency(provider) +### *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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) +- Reason for inconsistency if the method was called with the `options.rejectWithReason` argument | Param | Type | Description | | --- | --- | --- | -| provider | Provider | Network provider | +| 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 | -**Returns**: function - [`checkConsistency`](#module_core.checkConsistency) - +This method finds out if a transaction has a chance of being confirmed, using the connected node's +[`checkConsistency`](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference#checkconsistency) endpoint. -### *core*.checkConsistency(transactions, [options], [callback]) -**Fulfil**: boolean Consistency state of given transaction or co-consistency of given transactions. -**Reject**: Error -- `INVALID_TRANSACTION_HASH`: Invalid transaction hash -- Fetch error -- Reason for returning `false`, if called with `options.rejectWithReason` +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 -| Param | Type | Description | -| --- | --- | --- | -| transactions | Hash \| Array.<Hash> | Tail transaction hash (hash of transaction with `currentIndex == 0`), or array of tail transaction hashes | -| [options] | object | Options | -| [options.rejectWithReason] | boolean | Enables rejection if state is `false`, with reason as error message | -| [callback] | Callback | Optional callback | +For more information about what makes a bundles and transactions valid, see [this article](https://docs.iota.org/docs/node-software/0.1/iri/concepts/transaction-validation). -Checks if a transaction is _consistent_ or a set of transactions are _co-consistent_, by calling -[`checkConsistency`](https://docs.iota.org/iri/api#endpoints/checkConsistency) command. -_Co-consistent_ transactions and the transactions that they approve (directly or inderectly), -are not conflicting with each other and rest of the ledger. +As long as a transaction is consistent it has a chance of being confirmed. -As long as a transaction is consistent it might be accepted by the network. -In case a transaction is inconsistent, it will not be accepted, and a reattachment -is required by calling [`replayBundle`](#module_core.replayBundle). +## Related methods + +If a consistent transaction is taking a long time to be confirmed, you can improve its chances, using the +[`promoteTransaction()`](#module_core.promoteTransaction) method. + +If a transaction is inconsistent, it will never be confirmed. In this case, you can reattach the transaction, using the [`replayBundle()`](#module_core.replayBundle) method. **Example** ```js -checkConsistency(tailHash) +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}`); }) ``` -**Example** -##### Example with `checkConsistency` & `isPromotable` - -Consistent transactions might remain pending due to networking issues, -or if not referenced by recent milestones issued by -[Coordinator](https://docs.iota.org/introduction/tangle/consensus). -Therefore `checkConsistency` with a time heuristic can determine -if a transaction should be [_promoted_](#module_core.promoteTransaction) -or [_reattached_](#module_core.replayBundle). -This functionality is abstracted in [`isPromotable`](#module_core.isPromotable). - -```js -const isAboveMaxDepth = attachmentTimestamp => ( - // Check against future timestamps - attachmentTimestamp < Date.now() && - // Check if transaction wasn't issued before last 6 milestones - // Milestones are being issued every ~2mins - Date.now() - attachmentTimestamp < 11 * 60 * 1000 -) - -const isPromotable = ({ hash, attachmentTimestamp }) => ( - checkConsistency(hash) - .then(isConsistent => ( - isConsistent && - isAboveMaxDepth(attachmentTimestamp) - )) -) -``` - + -### *core*.createFindTransactionObjects(provider) +### *core*.findTransactionObjects(query, [callback]) +**Summary**: Searches the Tangle for transaction objects that contain all the given values in their [transaction fields](https://docs.iota.org/docs/getting-started/0.1/transactions/transactions#structure-of-a-transaction). +**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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| provider | Provider | Network provider for accessing IRI | +| 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 | -**Returns**: function - [`findTransactionObjects`](#module_core.findTransactionObjects) - +This method uses the [`findTransactions()`](#module_core.findTransactions) to find transactions with the given fields, then it uses +the [`getTransactionObjects()`](#module_core.getTransactionObjects) method to return the transaction objects. -### *core*.findTransactionObjects(query, [callback]) -**Fulfil**: Transaction[] Array of transaction objects -**Reject**: Error -- `INVALID_SEARCH_KEY` -- `INVALID_HASH`: Invalid bundle hash -- `INVALID_TRANSACTION_HASH`: Invalid approvee transaction hash -- `INVALID_ADDRESS`: Invalid address -- `INVALID_TAG`: Invalid tag -- Fetch error +If you pass more than one query, this method returns only transactions that contain all the given fields in those queries. -| Param | Type | Description | -| --- | --- | --- | -| query | object | | -| [query.addresses] | Array.<Hash> | List of addresses | -| [query.bundles] | Array.<Hash> | List of bundle hashes | -| [query.tags] | Array.<Tag> | List of tags | -| [query.addresses] | Array.<Hash> | List of approvees | -| [callback] | Callback | Optional callback | +## Related methods -Wrapper function for [`findTransactions`](#module_core.findTransactions) and -[`getTrytes`](#module_core.getTrytes). -Searches for transactions given a `query` object with `addresses`, `tags` and `approvees` fields. -Multiple query fields are supported and `findTransactionObjects` returns intersection of results. +To find only transaction hashes, use the [`findTransactions()`](#module_core.findTransactions) method. **Example** -Searching for transactions by address: - ```js -findTransactionObjects({ addresses: ['ADR...'] }) - .then(transactions => { - // ... - }) - .catch(err => { - // ... - }) +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*.createFindTransactions(provider) +### *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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| provider | Provider | Network provider for accessing IRI | +| 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 | -**Returns**: function - [`findTransactionObjects`](#module_core.findTransactions) - +This method searches for transaction hashes by calling the connected IRI node's [`findTransactions`](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference#findTransactions) endpoint. -### *core*.findTransactions(query, [callback]) -**Fulfil**: Hash[] Array of transaction hashes -**Reject**: Error -- `INVALID_SEARCH_KEY` -- `INVALID_HASH`: Invalid bundle hash -- `INVALID_TRANSACTION_HASH`: Invalid approvee transaction hash -- `INVALID_ADDRESS`: Invalid address -- `INVALID_TAG`: Invalid tag -- Fetch error +If you pass more than one query parameter, this method returns only transactions that contain all the given fields in those queries. -| Param | Type | Description | -| --- | --- | --- | -| query | object | | -| [query.addresses] | Array.<Hash> | List of addresses | -| [query.bundles] | Array.<Hash> | List of bundle hashes | -| [query.tags] | Array.<Tag> | List of tags | -| [query.addresses] | Array.<Hash> | List of approvees | -| [callback] | Callback | Optional callback | +## Related methods -Searches for transaction `hashes` by calling -[`findTransactions`](https://docs.iota.org/iri/api#endpoints/findTransactions) command. -It allows to search for transactions by passing a `query` object with `addresses`, `tags` and `approvees` fields. -Multiple query fields are supported and `findTransactions` returns intersection of results. +To find transaction objects, use the [`findTransactionObjects()`](#module_core.findTransactionObjects) method. **Example** ```js -findTransactions({ addresses: ['ADRR...'] }) - .then(hashes => { - // ... - }) - .catch(err => { - // handle errors here - }) +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*.createGetAccountData(provider) - -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider for accessing IRI | - -**Returns**: function - [`getAccountData`](#module_core.getAccountData) ### *core*.getAccountData(seed, options, [callback]) -**Fulfil**: AccountData -**Reject**: Error -- `INVALID_SEED` -- `INVALID_START_OPTION` -- `INVALID_START_END_OPTIONS`: Invalid combination of start & end options` -- Fetch error +**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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Default | Description | | --- | --- | --- | --- | -| seed | string | | | -| options | object | | | -| [options.start] | number | 0 | Starting key index | -| [options.security] | number | 0 | Security level to be used for getting inputs and addresses | -| [options.end] | number | | Ending key index | -| [callback] | Callback | | Optional callback | +| 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](https://docs.iota.org/docs/getting-started/0.1/clients/security-levels) 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](https://docs.iota.org/docs/getting-started/0.1/clients/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](https://docs.iota.org/docs/client-libraries/0.1/how-to-guides/js/generate-an-address) on your local device. It is never sent anywhere. -Returns an `AccountData` object, containing account information about `addresses`, `transactions`, -`inputs` and total account balance. +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](https://docs.iota.org/docs/getting-started/0.1/clients/addresses#spent-addresses). + +## Related methods + +To find the balance of specific addresses, which don't have to belong to your seed, use the [`getBalances()`](#module_core.getBalances) method. + +To find only inputs (objects that contain information about addresses with a postive balance), use the [`getInputs()`](#module_core.getInputs) method. **Example** ```js -getAccountData(seed, { - start: 0, - security: 2 -}) +getAccountData(seed) .then(accountData => { const { addresses, inputs, transactions, balance } = accountData - // ... + console.log(`Successfully found the following transactions:) + console.log(JSON.stringify(transactions)); }) - .catch(err => { - // ... + .catch(error => { + console.log(`Something went wrong: ${error}`) }) ``` - + -### *core*.createGetBalances(provider) +### *core*.getBalances(addresses, threshold, [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 +- `INVALID_THRESHOLD`: Make sure that the threshold is a number greater than zero +- Fetch error: The connected IOTA node's API returned an error. See the [list of error messages](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| provider | Provider | Network provider | +| addresses | Array.<Hash> | Array of addresses | +| threshold | number | Not used, but should be set to 100 until [this issue](https://github.com/iotaledger/iri/issues/1723) is resolved. | +| [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 | -**Returns**: function - [`getBalances`](#module_core.getBalances) - +This method uses the connected IRI node's [`getBalances`](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference#getbalances) endpoint. -### _core_.getBalances(addresses, threshold, [tips], [callback]) -**Fulfil**: Balances Object with list of `balances` and corresponding `milestone` -**Reject**: Error -- `INVALID_HASH`: Invalid address -- `INVALID_THRESHOLD`: Invalid `threshold` -- Fetch error +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. -| Param | Type | Description | -| ---------- | ------------------------------- | ------------------------------------------------------------------------ | -| addresses | Array.<Hash> | List of addresses | -| threshold | number | Confirmation threshold, currently `100` should be used | -| [tips] | Array.<Hash> | List of tips to calculate the balance from the PoV of these transactions | -| [callback] | Callback | Optional callback | +## Related methods -Fetches _confirmed_ balances of given addresses at the latest solid milestone, -by calling [`getBalances`](https://docs.iota.works/iri/api#endpoints/getBalances) command. +To find the balance of all addresses that belong to your seed, use the [`getAccountData()`](#module_core.getAccountData) method. **Example** ```js getBalances([address], 100) - .then(({ balances }) => { - // ... - }) - .catch(err => { - // ... + .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*.createGetBundle(provider) - -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider for accessing IRI | - -**Returns**: function - [`getBundle`](#module_core.getBundle) ### *core*.getBundle(tailTransactionHash, [callback]) -**Fulfil**: Transaction[] Bundle as array of transaction objects -**Reject**: Error -- `INVALID_TRANSACTION_HASH` -- `INVALID_TAIL_HASH`: Provided transaction is not tail (`currentIndex !== 0`) -- `INVALID_BUNDLE`: Bundle is syntactically invalid -- Fetch error +**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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | | tailTransactionHash | Hash | Tail transaction hash | -| [callback] | Callback | Optional callback | +| [callback] | Callback | Optional callback function | -Fetches and validates the bundle given a _tail_ transaction hash, by calling -[`traverseBundle`](#module_core.traverseBundle) and traversing through `trunkTransaction`. +This method uses the [`traverseBundle()`](#module_core.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](https://docs.iota.org/docs/node-software/0.1/iri/concepts/transaction-validation). + +## Related methods + +To find transaction objects that aren't in the same bundle, use the [`getTransactionObjects()`](#module_core.getTransactionObjects) method. **Example** ```js getBundle(tail) .then(bundle => { - // ... - }) - .catch(err => { - // handle errors + console.log(`Bundle found:) + console.log(JSON.stringify(bundle)); + }) + .catch(error => { + console.log(`Something went wrong: ${error}`) }) ``` - + -### *core*.createGetInclusionStates(provider) +### *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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| provider | Provider | Network provider for accessing IRI | - -**Returns**: function - [`getInclusionStates`](#module_core.getInclusionStates) - +| transactions | Array.<Hash> | Array of transaction hashes to check | +| [callback] | Callback | Optional callback function | -### *core*.getInclusionStates(transactions, tips, [callback]) -**Fulfil**: boolean[] Array of inclusion state -**Reject**: Error -- `INVALID_TRANSACTION_HASH`: Invalid `hashes` or `tips` -- Fetch error +This method uses the connected IRI node's [`getInclusionStates`](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference#getinclusionstates) endpoint. -| Param | Type | Description | -| --- | --- | --- | -| transactions | Array.<Hash> | List of transaction hashes | -| tips | Array.<Hash> | List of tips to check if transactions are referenced by | -| [callback] | Callback | Optional callback | +If the given tip transactions reference a given transaction, the returned state is `true`. -Fetches inclusion states of given list of transactions, by calling -[`getInclusionStates`](https://docs.iota.works/iri/api#endpoints/getInclusionsStates) command. +If the given tip transactions do not reference a given transaction, the returned state is `false`. **Example** ```js getInclusionStates(transactions) .then(states => { - // ... - }) - .catch(err => { - // ... + 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*.createGetInputs(provider) - -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider for accessing IRI | - -**Returns**: function - [`getInputs`](#module_core.getInputs) ### *core*.getInputs(seed, [options], [callback]) -**Fulfil**: Inputs Inputs object containg a list of `[Address](Address)` objects and `totalBalance` field -**Reject**: Error -- `INVALID_SEED` -- `INVALID_SECURITY_LEVEL` -- `INVALID_START_OPTION` -- `INVALID_START_END_OPTIONS` -- `INVALID_THRESHOLD` -- `INSUFFICIENT_BALANCE` -- Fetch error +**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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) ` +- `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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Default | Description | | --- | --- | --- | --- | -| seed | string | | | -| [options] | object | | | -| [options.start] | number | 0 | Index offset indicating from which address we start scanning for balance | -| [options.end] | number | | Last index up to which we stop scanning | -| [options.security] | number | 2 | Security level of inputs | -| [options.threshold] | threshold | | Minimum amount of balance required | -| [callback] | Callback | | Optional callback | +| 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](https://docs.iota.org/docs/getting-started/0.1/clients/security-levels) 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](https://docs.iota.org/docs/getting-started/0.1/clients/addresses) for a given seed and finds those that have a positive balance. + +**Note:** The given seed is used to [generate addresses](https://docs.iota.org/docs/client-libraries/0.1/how-to-guides/js/generate-an-address) on your local device. It is never sent anywhere. + +To find a certain amount of [IOTA tokens](https://docs.iota.org/docs/getting-started/0.1/clients/token) and return only the addresses that, when combined, contain that amount, pass it to the `options.threshold` argument. -Creates and returns an `Inputs` object by generating addresses and fetching their latest balance. +## Related methods + +You may want to use this method to find inputs for the [`prepareTransfers()`](#module_core.prepareTransfers) method. **Example** ```js -getInputs(seed, { start: 0, threhold }) +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(err => { - if (err.message === errors.INSUFFICIENT_BALANCE) { - // ... + .catch(error => { + if (error.message === errors.INSUFFICIENT_BALANCE) { + console.log('You have no IOTA tokens'); } - // ... - }) + }); ``` - + -### *core*.createGetLatestInclusion(provider) +### *core*.getLatestInclusion(transactions, [callback]) +**Summary**: Finds out if one or more given transactions are [confirmed or pending](https://docs.iota.org/docs/getting-started/0.1/network/the-tangle#transaction-states). +**Fulfil**: boolean[] states - Array of inclusion states, where `true` means that the transaction is confirmed and `false` means that it's not. +**Reject**: Error error - An error that contains one of the following: +- `INVALID_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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| provider | Provider | Network provider for accessing IRI | +| transactions | Array.<Hash> | List of transactions hashes to check | +| [callback] | Callback | Optional callback function | -**Returns**: function - [`getLatestInclusion`](#module_core.getLatestInclusion) - +This method uses the node's `latestSolidSubtangleMilestone` field as the `tips` argument to make sure that the given transactions are referenced by the node's latest solid milestone. -### *core*.getLatestInclusion(transactions, tips, [callback]) -**Fulfil**: boolean[] List of inclusion states -**Reject**: Error -- `INVALID_HASH`: Invalid transaction hash -- Fetch error +An invalid transaction will always remain in a pending state. -| Param | Type | Description | -| --- | --- | --- | -| transactions | Array.<Hash> | List of transactions hashes | -| tips | number | List of tips to check if transactions are referenced by | -| [callback] | Callback | Optional callback | +**Note:** If a valid transaction is in a pending state for too long, you can [increase its chances of being confirmed](https://docs.iota.org/docs/client-libraries/0.1/how-to-guides/js/confirm-pending-bundle). -Fetches inclusion states of given transactions and a list of tips, -by calling [`getInclusionStates`](#module_core.getInclusionStates) on `latestSolidSubtangleMilestone`. +## Related methods + +To check if transactions are referenced by a non-milestone transaction, use the [`getInclusionStates()`](#module_core.getInclusionStates) method. **Example** ```js -getLatestInclusion(hashes) - .then(states => { - // ... - }) - .catch(err => { - // handle error - }) +iota.getLatestInclusionState(['transactionHash']) +.then(states => { + for(let i = 0; i < states.length; i++){ + states[i]? console.log(`Transaction ${i} is confirmed`) : + console.log(`transaction ${i} is pending`); + } + }) +.catch(error => { + console.log(`Something went wrong: ${error}`); + }); ``` - - -### *core*.createGetNeighbors(provider) - -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider | - -**Returns**: function - [`getNeighbors`](#module_core.getNeighbors) ### *core*.getNeighbors([callback]) -**Fulfil**: Neighbors -**Reject**: Error -- Fetch error +**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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| [callback] | Callback | Optional callback | +| [callback] | Callback | Optional callback function | -Returns list of connected neighbors. +This method uses the connected IRI node's [`getNeighbors`](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference#getneighbors) endpoint to find information about the neighbors' activity. - +All statistics are aggregated until the node restarts. -### *core*.createGetNewAddress(provider) +## Related methods -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider | +To add neighbors to the node, use the [`addNeighbors()`](#module_core.addNeighbors) method. -**Returns**: function - [`getNewAddress`](#module_core.getNewAddress) +**Example** +```js +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]) -**Fulfil**: Hash\|Hash[] New (unused) address or list of addresses up to (and including) first unused address -**Reject**: Error -- `INVALID_SEED` -- `INVALID_START_OPTION` -- `INVALID_SECURITY` -- Fetch error +**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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Default | Description | | --- | --- | --- | --- | -| seed | string | | At least 81 trytes long seed | -| [options] | object | | | -| [options.index] | number | 0 | Key index to start search at | -| [options.security] | number | 2 | Security level | -| [options.checksum] | boolean | false | `Deprecated` Flag to include 9-trytes checksum or not | -| [options.total] | number | | `Deprecated` Number of addresses to generate. | -| [options.returnAll] | boolean | false | `Deprecated` Flag to return all addresses, from start up to new address. | -| [callback] | Callback | | Optional callback | - -Generates and returns a new address by calling [`findTransactions`](#module_core.findTransactions) -until the first unused address is detected. This stops working after a snapshot. +| 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](https://docs.iota.org/docs/getting-started/0.1/clients/security-levels) 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`](#module_core.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](https://docs.iota.org/docs/client-libraries/0.1/how-to-guides/js/generate-an-address) 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](https://docs.iota.org/docs/client-libraries/0.1/account-module/introduction/overview) to keep track of your spent addresses. + +## Related methods + +To find out which of your addresses are spent, use the [`getAccountData()`](#module_core.getAccountData) method. **Example** ```js -getNewAddress(seed, { index }) +getNewAddress(seed) .then(address => { - // ... + console.log(`Here's your new address: ${address}) }) - .catch(err => { - // ... + .catch(error => { + console.log(`Something went wrong: ${error}`); }) ``` - - -### *core*.createGetNodeInfo(provider) - -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider | - -**Returns**: function - [`getNodeInfo`](#module_core.getNodeInfo) ### *core*.getNodeInfo([callback]) -**Fulfil**: NodeInfo Object with information about connected node. -**Reject**: Error -- Fetch error +**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](https://docs.iota.org/docs/node-software/0.1/iri/introduction/overview) +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](https://docs.iota.org/docs/getting-started/0.1/network/the-coordinator) +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](https://docs.iota.org/docs/getting-started/0.1/network/nodes#local-snapshots) 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](https://docs.iota.org/docs/getting-started/0.1/network/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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| [callback] | Callback | Optional callback | +| [callback] | Callback | Optional callback function | + +This method uses the connected IRI node's +[`getNodeInfo`](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference#getnodeinfo) endpoint. -Returns information about connected node by calling -[`getNodeInfo`](https://docs.iota.works/iri/api#endpoints/getNodeInfo) command. +## Related methods + +To get statistics about the connected node's neighbors, use the [`getNeighbors()`](#module_core.getNeighbors) method. **Example** ```js getNodeInfo() - .then(info => console.log(info)) - .catch(err => { - // ... + .then(info => console.log(JSON.stringify(info))) + .catch(error => { + console.log(`Something went wrong: ${error}`); }) ``` - - -### *core*.createGetTips(provider) - -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider | - -**Returns**: function - [`getTips`](#module_core.getTips) ### *core*.getTips([callback]) -**Fulfil**: Hash[] List of tip hashes -**Reject**: Error -- Fetch error +**Summary**: Searches the Tangle for tip transactions. +**Fulfil**: Hash[] tips - Array of tip transaction hashes +**Reject**: Error error - Fetch error: The connected IOTA node's API returned an error. See the [list of error messages](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| [callback] | Callback | Optional callback | +| [callback] | Callback | Optional callback function | + +This method finds all transactions that aren't referenced by other transactions in the Tangle +by calling the connected IRI node's [`getTips`](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference#gettips) endpoint. -Returns a list of tips (transactions not referenced by other transactions), -as seen by the connected node. +## Related methods + +To find two consistent tip transactions to use as branch and trunk transactions, use the [`getTransactionsToApprove()`](#module_core.getTransactionsToApprove) method. **Example** ```js getTips() .then(tips => { - // ... + console.log('Found the following tip transactions:'); + console.log(JSON.stringify(tips)); }) - .catch(err => { - // ... + .catch(error => { + console.log(`Something went wrong: ${error}`); }) ``` - - -### *core*.createGetTransactionObjects(provider) - -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider | - -**Returns**: function - [`getTransactionObjects`](#module_core.getTransactionObjects) ### *core*.getTransactionObjects(hashes, [callback]) -**Fulfil**: Transaction[] - List of transaction objects -**Reject**: Error -- `INVALID_TRANSACTION_HASH` -- Fetch error +**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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | | hashes | Array.<Hash> | Array of transaction hashes | -| [callback] | function | Optional callback | +| [callback] | function | Optional callback function | -Fetches the transaction objects, given an array of transaction hashes. +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()`](#module_core.getBundle) method. **Example** ```js -getTransactionObjects(hashes) - .then(transactions => { - // ... - }) - .catch(err => { - // handle errors +getTransactionObjects(transactionHashes) + .then(transactionObjects => { + console.log('Found the following transactions:'); + console.log(JSON.stringify(transactionObjects)); }) + .catch(error => { + console.log(`Something went wrong: ${error}`); + }); ``` - - -### *core*.createGetTransactionsToApprove(provider) - -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider | - -**Returns**: function - [`getTransactionsToApprove`](#module_core.getTransactionsToApprove) ### *core*.getTransactionsToApprove(depth, [reference], [callback]) -**Fulfil**: trunkTransaction, branchTransaction A pair of approved transactions -**Reject**: Error -- `INVALID_DEPTH` -- `INVALID_REFERENCE_HASH`: Invalid reference hash -- Fetch error +**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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| depth | number | The depth at which Random Walk starts. A value of `3` is typically used by wallets, meaning that RW starts 3 milestones back. | -| [reference] | Hash | Optional reference transaction hash | -| [callback] | Callback | Optional callback | +| depth | number | The [depth](https://docs.iota.org/docs/getting-started/0.1/transactions/depth) at which to start the weighted random walk. The [Trinity wallet](https://trinity.iota.org/) 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](#module_core.checkConsistency) tip transaction hashes that can be used as branch and trunk transactions by calling the connected IRI node's [`getTransactionsToApprove`](https://docs.iota.works/iri/api#endpoints/getTransactionsToApprove) endpoint. -Does the _tip selection_ by calling -[`getTransactionsToApprove`](https://docs.iota.works/iri/api#endpoints/getTransactionsToApprove) command. -Returns a pair of approved transactions, which are chosen randomly after validating the transaction trytes, -the signatures and cross-checking for conflicting transactions. +To make sure that the tip transactions also directly or indirectly reference another transaction, add that transaction's hash to the `reference` argument. -Tip selection is executed by a Random Walk (RW) starting at random point in given `depth` -ending up to the pair of selected tips. For more information about tip selection please refer to the -[whitepaper](https://iota.org/IOTA_Whitepaper.pdf). +## Related methods -The `reference` option allows to select tips in a way that the reference transaction is being approved too. -This is useful for promoting transactions, for example with -[`promoteTransaction`](#module_core.promoteTransaction). +You can use the returned transaction hashes to do proof of work on transaction trytes, using the [`attachToTangle()`](#module_core.attachToTangle) method. **Example** ```js -const depth = 3 -const minWeightMagnitude = 14 - -getTransactionsToApprove(depth) - .then(transactionsToApprove => - attachToTangle(minWeightMagnitude, trytes, { transactionsToApprove }) - ) - .then(storeAndBroadcast) - .catch(err => { - // handle errors here +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*.createGetTrytes(provider) +### *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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| provider | Provider | Network provider | +| hashes | Array.<Hash> | Array of transaction hashes | +| [callback] | Callback | Optional callback function | -**Returns**: function - [`getTrytes`](#module_core.getTrytes) - +This method uses the connected IRI node's +[`getTrytes`](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference#gettrytes) endpoint. -### *core*.getTrytes(hashes, [callback]) -**Fulfil**: Trytes[] - Transaction trytes -**Reject**: Error{} -- `INVALID_TRANSACTION_HASH`: Invalid hash -- Fetch error +The transaction trytes include all transaction fields except the transaction hash. -| Param | Type | Description | -| --- | --- | --- | -| hashes | Array.<Hash> | List of transaction hashes | -| [callback] | Callback | Optional callback | +**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 `9`s. -Fetches the transaction trytes given a list of transaction hashes, by calling -[`getTrytes`](https://docs.iota.works/iri/api#endpoints/getTrytes) command. +## Related methods + +To get transaction objects instead of trytes, use the [`getTransactionObjects()`](#module_core.getTransactionObjects) method. **Example** ```js getTrytes(hashes) - // Parsing as transaction objects - .then(trytes => asTransactionObjects(hashes)(trytes)) - .then(transactions => { - // ... - }) - .catch(err => { - // ... + .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*.createIsPromotable(provider, [depth]) - -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| provider | Provider | | Network provider | -| [depth] | number | 6 | Depth up to which promotion is effective. | - -**Returns**: function - [`isPromotable`](#module_core.isPromotable) ### *core*.isPromotable(tail, [callback]) -**Fulfil**: boolean Consistency state of transaction or co-consistency of transactions -**Reject**: Error -- `INVALID_HASH`: Invalid hash -- `INVALID_DEPTH`: Invalid depth -- Fetch error +**Summary**: Checks if a given tail transaction hash can be [promoted](https://docs.iota.org/docs/getting-started/0.1/transactions/reattach-rebroadcast-promote#promote). +**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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | | tail | Hash | Tail transaction hash | -| [callback] | Callback | Optional callback | +| [callback] | Callback | Optional callback function | -Checks if a transaction is _promotable_, by calling [`checkConsistency`](#module_core.checkConsistency) and -verifying that `attachmentTimestamp` is above a lower bound. -Lower bound is calculated based on number of milestones issued -since transaction attachment. +To decide if a transaction can be promoted, this method makes sure that it's [consistent](#module_core.checkConsistency) +and that the value of the transaction's `attachmentTimestamp` field is not older than the latest 6 milestones. -**Example** -#### Example with promotion and reattachments +## Related methods -Using `isPromotable` to determine if transaction can be [_promoted_](#module_core.promoteTransaction) -or should be [_reattached_](#module_core.replayBundle) +If a transaction is promotable, you can promote it by using the [`promoteTransaction()`](#module_core.promoteTransaction) method. +**Example** ```js -// We need to monitor inclusion states of all tail transactions (original tail & reattachments) -const tails = [tail] - -getLatestInclusion(tails) - .then(states => { - // Check if none of transactions confirmed - if (states.indexOf(true) === -1) { - const tail = tails[tails.length - 1] // Get latest tail hash - - return isPromotable(tail) - .then(isPromotable => isPromotable - ? promoteTransaction(tail, 3, 14) - : replayBundle(tail, 3, 14) - .then(([reattachedTail]) => { - const newTailHash = reattachedTail.hash - - // Keeping track of all tail hashes to check confirmation - tails.push(newTailHash) - - // Promote the new tail... - }) - } - }).catch(err => { - // ... +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 network provider to fetch inputs and remainder address. In case this is omitted, proper input objects and remainder should be passed to [`prepareTransfers`](#module_core.prepareTransfers), if required. | +| [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. | -Create a [`prepareTransfers`](#module_core.prepareTransfers) function by passing an optional network `provider`. -It is possible to prepare and sign transactions offline, by omitting the provider option. - -**Returns**: function - [`prepareTransfers`](#module_core.prepareTransfers) +**Returns**: function - [`prepareTransfers`](#module_core.prepareTransfers) - A new `prepareTransfers()` function that uses your chosen Provider instance. +**Example** +```js +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]) -**Fulfil**: array Returns bundle trytes -**Reject**: Error -- `INVALID_SEED` -- `INVALID_TRANSFER_ARRAY` -- `INVALID_INPUT` -- `INVALID_REMAINDER_ADDRESS` -- `INSUFFICIENT_BALANCE` -- `NO_INPUTS` -- `SENDING_BACK_TO_INPUTS` -- Fetch error, if connected to network +**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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Default | Description | | --- | --- | --- | --- | -| seed | string | | | -| transfers | object | | | -| [options] | object | | | -| [options.inputs] | Array.<Input> | | Inputs used for signing. Needs to have correct security, keyIndex and address value | -| [options.inputs[].address] | Hash | | Input address trytes | -| [options.inputs[].keyIndex] | number | | Key index at which address was generated | -| [options.inputs[].security] | number | | Security level | -| [options.inputs[].balance] | number | | Balance in iotas | -| [options.address] | Hash | | Remainder address | -| [options.security] | Number | 2 | Security level to be used for getting inputs and remainder address | -| [callback] | function | | Optional callback | +| 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`](#module_core.getInputs) method to automatically select input objects | +| [callback] | function | | Optional callback function | **Properties** | Name | Type | Description | | --- | --- | --- | -| [options.hmacKey] | Hash | HMAC key used for attaching an HMAC | +| [options.hmacKey] | Hash | HMAC key used for adding an HMAC signature to the transaction | -Prepares the transaction trytes by generating a bundle, filling in transfers and inputs, -adding remainder and signing. It can be used to generate and sign bundles either online or offline. -For offline usage, please see [`createPrepareTransfers`](#module_core.createPrepareTransfers) -which can create a `prepareTransfers` function without a network provider. +This method creates a bundle, using the given arguments and uses the given seed to sign any transactions that withdraw IOTA tokens. -**Note:** After calling this method, persist the returned transaction trytes in local storage. Only then you should broadcast to network. -This will allow for reattachments and prevent key reuse if trytes can't be recovered by querying the network after broadcasting. +**Note:** The given seed is used to [generate addresses](https://docs.iota.org/docs/client-libraries/0.1/how-to-guides/js/generate-an-address) and sign transactions on your local device. It is never sent anywhere. - +**Note:** To create transactions offline, use the [`createPrepareTransfers`](#module_core.createPrepareTransfers) without a `provider` argument. -### *core*.createPromoteTransaction(provider, [attachFn]) +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](https://docs.iota.org/docs/getting-started/0.1/clients/addresses#spent-addresses). -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider | -| [attachFn] | function | Optional `attachToTangle` function to override the [default method](#module_core.attachToTangle). | +## Related methods + +To attach the returned transaction trytes to the Tangle, you can use one of the following: + +- [`sendTrytes()`](#module_core.sendTrytes) (easiest) +- [`getTransactionsToApprove()`](#module_core.getTransactionsToApprove) followed by [`attachToTangle()`](#module_core.attachToTangle) followed by [`broadcastTransactions()`](#module_core.broadcastTransactions) (for more control) + +**Example** +```js -**Returns**: function - [`promoteTransaction`](#module_core.promoteTransaction) +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]) -**Fulfil**: Transaction[] -**Reject**: Error -- `INCONSISTENT_SUBTANGLE`: In this case promotion has no effect and a reattachment is required by calling [`replayBundle`](#module_core.replayBundle). -- Fetch error +**Summary**: [Promotes](https://docs.iota.org/docs/getting-started/0.1/transactions/reattach-rebroadcast-promote#promote) 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()`](#module_core.replayBundle) method +- Fetch error: The connected IOTA node's API returned an error. See the [list of error messages](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) -| Param | Type | Description | -| --- | --- | --- | -| tail | Hash | Tail transaction hash. Tail transaction is the transaction in the bundle with `currentIndex == 0`. | -| depth | number | The depth at which Random Walk starts. A value of `3` is typically used by wallets, meaning that RW starts 3 milestones back. | -| minWeightMagnitude | number | Minimum number of trailing zeros in transaction hash. This is used by [`attachToTangle`](#module_core.attachToTangle) function to search for a valid `nonce`. Currently it is `14` on mainnet & spamnet and `9` on most other testnets. | -| [spamTransfers] | array | Array of spam transfers to promote with. By default it will issue an all-9s, zero-value transfer. | -| [options] | object | Options | -| [options.delay] | number | Delay between spam transactions in `ms` | -| [options.interrupt] | boolean \| function | Interrupt signal, which can be a function that evaluates to boolean | -| [callback] | Callback | Optional callback | +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| tail | Hash | | Tail transaction hash | +| depth | number | | The [depth](https://docs.iota.org/docs/getting-started/0.1/transactions/depth) at which to start the weighted random walk. The [Trinity wallet](https://trinity.iota.org/) uses a value of `3`, meaning that the weighted random walk starts 3 milestones in the past. | +| minWeightMagnitude | number | | [Minimum weight magnitude](https://docs.iota.org/docs/getting-started/0.1/network/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 | -Promotes a transaction by adding zero-value spam transactions on top of it. -Will promote `maximum` transfers on top of the current one with `delay` interval. Promotion -is interruptable through the `interrupt` option. +This method promotes only consistent transactions by checking them with the [`checkConsistency()`](#module_core.checkConsistency) method. - +## Related methods -### *core*.createRemoveNeighbors(provider) +Use the [`isPromotable()`](#module_core.isPromotable) method to check if a transaction can be [promoted](https://docs.iota.org/docs/getting-started/0.1/transactions/reattach-rebroadcast-promote). -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider | +If a transaction can't be promoted, use the [`replayBundle()`](#module_core.replayBundle) method to [reattach](https://docs.iota.org/docs/getting-started/0.1/transactions/reattach-rebroadcast-promote) it to the Tangle. -**Returns**: function - [`removeNeighbors`](#module_core.removeNeighbors) +**Example** +```js +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]) -**Fulfil**: number Number of neighbors that were removed -**Reject**: Error -- `INVALID_URI`: Invalid uri -- Fetch error +**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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| uris | Array | List of URI's | -| [callback] | Callback | Optional callback | - -Removes a list of neighbors from the connected IRI node by calling -[`removeNeighbors`](https://docs.iota.works/iri/api#endpoints/removeNeighbors) command. -Assumes `removeNeighbors` command is available on the node. +| uris | Array | Array of neighbor URIs that you want to add to the node | +| [callback] | Callback | Optional callback function | -This method has temporary effect until your IRI node relaunches. +This method removes a list of neighbors from the connected IRI node by calling its +[`removeNeighbors`](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference#removeneighbors) endpoint. - +These neighbors are re-added when the node is restarted. -### *core*.createReplayBundle(provider) +## Related methods -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider | +To see statistics about the connected IRI node's neighbors, use the [`getNeighbors()`](#module_core.getNeighbors) method. -**Returns**: function - [`replayBundle`](#module_core.replayBundle) +**Example** +```js +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]) -**Fulfil**: Transaction[] -**Reject**: Error -- `INVALID_DEPTH` -- `INVALID_MIN_WEIGHT_MAGNITUDE` -- `INVALID_TRANSACTION_HASH` -- `INVALID_BUNDLE` -- Fetch error +**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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| tail | Hash | Tail transaction hash. Tail transaction is the transaction in the bundle with `currentIndex == 0`. | -| depth | number | The depth at which Random Walk starts. A value of `3` is typically used by wallets, meaning that RW starts 3 milestones back. | -| minWeightMagnitude | number | Minimum number of trailing zeros in transaction hash. This is used by [`attachToTangle`](#module_core.attachToTangle) function to search for a valid `nonce`. Currently it is `14` on mainnet & spamnet and `9` on most other testnets. | -| [callback] | Callback | Optional callback | +| tail | Hash | Tail transaction hash | +| depth | number | The [depth](https://docs.iota.org/docs/getting-started/0.1/transactions/depth) at which to start the weighted random walk. The [Trinity wallet](https://trinity.iota.org/) uses a value of `3`, meaning that the weighted random walk starts 3 milestones in the past. | +| minWeightMagnitude | number | The [minimum weight magnitude](https://docs.iota.org/docs/getting-started/0.1/network/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 | -Reattaches a transfer to the Tangle by selecting tips and performing the Proof-of-Work again. -Reattachments are useful in case the original transactions are pending, and can be done securely -as many times as needed. +This method [reattaches](https://docs.iota.org/docs/getting-started/0.1/transactions/reattach-rebroadcast-promote#reattach) a bundle to the Tangle by calling the [`sendTrytes()`](#module_core.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()`](#module_core.isPromotable) method. **Example** ```js -replayBundle(tail) - .then(transactions => { - // ... - }) - .catch(err => { - // ... +iota.replayBundle(tailTransactionHash) + .then(bundle => { + console.log(`Successfully reattached ${tailTransactionHash}`); + console.log(JSON.stringify(bundle)); + }).catch(error => { + console.log(`Something went wrong: ${error}`) }) -}) ``` - - -### *core*.createSendTrytes(provider) - -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider | - -**Returns**: function - [`sendTrytes`](#module_core.sendTrytes) ### *core*.sendTrytes(trytes, depth, minWeightMagnitude, [reference], [callback]) -**Fulfil**: Transaction[] Returns list of attached transactions -**Reject**: Error -- `INVALID_TRANSACTION_TRYTES` -- `INVALID_DEPTH` -- `INVALID_MIN_WEIGHT_MAGNITUDE` -- Fetch error, if connected to network +**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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| trytes | Array.<Trytes> | List of trytes to attach, store and broadcast | -| depth | number | The depth at which Random Walk starts. A value of `3` is typically used by wallets, meaning that RW starts 3 milestones back. | -| minWeightMagnitude | number | Minimum number of trailing zeros in transaction hash. This is used to search for a valid `nonce`. Currently it is `14` on mainnet & spamnet and `9` on most other testnets. | +| trytes | Array.<Trytes> | Array of prepared transaction trytes to attach, store, and send | +| depth | number | The [depth](https://docs.iota.org/docs/getting-started/0.1/transactions/depth) at which to start the weighted random walk. The [Trinity wallet](https://trinity.iota.org/) uses a value of `3`, meaning that the weighted random walk starts 3 milestones in the past. | +| minWeightMagnitude | number | The [minimum weight magnitude](https://docs.iota.org/docs/getting-started/0.1/network/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 | +| [callback] | Callback | Optional callback function | + +This method takes an array of transaction trytes that don't include a proof of work or -[Attaches to Tangle](#module_core.attachToTangle), [stores](#module_core.storeTransactions) -and [broadcasts](#module_core.broadcastTransactions) a list of transaction trytes. +Then, the method calls the following to finalize the bundle and send it to the node: +- [`getTransactionsToApprove()`](#module_core.getTransactionsToApprove) +- [`attachToTangle()`](#module_core.attachToTangle) +- [`storeAndBroadcast()`](#module_core.storeAndBroadcast) -**Note:** Persist the transaction trytes in local storage __before__ calling this command, to ensure -that reattachment is possible, until your bundle has been included. +**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()`](#module_core.prepareTransfers) method. **Example** ```js prepareTransfers(seed, transfers) .then(trytes => { - // Persist trytes locally before sending to network. - // This allows for reattachments and prevents key reuse if trytes can't - // be recovered by querying the network after broadcasting. - return iota.sendTrytes(trytes, depth, minWeightMagnitude) }) - .then(transactions => { - // ... - }) - .catch(err => { - // ... + .then(bundle => { + console.log(`Successfully attached transactions to the Tangle`); + console.log(JSON.stringify(bundle)); + }).catch(error => { + console.log(`Something went wrong: ${error}`) }) ``` - - -### *core*.createStoreAndBroadcast(provider) - -| Param | Type | -| --- | --- | -| provider | Provider | - -**Returns**: function - [`storeAndBroadcast`](#module_core.storeAndBroadcast) ### *core*.storeAndBroadcast(trytes, [callback]) -**Fulfil**: Trytes[] Attached transaction trytes -**Reject**: Error -- `INVALID_ATTACHED_TRYTES`: Invalid attached trytes -- Fetch error +**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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| trytes | Array.<Trytes> | Attached transaction trytes | -| [callback] | Callback | Optional callback | +| trytes | Array.<Trytes> | Array of transaction trytes | +| [callback] | Callback | Optional callback function | -Stores and broadcasts a list of _attached_ transaction trytes by calling -[`storeTransactions`](#module_core.storeTransactions) and -[`broadcastTransactions`](#module_core.broadcastTransactions). +This method uses the connected IRI node's +[`broadcastTransactions`](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference#broadcastTransactions) and [`storeTransactions`](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference#storeTransactions) endpoints to send it the given transaction trytes. -**Note:** Persist the transaction trytes in local storage __before__ calling this command, to ensure -that reattachment is possible, until your bundle has been included. +**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. -Any transactions stored with this command will eventaully be erased, as a result of a snapshot. +## Related methods - +The given transaction trytes must be in a valid bundle and must include a proof of work. -### *core*.createStoreTransactions(provider) +To create a valid bundle, use the `prepareTransfers()` method. For more information about what makes a bundles and transactions valid, see [this guide](https://docs.iota.org/docs/node-software/0.1/iri/concepts/transaction-validation). -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider | +To do proof of work, use one of the following methods: -**Returns**: function - [`storeTransactions`](#module_core.storeTransactions) - +- [`attachToTangle()`](#module_core.attachToTangle) +- [`sendTrytes()`](#module_core.sendTrytes) + +**Example** +```js +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*.storeTransactions(trytes, [callback]) -**Fullfil**: Trytes[] Attached transaction trytes -**Reject**: Error -- `INVALID_ATTACHED_TRYTES`: Invalid attached trytes -- Fetch 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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Description | | --- | --- | --- | -| trytes | Array.<Trytes> | Attached transaction trytes | -| [callback] | Callback | Optional callback | +| trytes | Array.<Trytes> | Array of transaction trytes | +| [callback] | Callback | Optional callback function | + +This method uses the connected IRI node's +[`storeTransactions`](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference#storeTransactions) endpoint to store the given transaction trytes. -Persists a list of _attached_ transaction trytes in the store of connected node by calling -[`storeTransactions`](https://docs.iota.org/iri/api#endpoints/storeTransactions) command. -Tip selection and Proof-of-Work must be done first, by calling -[`getTransactionsToApprove`](#module_core.getTransactionsToApprove) and -[`attachToTangle`](#module_core.attachToTangle) or an equivalent attach method or remote -[`PoWbox`](https://powbox.devnet.iota.org/). +**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. -**Note:** Persist the transaction trytes in local storage __before__ calling this command, to ensure -that reattachment is possible, until your bundle has been included. +## Related methods -Any transactions stored with this command will eventaully be erased, as a result of a snapshot. +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](https://docs.iota.org/docs/node-software/0.1/iri/concepts/transaction-validation). -### *core*.createTraverseBundle(provider) +To do proof of work, use one of the following methods: -| Param | Type | -| --- | --- | -| provider | Provider | +- [`attachToTangle()`](#module_core.attachToTangle) +- [`sendTrytes()`](#module_core.sendTrytes) -**Returns**: function - [`traverseBundle`](#module_core.traverseBundle) +**Example** +```js +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]) -**Fulfil**: Transaction[] Bundle as array of transaction objects -**Reject**: Error -- `INVALID_TRANSACTION_HASH` -- `INVALID_TAIL_HASH`: Provided transaction is not tail (`currentIndex !== 0`) -- `INVALID_BUNDLE`: Bundle is syntactically invalid -- Fetch error +**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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) | Param | Type | Default | Description | | --- | --- | --- | --- | -| trunkTransaction | Hash | | Trunk transaction, should be tail (`currentIndex == 0`) | -| [bundle] | Hash | [] | List of accumulated transactions | -| [callback] | Callback | | Optional callback | +| trunkTransaction | Hash | | Tail transaction hash | +| [bundle] | Hash | [] | Array of existing transaction objects to include in the returned bundle | +| [callback] | Callback | | Optional callback function | -Fetches the bundle of a given the _tail_ transaction hash, by traversing through `trunkTransaction`. -It does not validate the bundle. +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()`](#module_core.getBundle) method. **Example** ```js -traverseBundle(tail) - .then(bundle => { - // ... - }) - .catch(err => { - // handle errors - }) +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 | | | -| index | number | | Private key index | -| [security] | number | 2 | Security level of the private key | -| [checksum] | boolean | false | Flag to add 9trytes checksum | +| 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](https://docs.iota.org/docs/getting-started/0.1/clients/security-levels) to use to generate the address | +| [checksum] | boolean | false | Whether to add the [checksum](https://docs.iota.org/docs/getting-started/0.1/clients/checksums) | + +Generates an address, according to the given seed, index, and security level. -Generates an address deterministically, according to the given seed, index and security level. +**Note:** This method does not check if the address is [spent](https://docs.iota.org/docs/getting-started/0.1/clients/addresses#spent-addresses). -**Returns**: Hash - Address trytes +## Related methods + +To generate an address that has a lower probability of being spent, use the [`getNewAddress()`](#module_core.getNewAddress) method. + +**Returns**: Hash - address - An 81-tryte address +**Example** +```js +const myAddress = generateAddress(seed, 0); +``` diff --git a/packages/core/src/composeAPI.ts b/packages/core/src/composeAPI.ts index 875aa6f5b..de3ed8043 100644 --- a/packages/core/src/composeAPI.ts +++ b/packages/core/src/composeAPI.ts @@ -25,7 +25,6 @@ import { createGetBundle, createGetInclusionStates, createGetInputs, - createGetLatestInclusion, createGetNeighbors, createGetNewAddress, createGetNodeInfo, @@ -74,7 +73,7 @@ export function returnType(func: Func) { /** * @method composeApi - * + * * @summary Creates an API object that's used to send requests to an IRI node. * * @memberof module:core @@ -89,12 +88,12 @@ export function returnType(func: Func) { * @example * ```js * const Iota = require('@iota/core`); - * + * * const iota = Iota.composeAPI({ * provider: 'https://nodes.devnet.thetangle.org:443' * }); * ``` - * + * * @return {API} iota - API object to use to interact with an IRI node. */ export const composeAPI = (settings: Partial = {}) => { @@ -103,7 +102,7 @@ export const composeAPI = (settings: Partial = {}) => { /** * @method setSettings - * + * * @summary Defines network provider configuration and [`attachToTangle`]{@link #module_core.attachToTangle} method. * * @memberof API @@ -126,13 +125,13 @@ export const composeAPI = (settings: Partial = {}) => { } /** - * + * * @method overrideNetwork - * + * * @summary Overrides the default provider * * @memberof API - * + * * @ignore * * @param {Provider} network - Provider instance to use to override the existing network settings @@ -145,11 +144,11 @@ export const composeAPI = (settings: Partial = {}) => { /** * * @method overrideAttachToTangle - * + * * @summary Overrides the default [`attachToTangle`]{@link #module_core.attachToTangle} method * * @memberof API - * + * * @ignore * * @param {function} attachToTangle - Function that overrides the @@ -185,7 +184,6 @@ export const composeAPI = (settings: Partial = {}) => { getAccountData: createGetAccountData(provider), getBundle: createGetBundle(provider), getBundlesFromAddresses: createGetBundlesFromAddresses(provider), - getLatestInclusion: createGetLatestInclusion(provider), getNewAddress: createGetNewAddress(provider), getTransactionObjects: createGetTransactionObjects(provider), findTransactionObjects: createFindTransactionObjects(provider), diff --git a/packages/core/src/createGetBundlesFromAddresses.ts b/packages/core/src/createGetBundlesFromAddresses.ts index 75b77bec8..51fb7b773 100644 --- a/packages/core/src/createGetBundlesFromAddresses.ts +++ b/packages/core/src/createGetBundlesFromAddresses.ts @@ -1,10 +1,10 @@ import * as Promise from 'bluebird' import { Bundle, Callback, Hash, Provider, Transaction } from '../../types' -import { createFindTransactionObjects, createGetLatestInclusion } from './' +import { createFindTransactionObjects, createGetInclusionStates } from './' export const createGetBundlesFromAddresses = (provider: Provider, caller?: string) => { const findTransactionObjects = createFindTransactionObjects(provider) - const getLatestInclusion = createGetLatestInclusion(provider) + const getInclusionStates = createGetInclusionStates(provider) /* tslint:disable-next-line:only-arrow-functions */ return function( @@ -36,9 +36,8 @@ export const createGetBundlesFromAddresses = (provider: Provider, caller?: strin .then(groupTransactionsIntoBundles) // 4. If requested, add persistence status to each bundle - .then( - (bundles: ReadonlyArray) => - inclusionStates ? addPersistence(getLatestInclusion, bundles) : bundles + .then((bundles: ReadonlyArray) => + inclusionStates ? addPersistence(getInclusionStates, bundles) : bundles ) // 5. Sort bundles by timestamp @@ -96,16 +95,16 @@ export const zipPersistence = (bundles: ReadonlyArray) => ( // Since bundles are atomic, all transactions have the same state zip2(bundles, states).map(([bundle, state]) => bundle.map(tx => ({ ...tx, persistence: state }))) -type GetLatestInclusion = ( +type GetInclusionStates = ( transactions: ReadonlyArray, callback?: Callback> ) => Promise> -export const addPersistence = (getLatestInclusion: GetLatestInclusion, bundles: ReadonlyArray) => { +export const addPersistence = (getInclusionStates: GetInclusionStates, bundles: ReadonlyArray) => { // Get the first hash of each bundle const hashes = bundles.map(bundle => bundle[0].hash) - return getLatestInclusion(hashes).then(zipPersistence(bundles)) + return getInclusionStates(hashes).then(zipPersistence(bundles)) } export const sortByTimestamp = (bundles: ReadonlyArray) => diff --git a/packages/core/src/createGetInclusionStates.ts b/packages/core/src/createGetInclusionStates.ts index ab095aa3e..9d204f65c 100644 --- a/packages/core/src/createGetInclusionStates.ts +++ b/packages/core/src/createGetInclusionStates.ts @@ -12,11 +12,11 @@ import { /** * @method createGetInclusionStates - * + * * @summary Creates a new `getInclusionStates()` method, using a custom Provider instance. * * @memberof module:core - * + * * @ignore * * @param {Provider} provider - The Provider object that the method should use to call the node's API endpoints. @@ -26,28 +26,23 @@ import { export const createGetInclusionStates = ({ send }: Provider) => /** * This method uses the connected IRI node's [`getInclusionStates`](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference#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`. - * - * ## Related methods - * - * To find out if one or more transactions are confirmed, use the [`getLatestInclusion()`]{@link #module_core.getLatestInclusion} method. - * + * * @method getInclusionStates - * + * * @summary Finds out if one or more given transactions are referenced by one or more other given transactions. - * + * * @memberof module:core * * @param {Hash[]} transactions - Array of transaction hashes to check - * @param {Hash[]} tips - Array of transaction hashes that should directly or indirectly reference the given transactions * @param {Callback} [callback] - Optional callback function - * + * * @example * ```js - * getInclusionStates(transactions, ) + * getInclusionStates(transactions) * .then(states => { * for(let i = 0; i < states.length; i++){ * states? console.log(`Transaction ${i} is referenced by the given transactions`) : @@ -60,29 +55,19 @@ export const createGetInclusionStates = ({ send }: Provider) => * ``` * * @return {Promise} - * + * * @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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) + * - Fetch error: The connected IOTA node's API returned an error. See the [list of error messages](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) */ - ( - transactions: ReadonlyArray, - tips: ReadonlyArray, - callback?: Callback> - ): Promise> => - Promise.resolve( - validate( - arrayValidator(hashValidator)(transactions, errors.INVALID_TRANSACTION_HASH), - arrayValidator(hashValidator)(tips, errors.INVALID_TRANSACTION_HASH) - ) - ) + (transactions: ReadonlyArray, callback?: Callback>): Promise> => + Promise.resolve(validate(arrayValidator(hashValidator)(transactions, errors.INVALID_TRANSACTION_HASH))) .then(() => send({ command: IRICommand.GET_INCLUSION_STATES, transactions, - tips, }) ) .then(({ states }) => states) diff --git a/packages/core/src/createGetLatestInclusion.ts b/packages/core/src/createGetLatestInclusion.ts deleted file mode 100644 index c9d0c58ae..000000000 --- a/packages/core/src/createGetLatestInclusion.ts +++ /dev/null @@ -1,73 +0,0 @@ -import * as Promise from 'bluebird' -import { Callback, Hash, Provider } from '../../types' -import { createGetInclusionStates, createGetNodeInfo } from './' - -/** - * @method createGetLatestInclusion - * - * @summary Creates a new `getLatestInclusion()` method, using a custom Provider instance. - * - * @memberof module:core - * - * @ignore - * - * @param {Provider} provider - The Provider object that the method should use to call the node's API endpoints. - * - * @return {Function} [`getLatestInclusion`]{@link #module_core.getLatestInclusion} - A new `getLatestInclusion()` function that uses your chosen Provider instance. - */ -export const createGetLatestInclusion = (provider: Provider) => { - const getInclusionStates = createGetInclusionStates(provider) - const getNodeInfo = createGetNodeInfo(provider) - - /** - * This method uses the node's `latestSolidSubtangleMilestone` field as the `tips` argument to make sure that the given transactions are referenced by the node's latest solid milestone. - * - * An invalid transaction will always remain in a pending state. - * - * **Note:** If a valid transaction is in a pending state for too long, you can [increase its chances of being confirmed](https://docs.iota.org/docs/client-libraries/0.1/how-to-guides/js/confirm-pending-bundle). - * - * ## Related methods - * - * To check if transactions are referenced by a non-milestone transaction, use the [`getInclusionStates()`]{@link #module_core.getInclusionStates} method. - * - * @method getLatestInclusion - * - * @summary Finds out if one or more given transactions are [confirmed or pending](https://docs.iota.org/docs/getting-started/0.1/network/the-tangle#transaction-states). - * - * @memberof module:core - * - * @param {Array} transactions - List of transactions hashes to check - * @param {Callback} [callback] - Optional callback function - * - * @example - * - * ```js - * iota.getLatestInclusionState(['transactionHash']) - * .then(states => { - * for(let i = 0; i < states.length; i++){ - * states[i]? console.log(`Transaction ${i} is confirmed`) : - * console.log(`transaction ${i} is pending`); - * } - * }) - * .catch(error => { - * console.log(`Something went wrong: ${error}`); - * }); - * ``` - * - * @return {Promise} - * - * @fulfil {boolean[]} states - Array of inclusion states, where `true` means that the transaction is confirmed and `false` means that it's not. - * - * @reject {Error} error - An error that contains one of the following: - * - `INVALID_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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) - */ - return function getLatestInclusion( - transactions: ReadonlyArray, - callback?: Callback> - ): Promise> { - return getNodeInfo() - .then(nodeInfo => getInclusionStates(transactions, [nodeInfo.latestSolidSubtangleMilestone])) - .asCallback(callback) - } -} diff --git a/packages/core/src/createIsReattachable.ts b/packages/core/src/createIsReattachable.ts index 854e6bce1..a1eaf5296 100644 --- a/packages/core/src/createIsReattachable.ts +++ b/packages/core/src/createIsReattachable.ts @@ -3,7 +3,7 @@ import * as Promise from 'bluebird' import { INVALID_ADDRESS } from '../../errors' import { arrayValidator, hashValidator, validate } from '../../guards' import { asArray, Callback, Hash, Provider, Transaction, Trytes } from '../../types' -import { createFindTransactionObjects, createGetLatestInclusion } from './' +import { createFindTransactionObjects, createGetInclusionStates } from './' // Filters out all receiving or 0-value transactions // Note: Transaction value < 0 is a tx-out (spending transaction) @@ -11,7 +11,7 @@ const filterSpendingTransactions = (transactions: ReadonlyArray) => // Appends the confirmation status to each transaction const withInclusionState = (provider: Provider, transactions: ReadonlyArray) => - createGetLatestInclusion(provider)(transactions.map(tx => tx.hash)).then(states => + createGetInclusionStates(provider)(transactions.map(tx => tx.hash)).then(states => transactions.map((tx, i) => ({ ...tx, confirmed: states[i], diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 96a308e78..46f1417fe 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -108,8 +108,6 @@ export { createGetBundlesFromAddresses } from './createGetBundlesFromAddresses' export { createGetInputs, GetInputsOptions } from './createGetInputs' -export { createGetLatestInclusion } from './createGetLatestInclusion' - export { createGetNewAddress, // createGetUntilFirstUnusedAddress, diff --git a/packages/core/test/integration/getInclusionStates.test.ts b/packages/core/test/integration/getInclusionStates.test.ts index 355a6f428..cbbbfa427 100644 --- a/packages/core/test/integration/getInclusionStates.test.ts +++ b/packages/core/test/integration/getInclusionStates.test.ts @@ -9,7 +9,7 @@ const getInclusionStates = createGetInclusionStates(createHttpClient()) test('getInclusionStates() resolves to correct inclusion states', async t => { t.deepEqual( - await getInclusionStates(getInclusionStatesCommand.transactions, getInclusionStatesCommand.tips), + await getInclusionStates(getInclusionStatesCommand.transactions), getInclusionStatesResponse.states, 'getInclusionStates() should resolve to correct inclusion states' ) @@ -17,24 +17,18 @@ test('getInclusionStates() resolves to correct inclusion states', async t => { const invalidHashes = ['asdasDSFDAFD'] t.is( - t.throws(() => getInclusionStates(invalidHashes, getInclusionStatesCommand.tips), Error).message, + t.throws(() => getInclusionStates(invalidHashes), Error).message, `${INVALID_TRANSACTION_HASH}: ${stringify(invalidHashes)}`, 'getInclusionStates() throws error for invalid hashes' ) - - t.is( - t.throws(() => getInclusionStates(getInclusionStatesCommand.transactions, invalidHashes), Error).message, - `${INVALID_TRANSACTION_HASH}: ${stringify(invalidHashes)}`, - 'getInclusionStates() throws error for invalid tips' - ) }) test.cb('getInclusionStates() invokes callback', t => { - getInclusionStates(getInclusionStatesCommand.transactions, getInclusionStatesCommand.tips, t.end) + getInclusionStates(getInclusionStatesCommand.transactions, t.end) }) test.cb('getInclusionStates() passes correct arguments to callback', t => { - getInclusionStates(getInclusionStatesCommand.transactions, getInclusionStatesCommand.tips, (err, res) => { + getInclusionStates(getInclusionStatesCommand.transactions, (err, res) => { t.is(err, null, 'getInclusionStates() should pass null as first argument in callback for successuful requests') t.deepEqual( diff --git a/packages/core/test/integration/nocks/getInclusionStates.ts b/packages/core/test/integration/nocks/getInclusionStates.ts index e07ad8341..02ff61bb8 100644 --- a/packages/core/test/integration/nocks/getInclusionStates.ts +++ b/packages/core/test/integration/nocks/getInclusionStates.ts @@ -5,7 +5,6 @@ import headers from './headers' export const getInclusionStatesCommand: GetInclusionStatesCommand = { command: IRICommand.GET_INCLUSION_STATES, transactions: ['A'.repeat(81), 'B'.repeat(81)], - tips: ['M'.repeat(81)], } export const getInclusionStatesResponse: GetInclusionStatesResponse = { diff --git a/packages/extract-json/README.md b/packages/extract-json/README.md index 836469aa2..dcdcff617 100644 --- a/packages/extract-json/README.md +++ b/packages/extract-json/README.md @@ -17,42 +17,39 @@ yarn add @iota/extract-json ## API Reference - + -### *extract-json*~extractJson(bundle) +### *extract-json*.extractJson(bundle) +**Summary**: Extracts JSON from transactions. +**Throws**: -| Param | Type | -| --- | --- | -| bundle | array | +- errors.INVALID\_BUNDLE : Make sure that the `bundle` argument is an array of transaction trytes. +- errors.INVALID\_JSON : Make sure that the transactions' `signatureMessageFragment` fields contain valid JSON. -Takes a bundle as input and from the signatureMessageFragments extracts the correct JSON -data which was encoded and sent with the transaction. -Supports the following forms of JSON encoded values: + +| Param | Type | Description | +| --- | --- | --- | +| bundle | array | Transaction trytes | + +This method takes the `signatureMessageFragment` fields of all the given transaction trytes, and tries to extract any JSON data that's in them. + +The following forms of JSON-encoded values are supported: - `"{ \"message\": \"hello\" }"` - `"[1, 2, 3]"` - `"true"`, `"false"` & `"null"` - `"\"hello\""` - `123` +## Related methods + +To get a bundle's transaction trytes from the Tangle, use the [`getBundle()`](#module_core.getBundle) method. + +**Returns**: string \| number \| null - The JSON data in the transactions **Example** ```js try { - const msg = JSON.parse(extractJson(bundle)) -} catch (err) { - err.msg == errors.INVALID_BUNDLE - // Invalid bundle or invalid encoded JSON + const json = JSON.parse(extractJson(bundle)) +} catch (error) { + console.log(error); } ``` -**Example** -Example with `getBundle`: - -```js -getBundle(tailHash) - .then(bundle => { - const msg = JSON.parse(extractJson(bundle)) - // ... - }) - .catch((err) => { - // Handle network & extraction errors - }) -``` diff --git a/packages/http-client/README.md b/packages/http-client/README.md index 7c1a5058b..360a488a4 100644 --- a/packages/http-client/README.md +++ b/packages/http-client/README.md @@ -22,16 +22,43 @@ yarn add @iota/http-client * [http-client](#module_http-client) * _static_ + * [.createHttpClient([settings])](#module_http-client.createHttpClient) + * [.send(command, [uri], [apiVersion])](#module_http-client.send) * _inner_ - * [~send](#module_http-client..send) + * [~createHttpClient(command)](#module_http-client..createHttpClient) + + * [~setSettings([settings])](#module_http-client..setSettings) + + + + +### *http-client*.createHttpClient([settings]) +**Summary**: Creates an HTTP client to access the IRI API. + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| [settings] | Object | {} | | +| [settings.provider] | String | http://localhost:14265 | URI of an IRI node to connect to | +| [settings.apiVersion] | String \| number | 1 | IOTA API version to be sent in the `X-IOTA-API-Version` header. | +| [settings.requestBatchSize] | number | 1000 | Number of search values per request | + +This method creates an HTTP client that you can use to send requests to the [IRI API endpoints](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference). - * [~setSettings](#module_http-client..setSettings) +## Related methods - * [~createHttpClient([settings])](#module_http-client..createHttpClient) +To send requests to the IRI node, use the [`send()`](#module_http-client.send) method. +**Returns**: HTTP client object +**Example** +```js +let settings = { + provider: 'http://mynode.eu:14265' +} +let httpClient = HttpClient.createHttpClient(settings); +``` ### *http-client*.send(command, [uri], [apiVersion]) @@ -47,39 +74,70 @@ yarn add @iota/http-client Sends an http request to a specified host. **Returns**: Promise - + -### *http-client*~send +### *http-client*~createHttpClient(command) +**Summary**: Sends an API request to the connected IRI node. +**Fulfil**: Object response - The response from the IRI node +**Reject**: Object error - The connected IOTA node's API returned an error. See the [list of error messages](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) -| Param | Type | -| --- | --- | -| command | object | +| Param | Type | Description | +| --- | --- | --- | +| command | Object | The request body for the API endpoint | -**Returns**: object - response +This method uses the HTTP client to send requests to the [IRI API endpoints](https://docs.iota.org/docs/node-software/0.1/iri/references/api-reference). + +## Related methods + +To create an HTTP client, use the [`createHttpClient()`](#module_http-client.createHttpClient) method. + +**Example** +```js +let httpClient = HttpClient.createHttpClient(settings); +httpClient.send({command:'getNodeInfo'}) +.then(response => { + console.log(response); +}) +.catch(error => { + console.log(error); +}) +``` -### *http-client*~setSettings +### *http-client*~setSettings([settings]) +**Summary**: Updates the settings of an existing HTTP client. | Param | Type | Default | Description | | --- | --- | --- | --- | -| [settings] | object | {} | | -| [settings.provider] | string | "http://localhost:14265" | Uri of IRI node | -| [settings.apiVersion] | string \| number | 1 | IOTA Api version to be sent as `X-IOTA-API-Version` header. | +| [settings] | Object | {} | | +| [settings.provider] | String | http://localhost:14265 | URI of an IRI node to connect to | +| [settings.apiVersion] | String \| number | 1 | IOTA API version to be sent in the `X-IOTA-API-Version` header. | | [settings.requestBatchSize] | number | 1000 | Number of search values per request. | -| [settings.agent] | object | {} | Agent to handle the connections | - +This method updates the settings of an existing HTTP client. -### *http-client*~createHttpClient([settings]) +## Related methods -| Param | Type | Default | Description | -| --- | --- | --- | --- | -| [settings] | object | {} | | -| [settings.provider] | string | "http://localhost:14265" | Uri of IRI node | -| [settings.apiVersion] | string \| number | 1 | IOTA Api version to be sent as `X-IOTA-API-Version` header. | -| [settings.requestBatchSize] | number | 1000 | Number of search values per request. | -| [settings.agent] | object | {} | Agent to handle the connections | +To create an HTTP client, use the [`createHttpClient()`](#module_http-client.createHttpClient) method. + +**Example** +```js +let settings = { + provider: 'https://nodes.devnet.thetangle.org:443' + } -Create an http client to access IRI http API. +let httpClient = http.createHttpClient(settings); +httpClient.send({command:'getNodeInfo'}).then(res => { + console.log(res) +}).catch(err => { + console.log(err) +}); -**Returns**: Object +httpClient.setSettings({provider:'http://newnode.org:14265'}); + +httpClient.send({command:'getNodeInfo'}).then(res => { + console.log(res) +}).catch(err => { + console.log(err) +}) +``` diff --git a/packages/http-client/test/batchedSend.ts b/packages/http-client/test/batchedSend.ts index dd4f056c6..a7d6c351e 100644 --- a/packages/http-client/test/batchedSend.ts +++ b/packages/http-client/test/batchedSend.ts @@ -185,19 +185,16 @@ export const getBalancesNockBatchB = nock('http://localhost:24265', headers(apiV export const getInclusionStatesCommand: GetInclusionStatesCommand = { command: IRICommand.GET_INCLUSION_STATES, transactions: ['A'.repeat(81), 'B'.repeat(81), 'C'.repeat(81)], - tips: ['T'.repeat(81)], } export const getInclusionStatesCommandA: GetInclusionStatesCommand = { command: IRICommand.GET_INCLUSION_STATES, transactions: ['A'.repeat(81), 'B'.repeat(81)], - tips: ['T'.repeat(81)], } export const getInclusionStatesCommandB: GetInclusionStatesCommand = { command: IRICommand.GET_INCLUSION_STATES, transactions: ['C'.repeat(81)], - tips: ['T'.repeat(81)], } export const expectedGetInclusionStatesResponse: GetInclusionStatesResponse = { diff --git a/packages/http-client/test/isBatchableCommand.test.ts b/packages/http-client/test/isBatchableCommand.test.ts index ba9b3fdd3..454f623c4 100644 --- a/packages/http-client/test/isBatchableCommand.test.ts +++ b/packages/http-client/test/isBatchableCommand.test.ts @@ -28,7 +28,6 @@ const getBalancesCommand: GetBalancesCommand = { const getInclusionStatesCommand: GetInclusionStatesCommand = { command: IRICommand.GET_INCLUSION_STATES, transactions: ['A'.repeat(81), 'B'.repeat(81)], - tips: ['T'.repeat(81)], } interface CustomCommand extends BaseCommand { diff --git a/packages/signing/README.md b/packages/signing/README.md index ab041c5de..576f11d0c 100644 --- a/packages/signing/README.md +++ b/packages/signing/README.md @@ -20,98 +20,204 @@ yarn add @iota/signing * [signing](#module_signing) - * [~subseed(seed, index)](#module_signing..subseed) + * [.subseed(seed, index)](#module_signing.subseed) - * [~key(subseedTrits, length)](#module_signing..key) + * [.key(subseedTrits, numberOfFragments)](#module_signing.key) - * [~digests(key)](#module_signing..digests) + * [.digests(key)](#module_signing.digests) - * [~address(digests)](#module_signing..address) + * [.address(digests)](#module_signing.address) - * [~digest(normalizedBundleFragment, signatureFragment)](#module_signing..digest) + * [.validateSignatures(expectedAddress, signatureFragments, bundle)](#module_signing.validateSignatures) - * [~signatureFragment(normalizeBundleFragment, keyFragment)](#module_signing..signatureFragment) + * [.normalizedBundle(bundle)](#module_signing.normalizedBundle) - * [~validateSignatures(expectedAddress, signatureFragments, bundleHash)](#module_signing..validateSignatures) - * [~normalizedBundleHash(bundlehash)](#module_signing..normalizedBundleHash) + +### *signing*.subseed(seed, index) +**Summary**: Generates a subseed. +**Throws**: - +- errors.ILLEGAL\_SUBSEED\_INDEX : Make sure that the `index` argument is a number greater than 0. -### *signing*~subseed(seed, index) | Param | Type | Description | | --- | --- | --- | -| seed | Int8Array | Seed trits | -| index | number | Private key index | +| seed | Int8Array | A 243-trit seed to use to derive the subseed | +| index | number | The private key index to use to derive the subseed | -**Returns**: Int8Array - subseed trits - +This method derives a subseed from a seed and a private key index. -### *signing*~key(subseedTrits, length) +You can use the subseed to [derive private keys and their addresses](https://docs.iota.org/docs/client-libraries/0.1/how-to-guides/js/derive-addresses-from-private-keys). -| Param | Type | Description | -| --- | --- | --- | -| subseedTrits | Int8Array | Subseed trits | -| length | number | Private key length | +**Note:** If the given seed is less then 243 trits, 0 trits are appended to it until it is 243 trits long. -**Returns**: Int8Array - Private key trits - +## Related methods -### *signing*~digests(key) +To convert a seed from trytes to trits, use the [`trytesToTrits()`](#module_converter.trytesToTrits) method. -| Param | Type | Description | -| --- | --- | --- | -| key | Int8Array | Private key trits | +To derive a private key from the subseed, use the [`key()`](#module_signing.key) method. + +**Returns**: Int8Array - subseed - A subseed in trits +**Example** +```js +const seed = 'MYSUPERSECRETSEED...'; +const subseed = Sign.subseed(Converter.trytesToTrits(seed), 0); +``` + - +### *signing*.key(subseedTrits, numberOfFragments) +**Summary**: Generates a private key. +**Throws**: + +- errors.ILLEGAL\_SUBSEED\_LENGTH : Make sure that the `subseedTrits` argument contains 243 trits. +- errors.ILLEGAL\_NUMBER\_OF\_FRAGMENTS : Make sure that the `numberOfFragments` argument is a valid security level (between 1 and 3). -### *signing*~address(digests) | Param | Type | Description | | --- | --- | --- | -| digests | Int8Array | Digests trits | +| subseedTrits | Int8Array | A subseed in trits | +| numberOfFragments | number | The security level that you want the private key to have | + +This method derives a private key from a subseed. + +You can use the private key to [derive an address](https://docs.iota.org/docs/client-libraries/0.1/how-to-guides/js/derive-addresses-from-private-keys) and to sign bundles that withdraw from that address. + +## Related methods + +To generate a subseed, use the [`subseed()`](#module_signing.subseed) method. + +**Returns**: Int8Array - privateKey - A private key in trits. +**Example** +```js +const seed = 'MYSUPERSECRETSEED...'; +const subseed = Signing.subseed(Converter.trytesToTrits(seed), 0); -**Returns**: Int8Array - Address trits - +const privateKey = Signing.key(subseed, 2); +``` + + +### *signing*.digests(key) +**Summary**: Generates key digests for a given private key. +**Throws**: + +- errors.ILLEGAL\_KEY\_LENGTH : Make sure that the `key` argument contains 2,187, 4,374, or 6,561 trits. -### *signing*~digest(normalizedBundleFragment, signatureFragment) | Param | Type | Description | | --- | --- | --- | -| normalizedBundleFragment | array | Normalized bundle fragment | -| signatureFragment | Int8Array | Signature fragment trits | +| key | Int8Array | Private key in trits | + +This method derives key digests from a private key. + +You can use the key digests to [generate an address](https://docs.iota.org/docs/client-libraries/0.1/how-to-guides/js/derive-addresses-from-private-keys). + +## Related methods + +To generate a private key, use the [`key()`](#module_signing.key) method. + +**Returns**: Int8Array - digests - Key digests in trits +**Example** +```js +const seed = 'MYSUPERSECRETSEED...'; +const subseed = Signing.subseed(Converter.trytesToTrits(seed), 0); + +const privateKey = Signing.key(subseed, 2); + +const digests = Signing.digests(privateKey); +``` + + +### *signing*.address(digests) +**Summary**: Derives an address from the given key digests. +**Throws**: -**Returns**: Int8Array - Digest trits - +- errors.ILLEGAL\_DIGESTS\_LENGTH : Make sure that the `digests` argument contains a multiple of 243 trits. -### *signing*~signatureFragment(normalizeBundleFragment, keyFragment) | Param | Type | Description | | --- | --- | --- | -| normalizeBundleFragment | array | normalized bundle fragment | -| keyFragment | keyFragment | key fragment trits | +| digests | Int8Array | Key digests in trits | -**Returns**: Int8Array - Signature Fragment trits - +This method derives a 243-trit address from the given key digests. + +## Related methods + +To generate a private key, use the [`key()`](#module_signing.key) method. + +**Returns**: Int8Array - address - Address in trits +**Example** +```js +const seed = 'MYSUPERSECRETSEED...'; +const subseed = Signing.subseed(Converter.trytesToTrits(seed), 0); + +const privateKey = Signing.key(subseed, 2); + +const digests = Signing.digests(privateKey); + +const address = Signing.address(digests); +``` + + +### *signing*.validateSignatures(expectedAddress, signatureFragments, bundle) +**Summary**: Validates the given signature, using the given bundle and address. +**Throws**: + +- errors.ILLEGAL\_BUNDLE\_HASH\_LENGTH : Make sure that the `bundle` argument contains a 243-trit bundle hash. -### *signing*~validateSignatures(expectedAddress, signatureFragments, bundleHash) | Param | Type | Description | | --- | --- | --- | -| expectedAddress | string | Expected address trytes | -| signatureFragments | array | Array of signatureFragments trytes | -| bundleHash | string | Bundle hash trytes | +| expectedAddress | Int8Array | Input address in trits | +| signatureFragments | Array.<Int8Array> | Signature fragments in trits | +| bundle | Int8Array | Bundle hash in trits | + +This method validates a signature by doing the following: + +- Normalizing the bundle hash +- Deriving the key digests of the address, using the normalized bundle hash and the signature +-.Deriving an address from the key digests +- Comparing the derived address to the `expectedAddress` argument to find out if they match + +If the addresses match, the signature is valid. - +For more information about signatures see the [documentation portal](https://docs.iota.org/docs/getting-started/0.1/clients/signatures). + +## Related methods + +To convert trytes such as bundle hashes and addresses to trits, use the [`trytesToTrits()`](#module_converter.trytesToTrits) method. + +**Returns**: boolean - valid - Whether the signatures are valid. +**Example** +```js +let valid = Signing.validateSignatures(expectedAddress, signatureFragments, bundle); +``` + + +### *signing*.normalizedBundle(bundle) +**Summary**: Normalizes the bundle hash. +**Throws**: + +- errors.ILLEGAL\_BUNDLE\_HASH\_LENGTH : Make sure that the `bundle` argument contains a 243-trit bundle hash. -### *signing*~normalizedBundleHash(bundlehash) | Param | Type | Description | | --- | --- | --- | -| bundlehash | Hash | Bundle hash trytes | +| bundle | Int8Array | Bundle hash in trits | -Normalizes the bundle hash, with resulting digits summing to zero. +This method normalizes the given bundle hash to make sure that only around half of the private key is revealed when the bundle hash is signed. -**Returns**: Int8Array - Normalized bundle hash +For more information about signatures see the [documentation portal](https://docs.iota.org/docs/getting-started/0.1/clients/signatures). + +To find out more about why the bundle hash is normalized, see [this answer on StackExchange](https://iota.stackexchange.com/questions/1588/why-is-the-bundle-hash-normalized). + +## Related methods + +To convert a bundle hash from trytes to trits, use the [`trytesToTrits()`](#module_converter.trytesToTrits) method. + +**Returns**: Int8Array - Normalized bundle hash in trits +**Example** +```js +let normalizedBundleHash = Signing.normalizedBundle(bundle); +``` diff --git a/packages/transaction-converter/README.md b/packages/transaction-converter/README.md index 0be6d8d98..3e8a57032 100644 --- a/packages/transaction-converter/README.md +++ b/packages/transaction-converter/README.md @@ -20,50 +20,93 @@ yarn add @iota/transaction-converter * [transaction-converter](#module_transaction-converter) - * [~asTransactionTrytes(transactions)](#module_transaction-converter..asTransactionTrytes) + * _static_ + * [.asTransactionTrytes(transactions)](#module_transaction-converter.asTransactionTrytes) - * [~asTransactionObject(trytes)](#module_transaction-converter..asTransactionObject) + * [.asTransactionObject(transaction)](#module_transaction-converter.asTransactionObject) - * [~asTransactionObjects([hashes])](#module_transaction-converter..asTransactionObjects) + * [.asTransactionObjects([hashes])](#module_transaction-converter.asTransactionObjects) - * [~transactionObjectsMapper(trytes)](#module_transaction-converter..transactionObjectsMapper) + * _inner_ + * [~transactionObjectsMapper(trytes)](#module_transaction-converter..transactionObjectsMapper) - + + +### *transaction-converter*.asTransactionTrytes(transactions) +**Summary**: Converts one or more transaction objects into transaction trytes. +**Throws**: + +- errors.INVALID\_TRYTES : Make sure that the object fields in the `transactions` argument contains valid trytes (A-Z or 9). -### *transaction-converter*~asTransactionTrytes(transactions) | Param | Type | Description | | --- | --- | --- | -| transactions | Transaction \| Array.<Transaction> | Transaction object(s) | +| transactions | Transaction \| Array.<Transaction> | Transaction objects | + +This method takes one or more transaction objects and converts them into trytes. -Converts a transaction object or a list of those into transaction trytes. +## Related methods + +To get JSON data from the `signatureMessageFragment` field of the transaction trytes, use the [`extractJSON()`](#module_extract-json.extractJSON) method. **Returns**: Trytes \| Array.<Trytes> - Transaction trytes - +**Example** +```js +let trytes = TransactionConverter.asTransactionTrytes(transactionObject); +``` + + +### *transaction-converter*.asTransactionObject(transaction) +**Summary**: Converts transaction trytes into a transaction object. +**Throws**: + +- errors.INVALID\_TRYTES : Make sure that the object fields in the `transaction` argument contains valid trytes (A-Z or 9). -### *transaction-converter*~asTransactionObject(trytes) | Param | Type | Description | | --- | --- | --- | -| trytes | Trytes | Transaction trytes | +| transaction | Trytes | Transaction trytes | -Converts transaction trytes of 2673 trytes into a transaction object. +This method takes 2,673 transaction trytes and converts them into a transaction object. -**Returns**: Transaction - Transaction object - +## Related methods + +To convert more than one transaction into an object at once, use the [`asTransactionObjects()`](#module_transaction-converter.asTransactionObjects) method. + +To get a transaction's trytes from the Tangle, use the [`getTrytes()`](#module_core.getTrytes) method. + +**Returns**: Transaction - transactionObject - A transaction object +**Example** +```js +let transactionObject = TransactionConverter.asTransactionObject(transactionTrytes); +``` + + +### *transaction-converter*.asTransactionObjects([hashes]) +**Summary**: Converts one or more transaction trytes into transaction objects. +**Throws**: + +- errors.INVALID\_TRYTES : Make sure that transcactions contains valid trytes (A-Z or 9). -### *transaction-converter*~asTransactionObjects([hashes]) | Param | Type | Description | | --- | --- | --- | -| [hashes] | Array.<Hash> | Optional list of known hashes. Known hashes are directly mapped to transaction objects, otherwise all hashes are being recalculated. | +| [hashes] | Array.<Hash> | Transaction hashes | -Converts a list of transaction trytes into list of transaction objects. -Accepts a list of hashes and returns a mapper. In cases hashes are given, -the mapper function map them to converted objects. +This method takes an array of transaction hashes and returns a mapper. -**Returns**: function - [`transactionObjectsMapper`](#module_transaction.transactionObjectsMapper) +If any hashes are given, the mapper function maps them to their converted objects. Otherwise, all hashes are recalculated. + +## Related methods + +To get a transaction's trytes from the Tangle, use the [`getTrytes()`](#module_core.getTrytes) method. + +**Returns**: function - [`transactionObjectsMapper()`](#module_transaction.transactionObjectsMapper) +**Example** +```js +let transactionObjectsMapper = TransactionConverter.asTransactionObjects([hashes]); +``` ### *transaction-converter*~transactionObjectsMapper(trytes) diff --git a/packages/transaction/README.md b/packages/transaction/README.md index 9940bedc9..22cacc885 100644 --- a/packages/transaction/README.md +++ b/packages/transaction/README.md @@ -20,81 +20,338 @@ yarn add @iota/transaction * [transaction](#module_transaction) - * [~transactionHash(trits)](#module_transaction..transactionHash) + * _static_ + * [.transactionHash(buffer, [offset])](#module_transaction.transactionHash) - * [~isTransaction(tx)](#module_transaction..isTransaction) + * [.isTransaction(transaction, [minWeightMagnitude])](#module_transaction.isTransaction) - * [~isTailTransaction(transaction)](#module_transaction..isTailTransaction) + * [.isTailTransaction(transaction)](#module_transaction.isTailTransaction) - * [~isTransactionHash(hash, mwm)](#module_transaction..isTransactionHash) + * [.isHeadTransaction(transaction)](#module_transaction.isHeadTransaction) - * [~isTransactionTrytes(trytes, minWeightMagnitude)](#module_transaction..isTransactionTrytes) + * _inner_ + * [~isMultipleOfTransactionLength(lengthOrOffset)](#module_transaction..isMultipleOfTransactionLength) - * [~isAttachedTrytes(trytes)](#module_transaction..isAttachedTrytes) + * [~signatureOrMessage(buffer)](#module_transaction..signatureOrMessage) + * [~address(buffer, [offset])](#module_transaction..address) - + * [~value(buffer, [offset])](#module_transaction..value) + + * [~obsoleteTag(buffer, [offset])](#module_transaction..obsoleteTag) + + * [~issuanceTimestamp(buffer, [offset])](#module_transaction..issuanceTimestamp) + + * [~currentIndex(buffer, [offset])](#module_transaction..currentIndex) + + * [~lastIndex(buffer, [offset])](#module_transaction..lastIndex) + + * [~bundle(buffer, [offset])](#module_transaction..bundle) + + * [~trunkTransaction(buffer, [offset])](#module_transaction..trunkTransaction) + + * [~branchTransaction(buffer, [offset])](#module_transaction..branchTransaction) + + * [~tag(buffer, [offset])](#module_transaction..tag) + + * [~attachmentTimestamp(buffer, [offset])](#module_transaction..attachmentTimestamp) + + * [~attachmentTimestampLowerBound(buffer, [offset])](#module_transaction..attachmentTimestampLowerBound) + + * [~attachmentTimestampUpperBound(buffer, [offset])](#module_transaction..attachmentTimestampUpperBound) + + * [~transactionNonce(buffer, [offset])](#module_transaction..transactionNonce) + + * [~bundle(buffer, [offset])](#module_transaction..bundle) + + + + +### *transaction*.transactionHash(buffer, [offset]) +**Summary**: Generates the transaction hash for a given transaction. +**Throws**: + +- errors.ILLEGAL\_TRANSACTION\_BUFFER\_LENGTH : Make sure that the `buffer` argument contains 8,019 trits (the length of a transaction without the transaction hash). +- errors.ILLEGAL\_TRANSACTION\_OFFSET : Make sure that the `offset` argument is a multiple of 8,019 (the length of a transaction without the transaction hash). + + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Int8Array | | Transactions in trits | +| [offset] | Number | 0 | Offset in trits to define a transaction to hash in the `buffer` argument | + +This method takes transaction trits, and returns the transaction hash. + +## Related methods + +To validate the length of transaction trits, use the [`isMultipleOfTransactionLength()`](#module_transaction.isMultipleOfTransactionLength) method. + +To get a transaction's trits from the Tangle, use the [`getTrytes()`](#module_core.getTrytes) method, then convert them to trits, using the [`trytesToTrits()`](#module_converter.trytesToTrits) method. + +**Returns**: Int8Array - Transaction hash +**Example** +```js +let hash = Transaction.transactionHash(transactions); +``` + + +### *transaction*.isTransaction(transaction, [minWeightMagnitude]) +**Summary**: Validates the structure and contents of a given transaction. +**Throws**: + +- errors.ILLEGAL\_MIN\_WEIGHT\_MAGNITUDE : Make sure that the `minWeightMagnitude` argument is a number between 1 and 81. +- errors.ILLEGAL\_TRANSACTION\_BUFFER\_LENGTH : Make sure that the `transaction` argument contains 8,019 trits (the length of a transaction without the transaction hash). + + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| transaction | Int8Array | | Transaction trits | +| [minWeightMagnitude] | number | 0 | Minimum weight magnitude | + +This method takes an array of transaction trits and validates whether they form a valid transaction by checking the following: + +- Addresses in value transactions have a 0 trit at the end, which means they were generated using the Kerl hashing function +- The transaction would result in a valid hash, according to the given [`minWeightMagnitude`](https://docs.iota.org/docs/getting-started/0.1/network/minimum-weight-magnitude) argument + +## Related methods + +To get a transaction's trits from the Tangle, use the [`getTrytes()`](#module_core.getTrytes) method, then convert them to trits, using the [`trytesToTrits()`](#module_converter.trytesToTrits) method. + +**Returns**: boolean - valid - Whether the transaction is valid. +**Example** +```js +let valid = Transaction.isTransaction(transaction); +``` + + +### *transaction*.isTailTransaction(transaction) +**Summary**: Checks if the given transaction is a tail transaction in a bundle. +**Throws**: + +- errors.ILLEGAL\_TRANSACTION\_BUFFER\_LENGTH : Make sure that the `transaction` argument contains 8,019 trits (the length of a transaction without the transaction hash). -### *transaction*~transactionHash(trits) | Param | Type | Description | | --- | --- | --- | -| trits | Int8Array | Int8Array of 8019 transaction trits | +| transaction | Int8Array | Transaction trits | -Calculates the transaction hash out of 8019 transaction trits. +This method takes an array of transaction trits, and checks its `currentIndex` field to validate whether it is the tail transaction in a bundle. -**Returns**: Hash - Transaction hash - +## Related methods -### *transaction*~isTransaction(tx) +To get a transaction's trits from the Tangle, use the [`getTrytes()`](#module_core.getTrytes) method, then convert them to trits, using the [`trytesToTrits()`](#module_converter.trytesToTrits) method. -| Param | Type | -| --- | --- | -| tx | object | +**Returns**: boolean - tail - Whether the transaction is a tail transaction. +**Example** +```js +let tail = Transaction.isTailTransaction(transaction); +``` + -Checks if input is valid transaction object. +### *transaction*.isHeadTransaction(transaction) +**Summary**: Checks if the given transaction is a head transaction in a bundle. +**Throws**: - +- errors.ILLEGAL\_TRANSACTION\_BUFFER\_LENGTH : Make sure that the `transaction` argument contains 8,019 trits (the length of a transaction without the transaction hash). -### *transaction*~isTailTransaction(transaction) -| Param | Type | -| --- | --- | -| transaction | object | +| Param | Type | Description | +| --- | --- | --- | +| transaction | Int8Array | Transaction trits | -Checks if given transaction object is tail transaction. -A tail transaction is one with `currentIndex=0`. +This method takes an array of transaction trits, and checks its `currentIndex` field to validate whether it is the head transaction in a bundle. - +## Related methods -### *transaction*~isTransactionHash(hash, mwm) +To get a transaction's trits from the Tangle, use the [`getTrytes()`](#module_core.getTrytes) method, then convert them to trits, using the [`trytesToTrits()`](#module_converter.trytesToTrits) method. + +**Returns**: boolean - head - Whether the transaction is a head transaction. +**Example** +```js +let head = Transaction.isHeadTransaction(transaction); +``` + + +### *transaction*~isMultipleOfTransactionLength(lengthOrOffset) | Param | Type | | --- | --- | -| hash | string | -| mwm | number | +| lengthOrOffset | Int8Array | -Checks if input is correct transaction hash (81 trytes) +Checks if given value is a valid transaction buffer length or offset. - + -### *transaction*~isTransactionTrytes(trytes, minWeightMagnitude) +### *transaction*~signatureOrMessage(buffer) -| Param | Type | -| --- | --- | -| trytes | string | -| minWeightMagnitude | number | +| Param | Type | Description | +| --- | --- | --- | +| buffer | Int8Array | Transaction trytes | -Checks if input is correct transaction trytes (2673 trytes) +Gets the `signatureOrMessage` field of all transactions in a bundle. - + -### *transaction*~isAttachedTrytes(trytes) +### *transaction*~address(buffer, [offset]) -| Param | Type | -| --- | --- | -| trytes | string | +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Int8Array | | Transaction buffer. Buffer length must be a multiple of transaction length | +| [offset] | Number | 0 | Transaction trit offset. It must be a multiple of transaction length. | + +Returns a copy of `address` field. + + + +### *transaction*~value(buffer, [offset]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Int8Array | | Transaction buffer. Buffer length must be a multiple of transaction length. | +| [offset] | Number | 0 | Transaction trit offset. It must be a multiple of transaction length. | + +Returns a copy of `value` field. + + + +### *transaction*~obsoleteTag(buffer, [offset]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Int8Array | | Transaction buffer. Buffer length must be a multiple of transaction length. | +| [offset] | Number | 0 | Transaction trit offset. It must be a multiple of transaction length. | + +Returns a copy of `obsoleteTag` field. + + + +### *transaction*~issuanceTimestamp(buffer, [offset]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Int8Array | | Transaction buffer. Buffer length must be a multiple of transaction length. | +| [offset] | Number | 0 | Transaction trit offset. It must be a multiple of transaction length. | + +Returns a copy of `issuanceTimestamp` field. + + + +### *transaction*~currentIndex(buffer, [offset]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Int8Array | | Transaction buffer. Buffer length must be a multiple of transaction length. | +| [offset] | Number | 0 | Transaction trit offset. It must be a multiple of transaction length. | + +Returns a copy of `currentIndex` field. + + + +### *transaction*~lastIndex(buffer, [offset]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Int8Array | | Transaction buffer. Buffer length must be a multiple of transaction length. | +| [offset] | Number | 0 | Transaction trit offset. It must be a multiple of transaction length. | + +Returns a copy of `lastIndex` field. + + + +### *transaction*~bundle(buffer, [offset]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Int8Array | | Transaction buffer. Buffer length must be a multiple of transaction length. | +| [offset] | Number | 0 | Transaction trit offset. It must be a multiple of transaction length. | + +Returns a copy of `bundle` field. + + + +### *transaction*~trunkTransaction(buffer, [offset]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Int8Array | | Transaction buffer. Buffer length must be a multiple of transaction length. | +| [offset] | Number | 0 | Transaction trit offset. It must be a multiple of transaction length. | + +Returns a copy of `trunkTransaction` field. + + + +### *transaction*~branchTransaction(buffer, [offset]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Int8Array | | Transaction buffer. Buffer length must be a multiple of transaction length. | +| [offset] | Number | 0 | Transaction trit offset. It must be a multiple of transaction length. | + +Returns a copy of `branchTransaction` field. + + + +### *transaction*~tag(buffer, [offset]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Int8Array | | Transaction buffer. Buffer length must be a multiple of transaction length. | +| [offset] | Number | 0 | Transaction trit offset. It must be a multiple of transaction length. | + +Returns a copy of `tag` field. + + + +### *transaction*~attachmentTimestamp(buffer, [offset]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Int8Array | | Transaction buffer. Buffer length must be a multiple of transaction length. | +| [offset] | Number | 0 | Transaction trit offset. It must be a multiple of transaction length. | + +Returns a copy of `attachmentTimestamp` field. + + + +### *transaction*~attachmentTimestampLowerBound(buffer, [offset]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Int8Array | | Transaction buffer. Buffer length must be a multiple of transaction length. | +| [offset] | Number | 0 | Transaction trit offset. It must be a multiple of transaction length. | + +Returns a copy of `attachmentTimestampLowerBound` field. + + + +### *transaction*~attachmentTimestampUpperBound(buffer, [offset]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Int8Array | | Transaction buffer. Buffer length must be a multiple of transaction length. | +| [offset] | Number | 0 | Transaction trit offset. It must be a multiple of transaction length. | + +Returns a copy of `attachmentTimestampUpperBound` field. + + + +### *transaction*~transactionNonce(buffer, [offset]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Int8Array | | Transaction buffer. Buffer length must be a multiple of transaction length. | +| [offset] | Number | 0 | Transaction trit offset. It must be a multiple of transaction length. | + +Returns a copy of `tansactionNonce` field. + + + +### *transaction*~bundle(buffer, [offset]) + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| buffer | Int8Array | | Transaction buffer. Buffer length must be a multiple of transaction length. | +| [offset] | Number | 0 | Transaction trit offset. It must be a multiple of transaction length. | -Checks if input is valid attached transaction trytes. -For attached transactions last 241 trytes are non-zero. +Returns a copy of transaction essence fields. diff --git a/packages/types.ts b/packages/types.ts index ce72d2f1d..bf05bdb20 100644 --- a/packages/types.ts +++ b/packages/types.ts @@ -186,7 +186,6 @@ export interface Balances { export interface GetInclusionStatesCommand extends BaseCommand { readonly command: IRICommand.GET_INCLUSION_STATES readonly transactions: ReadonlyArray - readonly tips: ReadonlyArray } export interface GetInclusionStatesResponse { diff --git a/packages/unit-converter/README.md b/packages/unit-converter/README.md index 22f31f4ad..a6103db42 100644 --- a/packages/unit-converter/README.md +++ b/packages/unit-converter/README.md @@ -17,16 +17,29 @@ yarn add @iota/unit-converter ## API Reference - + -### *unit-converter*~convertUnits(value, fromUnit, toUnit) +### *unit-converter*.convertUnits(value, fromUnit, toUnit) +**Summary**: Converts a value of IOTA tokens from one unit to another. | Param | Type | Description | | --- | --- | --- | -| value | string \| int \| float | | -| fromUnit | string | Name of original value unit | -| toUnit | string | Name of unit wich we convert to | - -Converts accross IOTA units. Valid unit names are: -`i`, `Ki`, `Mi`, `Gi`, `Ti`, `Pi` - +| value | String \| integer \| float | Number of IOTA tokens | +| fromUnit | String | Unit of the `value` argument | +| toUnit | String | Unit to which to convert the value to | + +This method converts a value of [IOTA tokens](https://docs.iota.org/docs/getting-started/0.1/clients/token) from a given unit to another given unit. + +Valid unit names include the following: +- `i`: 1 +- `Ki`: 1,000 +- `Mi`: 1,000,000 +- `Gi`: 1,000,000,000 +- `Ti`: 1,000,000,000,000 +- `Pi`: 1,000,000,000,000,000 + +**Returns**: number - newUnit - The number of units of IOTA tokens +**Example** +```js +let newUnit = UnitConverter.convertUnits(100, 'Ti', 'Pi'); +``` diff --git a/packages/validators/README.md b/packages/validators/README.md index a40640315..537c378c0 100644 --- a/packages/validators/README.md +++ b/packages/validators/README.md @@ -20,28 +20,74 @@ yarn add @iota/validators * [validators](#module_validators) - * [~isTrytes(trytes, [length])](#module_validators..isTrytes) + * _static_ + * [.isAddress(address)](#module_validators.isAddress) - * [~isTrytesOfExactLength(trytes, length)](#module_validators..isTrytesOfExactLength) + * _inner_ + * [~isTrits(input)](#module_validators..isTrits) - * [~isTrytesOfMaxLength(trytes, length)](#module_validators..isTrytesOfMaxLength) + * [~isNullTrits(trits)](#module_validators..isNullTrits) - * [~isEmpty(hash)](#module_validators..isEmpty) + * [~isTrytes(trytes, [length])](#module_validators..isTrytes) - * [~isHash(hash)](#module_validators..isHash) + * [~isTrytesOfExactLength(trytes, length)](#module_validators..isTrytesOfExactLength) - * [~isInput(address)](#module_validators..isInput) + * [~isTrytesOfMaxLength(trytes, length)](#module_validators..isTrytesOfMaxLength) - * [~isTag(tag)](#module_validators..isTag) + * [~isEmpty(hash)](#module_validators..isEmpty) - * [~isTransfer(transfer)](#module_validators..isTransfer) + * [~isHash(hash)](#module_validators..isHash) - * [~isUri(uri)](#module_validators..isUri) + * [~isInput(address)](#module_validators..isInput) - * [~validate()](#module_validators..validate) + * [~isTag(tag)](#module_validators..isTag) - * [~isAddress(address)](#module_validators..isAddress) + * [~isTransfer(transfer)](#module_validators..isTransfer) + * [~isUri(uri)](#module_validators..isUri) + + * [~validate()](#module_validators..validate) + + + + +### *validators*.isAddress(address) +**Summary**: Validates the checksum of the given address. + +| Param | Type | Description | +| --- | --- | --- | +| address | string | Address with a checksum | + +This method takes an address with a checksum and validates that the checksum is correct. + +## Related methods + +To generate a new address with a checksum, use the [`getNewAddress()`](#module_core.getNewAddress) method. + +**Returns**: boolean - valid - Whether the checksum is valid +**Example** +```js +let valid = Validator.isAddress('9FNJWLMBECSQDKHQAGDHDPXBMZFMQIMAFAUIQTDECJVGKJBKHLEBVU9TWCTPRJGYORFDSYENIQKBVSYKW9NSLGS9UW'); +``` + + +### *validators*~isTrits(input) + +| Param | Type | +| --- | --- | +| input | any | + +Checks if input is an `Int8Array` of trit values; `-1, 0, 1`. + + + +### *validators*~isNullTrits(trits) + +| Param | Type | +| --- | --- | +| trits | Int8Array | + +Checks if trits are NULL. @@ -164,13 +210,3 @@ try { console.log(err.message) // 'Invalid trytes' } ``` - - -### *validators*~isAddress(address) - -| Param | Type | Description | -| --- | --- | --- | -| address | string | Address trytes, with checksum | - -Checks integrity of given address by validating the checksum. - From 5f16dc79de9f27a5bd69977e8e0e65e0a0a8adc1 Mon Sep 17 00:00:00 2001 From: Umair Sarfraz Date: Sun, 14 Jun 2020 07:55:53 +0500 Subject: [PATCH 2/2] docs: remove getLatestInclusion refs --- README.md | 2 -- api_reference.md | 42 +---------------------------------------- packages/core/README.md | 39 -------------------------------------- 3 files changed, 1 insertion(+), 82 deletions(-) diff --git a/README.md b/README.md index 762fca804..e6748f4ed 100644 --- a/README.md +++ b/README.md @@ -121,8 +121,6 @@ For details on all available API methods, see the [reference page](api_reference * [.getInputs(seed, [options], [callback])](api_reference.md#module_core.getInputs) -* [.getLatestInclusion(transactions, tips, [callback])](api_reference.md#module_core.getLatestInclusion) - * [.getNeighbors([callback])](api_reference.md#module_core.getNeighbors) * [.getNewAddress(seed, [options], [callback])](api_reference.md#module_core.getNewAddress) diff --git a/api_reference.md b/api_reference.md index ffc6f5b46..096052fb0 100644 --- a/api_reference.md +++ b/api_reference.md @@ -320,10 +320,6 @@ Converts an integer value to trits * [.getInputs(seed, [options], [callback])](#module_core.getInputs) - * [.createGetLatestInclusion(provider)](#module_core.createGetLatestInclusion) - - * [.getLatestInclusion(transactions, tips, [callback])](#module_core.getLatestInclusion) - * [.createGetNeighbors(provider)](#module_core.createGetNeighbors) * [.getNeighbors([callback])](#module_core.getNeighbors) @@ -947,42 +943,6 @@ getInputs(seed, { start: 0, threhold }) // ... }) ``` - - -### *core*.createGetLatestInclusion(provider) - -| Param | Type | Description | -| --- | --- | --- | -| provider | Provider | Network provider for accessing IRI | - -**Returns**: function - [`getLatestInclusion`](#module_core.getLatestInclusion) - - -### *core*.getLatestInclusion(transactions, tips, [callback]) -**Fulfil**: boolean[] List of inclusion states -**Reject**: Error -- `INVALID_HASH`: Invalid transaction hash -- Fetch error - -| Param | Type | Description | -| --- | --- | --- | -| transactions | Array.<Hash> | List of transactions hashes | -| tips | number | List of tips to check if transactions are referenced by | -| [callback] | Callback | Optional callback | - -Fetches inclusion states of given transactions and a list of tips, -by calling [`getInclusionStates`](#module_core.getInclusionStates) on `latestSolidSubtangleMilestone`. - -**Example** -```js -getLatestInclusion(hashes) - .then(states => { - // ... - }) - .catch(err => { - // handle error - }) -``` ### *core*.createGetNeighbors(provider) @@ -1241,7 +1201,7 @@ or should be [_reattached_](#module_core.replayBundle) // We need to monitor inclusion states of all tail transactions (original tail & reattachments) const tails = [tail] -getLatestInclusion(tails) +getInclusionStates(tails) .then(states => { // Check if none of transactions confirmed if (states.indexOf(true) === -1) { diff --git a/packages/core/README.md b/packages/core/README.md index e8c5bd52b..426086cf5 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -53,8 +53,6 @@ yarn add @iota/core * [.getInputs(seed, [options], [callback])](#module_core.getInputs) - * [.getLatestInclusion(transactions, [callback])](#module_core.getLatestInclusion) - * [.getNeighbors([callback])](#module_core.getNeighbors) * [.getNewAddress(seed, [options], [callback])](#module_core.getNewAddress) @@ -632,43 +630,6 @@ getInputs(seed) } }); ``` - - -### *core*.getLatestInclusion(transactions, [callback]) -**Summary**: Finds out if one or more given transactions are [confirmed or pending](https://docs.iota.org/docs/getting-started/0.1/network/the-tangle#transaction-states). -**Fulfil**: boolean[] states - Array of inclusion states, where `true` means that the transaction is confirmed and `false` means that it's not. -**Reject**: Error error - An error that contains one of the following: -- `INVALID_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](https://docs.iota.org/docs/node-software/0.1/iri/references/api-errors) - -| Param | Type | Description | -| --- | --- | --- | -| transactions | Array.<Hash> | List of transactions hashes to check | -| [callback] | Callback | Optional callback function | - -This method uses the node's `latestSolidSubtangleMilestone` field as the `tips` argument to make sure that the given transactions are referenced by the node's latest solid milestone. - -An invalid transaction will always remain in a pending state. - -**Note:** If a valid transaction is in a pending state for too long, you can [increase its chances of being confirmed](https://docs.iota.org/docs/client-libraries/0.1/how-to-guides/js/confirm-pending-bundle). - -## Related methods - -To check if transactions are referenced by a non-milestone transaction, use the [`getInclusionStates()`](#module_core.getInclusionStates) method. - -**Example** -```js -iota.getLatestInclusionState(['transactionHash']) -.then(states => { - for(let i = 0; i < states.length; i++){ - states[i]? console.log(`Transaction ${i} is confirmed`) : - console.log(`transaction ${i} is pending`); - } - }) -.catch(error => { - console.log(`Something went wrong: ${error}`); - }); -``` ### *core*.getNeighbors([callback])