Skip to content

SDK Reference

The @assegailabs/sdk package provides typed access to blockchain operations, AI models, and logging from within Assegai agents.

Terminal window
npm install @assegailabs/sdk
import { AssegaiSDK } from '@assegailabs/sdk';
// SDK automatically reads credentials from environment
const sdk = new AssegaiSDK();
async function main() {
await sdk.info('Agent starting...');
const address = await sdk.getWalletAddress('eip155:1');
const balance = await sdk.getBalance('eip155:1', address);
await sdk.success(`Balance: ${BigInt(balance)} wei`);
}
main().catch(console.error);
const sdk = new AssegaiSDK(config?: AssegaiConfig);

Configuration options (all optional, defaults to environment variables):

OptionTypeDefaultDescription
apiProxyUrlstringASSEGAI_API_PROXY or http://host.docker.internal:8765API proxy URL
agentIdstringASSEGAI_AGENT_IDAgent identifier
agentTokenstringASSEGAI_AGENT_TOKENAuthentication token
timeoutnumber30000Request timeout in milliseconds
debugbooleanfalseEnable debug logging

Get the connected wallet address for a chain.

const address = await sdk.getWalletAddress('eip155:1');
// Returns: "0x..."

Parameters:

  • chain: CAIP-2 chain identifier (e.g., 'eip155:1' for Ethereum mainnet)

Returns: Promise<Address> - The wallet address (0x-prefixed)

Execute a JSON-RPC query on a chain.

const blockNumber = await sdk.queryChain('eip155:1', 'eth_blockNumber', []);
const code = await sdk.queryChain('eip155:1', 'eth_getCode', [address, 'latest']);

Parameters:

  • chain: CAIP-2 chain identifier
  • method: JSON-RPC method name
  • params: Array of method parameters (default: [])

Returns: Promise<T> - The RPC result

Get the ETH balance of an address.

const balanceHex = await sdk.getBalance('eip155:1', '0x...');
const balanceWei = BigInt(balanceHex);

Returns: Promise<string> - Balance in wei as hex string

Get the transaction count (nonce) for an address.

const nonce = await sdk.getTransactionCount('eip155:1', address);

Returns: Promise<string> - Transaction count as hex string

Get the current gas price.

const gasPrice = await sdk.getGasPrice('eip155:1');

Returns: Promise<string> - Gas price in wei as hex string

Get the current block number.

const blockNumber = await sdk.getBlockNumber('eip155:1');

Returns: Promise<string> - Block number as hex string

Check if an address is a contract.

const isContract = await sdk.isContract('eip155:1', address);

Returns: Promise<boolean> - True if address has code deployed

Request a transaction. This will pause execution until the user approves or rejects.

try {
const txHash = await sdk.requestTransaction({
chain: 'eip155:1',
to: '0x742d35Cc6634C0532925a3b844Bc9e7595f...',
value: '1000000000000000000', // 1 ETH in wei
data: '0x', // optional, default: '0x'
gasLimit: '21000' // optional, default: '21000'
});
await sdk.success(`Transaction sent: ${txHash}`);
} catch (error) {
if (error instanceof TransactionRejectedError) {
await sdk.warn('User rejected the transaction');
} else if (error instanceof InsufficientAllowanceError) {
await sdk.error('Spending allowance not configured');
}
}

Parameters:

FieldTypeRequiredDescription
chainstringYesCAIP-2 chain identifier
toAddressYesRecipient address (0x-prefixed)
valuestringYesValue in wei (as string)
dataHexDataNoTransaction data (default: '0x')
gasLimitstringNoGas limit (default: '21000')

Returns: Promise<TransactionHash> - The transaction hash

Throws:

  • TransactionRejectedError - User clicked “Reject”
  • TransactionTimeoutError - User didn’t respond within 5 minutes
  • InsufficientAllowanceError - Spending allowance not configured

Call the Anthropic Claude API.

const response = await sdk.callClaude({
model: 'claude-sonnet-4-5-20250929',
messages: [
{ role: 'user', content: 'Analyze this transaction...' }
],
system: 'You are a blockchain analyst.',
max_tokens: 4096,
});
// Extract text from response
const text = response.content
.filter(block => block.type === 'text')
.map(block => block.text)
.join('');

Options:

FieldTypeRequiredDescription
modelClaudeModelYesModel identifier
messagesMessage[]YesConversation messages
max_tokensnumberNoMax tokens to generate (default: 4096)
systemstringNoSystem prompt
toolsTool[]NoTools available to the model
temperaturenumberNoTemperature (0-1)
stop_sequencesstring[]NoStop sequences

