Mempool SDK
Access Blocknative notification messages in Javascript with our simple web socket library
Open source GitHub repo: https://github.com/blocknative/sdk
The SDK uses our API, which has rate limits. Please see Rate Limits for more details.
As Blocknative community members create SDKs in additional languages, we list them here. We greatly appreciate community member contributions. Golang: https://github.com/bonedaddy/go-blocknative
These SDKs are not supported directly by Blocknative.

Quickstart

It should take less than 5 minutes to get going with the SDK.

Create a Blocknative Account

Go to the Account page at https://explorer.blocknative.com/account and setup an account with an email address. You will receive an email to confirm your account.
You can read the Getting Started guide on the API Docs to get more information on how to set up an API Key for your purpose. API keys segment analytics data. Consider using different API keys for development, staging, and production releases.

Install the library using npm

1
npm install bnc-sdk
Copied!

Initialize the Library

1
// For Node < v13 / CommonJS environments
2
const BlocknativeSdk = require('bnc-sdk');
3
const WebSocket = require('ws');
4
const Web3 = require('web3');
5
6
// OR
7
8
// For Node >= v13 / es module environments
9
import BlocknativeSdk from 'bnc-sdk'
10
import Web3 from 'web3'
11
import WebSocket from 'ws' // only neccessary in server environments
12
13
// create options object
14
const options = {
15
dappId: 'Your dappId here',
16
networkId: 1,
17
system: 'bitcoin', // optional, defaults to ethereum
18
transactionHandlers: [event => console.log(event.transaction)],
19
ws: WebSocket, // only neccessary in server environments
20
name: 'Instance name here', // optional, use when running multiple instances
21
onerror: (error) => {console.log(error)} //optional, use to catch errors
22
}
23
24
// initialize and connect to the api
25
const blocknative = new BlocknativeSdk(options)
Copied!

Track transactions

