The Streamr SDK allows you to interact with the Streamr Network from JavaScript-based environments, such as browsers and Node.js. This library contains convenience functions for creating and managing streams on the Streamr Network.
Checkout our documentation for the full usage instructions.
The SDK is available on NPM and can be installed simply by:
npm install @streamr/sdk
If using TypeScript you can import the library with:
import { StreamrClient } from '@streamr/sdk'
If using Node.js you can import the library with:
const { StreamrClient } = require('@streamr/sdk')
The Streamr SDK is built for the browser and NodeJS environments.
NodeJS
- NodeJS
18.13.x
, NPM8.x
and later versions are recommended.
Browser (Website/WebApps)
- For usage in the browser include the latest build, e.g. by including a
<script>
tag pointing at a CDN: <script src="https://unpkg.com/@streamr/sdk@latest/streamr-sdk.web.min.js"></script>
- To use within React, please see streamr-client-react
Browser extension
- Due to the stricter security rules inside browser extensions you must use the web build version of the Streamr SDK.
For a full API reference visit https://docs.streamr.network/usage/sdk/api/.
In 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. A private key is not required if you are subscribing to public streams on the Network.
const streamr = new StreamrClient({
auth: {
privateKey: 'your-private-key'
}
})
Authenticating with an Ethereum private key contained in an Ethereum (web3) provider (e.g. MetaMask):
const streamr = new StreamrClient({
auth: {
ethereum: window.ethereum,
}
})
You can also create an anonymous client instance that can interact with public streams:
const streamr = new StreamrClient()
// Requires MATIC tokens (Polygon blockchain gas token)
const stream = await streamr.createStream({
id: '/foo/bar'
})
console.log(stream.id) // e.g. `0x12345.../foo/bar`
const streamId = 'streams.dimo.eth/firehose/weather'
streamr.subscribe(streamId, (message) => {
// handle for individual messages
})
Publishing messages requires your Ethereum account to have permission to publish. See the stream permission docs for more information.
// Requires MATIC tokens (Polygon blockchain gas token)
const stream = await streamr.createStream({
id: '/foo/bar'
})
await stream.publish({ timestamp: Date.now() })
By default subscribe
will not request historical messages.
You can fetch historical messages with the resend
method:
streamr.resend(streamId, { last: 10 }, (msgs) => {
console.log("messages": msgs);
});
This Readme only scratches the surface of what's possible - be sure to checkout our documentation for the full usage instructions.