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: Server-streaming subscriptions deliver checkpoints without polling
- 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 checkpoint, transaction, and event processing
- 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 | Server-streaming checkpoint subscriptions | Request/response and deprecated WebSocket subscriptions |
| 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 seven 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. State Service
Query current blockchain state efficiently:
- Check account balances for any coin type
- List owned objects with pagination
- Enumerate dynamic fields
- Retrieve coin metadata and information
3. Transaction Execution Service
Execute and broadcast transactions:
- Submit signed transactions for on-chain execution
- Simulate transactions before execution for gas estimation and validation
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 checkpoint streaming:
- Subscribe to checkpoint updates as they finalize
- Request only the checkpoint fields needed with a field mask
- Inspect transactions and events client-side as checkpoints arrive
The standard Sui subscription does not support server-side filters for wallets, Move calls, packages, modules, functions, or event types. It emits every checkpoint. Use a field mask to reduce each response, then filter the selected transaction and event data client-side. See SubscribeCheckpoints for request shapes and filtering examples.
6. Signature Verification Service
Cryptographic signature operations:
- Verify transaction signatures off-chain
- Validate multi-sig configurations
- Check signature authenticity
7. Name Service
Resolve SuiNS records:
- Resolve a SuiNS name to its record
- Reverse-resolve an address to its default name
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_service.proto- Ledger service definitionsstate_service.proto- Current state queriestransaction_execution_service.proto- Transaction execution and simulationmove_package_service.proto- Move package inspectionsubscription_service.proto- Checkpoint subscriptionssignature_verification_service.proto- Signature operationsname_service.proto- SuiNS resolution
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 subscriptionDefinition = protoLoader.loadSync(
'./protos/sui/rpc/v2/subscription_service.proto',
{
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true,
includeDirs: ['./protos']
}
);
const subscriptionDescriptor = grpc.loadPackageDefinition(
subscriptionDefinition
) as any;
const request = {
read_mask: {
paths: [
'sequence_number',
'digest',
'summary.timestamp',
'transactions.digest'
]
}
};
const subscriptionClient = new subscriptionDescriptor.sui.rpc.v2.SubscriptionService(
ENDPOINT,
credentials
);
const stream = subscriptionClient.SubscribeCheckpoints(request, metadata);
stream.on('data', (response) => {
const checkpoint = response.checkpoint;
if (!checkpoint) return;
console.log('New checkpoint:', {
sequence: checkpoint.sequence_number,
digest: checkpoint.digest,
timestamp: checkpoint.summary?.timestamp,
txCount: checkpoint.transactions?.length ?? 0
});
});
stream.on('error', (error) => {
console.error('Stream error:', error.message);
// Implement reconnection logic
});
stream.on('end', () => {
console.log('Stream ended');
});SubscribeCheckpoints does not support server-side filters. A field mask only
selects which fields are returned for every checkpoint; it does not select
which checkpoints or transactions the server sends. Request the fields needed
for matching, then filter transactions and events client-side. For example:
- Wallet senders:
transactions.transaction.sender - Wallet balance changes:
transactions.balance_changes - Move package, module, and function calls:
transactions.transaction.kind - Event package, module, sender, and type:
transactions.events.events
Sui's native gRPC guidance recommends GraphQL for filtered historical transaction and event queries. It is useful for backfills and lookups, but it does not replace the live global checkpoint subscription.
Stream Management Best Practices
- Recover gaps on reconnect: Persist the last cursor, compare it with the first cursor after reconnecting, and backfill missing checkpoints before processing buffered live data
- 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 generated clients and explicit request and response mapping. Use this table as a starting point:
| JSON-RPC | gRPC Equivalent |
|---|---|
sui_getObject | LedgerService.GetObject |
suix_getBalance | StateService.GetBalance |
sui_executeTransactionBlock | TransactionExecutionService.ExecuteTransaction |
suix_subscribeEvent | No direct filtered subscription equivalent; use SubscribeCheckpoints with client-side filtering |
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
- State Service Methods - Current state queries
- Subscription Service - Checkpoint 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.