Skip to content

SDK API Reference

Varity Team Core Contributors Updated March 2026

Complete API reference for all exports from @varity-labs/sdk. All signatures, parameters, return types, and examples verified against source code.

The database API provides zero-config access to Varity’s distributed database.

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_URL or VITE_VARITY_DB_PROXY_URL or REACT_APP_VARITY_DB_PROXY_URL (proxy URL)
  • NEXT_PUBLIC_VARITY_APP_TOKEN or VITE_VARITY_APP_TOKEN or REACT_APP_VARITY_APP_TOKEN (authentication)
  • Fallback: Development credentials (automatic)

Example:

import { db } from '@varity-labs/sdk';
// Add a document
const user = await db.collection('users').add({
name: 'Alice',
email: 'alice@example.com'
});
console.log('Created:', user.id);
// Output: Created: doc_abc123
console.log('Name:', user.name);
// Output: Name: Alice
// Get all documents
const users = await db.collection('users').get();
console.log('Users:', users.length);
// Update
const updated = await db.collection('users').update(user.id, {
name: 'Alice Smith'
});
console.log('Updated name:', updated.name);
// Delete
const success = await db.collection('users').delete(user.id);
console.log('Deleted:', success); // true

Database client class for custom configurations.

Constructor: new Database(config?: DatabaseConfig)

Parameters:

ParameterTypeRequiredDescription
configDatabaseConfigNoCustom 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 instance
const 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:

ParameterTypeRequiredDescription
namestringYesCollection 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.id

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:

ParameterTypeRequiredDescription
dataPartial<T>YesDocument 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 .data
console.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:

ParameterTypeRequiredDescription
optionsQueryOptionsNoQuery 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 documents
const allUsers = await users.get();
// Get with limit and offset
const 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:

ParameterTypeRequiredDescription
idstringYesDocument ID
dataPartial<T>YesFields to update

Returns: Promise<T & Document> — The updated document.

Example:

// Update single field
const updated = await users.update('doc_abc123', {
name: 'Alice Updated'
});
console.log(updated.name); // 'Alice Updated'
// Update multiple fields
const 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'

Deletes a document from the collection.

Parameters:

ParameterTypeRequiredDescription
idstringYesDocument ID

Returns: Promise<boolean>true on success.

Example:

const success = await users.delete('doc_abc123');
console.log('Deleted:', success); // true

Functions for managing authentication credentials. Used internally by UI-Kit.

Automatically resolves credentials from environment variables with fallback to dev credentials.

Signature: resolveCredentials(appId?: string, clientId?: string): CredentialConfig

Parameters:

ParameterTypeRequiredDescription
appIdstringNoPrivy App ID (falls back to dev credentials)
clientIdstringNoThirdweb 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 fallback
const creds = resolveCredentials();
console.log('Privy App ID:', creds.privy.appId);
console.log('Thirdweb Client ID:', creds.thirdweb.clientId);
// Override specific credentials
const customCreds = resolveCredentials(
'custom-privy-app-id',
'custom-thirdweb-client-id'
);

Checks if the provided credentials match development credentials.

Signature: isUsingDevCredentials(appId?: string, clientId?: string): boolean

Parameters:

ParameterTypeRequiredDescription
appIdstringNoPrivy App ID to check
clientIdstringNoThirdweb 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!');
}

Checks if credentials are production-ready (opposite of isUsingDevCredentials).

Signature: isProductionCredentials(appId?: string, clientId?: string): boolean

Parameters:

ParameterTypeRequiredDescription
appIdstringNoPrivy App ID to check
clientIdstringNoThirdweb 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');
}

Returns a warning message if using dev credentials.

Signature: getCredentialWarning(environment: 'development' | 'staging' | 'production'): string | null

Parameters:

ParameterTypeRequiredDescription
environmentstringYesCurrent 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..."
}

Logs credential usage information to the console (with deduplication to avoid spam).

Signature: logCredentialUsage(): void

Example:

import { logCredentialUsage } from '@varity-labs/sdk';
logCredentialUsage();

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');
}

Returns instructions for upgrading from dev credentials to production credentials.

Signature: getUpgradeInstructions(): string

Example:

import { getUpgradeInstructions } from '@varity-labs/sdk';
console.log(getUpgradeInstructions());

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: cmhwbozxu004fjr0cicfz0tf8

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.2

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.2

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); // 33529
console.log('RPC URL:', varityL3Testnet.rpcUrls.default.http[0]);
console.log('USDC Decimals:', USDC_DECIMALS); // 6
// Parse a USDC amount to its raw bigint value
const amount = parseUSDC('99.50');
console.log('Raw amount:', amount); // 99500000n
// Format a raw bigint back to a human-readable string
const 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 USDC
const cost = calculateGasInUSDC(21000n, 1000000n);

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.


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 products
const allProducts = await products.get();
console.log(`Total products: ${allProducts.length}`);
// Filter by category (client-side) — fields are flat, NOT nested
const electronics = allProducts.filter(
p => p.category === 'electronics'
);
// Update stock — returns the updated document
const updated = await products.update(laptop.id, {
stock: 45 // Sold 5 units
});
console.log(`Laptop stock: ${updated.stock}`); // 45

import {
resolveCredentials,
isUsingDevCredentials,
getCredentialWarning
} from '@varity-labs/sdk';
// Auto-resolve credentials
const creds = resolveCredentials(
process.env.NEXT_PUBLIC_PRIVY_APP_ID,
process.env.NEXT_PUBLIC_THIRDWEB_CLIENT_ID
);
// Check environment
if (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 credentials
console.log('Privy App ID:', creds.privy.appId);
console.log('Thirdweb Client ID:', creds.thirdweb.clientId);

import { Database } from '@varity-labs/sdk';
// Custom database for multi-tenant app
const 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();