Supported Claude Models:

  • claude-opus-4-5-20251124 - Most capable, complex reasoning
  • claude-sonnet-4-5-20250929 - Balanced performance and speed
  • claude-haiku-4-5-20251015 - Fast, cost-efficient
  • claude-3-5-sonnet-20241022 - Previous generation
  • claude-3-5-haiku-20241022 - Previous generation

Call the OpenAI API.

const response = await sdk.callOpenAI({
model: 'gpt-4o',
messages: [
{ role: 'system', content: 'You are a DeFi assistant.' },
{ role: 'user', content: 'Hello!' }
],
max_tokens: 1024,
});
const text = response.choices[0].message.content;

Options:

FieldTypeRequiredDescription
modelOpenAIModelYesModel identifier
messagesarrayYesConversation messages
max_tokensnumberNoMax tokens to generate
temperaturenumberNoTemperature (0-2)
toolsarrayNoFunction tools

Supported OpenAI Models:

  • gpt-5.2 - Latest flagship model
  • gpt-5.1 - Previous flagship
  • gpt-5 - GPT-5 base
  • gpt-4.1 - Optimized for coding
  • gpt-4.1-mini - Fast, efficient
  • gpt-4o - Multimodal flagship
  • gpt-4o-mini - Fast multimodal
  • o3 - Reasoning model
  • o4-mini - Fast reasoning

Send a log message to the Assegai UI.

await sdk.log('info', 'Processing started', { step: 1 });

Parameters:

  • level: 'debug' | 'info' | 'warn' | 'error' | 'success'
  • message: Log message string
  • data: Optional structured data object
await sdk.debug('Debug message', { data }); // Only shown when debug=true
await sdk.info('Info message', { data });
await sdk.warn('Warning message', { data });
await sdk.error('Error message', { data });
await sdk.success('Success message', { data }); // Shown in green

Get the agent ID.

const agentId = sdk.getAgentId();

Check if the SDK is properly configured.

if (!sdk.isConfigured()) {
throw new Error('SDK not configured');
}

Check if the API proxy is reachable.

const healthy = await sdk.healthCheck();

The SDK throws typed errors for different failure scenarios:

import {
AssegaiError,
AuthenticationError,
ForbiddenError,
RateLimitError,
TimeoutError,
NetworkError,
ValidationError,
TransactionRejectedError,
TransactionTimeoutError,
InsufficientAllowanceError,
RpcError,
ApiError,
ErrorCode,
} from '@assegailabs/sdk';
try {
await sdk.requestTransaction({ ... });
} catch (error) {
if (error instanceof TransactionRejectedError) {
// User clicked "Reject" in the UI
} else if (error instanceof TransactionTimeoutError) {
// User didn't respond within 5 minutes
} else if (error instanceof InsufficientAllowanceError) {
// Spending allowance not configured
} else if (error instanceof RateLimitError) {
// Too many requests
console.log('Retry after:', error.retryAfter);
} else if (error instanceof RpcError) {
// Blockchain RPC error
console.log('RPC code:', error.rpcCode);
} else if (error instanceof AssegaiError) {
// Other SDK error
console.log(error.code, error.message, error.details);
}
}
CodeDescription
UNAUTHORIZEDAuthentication failed
FORBIDDENAccess forbidden
NOT_FOUNDResource not found
RATE_LIMITEDRate limit exceeded
TIMEOUTRequest timed out
NETWORK_ERRORNetwork error
VALIDATION_ERRORValidation failed
TRANSACTION_REJECTEDUser rejected transaction
TRANSACTION_TIMEOUTTransaction approval timed out
INSUFFICIENT_ALLOWANCESpending allowance not configured
RPC_ERRORBlockchain RPC error
API_ERRORAI API error

The SDK exports comprehensive TypeScript types:

import type {
// Configuration
AssegaiConfig,
// Chain types
ChainId, // CAIP-2 identifier, e.g., "eip155:1"
Address, // 0x-prefixed address
TransactionHash, // 0x-prefixed tx hash
HexData, // 0x-prefixed hex data
// Transaction types
TransactionRequest,
TransactionResult,
// RPC types
RpcMethod,
ChainQueryParams,
// AI types
ClaudeModel,
ClaudeOptions,
ClaudeResponse,
OpenAIModel,
OpenAIOptions,
OpenAIResponse,
Message,
MessageRole,
Tool,
ContentBlock,
TextContent,
ImageContent,
ToolUseContent,
ToolResultContent,
// Logging
LogLevel,
LogEntry,
// Errors
AssegaiErrorInfo,
} from '@assegailabs/sdk';
export { ErrorCode } from '@assegailabs/sdk';

These environment variables are set automatically by Assegai when running agents:

VariableDescription
ASSEGAI_AGENT_IDUnique agent identifier
ASSEGAI_AGENT_TOKENAuthentication token
ASSEGAI_API_PROXYAPI proxy URL (default: http://host.docker.internal:8765)