API Reference
Complete reference for the @7n7d/sdk package.
Installation
npm install @7n7d/sdk
SevenNSevenD (Main Client)
The main entry point. Creates API and on-chain sub-clients.
import { SevenNSevenD } from '@7n7d/sdk';
const client = new SevenNSevenD({
apiKey: 'your-api-key',
network: 'testnet', // 'testnet' | 'mainnet'
privateKey: '0x...', // Required for on-chain transactions
});
SevenNSevenDConfig
| Property | Type | Required | Description |
|---|---|---|---|
apiKey | string | Yes | API key for the 7N7D REST API |
apiUrl | string | No | Override the default API URL |
rpcUrl | string | No | Override the default RPC endpoint |
privateKey | string | No | Private key for signing on-chain transactions |
network | 'testnet' | 'mainnet' | No | Network selection (default: 'testnet') |
Sub-Clients
| Property | Type | Description |
|---|---|---|
api | ApiClient | REST API client (status, positions, chat) |
vault | VaultClient | Trading vault on-chain operations |
staking | StakingClient | Token staking on-chain operations |
token | TokenClient | 7N7D token on-chain operations |
ApiClient
REST API client for querying the 7N7D backend. Accessed via client.api.
Methods
api.status()
Get vault and agent status.
const { data } = await client.api.status();
// data: { vault: { status, network }, agent: { status, positions }, trading?: { venue, network, dexes }, timestamp }
Returns: Promise<ApiResponse<StatusData>>
api.positions(filter?)
List open trading positions. Each position carries additive market identity
(market_id, network, dex, asset_class, display_ticker). The optional
filter is applied client-side on that identity.
const { data } = await client.api.positions();
// data: { positions: Position[], timestamp }
const stocks = await client.api.positions({ assetClass: 'EQUITY' });
const tesla = await client.api.positions({ marketId: 'hl-testnet:xyz:TSLA' });
| Parameter | Type | Required | Description |
|---|---|---|---|
filter.assetClass | AssetClass | string | No | CRYPTO, EQUITY, COMMODITY, PREDICTION |
filter.marketId | string | No | Canonical id, e.g. hl-testnet:xyz:TSLA |
Returns: Promise<ApiResponse<PositionsData>>
api.markets(filter?)
Every market on the configured Hyperliquid network (native DEX plus enabled
HIP-3 builder DEXes) with its activation state. Display names are never
execution identifiers — use marketId / coin.
const catalog = await client.api.markets();
// { network: 'TESTNET', dexes: ['', 'xyz'], markets: Market[], count, timestamp }
const activeStocks = await client.api.markets({ assetClass: 'EQUITY', activeOnly: true });
Returns: Promise<MarketsData>
api.market(marketId)
One market by canonical id.
const tsla = await client.api.market('hl-testnet:xyz:TSLA');
// { marketId, network, venue, dex: 'xyz', coin: 'xyz:TSLA', displayTicker: 'TSLA', assetClass: 'EQUITY', activation, maxLeverage, reference, ... }
Returns: Promise<Market>
api.marketState(marketId)
Venue session, underlying session, entry status and data freshness for one market — the facts behind “entries paused” on the dashboard.
const state = await client.api.marketState('hl-testnet:xyz:TSLA');
// { marketId, asOf, venueSession, referenceSession, entry: { status, reason }, quote, freshness }
Returns: Promise<MarketState>
api.accountSnapshot()
Mode-aware account snapshot from the trading agent: account mode, per-DEX
state, capital reservations and pending transfers. null fields mean
unknown, never zero.
const { data } = await client.api.accountSnapshot();
Returns: Promise<ApiResponse<AccountSnapshotData>>
api.balance(address)
Get balance information for an address.
const { data } = await client.api.balance('0x...');
// data: { address, network, contracts: { tradingVault, token, usdc }, timestamp }
Returns: Promise<ApiResponse<BalanceData>>
api.chat(message, walletAddress?, conversationHistory?)
Send a message to the AI agent.
const { data } = await client.api.chat('What is the current TVL?');
// data: { response, intent, action, timestamp }
| Parameter | Type | Required | Description |
|---|---|---|---|
message | string | Yes | User message |
walletAddress | string | No | Wallet for context |
conversationHistory | Array<{ role: string; content: string }> | No | Previous messages |
Returns: Promise<ApiResponse<ChatData>>
api.contracts()
Get deployed contract addresses and network info.
const { data } = await client.api.contracts();
// data: { network, chainId, contracts: { tradingVault, token, usdc, profitDistributor, governanceDao }, rpcUrl, explorerUrl, timestamp }
Returns: Promise<ApiResponse<ContractsData>>
api.health()
Health check endpoint.
const health = await client.api.health();
// { ok: true, service: '7n7d-api', version: '...', timestamp: '...' }
Returns: Promise<HealthData>
VaultClient
On-chain trading vault operations. Accessed via client.vault.
Methods that write to the blockchain (deposit, withdraw) require a privateKey in the client config.
Methods
vault.deposit(amount)
Deposit USDC into the trading vault. Automatically approves USDC spending first.
const result = await client.vault.deposit('1000'); // 1000 USDC
// { txHash: '0x...', explorerLink: 'https://...' }
| Parameter | Type | Description |
|---|---|---|
amount | string | USDC amount in human-readable units |
Returns: Promise<{ txHash: string; explorerLink: string }>
vault.withdraw(shares)
Request withdrawal of vault shares.
const result = await client.vault.withdraw('100'); // 100 shares
// { txHash: '0x...', explorerLink: 'https://...' }
| Parameter | Type | Description |
|---|---|---|
shares | string | Share amount in human-readable units |
Returns: Promise<{ txHash: string; explorerLink: string }>
vault.balance(address)
Get vault share balance for an address.
const shares = await client.vault.balance('0x...');
// '1234.567890123456789'
Returns: Promise<string> — Human-readable share balance.
vault.sharePrice()
Get current share price (USDC per 1 share).
const price = await client.vault.sharePrice();
// '1.023456'
Returns: Promise<string> — Human-readable USDC value per share.
vault.totalAssets()
Get total vault TVL in USDC.
const tvl = await client.vault.totalAssets();
// '50000.000000'
Returns: Promise<string> — Human-readable USDC total.
vault.withdrawalRequest(address)
Check withdrawal request status for an address.
const req = await client.vault.withdrawalRequest('0x...');
// { shares: 100n, requestTime: 1711900000n, processed: false }
Returns: Promise<WithdrawalRequest>
interface WithdrawalRequest {
shares: bigint;
requestTime: bigint;
processed: boolean;
}
StakingClient
Token staking operations via the ProfitDistributor contract. Accessed via client.staking.
Methods that write to the blockchain (stake, unstake, claim) require a privateKey in the client config.
Methods
staking.stake(amount)
Stake 7N7D tokens. Automatically approves token spending first.
const result = await client.staking.stake('5000'); // 5000 7N7D
// { txHash: '0x...', explorerLink: 'https://...' }
Returns: Promise<{ txHash: string; explorerLink: string }>
staking.unstake(amount)
Unstake 7N7D tokens.
const result = await client.staking.unstake('5000');
// { txHash: '0x...', explorerLink: 'https://...' }
Returns: Promise<{ txHash: string; explorerLink: string }>
staking.earned(address)
Get pending USDC rewards for an address.
const rewards = await client.staking.earned('0x...');
// '42.500000'
Returns: Promise<string> — Human-readable USDC rewards.
staking.claim()
Claim pending USDC staking rewards.
const result = await client.staking.claim();
// { txHash: '0x...', explorerLink: 'https://...' }
Returns: Promise<{ txHash: string; explorerLink: string }>
staking.balance(address)
Get staked 7N7D token balance for an address.
const staked = await client.staking.balance('0x...');
// '5000.000000000000000000'
Returns: Promise<string> — Human-readable staked token balance.
TokenClient
7N7D token operations. Accessed via client.token.
Methods
token.balance(address)
Get 7N7D token balance for an address.
const balance = await client.token.balance('0x...');
// '10000.000000000000000000'
Returns: Promise<string> — Human-readable token balance.
token.approve(spender, amount)
Approve a spender to use 7N7D tokens.
const result = await client.token.approve('0xSpender...', '5000');
// { txHash: '0x...', explorerLink: 'https://...' }
| Parameter | Type | Description |
|---|---|---|
spender | string | Address to approve |
amount | string | Token amount in human-readable units |
Returns: Promise<{ txHash: string; explorerLink: string }>
DelegationClient
ERC-7710 delegation encoding, on-chain redemption, and status reads.
Imported directly from @7n7d/sdk and constructed with a
DelegationClientConfig.
Methods
delegationClient.redeemDelegation(delegation, execution, walletClient)
Redeem a signed delegation on-chain by sending
DelegationManager.redeemDelegations calldata from the agent's own wallet.
The delegator can be offline and never pays gas.
const txHash = await delegationClient.redeemDelegation(
delegation,
{ target: usdcAddress, callData: transferCalldata },
walletClient,
);
| Parameter | Type | Description |
|---|---|---|
delegation | Delegation | The signed delegation to redeem |
execution | RedeemExecution | The scoped action: { target, callData, value? } |
walletClient | RedemptionWalletClient | Any client with sendTransaction({ to, data }) |
Returns: Promise<Hex> — the redemption transaction hash.
delegationClient.encodeRedeemDelegation(delegation, execution)
Encode the redeemDelegations calldata without submitting it — for callers
that wrap the action in a UserOperation instead of a direct transaction.
Returns: { to: Address; data: Hex } — the DelegationManager call target and calldata.
delegationClient.getStatus(delegation, publicClient, options?)
Read the live on-chain status of a delegation. Checks the DelegationManager's
disabled map (revocation), the timestamp caveat's after/before window, and
the ERC20 transfer amount enforcer's spent map.
const status = await delegationClient.getStatus(delegation, publicClient);
// "active" | "not_yet_active" | "expired" | "revoked" | "redeemed"
| Parameter | Type | Description |
|---|---|---|
delegation | Delegation | The delegation to check |
publicClient | Client | viem public client for the delegation's chain |
options.now | bigint (optional) | Current time in unix seconds (defaults to clock) |
Returns: Promise<DelegationStatus>
delegationClient.getRemainingAllowance(delegation, publicClient)
Read the remaining USDC the delegation still allows: maxAmount from the ERC20
transfer amount caveat minus the amount already spent on-chain.
Returns: Promise<bigint> — remaining allowance in base units (0 once fully spent).
Exported Types
All types are importable from @7n7d/sdk:
import {
type SevenNSevenDConfig,
type ApiResponse,
type StatusData,
type TradingEnvironment,
type Position,
type PositionFilter,
type PositionsData,
type AssetClass,
type HlNetwork,
type MarketIdentity,
type MarketReference,
type MarketActivation,
type Market,
type MarketFilter,
type MarketsData,
type MarketQuote,
type MarketState,
type AccountSnapshotData,
type BalanceData,
type ChatData,
type ContractsData,
type HealthData,
type WithdrawalRequest,
// Delegation (ERC-7710)
DelegationClient,
type DelegationClientConfig,
type Caveat,
type Delegation,
type DelegationResult,
type DelegationStatus,
type RedeemExecution,
type RedemptionWalletClient,
type VaultDepositDelegationConfig,
CAVEAT_ENFORCERS,
DELEGATION_EIP712_DOMAIN,
ROOT_AUTHORITY,
// Agent-to-agent delegation + handshake
AgentDelegationManager,
type AgentDelegationManagerConfig,
type AcceptDelegationResult,
type DelegationAcceptancePolicy,
type DelegationRecord,
DELEGATION_TYPED_DATA_TYPES,
delegationId,
AgentHandshake,
HANDSHAKE_PROTOCOL_VERSION,
serializeHandshakeMessage,
parseHandshakeMessage,
type AgentHandshakeConfig,
type HandshakeAck,
type HandshakeOffer,
type HandshakeOfferResult,
type HandshakeRequest,
type HandshakeSession,
type HandshakeSessionState,
// Errors
SdkError,
ApiError,
ContractError,
ConfigError,
} from '@7n7d/sdk';
ApiResponse<T>
interface ApiResponse<T = unknown> {
ok: boolean;
data: T;
}
Error Classes
All errors extend SdkError:
| Class | Code | Description |
|---|---|---|
SdkError | (varies) | Base error class |
ApiError | API_ERROR | REST API request failure (includes HTTP status) |
ContractError | CONTRACT_ERROR | On-chain transaction failure |
ConfigError | CONFIG_ERROR | Invalid client configuration |
try {
await client.vault.deposit('1000');
} catch (error) {
if (error instanceof ApiError) {
console.log(error.status); // HTTP status code
}
if (error instanceof SdkError) {
console.log(error.code); // Error code string
console.log(error.message); // Human-readable message
console.log(error.cause); // Underlying error (if any)
}
}
Exported Constants
import { NETWORKS, DECIMALS, API_PATHS } from '@7n7d/sdk';
NETWORKS
Pre-configured network settings for testnet and mainnet.
const NETWORKS: {
testnet: NetworkConfig;
mainnet: NetworkConfig;
};
interface NetworkConfig {
chainId: number; // e.g. 11155111 (Sepolia)
name: string; // e.g. "Sepolia"
rpcUrl: string; // JSON-RPC endpoint
explorerUrl: string; // Block explorer base URL
apiUrl: string; // 7N7D API base URL
contracts: {
token: string; // 7N7D token address
usdc: string; // USDC token address
profitDistributor: string; // Staking rewards contract
tradingVault: string; // Trading vault contract
governanceDao: string; // Governance DAO contract
};
}
Usage:
import { NETWORKS } from '@7n7d/sdk';
// Get testnet vault address
const vaultAddress = NETWORKS.testnet.contracts.tradingVault;
// Get RPC URL for direct provider setup
const rpcUrl = NETWORKS.testnet.rpcUrl;
You typically don't need to access NETWORKS directly — the SevenNSevenD client resolves network config automatically from the network option.
DECIMALS
Token decimal constants used for parsing and formatting on-chain values.
| Key | Value | Description |
|---|---|---|
USDC | 6 | USDC decimal places |
TOKEN | 18 | 7N7D token decimals |
SHARES | 18 | Vault share decimals |
Usage:
import { DECIMALS } from '@7n7d/sdk';
import { parseUnits, formatUnits } from 'viem';
// Parse 1000 USDC to on-chain units
const amount = parseUnits('1000', DECIMALS.USDC); // 1000000000n
// Format vault shares from on-chain units
const shares = formatUnits(rawShares, DECIMALS.SHARES);
API_PATHS
REST API endpoint paths used internally by ApiClient. Exported for custom integrations.
| Key | Path | Description |
|---|---|---|
status | /api/v1/agent/status | Vault and agent status |
positions | /api/v1/agent/positions | Open trading positions |
balance | /api/v1/agent/balance | Address balance information |
chat | /api/v1/agent/chat | AI agent chat endpoint |
contracts | /api/v1/agent/contracts | Deployed contract addresses |
health | /api/v1/agent/health | Health check |
accountSnapshot | /api/v1/agent/account/snapshot | Mode-aware account snapshot |
markets | /api/markets | Market catalog (append /:marketId, /:marketId/state) |
Usage:
import { API_PATHS, NETWORKS } from '@7n7d/sdk';
// Build a custom request URL
const url = `${NETWORKS.testnet.apiUrl}${API_PATHS.status}`;
const response = await fetch(url);
Exported ABIs
Contract ABIs for direct use with ethers.js, viem, or any EVM library. Use these when you need low-level contract access beyond what the SDK clients provide.
import {
TRADING_VAULT_ABI,
USDC_ABI,
TOKEN_ABI,
PROFIT_DISTRIBUTOR_ABI,
} from '@7n7d/sdk';
| ABI | Contract | Description |
|---|---|---|
TRADING_VAULT_ABI | TradingVault | Trading vault — deposit USDC, withdraw shares, view TVL |
USDC_ABI | USDC (ERC-20) | Standard ERC-20 for USDC approve/transfer operations |
TOKEN_ABI | 7N7D Token (ERC-20) | 7N7D governance token — transfer, approve, burn |
PROFIT_DISTRIBUTOR_ABI | ProfitDistributor | Staking rewards — stake, unstake, claim USDC rewards |
Usage with viem:
import { createPublicClient, http } from 'viem';
import { sepolia } from 'viem/chains';
import { TRADING_VAULT_ABI, NETWORKS } from '@7n7d/sdk';
const client = createPublicClient({ chain: sepolia, transport: http() });
const tvl = await client.readContract({
address: NETWORKS.testnet.contracts.tradingVault as `0x${string}`,
abi: TRADING_VAULT_ABI,
functionName: 'totalAssets',
});
Need Help?
- Getting Started — Installation and setup
- Deposit Guide — Deposit examples
- Withdraw Guide — Withdrawal examples
- FAQ — Common questions