Send a transaction using web3.js and get the transaction hash while its processing. Let the SDK know the hash and it will track its progress through the mempool and into a block.
1
// initialize web3
2
const web3 = new Web3(window.ethereum)
3
4
// get current account
5
const accounts = await web3.eth.getAccounts();
6
const address = accounts[0];
7
8
// create transaction options object
9
const txOptions = {
10
from: address,
11
to: "0x792ec62e6840bFcCEa00c669521F678CE1236705",
12
value: "1000000"
13
}
14
15
// initiate a transaction via web3.js
16
web3.eth.sendTransaction(txOptions).on('transactionHash', hash => {
17
// call with the transaction hash of the
18
// transaction that you would like to receive status updates for
19
const { emitter } = blocknative.transaction(hash)
20
21
// listen to some events
22
emitter.on('txPool', transaction => {
23
console.log(`Sending ${transaction.value} wei to ${transaction.to}`)
24
})
25
26
emitter.on('txConfirmed', transaction => {
27
console.log('Transaction is confirmed!')
28
})
29
30
// catch every other event that occurs and log it
31
emitter.on('all', transaction => {
32
console.log(`Transaction event: ${transaction.eventCode}`)
33
})
Copied!

And you are live!

Screencasts

See how to get started with the SDK in this screencast:
SDK Quickstart Screencast

Initialization Options

The following options object needs to be passed when initializing and connecting
1
const options = {
2
dappId: String,
3
system: String,
4
networkId: Number,
5
transactionHandlers: Array,
6
ws: WebSocket,
7
name: String,
8
onopen: Function,
9
onerror: Function,
10
ondown: Function,
11
onreopen: Function,
12
onclose: Function
13
}
Copied!

dappId - [REQUIRED]

Your unique API key that identifies your application. You can generate a dappId by visiting the Blocknative account page and creating a free account.

system - [OPTIONAL]

The system that you would like to monitor transactions on. Currently bitcoin and ethereum are supported. Defaults to ethereum if no value is passed in.

networkId - [REQUIRED]

Valid Ethereum and EVM compatible network ids (use ethereum for system):
    1 Main Network
    3 Ropsten Test Network
    4 Rinkeby Test Network
    5 Goerli Test Network
    42 Kovan Test Network
    56 Binance Smart Chan Main Network
    100 xDai POA Network
    137 Polygon Matic Mainnet Network
Valid Bitcoin network ids (use bitcoin for system):
    1 Main Network
    2 Testnet Network

transactionHandlers - [OPTIONAL]

An array of functions that will each be called once for every status update for every transaction that is associated with this connection on a watched address or a watched transaction.
1
const handleTransactionEvent = event => {
2
const {
3
transaction, // transaction object
4
emitterResult // data that is returned from the transaction event listener defined on the emitter
5
} = event
6
7
console.log(transaction)
8
}
9
10
const options = {
11
// other options
12
transactionHandlers: [handleTransactionEvent]
13
}
Copied!
See the Transaction Object section for more info on what is included in the transaction parameter.

ws - [OPTIONAL]

If you are running the sdk in a server environment, there won't be a native WebSocket instance available for the sdk to use, so you will need to pass one in. You can use any WebSocket library that you prefer as long as it correctly implements the WebSocket specifications. We recommend ws.

name - [OPTIONAL]

If you are running multiple instances of the sdk on the same client, passing in a name property allows the sdk to properly manage persistent state.

onopen - [OPTIONAL]

A function that is called once the WebSocket has successfully connected to the Blocknative backend infrastructure.

onerror - [OPTIONAL]

A function that is called for every error that happens within the SDK including WebSocket connection errors. The function is called with an error object with the following parameters:
message : String - The error message, describing what went wrong
error : ErrorObject - An error object if ine exist (for instance a WebSocket error)
transaction : String - The hash or txid passed to the call to transaction that caused the error
account : String - The address passed to the call to account that caused the error
If this function is not passed in then error will be thrown.

ondown - [OPTIONAL]

A function that is called when the WebSocket connection has dropped. The SDK will automatically reconnect.

onreopen - [OPTIONAL]

A function that is called once the WebSocket has successfully re-connected after dropping.

onclose - [OPTIONAL]

A function that is called when the WebSocket has successfully been destroyed.

Initialize and Connect

Import and initialize the SDK with the configuration options described above for client and server environments.

Client/Browser Environment

1
import BlocknativeSdk from 'bnc-sdk'
2
3
// create options object
4
const options = {
5
dappId: 'Your dappId here',
6
networkId: 1,
7
transactionHandlers: [event => console.log(event.transaction)],
8
onerror: (error) => {console.log(error)}
9
}
10
11
// initialize and connect to the api
12
const blocknative = new BlocknativeSdk(options)
Copied!

Server/Node.js Environment

1
// For Node < v13 / CommonJS environments
2
const BlocknativeSdk = require('bnc-sdk');
3
const WebSocket = require('ws');
4
5
// OR
6
7
// For Node >= v13 / es module environments
8
import BlocknativeSdk from 'bnc-sdk'
9
import WebSocket from 'ws' // only neccessary in server environments
10
11
// create options object
12
const options = {
13
dappId: 'Your dappId here',
14
networkId: 1,
15
transactionHandlers: [event => console.log(event.transaction)],
16
ws: WebSocket,
17
onerror: (error) => {console.log(error)}
18
}
19
20
// initialize and connect to the api
21
const blocknative = new BlocknativeSdk(options)
Copied!

Events

Watch a Transaction

Now that your application is successfully connected via a WebSocket connection to the Blocknative back-end, you can register transactions to watch for updates (notifications).

Ethereum

Once you have initiated a transaction and have received the transaction hash, you can pass it in to the transaction function:
1
// initiate a transaction via web3.js
2
web3.eth.sendTransaction(txOptions).on('transactionHash', hash => {
3
// call with the transaction hash of the transaction that you would like to receive status updates for
4
const {
5
emitter, // emitter object to listen for status updates
6
details // initial transaction details which are useful for internal tracking: hash, timestamp, eventCode
7
} = blocknative.transaction(hash)
8
})
9
10
Copied!
The emitter is used to listen for status updates. See the Emitter Section for details on how to use the emitter object to handle specific transaction state changes.
The details object contains the initial transaction details which are useful for internal tracking.
If the library was initialized with transaction handlers, those handlers will also be called on each status change for the watched transaction.
If a transaction is watched that is currently in the txpool or was updated in the last 60 minutes, the SDK will immediately send a notification with the last detected status for that transaction.
If a watched transaction is replaced (status speedup or cancel), the SDK will automatically watch the hash of the replacement transaction for the client and start delivering notifications for it.

Bitcoin

1
const { emitter, details } = blocknative.transaction(txid)
Copied!

Watch an Account Address

You can also register an account address to listen to any incoming and outgoing transactions that occur on that address using the account method:

Ethereum

1
// get the current accounts list of the user via web3.js
2
const accounts = await web3.eth.getAccounts()
3
4
// grab the primary account
5
const address = accounts[0]
6
7
// call with the address of the account that you would like to receive status updates for
8
const {
9
emitter, // emitter object to listen for status updates
10
details // initial account details which are useful for internal tracking: address
11
} = blocknative.account(address)
Copied!
This will tell the Blocknative back-end to watch for any transactions that occur involving this address and any updates to the transaction status over time. The return object from successful calls to account will include an event emitter that you can use to listen for those events and a details object which includes the address that is being watched.

Bitcoin

1
const { emitter, details } = blocknative.account(address)
Copied!

Un-watch an Account Address or Transaction Hash

If you no longer want to receive notifications for an account address or transaction hash, you can use the unsubscribe method:
1
// unsubscribe from address
2
blocknative.unsubscribe(address)
3
4
// unsubscribe from Ethereum transaction hash
5
blocknative.unsubscribe(hash)
6
7
// unsubscribe from Bitcoin txid
8
blocknative.unsubscribe(txid)
Copied!

Log an Event

You may want to log an event that isn't associated with a transaction for analytics purposes. Events are collated and displayed in the developer portal and are segmented by your dappId. To log an event, simple call event with a categoryCode and an eventCode, both of which can be any String that you like:
1
blocknative.event({
2
categoryCode: String, // [REQUIRED] - The general category of the event
3
eventCode: String // [REQUIRED] - The specific event
4
})
Copied!

Emitter

The emitter object is returned from calls to account and transaction and is used to listen to status updates via callbacks registered for specific event codes.
1
// register a callback for a txPool event
2
emitter.on("txPool", transaction => {
3
console.log("Transaction is pending")
4
})
Copied!
The first parameter is the eventCode string of the event that you would like to register a callback for. For a list of the valid event codes, see the event codes section.
The second parameter is the callback that you would like to register to handle that event and will be called with a transaction object that includes all of the relevant details for that transaction. See the Transaction Object section for more info on what is included.
Any data that is returned from the listener callback for transaction emitters will be included in the object that the global transactionHandlers are called with under the emitterResult property.
To prevent memory leaks on long running processes, you can use the off method on the emitter to remove your callback listener:
1
// remove callback for txPool event
2
emitter.off('txPool')
Copied!

Transaction Object

The callback that is registered for events on an emitter or included in the transactionHandlers array will be called with the following transaction object:

Ethereum

1
{
2
status: String, // current status of the transaction
3
hash: String,
4
to: String,
5
from: String,
6
gas: Number,
7
gasPrice: String,
8
gasPriceGwei: Number,
9
gasUsed: String, // present on on-chain txns
10
nonce: Number,
11
value: String,
12
eventCode: String,
13
blockHash: String,
14
blockNumber: Number,
15
input: String,
16
timeStamp: string // the UTC time of first detection of current status
17
pendingTimeStamp: string // the UTC time of initial pending status detection
18
pendingBlockNumber: Number // the chain head block number at time of pending detection
19
transactionIndex: Number, // optional, present if status confirmed, failed
20
blockTimeStamp: String, // optional, present if status confirmed, failed - UTC time of miner block creation
21
counterParty: String, // address of the counterparty of the transaction when watching an account
22
direction: String, // the direction of the transaction in relation to the account that is being watched ("incoming" or "outgoing")
23
watchedAddress: String, // the address of the account being watched
24
timePending: String, // optional, present if status confirmed, failed, speedup, cancel. "-1" if first detection is on-chain.
25
blocksPending: Number, // optional, present if status confirmed, failed, speedup, cancel
26
originalHash: String, // if a speedup or cancel status, this will be the hash of the original transaction
27
asset: String, // the asset that was transfered
28
v: String,
29
r: String,
30
s: String,
31
contractCall: { // if transaction was a contract call otherwise undefined
32
contractAddress: String,
33
contractType: String,
34
methodName: String,
35
params: {
36
// params that the contract method was called with
37
},
38
contractName: String,
39
contractDecimals: Number (optional),
40
decimalValue: String (optional),
41
}
42
}
Copied!

Bitcoin

1
{
2
"rawTransaction": {
3
"txid": String,
4
"hash": String,
5
"version": Number,
6
"size": Number,
7
"vsize": Number,
8
"weight": Number,
9
"locktime": Number,
10
"vin": Vin[],
11
"vout": Vout[],
12
"hex": String,
13
},
14
"txid": String,
15
"system": String,
16
"network": String,
17
"status": Status,
18
"apiKey": String,
19
"monitorVersion": String,
20
"monitorId": String,
21
"serverVersion": String,
22
"timeStamp": String,
23
"timePending": String,
24
"watchedAddress": String,
25
"inputs": Transfer[],
26
"outputs": Transfer[],
27
"fee": String,
28
"netBalanceChanges": BalanceChange[],
29
"blockHeight": String,
30
"blockHash": String,
31
}
32
33
// Vin
34
{
35
"txid": String,
36
"vout": Number,
37
"scriptSig": {
38
"asm": String,
39
"hex": String
40
},
41
"txinwitness": String[],
42
"sequence": Number
43
}
44
45
// Vout
46
{
47
"value": Number,
48
"n": Number,
49
"scriptPubKey": {
50
"asm": String,
51
"hex": String,
52
"reqSigs": Number,
53
"type": String,
54
"addresses": String[]
55
}
56
}
57
58
// Transfer
59
{
60
"address": String,
61
"value": String
62
}
63
64
// BalanceChange
65
{
66
"address": String,
67
"delta": String
68
}
Copied!

Internal Transactions (Ethereum)

The SDK will send confirmednotifications when a watchedAddress is detected in the internal transactions of a contract call. In this case, the confirmed transaction object will include details of the internal transactions and balance changes resulting from those internal transactions. Fields are not ordered.
1
"internalTransactions": [],
2
"netBalanceChanges": Object
Copied!
Field
Description
internalTransactions
Array of objects containing details of each internal transaction (see below)
netBalanceChanges
Object containing details of balance changes for all addresses involved in internal transactions (see below)
The internalTransactions array contains details on each internal transaction executed by the contract call of the parent (main) transaction. Fields are not ordered.
1
"internalTransactions": [
2
{
3
"type": String,
4
"from": String,
5
"to": String,
6
"input": String,
7
"gas": Number,
8
"gasUsed": Number,
9
"value": String,
10
"contractCall": Object (optional, contains an additional param 'contractAlias' which will be the symbol of the token if this is an erc20 transfer or transferFrom)
11
},
12
...
13
]
Copied!
Field
Description
type
Type of internal transaction (one of CALL, DELEGATECALL, STATICCALL, CALLCODE)
from
Address initiating the internal transaction call (typically the parent (main) transaction's contract address
to
Address the internal transaction is calling or sending value to
input
Data sent to internal transaction. For value transfers from external account initiating parent (main) transaction to another external account, this field contains 0x. For contract calls, this value contains the contract method signature and params as a hex string.
gas
Maximum amount of gas available to the internal transaction
gasUsed
Amount of gas actually used executing the internal transaction
value
Amount of ETH transferred directly to to address from parent (main) transaction from address.
contractCall
Optional. A series of keys and values specific to the contract method . This object is present only if the contract method call includes parameters and Blocknative decodes the internal transaction contract call (e.g. an ERC20 transfer). For details see decoded contract payload above. NOTE: If the Internal transaction is an ERC20 transfer or transferFrom call, the contractCall object will include an additional field, contractAlias with the symbol of the token transferred.
The netBalanceChanges object contains details of all the balance changes resulting from the internal transactions details in the internalTransactions array.
1
"netBalanceChanges": {
2
"<address>": [
3
{
4
"delta": String,
5
"asset": {
6
"type": String,
7
"symbol": String
8
},
9
"breakdown": [
10
{
11
"counterparty": Atring,
12
"amount": String
13
}
14
]
15
}
16
],
17
...
18
}
Copied!
Field
Description
<address>
Address involved in internal transaction. Each address contains an array of balances changes, one for each counterparty
asset
Details of the asset being transferred. Contains type and symbol.
delta
Amount of value transfer (balance change) in wei to the <address>. Outgoing value is represented as a negative balance change and incoming value is represented as a positive balance change
type
The type of asset transferred (e.g. "ether")
symbol
The symbol of the asset transferred. "ETH" or appropriate ERC20 symbol
breakdown
Array of individual transfers to <address> for the current asset
counterparty
Address of the other side of the transfer relative to the <address>
amount
The amount of asset transferred with this counterparty

Event Codes

The following is a list of event codes that are valid, and the events that they represent:
    all: Will be called for all events that are associated with that emitter. If a more specific listener exists for that event, then that will be called instead. This is useful to catch any remaining events that you haven't specified a handler for
    txSent: Transaction has been sent to the network
    txPool: Transaction was detected in the "pending" area of the mempool and is eligible for inclusion in a block
    txPoolSimulation: Transaction was detected in the "pending" area of the mempool and is eligible for inclusion in a block and has been simulated against the latest block
    txStuck: Transaction was detected in the "queued" area of the mempool and is not eligible for inclusion in a block
    txConfirmed: Transaction has been mined
    txFailed: Transaction has failed
    txSpeedUp: A new transaction has been submitted with the same nonce and a higher gas price, replacing the original transaction
    txCancel: A new transaction has been submitted with the same nonce, a higher gas price, a value of zero and sent to an external address (not a contract)
    txDropped: Transaction was dropped from the mempool without being added to a block

Filtering and Decoding Ethereum Transactions

You may want to filter events that occur on an Ethereum address and/or have the Blocknative server automatically decode the input data for a particular contract. To do this the configuration function can be used to send a configuration that will be scoped globally or to a particular address:
1
await blocknative.configuration({
2
scope: String, // [required] - either 'global' or valid Ethereum address
3
filters: Array, // [optional] - array of valid searchjs filter strings
4
abi: Array, // [optional] - valid contract ABI
5
watchAddress: Boolean // [optional] - Whether the server should automatically watch the "scope" value if it is an address
6
})
7
8
// returns a promise that resolves once the configuration has been applied
9
// or rejects if there was a problem with the configuration
Copied!

Options

scope - [required]
The scope that the configuration will be applied to. Can be a 'global' configuration so that you can filter all events for all addresses that you are watching or a valid Ethereum address to scope the configuration to events that occur only on that address.
filters - [optional]
The filters that you would like applied to events in scope. The Blocknative server uses jsql a JavaScript query language to filter events. Documentation for how to create filter queries can be found here
abi - [optional]
A JavaScript ABI (application binary interface) so that the Blocknative server can automatically decode transaction input data
watchAddress - [optional]
If the scope is an Ethereum address, then watchAddress can be set to true so that the Blocknative server can automatically watch the address in scope, rather than needing to send an extra call to blocknative.account
scope establishes the context in which a filter is applied. The global scope applies the filter to all transactions/addresses watched. Therefore a global scope only supports generic transaction elements. A scope set to an address can include filters, such as methodName,that are specific to the contract at that address. Similarly, the abi field only works for a contract specific scope.

Mempool Explorer Configurations

Export & Import

You can download a Mempool Explorer configuration to be used with the SDK. You can also use your account page to download a configuration that was saved to a specific API key. Once you have the files (configuration.json, sdk-setup.js) downloaded, drop them in to your project directory. They can then be imported and setup with the SDK:
1
import BlocknativeSDK from 'bnc-sdk'
2
import configuration from './configuration'
3
import sdkSetup from './sdk-setup'
4
5
// function to handle all transaction events
6
function handleTransactionEvent(transaction) {
7
console.log('Transaction event:', transaction)
8
}
9
10
// initialize the SDK
11
const blocknative = BlocknativeSDK({
12
// ...other initialization options
13
transactionHandlers: [handleTransactionEvent]
14
})
15
16
// setup the configuration with the SDK
17
sdkSetup(blocknative, configuration)
Copied!

Get Started Today

Sign up for a free Blocknative Account at https://account.blocknative.com/ with your work email address.
If you have any questions, connect with the team on our discord
Last modified 1mo ago