Skip to content

The entry point for the Anvil SDK.

Create one instance per session (per wallet connection). In React, pass it to <AnvilProvider sdk={sdk}>.

The protocol operations live in four modules:

  • sdk.loc (LOCModule) — create, manage, and read Letters of Credit
  • sdk.vault (VaultModule) — Collateral Vault balances, deposits, and withdrawals
  • sdk.pricing (PricingModule) — oracle prices and price updates
  • sdk.tokens (TokenModule) — token metadata and wallet balances

Methods on the instance itself cover the signer, chain, contract addresses, ERC-20 allowances, and ENS.

Examples

Read-only instance (no wallet) against Sepolia, using a profile

// No walletClient: queries, validation, and workflow building all work;
// only executing a workflow needs a signer.
const sdk = new AnvilSDK({
publicClient: createPublicClient({
chain: sepolia,
transport: http('https://your-rpc-url'),
}),
profile: testnetProfile,
});
// A direct contract read; no wallet and no subgraph involved.
const loc = await sdk.loc.getOutstandingLetterOfCredit({ id: 1n });
console.log(loc);

With a wallet: validate, build, then execute a workflow

const transport = http('https://your-rpc-url');
const account = privateKeyToAccount(
'0x0000000000000000000000000000000000000000000000000000000000000001'
);
const sdk = new AnvilSDK({
profile: mainnetProfile,
publicClient: createPublicClient({ chain: mainnet, transport }),
walletClient: createWalletClient({
account,
chain: mainnet,
transport,
}),
subgraphUrl: 'https://your-subgraph-url',
});
const params: CreateStaticLOCParams = {
beneficiary: '0x1111111111111111111111111111111111111111',
// 1,000 USDC (6 decimals), in the token's smallest unit.
tokenAmount: {
tokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',
amount: 1_000_000_000n,
},
expirationTimestampSeconds: BigInt(Math.floor(Date.now() / 1000) + 30 * 86_400),
};
// Validation touches no wallet; an empty array means the params are valid.
const issues = await sdk.loc.validateCreateStatic(params);
if (issues.length === 0) {
const workflow = await sdk.loc.buildCreateStaticWorkflow(params);
// Approvals, deposit, and creation run in order, each a wallet prompt.
await workflow.execute();
}

Implements

  • SDKContext

Constructors

Constructor

new AnvilSDK(deps): AnvilSDK;

Parameters

ParameterTypeDescription
depsAnvilDependenciesThe clients and configuration this instance uses; see AnvilDependencies. The SDK keeps a shallow copy, so AnvilSDK.updateAccountAddress and AnvilSDK.updateWalletClient never change the object you pass in.
deps.accountAddress?`0x${string}`Connected account address for read operations (balance queries, validation, allowance checks). Resolves before walletClient in wagmi — set this from useAccount().address so reads work immediately without waiting for the wallet connector to reconnect. Falls back to walletClient.account.address if not set. Explicit undefined is equivalent to omission.
deps.locConfig?LOCConfigLOC management behavior and display configuration (beneficiary allowlist, default destination, token allowlists, etc.). See LOCConfig for what the SDK enforces versus what only the React components read. Explicit undefined is equivalent to omission.
deps.mainnetRpcUrl?stringRPC URL for a dedicated, mainnet-pinned viem client used only for ENS operations (resolveAddress, getEnsName). ENS is a mainnet-only protocol, so this lets ENS resolution work correctly even when publicClient above is configured for another chain (for example Sepolia, which testnet uses). ENS resolution on non-mainnet protocol chains requires mainnetRpcUrl. When not provided, ENS actions fall back to publicClient — correct only when the protocol chain IS mainnet.
deps.oracleConfig?OracleConfigPyth Hermes settings, used only by Dynamic LOC operations and price reads. Every field is optional: - hermesEndpoint: the Hermes URL, https://hermes.pyth.network by default, which rejects requests without an API key. In a browser, point it at your own proxy that adds the key server-side. - hermesAccessToken: the Pyth API key, sent as a Bearer token. Set it only where the SDK runs server-side; never ship it in a browser bundle. - maxPriceAgeSeconds: the oldest Hermes price accepted, 300 seconds by default; Infinity turns the freshness check off. - updateBufferSeconds: time validation allows for a price-update transaction to confirm, 30 seconds by default.
deps.profileAnvilSdkProfileThe environment profile: import testnetProfile or mainnetProfile directly so bundlers can drop the other, or select anvilProfiles[name] at runtime by environment name. The profile supplies contract addresses, the ABI bound at each of those addresses, the subgraph URL, and the environment’s token-alias map. subgraphUrl may override the profile’s endpoint. The ABIs are what make this more than address configuration: a profile binds each address to the interface derived from the deployment at that address, and the SDK encodes calldata, decodes returns, and names revert errors against that interface rather than against its bundled modules, so environments running different deployed generations each get their own. Contract-address resolution asserts the live chain equals profile.chainId, throwing ConfigError on disagreement so a client wired to the wrong network fails loudly instead of transacting at another environment’s addresses. More than one environment can share a chain id, and the guard cannot tell those apart — the profile you pass is the selector; the guard catches cross-chain wiring mistakes. The SDK does not read profile.pyth.hermesPath. Price reads go to oracleConfig.hermesEndpoint.
deps.publicClientobjectviem PublicClient for every read: contract calls, chain-id resolution, and (absent mainnetRpcUrl) ENS. Its chain must match the generated AnvilDependencies.profile. Create one with viem’s createPublicClient({ chain, transport }), or in React take wagmi’s usePublicClient().
deps.subgraphHeaders?Record<string, string>HTTP headers to send with every subgraph request (e.g. authorization).
deps.subgraphUrl?stringGraphQL endpoint of the Anvil subgraph. Required for indexed reads — LOC and vault listings, history, collateral-token discovery — which throw ConfigError without it; direct contract reads (sdk.loc.getOutstandingLetterOfCredit, balances, prices) do not need it, and each published profile carries its endpoint at <profile>.subgraph.url.
deps.walletClient?objectviem WalletClient that signs and sends transactions. Omit it for read-only use: queries, validation, and workflow building work without a wallet, while a built workflow’s execute() and any other write throw WalletNotConnectedError until one is supplied here or via AnvilSDK.updateWalletClient. Explicit undefined is equivalent to omission. Create one with viem’s createWalletClient({ account, chain, transport }), or in React take data from wagmi’s useWalletClient().

