BitBadges SDK
The official TypeScript SDK for interacting with the BitBadges blockchain, API, and indexer.
Previously published as
bitbadgesjs-sdk. If you have old imports or install commands referencing that name, update them tobitbadges.
Installation
npm install bitbadges
# or
bun add bitbadgesAI agents — three ways to build
Pick the path that fits your use case. All three produce the same on-chain collection transactions.
1. Programmatic agent (BYO Anthropic key)
Scriptable from Node / TypeScript. You bring your own Anthropic API key; BitBadges never sees it.
npm install bitbadges @anthropic-ai/sdk
export ANTHROPIC_API_KEY=sk-...import { BitBadgesBuilderAgent } from 'bitbadges/builder/agent';
const agent = new BitBadgesBuilderAgent({ anthropicKey: process.env.ANTHROPIC_API_KEY });
const result = await agent.build('create a subscription token for $10/month');
console.log(result.transaction);Supports OAuth tokens (anthropicAuthToken or ANTHROPIC_OAUTH_TOKEN env), a
BitBadges API key for query/search tools (bitbadgesApiKey or BITBADGES_API_KEY
env), skills filter, system prompt additions, hooks, pluggable session store,
typed errors, cost reporting, image placeholder substitution, health checks,
and a /internals escape hatch for DIY loops.
Examples: examples/builder-agent/. Full guide:
https://docs.bitbadges.io/for-developers/ai-agents/programmatic-agent
2. MCP builder (Claude Desktop / Cursor / Claude Code)
Zero-code path for human-in-the-loop builds. Point your MCP client at the
bundled bitbadges-builder stdio server:
claude mcp add bitbadges-builder bitbadges-builderFull walkthrough, tool reference, and skill instructions: https://docs.bitbadges.io/for-developers/ai-agents/builder-tools
3. Hand-rolled transactions via SDK classes
For non-AI workflows, import the message builders directly — see the Quick Start below.
The package ships three bins:
bitbadges/bitbadges-cli— flat verb-first CLI:build,check,explain,simulate,preview,deploy,tool,tools, plusapi,auth,config,burner,session,docs,skills,resources,doctor,address,alias,lookup,gen-list-id. Runbitbadges-cli --helpfor the grouped overview.bitbadges-builder— the stdio MCP server (entry point:src/builder/index.ts)
CLI authentication (headless / agentic)
For endpoints that require a user-scoped session (anything gated by
Full Access on the indexer), bitbadges-cli auth runs the Blockin
challenge → verify dance and persists the resulting cookie under
~/.bitbadges/auth.json (mode 0600), keyed by network + address.
Subsequent api calls opt in via --with-session.
The flow is wallet-agnostic — the CLI never touches a private key.
The signature comes from any external producer: the chain binary's
bitbadgeschaind sign-arbitrary (recommended for headless agents),
MetaMask / Keplr (paste-in), a hardware wallet, a custodial signer.
# 1. Fetch a challenge (saves nonce locally for the verify step)
bitbadges-cli auth challenge --address bb1...
# 2. Sign the printed message with whatever signer you have. Headless
# Cosmos example using the chain binary:
bitbadgeschaind sign-arbitrary mykey "$(bitbadges-cli auth challenge --address bb1...)"
# 3. Post the signature — stores the session cookie
bitbadges-cli auth login \
--address bb1... \
--signature <hex|base64> \
--public-key <b64> # required for Cosmos addresses
# 4. Make authenticated requests
bitbadges-cli api accounts get-account --body '{"address":"bb1..."}' --with-sessionOther subcommands: auth status [--check], auth use <addr>,
auth whoami, auth logout [--all], auth path. 2FA accounts pass
--2fa <totp> (or --2fa-backup <code>) to auth login. Multi-account
support is built in — store as many addresses as you want, switch via
auth use. Full reference:
https://docs.bitbadges.io/for-developers/cli/auth-commands
CLI verbs for the agent loop
Three verbs cover the build → ship → confirm loop:
# 1. Build (deterministic, flag-driven)
bitbadges-cli build vault --backing-coin USDC --name "..." \
--image https://... --description "..." --json-only > vault.json
# 2. Dry-run before spending (NEW: deploy --dry-run)
# Calls simulate; never broadcasts. Exits non-zero on rejection.
bitbadges-cli deploy vault.json --burner --dry-run --manager bb1... --mainnet
# 3. Real deploy
bitbadges-cli deploy vault.json --burner --manager bb1... --mainnet --format json
# 4. Confirm it landed (NEW: tx wait)
# Hits chain LCD; falls through to EVM RPC for keccak256 hashes.
bitbadges-cli tx wait $TXHASH --mainnet --timeout 60 --format json
# 5. Plain-English audit of what was built (NEW: explain --format json)
bitbadges-cli explain vault.json --format jsonDiscovery without per-route wrappers:
bitbadges-cli api --search swap # list matching routes
bitbadges-cli api assets estimate-swap --schema # route shape, no API callPipe-friendly: pass --quiet (or BB_QUIET=1) to silence stderr
commentary across every command.
Output envelope
The tx, explain, and api --search verbs (with broader rollout
to follow) emit a uniform JSON envelope on --format json (the
default for non-TTY pipes):
{
"ok": true,
"data": { ... },
"warnings": [],
"hint": "optional next-step suggestion",
"error": null
}On error: {ok: false, data: null, error: {code, message, details?}, hint?}.
Common failure modes (auth-rejected, 401/403, tx-wait-timeout, deploy
insufficient-funds) populate hint with a one-liner that points at
the recovery action — designed to cut agent retry loops in half.
Quick Start
1. Initialize the API Client
import { BitBadgesAPI, BigIntify } from 'bitbadges';
const api = new BitBadgesAPI({
convertFunction: BigIntify,
apiKey: 'your-api-key', // Get from https://bitbadges.io/developer
apiUrl: 'https://api.bitbadges.io' // Optional, defaults to production
});2. Fetch a Collection
const response = await api.getCollections({
collectionsToFetch: [
{
collectionId: '1',
metadataToFetch: {
tokenIds: [{ start: 1n, end: 10n }]
}
}
]
});
const collection = response.collections[0]?.collection;
console.log('Name:', collection?.collectionMetadataTimeline?.[0]?.collectionMetadata?.name);3. Check a User's Balance
const balance = await api.getBalanceByAddress(
'1', // collectionId
'bb1abc...', // address
{}
);
console.log('Token IDs:', balance.balances.map(b => b.badgeIds));
console.log('Amounts:', balance.balances.map(b => b.amount));4. Get Token Activity
const activity = await api.getTokenActivity('1', '1', { bookmark: '' });
for (const item of activity.activity) {
console.log(`${item.from} -> ${item.to}: ${item.balances}`);
}Browser vs Node.js Usage
The SDK works in both browser and Node.js environments. Environment detection is handled automatically.
Node.js
// API key can be set via environment variable
process.env.BITBADGES_API_KEY = 'your-api-key';
const api = new BitBadgesAPI({
convertFunction: BigIntify
// apiKey will be read from BITBADGES_API_KEY env var
});Browser
// In browsers, you MUST pass the apiKey explicitly
const api = new BitBadgesAPI({
convertFunction: BigIntify,
apiKey: 'your-api-key' // Required in browser - no env var access
});Note: The SDK uses defensive checks (
typeof process !== 'undefined') to support both environments. No polyfills needed.
Network configuration
The SDK ships preset network configs (mainnet, testnet, local) used by BitBadgesSigningClient and the CLI's --testnet / --local flags.
Testnet is temporarily offline as of 2026-04-25 to reduce hosting costs. In the meantime, BitBadges mainnet operates as a chaosnet — fully live, but safe to experiment on. Network gas fees can be set to zero while activity is low, and you can transact with worthless tokens like CHAOS instead of real-value assets. Point your code at network: 'mainnet' to test contracts, transactions, and integrations on the live network without spending anything real — just choose your assets accordingly.
Selecting network: 'testnet', passing --testnet, or setting network = testnet in ~/.bitbadges/config.json will throw a clear error nudging you toward mainnet. All testnet URLs and chain IDs are preserved in the config so the network can be revived by flipping a single disabled flag. If you're running a private chain at the testnet chain ID for local development, set BITBADGES_TESTNET_OFFLINE=false in your environment to bypass the assertion. See docs.bitbadges.io for full details.
Core Concepts
Number Types
The SDK uses a flexible NumberType system supporting bigint, number, and string to handle large blockchain values safely.
import { BigIntify, Stringify, Numberify } from 'bitbadges';
// Always use BigIntify for large numbers (recommended)
const collectionId = BigIntify('12345678901234567890');
// Stringify for JSON serialization
const idString = Stringify(12345678901234567890n);
// Numberify only for small, safe integers
const smallNum = Numberify('100');Type System
The SDK has three type layers:
| Type | Example | Use Case |
|---|---|---|
Interface (iType) |
iBalance<bigint> |
Type annotations, function parameters |
| Class | Balance |
Most SDK operations - has utility methods |
| Proto | proto.Balance |
Blockchain serialization (strings only) |
import { Balance, UintRange } from 'bitbadges';
// Create instances with classes
const balance = new Balance({
amount: 100n,
badgeIds: [{ start: 1n, end: 10n }],
ownershipTimes: [{ start: 1n, end: 1000n }]
});
// Convert between number types
const stringBalance = balance.convert(Stringify);
// Convert to proto for blockchain
const protoBalance = balance.toProto();Common Patterns
Pagination
let bookmark = '';
let hasMore = true;
while (hasMore) {
const response = await api.getTokenActivity('1', '1', { bookmark });
// Process results
console.log(response.activity);
// Get next page
hasMore = response.pagination.hasMore;
bookmark = response.pagination.bookmark;
}Error Handling
try {
const response = await api.getCollections({ collectionsToFetch: [{ collectionId: '1' }] });
} catch (error) {
if (error.errorMessage) {
console.error('API Error:', error.errorMessage);
}
if (error.unauthorized) {
console.error('Authentication required');
}
}Address Utilities
import { convertToBitBadgesAddress, isAddressValid } from 'bitbadges';
// Validate a BitBadges address
const isValid = isAddressValid('bb1abc...');
// Convert to BitBadges format (bb-prefixed only)
const bbAddress = convertToBitBadgesAddress('bb1abc...');Module Structure
bitbadges/
├── core/ # Balance, UintRange, Approvals, Permissions
├── api-indexer/ # BitBadgesAPI client and response types
├── transactions/ # Message builders (MsgTransferTokens, etc.)
├── address-converter/ # Address utilities
├── interfaces/ # TypeScript type definitions
├── proto/ # Protocol buffer types
├── common/ # Number conversion utilities
└── gamm/ # AMM pool utilities
Key Exports
// API Client
import { BitBadgesAPI } from 'bitbadges';
// Number Conversion
import { BigIntify, Stringify, Numberify } from 'bitbadges';
// Core Classes
import { Balance, UintRange, Transfer, CollectionApproval } from 'bitbadges';
// Address Utilities
import { convertToBitBadgesAddress, isAddressValid } from 'bitbadges';
// Transaction Messages
import { MsgTransferTokens, MsgCreateCollection } from 'bitbadges';Version Compatibility
| BitBadges Chain | SDK Version | Status |
|---|---|---|
| v25 | 0.30.x | Current |
| v24 | 0.29.x | Supported |
| v23 | 0.28.x | Supported |
| v22 | 0.27.x | Supported |
| v21 | 0.26.x | Supported |
| v20 | 0.25.x | Supported |
| v19 | 0.24.x | Supported |
| v18 | 0.23.x | Supported |
| v16 | 0.21.x | Supported |
| v14-15 | 0.20.x | Supported |
| v13 | 0.19.x | Supported |
| v12 | 0.18.x | Supported |
# Install specific version for your chain
npm install bitbadges@^0.30.0Troubleshooting
"BigInt is not defined"
Ensure you're running Node.js 10.4+ or a modern browser. BigInt is required.
Precision loss with large numbers
Always use BigIntify instead of Numberify for collection IDs and token IDs.
Browser: "process is not defined"
This shouldn't occur - the SDK checks for process existence. If it does, ensure you're using the latest SDK version.
API authentication errors
- Verify your API key at https://bitbadges.io/developer
- In browsers, pass
apiKeyexplicitly (env vars don't work) - For authenticated endpoints, use
api.setAccessToken(token)
Transaction failures
- Always simulate first:
await api.simulateTx(payload) - Verify account has sufficient balance for fees
- Check sequence number is correct
Additional Resources
- Detailed Patterns & Examples: See AI_AGENT_GUIDE.md for comprehensive patterns
- API Documentation: https://docs.bitbadges.io/for-developers/bitbadges-api/api
- GitHub: https://github.com/bitbadges/bitbadgesjs
- Broadcast Helper: https://bitbadges.io/dev/broadcast
Reference Implementations
- BitBadges Frontend - Next.js web app
- BitBadges Indexer - Express.js API
License
See LICENSE for details.