Package Exports
- hoosat-sdk-web
Readme
hoosat-sdk-web
Browser-compatible TypeScript SDK for Hoosat blockchain. Build wallets, web extensions, and dApps with full crypto support in the browser.
๐ Features
- โ Browser-native - No Node.js dependencies, runs in any browser
- โ Cryptography - ECDSA key generation, signing, address creation
- โ Message Signing - Sign and verify messages for authentication and DApp integration
- โ Transaction Builder - Build and sign transactions with automatic fee calculation
- โ REST API Client - Connect to Hoosat proxy for balance, UTXOs, and submissions
- โ QR Code Generator - Payment URIs and address QR codes
- โ TypeScript - Full type safety with comprehensive types
- โ Lightweight - ~150KB gzipped
๐ฆ Installation
npm install hoosat-sdk-web๐ง Quick Start
1. Generate Wallet
import { HoosatCrypto } from 'hoosat-sdk-web';
// Generate new wallet
const wallet = HoosatCrypto.generateKeyPair('mainnet');
console.log('Address:', wallet.address);
console.log('Private Key:', wallet.privateKey.toString('hex'));
// Or import existing wallet
const imported = HoosatCrypto.importKeyPair('your-private-key-hex', 'mainnet');2. Check Balance
import { HoosatBrowserClient, HoosatUtils } from 'hoosat-sdk-web';
const client = new HoosatBrowserClient({
baseUrl: 'https://proxy.hoosat.net/api/v1'
});
const balance = await client.getBalance('hoosat:qz7ulu...');
console.log(`Balance: ${HoosatUtils.sompiToAmount(balance.balance)} HTN`);3. Send Transaction
import { HoosatTxBuilder, HoosatCrypto } from 'hoosat-sdk-web';
// Get UTXOs
const utxos = await client.getUtxos([wallet.address]);
// Build transaction
const builder = new HoosatTxBuilder();
utxos.utxos.forEach(utxo => {
builder.addInput(utxo, wallet.privateKey);
});
builder
.addOutput('hoosat:recipient...', '100000000') // 1 HTN in sompi
.setFee('2500')
.addChangeOutput(wallet.address);
// Sign and submit
const signedTx = builder.sign();
const result = await client.submitTransaction(signedTx);
console.log('TX ID:', result.transactionId);4. Generate QR Code
import { HoosatQR } from 'hoosat-sdk-web';
// Simple address QR
const qr = await HoosatQR.generateAddressQR('hoosat:qz7ulu...');
// Use in HTML: <img src="${qr}" />
// Payment request QR
const paymentQR = await HoosatQR.generatePaymentQR({
address: 'hoosat:qz7ulu...',
amount: 100, // HTN
label: 'Coffee Shop',
message: 'Order #12345'
});5. Sign Messages (Authentication, DApp Integration)
import { HoosatSigner } from 'hoosat-sdk-web';
// Sign a message with your wallet
const privateKey = wallet.privateKey.toString('hex');
const message = 'Sign in to MyDApp\nTimestamp: ' + Date.now();
const signature = HoosatSigner.signMessage(privateKey, message);
// Verify the signature
const publicKey = wallet.publicKey.toString('hex');
const isValid = HoosatSigner.verifyMessage(signature, message, publicKey);
console.log('Signature valid:', isValid);
// Create a complete signed message object
const signedMessage = HoosatSigner.createSignedMessage(
privateKey,
message,
wallet.address
);
// Returns: { message, signature, address, timestamp }
// Verify signed message object
const result = HoosatSigner.verifySignedMessage(signedMessage, publicKey);
if (result.valid) {
console.log('Authenticated!');
}๐ API Reference
HoosatCrypto
Key Management:
generateKeyPair(network?)- Generate new ECDSA key pairimportKeyPair(privateKeyHex, network?)- Import from private keygetPublicKey(privateKey)- Derive public key
Address Operations:
publicKeyToAddressECDSA(publicKey, network?)- Create ECDSA addresspublicKeyToAddress(publicKey, network?)- Create Schnorr addressaddressToScriptPublicKey(address)- Convert to script
Transaction Signing:
signTransactionInput(tx, inputIndex, privateKey, utxo)- Sign inputverifyTransactionSignature(tx, inputIndex, sig, pubKey, utxo)- VerifygetTransactionId(tx)- Calculate TX ID
Utilities:
calculateFee(inputCount, outputCount, feePerByte?)- Estimate feeblake3Hash(data)- BLAKE3 hashsha256Hash(data)- SHA256 hash
HoosatSigner
Message Signing:
signMessage(privateKey, message)- Sign message with ECDSAverifyMessage(signature, message, publicKey)- Verify signaturegetPublicKey(privateKey, compressed?)- Get public key from private keyrecoverPublicKey(signature, message, recoveryId?)- Recover public key from signature
Signed Message Objects:
createSignedMessage(privateKey, message, address)- Create complete signed message with metadataverifySignedMessage(signedMessage, publicKey)- Verify signed message object
Utilities:
hashMessage(message)- Hash message with BLAKE3 (includes prefix)formatMessage(message)- Format message with Hoosat prefixMESSAGE_PREFIX- Standard message prefix: "Hoosat Signed Message:\n"
HoosatTxBuilder
Building:
addInput(utxo, privateKey?)- Add inputaddOutput(address, amount)- Add output (max 2 recipients)addChangeOutput(address)- Add change automaticallysetFee(fee)- Set transaction feesetLockTime(lockTime)- Set lock time
Info:
getTotalInputAmount()- Total input valuegetTotalOutputAmount()- Total output valueestimateFee(feePerByte?)- Estimate fee
Execution:
build()- Build unsigned transactionsign(privateKey?)- Sign transactionbuildAndSign(privateKey?)- Build and signvalidate()- Validate amountsclear()- Reset builder
HoosatBrowserClient
Constructor:
new HoosatBrowserClient({
baseUrl: 'https://proxy.hoosat.net/api/v1',
timeout: 30000,
debug: false
})Methods:
getBalance(address)- Get address balancegetUtxos(addresses)- Get UTXOs for addressessubmitTransaction(tx)- Submit signed transactiongetFeeEstimate()- Get recommended feesgetNetworkInfo()- Get network informationcheckHealth()- Check API healthping()- Quick connectivity check
HoosatUtils
Amount Conversion:
sompiToAmount(sompi)- Convert sompi to HTNamountToSompi(htn)- Convert HTN to sompiformatAmount(htn, decimals?)- Format with separators
Validation:
isValidAddress(address)- Validate Hoosat addressisValidTransactionId(txId)- Validate TX IDisValidHash(hash, length?)- Validate hex hashisValidPrivateKey(privateKey)- Validate private keyisValidAmount(amount, maxDecimals?)- Validate amount
Address Info:
getAddressVersion(address)- Get address version (0x00, 0x01, 0x08)getAddressType(address)- Get type (schnorr, ecdsa, p2sh)getAddressNetwork(address)- Get network (mainnet, testnet)
Formatting:
truncateAddress(address, start?, end?)- Truncate for UItruncateHash(hash, start?, end?)- Truncate hashformatHashrate(hashrate, decimals?)- Format hashrate (H/s, TH/s, etc)formatDifficulty(difficulty, decimals?)- Format difficulty
Conversion:
hexToBuffer(hex)- Convert hex to BufferbufferToHex(buffer)- Convert Buffer to hex
HoosatQR
Generation:
generateAddressQR(address, options?)- Generate address QR (Data URL)generatePaymentQR(params, options?)- Generate payment QRgenerateQRSVG(address, options?)- Generate as SVGgenerateQRBuffer(address, options?)- Generate as BuffergenerateQRTerminal(address)- Generate ASCII QR
Parsing:
buildPaymentURI(params)- Build payment URI stringparsePaymentURI(uri)- Parse payment URIisValidPaymentURI(uri)- Validate URI
๐ Network Support
- Mainnet -
hoosat:addresses - Testnet -
hoosattest:addresses
๐ Security Best Practices
// โ Never hardcode private keys
const privateKey = '33a4a81e...';
// โ
Use environment variables
const privateKey = process.env.WALLET_PRIVATE_KEY;
// โ
Clear sensitive data
let keyBuffer = Buffer.from(privateKey, 'hex');
// ... use key ...
keyBuffer.fill(0);
keyBuffer = null;๐งช Testing
# Run tests
npm test
# Run with coverage
npm run test:coverage
# Browser tests
npm run test:browser๐ Examples
See examples/ folder:
example-wallet.html- Full wallet implementationtest-browser.html- SDK functionality tests
๐ค Related Projects
- hoosat-sdk - Full Node.js SDK with gRPC
- hoosat-proxy - REST API proxy for Hoosat
- Hoosat - Official Hoosat blockchain
๐ License
MIT License - see LICENSE file for details
๐ Links
- GitHub: https://github.com/Namp88/hoosat-sdk-web
- Issues: https://github.com/Namp88/hoosat-sdk-web/issues
- NPM: https://www.npmjs.com/package/hoosat-sdk-web
- Hoosat Website: https://hoosat.fi
๐ฌ Support
For questions and support:
- Open an issue
- Email: namp2988@gmail.com
Made with โค๏ธ for the Hoosat community