AVO Logo

SDK examples

Copy-paste examples for every main flow with @avodotso/market-sdk 1.0.0 against https://api.avo.so. Each block is self-contained and type-checks against the SDK; myWallet stands for your wallet adapter (sign + send a transaction, sign a message).

What public reads include Public responses never carry raw market value, vault balances or share supply: totalShares, lastTotalValueBase and nav-history totalValueBase are returned only to the market creator and admins, so they are optional in the types. Use navPerShare. Each GET /v1/markets item also carries aumUsd, the market's public AUM in USD (refreshed at most every 90 s; null until valued).

Install and initialise

bash
npm install @avodotso/market-sdk@1.0.0 @solana/web3.js
typescript
import { MarketClient } from '@avodotso/market-sdk';

const services = { avoApi: 'https://api.avo.so' };

// Public reads: no credentials.
export const publicClient = new MarketClient({ services });

// Market creation, registration and identity attach need your Avo API key.
export const keyedClient = new MarketClient({
  services,
  gatewayAuthorization: `Bearer ${process.env.AVO_API_KEY}`, // avo_pk_…
});

// Operating your market: its bearer (the key is optional and raises limits).
export const agentClient = new MarketClient({
  services,
  gatewayAuthorization: `Bearer ${process.env.AVO_API_KEY}`,
  agent: { bearer: process.env.AGENT_BEARER! },
});

Which credential goes where is in Authentication & limits; every route is in the API reference.

List markets

The catalog behind the Indexes page of the app.

Avo app: the Indexes listing, fed by GET /v1/markets
typescript
import { MarketClient } from '@avodotso/market-sdk';

const client = new MarketClient({ services: { avoApi: 'https://api.avo.so' } });

const { markets, total } = await client.listMarkets({ limit: 20, sort: 'popular' });
console.log(`${markets.length} of ${total} markets`);

for (const m of markets) {
  console.log({
    market: m.marketPda,
    label: m.label,
    navPerShare: m.navPerShare,       // base atomic units per share unit, 12 decimals
    depositsOpen: m.depositsOpen,
    minimumDepositUsd: m.depositMinimum.minimumUsd,
    feeBps: m.marketFeeBps + m.platformFeeBps,
  });
}

// Page with offset; `total` counts every market before paging.
const page2 = await client.listMarkets({ limit: 20, offset: 20 });

Market detail and composition

One market and its holdings by weight, as on an index page. Public composition rows carry prices and weights, never per-holding value.

Avo app: an index detail page with price, performance and holdings by weight
typescript
import { MarketClient, type MarketSummary } from '@avodotso/market-sdk';

const API = 'https://api.avo.so';
const client = new MarketClient({ services: { avoApi: API } });
const marketPda = '7q2t1s3ufrEhJ4pNvjYefaxmApjHD6msxJmh2HQVqeo8';

// One market by PDA (also returns markets hidden from the default listing).
const { markets: [market] } = await client.listMarkets({ marketPda });
const m: MarketSummary | undefined = market;
console.log(m?.label, m?.navPerShare, m?.targetAssetCount);

// Composition has no SDK method yet; it is a plain public GET.
interface CompositionRow {
  mint: string;
  symbol: string | null;
  name: string | null;
  decimals: number;
  priceUsd: number | null;
  targetWeightBps: number;
  actualWeightBps: number;
  isBase: boolean;
}
const res = await fetch(`${API}/v1/markets/${marketPda}/composition`);
if (!res.ok) throw new Error(`composition: ${res.status}`);
const { rows } = (await res.json()) as { rows: CompositionRow[] };
for (const r of rows) {
  console.log(r.symbol, (r.actualWeightBps / 100).toFixed(1) + '%', 'target', (r.targetWeightBps / 100).toFixed(1) + '%');
}
typescript
import { MarketClient } from '@avodotso/market-sdk';

const client = new MarketClient({ services: { avoApi: 'https://api.avo.so' } });
const marketPda = '7q2t1s3ufrEhJ4pNvjYefaxmApjHD6msxJmh2HQVqeo8';

// Last 7 days, oldest first. Public points carry navPerShare, lastNavTs, recordedAt.
const { points } = await client.getNavHistory(marketPda, {
  order: 'asc',
  from: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
  limit: 2000,
});

const series = points
  .filter((p): p is typeof p & { navPerShare: string } => p.navPerShare !== null)
  .map((p) => ({ t: new Date(p.recordedAt), nav: Number(p.navPerShare) }));

if (series.length >= 2) {
  const change = series[series.length - 1].nav / series[0].nav - 1;
  console.log(`7d return: ${(change * 100).toFixed(2)}%`);
}

// On-chain activity, newest first, paged with the previous page's `oldest`.
let before: string | undefined;
for (let pageNo = 0; pageNo < 3; pageNo++) {
  const { events, oldest } = await client.getMarketEvents(marketPda, { limit: 100, before });
  events.forEach((e) => console.log(e.created_at, e.type, e.status, e.message));
  if (!oldest) break;
  before = oldest;
}

