Private Keys & Wallets

Learn how to manage secrets with Stacks.js.


WITHOUT direct private key access

Most users interact with apps via their favorite Stacks wallet. Developers can build web apps that prompt the user for an action (e.g. sign a transaction), and then the wallet will handle the rest.

Build Web Apps

You can build Stacks enabled web apps without direct private key access using Stacks Connect.

WITH private key access

Developers can build scripts, backends, and tools intended for full control over private keys.

  • Using the Stacks.js CLI directly to send transactions, or perform common tasks
  • Building custom tools using Stacks.js libraries that manage private keys directly

Generating random private keys

Let's start by generating a random private key. Note that this will return a different value each time you run the code.

import { randomPrivateKey } from '@stacks/transactions';
const privateKey = randomPrivateKey();
// 'f5a31c1268a1e37d4edaa05c7d11183c5fbfdcdc48aae36ea4d8cd5cb709932801'

Private keys are typically represented as hex strings in Stacks.js. For more control you can use the PrivateKey type, which also accepts raw bytes as Uint8Array in JavaScript.

Using a wallet / seed phrase

Typically, we don't want to generate random private keys, but instead use a deterministic wallet based on a seed phrase.

Generate a random seed phrase (24 words):

import { randomSeedPhrase } from '@stacks/wallet-sdk';
const phrase = randomSeedPhrase();
// "warrior volume sport ... figure cake since"

Generate a wallet from a seed phrase:

import { generateWallet } from '@stacks/wallet-sdk';
let wallet = generateWallet({
secretKey: seed,
password: "secret",
});
console.log(wallet.accounts[0]); // one account is generated by default
// {
// stxPrivateKey: '893fc4936c5350394bbe0053d2c31a4b5a44680f6dceb4be2aacaaa3c12e45ff01',
// dataPrivateKey: '676dc36d89ba04cf1789552fc35f3a6279b4b5f13f3d49fb469b0afecea9698f',
// appsKey: 'xprvA19evFHUzrZF3wULUSv1UVcQNRP7xJ2vn2MyAKaUHbT8SvjrrkkhANRG2bewMxHAeDSoUVUBRPiztDc8WwGtz9Ero2GXW5rk3vHHXmutb4V',
// salt: 'cf8a5c7142d842bb38f30c5ab626f7996dd7494236edf21ba00349bb09b9558d',
// index: 0
// }

Generate more accounts:

import { generateNewAccount } from '@stacks/wallet-sdk';
wallet = generateNewAccount(wallet);
console.log(wallet.accounts.length); // 2

What else can we do with private keys?

Sign Transactions

Learn how to sign transactions with Stacks.js.