This reference refers to the 7.x.x release of Stacks.js—it's the recommended version to use, but not needed for the Stacks Nakamoto release.
Read the migration guide to learn how to update to the latest version.
The @stacks/common package contains common utilities for working with Stacks.
This includes fetch helpers, middleware, and various other functions.
Some Stacks APIs make use API keys to provide less rate-limited plans.
import { createApiKeyMiddleware, createFetchFn, StacksMainnet } from '@stacks/network';import { broadcastTransaction, getNonce, makeSTXTokenTransfer } from '@stacks/transactions';const myApiMiddleware = createApiKeyMiddleware('example_e8e044a3_41d8b0fe_3dd3988ef302');const myFetchFn = createFetchFn(myApiMiddleware); // middlewares can be used to create a new fetch functionconst txOptions = { recipient: 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159', amount: 12345n, senderKey: 'b244296d5907de9864c0b0d51f98a13c52890be0404e83f273144cd5b9960eed01', memo: 'some memo', anchorMode: AnchorMode.Any, client: { fetch: myFetchFn, }};const transaction = await makeSTXTokenTransfer(txOptions); // fee-estimation will use the custom fetchFnconst response = await broadcastTransaction(transaction, myMainnet); // make sure to broadcast via the custom network object// stacks.js functions, which take a StacksNetwork object will use the custom fetchFnconst nonce = await getNonce('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159', myMainnet);
Middleware can be used to hook into network calls before sending a request or after receiving a response.
import { createFetchFn, RequestContext, ResponseContext } from '@stacks/common';const preMiddleware = (ctx: RequestContext) => { ctx.init.headers = new Headers(); ctx.init.headers.set('x-foo', 'bar'); // override headers and set new `x-foo` header};const postMiddleware = (ctx: ResponseContext) => { console.log(await ctx.response.json()); // log response body as json};const fetchFn = createFetchFn({ pre: preMiddleware, post: preMiddleware }); // a middleware can contain `pre`, `post`, or bothconst network = new StacksTestnet({ fetchFn });// stacks.js functions, which take a StacksNetwork object will use the custom fetchFnconst nonce = await getNonce('SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159', network);