Complete Guide← Back to Guides
Full Setup
A complete walkthrough to give your AI agent identity, wallet, and autonomous payment capabilities.
Prerequisites
- Node.js 18+ installed
- npm or yarn package manager
- A Lightning wallet with NWC support (we'll help you set this up)
Step 1: Install Dependencies
Terminal
npm install nostr-tools @getalby/sdk @noble/hashesStep 2: Generate Your Agent's Identity
Create a new file to generate your agent's Nostr keypair:
setup-identity.js
import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';
import { bytesToHex } from '@noble/hashes/utils';
import { nip19 } from 'nostr-tools';
// Generate new identity
const secretKey = generateSecretKey();
const publicKey = getPublicKey(secretKey);
// Convert to different formats
const secretKeyHex = bytesToHex(secretKey);
const nsec = nip19.nsecEncode(secretKey);
const npub = nip19.npubEncode(publicKey);
console.log('=== Your Agent Identity ===');
console.log('');
console.log('Public Key (npub):', npub);
console.log('Public Key (hex):', publicKey);
console.log('');
console.log('=== KEEP THESE SECRET ===');
console.log('Secret Key (nsec):', nsec);
console.log('Secret Key (hex):', secretKeyHex);
console.log('');
console.log('Add to your .env file:');
console.log(`NOSTR_SECRET_KEY=${secretKeyHex}`);
console.log(`NOSTR_PUBLIC_KEY=${publicKey}`);Run it: node setup-identity.js
SYS: OUTPUT
=== Your Agent Identity ===
Public Key (npub): npub1abc123...
Public Key (hex): abc123...
=== KEEP THESE SECRET ===
Secret Key (nsec): nsec1xyz789...
Secret Key (hex): xyz789...
Step 3: Get an NWC Connection String
The easiest way to get started is with Alby:
- 1. Go to getalby.com and create an account
- 2. Navigate to Settings → Wallet Connections
- 3. Click "Add a new connection"
- 4. Name it something like "My AI Agent"
- 5. Set permissions (recommend: make_invoice, pay_invoice, get_balance)
- 6. Set a daily budget (e.g., 10,000 sats)
- 7. Copy the NWC connection string
Add to your .env file:
.env
NOSTR_SECRET_KEY=your_secret_key_hex
NOSTR_PUBLIC_KEY=your_public_key_hex
NWC_URL=nostr+walletconnect://...Step 4: Create Your Agent
Now create your agent with full Bitcoin capabilities:
bitcoin-agent.js
import { hexToBytes } from '@noble/hashes/utils';
import { getPublicKey, finalizeEvent, nip04 } from 'nostr-tools';
import { Relay } from 'nostr-tools/relay';
import { nwc } from '@getalby/sdk';
class BitcoinAgent {
constructor() {
// Load identity
this.secretKey = hexToBytes(process.env.NOSTR_SECRET_KEY);
this.publicKey = process.env.NOSTR_PUBLIC_KEY;
// Initialize wallet
this.wallet = new nwc.NWCClient({
nostrWalletConnectUrl: process.env.NWC_URL,
});
}
// Get wallet balance
async getBalance() {
const balance = await this.wallet.getBalance();
return balance.balance;
}
// Create invoice to receive payment
async createInvoice(amountSats, description) {
const invoice = await this.wallet.makeInvoice({
amount: amountSats,
description: description,
});
return invoice.invoice;
}
// Pay a Lightning invoice
async payInvoice(bolt11) {
const result = await this.wallet.payInvoice({
invoice: bolt11,
});
return result.preimage;
}
// Send encrypted DM
async sendDM(recipientPubkey, message) {
const encrypted = await nip04.encrypt(
this.secretKey,
recipientPubkey,
message
);
const event = finalizeEvent({
kind: 4,
created_at: Math.floor(Date.now() / 1000),
tags: [['p', recipientPubkey]],
content: encrypted,
}, this.secretKey);
const relay = await Relay.connect('wss://relay.damus.io');
await relay.publish(event);
relay.close();
return event.id;
}
// Post public note
async postNote(content) {
const event = finalizeEvent({
kind: 1,
created_at: Math.floor(Date.now() / 1000),
tags: [],
content: content,
}, this.secretKey);
const relay = await Relay.connect('wss://relay.damus.io');
await relay.publish(event);
relay.close();
return event.id;
}
}
export default BitcoinAgent;Step 5: Test Your Setup
test-agent.js
import BitcoinAgent from './bitcoin-agent.js';
async function testAgent() {
const agent = new BitcoinAgent();
console.log('Testing Bitcoin Agent...');
console.log('');
// Test 1: Check balance
console.log('1. Checking balance...');
const balance = await agent.getBalance();
console.log(` Balance: ${balance} sats`);
console.log('');
// Test 2: Create invoice
console.log('2. Creating invoice for 100 sats...');
const invoice = await agent.createInvoice(100, 'Test invoice');
console.log(` Invoice: ${invoice.substring(0, 50)}...`);
console.log('');
// Test 3: Post announcement
console.log('3. Posting announcement...');
const noteId = await agent.postNote(
'Bitcoin Agent online! Ready to transact. #nostr #bitcoin'
);
console.log(` Note ID: ${noteId}`);
console.log('');
console.log('All tests passed!');
}
testAgent().catch(console.error);Run it: node test-agent.js
SYS: EXPECTED OUTPUT
$node test-agent.js
Testing Bitcoin Agent...
1. Checking balance...
Balance: 50000 sats
2. Creating invoice for 100 sats...
Invoice: lnbc1u1pjxxx...
3. Posting announcement...
Note ID: abc123...
All tests passed!
Step 6: Receive Your First Payment
Test receiving a payment:
- 1. Run the test to create an invoice
- 2. Copy the full invoice string
- 3. Open a Lightning wallet (Phoenix, Wallet of Satoshi, etc.)
- 4. Paste the invoice and pay
- 5. Run
agent.getBalance()to verify
Step 7: Send Your First Payment
Test sending a payment:
send-test.js
import BitcoinAgent from './bitcoin-agent.js';
async function sendTestPayment() {
const agent = new BitcoinAgent();
// Get an invoice from somewhere (or create one in another wallet)
const invoice = 'lnbc...'; // Paste a real invoice here
console.log('Paying invoice...');
const preimage = await agent.payInvoice(invoice);
console.log('Payment successful!');
console.log('Preimage:', preimage);
}
sendTestPayment().catch(console.error);What's Next?
- Build services - Create endpoints where users pay to access your agent's capabilities.
- Agent-to-agent - Have your agent hire other agents and pay them in sats.
- Publish profile - Add a profile (kind 0) so others can discover your agent.
- Listen for DMs - Accept service requests via encrypted Nostr messages.
Need Help?
Check out our Resources page for more tools and libraries. Browse code examples for common use cases.
Have questions? Open an issue on GitHub.