AVO Logo

Build on-chain

Reasoning agents are not available here The SDK + REST API only cover markets AVO operates on your behalf — programmatic indexes and managed markets. Reasoning agents, where an LLM decides the trades, are exclusively creatable and operable through the Avo MCP. Head there if that's what you need.

Use the Avo Market SDK to build fully on-chain, custodially signed indexes and managed portfolios. Every market documented here is one AVO signs on your behalf — you never hold the agent's Solana keypair, and the API can autonomously rebalance, refresh NAV, and sweep fees using nothing but the bearer token it issued you at creation.

Tip for AI builders Feed the NPM docsdirectly to your LLM or agent framework. It contains full walkthroughs, schemas, and response examples — everything needed to start and run a market.

Downloads

SDK version This page tracks @avodotso/market-sdk 1.0.0. Since 0.3.0, finalizeCreateMarket requires a creator-signed creatorAuth and createMarketWithShadowPortfolio takes a signMessage callback; SDKs older than 0.3.0 can't finalize against api.avo.so. 1.0.0 changes types only: public reads never carry raw totals, so totalShares / lastTotalValueBase / totalValueBase are optional; use navPerShare. It also retries FUNDING_TX_NOT_FINALIZED. See the changelog and SDK examples.

Installation

bash
npm install @avodotso/market-sdk
# or
yarn add @avodotso/market-sdk

Getting Started

The SDK exports one primary class — MarketClient — that covers the entire market-maker journey: create → operate → close. For the markets documented here it uses one auth mode: the one-time bearer token AVO returns when you finalize the market. That's all you ever need to hold.

Operate a market

You hold the bearer AVO returned from finalizeCreateMarket; the API holds the agent's signing keypair encrypted at rest. You never touch a private key. That's the whole point — the API can rebalance, push NAV, or sweep fees on a cron without any cooperation from your machine after boot.

ts
import { MarketClient } from '@avodotso/market-sdk';

const client = new MarketClient({
  services: { avoApi: 'https://api.avo.so' },
  agent: { bearer: process.env.AGENT_BEARER! },
});

// Live valuation of every vault in the market.
const value = await client.getValue(/* slippageBps = */ 50);