Returns

AnvilSDK

Throws

A ConfigError if deps is missing or is not an object, if its required profile is missing or is not an object, if it passes a contractAddresses map instead of a profile, or if oracleConfig.maxPriceAgeSeconds is negative or not a number.

Properties

deps

readonly deps: AnvilDependencies;

The dependencies this instance uses: a shallow copy of the object passed to the constructor. AnvilSDK.updateAccountAddress and AnvilSDK.updateWalletClient change this copy, never your object.

Implementation of

SDKContext.deps


loc

readonly loc: LOCModule;

Letter of Credit reads, workflow builders, and validation; see LOCModule.


pricing

readonly pricing: PricingModule;

Oracle prices, price updates, and update fees; see PricingModule.


tokens

readonly tokens: TokenModule;

Token metadata and wallet balances; see TokenModule.


vault

readonly vault: VaultModule;

Collateral Vault balances, deposits, withdrawals, and authorizations; see VaultModule.

Accessors

locConfig

Get Signature

get locConfig(): LOCConfig | undefined;

The LOCConfig this instance was constructed with, if any.

Returns

LOCConfig | undefined


logger

Get Signature

get logger(): Logger;

The SDK’s logger: warn and error go to the console with an [AnvilSDK] prefix; info, log, and debug are silent, since those levels carry request and response payloads.

Returns

Logger

Sink for the SDK’s diagnostic output. AnvilSDK supplies a console-backed logger that prefixes every line with [AnvilSDK]; there is no public way to replace it today. That default only surfaces warn and error — info, log, and debug are no-ops, since those are the levels request/response payloads log at.

Implementation of

SDKContext.logger

Methods

getChainId()

getChainId(): Promise<bigint>;

Chain ID of publicClient as a bigint, fetched live from the RPC on every call (not cached).

Returns

Promise<bigint>

Throws

ProviderConnectionError if the RPC call fails.


getContractAddress()

getContractAddress(contract): Promise<`0x${string}`>;

Address of a protocol contract on the current chain, read from the profile. Multicall3 is the exception: it resolves to its standard address, which is the same on every chain.

Parameters

ParameterTypeDescription
contractAnvilContractThe protocol contract to look up.

Returns

Promise<`0x${string}`>

The contract’s address.

Throws

ConfigError if the profile disagrees with the connected chain.


getEnsName()

getEnsName(params): Promise<string | null>;

Primary ENS name for an address, or null when none is set. ENS uses the mainnetRpcUrl client when configured.

Parameters

ParameterTypeDescription
paramsGetEnsNameParamsThe address to look up.
params.address`0x${string}`The address to reverse-resolve to a primary ENS name.

Returns

Promise<string | null>

Throws

ProviderConnectionError only on RPC failure.


getERC20Allowance()

getERC20Allowance(params): Promise<bigint>;

ERC-20 allowance(owner, spender) in the token’s smallest unit; owner defaults to the signer address.

Parameters

ParameterTypeDescription
paramsGetERC20AllowanceParamsThe token, the spender, and optionally the owner.
params.erc20AddressAddressThe ERC-20 token contract to query.
params.owner?AddressToken holder who granted the allowance. Defaults to the connected account.
params.spenderAddressThe address whose allowance to read (for deposits, the Collateral Vault).

Returns

Promise<bigint>

The approved amount in the token’s smallest unit.


getSignerAddress()

getSignerAddress(): Promise<`0x${string}`>;

Address the SDK treats as the current account: accountAddress if set, otherwise the wallet client’s account.

Returns

Promise<`0x${string}`>

Throws

WalletNotConnectedError When neither is configured.


resolveAddress()

resolveAddress(value): Promise<`0x${string}` | undefined>;

Resolve a hex address or ENS name to a checksummed address; undefined when the string is neither, or is a name with no address set. ENS uses the mainnetRpcUrl client when configured.

Parameters

ParameterTypeDescription
valuestringA hex address or an ENS name such as vitalik.eth.

Returns

Promise<`0x${string}` | undefined>

Throws

ProviderConnectionError only on RPC failure — “no such name” is undefined, not an error.


updateAccountAddress()

updateAccountAddress(address): void;

Updates the connected account address that reads and validation use, for example when the user switches accounts in their wallet.

Parameters

ParameterTypeDescription
address`0x${string}` | undefinedThe new account address, or undefined to clear it and fall back to the wallet client’s account.

Returns

void


updateWalletClient()

updateWalletClient(walletClient): void;

Updates the wallet client that signs and sends transactions, for example after the user connects or disconnects a wallet.

Parameters

ParameterTypeDescription
walletClient| { } | undefinedThe new viem WalletClient, or undefined to disconnect; writes then throw WalletNotConnectedError.

Returns

void