npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@sereel/sdk

v1.1.0

Published

TypeScript SDK for Sereel asset read endpoints and the Open Fund contract and program interfaces

Readme

Sereel TypeScript SDK

TypeScript SDK for the Sereel marketplace REST endpoints. Use it to browse security tokens listed on the Sereel marketplace, inspect their compliance rule engines, and filter by issuer. It also ships the Open Fund interfaces: the EVM contract ABIs and the Solana program interface.

Only tokens whose issuer has created an Open Fund are ever returned; see Fund availability. The client needs a secret API key, so run it on a server, never in a browser (see Authentication).

Install

npm install @sereel/sdk
# or
pnpm add @sereel/sdk

Quickstart

import { createClient } from "@sereel/sdk";

const client = createClient({
  environment: "mainnet",
  apiKey: process.env.SEREEL_SDK_API_KEY!,
});

// All listed assets
const assets = await client.getAssets();

// Single asset by token address
const asset = await client.getAssetByTokenAddress("0xabc…");

// All assets issued by a specific issuer
const issuerAssets = await client.getAssetsByIssuer("64f1a2b3c4d5e6f7a8b9c0d1");

Authentication

The SDK sends your API key in the x-api-key header.
Only MATATA-issued API keys are supported.

Keep the key server-side. The API key is a secret that grants read access to every asset the key's scope covers. Create the client only in server code (API routes, server components, background jobs) and load the key from an environment variable. Never ship it in a browser bundle, a NEXT_PUBLIC_* variable, or a mobile app; expose the data your UI needs through your own backend instead.

const client = createClient({
  environment: "testnet",
  apiKey: process.env.SEREEL_SDK_API_KEY!,
});

Environments

| Key | Base URL | |-----|----------| | devnet | https://api-lazer.sereel.com | | testnet | https://api-lazer-v2.sereel.com | | mainnet | https://cahokia.sereel.com |

