{"bugs":{"url":"https://github.com/streamr-dev/streamr-client/issues"},"dist":{"shasum":"08d995f4011b56d437f9e1df135d064b477a6118","tarball":"https://registry.npmjs.org/streamr-client/-/streamr-client-6.0.0-alpha.25.tgz","fileCount":241,"integrity":"sha512-kksBx9haxL7vVLMw7NDTnSbht2SE62Zr5VivKUVLqRMHZXMxVyzqq0i90RU86CpCWr+dcMz5zumJLdS44bpllg==","signatures":[{"sig":"MEQCIGvlZo5LyQWleFPime06/JrrT5jQXHxGzrDzXncTF7qSAiAsAWUD9LH1/MzkL8PVdjpKsHsYC3FSYPaJbpZsxhaIsA==","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":22402254,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJh8ZMSCRA9TVsSAnZWagAATA4P/3d6NHuZQy6dtS9oVLlz\nk7d/r/WANB1kz8j1V3AHFGw/YowWpgI3y32gHqrWtoxjYhABbD1sNPQPu0LY\nW88C12XwsGr0T9JVh/q8SLxGYVxrZr8agnoo0SfHYXk846zmA0raEy+4jdMx\nq3q7FEzdIW3MHqlNMJGMlAqi2OQbuKBvnouMUMbEsFqpTVYD7gkOdVBKtqad\nvB3ywak/RKKw5CHparjet75C3X10Y5bZ7WsNEAFeeR+iQD+t81aUr067nVJE\ntnZgwMpQRWA/Kf8Cvdb/beZ1ntwXQUerm1o478UL4BeplhULEkkO99AKkft3\nc+mNpN25uXmDqNuvrrIJlY+8lzWbD3RJi2DExC53MQ/uBlnaoKVIjhcNY8Wz\nfpUwTKrHGedxMFTXA33fC0ERlKs7r4gy660EkpRdc/CwJHiq9YIQKKWM0XMs\nZ5zEWWPRMOPtgner3MuBaehksvhDdS1vCor2R0rQqEhLce9hSzMZySUpxs0j\nYGNm6NZKLLOQ2P77ZNIUsXpSlJxmb3ej9CWgInyMKvGg1e31UAn6n1PkKDVs\ndV+uJ0bvV4LvOll8zxMCCb8Q8pvXcnLc0v5UwuVOx+czLcWYkPbgmgcEuILq\neDyhB9FYOOt8gGIn+FaxHOjP0vQQY6m0PumQPmyEr0fGtY/fAvM4xklxIL6U\nXLnV\r\n=36Tx\r\n-----END PGP SIGNATURE-----\r\n"},"main":"./src/index-commonjs.js","name":"streamr-client","types":"./types/src/index.d.ts","author":{"name":"Streamr"},"readme":"<p align=\"center\">\n  <a href=\"https://streamr.network\">\n    <img alt=\"Streamr\" src=\"https://raw.githubusercontent.com/streamr-dev/network-monorepo/main/packages/client/readme-header-img.png\" width=\"1320\" />\n  </a>\n</p>\n\n<h1 align=\"left\">\n  Streamr JavaScript Client\n</h1>\n\n[![Build status](https://github.com/streamr-dev/monorepo/actions/workflows/client-build.yml/badge.svg)](https://github.com/streamr-dev/monorepo/actions/workflows/client-build.yml)\n![latest npm package version](https://img.shields.io/npm/v/streamr-client?label=latest)\n[![GitHub stars](https://img.shields.io/github/stars/streamr-dev/network-monorepo?style=social)\n[![Discord Chat](https://img.shields.io/discord/801574432350928907.svg?label=Discord&logo=Discord&colorB=7289da)](https://discord.gg/FVtAph9cvz)\n\nThis library allows you to easily interact with the [Streamr Network](https://streamr.network) from JavaScript-based environments, such as browsers and [node.js](https://nodejs.org). The library wraps a Streamr light node for publishing and subscribing to data, as well as contains convenience functions for creating and managing streams.\n\nPlease see the [Streamr project docs](https://streamr.network/docs) for more detailed documentation.\n\n## Important information\n\nThe current stable version of the Streamr Client is `5.x` (at the time of writing, December 2021) which is connected to the [Corea Network](https://streamr.network/roadmap). The Brubeck Network Streamr Client is the [6.0.0-alpha.19](https://www.npmjs.com/package/streamr-client/v/6.0.0-alpha.19) build along with the `testnet` builds of the Broker node. The developer experience of the two networks is the same, however, the `6.0.0-alpha.19` client also runs as a light node in the network, whereas the `5.x` era client communicates remotely to a Streamr run node. When the Streamr Network transitions into the Brubeck era (ETA Jan/Feb 2022), data guarantees of `5.x` clients will need to be reassessed. Publishing data to the Brubeck network will only be visible in the [Brubeck Core UI](https://brubeck.streamr.network). The Marketplace, Core app and CLI tool are currently all configured to interact with the Corea Network only. Take care not to mix networks during this transition period.\n\n----\n\n## Table of contents\n\n[Installation](#installation) · [Usage](#usage) · [API Docs](#API-docs) · [Client options](#client-options) · [Authentication](#authentication-options) · [Managing subscriptions](#managing-subscriptions) · [Stream API](#stream-api) · [Subscription options](#subscription-options) · [Storage](#storage) ·[Data Unions](#data-unions) · [Utility functions](#utility-functions) · [Events](#events) · [Stream Partitioning](#stream-partitioning) · [Logging](#logging) · [NPM Publishing](#publishing-latest)\n\n\n## Installation\n\nThe client is available on [npm](https://www.npmjs.com/package/streamr-client) and can be installed simply by:\n\n```\nnpm install streamr-client\n```\n\n## Usage\n\nHere are some usage examples. More examples can be found [here](https://github.com/streamr-dev/examples).\n\nIn Streamr, Ethereum accounts are used for identity. You can generate an Ethereum private key using any Ethereum wallet, or you can use the utility function `StreamrClient.generateEthereumAccount()`, which returns the address and private key of a fresh Ethereum account.\n\n### Creating a StreamrClient instance\n\n```js\nconst client = new StreamrClient({\n    auth: {\n        privateKey: 'your-ethereum-private-key'\n    }\n})\n```\n\nWhen using Node.js remember to import the library with:\n\n```js\nimport { StreamrClient } from 'streamr-client'\n```\n\n### Subscribing to real-time events in a stream\n\n```js\nconst sub = await client.subscribe({\n    stream: 'streamId',\n    partition: 0, // Optional, defaults to zero. Use for partitioned streams to select partition.\n    // optional resend options here\n}, (message, metadata) => {\n    // This is the message handler which gets called for every incoming message in the stream.\n    // Do something with the message here!\n})\n```\n\n### Resending historical data\n\n```js\nconst sub = await client.resend({\n    stream: 'streamId',\n    resend: {\n        last: 5,\n    },\n}, (message) => {\n    // This is the message handler which gets called for every received message in the stream.\n    // Do something with the message here!\n})\n```\n\nSee \"Subscription options\" for resend options\n\n### Programmatically creating a stream\n\n```js\nconst stream = await client.createStream({\n    id: '/foo/bar', // or 0x1234567890123456789012345678901234567890/foo/bar or mydomain.eth/foo/bar\n})\nconsole.log(`Stream ${stream.id} has been created!`)\n\n// Optional: to enable historical data resends, add the stream to a storage node\nconst { StorageNode, StreamrClient } = require('streamr-client').StreamrClient\nawait stream.addToStorageNode(StorageNode.STREAMR_GERMANY)\n\n// Do something with the stream, for example call stream.publish(message)\n```\n\n### Publishing data points to a stream\n\n```js\n// Here's our example data point\nconst msg = {\n    temperature: 25.4,\n    humidity: 10,\n    happy: true\n}\n\n// Publish using the stream id only\nawait client.publish('my-stream-id', msg)\n\n// The first argument can also be the stream object\nawait client.publish(stream, msg)\n\n// Publish with a specific timestamp as a Date object (default is now)\nawait client.publish('my-stream-id', msg, new Date(54365472))\n\n// Publish with a specific timestamp in ms\nawait client.publish('my-stream-id', msg, 54365472)\n\n// Publish with a specific timestamp as a ISO8601 string\nawait client.publish('my-stream-id', msg, '2019-01-01T00:00:00.123Z')\n\n// Publish with a specific partition key (read more about partitioning further down this readme)\nawait client.publish('my-stream-id', msg, Date.now(), 'my-partition-key')\n\n// For convenience, stream.publish(...) equals client.publish(stream, ...)\nawait stream.publish(msg)\n```\n\n----\n\n## Client options\n\n| Option                   | Default value                    | Description                                                                                                                                                                                                                                                                                                                             |\n| :----------------------- | :------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| url                      | wss://streamr.network/api/v1/ws  | Address of the Streamr websocket endpoint to connect to.                                                                                                                                                                                                                                                                                |\n| restUrl                  | <https://streamr.network/api/v1> | Base URL of the Streamr REST API.                                                                                                                                                                                                                                                                                                       |\n| auth                     | {}                               | Object that can contain different information to authenticate. More details below.                                                                                                                                                                                                                                                      |\n| publishWithSignature     | 'auto'                           | Determines if data points published to streams are signed or not. Possible values are: 'auto', 'always' and 'never'. Signing requires `auth.privateKey` or `auth.ethereum`.  'auto' will sign only if one of them is set. 'always' will throw an exception if none of them is set.                                                      |\n| verifySignatures         | 'auto'                           | Determines under which conditions signed and unsigned data points are accepted or rejected. 'always' accepts only signed and verified data points. 'never' accepts all data points. 'auto' verifies all signed data points before accepting them and accepts unsigned data points only for streams not supposed to contain signed data. |\n| autoConnect              | true                             | If set to `true`, the client connects automatically on the first call to `subscribe()`. Otherwise an explicit call to `connect()` is required.                                                                                                                                                                                          |\n| autoDisconnect           | true                             | If set to `true`, the client automatically disconnects when the last stream is unsubscribed. Otherwise the connection is left open and can be disconnected explicitly by calling `disconnect()`.                                                                                                                                        |\n| orderMessages            | true                             | If set to `true`, the subscriber handles messages in the correct order, requests missing messages and drops duplicates. Otherwise, the subscriber processes messages as they arrive without any check.                                                                                                                                  |\n| maxPublishQueueSize      | 10000                            | Only in effect when `autoConnect = true`. Controls the maximum number of messages to retain in internal queue when client has disconnected and is reconnecting to Streamr.                                                                                                                                                              |\n| publisherGroupKeys       | {}                               | Object defining the group key as a hex string used to encrypt for each stream id.                                                                                                                                                                                                                                                       |\n| publisherStoreKeyHistory | true                             | If `true`, the client will locally store every key used to encrypt messages at some point. If set to `false`, the client will not be able to answer subscribers asking for historical keys during resend requests.                                                                                                                      |\n| subscriberGroupKeys      | {}                               | Object defining, for each stream id, an object containing the group key used to decrypt for each publisher id. Not needed if `keyExchange` is defined.                                                                                                                                                                                  |\n| keyExchange              | {}                               | Defines RSA key pair to use for group key exchange. Can define `publicKey` and `privateKey` fields as strings in the PEM format, or stay empty to generate a key pair automatically. Can be set to `null` if no key exchange is required.                                                                                               |\n\n## Authentication options\n\nNote: **Authenticating with an API key has been deprecated. Cryptographic keys/wallets is the only supported authentication method.**\n\nIf you don't have an Ethereum account you can use the utility function `StreamrClient.generateEthereumAccount()`, which returns the address and private key of a fresh Ethereum account.\n\nAuthenticating with Ethereum also automatically creates an associated Streamr user, even if it doesn't already exist. Under the hood, the client will cryptographically sign a challenge to authenticate you as a Streamr user:\n\n```js\nconst client = new StreamrClient({\n    auth: {\n        privateKey: 'your-private-key'\n    }\n})\n```\n\nAuthenticating with an Ethereum private key contained in an Ethereum (web3) provider:\n\n```js\nconst client = new StreamrClient({\n    auth: {\n        ethereum: window.ethereum,\n    }\n})\n```\n\nAuthenticating with a pre-existing session token (used internally by the Streamr app):\n\n```js\nconst client = new StreamrClient({\n    auth: {\n        sessionToken: 'session-token'\n    }\n})\n```\n\nTo extract the session token from an authenticated client:\n\n```js\nconst bearerToken = await client.session.getSessionToken()\n```\n\nThen for example,\n```js\n    axios({\n        headers: {\n            Authorization: `Bearer ${bearerToken}`,\n        },\n        ...\n    )}\n```\n\nNote, session tokens expire after four hours and may need to be refreshed.\n\n## Connecting\n\nBy default the client will automatically connect and disconnect as needed, ideally you should not need to manage connection state explicitly.\nSpecifically, it will automatically connect when you publish or subscribe, and automatically disconnect once all subscriptions are removed and no\nmessages were recently published. This behaviour can be disabled using the `autoConnect` & `autoDisconnect` options when creating a `new\nStreamrClient`. Explicit calls to either `connect()` or `disconnect()` will disable all `autoConnect` & `autoDisconnect` functionality, but they can\nbe re-enabled by calling `enableAutoConnect()` or `enableAutoDisconnect()`.\n\nCalls that need a connection, such as `publish` or `subscribe` will fail with an error if you are disconnected and autoConnect is disabled.\n\n| Name                                | Description                                                                                                                                                                                         |\n| :---------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| connect()                           | Safely connects if not connected. Returns a promise. Resolves immediately if already connected. Only rejects if an error occurs during connection.                                                  |\n| disconnect()                        | Safely disconnects if not already disconnected, clearing all subscriptions. Returns a Promise.  Resolves immediately if already disconnected. Only rejects if an error occurs during disconnection. |\n| enableAutoConnect(enable = true)    | Enables autoConnect if it wasn't already enabled. Does not connect immediately. Use `enableAutoConnect(false)` to disable autoConnect.                                                              |\n| enableAutoDisconnect(enable = true) | Enables autoDisconnect if it wasn't already enabled. Does not disconnect immediately. Use `enableAutoConnect(false)` to disable autoDisconnect.                                                     |\n\n```js\nconst client = new StreamrClient({\n    auth: {\n        privateKey: 'your-private-key'\n    },\n    autoConnect: false,\n    autoDisconnect: false,\n})\n\nawait client.connect()\n```\n\n## Managing subscriptions\n\n| Name                         | Description                                                                                                                                                                     |\n| :--------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| subscribe(options, callback) | Subscribes to a stream. Messages in this stream are passed to the `callback` function. See below for subscription options. Returns a Promise resolving a `Subscription` object. |\n| unsubscribe(Subscription)    | Unsubscribes the given `Subscription`. Returns a promise.                                                                                                                       |\n| unsubscribeAll(`streamId`)   | Unsubscribes all `Subscriptions` for `streamId`. Returns a promise.                                                                                                             |\n| getSubscriptions() | Returns a list of all active `Subscriptions` on this client. Returns a promise.                                                                                                            |\n\n### Message handler callback\n\nThe second argument to `client.subscribe(options, callback)` is the callback function that will be called for each message as they arrive. Its arguments are as follows:\n\n| Argument      | Description                                                                                                                                                                                                                      |\n| :------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| payload       | A JS object containing the message payload itself                                                                                                                                                                                |\n| streamMessage | The whole [StreamMessage](https://github.com/streamr-dev/streamr-client-protocol-js/blob/master/src/protocol/message_layer/StreamMessage.js) object containing various metadata, for example `streamMessage.getTimestamp()` etc. |\n\n```js\nconst sub = await client.subscribe({\n    streamId: 'my-stream-id',\n}, (payload, streamMessage) => {\n    console.log({\n        payload, streamMessage\n    })\n})\n\n```\n\n### Subscription Options\n\nNote that only one of the resend options can be used for a particular subscription. The default functionality is to resend nothing, only subscribe to messages from the subscription moment onwards.\n\n| Name      | Description                                                                        |\n| :-------- | :--------------------------------------------------------------------------------- |\n| stream    | Stream id to subscribe to                                                          |\n| partition | Partition number to subscribe to. Defaults to partition 0.                         |\n| resend    | Object defining the resend options. Below are examples of its contents.            |\n| groupKeys | Object defining the group key as a hex string for each publisher id of the stream. |\n\n```js\n// Resend N most recent messages\nconst sub1 = await client.subscribe({\n    streamId: 'my-stream-id',\n    resend: {\n        last: 10,\n    }\n}, onMessage)\n\n// Resend from a specific message reference up to the newest message\nconst sub2 = await client.subscribe({\n    streamId: 'my-stream-id',\n    resend: {\n        from: {\n            timestamp: 12345,\n            sequenceNumber: 0, // optional\n        },\n        publisher: 'publisherId', // optional\n        msgChainId: 'msgChainId', // optional\n    }\n}, onMessage)\n\n// Resend a limited range of messages\nconst sub3 = await client.subscribe({\n    streamId: 'my-stream-id',\n    resend: {\n        from: {\n            timestamp: 12345,\n            sequenceNumber: 0, // optional\n        },\n        to: {\n            timestamp: 54321,\n            sequenceNumber: 0, // optional\n        },\n        publisher: 'publisherId', // optional\n        msgChainId: 'msgChainId', // optional\n    }\n}, onMessage)\n```\n\nIf you choose one of the above resend options when subscribing, you can listen on the completion of this resend by doing the following:\n\n```js\nconst sub = await client.subscribe(options)\nsub.on('resent', () => {\n    console.log('All caught up and received all requested historical messages! Now switching to real time!')\n})\n```\n\n### Storage\n\nYou can enable data storage on your streams to retain historical data in one or more geographic locations of your choice. By default storage is not enabled on streams.\n\n`await stream.addToStorageNode(StorageNode.STREAMR_GERMANY)`\n\n## Stream API\n\nAll the below functions return a Promise which gets resolved with the result.\n\n| Name                                                | Description                                                                                                                                          |\n| :-------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------- |\n| getStream(streamId)                                 | Fetches a stream object from the API.                                                                                                                |\n| searchStreams(term)                                 | Fetches an array of stream objects      |\n| createStream(\\[properties])                         | Creates a stream with the given properties. For more information on the stream properties, consult the [API docs](https://api-explorer.streamr.com). If you specify `id`, it can be a full streamId or a path (e.g. `/foo/bar` will create a stream with id `<your-ethereum-address>/foo/bar` if you have authenticated with a private key)|\n| getOrCreateStream(properties)                       | Gets a stream with the id given in `properties`, or creates it if one is not found.                                                          |\n| publish(streamId, message, timestamp, partitionKey) | Publishes a new message to the given stream.                                                                                                         |\n\n### Stream object\n\nAll the below functions return a Promise which gets resolved with the result.\n\n| Name                                      | Description                                                                                                                                                                                                                                                                   |\n| :---------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| update()                                  | Updates the properties of this stream object by sending them to the API.                                                                                                                                                                                                      |\n| delete()                                  | Deletes this stream.                                                                                                                                                                                                                                                          |\n| getPermissions()                          | Returns the list of permissions for this stream.                                                                                                                                                                                                                              |\n| hasPermission(operation, user)            | Returns a permission object, or null if no such permission was found. Valid `operation` values for streams are: stream_get, stream_edit, stream_delete, stream_publish, stream_subscribe, and stream_share. `user` is the username of a user, or null for public permissions. |\n| grantPermission(operation, user)          | Grants the permission to do `operation` to `user`, which are defined as above.                                                                                                                                                                                                |\n| revokePermission(permissionId)            | Revokes a permission identified by its `id`.                                                                                                                                                                                                                                  |\n| detectFields()                            | Updates the stream field config (schema) to match the latest data point in the stream.                                                                                                                                                                                        |\n| publish(message, timestamp, partitionKey) | Publishes a new message to this stream.                                                                                                                                                                                                                                       |\n\n## Data Unions\n\nThis library provides functions for working with Data Unions. Please see the [TypeScript generated function documentation](https://streamr-dev.github.io/streamr-client-javascript/classes/dataunion_dataunion.dataunion.html) for information on each Data Union endpoint.\n\nTo deploy a new DataUnion with default [deployment options](#deployment-options):\n```js\nconst dataUnion = await client.deployDataUnion()\n```\n\nTo get an existing (previously deployed) `DataUnion` instance:\n```js\nconst dataUnion = client.getDataUnion(dataUnionAddress)\n```\n\nOr to verify untrusted (e.g. user) input, use:\n```js\nconst dataUnion = await client.safeGetDataUnion(dataUnionAddress)\n```\n\n<!-- This stuff REALLY isn't for those who use our infrastructure, neither DU admins nor DU client devs. It's only relevant if you're setting up your own sidechain.\nThese DataUnion-specific options can be given to `new StreamrClient` options:\n\n| Property                            | Default                                                | Description                                                                                |\n| :---------------------------------- | :----------------------------------------------------- | :----------------------------------------------------------------------------------------- |\n| dataUnion.minimumWithdrawTokenWei   | 1000000                                                | Threshold value set in AMB configs, smallest token amount that can pass over the bridge    |\n| dataUnion.payForTransport           | true                                                   | true = client does the transport as self-service and pays the mainnet gas costs            |\n|                                     |                                                        | false = someone else pays for the gas when transporting the withdraw tx to mainnet         |\n-->\n\n### Admin Functions\n\nAdmin functions require xDai tokens on the xDai network. To get xDai you can either use a [faucet](https://www.xdaichain.com/for-users/get-xdai-tokens/xdai-faucet) or you can reach out on the [Streamr Discord #dev channel](https://discord.gg/gZAm8P7hK8).\n\nAdding members using admin functions is not at feature parity with the member function `join`. The newly added member will not be granted publish permissions to the streams inside the Data Union. This will need to be done manually using, `streamr.grantPermission(stream_publish, user)`. Similarly, after removing a member using the admin function `removeMembers`, the publish permissions will need to be removed in a secondary step using `revokePermission(permissionId)`.\n\n| Name                              | Returns             | Description                                                    |\n| :-------------------------------- | :------------------ | :------------------------------------------------------------- |\n| createSecret(\\[name])             | string              | Create a secret for a Data Union                               |\n| addMembers(memberAddressList)     | Transaction receipt | Add members                                                    |\n| removeMembers(memberAddressList)  | Transaction receipt | Remove members from Data Union                                 |\n| setAdminFee(newFeeFraction[, ethersOptions]) `**`                                                     | Transaction receipt     | `newFeeFraction` is a `Number` between 0.0 and 1.0 (inclusive) |\n| withdrawAllToMember(memberAddress\\[, [options](#withdraw-options)\\])                              | Transaction receipt `*` | Send all withdrawable earnings to the member's address |\n| withdrawAllToSigned(memberAddress, recipientAddress, signature\\[, [options](#withdraw-options)\\]) | Transaction receipt `*` | Send all withdrawable earnings to the address signed off by the member (see [example below](#member-functions)) |\n| withdrawAmountToSigned(memberAddress, recipientAddress, amountTokenWei, signature\\[, [options](#withdraw-options)\\]) | Transaction receipt `*` | Send some of the withdrawable earnings to the address signed off by the member |\n\n`*` The return value type may vary depending on [the given options](#withdraw-options) that describe the use case.<br>\n`**` `ethersOptions` that `setAdminFee` takes can be found as [\"overrides\" documented in docs.ethers.io](https://docs.ethers.io/v5/api/contract/contract/#contract-functionsSend).\n\nHere's how to deploy a Data Union contract with 30% Admin fee and add some members:\n\n```js\nimport { StreamrClient } from 'streamr-client'\n\nconst client = new StreamrClient({\n    auth: { privateKey },\n})\n\nconst dataUnion = await client.deployDataUnion({\n    adminFee: 0.3,\n})\nconst receipt = await dataUnion.addMembers([\n    \"0x1234567890123456789012345678901234567890\",\n    \"0x1234567890123456789012345678901234567891\",\n    \"0x1234567890123456789012345678901234567892\",\n])\n```\n\n### Member functions\n\n| Name                                                                  | Returns                   | Description                                                                 |\n| :-------------------------------------------------------------------- | :------------------------ | :-------------------------------------------------------------------------- |\n| join(\\[secret])                                                       | JoinRequest               | Join the Data Union (if a valid secret is given, the promise waits until the automatic join request has been processed)  |\n| part()                                                                | Transaction receipt       | Leave the Data Union\n| isMember(memberAddress)                                               | boolean                   |                                                                             |\n| withdrawAll(\\[[options](#withdraw-options)\\])                         | Transaction receipt `*`   | Withdraw funds from Data Union                                              |\n| withdrawAllTo(recipientAddress\\[, [options](#withdraw-options)\\])     | Transaction receipt `*`   | Donate/move your earnings to recipientAddress instead of your memberAddress |\n| signWithdrawAllTo(recipientAddress)                                   | Signature (string)        | Signature that can be used to withdraw all available tokens to given recipientAddress        |\n| signWithdrawAmountTo(recipientAddress, amountTokenWei)                | Signature (string)        | Signature that can be used to withdraw a specific amount of tokens to given recipientAddress |\n| transportMessage(messageHash[, pollingIntervalMs[, retryTimeoutMs]])  | Transaction receipt       | Send the mainnet transaction to withdraw tokens from the sidechain |\n\n`*` The return value type may vary depending on [the given options](#withdraw-options) that describe the use case.\n\nHere's an example on how to sign off on a withdraw to (any) recipientAddress (NOTE: this requires no gas!)\n\n```js\nimport { StreamrClient } from 'streamr-client'\n\nconst client = new StreamrClient({\n    auth: { privateKey },\n})\n\nconst dataUnion = client.getDataUnion(dataUnionAddress)\nconst signature = await dataUnion.signWithdrawAllTo(recipientAddress)\n```\n\nLater, anyone (e.g. Data Union admin) can send that withdraw transaction to the blockchain (and pay for the gas)\n\n```js\nimport { StreamrClient } from 'streamr-client'\n\nconst client = new StreamrClient({\n    auth: { privateKey },\n})\n\nconst dataUnion = client.getDataUnion(dataUnionAddress)\nconst receipt = await dataUnion.withdrawAllToSigned(memberAddress, recipientAddress, signature)\n```\n\nThe `messageHash` argument to `transportMessage` will come from the withdraw function with the specific options. The following is equivalent to the above withdraw line:\n```js\nconst messageHash = await dataUnion.withdrawAllToSigned(memberAddress, recipientAddress, signature, {\n    payForTransport: false,\n    waitUntilTransportIsComplete: false,\n}) // only pay for sidechain gas\nconst receipt = await dataUnion.transportMessage(messageHash) // only pay for mainnet gas\n```\n\n### Query functions\n\nThese are available for everyone and anyone, to query publicly available info from a Data Union:\n\n| Name                                                       | Returns                                        | Description                             |\n| :--------------------------------------------------------- | :--------------------------------------------- | :-------------------------------------- |\n| getStats()                                                 | {activeMemberCount, totalEarnings, ...}        | Get Data Union's statistics             |\n| getMemberStats(memberAddress)                              | {status, totalEarnings, withdrawableEarnings}  | Get member's stats                      |\n| getWithdrawableEarnings(memberAddress)                     | `BigNumber` withdrawable DATA tokens in the DU |                                         |\n| getAdminFee()                                              | `Number` between 0.0 and 1.0 (inclusive)       | Admin's cut from revenues               |\n| getAdminAddress()                                          | Ethereum address                               | Data union admin's address              |\n| getVersion()                                               | `0`, `1` or `2`                                | `0` if the contract is not a data union |\n\nHere's an example how to get a member's withdrawable token balance (in \"wei\", where 1 DATA = 10^18 wei)\n\n```js\nimport { StreamrClient } from 'streamr-client'\n\nconst dataUnion = new StreamrClient().getDataUnion(dataUnionAddress)\nconst withdrawableWei = await dataUnion.getWithdrawableEarnings(memberAddress)\n```\n\n### Withdraw options\n\nThe functions `withdrawAll`, `withdrawAllTo`, `withdrawAllToMember`, `withdrawAllToSigned`, `withdrawAmountToSigned` all can take an extra \"options\" argument. It's an object that can contain the following parameters:\n\n| Name              | Default               | Description                                                                               |\n| :---------------- | :-------------------- | :--------------------------------------------------------------------------------------   |\n| sendToMainnet     | true                  | Whether to send the withdrawn DATA tokens to mainnet address (or sidechain address)       |\n| payForTransport   | true                  | Whether to pay for the withdraw transaction signature transport to mainnet over the bridge|\n| waitUntilTransportIsComplete | true       | Whether to wait until the withdrawn DATA tokens are visible in mainnet                    |\n| pollingIntervalMs | 1000 (1&nbsp;second)  | How often requests are sent to find out if the withdraw has completed                     |\n| retryTimeoutMs    | 60000 (1&nbsp;minute) | When to give up when waiting for the withdraw to complete                                 |\n| gasPrice          | network estimate      | Ethereum Mainnet transaction gas price to use when transporting tokens over the bridge    |\n\nThese withdraw transactions are sent to the sidechain, so gas price shouldn't be manually set (fees will hopefully stay very low),\nbut a little bit of [sidechain native token](https://www.xdaichain.com/for-users/get-xdai-tokens) is nonetheless required.\n\nThe return values from the withdraw functions also depend on the options.\n\nIf `sendToMainnet: false`, other options don't apply at all, and **sidechain transaction receipt** is returned as soon as the withdraw transaction is done. This should be fairly quick in the sidechain.\n\nThe use cases corresponding to the different combinations of the boolean flags:\n\n| `transport` | `wait`  | Returns | Effect |\n| :---------- | :------ | :------ | :----- |\n| `true`      | `true`  | Transaction receipt | *(default)* Self-service bridge to mainnet, client pays for mainnet gas |\n| `true`      | `false` | Transaction receipt | Self-service bridge to mainnet (but **skip** the wait that double-checks the withdraw succeeded and tokens arrived to destination) |\n| `false`     | `true`  | `null`              | Someone else pays for the mainnet gas automatically, e.g. the bridge operator (in this case the transaction receipt can't be returned) |\n| `false`     | `false` | AMB message hash    | Someone else pays for the mainnet gas, but we need to give them the message hash first |\n\n### Deployment options\n\n`deployDataUnion` can take an options object as the argument. It's an object that can contain the following parameters:\n\n| Name                      | Type      | Default               | Description                                                                           |\n| :------------------------ | :-------- | :-------------------- | :------------------------------------------------------------------------------------ |\n| owner                     | Address   |`*`you                 | Owner / admin of the newly created Data Union                                         |\n| joinPartAgents            | Address[] |`*`you, Streamr Core   | Able to add and remove members to/from the Data Union                                 |\n| dataUnionName             | string    | Generated             | NOT stored anywhere, only used for address derivation                                 |\n| adminFee                  | number    | 0 (no fee)            | Must be between 0...1 (inclusive)                                                     |\n| sidechainPollingIntervalMs| number    | 1000 (1&nbsp;second)  | How often requests are sent to find out if the deployment has completed               |\n| sidechainRetryTimeoutMs   | number    | 60000 (1&nbsp;minute) | When to give up when waiting for the deployment to complete                           |\n| confirmations             | number    | 1                     | Blocks to wait after Data Union mainnet contract deployment to consider it final      |\n| gasPrice                  | BigNumber | network estimate      | Ethereum Mainnet gas price to use when deploying the Data Union mainnet contract      |\n\n`*`you here means the address of the authenticated StreamrClient\n(that corresponds to the `auth.privateKey` given in constructor)\n\nStreamr Core is added as a `joinPartAgent` by default\nso that joining with secret works using the [member function](#member-functions) `join`.\nIf you don't plan to use `join` for \"self-service joining\",\nyou can leave out Streamr Core agent by calling `deployDataUnion`\ne.g. with your own address as the sole joinPartAgent:\n```\nconst dataUnion = await client.deployDataUnion({\n    joinPartAgents: [yourAddress],\n    adminFee,\n})\n```\n\n`dataUnionName` option exists purely for the purpose of predicting the addresses of Data Unions not yet deployed.\nData Union deployment uses the [CREATE2 opcode](https://eips.ethereum.org/EIPS/eip-1014) which means\na Data Union deployed by a particular address with particular \"name\" will have a predictable address.\n\n## Utility functions\n\n| Name                                    | Returns                 |   Description    |\n| :-------------------------------------- | :---------------------- | :--------------- |\n| `*` generateEthereumAccount()           | `{address, privatekey}` | Generates a random Ethereum account  |\n| getTokenBalance(address)                | `BigNumber`             | Mainnet DATA token balance |\n| getSidechainTokenBalance(address)       | `BigNumber`             | Sidechain DATA token balance |\n\n`*` The static function `StreamrClient.generateEthereumAccount()` generates a new\nEthereum private key and returns an object with fields `address` and `privateKey`.\nNote that this private key can be used to authenticate to the Streamr API\nby passing it in the authentication options, as described earlier in this document.\n\n## Events\n\nThe client and the subscriptions can fire events as detailed below.\nYou can bind to them using `on`.\n\n| Name                                | Description                                                                              |\n| :---------------------------------- | :--------------------------------------------------------------------------------------- |\n| on(eventName, function)             | Binds a `function` to an event called `eventName`                                        |\n| once(eventName, function)           | Binds a `function` to an event called `eventName`. It gets called once and then removed. |\n| removeListener(eventName, function) | Unbinds the `function` from events called `eventName`                                    |\n\n### Events on the StreamrClient instance\n\n| Name         | Handler Arguments | Description                                                      |\n| :----------- | :---------------- | :--------------------------------------------------------------- |\n| connected    |                   | Fired when the client has connected (or reconnected).            |\n| disconnected |                   | Fired when the client has disconnected (or paused).              |\n| error        | Error             | Fired when the client encounters an error e.g. connection issues |\n\n```js\n// The StreamrClient emits various events\nclient.on('connected', () => {\n    // note no need to wait for this before doing work,\n    // with autoconnect enabled the client will happily establish a connection for you as required.\n    console.log('Yeah, we are connected now!')\n})\n```\n\n### Events on the Subscription object\n\n| Name         | Handler Arguments                                                                                                                                                         | Description                                                                                         |\n| :----------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------------------------------- |\n| unsubscribed |                                                                                                                                                                           | Fired when an unsubscription is acknowledged by the server.                                         |\n| resent       | [ResendResponseResent](https://github.com/streamr-dev/streamr-client-protocol-js/blob/master/src/protocol/control_layer/resend_response_resent/ResendResponseResentV1.js) | Fired after `resending` when the subscription has finished resending and message has been processed |\n| error        | Error object                                                                                                                                                              | Reports errors, for example problems with message content                                           |\n\n## Stream Partitioning\n\nPartitioning (sharding) enables streams to scale horizontally. This section describes how to use partitioned streams via this library. To learn the basics of partitioning, see [the docs](https://streamr.network/docs/streams#partitioning).\n\n### Creating partitioned streams\n\nBy default, streams only have 1 partition when they are created. The partition count can be set to any positive number (1-100 is reasonable). An example of creating a partitioned stream using the JS client:\n\n```js\nconst stream = await client.createStream({\n    name: 'My partitioned stream',\n    partitions: 10,\n})\nconsole.log(`Stream created: ${stream.id}. It has ${stream.partitions} partitions.`)\n```\n\n### Publishing to partitioned streams\n\nIn most use cases, a user wants related events (e.g. events from a particular device) to be assigned to the same partition, so that the events retain a deterministic order and reach the same subscriber(s) to allow them to compute stateful aggregates correctly.\n\nThe library allows the user to choose a _partition key_, which simplifies publishing to partitioned streams by not requiring the user to assign a partition number explicitly. The same partition key always maps to the same partition. In an IoT use case, the device id can be used as partition key; in user interaction data it could be the user id, and so on.\n\nThe partition key can be given as an argument to the `publish` methods, and the library assigns a deterministic partition number automatically:\n\n```js\nawait client.publish('my-stream-id', msg, Date.now(), msg.vehicleId)\n\n// or, equivalently\nawait stream.publish(msg, Date.now(), msg.vehicleId)\n```\n\n### Subscribing to partitioned streams\n\nBy default, the JS client subscribes to the first partition (partition `0`) in a stream. The partition number can be explicitly given in the subscribe call:\n\n```js\nconst sub = await client.subscribe({\n    stream: 'my-stream-id',\n    partition: 4, // defaults to 0\n}, (payload) => {\n    console.log('Got message %o', payload)\n})\n```\n\nOr, to subscribe to multiple partitions, if the subscriber can handle the volume:\n\n```js\nconst handler = (payload, streamMessage) => {\n    console.log('Got message %o from partition %d', payload, streamMessage.getStreamPartition())\n}\n\nawait Promise.all([2, 3, 4].map(async (partition) => {\n    await client.subscribe({\n        stream: 'my-stream-id',\n        partition,\n    }, handler)\n}))\n```\n\n## Proxy publishing\n\nIn some cases the client might be interested in publishing data without participating in the stream's message propagation. With this option the nodes can sign all messages they publish by themselves. Alternatively, a client could open a WS connection to a broker node and allow the broker to handle signing with its private key.\n\nProxy publishing is done on the network overlay level. This means that there is no need to know the IP address of the node that will be used as a proxy. Instead, the node needs to know the ID of the network node it wants to connect to. It is not possible to set publish proxies for a stream that is already being \"traditionally\" subscribed or published to and vice versa.\n\n```js\n// Open publish proxy to a node on stream\nawait publishingClient.setPublishProxy(stream, 'proxyNodeId')\n\n// Open publish proxy to multiple nodes on stream\nawait publishingClient.setPublishProxies(stream, ['proxyNodeId1', 'proxyNodeId2'])\n\n// Remove publish proxy to a node on stream\nawait publishingClient.removePublishProxy(stream, proxyNodeId1)\n\n// Remove publish proxy to multiple nodes on stream\nawait publishingClient.removePublishProxies(stream, ['proxyNodeId1', 'proxyNodeId2'])\n```\n\nIMPORTANT: The node that is used as a proxy must have set the option on the network layer to accept incoming proxy connections.\n\n## Logging\n\nThe Streamr JS client library supports [debug](https://github.com/visionmedia/debug) for logging.\n\nIn node.js, start your app like this: `DEBUG=StreamrClient* node your-app.js`\n\nIn the browser, set `localStorage.debug = 'StreamrClient*'`\n\n## For Developers\n\nPublishing to npm is automated via Github Actions. Follow the steps below to publish `latest` or `beta`.\n\nFor more technical documentation on the Data Unions API, see the [JS Client API Docs](https://streamr-dev.github.io/streamr-client-javascript/). These can also be rebuilt locally via:\n```\nnpm run docs\n```\n\n### Publishing `latest`\n\n1.  Update version with either `npm version [patch|minor|major]`. Use\n    semantic versioning <https://semver.org/>. Files package.json and\n    package-lock.json will be automatically updated, and an appropriate\n    git commit and tag created.\n\n2.  `git push --follow-tags`\n\n3.  Wait for Github Actions to run tests\n\n4.  If tests passed, Github Actions will publish the new version to npm\n\n### Publishing `beta`\n\n1.  Update version with either `npm version [prepatch|preminor|premajor] --preid=beta`. Use semantic versioning\n    <https://semver.org/>. Files package.json and package-lock.json will be automatically updated, and an appropriate git commit and tag created.\n\n2.  `git push --follow-tags`\n\n3.  Wait for Github Actions to run tests\n\n4.  If tests passed, Github Actions will publish the new version to npm\n","browser":"./streamr-client.web.js","engines":{"node":">= 12"},"exports":{"browser":"./streamr-client.web.js","default":{"import":"./src/index-esm.mjs","require":"./src/index-commonjs.js"}},"gitHead":"9411adfd84cf4134c8d3f99ee156b22eed47bdbd","license":"Apache-2.0","_npmUser":{"name":"harbu","email":"harbuzen@gmail.com"},"homepage":"https://github.com/streamr-dev/streamr-client#readme","#IMPORTANT":"babel-runtime must be in dependencies, not devDependencies","repository":{"url":"git+https://github.com/streamr-dev/network-monorepo.git","type":"git","directory":"packages/client"},"_npmVersion":"8.3.2","description":"JavaScript client library for Streamr","directories":{},"maintainers":[{"name":"kare","email":"kare.nuorteva@me.com"},{"name":"juhah","email":"juha.haavisto@streamr.com"},{"name":"fonty1","email":"mr.matto@gmail.com"},{"name":"hpihkala","email":"henri.pihkala@streamr.com"},{"name":"tumppi","email":"tuomas.koponen@streamr.com"},{"name":"timoxley","email":"secoif@gmail.com"},{"name":"harbu","email":"harbuzen@gmail.com"},{"name":"mariusz_io","email":"mariusz@mariusz.io"},{"name":"pzsavola","email":"petri.savolainen@spaceify.net"},{"name":"mmartinmo","email":"martin.moravek@streamr.com"},{"name":"juslesan","email":"santeri.juslenius@gmail.com"},{"name":"jtakalai","email":"juuso.takalainen@streamr.com"},{"name":"jwolff","email":"jwolff@isentropy.com"},{"name":"streamr-dev","email":"devtools@streamr.com"},{"name":"teogeb","email":"teo@streamr.com"},{"name":"samt1803","email":"samt1803@gmail.com"},{"name":"simppafi","email":"simo.santavirta@gmail.com"}],"_nodeVersion":"16.13.1","dependencies":{"ajv":"^8.8.2","mem":"^8.1.1","uuid":"^8.3.2","debug":"^4.3.2","lodash":"^4.17.21","split2":"^3.2.2","sqlite":"^4.0.23","core-js":"^3.19.1","p-limit":"^3.1.0","sqlite3":"^5.0.2","tsyringe":"^4.6.0","env-paths":"^2.2.1","p-memoize":"4.0.3","quick-lru":"^6.0.1","bufferutil":"^4.0.5","idb-keyval":"^5.1.5","node-fetch":"^2.6.6","ajv-formats":"^2.1.1","ts-toolbelt":"^9.6.0","@types/debug":"^4.1.7","eventemitter3":"^4.0.7","@babel/runtime":"^7.16.3","utf-8-validate":"^5.0.7","readable-stream":"^3.6.0","streamr-network":"^32.0.0","reflect-metadata":"^0.1.13","@ethersproject/abi":"^5.5.0","@ethersproject/web":"^5.5.0","@ethersproject/bytes":"^5.5.0","@ethersproject/units":"^5.5.0","@ethersproject/wallet":"^5.5.0","node-abort-controller":"^2.0.0","@babel/runtime-corejs3":"^7.16.3","@ethersproject/address":"^5.5.0","streamr-client-protocol":"^11.0.0","@ethersproject/bignumber":"^5.5.0","@ethersproject/constants":"^5.5.0","@ethersproject/contracts":"^5.5.0","@ethersproject/keccak256":"^5.5.0","@ethersproject/providers":"^5.5.0","@ethersproject/transactions":"^5.5.0","@ethersproject/abstract-signer":"^5.5.0"},"_hasShrinkwrap":false,"readmeFilename":"README.md","devDependencies":{"cors":"^2.8.5","jest":"^27.2.5","util":"^0.12.4","bytes":"^3.1.1","buffer":"^6.0.3","eslint":"^7.32.0","ethers":"^5.4.7","express":"^4.17.1","process":"^0.11.10","ts-jest":"^27.0.5","typedoc":"^0.22.5","webpack":"^5.64.1","benchmark":"^2.1.4","ts-loader":"^9.2.6","weak-napi":"^2.0.2","nightwatch":"^1.7.12","typescript":"^4.5.2","@babel/core":"^7.16.0","@types/jest":"^27.0.2","@types/node":"^16.10.6","@types/uuid":"^8.3.1","jest-circus":"^27.2.5","webpack-cli":"^4.9.1","babel-loader":"^8.2.3","chromedriver":"^96.0.0","concurrently":"^6.4.0","pretty-bytes":"^5.6.0","@types/lodash":"^4.14.175","@types/split2":"^3.2.1","eslint-loader":"^4.0.2","webpack-merge":"^5.8.0","@types/express":"^4.17.13","@babel/preset-env":"^7.16.4","@types/node-fetch":"^2.5.12","crypto-browserify":"^3.12.0","jest-leak-detector":"^27.3.1","streamr-test-utils":"^2.0.0","@streamr/dev-config":"^1.0.0","babel-plugin-lodash":"^3.3.4","eslint-config-airbnb":"^18.2.1","eslint-plugin-import":"^2.25.3","eslint-plugin-promise":"^5.1.0","lodash-webpack-plugin":"^0.11.6","terser-webpack-plugin":"^5.2.5","webpack-bundle-analyzer":"^4.5.0","@babel/preset-typescript":"^7.16.0","@ethersproject/wordlists":"^5.5.0","@typescript-eslint/parser":"^5.0.0","git-revision-webpack-plugin":"^5.0.0","eslint-config-streamr-nodejs":"^2.0.1","node-polyfill-webpack-plugin":"^1.1.4","@babel/plugin-transform-runtime":"^7.16.4","babel-plugin-add-module-exports":"^1.0.4","@typescript-eslint/eslint-plugin":"^5.0.0","@babel/plugin-proposal-decorators":"^7.16.4","@babel/plugin-transform-modules-commonjs":"^7.16.0","babel-plugin-transform-typescript-metadata":"^0.3.2"},"optionalDependencies":{"bufferutil":"^4.0.5","utf-8-validate":"^5.0.7"},"_npmOperationalInternal":{"tmp":"tmp/streamr-client_6.0.0-alpha.25_1643221777959_0.6639538581396349","host":"s3://npm-registry-packages"},"_id":"streamr-client@6.0.0-alpha.25","version":"6.0.0-alpha.25"}