SDK API Reference
The web3agent package exports a programmatic API for use in TypeScript and JavaScript projects. Import from "web3agent" for most functions. A few specialized entry points exist for runtime creation and protocol-specific clients.
npm install web3agent
# or
pnpm add web3agent
Entry Points
| Import Path | Contents |
|---|---|
"web3agent" | All SDK functions, types, schemas, config helpers |
"web3agent/runtime" | createRuntime(), Web3AgentRuntime type |
"web3agent/mcp" | ProxyServer, startServer() |
"web3agent/agdp" | aGDP API client |
"web3agent/x402" | X-402 payment client |
Chains
import { getChain, listSupportedChains, findChainByName } from "web3agent";
getChain(chainId: number)
Returns chain metadata for a given chain ID, or undefined if not supported.
const chain = getChain(8453);
// { id: 8453, name: "Base", nativeCurrency: { symbol: "ETH", decimals: 18 }, ... }
listSupportedChains()
Returns an array of all 17 supported chain objects.
const chains = listSupportedChains();
// [{ id: 1, name: "Ethereum" }, { id: 8453, name: "Base" }, ...]
findChainByName(name: string)
Case-insensitive name lookup. Returns undefined if not found.
const chain = findChainByName("arbitrum");
// { id: 42161, name: "Arbitrum One", ... }
Tokens
import { resolveToken, resolveCanonicalToken, resolveCanonicalTokenSync, listChainTokens } from "web3agent";
resolveToken(params, options?)
Resolves a token symbol or address to full metadata.
const token = await resolveToken({ symbol: "USDC", chainId: 8453 });
// { address: "0x833589...", symbol: "USDC", decimals: 6, name: "USD Coin" }
resolveCanonicalToken(params, options?)
Like resolveToken, but returns the canonical (most widely recognized) version of a token when multiple exist.
resolveCanonicalTokenSync(params)
Synchronous version of resolveCanonicalToken. Uses the local token registry only, no network calls.
listChainTokens(params, options?)
Returns all known tokens for a chain.
const tokens = await listChainTokens({ chainId: 8453 });
// [{ address: "0x...", symbol: "USDC", decimals: 6 }, ...]
Swaps
import { getSwapQuote, executeSameChainSwap, getSwapHistory } from "web3agent";
getSwapQuote(params, options?)
Fetches a swap quote from Orbs Liquidity Hub.
const quote = await getSwapQuote({
fromToken: "0x833589...", // USDC on Base
toToken: "0x4200000...", // WETH on Base
fromAmount: "100000000", // 100 USDC (6 decimals)
chainId: 8453,
});
executeSameChainSwap(params, options?)
Executes a swap using the active server-side wallet. Requires PRIVATE_KEY or MNEMONIC to be set.
const result = await executeSameChainSwap({
fromToken: "0x833589...",
toToken: "0x4200000...",
fromAmount: "100000000",
chainId: 8453,
});
// { txHash: "0x...", status: "success", fromAmountUsd: 100, toAmountUsd: 99.8 }
getSwapHistory(params, options?)
Returns historical swap records for an address.
const history = await getSwapHistory({ address: "0x...", chainId: 8453 });
Intents
Intent functions prepare signed data structures for browser-wallet signing flows. They do not execute transactions themselves.
import {
prepareSwapIntent,
prepareTwapIntent,
prepareLimitIntent,
prepareBridgeIntent,
prepareOrderIntent,
} from "web3agent";
prepareSwapIntent(params, options?)
Prepares EIP-712 typed data for a Liquidity Hub swap. Returns the data structure the user must sign, plus any required token approvals.
const intent = await prepareSwapIntent({
fromToken: "0x833589...",
toToken: "0x4200000...",
fromAmount: "100000000",
userAddress: "0xabc...",
chainId: 8453,
});
// { typedData: { domain, types, message }, requiredApprovals: [...] }
prepareTwapIntent(params, options?)
Prepares a dTWAP order intent. Splits a large trade into equal chunks executed over a time window.
const intent = await prepareTwapIntent({
fromToken: "0x833589...",
toToken: "0x4200000...",
fromAmount: "1000000000", // 1000 USDC
chunks: 10,
deadline: Math.floor(Date.now() / 1000) + 3600, // 1 hour
userAddress: "0xabc...",
chainId: 8453,
});
prepareLimitIntent(params, options?)
Prepares a dLIMIT order intent. Executes when the output token reaches a target price.
const intent = await prepareLimitIntent({
fromToken: "0x833589...",
toToken: "0x4200000...",
fromAmount: "100000000",
minOutputAmount: "45000000000000000", // minimum WETH to receive
deadline: Math.floor(Date.now() / 1000) + 86400,
userAddress: "0xabc...",
chainId: 8453,
});
prepareBridgeIntent(params, options?)
Prepares a cross-chain bridge intent via LI.FI.
const intent = await prepareBridgeIntent({
fromToken: "0x833589...",
toToken: "0xaf88d...", // USDC on Arbitrum
fromAmount: "100000000",
fromChainId: 8453,
toChainId: 42161,
userAddress: "0xabc...",
});
prepareOrderIntent(params, options?)
Prepares a generic Spot order intent. Used for stop-loss and take-profit orders by setting outputTriggerLower or outputTriggerUpper.
// Stop-loss: sell WETH if output drops below threshold
const intent = await prepareOrderIntent({
fromToken: "0x4200000...", // WETH
toToken: "0x833589...", // USDC
fromAmount: "15000000000000000", // 0.015 WETH
outputTriggerLower: "34620000", // trigger in USDC decimals
userAddress: "0xabc...",
chainId: 8453,
});
Orders
import { listOrders, placeOrder, cancelOrder } from "web3agent";
listOrders(params, options?)
Lists open Spot orders for an address.
const orders = await listOrders({ address: "0xabc...", chainId: 8453 });
placeOrder(params, options?)
Places a new Spot order directly (server-side wallet).
cancelOrder(params, options?)
Cancels an open Spot order on-chain.
Operations
Multi-step operation orchestration for complex flows.
import { prepareOperation, resumeOperation } from "web3agent";
prepareOperation(params, options?)
Prepares a multi-step operation and returns the steps with their current state.
resumeOperation(params, options?)
Resumes a paused operation at a specific step, typically after user confirmation.
Submission
import { submitSignedSwap, submitSignedOrder, pollSwapStatus } from "web3agent";
submitSignedSwap(params, options?)
Submits a user-signed swap to the Orbs relay.
const result = await submitSignedSwap({
signature: "0x...",
typedData: intent.typedData,
chainId: 8453,
});
// { orderHash: "0x...", status: "pending" }
submitSignedOrder(params, options?)
Submits a user-signed Spot order to the Orbs relay.
const result = await submitSignedOrder({
signature: "0x...",
typedData: intent.typedData,
chainId: 8453,
});
pollSwapStatus(params, options?)
Polls the Orbs relay until the swap reaches a terminal status.
const status = await pollSwapStatus({
orderHash: "0x...",
chainId: 8453,
timeoutMs: 60000,
});
// { status: "filled" | "completed" | "cancelled" | "expired" | "failed" | "rejected" }
Simulation
import { simulateTransaction } from "web3agent";
simulateTransaction(params, options?)
Simulates a transaction and returns expected balance changes without broadcasting.
const sim = await simulateTransaction({
to: "0x...",
data: "0x...",
value: "0",
from: "0xabc...",
chainId: 8453,
});
// { balanceChanges: [...], gasEstimate: "21000", success: true }
Explorer
40+ functions for indexed blockchain data. All require Blockscout support on the target chain.
import {
getAddressInfo,
getTransactionHistory,
getTokenTransfers,
getTokenInfo,
getContractAbi,
getBlockInfo,
// ... and more
} from "web3agent";
Key functions:
| Function | Description |
|---|---|
getAddressInfo(params) | Address overview: balance, tx count, contract status |
getTransactionHistory(params) | Paginated transaction history |
getTokenTransfers(params) | ERC-20 transfer history |
getNftTransfers(params) | NFT transfer history |
getInternalTransactions(params) | Internal (trace-level) transactions |
getTransactionDetails(params) | Full transaction details by hash |
getTokenInfo(params) | Token metadata |
getTokenHolders(params) | Top token holders |
getContractAbi(params) | Verified contract ABI |
getContractSource(params) | Verified contract source code |
readContractMethod(params) | Call a view function on a verified contract |
getBlockDetails(params) | Block details by number or hash |
getChainStats(params) | Chain-level statistics |
getGasPriceOracle(params) | Gas price estimates |
Market
20+ functions for price, TVL, volume, and sentiment data.
import {
getTokenPrice,
getProtocolTvl,
getChainTvl,
getTopProtocols,
getTrendingTokens,
getDexPairs,
getFearGreedIndex,
// ... and more
} from "web3agent";
Research
10+ functions for security, yield, and governance research.
import {
getSecurityAudit,
getYieldOpportunities,
getGovernanceProposals,
getTokenUnlocks,
getWhaleActivity,
// ... and more
} from "web3agent";
Config
import { setConfig, parseEnv } from "web3agent";
setConfig(config)
Programmatically set configuration instead of using environment variables. Useful when embedding web3agent in a larger application.
setConfig({
chainId: 8453,
privateKey: process.env.MY_WALLET_KEY,
confirmWrites: false,
policyEnabled: true,
policyMaxSingleTxUsd: 500,
policyMaxDailyUsd: 2000,
});
parseEnv()
Reads and validates all recognized environment variables. Called automatically at startup, but can be called manually to reload config after env changes.
Runtime (Advanced)
For projects that need direct runtime access, import from "web3agent/runtime".
import { createRuntime } from "web3agent/runtime";
import type { Web3AgentRuntime } from "web3agent/runtime";
const runtime: Web3AgentRuntime = await createRuntime({
env: {
CHAIN_ID: "8453",
PRIVATE_KEY: process.env.AGENT_WALLET_KEY,
CONFIRM_WRITES: "false",
POLICY_ENABLED: "true",
POLICY_MAX_SINGLE_TX_USD: "100",
},
});
// Invoke any tool directly
const result = await runtime.invokeTool("resolve_token", {
symbol: "USDC",
chainId: 8453,
});
The Web3AgentRuntime interface exposes:
| Method | Description |
|---|---|
invokeTool(name, args) | Call any registered tool by name |
listTools() | List all registered tools with metadata |
getHealth() | Runtime health status |
Types and Schemas
All input and output types are exported from "web3agent". Zod schemas are also exported for runtime validation.
import type {
SwapQuoteInput,
SwapQuoteOutput,
SwapIntentInput,
SwapIntentOutput,
TwapIntentInput,
LimitIntentInput,
BridgeIntentInput,
OrderIntentInput,
TokenInfo,
ChainInfo,
// ... and more
} from "web3agent";
import {
SwapQuoteInputSchema,
SwapIntentInputSchema,
// ... and more
} from "web3agent";
Error Handling
All SDK functions throw Web3AgentError on failure. See the Error Handling page for details.
import { Web3AgentError } from "web3agent";
try {
const quote = await getSwapQuote({ ... });
} catch (e: unknown) {
if (e instanceof Web3AgentError) {
console.error(e.code, e.message);
}
}