Skip to main content

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​

PropertyTypeRequiredDescription
apiKeystringYesAPI key for the 7N7D REST API
apiUrlstringNoOverride the default API URL
rpcUrlstringNoOverride the default RPC endpoint
privateKeystringNoPrivate key for signing on-chain transactions
network'testnet' | 'mainnet'NoNetwork selection (default: 'testnet')

Sub-Clients​

PropertyTypeDescription
apiApiClientREST API client (status, positions, chat)
vaultVaultClientTrading vault on-chain operations
stakingStakingClientToken staking on-chain operations
tokenTokenClient7N7D 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' });
ParameterTypeRequiredDescription
filter.assetClassAssetClass | stringNoCRYPTO, EQUITY, COMMODITY, PREDICTION
filter.marketIdstringNoCanonical 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 }
ParameterTypeRequiredDescription
messagestringYesUser message
walletAddressstringNoWallet for context
conversationHistoryArray<{ role: string; content: string }>NoPrevious 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.

note

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://...' }
ParameterTypeDescription
amountstringUSDC 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://...' }
ParameterTypeDescription
sharesstringShare 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.

note

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://...' }
ParameterTypeDescription
spenderstringAddress to approve
amountstringToken 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,
);
ParameterTypeDescription
delegationDelegationThe signed delegation to redeem
executionRedeemExecutionThe scoped action: { target, callData, value? }
walletClientRedemptionWalletClientAny 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"
ParameterTypeDescription
delegationDelegationThe delegation to check
publicClientClientviem public client for the delegation's chain
options.nowbigint (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:

ClassCodeDescription
SdkError(varies)Base error class
ApiErrorAPI_ERRORREST API request failure (includes HTTP status)
ContractErrorCONTRACT_ERROROn-chain transaction failure
ConfigErrorCONFIG_ERRORInvalid 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;
tip

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.

KeyValueDescription
USDC6USDC decimal places
TOKEN187N7D token decimals
SHARES18Vault 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.

KeyPathDescription
status/api/v1/agent/statusVault and agent status
positions/api/v1/agent/positionsOpen trading positions
balance/api/v1/agent/balanceAddress balance information
chat/api/v1/agent/chatAI agent chat endpoint
contracts/api/v1/agent/contractsDeployed contract addresses
health/api/v1/agent/healthHealth check
accountSnapshot/api/v1/agent/account/snapshotMode-aware account snapshot
markets/api/marketsMarket 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';
ABIContractDescription
TRADING_VAULT_ABITradingVaultTrading vault — deposit USDC, withdraw shares, view TVL
USDC_ABIUSDC (ERC-20)Standard ERC-20 for USDC approve/transfer operations
TOKEN_ABI7N7D Token (ERC-20)7N7D governance token — transfer, approve, burn
PROFIT_DISTRIBUTOR_ABIProfitDistributorStaking 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?​