Stellar is a powerful, open-source blockchain network designed to facilitate fast, low-cost cross-border payments and asset transfers. With its native cryptocurrency, Lumens (XLM), Stellar has become a popular choice among developers building decentralized financial applications. This comprehensive guide walks you through the core aspects of Stellar blockchain development using JavaScript, from account creation and funding to executing transactions and retrieving transaction history—all on the Stellar testnet.
Understanding the Stellar Ecosystem
Before diving into code, it's essential to understand the key components that power the Stellar network.
Horizon API
Horizon serves as the primary interface between your application and the Stellar network. It’s a RESTful HTTP API server that enables developers to submit transactions, query account balances, and subscribe to real-time events. While you can interact with Horizon via cURL or direct HTTP requests, the easiest method is using the official Stellar SDK, available for JavaScript, Java, Go, and community-supported languages like Python and C#.
Stellar Core
Stellar Core is the backbone of the network. Each Horizon server connects to a Stellar Core instance, which validates transactions and maintains consensus across the decentralized network. Every transaction incurs a minimal fee—100 stroops (0.00001 XLM)—designed to prevent spam and ensure network stability.
Stellar Consensus Protocol (SCP)
Unlike proof-of-work or proof-of-stake models, SCP achieves consensus through a unique federated voting mechanism. It prioritizes safety over liveness: during network partitions or malicious node behavior, SCP halts progress until agreement is restored. This design ensures high security and integrity across the network.
Testnet for Developers
Stellar provides a fully functional testnet environment for developers to experiment without risking real funds. The testnet mirrors the mainnet’s functionality, making it ideal for learning and debugging.
👉 Get started with blockchain development tools and resources today.
Setting Up Your Development Environment
To follow this tutorial, ensure you have basic knowledge of JavaScript, Express.js, and async/await patterns. We’ll use the Stellar JavaScript SDK, known for its stability and rich feature set.
Install the SDK using npm:
npm install stellar-sdk request-promiseInitialize a connection to the Stellar testnet:
const Stellar = require('stellar-sdk');
const rp = require('request-promise');
const server = new Stellar.Server('https://horizon-testnet.stellar.org');
Stellar.Network.useTestNetwork();Creating and Funding Stellar Accounts
The first step in any blockchain interaction is setting up accounts. In Stellar, each account is represented by a keypair: a public key (account ID) and a secret seed (private key).
Generate two random keypairs:
let pairA = Stellar.Keypair.random();
let pairB = Stellar.Keypair.random();
console.log('Account A Public Key:', pairA.publicKey());
console.log('Account A Secret Key:', pairA.secret());
console.log('Account B Public Key:', pairB.publicKey());Funding Accounts via Friendbot
On the Stellar testnet, you can receive free test XLM using Friendbot, an automated faucet service. Simply send a GET request with your public key:
await rp.get({
uri: 'https://horizon-testnet.stellar.org/friendbot',
qs: { addr: pairA.publicKey() },
json: true
});
await rp.get({
uri: 'https://horizon-testnet.stellar.org/friendbot',
qs: { addr: pairB.publicKey() },
json: true
});Once funded, load the account object to access balance data:
let accountA = await server.loadAccount(pairA.publicKey());
let accountB = await server.loadAccount(pairB.publicKey());
accountA.balances.forEach((balance) => {
console.log(`Asset: ${balance.asset_type}, Balance: ${balance.balance}`);
});You should see a balance of 10,000 XLM for each account.
Executing Transactions on Stellar
A transaction in Stellar can include multiple operations. For simplicity, we’ll focus on payment operations—transferring XLM between accounts.
Construct and sign a transaction from Account A to Account B:
const transaction = new Stellar.TransactionBuilder(accountA)
.addOperation(Stellar.Operation.payment({
destination: pairB.publicKey(),
asset: Stellar.Asset.native(), // Native XLM asset
amount: '30.0000001' // Amount in XLM (7 decimal places required)
}))
.build();
// Sign the transaction with the source account's secret key
transaction.sign(pairA);
// Submit to the network
const result = await server.submitTransaction(transaction);
console.log('Transaction successful:', result.hash);Note: Stellar requires amounts to be specified with exactly seven decimal places due to its internal stroop-based accounting system (1 XLM = 10,000,000 stroops).
👉 Explore secure wallet solutions and blockchain APIs for your next project.
Retrieving Transaction History
After submitting a transaction, you can retrieve historical data using Horizon’s pagination system.
Fetch recent transactions for an account:
let historyPage = await server.transactions()
.forAccount(pairA.publicKey())
.limit(1)
.order('desc')
.call();
console.log('Latest Transaction Hash:', historyPage.records[0].hash);To inspect transaction details encoded in XDR (External Data Representation), decode and parse the operations:
const xdrEnvelope = Stellar.xdr.TransactionEnvelope.fromXDR(
historyPage.records[0].envelope_xdr,
'base64'
);
const operations = xdrEnvelope.toXDR().tx().operations();
operations.forEach(op => {
if (op.body().switch().name === 'payment') {
const amount = op.body().paymentOp().amount().toString();
console.log(`Transferred ${amount} stroops (${amount / 10000000} XLM)`);
}
});Navigate through pages of transaction history:
historyPage = await historyPage.next();Advanced Tips & Tools for Stellar Development
- Explore live transactions on the testnet using the Horizon Explorer.
- Decode XDR data using the Stellar Laboratory XDR Viewer, which helps debug complex transaction structures.
- Monitor account activity by querying all operations for a given public key:
https://horizon-testnet.stellar.org/accounts/{publicKey}/operations
Frequently Asked Questions (FAQ)
Q: What is the difference between XLM and stroops?
A: XLM is the human-readable unit of Stellar’s native currency. One XLM equals 10,000,000 stroops—the base unit used internally by the network for precision in calculations and fees.
Q: Can I use the same code on the Stellar mainnet?
A: Yes! Just switch from useTestNetwork() to usePublicNetwork() and connect to https://horizon.stellar.org. Ensure you manage private keys securely and fund accounts with real XLM.
Q: How much does a transaction cost on Stellar?
A: Each operation costs 100 stroops (0.00001 XLM). A simple payment transaction costs this base fee, making Stellar one of the most cost-efficient blockchains.
Q: Is it safe to generate keys client-side in JavaScript?
A: For production applications, avoid generating or storing secret keys in browser environments. Use secure backend services or hardware wallets instead.
Q: How fast are Stellar transactions confirmed?
A: Transactions typically confirm within 3–5 seconds thanks to the SCP consensus mechanism, enabling near-instant settlements.
Q: Can I issue custom assets on Stellar?
A: Absolutely. Stellar supports issuing tokenized assets like USD-backed stablecoins or loyalty points. Use Stellar.Asset with an issuer public key to create them.
👉 Discover how to integrate digital assets and blockchain services seamlessly into your apps.