// Rebalance to a new target weight vector (asset mint → percent; sum = 100).
await client.rebalance({
  weights: [
    { asset: 'base', weight: 0 },
    { asset: 'So11111111111111111111111111111111111111112', weight: 50 },
    { asset: 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263', weight: 50 },
  ],
  slippageBps: 100,
  deadlineSecs: 180,
});

// Push fresh NAV onto chain.
await client.updateNav();

Create a new market

The API generates a fresh agent keypair custodially. Your creator wallet signs two things: the 0.1 SOL funding transaction, and a short-lived creatorAuth message that binds the pending market, its agent and that funding transaction to you. The API does the rest and hands you back a one-time bearer for ongoing ops.

typescript
import { MarketClient, buildCreatorAuth } from '@avodotso/market-sdk';
import { VersionedTransaction } from '@solana/web3.js';

// `myWallet` is your creator wallet: any adapter that can sign + send a
// transaction and sign a message (Phantom, Dynamic, wallet-standard, ...).

// Market creation requires an Avo API key.
const client = new MarketClient({
  services: { avoApi: 'https://api.avo.so' },
  gatewayAuthorization: `Bearer ${process.env.AVO_API_KEY}`, // avo_pk_…
});

// Phase 1: register intent + receive an unsigned 0.1 SOL funding tx.
const creator = myWallet.publicKey.toBase58();
const prep = await client.prepareCreateMarket({
  creator,
  baseAssetMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC mainnet
  feeAssetMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
  marketFeeBps: 30,
  label: 'My Index',
  assetMints: ['So11111111111111111111111111111111111111112'],
  initialWeights: { base: 0, So11111111111111111111111111111111111111112: 10_000 },
});

// Phase 1b: your wallet signs + submits the funding transfer.
const tx = VersionedTransaction.deserialize(Buffer.from(prep.fundingTx, 'base64'));
const fundingSignature = await myWallet.signAndSendTransaction(tx);

// Phase 2a: the creator wallet signs creatorAuth. Single-use and valid for
// at most 110 s, so build a fresh one for every finalize attempt.
const { creatorAuth } = await buildCreatorAuth({
  creator,
  pendingId: prep.pendingId,
  agentPubkey: prep.agentPubkey,
  fundingSignature,
  signMessage: (message) => myWallet.signMessage(message),
});

// Phase 2b: API verifies creatorAuth + funding, custodial agent signs
// create_market on chain, weight-set rebalance lands the initial weights.
const result = await client.finalizeCreateMarket({
  agentPubkey: prep.agentPubkey,
  fundingSignature,
  creatorAuth,
});

// The bearer is shown once and is a live credential: write it straight to
// your secret manager (Vault, AWS Secrets Manager, Doppler, …). Never log it.
declare const secrets: { set(name: string, value: string): Promise<void> };
if (result.converged || !result.bearer) {
  // An earlier finalize already created this market and issued its bearer;
  // it is never re-issued. Keep the one you stored. If you no longer have it,
  // mint a new one: POST /v1/markets/bearer/rotate { marketPda } as the creator.
  throw new Error(`market ${result.marketPda} already existed; not saving an empty bearer`);
}
await secrets.set(`avo/markets/${result.marketPda}/bearer`, result.bearer);
console.log({ marketPda: result.marketPda, agentPubkey: result.agentPubkey });

Or do all of it in one call. createMarketWithShadowPortfolio runs prepare → funding → creatorAuth → finalize. It retries finalize on FUNDING_TX_NOT_FOUND, FUNDING_TX_NOT_FINALIZED and FUNDING_TX_LOOKUP_FAILED (the SDK exports them as RETRYABLE_FINALIZE_CODES; honouring Retry-After, signing a fresh creatorAuth each time). Retries are bounded: maxFinalizeAttempts (1–20, default 4) and finalizeDeadlineMs (default 3 minutes from funding). It deliberately does not retry finalize's 503s (FINALIZE_IN_PROGRESS and friends): another finalize for the agent is running, and retrying could converge on that market with an empty bearer. If it fails after funding, the error's details carry pendingId, agentPubkey and fundingSignature so you can finish by hand with buildCreatorAuth + finalizeCreateMarket.

typescript
import { MarketClient } from '@avodotso/market-sdk';
import { VersionedTransaction } from '@solana/web3.js';

const client = new MarketClient({
  services: { avoApi: 'https://api.avo.so' },
  gatewayAuthorization: `Bearer ${process.env.AVO_API_KEY}`,
});

const created = await client.createMarketWithShadowPortfolio(
  {
    creator: myWallet.publicKey.toBase58(),
    baseAssetMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
    feeAssetMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
    marketFeeBps: 30,
    assetMints: ['So11111111111111111111111111111111111111112'],
    initialWeights: { base: 0, So11111111111111111111111111111111111111112: 10_000 },
  },
  (fundingTxBase64) =>
    myWallet.signAndSendTransaction(
      VersionedTransaction.deserialize(Buffer.from(fundingTxBase64, 'base64')),
    ),
  (message) => myWallet.signMessage(message),
);
// The bearer is shown once and is a live credential: write it straight to
// your secret manager (Vault, AWS Secrets Manager, Doppler, …). Never log it.
declare const secrets: { set(name: string, value: string): Promise<void> };
if (created.converged || !created.bearer) {
  // An earlier finalize already created this market and issued its bearer;
  // it is never re-issued. Keep the one you stored. If you no longer have it,
  // mint a new one: POST /v1/markets/bearer/rotate { marketPda } as the creator.
  throw new Error(`market ${created.marketPda} already existed; not saving an empty bearer`);
}
await secrets.set(`avo/markets/${created.marketPda}/bearer`, created.bearer);
console.log('created market', created.marketPda);
Only markets we create end up in the AVO marketplace The prepareCreateMarket → finalizeCreateMarket flow is the only way to get a market listed under Indexes or Managed in the AVO UI. Markets registered outside this flow (e.g. via direct on-chain create_market + operator-held keys) can still hit the on-chain program, but they will not be surfaced in the marketplace. If a shipped market needs to appear in the UI, walk it through the create flow so AVO holds the credential the API needs to operate it.

Auth

Every agent-scoped call goes over Authorization: Bearer <token>. The API hashes the token at receipt (sha256) and matches it against the bearerHash it stored at creation. No TTL — valid until you rotate.

Market creation additionally needs an Avo API key. Pass it as gatewayAuthorization: 'Bearer avo_pk_…'; the SDK then sends your agent credential in x-avo-agent-authorization. See Authentication & limits.

Rotation

Rotate any time via the manage console on app.avo.so or by hitting POST /v1/markets/bearer/rotate as the market's creator. The old bearer is invalidated the moment the new one is minted — deploy the new value into your env before rotating.

Threat model

A leaked bearer is equivalent operational power to a leaked secret key against the API: the attacker can rebalance, update NAV, add or remove assets as your agent. The blast radius is bounded though:

  • The bearer cannot sign on-chain transactions outside our API — it's not a Solana keypair.
  • The bearer cannot withdraw the agent's keypair — that material never leaves the API's at-rest encryption.
  • Rotation is one HTTP call.

Config

MarketClient reads the API base URL from AvoServiceConfig. Just one slot:

typescript
import { MarketClient, resolveServiceConfig } from '@avodotso/market-sdk';

const services = resolveServiceConfig({
  avoApi: 'https://api.avo.so',
});

const client = new MarketClient({ services });

You can pass a custom fetch for testing or instrumentation:

typescript
import { MarketClient } from '@avodotso/market-sdk';

new MarketClient({
  services: { avoApi: 'https://api.avo.so' },
  fetch: myInstrumentedFetch,
});

Public reads

healthz, listMarkets, getMarketEvents, getNavHistory and getIdentity need no credentials. Public responses never include raw market value or share supply: listMarkets items carry navPerShare and the public aumUsd (AUM in USD), but no totalShares / lastTotalValueBase, and nav-history points carry only navPerShare, lastNavTs and recordedAt. Use navPerShare for charts and returns. Your own market's live value is getValue(), which needs agent auth.

Errors

Every HTTP failure throws AvoSdkError with status, code, message, details and, when the API sent Retry-After, retryAfterMs. Network failures (DNS / connection refused / non-JSON body) throw AvoTransportError.

typescript
import { AvoSdkError, AvoTransportError } from '@avodotso/market-sdk';

try {
  await client.rebalance({ weights: [{ asset: 'base', weightBps: 10_000 }] });
} catch (err) {
  if (err instanceof AvoSdkError) {
    console.error(err.status, err.code, err.message, err.details);
  } else if (err instanceof AvoTransportError) {
    console.error('network failure:', err.message);
  } else {
    throw err;
  }
}

AvoSdkError codes the SDK itself raises:

CodeWhen
SERVICE_UNCONFIGUREDNo services.avoApi was set.
AGENT_NOT_CONFIGUREDA protected method was called on an unauthenticated client.
AGENT_AUTH_EMPTYConstructor got agent: with no bearer or signer.
AGENT_AUTH_AMBIGUOUSagent carries both a bearer and a signer.
AGENT_PUBLIC_KEY_MISSINGSig mode without agent.publicKey.
GATEWAY_AUTH_EMPTYgatewayAuthorization resolved to an empty string.
SIGN_MESSAGE_REQUIRED, PENDING_ID_MISSING, INVALID_FUNDING_SIGNATURE, CREATOR_AUTH_SIGN_FAILED, FINALIZE_INCOMPLETEcreateMarketWithShadowPortfolio could not complete. After funding, details carries pendingId, agentPubkey and fundingSignature for a manual finalize.
HTTP_<status>API returned a non-2xx with no parseable error envelope.

All other code values come straight from the API's error envelope. Ones you are likely to see from api.avo.so:

  • 401 API_KEY_REQUIRED / 401 INVALID_API_KEY: market creation without a (valid) API key.
  • 401 AGENT_CREDENTIAL_REQUIRED: an agent op with no bearer or Sig.
  • 400 AMBIGUOUS_CREDENTIALS: two API keys or two agent credentials, e.g. an API key in both x-avo-api-key and gatewayAuthorization.
  • 401 CREATOR_AUTH_REQUIRED / _EXPIRED / _INVALID / _REPLAYED, 403 CREATOR_MISMATCH: finalize's creatorAuth was missing, stale, wrongly signed or reused.
  • 409 FUNDING_TX_NOT_FOUND / 409 FUNDING_TX_NOT_FINALIZED (retry after retryAfterMs with a fresh creatorAuth), 409 FUNDING_TX_REUSED, 402 FUNDING_AMOUNT_INSUFFICIENT, 403 FUNDING_PAYER_MISMATCH: funding checks at finalize.
  • 429 RATE_LIMITED: back off for retryAfterMs.
  • 503 LONG_OPERATION_CAPACITY / 429 LONG_OPERATION_CALLER_LIMIT: too many concurrent on-chain operations; retry shortly.
  • 503 FINALIZE_IN_PROGRESS, FINALIZE_LEASE_LOST, FINALIZE_LOOKUP_TABLE_UNRESOLVED, FINALIZE_UNAVAILABLE: finalize is busy or not settled yet; retry later and it resumes or converges on the same market.
  • 404 ROUTE_NOT_EXPOSED: the path is not part of the public API.