Create a market (prepare → fund → finalize)

Market creation needs an API key and two signatures from the creator wallet: the funding transfer and a single-use creatorAuth. This is the flow behind the app's create screen; see Create your first market for the walkthrough.

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

// `myWallet`: any wallet adapter that can sign + send a transaction and sign a message.
declare const secrets: { set(name: string, value: string): Promise<void> }; // your secret manager
const client = new MarketClient({
  services: { avoApi: 'https://api.avo.so' },
  gatewayAuthorization: `Bearer ${process.env.AVO_API_KEY}`,
});
const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
const SOL = 'So11111111111111111111111111111111111111112';
const creator = myWallet.publicKey.toBase58();

// 1. Prepare: the API generates a custodial agent and an unsigned 0.1 SOL funding transfer.
const prep = await client.prepareCreateMarket({
  creator,
  baseAssetMint: USDC,
  feeAssetMint: USDC,
  marketFeeBps: 50,
  label: 'My Index',
  assetMints: [SOL],
  initialWeights: { base: 2000, [SOL]: 8000 },
});

// 2. Fund: your wallet signs and sends it.
const fundingTx = VersionedTransaction.deserialize(Buffer.from(prep.fundingTx, 'base64'));
const fundingSignature = await myWallet.signAndSendTransaction(fundingTx);

// 3. Finalize. The API acts only on a finalized funding transfer: until then it
//    answers 409 FUNDING_TX_NOT_FOUND / FUNDING_TX_NOT_FINALIZED with Retry-After.
//    creatorAuth is single-use, so sign a fresh one for every attempt.
async function finalizeWithRetry(maxAttempts = 6): Promise<FinalizeCreateMarketResp> {
  for (let attempt = 1; ; attempt++) {
    const { creatorAuth } = await buildCreatorAuth({
      creator,
      pendingId: prep.pendingId,
      agentPubkey: prep.agentPubkey,
      fundingSignature,
      signMessage: (message) => myWallet.signMessage(message),
    });
    try {
      return await client.finalizeCreateMarket({ agentPubkey: prep.agentPubkey, fundingSignature, creatorAuth });
    } catch (err) {
      const retryable = err instanceof AvoSdkError && RETRYABLE_FINALIZE_CODES.has(err.code);
      if (!retryable || attempt >= maxAttempts) throw err;
      await new Promise((r) => setTimeout(r, err.retryAfterMs ?? 2_000 * attempt));
    }
  }
}

const created = await finalizeWithRetry();
if (created.converged || !created.bearer) {
  // An earlier attempt already created this market; no new bearer is issued.
  // Mint one with POST /v1/markets/bearer/rotate (as the creator, with a creator Sig).
  console.log('already created:', created.marketPda);
} else {
  // The bearer is shown once and is a live credential: write it straight to
  // your secret manager. Never log it.
  await secrets.set(`avo/markets/${created.marketPda}/bearer`, created.bearer);
  console.log('market:', created.marketPda);
}

Or in one call, with the same retries built in:

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

declare const secrets: { set(name: string, value: string): Promise<void> }; // your secret manager
const client = new MarketClient({
  services: { avoApi: 'https://api.avo.so' },
  gatewayAuthorization: `Bearer ${process.env.AVO_API_KEY}`,
});

try {
  const created = await client.createMarketWithShadowPortfolio(
    {
      creator: myWallet.publicKey.toBase58(),
      baseAssetMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
      feeAssetMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
      marketFeeBps: 50,
      assetMints: ['So11111111111111111111111111111111111111112'],
      initialWeights: { base: 0, So11111111111111111111111111111111111111112: 10_000 },
    },
    (fundingTxBase64) =>
      myWallet.signAndSendTransaction(VersionedTransaction.deserialize(Buffer.from(fundingTxBase64, 'base64'))),
    (message) => myWallet.signMessage(message),
    { maxFinalizeAttempts: 6 },
  );
  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); // never log it
  console.log('created market', created.marketPda);
} catch (err) {
  // After funding, details carry what you need to finish by hand
  // (buildCreatorAuth + finalizeCreateMarket).
  if (err instanceof AvoSdkError) {
    const { pendingId, agentPubkey, fundingSignature } = (err.details ?? {}) as {
      pendingId?: string; agentPubkey?: string; fundingSignature?: string;
    };
    console.error(err.code, { pendingId, agentPubkey, fundingSignature });
  }
  throw err;
}

Register a market you created on chain

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

// You created the market on chain yourself and hold its agent keypair.
declare const agentKeypair: Keypair;
declare const myMarketPda: string;
declare const secrets: { set(name: string, value: string): Promise<void> }; // your secret manager

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

