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.
Sui RPC endpoint: endpoint URLs, plans and pricing.
High-Performance Blockchain Data Access
Dwellir's Sui gRPC API provides typed full-node access for querying data, executing transactions, and consuming live streams. Sui removed JSON-RPC from full nodes in mainnet-v1.82.3, so existing integrations must migrate to gRPC or GraphQL. Built on Protocol Buffers and HTTP/2, gRPC offers efficient binary serialization and explicit request and response schemas.
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 because most gRPC libraries default to it for TLS connections. Tools such as
grpcurlrequire 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
- HTTP/2 Multiplexing: Multiple concurrent requests over a single connection eliminate connection overhead
- Streaming Support: Server-streaming subscriptions deliver checkpoints, transactions, and events 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 and the retired JSON-RPC API
| Feature | gRPC | Retired JSON-RPC |
|---|---|---|
| Protocol | HTTP/2 + Protocol Buffers | HTTP/1.1 + JSON |
| Payload Format | Compact Protocol Buffers | Text-based JSON |
| Streaming | Server-streaming checkpoint, transaction, and event subscriptions | Removed from Sui full nodes |
| Type Safety | Strong typing via .proto | Runtime validation required |
| Serialization | Generated binary codecs | Runtime JSON parsing |
| Availability | Supported full-node API | Removed in mainnet-v1.82.3 |
| Tooling | Generated clients or reflection-aware tools | Existing clients require migration |
Available Services
The API exposes 27 methods across seven stable sui.rpc.v2 services. One experimental sui.rpc.v2alpha proof method brings the total to 28.
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 streaming:
- Subscribe to checkpoint updates as they finalize
- Subscribe to transactions with server-side filters
- Subscribe to events with server-side filters
- Request only the response fields needed with a field mask
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
Experimental Proof Service
Request a checkpoint object proof from sui.rpc.v2alpha.ProofService. The alpha namespace can change without the compatibility guarantees of the stable v2 services.
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 node clusters only (contact us) |
Note: Testnet access is currently offered only through dedicated node clusters. 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, transaction, and event 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:
- Smaller responses when unused fields are omitted
- 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
Reuse service clients
Create each service client once and reuse it across requests. Pass the endpoint string and TLS credentials to its constructor.
The TypeScript setup guide provides a working constructor and callback example. A grpc.Client object is not an endpoint string.
Batch requests
Use BatchGetObjects for multiple object reads. Its request contains requests, an array of GetObjectRequest messages:
grpcurl \
-H "x-api-key: YOUR_API_KEY" \
-d '{"requests":[{"object_id":"0x5"},{"object_id":"0x6"}],"read_mask":{"paths":["object_id","version"]}}' \
api-sui-mainnet-full.n.dwellir.com:443 \
sui.rpc.v2.LedgerService/BatchGetObjectsInspect each batch result for an error, even when the RPC succeeds. Node.js callback clients require a callback or an explicit Promise wrapper; awaiting a unary call object does not return its response.
Field masks
Request the fields your application uses. Omitting read_mask selects method-specific defaults; it does not request every field.
GetObject defaults to object_id, version, and digest. Request owner explicitly when your application needs it:
{
"object_id": "0x5",
"read_mask": {"paths": ["object_id", "version", "owner"]}
}Read-mask roots vary by method. See each method's usage notes before reusing a mask across services.
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 supports a server-side TransactionFilter. A checkpoint matches when any transaction it contains matches the filter. The checkpoint payload can still contain other transactions.
Filtered streams can send progress-only frames containing only a cursor. A missing checkpoint is not an error. Unfiltered streams deliver every checkpoint in order.
See checkpoint recovery before persisting cursors or reconnecting.
Server-side filters
ListCheckpoints, ListTransactions, and their subscriptions accept TransactionFilter. ListEvents and SubscribeEvents accept EventFilter.
Filters use disjunctive normal form: terms are ORed together, and literals within a term are ANDed together. Set negated: true to invert one literal.
An absent filter matches everything. An included filter must contain at least one term; filter: {} returns INVALID_ARGUMENT.
Transaction filter example
Use this value as filter to match transactions from the zero address:
{
"terms": [{
"literals": [{
"sender": {
"address": "0x0000000000000000000000000000000000000000000000000000000000000000"
}
}]
}]
}Transaction predicates are sender, affected_address, affected_object, move_call, emit_module, event_type, event_stream_head, and package_write.
| Predicate | Value fields |
|---|---|
sender, affected_address | address |
affected_object | object_id |
move_call | function: package[::module[::function]] |
emit_module | module: package[::module] |
event_type | event_type: address[::module[::Name[<type_params>]]] |
event_stream_head | stream_id |
package_write | Empty object {} |
Event filter example
This filter selects events whose declared type belongs to the Sui framework's coin module:
{
"terms": [{
"literals": [{
"event_type": {
"event_type": "0x0000000000000000000000000000000000000000000000000000000000000002::coin"
}
}]
}]
}Event filters support sender, emit_module, event_type, and event_stream_head. Use the same value fields listed above.
Use full 32-byte hexadecimal addresses in Move paths. Short prefixes such as 0x2::coin can be rejected by the filter parser.
emit_module matches the top-level Move call that triggered emission. event_type matches the declared event type. These packages can differ.
Every subscription frame carries progress. Transaction and event subscriptions use watermark; checkpoint subscriptions use cursor.
Use the corresponding LedgerService.List* method for retained filtered historical queries. GraphQL supports joined queries and historical data beyond full-node retention.
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, metadata, { 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
Sui JSON-RPC clients stopped working after the full-node service was removed. Migrating to gRPC requires generated clients and explicit request and response mapping. Use the complete migration guide and this table as a starting point:
| JSON-RPC | gRPC Equivalent |
|---|---|
sui_getObject | LedgerService.GetObject |
suix_getBalance | StateService.GetBalance |
sui_executeTransactionBlock | TransactionExecutionService.ExecuteTransaction |
sui_subscribeEvent | SubscriptionService.SubscribeEvents |
suix_queryTransactionBlocks | LedgerService.ListTransactions |
suix_queryEvents | LedgerService.ListEvents |
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
- Complete gRPC Method Reference - All 28 methods
- Ledger Service Methods - Object and transaction queries
- State Service Methods - Current state queries
- Subscription Service - Checkpoint, transaction, and event streams
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.