SDK API Reference
Complete API reference for all exports from @varity-labs/sdk. All signatures, parameters, return types, and examples verified against source code.
Database API
Section titled “Database API”The database API provides zero-config access to Varity’s distributed database.
Exports
Section titled “Exports”import { db, // Pre-configured database singleton Database, // Database class for custom configs Collection, // Type-safe collection class} from '@varity-labs/sdk';
import type { DatabaseConfig, // Database configuration options QueryOptions, // Query options for .get() Document, // Base document type (id, timestamps) CollectionResponse, // Response wrapper type} from '@varity-labs/sdk';Pre-configured database singleton for immediate use.
Type: Database
Description: Ready-to-use database instance that automatically resolves credentials from environment variables.
Auto-Configuration Sources:
NEXT_PUBLIC_VARITY_DB_PROXY_URLorVITE_VARITY_DB_PROXY_URLorREACT_APP_VARITY_DB_PROXY_URL(proxy URL)NEXT_PUBLIC_VARITY_APP_TOKENorVITE_VARITY_APP_TOKENorREACT_APP_VARITY_APP_TOKEN(authentication)- Fallback: Development credentials (automatic)
Example:
import { db } from '@varity-labs/sdk';
// Add a documentconst user = await db.collection('users').add({ name: 'Alice', email: 'alice@example.com'});console.log('Created:', user.id);// Output: Created: doc_abc123console.log('Name:', user.name);// Output: Name: Alice
// Get all documentsconst users = await db.collection('users').get();console.log('Users:', users.length);
// Updateconst updated = await db.collection('users').update(user.id, { name: 'Alice Smith'});console.log('Updated name:', updated.name);
// Deleteconst success = await db.collection('users').delete(user.id);console.log('Deleted:', success); // trueDatabase
Section titled “Database”Database client class for custom configurations.
Constructor: new Database(config?: DatabaseConfig)
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
config | DatabaseConfig | No | Custom database configuration |
DatabaseConfig Type:
interface DatabaseConfig { proxyUrl?: string; // Database proxy URL appToken?: string; // JWT authentication token}Returns: Database instance
Example:
import { Database } from '@varity-labs/sdk';
// Custom database instanceconst customDb = new Database({ proxyUrl: 'https://custom-db.example.com', appToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',});
const users = await customDb.collection('users').get();Methods:
collection<T>(name: string): Collection<T>
Section titled “collection<T>(name: string): Collection<T>”Creates a typed collection reference.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Collection name |
Type Parameter:
T- TypeScript type for documents in this collection
Returns: Collection<T> instance
Example:
interface Product { name: string; price: number; stock: number;}
const products = db.collection<Product>('products');const result = await products.add({ name: 'Pro Plan', price: 99, stock: 100});// result has type: Product & Document// Access fields directly: result.name, result.price, result.idCollection<T>
Section titled “Collection<T>”Type-safe collection interface for CRUD operations.
Type Parameter:
T- Document data type
add(data: Partial<T>): Promise<T & Document>
Section titled “add(data: Partial<T>): Promise<T & Document>”Adds a new document to the collection.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
data | Partial<T> | Yes | Document data to add |
Returns: Promise<T & Document> — The full inserted document with all fields at the top level.
Example:
const users = db.collection<{ name: string; email: string }>('users');
const user = await users.add({ name: 'Bob', email: 'bob@example.com'});
// Fields are flat — access directly, NOT via .dataconsole.log(user.id); // 'doc_xyz789'console.log(user.name); // 'Bob'console.log(user.email); // 'bob@example.com'get(options?: QueryOptions): Promise<(T & Document)[]>
Section titled “get(options?: QueryOptions): Promise<(T & Document)[]>”Retrieves documents from the collection.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
options | QueryOptions | No | Query options (limit, offset, orderBy) |
QueryOptions Type:
interface QueryOptions { limit?: number; // Maximum number of documents to return offset?: number; // Number of documents to skip orderBy?: string; // Field to sort by ("field" ascending, "-field" descending)}Returns: Promise<(T & Document)[]> — Array of flat documents.
Document Type:
interface Document { id: string; created_at?: string; updated_at?: string; [key: string]: any;}Documents returned are T & Document — all user fields and system fields exist at the same level. Access doc.name, NOT doc.data.name.
Example:
// Get all documentsconst allUsers = await users.get();
// Get with limit and offsetconst page2 = await users.get({ limit: 10, offset: 10 });
// Get with ordering (ascending)const sortedUsers = await users.get({ limit: 20, orderBy: 'name'});
// Get with descending order (prefix with -)const newestFirst = await users.get({ orderBy: '-created_at'});
// Client-side filtering (since .where() is not available)const admins = allUsers.filter(user => user.role === 'admin');update(id: string, data: Partial<T>): Promise<T & Document>
Section titled “update(id: string, data: Partial<T>): Promise<T & Document>”Updates an existing document.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Document ID |
data | Partial<T> | Yes | Fields to update |
Returns: Promise<T & Document> — The updated document.
Example:
// Update single fieldconst updated = await users.update('doc_abc123', { name: 'Alice Updated'});console.log(updated.name); // 'Alice Updated'
// Update multiple fieldsconst result = await users.update('doc_abc123', { name: 'Alice Smith', email: 'alice.smith@example.com'});console.log(result.name); // 'Alice Smith'console.log(result.email); // 'alice.smith@example.com'delete(id: string): Promise<boolean>
Section titled “delete(id: string): Promise<boolean>”Deletes a document from the collection.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
id | string | Yes | Document ID |
Returns: Promise<boolean> — true on success.
Example:
const success = await users.delete('doc_abc123');console.log('Deleted:', success); // trueCredentials API
Section titled “Credentials API”Functions for managing authentication credentials. Used internally by UI-Kit.
resolveCredentials()
Section titled “resolveCredentials()”Automatically resolves credentials from environment variables with fallback to dev credentials.
Signature: resolveCredentials(appId?: string, clientId?: string): CredentialConfig
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
appId | string | No | Privy App ID (falls back to dev credentials) |
clientId | string | No | Thirdweb Client ID (falls back to dev credentials) |
CredentialConfig Type:
interface CredentialConfig { privy: { appId: string; }; thirdweb: { clientId: string; };}Returns: CredentialConfig - Fully resolved credentials
Example:
import { resolveCredentials } from '@varity-labs/sdk';
// Auto-resolve with dev credential fallbackconst creds = resolveCredentials();console.log('Privy App ID:', creds.privy.appId);console.log('Thirdweb Client ID:', creds.thirdweb.clientId);
// Override specific credentialsconst customCreds = resolveCredentials( 'custom-privy-app-id', 'custom-thirdweb-client-id');isUsingDevCredentials()
Section titled “isUsingDevCredentials()”Checks if the provided credentials match development credentials.
Signature: isUsingDevCredentials(appId?: string, clientId?: string): boolean
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
appId | string | No | Privy App ID to check |
clientId | string | No | Thirdweb Client ID to check |
Returns: boolean - true if using dev credentials
Example:
import { isUsingDevCredentials } from '@varity-labs/sdk';
if (isUsingDevCredentials()) { console.warn('Using shared dev credentials - set your own for production!');}isProductionCredentials()
Section titled “isProductionCredentials()”Checks if credentials are production-ready (opposite of isUsingDevCredentials).
Signature: isProductionCredentials(appId?: string, clientId?: string): boolean
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
appId | string | No | Privy App ID to check |
clientId | string | No | Thirdweb Client ID to check |
Returns: boolean - true if using production credentials
Example:
import { isProductionCredentials } from '@varity-labs/sdk';
const appId = process.env.NEXT_PUBLIC_PRIVY_APP_ID;const clientId = process.env.NEXT_PUBLIC_THIRDWEB_CLIENT_ID;
if (!isProductionCredentials(appId, clientId)) { throw new Error('Production credentials required');}getCredentialWarning()
Section titled “getCredentialWarning()”Returns a warning message if using dev credentials.
Signature: getCredentialWarning(environment: 'development' | 'staging' | 'production'): string | null
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
environment | string | Yes | Current environment ('development', 'staging', or 'production') |
Returns: string | null - Warning message or null if in development environment
Example:
import { getCredentialWarning } from '@varity-labs/sdk';
const warning = getCredentialWarning('production');
if (warning) { console.warn(warning); // Output: "Using shared Varity development credentials in production environment..."}logCredentialUsage()
Section titled “logCredentialUsage()”Logs credential usage information to the console (with deduplication to avoid spam).
Signature: logCredentialUsage(): void
Example:
import { logCredentialUsage } from '@varity-labs/sdk';
logCredentialUsage();validateCredentials()
Section titled “validateCredentials()”Validates that the provided credentials are well-formed.
Signature: validateCredentials(appId?: string, clientId?: string): boolean
Example:
import { validateCredentials } from '@varity-labs/sdk';
const valid = validateCredentials( process.env.NEXT_PUBLIC_PRIVY_APP_ID, process.env.NEXT_PUBLIC_THIRDWEB_CLIENT_ID);
if (!valid) { console.error('Invalid credentials format');}getUpgradeInstructions()
Section titled “getUpgradeInstructions()”Returns instructions for upgrading from dev credentials to production credentials.
Signature: getUpgradeInstructions(): string
Example:
import { getUpgradeInstructions } from '@varity-labs/sdk';
console.log(getUpgradeInstructions());VARITY_DEV_CREDENTIALS
Section titled “VARITY_DEV_CREDENTIALS”Shared development credentials for zero-config testing.
Type: object (contains privy, thirdweb, and rateLimits)
Value:
{ privy: { appId: 'cmhwbozxu004fjr0cicfz0tf8', }, thirdweb: { clientId: 'a35636133eb5ec6f30eb9f4c15fce2f3', }, rateLimits: { privy: { monthlyActiveUsers: 1000 }, thirdweb: { requestsPerSecond: 100 }, },}Example:
import { VARITY_DEV_CREDENTIALS } from '@varity-labs/sdk';
console.log('Dev Privy App ID:', VARITY_DEV_CREDENTIALS.privy.appId);// Output: cmhwbozxu004fjr0cicfz0tf8Version Information
Section titled “Version Information”VERSION
Section titled “VERSION”SDK version string.
Type: string
Value: '2.0.0-beta.2'
Example:
import { VERSION } from '@varity-labs/sdk';
console.log('SDK Version:', VERSION);// Output: SDK Version: 2.0.0-beta.2SDK_VERSION
Section titled “SDK_VERSION”Alias for VERSION (same value).
Type: string
Value: '2.0.0-beta.2'
Example:
import { SDK_VERSION } from '@varity-labs/sdk';
console.log('SDK Version:', SDK_VERSION);// Output: SDK Version: 2.0.0-beta.2Advanced APIs (Subpath Imports)
Section titled “Advanced APIs (Subpath Imports)”For advanced use cases, the SDK provides subpath imports that expose infrastructure-level utilities.
Platform Configuration (@varity-labs/sdk/chains)
Section titled “Platform Configuration (@varity-labs/sdk/chains)”Access Varity platform network configuration.
Exports:
import { varityL3, // Chain object for Varity L3 varityL3Testnet, // Chain object for Varity L3 testnet varityL3Wagmi, // Wagmi-compatible chain config formatUSDC, // Format USDC amount (6 decimals) — returns a string parseUSDC, // Parse USDC string to bigint USDC_DECIMALS, // 6 VARITY_USDC_ADDRESS, // USDC contract address on Varity L3} from '@varity-labs/sdk/chains';Chain Object (varityL3Testnet):
{ id: 33529, name: 'Varity L3 Testnet', nativeCurrency: { name: 'USDC', symbol: 'USDC', decimals: 6 // NOT 18 - Varity uses USDC! }, rpcUrls: { default: { http: ['https://rpc-varity-testnet-rroe52pwjp.t.conduit.xyz'] } }, blockExplorers: { default: { name: 'Varity Explorer', url: 'https://explorer-varity-testnet-rroe52pwjp.t.conduit.xyz' } }}Example:
import { varityL3Testnet, formatUSDC, parseUSDC, USDC_DECIMALS } from '@varity-labs/sdk/chains';
console.log('Chain ID:', varityL3Testnet.id); // 33529console.log('RPC URL:', varityL3Testnet.rpcUrls.default.http[0]);console.log('USDC Decimals:', USDC_DECIMALS); // 6
// Parse a USDC amount to its raw bigint valueconst amount = parseUSDC('99.50');console.log('Raw amount:', amount); // 99500000n
// Format a raw bigint back to a human-readable stringconst formatted = formatUSDC(99500000n);console.log('Formatted:', formatted); // "99.50" (returns a string)Infrastructure Utilities (@varity-labs/sdk/blockchain)
Section titled “Infrastructure Utilities (@varity-labs/sdk/blockchain)”Low-level infrastructure utilities (rarely needed).
Exports:
import { BlockchainService, // Contract reading/writing service NFTLicensingService, // ERC-1155 NFT licensing RevenueSplitService, // Revenue split distribution} from '@varity-labs/sdk/blockchain';Thirdweb Helpers (@varity-labs/sdk/thirdweb)
Section titled “Thirdweb Helpers (@varity-labs/sdk/thirdweb)”Utilities for working with thirdweb SDK.
Exports:
import { ThirdwebWrapper, // Contract operations wrapper createThirdwebWrapper, // Create a ThirdwebWrapper instance EngineClient, // Production transaction management createEngineClient, // Create an EngineClient instance NebulaClient, // Natural language blockchain AI createNebulaClient, // Create a NebulaClient instance StorageClient, // IPFS/Arweave storage createStorageClient, // Create a StorageClient instance BridgeClient, // Cross-chain transfers createBridgeClient, // Create a BridgeClient instance GatewayClient, // RPC infrastructure createGatewayClient, // Create a GatewayClient instance x402Client, // API monetization createx402Client, // Create an x402Client instance x402Middleware, // Express middleware for x402 varietyTestnet, // Legacy chain export getVarityChain, // Get Varity chain config isVarityChain, // Check if a chain is Varity VARITY_TESTNET_RPC, // Testnet RPC URL} from '@varity-labs/sdk/thirdweb';Example:
import { createThirdwebWrapper } from '@varity-labs/sdk/thirdweb';
const wrapper = createThirdwebWrapper({ clientId: process.env.NEXT_PUBLIC_THIRDWEB_CLIENT_ID,});Event Tracking (@varity-labs/sdk/tracking)
Section titled “Event Tracking (@varity-labs/sdk/tracking)”Analytics and event tracking utilities.
Exports:
import { trackGasUsage, // Track gas usage for billing trackTransactionGasUsage, // Track gas from a transaction waitForTransactionReceipt, // Wait for tx confirmation calculateGasInUSDC, // Convert gas cost to USDC createGasTracker, // Create a gas tracker instance} from '@varity-labs/sdk/tracking';Example:
import { createGasTracker, calculateGasInUSDC } from '@varity-labs/sdk/tracking';
const tracker = createGasTracker({ appId: 'my-app' });
// Calculate gas cost in USDCconst cost = calculateGasInUSDC(21000n, 1000000n);TypeScript Types
Section titled “TypeScript Types”All TypeScript types are re-exported from @varity-labs/types:
import type { DatabaseConfig, // Database configuration QueryOptions, // Query options for .get() Document, // Base document type (id, created_at, updated_at) CollectionResponse, // Response from collection operations CredentialConfig, // Auth credentials} from '@varity-labs/sdk';See @varity-labs/types documentation for full type definitions.
Complete Examples
Section titled “Complete Examples”E-commerce Product Catalog
Section titled “E-commerce Product Catalog”import { db } from '@varity-labs/sdk';
interface Product { name: string; description: string; price: number; stock: number; category: string;}
const products = db.collection<Product>('products');
// Add products — returns the full document (flat, with id)const laptop = await products.add({ name: 'Pro Laptop 15"', description: 'High-performance laptop', price: 1299, stock: 50, category: 'electronics'});
const keyboard = await products.add({ name: 'Mechanical Keyboard', description: 'RGB gaming keyboard', price: 149, stock: 200, category: 'electronics'});
// Get all productsconst allProducts = await products.get();console.log(`Total products: ${allProducts.length}`);
// Filter by category (client-side) — fields are flat, NOT nestedconst electronics = allProducts.filter( p => p.category === 'electronics');
// Update stock — returns the updated documentconst updated = await products.update(laptop.id, { stock: 45 // Sold 5 units});console.log(`Laptop stock: ${updated.stock}`); // 45User Authentication with Credentials
Section titled “User Authentication with Credentials”import { resolveCredentials, isUsingDevCredentials, getCredentialWarning} from '@varity-labs/sdk';
// Auto-resolve credentialsconst creds = resolveCredentials( process.env.NEXT_PUBLIC_PRIVY_APP_ID, process.env.NEXT_PUBLIC_THIRDWEB_CLIENT_ID);
// Check environmentif (isUsingDevCredentials(creds.privy.appId, creds.thirdweb.clientId)) { const warning = getCredentialWarning('production'); if (warning) console.warn(warning);
// Prevent production deployment with dev credentials if (process.env.NODE_ENV === 'production') { throw new Error('Production deployment requires custom credentials'); }}
// Use credentialsconsole.log('Privy App ID:', creds.privy.appId);console.log('Thirdweb Client ID:', creds.thirdweb.clientId);Custom Database Configuration
Section titled “Custom Database Configuration”import { Database } from '@varity-labs/sdk';
// Custom database for multi-tenant appconst createTenantDatabase = (tenantId: string) => { return new Database({ proxyUrl: `https://${tenantId}.db.varity.app`, appToken: process.env[`JWT_${tenantId.toUpperCase()}`], });};
const acmeDb = createTenantDatabase('acme');const users = await acmeDb.collection('users').get();Known Limitations
Section titled “Known Limitations”Related Resources
Section titled “Related Resources”- SDK Overview - High-level SDK guide
- Database Quickstart - Build your first database app
- UI-Kit API Reference - React components
- TypeScript Types - Type definitions