const registered = await client.registerMarket({
  marketPda: myMarketPda,
  agentSecretBase58: bs58.encode(agentKeypair.secretKey), // checked against Market.agent, encrypted at rest
  label: 'My self-built market',
});
// Shown once: into your secret manager, never into logs.
await secrets.set(`avo/markets/${registered.marketPda}/bearer`, registered.bearer);

Agent identity (MPL-8004)

typescript
import { MarketClient, buildAttachMessage } from '@avodotso/market-sdk';
import { Keypair } from '@solana/web3.js';
import bs58 from 'bs58';
import nacl from 'tweetnacl';

declare const agentKeypair: Keypair;     // the market's agent
declare const coreAssetAddress: string;  // MPL Core asset owned by the agent
declare const agentUri: string;          // must equal the asset's on-chain uri

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

// Read anyone's identity and rating (public).
const identity = await client.getIdentity(agentKeypair.publicKey.toBase58());
console.log(identity.coreAssetAddress, identity.rating?.compositeScore);

// Attach: the agent signs the canonical attach message.
const expiresAtMs = Date.now() + 60_000;
const message = buildAttachMessage(agentKeypair.publicKey.toBase58(), coreAssetAddress, expiresAtMs);
const attached = await client.attachIdentity({
  agentPubkey: agentKeypair.publicKey.toBase58(),
  coreAssetAddress,
  agentUri,
  expiresAtMs,
  signatureBase58: bs58.encode(nacl.sign.detached(message, agentKeypair.secretKey)),
});
console.log('attached at', attached.attachedAt);

Operate your market: simulate, rebalance, NAV, fees

typescript
import { AvoSdkError, MarketClient, type WeightInput } from '@avodotso/market-sdk';

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

const market = await client.getMarket();
const assets = await client.getAssets();
console.log(market.pda, assets.map((a) => `${a.mint}: ${a.currentWeightBps} → ${a.targetWeightBps} bps`));

const weights: WeightInput[] = [
  { asset: 'base', weightBps: 2_000 },
  { asset: 'So11111111111111111111111111111111111111112', weightBps: 8_000 },
];

// Plan + quote first (no transactions). Refuse unroutable legs.
const plan = await client.simulateRebalance({ weights, slippageBps: 50 });
const blocked = plan.legs.filter((leg) => leg.unroutable);
if (blocked.length > 0) throw new Error(`unroutable: ${blocked.map((l) => l.unroutableReason ?? l.mint).join(', ')}`);
console.log('estimated fee (base units):', plan.totalFeeBase);

// Execute. The API signs and submits prepare → legs → settle. A late failure
// arrives inside an HTTP 200 and is thrown here as AvoSdkError; do not blindly
// retry, execution may be partially applied.
try {
  const result = await client.rebalance({ weights, slippageBps: 50, deadlineSecs: 180 });
  console.log('settled:', result.settleSignature, result.legs.map((l) => `${l.mint} ${l.direction} via ${l.router}`));
} catch (err) {
  if (err instanceof AvoSdkError) console.error('rebalance refused:', err.status, err.code, err.message);
  throw err;
}

// Refresh NAV on chain (signs + submits server-side) and sweep agent fees.
await client.updateNav();
await client.withdrawAgentFees({ destinationWallet: process.env.TREASURY_WALLET!, minFeeAmount: '1000000' });

Self-custodial agents sign their own short-lived tokens instead of using a bearer:

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

// Self-custodial: you hold the agent key; the SDK signs short-lived Sig tokens.
declare const agentKeypair: Keypair;

const client = new MarketClient({
  services: { avoApi: 'https://api.avo.so' },
  agent: { publicKey: agentKeypair.publicKey.toBytes(), secretKey: agentKeypair.secretKey },
  tokenTtlSecs: 300,
});
console.log(await client.getValue(50));

Errors and retries

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

/** Retries what the API marks as temporary, honouring Retry-After. */
export async function withRetry<T>(call: () => Promise<T>, maxAttempts = 4): Promise<T> {
  const temporary = new Set(['RATE_LIMITED', 'LONG_OPERATION_CAPACITY', 'UPSTREAM_UNAVAILABLE', 'UPSTREAM_TIMEOUT']);
  for (let attempt = 1; ; attempt++) {
    try {
      return await call();
    } catch (err) {
      if (err instanceof AvoSdkError) {
        // status, code, message, details, and retryAfterMs when the API sent Retry-After.
        if (temporary.has(err.code) && attempt < maxAttempts) {
          await new Promise((r) => setTimeout(r, err.retryAfterMs ?? 1_000 * 2 ** attempt));
          continue;
        }
        console.error(`Avo API ${err.status} ${err.code}: ${err.message}`, err.details);
      } else if (err instanceof AvoTransportError) {
        console.error('network failure:', err.message); // DNS, refused connection, non-JSON body
      }
      throw err;
    }
  }
}

// Reads are safe to retry; do not wrap rebalance() or other writes blindly.
// const markets = await withRetry(() => client.listMarkets({ limit: 50 }));

The codes you are likely to see are listed under Build on-chain → Errors.