TypeScript Integration
This guide demonstrates how to integrate the Surflux gRPC API into your backend using TypeScript. You'll learn how to configure the client to authenticate with your API key.
Prerequisites
Ensure you have the necessary packages installed:
npm install @mysten/sui @protobuf-ts/grpcweb-transport
Example Code
The following example shows how to create a custom fetch transport that injects your x-api-key header into every request.
import { SuiGrpcClient } from '@mysten/sui/grpc';
import { GrpcWebFetchTransport } from '@protobuf-ts/grpcweb-transport';
// Replace with your actual API key
const API_KEY = 'YOUR_API_KEY';
// Custom fetch function to inject the API key header
const fetchWithApiKey = async (url: string | URL | Request, init?: RequestInit): Promise<Response> => {
const headers = new Headers(init?.headers);
headers.set('x-api-key', API_KEY);
return fetch(url, {
...init,
headers,
credentials: 'include',
});
};
// Initialize the gRPC client with the custom transport
const grpcClient = new SuiGrpcClient({
network: 'mainnet',
transport: new GrpcWebFetchTransport({
baseUrl: 'https://grpc.surflux.dev',
fetch: fetchWithApiKey,
}),
});
// Example usage: Fetch current epoch information
const run = async () => {
try {
const { response: epochInfo } = await grpcClient.ledgerService.getEpoch({});
console.log('Current Epoch Info:', epochInfo);
} catch (error) {
console.error('Error fetching epoch info:', error);
}
};
run();
Key Concepts
- Custom Transport: We use
GrpcWebFetchTransportto handle the network requests. - Header Injection: The
fetchWithApiKeyfunction intercepts the fetch call to add thex-api-keyheader, which is required for authentication. - Client Initialization: The
SuiGrpcClientis initialized with the custom transport pointing tohttps://grpc.surflux.dev.