Blockchain Integration Solution
Connect directly to the Provenance blockchain with NUVA Labs' comprehensive blockchain integration APIs. This solution covers everything from node connectivity to transaction broadcasting and event monitoring.
Overview
The Blockchain Integration solution provides APIs for:
- Node Connectivity: Connect to blockchain nodes
- Transaction Broadcasting: Send transactions to the network
- Event Monitoring: Monitor blockchain events in real-time
- Consensus Participation: Participate in network consensus
- Blockchain Data Access: Access raw blockchain data
Key Features
🔗 Node Connectivity
- Connect to multiple blockchain nodes
- Load balancing and failover
- Connection health monitoring
- Automatic reconnection
📡 Transaction Broadcasting
- Send transactions to the network
- Transaction status tracking
- Confirmation monitoring
- Error handling and retries
👁️ Event Monitoring
- Real-time blockchain event monitoring
- Custom event filtering
- Event history and replay
- WebSocket event streams
🏗️ Consensus Participation
- Validator node management
- Staking and delegation
- Governance participation
- Network health monitoring
Quick Start
1. Connect to Blockchain
import { NUClient } from '@nu/sdk';
const client = new NUClient({
clientId: process.env.NU_CLIENT_ID,
clientSecret: process.env.NU_CLIENT_SECRET,
environment: 'production',
});
await client.authenticate();
// Connect to blockchain
const connection = await client.connectToBlockchain({
nodeUrl: 'https://pio-mainnet-1-rpc.provlabs.com',
timeout: 30000,
});
console.log('Connected to blockchain:', connection.nodeInfo);
2. Broadcast Transaction
// Create and broadcast transaction
const transaction = await client.broadcastTransaction({
type: 'transfer',
from: 'acc_1234567890',
to: 'acc_0987654321',
amount: 100,
assetId: 'asset_1234567890',
memo: 'Payment',
});
console.log('Transaction broadcasted:', transaction.txHash);
3. Monitor Events
// Monitor blockchain events
const ws = client.createBlockchainWebSocket();
ws.on('newBlock', (block) => {
console.log('New block:', block.height);
});
ws.on('transactionConfirmed', (tx) => {
console.log('Transaction confirmed:', tx.txHash);
});
ws.on('validatorUpdate', (validator) => {
console.log('Validator update:', validator.address);
});
API Reference
Blockchain Integration Endpoints
| Endpoint | Method | Description |
|---|---|---|
/blockchain/connect | POST | Connect to blockchain |
/blockchain/status | GET | Get blockchain status |
/blockchain/broadcast | POST | Broadcast transaction |
/blockchain/events | GET | Get event history |
/blockchain/subscribe | POST | Subscribe to events |
Node Connectivity
Connect to Node
const connection = await client.connectToBlockchain({
nodeUrl: 'https://pio-mainnet-1-rpc.provlabs.com',
timeout: 30000,
retries: 3,
});
console.log('Node info:', connection.nodeInfo);
console.log('Network:', connection.network);
console.log('Chain ID:', connection.chainId);
Get Node Status
const status = await client.getBlockchainStatus();
console.log('Sync status:', status.syncInfo);
console.log('Validator info:', status.validatorInfo);
console.log('Network info:', status.networkInfo);
Health Check
const health = await client.getBlockchainHealth();
console.log('Node health:', health.status);
console.log('Uptime:', health.uptime);
console.log('Last block:', health.lastBlockTime);
Transaction Broadcasting
Broadcast Transaction
const result = await client.broadcastTransaction({
type: 'transfer',
from: 'acc_1234567890',
to: 'acc_0987654321',
amount: 100,
assetId: 'asset_1234567890',
memo: 'Payment',
});
console.log('Transaction hash:', result.txHash);
console.log('Block height:', result.blockHeight);
console.log('Gas used:', result.gasUsed);
Check Transaction Status
const status = await client.getTransactionStatus('tx_1234567890');
console.log('Status:', status.status);
console.log('Confirmations:', status.confirmations);
console.log('Block height:', status.blockHeight);
Get Transaction Details
const tx = await client.getTransaction('tx_1234567890');
console.log('Transaction details:', tx);
console.log('Events:', tx.events);
console.log('Logs:', tx.logs);
Event Monitoring
Subscribe to Events
// Subscribe to specific events
await client.subscribeToEvents({
events: ['newBlock', 'transactionConfirmed', 'validatorUpdate'],
filters: {
blockHeight: { $gte: 1000000 },
},
});
Get Event History
const events = await client.getEventHistory({
eventType: 'newBlock',
startBlock: 1000000,
endBlock: 1000100,
limit: 100,
});
console.log('Events found:', events.length);
Real-time Event Stream
const ws = client.createBlockchainWebSocket();
ws.on('newBlock', (block) => {
console.log('New block:', block.height, block.hash);
});
ws.on('transactionConfirmed', (tx) => {
console.log('Transaction confirmed:', tx.txHash);
});
ws.on('validatorUpdate', (validator) => {
console.log('Validator update:', validator.address);
});
Consensus Participation
Get Validator Info
const validator = await client.getValidator('val_1234567890');
console.log('Validator address:', validator.address);
console.log('Voting power:', validator.votingPower);
console.log('Commission:', validator.commission);
Get Validator Set
const validators = await client.getValidatorSet();
console.log('Total validators:', validators.length);
console.log(
'Active validators:',
validators.filter((v) => v.status === 'active').length
);
Get Staking Info
const staking = await client.getStakingInfo('acc_1234567890');
console.log('Delegated amount:', staking.delegated);
console.log('Rewards:', staking.rewards);
console.log('Unbonding:', staking.unbonding);
Advanced Features
Multi-Node Connection
const connections = await client.connectToMultipleNodes([
'https://pio-mainnet-1-rpc.provlabs.com',
'https://pio-mainnet-2-rpc.provlabs.com',
'https://pio-mainnet-3-rpc.provlabs.com',
]);
console.log('Connected to', connections.length, 'nodes');
Transaction Batching
const batch = await client.broadcastTransactionBatch([
{
type: 'transfer',
from: 'acc_1234567890',
to: 'acc_0987654321',
amount: 100,
},
{
type: 'transfer',
from: 'acc_1234567890',
to: 'acc_1122334455',
amount: 50,
},
]);
console.log('Batch broadcasted:', batch.txHashes);
Custom Event Filters
const events = await client.getEventHistory({
eventType: 'transactionConfirmed',
filters: {
amount: { $gte: 1000 },
assetId: 'asset_1234567890',
timestamp: { $gte: '2024-01-01' },
},
});
Use Cases
1. Blockchain Monitor
class BlockchainMonitor {
constructor(client) {
this.client = client;
}
async startMonitoring() {
const ws = this.client.createBlockchainWebSocket();
ws.on('newBlock', (block) => {
console.log(`New block: ${block.height} at ${block.timestamp}`);
});
ws.on('transactionConfirmed', (tx) => {
console.log(`Transaction confirmed: ${tx.txHash}`);
});
ws.on('validatorUpdate', (validator) => {
console.log(`Validator update: ${validator.address}`);
});
}
}
2. Transaction Tracker
class TransactionTracker {
constructor(client) {
this.client = client;
}
async trackTransaction(txHash) {
const status = await this.client.getTransactionStatus(txHash);
if (status.status === 'confirmed') {
console.log('Transaction confirmed!');
return status;
} else if (status.status === 'failed') {
console.log('Transaction failed:', status.error);
return status;
} else {
// Still pending, check again later
setTimeout(() => this.trackTransaction(txHash), 5000);
}
}
}
3. Validator Monitor
class ValidatorMonitor {
constructor(client) {
this.client = client;
}
async monitorValidators() {
const validators = await this.client.getValidatorSet();
validators.forEach((validator) => {
console.log(`Validator: ${validator.address}`);
console.log(` Voting Power: ${validator.votingPower}`);
console.log(` Commission: ${validator.commission}%`);
console.log(` Status: ${validator.status}`);
});
}
}
Best Practices
1. Connection Management
- Use connection pooling for multiple requests
- Implement proper error handling and retries
- Monitor connection health regularly
- Handle network interruptions gracefully
2. Transaction Broadcasting
- Validate transactions before broadcasting
- Implement proper error handling
- Monitor transaction status
- Handle confirmation requirements
3. Event Monitoring
- Use appropriate event filters
- Implement proper error handling
- Handle connection drops gracefully
- Monitor subscription limits
4. Performance
- Use batch operations when possible
- Implement proper caching
- Monitor API usage
- Use compression for large datasets
Error Handling
Common Errors
try {
const result = await client.broadcastTransaction(txData);
} catch (error) {
switch (error.code) {
case 'INVALID_TRANSACTION':
console.error('Invalid transaction data');
break;
case 'INSUFFICIENT_FUNDS':
console.error('Insufficient funds for transaction');
break;
case 'NETWORK_ERROR':
console.error('Network connection error');
break;
case 'TIMEOUT':
console.error('Transaction timeout');
break;
default:
console.error('Unexpected error:', error.message);
}
}
Integration Examples
React Blockchain Component
import React, { useState, useEffect } from 'react';
import { NUClient } from '@nu/sdk';
function BlockchainStatus() {
const [status, setStatus] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const client = new NUClient({
clientId: process.env.REACT_APP_NU_CLIENT_ID,
clientSecret: process.env.REACT_APP_NU_CLIENT_SECRET,
environment: 'production',
});
const loadStatus = async () => {
try {
await client.authenticate();
const blockchainStatus = await client.getBlockchainStatus();
setStatus(blockchainStatus);
} catch (error) {
console.error('Failed to load blockchain status:', error);
} finally {
setLoading(false);
}
};
loadStatus();
}, []);
if (loading) return <div>Loading blockchain status...</div>;
return (
<div>
<h2>Blockchain Status</h2>
<div>
<p>Network: {status?.network}</p>
<p>Block Height: {status?.latestBlockHeight}</p>
<p>Chain ID: {status?.chainId}</p>
</div>
</div>
);
}
Next Steps
- Explore Asset Management for asset operations
- Learn about Trading & Transfers for trading functionality
- Check out our API Reference for detailed endpoint documentation
- Review Best Practices for production deployment
Ready to start building? Let's explore our API Reference for complete endpoint documentation!