Skip to main content

Balance changes

onBalance() calls you with the new confirmed balance of an address after every block that changes it.

const btc = cg.explore(cg.networks.bitcoin)

btc.onBalance('bc1q...', async ({ address, confirmed }) => {
console.log(address, 'now holds', confirmed.base(), confirmed.symbol)
console.log('≈', await confirmed.toCurrency('eur'), 'EUR')
})

With a wallet, follow its own address:

const wallet = cg.connect(cg.networks.ethereum, myWallet)

wallet.onBalance(({ confirmed, height }) => {
console.log(`Block ${height}: ${confirmed.base()} ETH`)
})
FieldTypeUTXOEVMDescription
addressstring✓✓The address being followed, as you passed it
confirmedAmount✓✓The new confirmed balance
heightnumber—✓Block height the balance corresponds to

An event is sent for every block in which the address was active, so if it receives several payments in one block you get a single event with the resulting balance.

Pending balance​

onPendingBalance() follows the mempool instead: it calls you whenever the address's pending delta changes — a new unconfirmed transaction touches the address, or one of its pending transactions confirms or expires.

btc.onPendingBalance('bc1q...', ({ pending }) => {
if (pending.min() > 0n) console.log('Incoming:', pending.base(), 'BTC')
else if (pending.min() < 0n) console.log('Outgoing:', pending.base(), 'BTC')
else console.log('Nothing pending')
})
FieldTypeDescription
addressstringThe address being followed
pendingAmountSigned sum of the value moved by every pending transaction touching the address — negative when the address is net-spending, zero when nothing is pending

The pending delta covers the native coin only: fees are not reflected on UTXO networks, and on EVM networks gas is excluded and token transfers are not visible until the transaction is mined. The balance a wallet would display is the confirmed balance plus this delta.

Pending events may be unavailable on some networks

Pending tracking is an optional capability of each network. Subscribing where it is not available succeeds, but no pending events arrive.

Displaying a live balance​

Combine an initial read with the events:

const address = 'bc1q...'
const btc = cg.explore(cg.networks.bitcoin)

let { confirmed } = await btc.getAddressBalance(address)
render(confirmed)

btc.onBalance(address, (event) => {
confirmed = event.confirmed
render(confirmed)
})