environment is typed SereelEnvironment ("devnet" | "testnet" | "mainnet"). The same map is exported as ENVIRONMENT_BASE_URLS, and resolveBaseUrl(environment, baseUrl?) returns the URL the client will use (the baseUrl override when given, otherwise the environment's URL).

Client API

createClient(config)

Returns a SereelSdkClient with the methods below. Throws InvalidConfigurationError for an empty apiKey or a non-positive timeoutMs.

import { createClient } from "@sereel/sdk";

const client = createClient({
  environment: "testnet",   // required
  apiKey: process.env.SEREEL_SDK_API_KEY!, // required
  timeoutMs: 10_000,        // optional, default: 30 000
  baseUrl: "http://localhost:8080", // optional – overrides environment URL
});
interface ClientConfig {
  environment: SereelEnvironment;
  apiKey:      string;
  timeoutMs?:  number;          // default 30 000
  baseUrl?:    string;          // overrides the environment URL
  fetch?:      typeof fetch;    // custom fetch; see Runtime support
}

client.getAssets()

GET /sdk/assets — returns all publicly listed security tokens that have an Open Fund deployed. See Fund availability. Each row is one token on one chain.

const { data, count, unavailable_funds } = await client.getAssets();

for (const asset of data) {
  console.log(asset.token_name, asset.issuer?.legal_name);
}

for (const fund of unavailable_funds) {
  console.warn(`fund ${fund.fund_address} on ${fund.network_id}: ${fund.reason}`);
}
interface SdkAssetsResponse {
  data:              SdkSecurityDetails[];
  count:             number;                 // data.length
  unavailable_funds: SdkUnavailableFundState[];
  unavailable_count: number;                 // unavailable_funds.length
}

interface SdkUnavailableFundState {
  fund_address:  string;
  network_id:    string;
  token_address: string;
  reason:        string;  // e.g. "CURRENT_ONCHAIN_STATE_UNAVAILABLE"
}

The API reads each fund's current state on-chain before responding. When that read fails (RPC outage, contract mid-upgrade) the fund's token is left out of data and reported in unavailable_funds instead, so a marketplace can show "temporarily unavailable" rather than stale prices. The request itself still succeeds.


client.getAssetByTokenAddress(tokenAddress)

GET /sdk/assets/{token_address} — returns a single asset by its on-chain token address. The response is a single SdkSecurityDetails object that contains the token, issuer, primary book, and network details all in one place.

const { data } = await client.getAssetByTokenAddress("0xabc…");

console.log(data.token_name);
console.log(data.rule_engine?.name);   // present if token has compliance rules
console.log(data.book?.status);        // always present: unfunded tokens are not returned
console.log(data.network.name);
interface SdkAssetResponse {
  data:              SdkSecurityDetails;
  unavailable_funds: SdkUnavailableFundState[];
  unavailable_count: number;
}

Throws NotFoundError when no token with that address exists, when it has no fund, or when every fund's on-chain state is unavailable. A multichain token shares one address across chains; for such an address the API answers HTTP 400 (HttpError) because the chain is ambiguous. Use getAssets() / getAssetsByIssuer() and match on (network_id, token_address) for multichain tokens.


client.getAssetsByIssuer(issuerId)

GET /sdk/assets/issuer/{issuer_id} — returns all assets belonging to a specific issuer that have an Open Fund deployed. The issuerId is the id field from SdkIssuerSummary (the issuer's hex-encoded MongoDB ObjectId).

const { data, count } = await client.getAssetsByIssuer("64f1a2b3c4d5e6f7a8b9c0d1");

console.log(`${count} tokens from this issuer`);
data.forEach(asset => console.log(asset.token_symbol));

Returns the same SdkAssetsResponse envelope as getAssets(). Throws NotFoundError when the issuer does not exist and HttpError (HTTP 400) when issuerId is not a valid 24-character hex id.


client.getNetworks()

GET /sdk/networks — returns every network the API supports, keyed by network_id. Use it to resolve names, chain ids, RPC and explorer URLs for the network_id values on assets.

const { data } = await client.getNetworks();

const sepolia = data["ethereum_sepolia"];
console.log(sepolia?.name, sepolia?.chain_id, sepolia?.explorer_urls[0]);
interface SdkNetworksResponse {
  data:  Record<string, NetworkDetails>;  // keyed by network_id
  count: number;
}

client.getComplianceFactories()

GET /sdk/compliance-factories — returns the chain-wide ERC-3643 (TREX) and identity infrastructure deployed on each network, keyed by network_id. Investor-onboarding flows use these addresses (ID factory, gateway, claim issuer) to create and register on-chain identities. A token's own registries are on SdkSecurityDetails; never substitute these chain-wide addresses for them.

const { data } = await client.getComplianceFactories();

const factory = data["ethereum_sepolia"];
console.log(factory?.id_factory, factory?.gateway, factory?.claim_issuer);
interface SdkComplianceFactoriesResponse {
  data:  Record<string, ComplianceFactoryDetails>;  // keyed by network_id
  count: number;
}

interface ComplianceFactoryDetails {
  deployer:                              string;
  salt:                                  string;
  timestamp:                             string;
  identity_implementation:               string;
  implementation_authority:              string;
  id_factory:                            string;
  gateway:                               string;
  trex_implementation_authority:         string;
  erc3643_token_impl:                    string;
  erc3643_modular_compliance_impl:       string;
  erc3643_identity_registry_storage:     string;
  erc3643_claim_topics_registry:         string;
  erc3643_trusted_issuers_registry:      string;
  erc3643_identity_registry:             string;
  claim_issuer:                          string;
  claim_issuer_management_key:           string;
  claim_signer_address:                  string;
  token_implementation:                  string;
  modular_compliance_implementation:     string;
  trex_factory_implementation_authority: string;
  identity_policy_factory?:              string | null; // CMTA identity-policy installer
  trex_factory:                          string;
  trex_gateway:                          string;
}

client.getKycTiers()

GET /sdk/kyc_tiers — returns the KYC tiers an investor can hold, keyed by tier id ("tier_1", "tier_2", …). An asset's kyc_tier is one of these keys; compare an investor's verified claims with the tier's claim_topics to decide whether they may invest.

const { data: tiers } = await client.getKycTiers();
const { data: asset } = await client.getAssetByTokenAddress("0xabc…");

const tier = asset.kyc_tier ? tiers[asset.kyc_tier] : undefined;
console.log(tier?.name, tier?.claim_topics, tier?.limits.daily_investment_limit_usd);
interface SdkKycTiersResponse {
  data:  Record<string, KycTier>;  // keyed by tier id
  count: number;
}

interface KycTier {
  id:           string;
  name:         string;
  claim_topics: number[];          // required topics; never infer from claim_id
  claim_id:     number;            // legacy ordinal
  limits:       KycTierLimits;
  verification: KycTierVerification;
}

interface KycTierLimits {
  daily_investment_limit_usd:   number;
  monthly_investment_limit_usd: number;
}

interface KycTierVerification {
  identity_verified:        boolean;
  liveness_verified:        boolean;
  aml_verified:             boolean;
  pep_check:                boolean;
  address_verified:         boolean;
  tax_verified:             boolean;
  source_of_funds_verified: boolean;
  business_verification:    boolean;
}

Listings (preview)

Not yet served by the API. The three listing methods below target /sdk/listings*, which no API environment serves yet; today they fail with NotFoundError. Use getAssets() / getAssetsByIssuer() until the CHANGELOG announces listing support.


client.listListings(options?)

GET /sdk/listings — returns chain-independent listings with cursor pagination. Each listing groups all per-chain deployments of the same instrument under a single asset_id. Only listings with a fund deployed on at least one chain are returned, and deployments / available_networks only contain the chains that have one. See Fund availability.

const { data, next_cursor, has_more } = await client.listListings({
  network_id: "ethereum_sepolia", // optional filter
  issuer_id: "org_1",             // optional filter
  standard: "cmtat",              // optional filter
  updated_since: "2024-01-01T00:00:00Z", // optional ISO-8601
  limit: 100,                     // integer 1–200, default 50
  cursor: "prev_cursor",          // optional cursor for next page
});

for (const listing of data) {
  console.log(listing.name, listing.symbol, listing.listing_state);
  console.log(`  ${listing.deployments.length} deployments`);
}
interface SdkListListingsOptions {
  network_id?:    string;
  issuer_id?:     string;
  standard?:      string;
  updated_since?: string;  // ISO-8601
  limit?:         number;  // integer 1–200, default 50
  cursor?:        string;
}

interface SdkListingsResponse {
  data:        SdkListing[];
  next_cursor: string | null;
  has_more:    boolean;
}

client.getListing(assetId)

GET /sdk/listings/{asset_id} — returns a single listing by its chain-independent asset ID.

const { data } = await client.getListing("asset_1");

console.log(data.name, data.symbol);
console.log(`Fund deployed on: ${data.available_networks.join(", ")}`);
data.deployments.forEach(dep => {
  console.log(`  ${dep.network}: ${dep.book_state}`);
});
interface SdkListingResponse {
  data: SdkListing;
}

client.getListingByTokenAddress(tokenAddress, options?)

GET /sdk/listings/by-address/{token_address} — returns the listing that owns the given on-chain token address. Pass network_id when the same address exists on multiple chains; omitting it when ambiguous returns HTTP 409 ambiguous_address.

const { data } = await client.getListingByTokenAddress("0xabc…", {
  network_id: "ethereum_sepolia",
});

console.log(data.asset_id, data.name);

Fund availability

Issuers approve cross-listing through the SDK by creating an Open Fund, so a token without a fund is private and is never exposed. The client enforces this on every response, even if the API returns more:

  • A chain counts as funded when its book has a fund address, belongs to that same network (a multichain token shares one address across chains, so another chain's book never counts), is the book of that same token (0x addresses compared case-insensitively, other formats exactly), and, for listing deployments, book_state is "active".
  • getAssets, getAssetsByIssuer and listListings drop unfunded rows. count on asset lists is recomputed; a listListings page can hold fewer than limit items, so keep paging while has_more is true.
  • listListings, getListing and getListingByTokenAddress return only the funded chains in deployments and available_networks.
  • getAssetByTokenAddress, getListing and getListingByTokenAddress throw NotFoundError (status 404, no details) for an unfunded asset, exactly as for an asset that does not exist.

Every returned SdkSecurityDetails and SdkListing carries has_fund: true.


Response shape

Every API method returns one or more SdkSecurityDetails objects or SdkListing objects. Field additions are recorded in CHANGELOG.md; additions are always optional so existing consumers keep compiling.

SdkListing

Chain-independent listing that groups all per-chain deployments of the same instrument under a single asset_id.

interface SdkListing {
  asset_id:        string;
  issuer:          SdkIssuerSummary | null;
  name:            string;
  symbol:          string;
  decimals:        number;
  standard:        string;       // e.g. "cmtat" | "erc3643"
  asset_category:  string | null;
  apy:             number | null;
  kyc_tier:        string | null;
  claim_topics:    SdkClaimTopic[] | null;
  icon_url:        string | null;
  prospectus:      SdkTokenProspectus | null;
  partners:        SdkTokenPartner[] | null;
  verify:          boolean;
  listing_state:   SdkListingState;
  available_networks: string[];         // only networks with a deployed fund
  parity:          SdkDeploymentParity;
  deployments:     SdkDeployment[];      // only chains with a deployed fund
  has_fund?:       boolean;              // set by the client; always true
}

type SdkListingState = "draft" | "pending_review" | "listed" | "delisted" | "suspended";

interface SdkDeploymentParity {
  status:      string;
  computed_at: string | null;
}

SdkDeployment

Per-chain token deployment within a listing. Contains compliance details, book information, and availability state.

interface SdkDeployment {
  deployment_id:  string;
  network_id:     string;
  chain_id:       number | null;
  network:        string;       // human-readable network name
  token_address:  string;
  token_admin:    string;
  paused:         boolean;
  listed:         boolean;
  compliance:     SdkDeploymentCompliance;
  book:           SdkBookSummary | null;
  book_state:     SdkDeploymentBookState;
}

type SdkDeploymentBookState = "active" | "unavailable" | "not_deployed" | "error";

interface SdkDeploymentCompliance {
  rule_engine:      string | null;
  rules:            string[];
  identity_policy:  string | null;
  document_engine:  string | null;
  snapshot_engine:  string | null;
}

SdkSecurityDetails

Full token details with issuer, book, and network flattened into a single object. org_id is the issuer organisation id (the same value as issuer.id). Internal and sensitive fields are intentionally excluded (id, deployment_txn_hash, token_program_id, engines (raw), extra_information_attributes, allowlist_manager, iota_* fields, individual_token_price, rule_engine_id, updated_at).

interface SdkSecurityDetails {
  org_id:        string;
  token_address: string;
  token_name:    string;
  token_symbol:  string;
  token_decimal: string;
  network_id:    string;
  token_type:    string;       // e.g. "cmtat_standard" | "cmtat_debt" | …
  isin?:         string | null; // assigned ISIN; SDK client returns null when unassigned
  admin:         string;       // token admin wallet address
  icon_url:      string | null;
  prospectus:    SdkTokenProspectus | null;
  prospectus_summary: string | null;
  issuer:        SdkIssuerSummary | null;
  book:          SdkBookSummary | null;
  partners:      SdkTokenPartner[]  | null;
  rule_engine:   SdkRuleEngineSummary | null;  // present when token has compliance rules
  identity_mode: "trex_native" | "cmta_policy" | "legacy_unmanaged" | "none";
  identity_policy: SdkIdentityPolicySummary | null;
  identity_contracts?: SdkIdentityContracts | null;
  network:       NetworkDetails;
  compliance_factory: ComplianceFactoryDetails | null; // chain-wide infra; see getComplianceFactories()
  created_at:    string | null;
  claim_topics:  SdkClaimTopic[] | null;
  kyc_tier?:     string | null; // explicit; not derived from claim count
  trex_issuers:  string[] | null;
  // Token-specific TREX suite addresses. Legacy records may be null.
  trex_identity_registry_address:         string | null;
  trex_identity_registry_storage_address?: string | null;
  claim_topics_registry_address:          string | null;
  trex_trusted_issuers_registry_address:  string | null;
  trex_modular_compliance_address?:       string | null;
  identity_readiness_status?:             "ready" | "degraded" | null;
  identity_readiness_failures?:           string[] | null;
  external_claim_topics?:                 number[] | null;
  asset_category: string | null;
  apy:            number | null;
  // Asset correlation (additive since 0.3.4; see below)
  asset_id?:      string | null;
  deployment_id?: string | null;
  chain_id?:      number | null;
  has_fund?:      boolean;       // set by the client; always true
}
interface SdkTokenProspectus {
  name: string;
  url:  string;
}

interface SdkTokenPartner {
  partner_name: string;
  partner_logo: string;
  partner_role: string;
}

interface SdkClaimTopic {
  value: number;   // on-chain claim topic id
  name:  string;   // e.g. "kyc_approved"
  label: string;   // human-readable
}

Asset correlation fields (additive since 0.3.4)

One real-world security can be issued as one token per chain. The API correlates those per-chain token rows under a single chain-independent asset. Every /sdk/assets* response keeps one row per token (per chain) and its existing envelope; the three fields below are simply added to each row so consumers can group rows that belong to the same instrument.

| Field | Type | Meaning | |-------|------|---------| | asset_id | string \| null | Id of the asset this token row belongs to. Rows on different chains that share an asset_id are the same instrument. | | deployment_id | string \| null | Id of this per-chain token row (deployment) within its asset. | | chain_id | number \| null | Numeric EVM chain id of the deployment. null on non-EVM networks. |

All three are optional and nullable. They are absent on older API deployments and null until the API has correlated a row, so code written against 0.3.3 keeps working unchanged. Always key on (network_id, token_address) or deployment_id, never on a bare address: the same token address can exist on more than one chain.

const { data } = await client.getAssets();

const byAsset = new Map<string, SdkSecurityDetails[]>();
for (const row of data) {
  const key = row.asset_id ?? `${row.network_id}:${row.token_address}`;
  byAsset.set(key, [...(byAsset.get(key) ?? []), row]);
}

TREX registry fields describe the token's own suite. They are null when a legacy token has not been backfilled; chain-wide infrastructure registries are never substituted as token policy addresses.

SdkRuleEngineSummary

When a token has an associated compliance rule engine, it is included in the security details. Only the name, address, and a slim view of each linked rule are exposed.

interface SdkRuleEngineSummary {
  name:                string;
  rule_engine_address: string;
  rules:               SdkRuleSummary[];
}

interface SdkRuleSummary {
  rule_address:              string;
  rule_type:                 string;  // e.g. "whitelist" | "blacklist" | "identity_registry" | …
  identity_policy_id?:       string | null; // present for CMTA identity rules
  identity_registry_address?: string | null; // resolved from the saved policy, not user-entered
  identity_policy?:           SdkIdentityPolicySummary | null; // exact immutable policy snapshot
  identity_policy_claim_topics?: number[] | null; // exact enforced policy topics
  config_metadata?:          Record<string, unknown> | null;
}

interface SdkIdentityPolicySummary {
  id:      string;
  name:    string;
  version: number;
  claim_topics: number[]; // exact on-chain requirements
  trusted_issuers: SdkIdentityPolicyTrustedIssuer[];
  identity_registry_address:          string | null;
  identity_registry_storage_address:  string | null;
  claim_topics_registry_address:      string | null;
  trusted_issuers_registry_address:   string | null;
  implementation_authority_address:  string | null;
  config_hash:                        string | null;
}

interface SdkIdentityPolicyTrustedIssuer {
  issuer_address: string;
  claim_topics:   number[];
}

identity_mode is authoritative routing metadata. trex_native means the consumer must resolve the registry from the TREX token itself. cmta_policy means it must use the attached policy snapshot. legacy_unmanaged identifies an older raw Identity Rule that cannot be treated as a managed policy.

identity_contracts is an additive, backward-compatible runtime view. It contains the ID factory, gateway, ClaimIssuer, authoritative Identity Registry, and exact required topics for both supported modes. CMTA responses additionally contain the policy-specific registry suite plus Rule Engine, Identity Rule, and policy identifiers. TREX responses never substitute chain-wide registry addresses for the token's own registry and omit suite/storage or modular-compliance contracts that investor onboarding does not consume. CMTA responses never include TREX factory implementation contracts.

Rule types:

| Value | Description | |-------|-------------| | whitelist | Only allow-listed addresses can hold the token | | blacklist | Blocked addresses cannot hold the token | | sanctions_list | Integrates with an external sanctions oracle | | conditional_transfer_light | Light conditional transfer checks | | erc2980 | ERC-2980 royalty enforcement | | identity_registry | On-chain identity linking | | max_total_supply | Total supply cap | | spender_whitelist | Approved spenders only | | whitelist_wrapper | Enhanced whitelist variant |

SdkIssuerSummary

Public-facing details about the organisation that issued the token.

interface SdkIssuerSummary {
  id:           string;
  legal_name:   string | null;
  display_name: string | null;
  jurisdiction: string | null;
  website:      string | null;
  logo_url:     string | null;
}

SdkBookSummary

Fund (order book) details attached to the token. The only wallet address in this response is the optional manager_wallet. Protocol subscription fee policy and the protocol fee recipient remain private backend/deployment configuration and are not part of SdkFundConfig.

type IssuanceStatus = "ACTIVE" | "SOFT_CLOSED" | "TERMINATED";

interface SdkFundConfig {
  nav_staleness_threshold:       string;
  min_subscription:              string;
  min_redemption:                string;
  entry_fee_bps:                 string;
  exit_fee_bps:                  string;
  approval_required:             boolean;
}

interface SdkBookSummary {
  id:                   string | null;
  organization_id:      string;
  name:                 string | null;
  book_type:            string | null;  // e.g. "open"
  token_address:        string;
  network_id:           string;
  settlement_token:     string;
  settlement_token_name:   string | null;  // e.g. "USD Coin"
  settlement_token_symbol: string | null;  // e.g. "USDC"
  order_book_address:   string;
  fund_address:         string;
  fund_id:              string;
  initial_nav:          string;
  deployment_txn_hash:  string | null;
  fund_config:          SdkFundConfig;
  status:               IssuanceStatus;
  paused:               boolean;
  visibility:           string | null;
  target_raise?:        string | null;  // raw settlement token units
  target_raise_deadline?: string | null; // ISO-8601 close date/time
  created_at:           string | null;
  // Asset correlation (additive since 0.3.4); same meaning as on SdkSecurityDetails
  asset_id?:            string | null;
  deployment_id?:       string | null;
  chain_id?:            number | null;
  // Network family (additive since 0.8.0)
  family?:              string | null;  // "ethereum" | "solana"
  solana?:              SdkSolanaFundAccounts | null;  // only when family is "solana"
  manager_wallet?:      string | null;  // manager recorded at creation
}

interface SdkSolanaFundAccounts {
  fund_program_id:          string;  // the sereel_open_fund program
  hook_program_id?:         string | null;  // legacy hook, normally absent
  registry:                 string;
  fund_id:                  string;  // u64 as a decimal string
  share_mint:               string;  // equals token_address
  share_token_program:      string;  // Token-2022
  settlement_token_program: string;  // legacy SPL Token
  custody:                  string;
  escrow:                   string;
  extra_account_meta_list?: string | null;
  total_claims_shares?:     string | null;
  share_mint_authority?:    string | null;
  lookup_table?:            string | null;
  idl_version:              string;  // e.g. "1.0.0"
}

asset_id, deployment_id and chain_id on a book mirror the owning token row: a book belongs to exactly one deployment on one chain. They are optional and nullable for the same reasons as on SdkSecurityDetails.

family, solana and manager_wallet are additive since 0.8.0 and absent on older API deployments, which only serve EVM books. For a Solana book:

  • fund_address and order_book_address are the fund account, token_address is the share mint, settlement_token is the settlement mint, chain_id is null, and solana carries the program ids and the fund's fixed accounts.
  • Identify a fund by (network_id, fund_address), never by a bare address and never by chain_id.
  • Solana addresses are base58 and case-sensitive. Never lowercase them. The client compares hex addresses case-insensitively and everything else exactly.
  • The client rejects a response whose solana addresses are not base58-shaped, and a book that says family: "solana" without solana.

NetworkDetails

On-chain network the token is deployed on.

interface NetworkDetails {
  network_id:              string;
  name:                    string;
  family:                  string;    // e.g. "ethereum" | "solana" | "iota"
  chain_id:                number | null;
  native_currency:         NativeCurrency;
  rpc_endpoint:            string;
  explorer_urls:           string[];
  is_testnet:              boolean;
}

interface NativeCurrency {
  symbol:   string;
  name:     string;
  decimals: number;
}

Contract ABIs

The package also ships the canonical SereelOpenFund ABIs, generated mechanically from the book contract repo. For each contract there are four exports: OPEN_FUND_ABI / OPEN_FUND_FACTORY_ABI (the ABI, typed as const for viem/abitype), *_ABI_VERSION (the contract's version() as declared in its Solidity source; compare it with version() on chain before relying on revision-specific behaviour), *_ABI_SHA256 (SHA-256 of JSON.stringify(abi) over the array, so you can verify the module is intact) and *_ABI_SOURCE_COMMIT (the last book commit that touched abis/ or src/open/ when the ABI was generated, with a -dirty suffix if those paths had uncommitted changes). To refresh them after a contract change, check out book next to this repo (or point SEREE_BOOK_ROOT at it) and run pnpm run abis; pnpm run abis:check exits non-zero when the committed ABI, version or digest no longer match a fresh generation (the recorded commit is not compared, so unrelated book commits do not fail it) and runs on prepublishOnly, where it fails when the book checkout is absent, so a publish can never ship an unverified ABI. pnpm run abis:check:local skips the check with a warning when book is absent, for local work only.

| Contract | ABI | Version | Digest | Source commit | |----------|-----|---------|--------|---------------| | SereelOpenFund | OPEN_FUND_ABI | OPEN_FUND_ABI_VERSION | OPEN_FUND_ABI_SHA256 | OPEN_FUND_ABI_SOURCE_COMMIT | | SereelOpenFundFactory | OPEN_FUND_FACTORY_ABI | OPEN_FUND_FACTORY_ABI_VERSION | OPEN_FUND_FACTORY_ABI_SHA256 | OPEN_FUND_FACTORY_ABI_SOURCE_COMMIT |

import { OPEN_FUND_ABI, OPEN_FUND_ABI_VERSION } from "@sereel/sdk";

const onChain = await client.readContract({ address, abi: OPEN_FUND_ABI, functionName: "version" });
if (onChain !== OPEN_FUND_ABI_VERSION) throw new Error(`fund runs ${onChain}, SDK ABI is ${OPEN_FUND_ABI_VERSION}`);

navChangeFromInitial(nav, initialNav) returns the change of a NAV against the fund's initial NAV in basis points (500 is +5.00%), truncated toward zero, or null when initialNav is not positive. Both values must be in the same units. It works for both fund families and is also exported from @sereel/sdk/solana.


Solana Open Fund programs

A Solana Open Fund is two Anchor programs: sereel_open_fund (registry, funds, orders, NAV, settlement and returned-share claims, redemption locks) and the legacy sereel_lock_hook interface (unused by Open Fund 1.0). The SDK carries their whole client interface, so applications never hand-encode an instruction or copy a byte layout.

IDLs (root entry, no dependencies)

Generated mechanically from the solana_fund program repo, like the ABIs:

| Program | IDL | Version | Digest | Source commit | |---------|-----|---------|--------|---------------| | sereel_open_fund | OPEN_FUND_IDL | OPEN_FUND_IDL_VERSION | OPEN_FUND_IDL_SHA256 | OPEN_FUND_IDL_SOURCE_COMMIT | | sereel_lock_hook | LOCK_HOOK_IDL | LOCK_HOOK_IDL_VERSION | LOCK_HOOK_IDL_SHA256 | LOCK_HOOK_IDL_SOURCE_COMMIT |

SUPPORTED_OPEN_FUND_IDL_VERSIONS ('1.0.0', '1.1.0') lists the interface versions a fund's solana.idl_version may report; solanaFundContextFromBook refuses any other. 1.1.0 only adds events to 1.0.0.

*_IDL_VERSION is the program version (metadata.version); both programs always carry the same one. *_IDL_SHA256 is the SHA-256 of the IDL file as anchor build wrote it, which is JSON.stringify(idl, null, 2), so you can recompute it from the export. *_IDL_SOURCE_COMMIT is the last solana_fund commit that touched the IDL package.

The address inside an IDL is a build-time placeholder, not a deployment. Program ids differ per network: take them from book.solana (or the platform registry) and pass them in.

To refresh after a program change, check out solana_fund next to this repo (or point SEREE_SOLANA_FUND_ROOT at it) and run pnpm run idls. It also regenerates the derived types and the golden vectors the tests run against, and refuses to generate when the vectors were produced from different IDL files. pnpm run idls:check exits non-zero on drift and runs on prepublishOnly; pnpm run idls:check:local skips with a warning when the program repo is absent.

@sereel/sdk/solana

The program interface lives in a subpath so the root entry stays free of dependencies. It needs @solana/web3.js v1 (an optional peer dependency):

pnpm add @sereel/sdk @solana/web3.js@^1.99.0

Unlike the REST client, this subpath holds no secret and runs in a browser.

import { Connection, PublicKey } from "@solana/web3.js";
import {
  readSolanaOrderState,
  verifiedOrderInstruction,
  verifySolanaOrder,
} from "@sereel/sdk/solana";

// `book` is an SdkBookSummary with family "solana" (from a listing or asset).
const expectation = {
  genesisHash,                       // pinned for book.network_id by the platform
  programs: {                        // the platform registry's ids for that network
    fundProgramId: new PublicKey(registry.fund_program_id),
    hookProgramId: registry.hook_program_id ? new PublicKey(registry.hook_program_id) : null,
  },
  book,
};
const intent = { side: "subscribe" as const, investor, amount: 1_000_000_000n, slippageBps: 500, ttlSeconds: 7 * 86_400 };

const state = await readSolanaOrderState(connection, expectation, intent); // fresh reads
const order = verifySolanaOrder(expectation, intent, state);               // throws on any failed check
const instruction = verifiedOrderInstruction(order);                       // subscribe, ready to sign

Addresses. solanaFundContextFromBook(book) derives every fixed address of a fund from the book's program ids and fund id and refuses a payload whose addresses do not match their derivation (SolanaFundContextError). solanaFundContext(programs, fundId, shareMint, settlementMint) derives the same context without a book. solanaFundPdas(programs) exposes each derivation (SolanaFundPdas: registry, fund, canonical mint authority, orders, settlement and share claims, lock ledger and pages, operator, NAV attestation, event authority, the hook's account list); associatedTokenAddress and programDataAddress cover the rest. The types are SolanaFundPrograms and SolanaFundContext.

Instructions. One builder per instruction, each returning a TransactionInstruction with every derivable account filled in:

| Who signs | Builders | |-----------|----------| | Investor | subscribe, redeem, cancelSubscription, cancelRedemption, claimSettlement, claimShares | | Manager or operator | updateNav, processSubscriptions, processRedemptions, rejectOrders, setOrdersApproval, withdrawSettlement, setStatus, pause, burnEscrowSurplus | | Manager | forceUpdateNav, setEntryFee, setExitFee, setLimits, setRedemptionLockPeriod, setMaxNavDeviationBps, setApprovalRequired, setOperator | | Manager or owner | unpause, revokeAllOperators | | Owner | proposeOwner, acceptOwner, setManager, setSettlementTreasury, setProtocolFeeRecipient, setProtocolFeeBps, setOracle, sweepTerminated | | Anyone | depositSettlement, releaseMaturedLocks, initClaim, initShareClaim, initLockPage | | Oracle attestor | postNavAttestation | | Registry and creation (platform) | initializeRegistry, proposeRegistryAuthority, acceptRegistryAuthority, setDeployer, setSettlementMint, createFund |

A manager signs alone; an operator passes asOperator: true (ControllerParams) so its Operator account is included. Batch instructions take strictly ascending ids and at most MAX_BATCH (64); FeeRecipients, OrderToSettle and SubscriptionToProcess describe their inputs, SubscribeParams, RedeemParams and CreateFundParams the larger ones. fundInstruction(programs, name, accounts, args, remaining?) is the typed generic builder underneath (account order and flags come from the IDL), and encodeInstructionData / decodeInstructionData expose the argument codec. Open Fund 1.0 wraps an existing Token-2022 mint, passed as CreateFundParams.shareMint. It creates no share token and requires no transfer hook. activateShareMint(ctx, { manager, currentMintAuthority }) requires both signatures and installs the canonical 1-of-2 multisig [manager, fund]. inspectShareMintPermission checks the live mint and exact multisig before activation is shown as complete. handoffShareMintAuthorityToManager builds an explicit single-admin transfer to the configured manager when a wallet flow cannot co-sign. A different previous admin loses its mint permission. rotateShareMintAuthority builds the manager's direct Token-2022 rotation and rejects the fund as destination; the fund has no rotation instruction. Revoke permission before setManager. No burn grant is needed for fund-owned escrow.

decodeShareClaim decodes returned-unit claims. parseMint includes the mint and freeze authorities, pause, extension compatibility and defaultAccountState, the state the DefaultAccountState extension gives new token accounts ("frozen" on an allowlist mint, null without the extension). parseToken2022Multisig exposes the initialized threshold and members. The snapshot types are TokenProgramAccountSnapshot, ShareMintPermissionState, ShareMintPermissionReason, InspectShareMintPermissionParams, HandoffShareMintAuthorityParams, RotateShareMintAuthorityParams, and Token2022MultisigInfo.

Redemption batches use five remaining accounts per order; rejection uses three. Plans initialize missing ShareClaims for legacy orders. Pass initializedShareClaims containing investor base58 addresses whose canonical claims were validated; otherwise the idempotent initializers are included. Paused minting or missing permission causes eligible subscriptions to reject and refund gross settlement without fees. Returned shares that cannot be delivered remain backed in escrow and can be redirected with claimShares, even while the fund is paused or terminated.

Batches. 64 ids fit an instruction but rarely a transaction (1232 bytes, 64 account locks: MAX_TRANSACTION_BYTES, MAX_ACCOUNT_LOCKS). planProcessSubscriptions, planProcessRedemptions, planRejectOrders and planSetOrdersApproval sort the ids, measure each candidate transaction as web3.js would serialise it (measureTransaction) and split greedily into a BatchPlan of PlannedTransactions. Pass the fund's lookup table in BatchPlanOptions.lookupTables: it holds the fund's fixed accounts, so it helps, but each order still brings its own accounts, which no fixed table can hold. Batch capacity depends on account reuse, optional initializers and compute-budget instructions. The planner measures the actual message; use its resulting transactions rather than a fixed order count. Three ordinary subscriptions fit without compute instructions, two with them.

Compute-budget instructions and a separate fee payer cost a few bytes and may lower these by one. Pass the NAV post in leadingInstructions so the strike and the first batch land atomically; a plan with no transactions carries none of them. For locked subscriptions (SubscriptionToPlan, InvestorLockState) the planner picks each investor's lock page, adds initLockPage when a page does not exist yet, and reports an order whose investor has no free slot (to begin with, or after earlier orders of the same plan took it) as unplaceable with reason LockCapacity.

Accounts. decodeFund, decodeSubOrder, decodeRedOrder, decodeClaim, decodeLockLedger, decodeLockPage, decodeOperator, decodeNavAttestation, decodeRegistry, decodeDeployer, decodeSettlementMintConfig, decodeManagerIndex and decodeManagerFundEntry check the discriminator and length and return typed objects (64-bit integers as bigint, keys as PublicKey); decodeAccount(name, data) is the generic form and SolanaFundDecodeError the failure. fetchFund reads a fund and fails closed when it is not owned by the fund program. isOperatorCurrent, isApprovalCurrent and maturedUnits apply the program's own rules; parseTokenAccount and parseMint read the base token layouts (TokenAccountInfo, MintInfo). FUND_ACCOUNT_LAYOUTS holds each account's size, discriminator and field offsets, and ACCOUNT_OFFSETS the ones used as getProgramAccounts filters.

Listings. listSubOrders, listRedOrders and listOperators return decoded accounts (Listed); ordersOfFundFilters, ordersOfInvestorFilters and operatorsOfFundFilters return the raw filters for an OrderSide. The RPC endpoint must allow filtered getProgramAccounts.

Events. The program emits events as self-CPI inner instructions, not logs. eventsFromTransaction(transaction, fundProgramId) returns every event of a confirmed transaction as FundEventRecords (accepting any TransactionWithInnerInstructions, such as a getTransaction response); decodeEventInstruction and decodeEventData decode raw bytes into a FundEvent. SKIP_REASON and skipReasonName name the OrderSkipped reasons 0 to 12 (SkipReason); ORDER_STATUS and FUND_STATUS name the status codes (OrderStatus, FundStatus).

Quotes. quoteSubscription and quoteRedemption price new orders exactly as the program does; redemption fees are charged in settlement tokens. Use quoteLegacyRedemption only for orders placed under the earlier share-unit fee terms. Quotes throw SolanaFundQuoteError (SolanaFundQuoteErrorCode) where the program would refuse; estimateSubscriptionUnits and estimateRedemptionPayout return 0n instead. Fees round up on Solana and down on EVM: never reuse an EVM quote for a Solana fund. applySlippageFloor derives the minimum output, navStepAllowance and navBandBounds tell a manager how far a routine NAV post may move, and feeCeil, unitScale, withdrawReserve and withinOracleTolerance cover the rest. The shapes are SubscriptionQuoteInput, SubscriptionQuote, RedemptionQuoteInput and RedemptionQuote.

Order verification. verifySolanaOrder(expectation, intent, state) is pure and fail-closed: it throws SolanaOrderVerificationError with a SolanaOrderFailureCode on the first failed check and otherwise returns a VerifiedSolanaOrder whose every value came from fresh state. readSolanaOrderState is the reader (one getMultipleAccountsInfo call), and verifiedOrderInstruction builds the instruction from the verified order. The inputs are SolanaOrderExpectation, SolanaOrderIntent (SolanaOrderSide) and SolanaOrderState.

| Code | Meaning | |------|---------| | cluster_mismatch | the RPC serves a different cluster than the listing's network (genesis hash) | | program_mismatch | the book's program ids are not the platform's, the book's addresses do not derive from them, or the fund account is not in that program | | account_version_mismatch | the fund account is not a layout this SDK understands | | settlement_token_mismatch, fund_token_mismatch, decimals_mismatch | the fund's mints or decimals are not the ones the listing or the order used | | fund_paused, fund_not_active, fund_terminated | dealing is closed for this side | | invalid_amount, below_minimum | the amount is zero, cannot be priced, or is under the fund's minimum | | insufficient_balance | not enough settlement token, or not enough unlocked units (matured tranches in the investor's lock pages are credited) | | insufficient_sol | not enough SOL for the rent of the accounts the order creates plus the fee, or the wallet would be left with a balance that is neither zero nor rent-exempt | | nav_unavailable, invalid_protection, zero_minimum_output, invalid_deadline | the order cannot carry a meaningful minimum output or deadline | | share_account_not_approved | subscriptions only: the wallet's share account or the share mint blocks the mint (the canReceiveShares check, run on the share mint and share account readSolanaOrderState already read; a state without shareReceive skips it) |

A first subscription creates the order, the investor's claim, share account, lock ledger and (for a fund with a lock period) lock page 0, about 0.01 SOL of rent in total, reported as rentLamports. Order rent is not refunded.

Receiving shares. canReceiveShares(connection, ctx, investor) tells whether the investor's side of the share mint is ready before a subscription. It reads the share mint and the investor's Token-2022 share account in one getMultipleAccountsInfo call and returns a ShareReceiveStatus: { ok: true } or { ok: false, reason }. A missing share account is fine unless the mint creates new accounts frozen. The reasons (ShareReceiveBlockReason) follow what processSubscriptions does with the order. ok: true does not cover the fund's mint permission. If the share mint authority is not the [manager, fund] multisig, the program refunds every subscription. Check that with inspectShareMintPermission. ShareReceiveAccounts is the raw mint and account pair that SolanaOrderState.shareReceive carries.

| Reason | Meaning | |--------|---------| | needs_thaw | the wallet has no share account and the mint creates new accounts frozen (an allowlist mint): the issuer must thaw the account first | | ata_frozen | the wallet's share account is frozen; the program rejects and refunds the subscription | | share_mint_paused | the share mint is paused; the program rejects and refunds subscriptions | | unsupported_mint | the share mint or the account at the share-account address is not one the program mints to: not Token-2022, another mint or owner, or uninitialized |

Fund and investor reads. readSolanaFundState(connection, ctx) is the Solana counterpart of the EVM navState(), configuration() and accountingState(). It returns a SolanaFundState: the decoded FundAccount (NAV, fees, minimums, approval, lock period, status, pause, pending order counts and totals, decimals), the share mint (MintInfo: supply, authorities, pause, default account state), the cluster time and navFresh. isNavFresh(fund, now) is the program's NAV gate: a positive NAV no older than navStalenessThreshold seconds, where a threshold of 0 never expires. The reader throws SolanaFundDecodeError when the fund account is missing, not the fund program's, of another version or describes another fund than ctx, when the share mint is not a Token-2022 mint, and when the RPC does not return the clock sysvar.

readSolanaInvestorPosition(connection, ctx, investor) returns a SolanaInvestorPosition: SOL, settlement and share balances, locked, matured and redeemable units, the lock pages to pass to redeem (lockPages), the pages holding matured tranches (maturedPages, for releaseMaturedLocks), the next unlock time, claimable settlement and shares, and every subscription and redemption order of the investor in any status. redeemableUnits is exactly what verifySolanaOrder accepts for a redemption of the same state. The reader makes one getMultipleAccountsInfo call and two filtered getProgramAccounts calls, so the RPC must allow the latter. Missing accounts read as zero. An account at one of the investor's addresses that belongs to another fund, mint, investor or program throws SolanaFundDecodeError.

solanaInvestorMetrics(fund, position) is pure and returns SolanaInvestorMetrics. It takes the fund's nav and shareDecimals and the position's balance and orders, so it reads the persisted order accounts and needs no transaction history. currentValue is the share balance at the fund's NAV. historicalSubscriptions is the gross amount of executed subscriptions. averageSubscriptionNav is their NAV weighted by units received, or null with no executed subscription. pendingSubscriptionAmount is the gross amount of pending and approved subscriptions, and pendingRedemptionUnits the units of pending and approved redemptions.

import {
  canReceiveShares,
  navChangeFromInitial,
  readSolanaFundState,
  readSolanaInvestorPosition,
  redeem,
  solanaFundContextFromBook,
  solanaInvestorMetrics,
} from "@sereel/sdk/solana";

const ctx = solanaFundContextFromBook(book);
const { fund, navFresh } = await readSolanaFundState(connection, ctx);
const position = await readSolanaInvestorPosition(connection, ctx, investor);
const metrics = solanaInvestorMetrics(fund, position);
const changeBps = navChangeFromInitial(fund.nav, BigInt(book.initial_nav));

const receive = await canReceiveShares(connection, ctx, investor);
if (!receive.ok) showReason(receive.reason);                   // e.g. "needs_thaw"

const instruction = redeem(ctx, {
  investor,
  orderId: fund.nextRedOrderId,
  units: position.redeemableUnits,
  minPayout,
  deadline,
  lockPages: position.lockPages,
});

History. listSolanaFundHistory(connection, ctx, options?) returns one SolanaFundHistoryPage of the fund's events. It reads up to limit signatures of the fund account (SolanaFundHistoryOptions: 1 to 100, default 25, else it throws a RangeError) older than before, fetches the successful transactions with getTransactions (one JSON-RPC batch of up to limit calls, and some providers cap the batch size) and decodes their events with eventsFromTransaction; it never parses logs. Each SolanaFundHistoryEntry is a FundEventRecord with the transaction's signature, slot and blockTime, newest transaction first. Events of other funds and registry events are dropped. With investor, the page keeps events that name the wallet as investor, beneficiary, claimant or recipient, and order events without an investor field (approval, cancellation, rejection, skip, unapproval, redemption fee lock) whose order account belongs to the wallet; those order accounts cost one extra getMultipleAccountsInfo call per 100 orders. A page can be empty and still continue: pass nextBefore as before until it is null. Old transactions need an archival RPC; the call throws when the node returns no transaction for a signature, rather than skipping it.

Constants and errors. TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID, SYSTEM_PROGRAM_ID and BPF_LOADER_UPGRADEABLE_PROGRAM_ID are the well-known ids; SEEDS, EVENT_IX_TAG, REMAINING_ACCOUNT_STRIDES, ACCOUNT_VERSION, BPS_BASE, DAY_SECONDS, MAX_LOCK_PAGES, TRANCHES_PER_PAGE, MAX_DECIMALS, MAX_ENTRY_EXIT_FEE_BPS, MAX_PROTOCOL_FEE_BPS, MAX_LOCK_SECONDS, MAX_NAV_STALENESS_SECONDS, MAX_SHARE_NAME_BYTES, MAX_SHARE_SYMBOL_BYTES and MAX_SHARE_URI_BYTES mirror the programs. fundProgramError(code) maps a custom error code to its name and message (FundProgramError, from FUND_ERRORS), and FUND_INSTRUCTION_NAMES maps builder names to IDL names. The decoded account, event and argument types (FundAccount, SubOrderAccount, OrderSkippedEvent, CreateFundArgs, ...) are generated from the IDL and exported from the same subpath.

Every byte this subpath produces or reads is tested against golden vectors generated by the program repo from the real program crates: every address derivation, every instruction's data and account list, every account layout, every event and the quote cases.


Errors

All errors extend SereelSdkError, which carries status (HTTP status, when there was a response), code and details (the parsed error body, or the validation failures for MalformedResponseError). Every HTTP error class extends HttpError.

Validation failures are reported as { path, expected, received }, where received is only the type of the value found ("string", "null", "array", …). Validation runs before the fund filter, so errors never carry response values: a malformed response for an unfunded token reveals nothing about it.

| Class | When thrown | |-------|-------------| | InvalidConfigurationError | Bad createClient options or empty method arguments. Thrown synchronously, before any request. | | HttpError | Any other non-2xx response, e.g. HTTP 400 for an ambiguous multichain address or a malformed issuer id. Base class of the five below. | | UnauthorizedError | API key missing, invalid, revoked or inactive (HTTP 401) | | ForbiddenError | HTTP 403. Not returned by the SDK endpoints today; handled for forward compatibility. | | NotFoundError | Asset or issuer not found, or the asset has no fund (HTTP 404) | | RateLimitError | Too many requests (HTTP 429); back off and retry | | ServerError | Unexpected server error (HTTP 5xx); safe to retry | | NetworkError | The request never got a response (DNS, TLS, connection reset) | | TimeoutError | Request exceeded timeoutMs | | MalformedResponseError | Response body is not JSON or doesn't match the expected shape. Usually an SDK/API version mismatch. |

An unfunded token raises NotFoundError with no details, exactly as a token that does not exist, so the error never reveals that it exists.

import {
  NotFoundError,
  UnauthorizedError,
  createClient,
} from "@sereel/sdk";

try {
  const asset = await client.getAssetByTokenAddress("0xmissing");
} catch (err) {
  if (err instanceof NotFoundError) {
    console.log("Token not found");
  } else if (err instanceof UnauthorizedError) {
    console.log("Check your API key");
  } else {
    throw err;
  }
}

Runtime support

The SDK is framework-agnostic and relies on the platform fetch API (Node ≥ 18, Deno, Bun, edge runtimes). The root entry has no dependencies at all; only the @sereel/sdk/solana subpath needs @solana/web3.js. The REST client must still run server-side because of the API key (see Authentication). In older runtimes, pass a compatible implementation:

import fetch from "node-fetch";

const client = createClient({
  environment: "testnet",
  apiKey: process.env.SEREEL_SDK_API_KEY!,
  fetch: fetch as unknown as typeof globalThis.fetch,
});