Sui gRPC API - High Performance Access
Access Sui blockchain data with gRPC for high-performance, low-latency communication. Learn how to use Dwellir's Sui gRPC infrastructure for efficient blockchain queries and real-time subscriptions.
High-Performance Blockchain Data Access
Dwellir's Sui gRPC API provides a high-performance alternative to traditional JSON-RPC for accessing Sui blockchain data. Built on Protocol Buffers and HTTP/2, gRPC offers superior performance, type safety, and efficient binary serialization for demanding applications that require minimal latency and maximum throughput.
Quick Reference — Connecting to Sui gRPC
Endpoint — connect over TLS on port 443:
api-sui-mainnet-full.n.dwellir.com:443Port 443 is typically not required — most gRPC libraries default to it for TLS connections. Some tools like
grpcurldo require it explicitly.
Authentication — pass your API key as gRPC metadata (not as a URL path segment):
x-api-key: YOUR_API_TOKENGet your API token from dashboard.dwellir.com. See Connection Configuration and Authentication for full details, or jump straight to language-specific setup guides.
Why Use gRPC?
Performance Advantages
- Binary Protocol: Protocol Buffers provide compact binary encoding, reducing payload sizes by up to 70% compared to JSON
- HTTP/2 Multiplexing: Multiple concurrent requests over a single connection eliminate connection overhead
- Streaming Support: Bidirectional streaming enables real-time data feeds with minimal latency
- Efficient Serialization: Native binary format significantly reduces parsing overhead
Developer Benefits
- Strong Typing: Protocol Buffer definitions provide compile-time type checking
- Code Generation: Automatic client generation from
.protofiles eliminates boilerplate - Language Support: Native implementations available for Go, Python, TypeScript, Rust, and more
- Built-in Features: Deadlines, cancellation, and load balancing come standard
Use Cases for gRPC
- High-frequency trading: Microsecond-level latency requirements
- Real-time monitoring: Live blockchain event streaming and monitoring dashboards
- Analytics pipelines: Bulk data extraction and processing
- Mobile applications: Reduced bandwidth consumption on limited connections
- Microservices: Efficient inter-service communication in distributed architectures
gRPC vs JSON-RPC Comparison
| Feature | gRPC | JSON-RPC |
|---|---|---|
| Protocol | HTTP/2 + Protocol Buffers | HTTP/1.1 + JSON |
| Payload Size | Compact binary (~30% smaller) | Text-based JSON |
| Streaming | Bidirectional streaming support | Request/response only |
| Type Safety | Strong typing via .proto | Runtime validation required |
| Performance | 5-10x faster serialization | Slower text parsing |
| Browser Support | Requires gRPC-Web proxy | Native browser support |
| Tooling | Code generation required | Simpler setup |
Available Services
The Sui gRPC API is organized into six specialized services:
1. Ledger Service
Access historical blockchain data and core object information:
- Retrieve objects by ID with field masking
- Query transactions with execution details
- Access checkpoint and epoch data
- Batch operations for multiple objects or transactions
2. Live Data Service
Query current blockchain state efficiently:
- Check account balances for any coin type
- List owned objects with pagination
- Enumerate dynamic fields
- Simulate transactions before execution
- Retrieve coin metadata and information
3. Transaction Service
Execute and broadcast transactions:
- Submit signed transactions for on-chain execution
- Monitor transaction status and finality
- Dry-run transactions for gas estimation
4. Move Package Service
Inspect Move smart contracts and modules:
- Retrieve package information and metadata
- Query function signatures and capabilities
- Inspect data types and structures
- List package version history
5. Subscription Service
Real-time blockchain event streaming:
- Subscribe to checkpoint updates as they finalize
- Stream events matching specific filters
- Monitor transaction confirmations in real-time
6. Signature Verification Service
Cryptographic signature operations:
- Verify transaction signatures off-chain
- Validate multi-sig configurations
- Check signature authenticity
Connection Configuration
Endpoint Structure
Dwellir's Sui gRPC endpoints follow this format:
api-sui-mainnet-full.n.dwellir.com:443Important Notes:
- gRPC uses port 443
- Connections require TLS encryption
- Authentication via metadata headers
Network Endpoints
| Network | gRPC Endpoint |
|---|---|
| Mainnet | api-sui-mainnet-full.n.dwellir.com:443 |
| Testnet | Dedicated nodes only (contact us) |
Note: Testnet access is currently offered only through dedicated nodes. Reach out to our team to provision a testnet endpoint.
Authentication
All gRPC requests to Dwellir's Sui endpoints require sending your API token in the x-api-key metadata header:
x-api-key: YOUR_API_TOKENDo not append the token as a path segment to the gRPC endpoint. Retrieve your API token from the Dwellir dashboard and pass it only via the header.
const metadata = new grpc.Metadata();
metadata.add('x-api-key', API_TOKEN);
client.GetObject(request, metadata, (error, response) => { ... });Security Best Practices
- Never expose tokens in client-side code: Use backend services to proxy gRPC requests
- Rotate tokens periodically: Generate new tokens through the Dwellir dashboard
- Use environment variables: Store tokens outside of source code
- Monitor usage: Track API consumption via the Dwellir dashboard
Quick Start Guide
Prerequisites
- Dwellir API Key: Obtain from dashboard.dwellir.com
- Protocol Buffers: Install
protoccompiler for code generation - gRPC Libraries: Language-specific gRPC implementation
Protocol Buffer Files
Download the official Sui proto definitions from the MystenLabs sui-apis repository:
# Clone the Sui API definitions
git clone https://github.com/MystenLabs/sui-apis.git
cd sui-apisKey proto files:
ledger.proto- Ledger service definitionslive_data.proto- Live data queriestransaction.proto- Transaction executionmove_package.proto- Move package inspectionsubscription.proto- Real-time subscriptionssignature_verification.proto- Signature operations
Language-Specific Setup
Field Masking
gRPC requests support field masking to optimize response payloads and reduce bandwidth. Specify only the fields you need:
const request = {
object_id: '0x5',
read_mask: {
paths: ['object_id', 'version', 'owner'] // Only return these fields
}
};Benefits:
- Reduced response sizes (up to 80% smaller)
- Faster serialization and network transfer
- Lower bandwidth costs
- Improved application performance
Error Handling
gRPC provides standardized error codes for consistent error handling:
| Code | Description | Action |
|---|---|---|
OK (0) | Success | Continue processing |
CANCELLED (1) | Client cancelled | Retry if needed |
INVALID_ARGUMENT (3) | Invalid request parameters | Fix request and retry |
NOT_FOUND (5) | Resource not found | Verify object IDs |
ALREADY_EXISTS (6) | Resource exists | Handle duplicate |
PERMISSION_DENIED (7) | Authentication failed | Check API token |
RESOURCE_EXHAUSTED (8) | Rate limit exceeded | Implement backoff |
FAILED_PRECONDITION (9) | System state invalid | Retry later |
UNAVAILABLE (14) | Service unavailable | Retry with backoff |
DEADLINE_EXCEEDED (4) | Request timeout | Increase timeout |
Example Error Handling
Performance Optimization
Connection Pooling
Reuse gRPC channels across requests to avoid connection overhead:
// Create a single channel for the application lifecycle
const channel = new grpc.Client(
ENDPOINT,
credentials,
{ 'grpc.keepalive_time_ms': 10000 }
);
// Reuse channel for all services
const ledgerClient = new protoDescriptor.sui.rpc.v2.LedgerService(channel);
const stateClient = new protoDescriptor.sui.rpc.v2.StateService(channel);Batch Requests
Use batch methods when querying multiple items:
// Efficient: Single batch request
const batchResponse = await client.BatchGetObjects({
object_ids: ['0x1', '0x2', '0x3', '0x4', '0x5']
});
// Inefficient: Multiple individual requests
for (const id of objectIds) {
await client.GetObject({ object_id: id }); // Avoid this pattern
}Field Masking
Request only necessary fields to minimize payload size:
// Efficient: Only request needed fields
const request = {
object_id: '0x5',
read_mask: { paths: ['object_id', 'owner'] }
};
// Inefficient: Requesting all fields
const request = { object_id: '0x5' }; // Returns everythingCompression
Enable gRPC compression for large payloads:
const options = {
'grpc.default_compression_algorithm': grpc.compressionAlgorithms.gzip,
'grpc.default_compression_level': grpc.compressionLevels.high
};
const client = new protoDescriptor.sui.rpc.v2.LedgerService(
ENDPOINT,
credentials,
options
);Real-Time Streaming
gRPC's streaming capabilities enable real-time blockchain monitoring:
Checkpoint Subscription Example
const subscribeRequest = {
read_mask: {
paths: [
'sequence_number',
'digest',
'timestamp_ms',
'network_total_transactions'
]
}
};
const stream = client.SubscribeCheckpoints(subscribeRequest, metadata);
stream.on('data', (checkpoint) => {
console.log('New checkpoint:', {
sequence: checkpoint.sequence_number,
digest: checkpoint.digest,
timestamp: new Date(parseInt(checkpoint.timestamp_ms)),
txCount: checkpoint.network_total_transactions
});
});
stream.on('error', (error) => {
console.error('Stream error:', error.message);
// Implement reconnection logic
});
stream.on('end', () => {
console.log('Stream ended');
});Stream Management Best Practices
- Implement reconnection logic: Automatically reconnect on stream failures
- Handle backpressure: Process data faster than it arrives or implement buffering
- Monitor connection health: Use keepalive pings and heartbeats
- Graceful shutdown: Close streams properly to avoid resource leaks
Best Practices
1. Use Appropriate Timeouts
Set reasonable timeouts to prevent hanging requests:
const deadline = new Date();
deadline.setSeconds(deadline.getSeconds() + 10);
client.GetObject(request, { deadline }, (error, response) => {
// Handle response
});2. Implement Exponential Backoff
Handle rate limits and transient failures gracefully:
async function retryWithBackoff(fn, maxRetries = 5) {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn();
} catch (error) {
if (i === maxRetries - 1) throw error;
const waitTime = Math.min(1000 * Math.pow(2, i), 30000);
await new Promise(resolve => setTimeout(resolve, waitTime));
}
}
}3. Monitor and Log
Track gRPC performance metrics:
const call = client.GetObject(request, metadata, callback);
call.on('status', (status) => {
console.log('RPC Status:', status.code, status.details);
});
call.on('metadata', (metadata) => {
console.log('Server metadata:', metadata.getMap());
});4. Validate Inputs
Validate request parameters before sending:
function isValidObjectId(id: string): boolean {
return /^0x[a-f0-9]+$/i.test(id);
}
if (!isValidObjectId(objectId)) {
throw new Error('Invalid object ID format');
}Migration from JSON-RPC
Transitioning from JSON-RPC to gRPC requires minimal code changes:
| JSON-RPC | gRPC Equivalent |
|---|---|
sui_getObject | LedgerService.GetObject |
suix_getBalance | StateService.GetBalance |
sui_executeTransactionBlock | TransactionService.ExecuteTransaction |
suix_subscribeEvent | SubscriptionService.SubscribeCheckpoints |
Example Migration
Before (JSON-RPC):
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
method: 'sui_getObject',
params: [objectId],
id: 1
})
});
const data = await response.json();After (gRPC):
const response = await new Promise((resolve, reject) => {
client.GetObject(
{ object_id: objectId },
metadata,
(error, response) => {
if (error) reject(error);
else resolve(response);
}
);
});Troubleshooting
Common Issues
Connection Refused
- Verify port 443 is used for gRPC
- Check firewall settings allow outbound connections on port 443
- Ensure TLS credentials are properly configured
Authentication Errors
- Verify API token is correct and active
- Check token is passed in
x-api-keymetadata header - Confirm endpoint URL matches your Dwellir account
Timeout Errors
- Increase request timeout/deadline
- Check network connectivity and latency
- Verify endpoint availability via Dwellir dashboard
Protocol Buffer Errors
- Ensure proto files match server version
- Regenerate client code after proto updates
- Check import paths and dependencies
Support and Resources
Documentation
- Ledger Service Methods - Object and transaction queries
- Live Data Service Methods - Real-time state queries
- Subscription Service - Event streaming
Getting Help
- Email: support@dwellir.com
- Dashboard: dashboard.dwellir.com
- Status Page: Monitor service health and incidents
Additional Resources
Ready to build with gRPC? Get your API key and experience the performance difference with Dwellir's enterprise-grade Sui infrastructure.
suix_queryTransactionBlocks - Query Tran...
Query and filter Sui transactions using suix_queryTransactionBlocks RPC method. Search by sender, recipient, transaction kind, time range with pagination support using Dwellir's high-performance Sui infrastructure.
Sui gRPC Go
Complete guide to building production Go applications with Sui gRPC API on Dwellir. Includes project setup, type safety, connection pooling, and production patterns.