unisat-api
v2.1.2
Published
Unisat API Client
Maintainers
Readme
UniSat API Client v2.1.2 🚀
🌟 UniSat API Client is a comprehensive open-source TypeScript/JavaScript client library for the UniSat API. It provides a simple and elegant interface to interact with various UniSat services, including blockchain queries, transactions, inscriptions, BRC-20 tokens, Runes, Alkanes, Collections, and more.
🎉 v2.1 Released! Updated with Biome V2 migration, enhanced type safety, and improved developer experience!
✨ Key Features
- 💼 Complete Coverage: Full support for all UniSat API features, including the latest Alkanes and Collections
- 📦 TypeScript Support: Complete type definitions with excellent developer experience
- 🌐 Multi-Network Support: Support for mainnet, testnet, fractal-mainnet, and fractal-testnet
- ⚙️ Enhanced Features: Batch requests, health checks, network switching, request cancellation, and more
- 🔧 Highly Configurable: Support for custom timeout, base URL, headers, and more
- 📊 Performance Monitoring: Built-in request timing statistics and error handling
- 🛡️ Error Handling: Unified error format and detailed error information
- 🎨 Modern Tooling: Built with Biome V2 for superior code quality and formatting
📦 Installation
Install via npm:
npm install unisat-apiOr using yarn:
yarn add unisat-apiOr using pnpm:
pnpm add unisat-api🚀 Quick Start
import UnisatApiClient from 'unisat-api';
const client = new UnisatApiClient({
apikey: 'YOUR_API_KEY',
network: 'mainnet', // 'mainnet' | 'testnet' | 'fractal-mainnet' | 'fractal-testnet'
timeout: 30000 // Optional, timeout in milliseconds
});
// 🔍 Get blockchain information
const blockchainInfo = await client.blocks.getBlockchainInfo();
console.log('Blockchain info:', blockchainInfo.data);
// 💰 Get address balance
const balance = await client.address.getAddressBalance('bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh');
console.log('Address balance:', balance.data);
// 📊 Get fee recommendations
const fees = await client.blocks.getFeeRecommendations();
console.log('Fee recommendations:', fees.data);
// 🪙 Runes protocol
const runesStatus = await client.runes.getRunesStatus();
console.log('Runes status:', runesStatus.data);
// 🎨 Alkanes protocol (v2.0+)
const alkanesStatus = await client.alkanes.getAlkanesStatus();
console.log('Alkanes status:', alkanesStatus.data);
// 🖼️ Collections (v2.0+)
const collectionsStats = await client.collections.getCollectionsStats();
console.log('Collections stats:', collectionsStats.data);🛠️ API Modules Overview
Core Modules
- 🧱
blocks- Blockchain information queries - 🏦
address- Address-related operations - 💸
transaction- Transaction-related operations - 📜
inscriptions- Inscription query operations
Protocol Support
- 🪙
runes- Runes protocol operations - 📊
brc20- BRC-20 token operations - 🎨
alkanes- Alkanes protocol support (v2.0+) - 🖼️
collections- Collections support (v2.0+)
Market Features
- 📈
market- Market data queries - 🔄
brc20swap- BRC-20 token swapping - 🖋️
inscribe- Inscription minting operations
🔥 v2.0+ New Features
1. Alkanes Protocol Support
// Get Alkanes status
const status = await client.alkanes.getAlkanesStatus();
// Get Alkanes list
const list = await client.alkanes.getAlkanesList({ start: 0, limit: 10 });
// Search Alkanes
const search = await client.alkanes.searchAlkanes('test');
// Get address Alkanes balance
const balance = await client.alkanes.getAddressAlkanesBalanceList(address);2. Collections Features
// Get Collections statistics
const stats = await client.collections.getCollectionsStats();
// Get Collections list
const collections = await client.collections.getCollections();
// Search Collections
const searchResults = await client.collections.searchCollections('art');
// Get trending Collections
const trending = await client.collections.getTrendingCollections();3. Fractal Network Support
// Connect to Fractal mainnet
const fractalClient = new UnisatApiClient({
apikey: 'YOUR_API_KEY',
network: 'fractal-mainnet'
});
// Or connect to Fractal testnet
const fractalTestnetClient = new UnisatApiClient({
apikey: 'YOUR_API_KEY',
network: 'fractal-testnet'
});4. Batch Requests
// Execute multiple requests in parallel
const results = await client.batchRequest([
() => client.blocks.getBlockchainInfo(),
() => client.address.getAddressBalance(address),
() => client.runes.getRunesStatus()
]);
results.forEach((result, index) => {
if (result.code === 0) {
console.log(`Request ${index} success:`, result.data);
} else {
console.error(`Request ${index} failed:`, result.message);
}
});5. Enhanced Client Features
// Health check
const health = await client.healthCheck();
console.log('API status:', health.data.status);
// Dynamic network switching
client.switchNetwork('testnet');
// Get client configuration
const config = client.getConfig();
console.log('Client config:', config);
// Set new API key
client.setApiKey('NEW_API_KEY');📖 Detailed Usage
Address Operations
// Get complete address information
const fullInfo = await client.address.getFullAddressInfo(address);
// Get available balance
const availableBalance = await client.address.getAvailableBalance(address);
// Batch get address balances
const batchBalances = await client.address.getBatchAddressBalances([address1, address2]);
// Filter UTXOs by specific amount range
const filteredUtxos = await client.address.filterUtxosByAmount(address, 1000, 10000);Transaction Operations
// Get complete transaction information
const fullTx = await client.transaction.getFullTransactionInfo(txid);
// Get raw transaction data
const rawTx = await client.transaction.getRawTransaction(txid);
// Batch push transactions
const pushResults = await client.transaction.pushMultipleTxs({
txHexs: ['raw_tx_hex_1', 'raw_tx_hex_2'],
maxFeeRate: 20
});
// Estimate transaction fee
const fee = await client.transaction.estimateFee(2, 3, 10);
// Monitor transaction confirmation
const confirmedTx = await client.transaction.monitorTransactionConfirmation(
txid,
6, // 6 confirmations
30000 // Check every 30 seconds
);Inscription Operations
// Get complete inscription information
const fullInscription = await client.inscriptions.getFullInscriptionInfo(inscriptionId);
// Get inscription content
const content = await client.inscriptions.getInscriptionContent(inscriptionId);
// Get complete address inscriptions
const addressInscriptions = await client.inscriptions.getFullAddressInscriptions(address);
// Estimate inscription fee
const inscriptionFee = await client.inscriptions.estimateInscriptionFee(
'text/plain',
100,
10
);Market Data
// BRC-20 market data
const brc20MarketData = await client.market.brc20.getMarketList({ tick: 'ordi' });
// Runes market data
const runesMarketData = await client.market.runes.getMarketList({ rune: 'UNCOMMONGOODS' });
// Collections market data
const collectionsMarketData = await client.market.collection.getMarketList();⚙️ Configuration Options
| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| apikey | string | ✅ | - | UniSat API key |
| network | Network | ❌ | 'mainnet' | Network type |
| baseURL | string | ❌ | - | Custom API base URL |
| timeout | number | ❌ | 30000 | Request timeout in milliseconds |
Supported Network Types
type Network = 'mainnet' | 'testnet' | 'testnet4' | 'signet' | 'fractal-mainnet' | 'fractal-testnet';Network Description
mainnet: Bitcoin mainnettestnet: Bitcoin testnettestnet4: Bitcoin testnet v4signet: Bitcoin Signet (supports Alkanes)fractal-mainnet: Fractal mainnetfractal-testnet: Fractal testnet
Protocol Support Matrix
| Network | BRC-20 | Runes | Alkanes | Collections | Fractal BRC20 | |---------|--------|-------|---------|-------------|---------------| | mainnet | ✅ | ✅ | ✅ | ✅ | ❌ | | testnet | ✅ | ✅ | ❌ | ✅ | ❌ | | testnet4 | ✅ | ✅ | ❌ | ✅ | ❌ | | signet | ✅ | ✅ | ✅ | ✅ | ❌ | | fractal-mainnet | ✅ | ✅ | ✅ | ✅ | ✅ | | fractal-testnet | ✅ | ✅ | ❌ | ✅ | ✅ |
💡 Tip: Alkanes protocol is currently only supported on mainnet, signet, and fractal-mainnet. Calling Alkanes-related APIs on unsupported networks will throw an error.
⚠️ Error Handling
All API methods return Promises, it's recommended to use try/catch or .catch() for error handling:
try {
const balance = await client.address.getAddressBalance(address);
console.log('Balance:', balance.data);
} catch (error) {
console.error('Failed to get balance:', error.message);
// v2.0+ enhanced error information
if (error.response) {
console.error('Status code:', error.response.status);
console.error('Error details:', error.response.data);
}
}🧪 Testing
Run the test suite:
# Install dependencies
npm install
# Set up environment variables (optional)
cp .env.example .env
# Edit .env file and add your UniSat API key
# UNISAT_API_KEY=your_api_key_here
# Run tests
bun test
# Or using npm
npm test
# Run test coverage report
npm run test:coverage
# Run tests in watch mode
npm run test:watchImportant Notes:
- Tests will attempt to connect to UniSat API. If a valid API key is not set, some tests may skip actual API calls
- Tests mainly verify client initialization, parameter validation, and error handling functionality
- It's recommended to use testnet API keys in a test environment
Tests cover all major features and new v2.0+ capabilities.
🛠️ Development
Development Environment Setup
# Clone repository
git clone https://github.com/IceHugh/unisat-api.git
cd unisat-api
# Install dependencies
npm install
# Development build
npm run build
# Run tests
npm test
# Code linting
npm run lint
# Code formatting
npm run lint:fix
# Format code
npm run format:fixCode Quality Tools
This project uses Biome V2 for superior code quality and formatting:
- Linting:
npm run lint- Check code quality and formatting - Auto-fix:
npm run lint:fix- Automatically fix linting issues - Formatting:
npm run format:fix- Format code with Biome
Project Structure
unisat-api/
├── src/ # Source code
│ ├── client.ts # HTTP client with interceptors
│ ├── index.ts # Main entry point
│ ├── type.ts # Type definitions
│ ├── addresses.ts # Address operations
│ ├── blocks.ts # Blockchain queries
│ ├── brc20.ts # BRC-20 operations
│ ├── runes.ts # Runes protocol
│ ├── transactions.ts # Transaction operations
│ ├── inscribe.ts # Inscription minting
│ ├── inscriptions.ts # Inscription queries
│ └── market/ # Market data modules
├── test/ # Test files
├── dist/ # Build output
└── docs/ # Documentation🙌 Contributing
We welcome and appreciate all forms of contribution. If you'd like to contribute to the project, please follow these steps:
- 🍴 Fork this repository
- 🌿 Create your feature branch (
git checkout -b feature/AmazingFeature) - 💻 Commit your changes (
git commit -m 'Add some AmazingFeature') - 🚀 Push to the branch (
git push origin feature/AmazingFeature) - 🎉 Open a Pull Request
Before submitting a Pull Request, please ensure your code follows our coding standards and passes all tests.
Contributing Guidelines
- Follow the existing code style and conventions
- Add tests for new features
- Update documentation for API changes
- Ensure all tests pass before submitting
- Use meaningful commit messages
📄 Version History
v2.1.2 (2025-10-23)
- 🎨 Enhanced Documentation: Added comprehensive badges for better project visibility
- 🌐 Improved Language Navigation: Added clear language switch links between English and Chinese docs
- 📊 Project Metrics: Added badges for download counts, build status, code coverage, and community engagement
- 🔗 Better User Experience: Enhanced README structure with professional project badges
- 🏷️ Standard Compliance: Followed open-source project best practices for README presentation
v2.1.1 (2025-10-23)
- 📝 Documentation Updates: Complete rewrite of README files with comprehensive v2.1.0 features
- 🌐 Bilingual Support: Added comprehensive Chinese documentation (README_zh.md)
- 📚 Enhanced Examples: Expanded code examples and usage guides
- 🔗 Cross-linking: Improved navigation between English and Chinese documentation
- ✨ Polish: Minor documentation improvements and formatting updates
v2.1.0 (2025-10-23)
- 🔧 Biome V2 Migration: Upgraded to Biome V2 for enhanced code quality
- 🛡️ Type Safety Improvements: Enhanced TypeScript type definitions and checks
- 🎨 Developer Experience: Improved tooling and development workflow
- 🔍 Code Quality: Better linting rules and formatting standards
- 📦 Build Optimization: Improved build process and output
v2.0.0 (2025-01-22)
- ✨ Added Alkanes protocol support
- ✨ Added Collections functionality
- ✨ Added Fractal network support
- ✨ Added batch request functionality
- ✨ Added health check functionality
- ✨ Added dynamic network switching
- ✨ Added request cancellation functionality
- ✨ Enhanced error handling and performance monitoring
- 📦 Complete type definition updates
- 🧪 Comprehensive test coverage
v1.x.x
- 🎯 Initial version release
- 📦 Basic UniSat API wrapper
- 🔧 TypeScript support
- 🌐 Mainnet and testnet support
📄 License
This project is licensed under the MIT License. See the LICENSE file for details.
🔗 Related Links
- 🌍 UniSat Official Website
- 📚 UniSat API Documentation
- 🛠️ UniSat Developer Center
- 📊 UniSat API Swagger
- 🐙 GitHub Repository
- 📦 NPM Package
📬 Contact Us
If you have any questions or suggestions, please contact us through:
- 💬 Submit a GitHub Issue
- 🐙 GitHub Repository
- 📧 Email us
- 💬 Join our Discord Community
🤝 Acknowledgments
- Thanks to the UniSat team for providing the excellent API service
- Thanks to all contributors who have helped improve this project
- Built with ❤️ for the Bitcoin ecosystem
Thank you for using UniSat API Client! 🚀
⭐ If this project helps you, please give us a Star!
