Skip to content

TypeScript SDK

@candledottv/agent-sdk is a typed, fetch-based client with a small set of audited crypto dependencies, for the whole agent rail: launch configuration, launches (blocking or async), job polling, market state, quotes, feed reads, verification, activity reporting, agent profiles, and image uploads. It runs on Bun and Node 18+.

Terminal window
npm install @candledottv/agent-sdk # or: bun add @candledottv/agent-sdk

The source lives in the public candledottv/agentic repo if you would rather vendor it or read along.

import { CandleClient } from "@candledottv/agent-sdk"
const candle = new CandleClient({
apiUrl: "https://api.alpha.candle.tv",
apiKey: process.env.CANDLE_AGENT_API_KEY, // cndl_live_... or cndl_test_...
})
const { imageUrl } = await candle.uploadImage(pngBytes, "image/png")
const launch = await candle.launch({
chain: "solana",
quoteAsset: "sol",
mode: "open",
name: "Trend Coin",
symbol: "TREND",
imageUrl,
buy: "0.001", // SOL
})
console.log(launch.mint, launch.links.candle)

clientLaunchId is generated for you when you omit it, so the retry policy below has a stable identity to reuse. The result carries it as launch.clientLaunchId, and so does any error the call throws: see Idempotency and retries.

candle.tokenPages reads About and immutable section history, and submits claims, section edits, restores and flags, and holder updates and comments. The methods are in the published package (0.6.14). Token page switches default off, updates and comments each behind their own; a server can return 404 or feature_off.

MethodAccessResult
about(token)Public, no key sentTokenAbout, with public feature switches
burns(token, { cursor, limit })Public, CNDL onlyAboutBurnHistory
history(token, section, { cursor, limit })Public, no key sentAboutHistory, including tombstones
capabilities(token)token-pages:readPrivate AboutCapabilities
creatorChallenge(token)token-pages:writeExact message, challenge ID and expiry
claim(token, body, options)token-pages:writeClaim result and idempotency key
setSection(token, section, body, options)token-pages:writeNew version ID/revision and idempotency key
restoreSection(token, section, body, options)token-pages:writeNew version ID/revision and idempotency key
flag(token, body, options)token-pages:writeFlag result and idempotency key
updates(token, { cursor, limit })Public, no key sentAboutUpdates: holder updates, newest first
postUpdate(token, { text }, options)token-pages:writeAn immutable holder update: its id and sequence
comments(token, { cursor, limit })Public, no key sentAboutComments, newest first, with tombstones
postComment(token, { text }, options)token-pages:writeAn immutable comment under the 0.5% holding rule; never pushed to holders
deletePost(token, id, options)token-pages:writeDeletes your own update or comment
seen(token) / markSeen(token, visibleUpdateSequence, options)Keyed (sends the API key)Which holder updates this account has seen

The token is { chain: "solana" | "hood", address: string }; sections are thesis, tokenomics and lore. History and burn pagination accepts a returned opaque cursor and a limit from 1 to 50. Revisions and raw amounts remain strings. Reads bypass caches; capabilities are never folded into public About. Hidden/removed history bodies stay null. The API validates strict bodies, text limits, fresh eligibility and restrictions on every write. Existing keys gain no scope automatically. Claim/edit/restore require 0.5% of current supply; any positive eligible balance can flag.

const token = { chain: "solana" as const, address: mint }
const about = await candle.tokenPages.about(token)
const capabilities = await candle.tokenPages.capabilities(token)
// Persist this key and the draft before sending; a rerun must reuse both.
const idempotencyKey = crypto.randomUUID()
if (about.features.edit && capabilities.canEdit) {
const saved = await candle.tokenPages.setSection(token, "thesis", {
text: "Our thesis",
baseRevision: about.sections.thesis?.revision ?? "0",
}, { idempotencyKey })
console.log(saved.data.revision, saved.idempotencyKey)
}

Claim explicitly with { kind: "holder" } or { kind: "creator", challengeId?, signature? }. A known creator may need no additional signature. Otherwise call creatorChallenge, sign the exact UTF-8 message locally and pass its challenge ID and signature in a separate creator claim. Solana signatures use base64; Hood uses the 65-byte 0x message signature. No method signs, creates a transaction, requests a private key, implicitly claims or automatically restores on conflict. Challenges are attempted once and expire after five minutes.

Restore takes { versionId, baseRevision } and appends a new version; it never rewrites history. Flag takes { contentId, reason, detail? } for an exact version, with reason spam, scam, abuse, misleading, unsafe_link or other. Restoring a removed/unsafe version is refused.

Every content write sends Idempotency-Key from options.idempotencyKey or a generated UUID and returns { data, idempotencyKey }. A connection or interrupted-body failure retries once with the same key and serialized body. HTTP refusals are not retried. TokenPageError extends CandleApiError: branch on code and status, retain idempotencyKey, inspect latest for revision_conflict, and respect retryAfterHeader on rate limits. Two missing answers or an invalid success produce OUTCOME_UNKNOWN; explicitly replay the same request/key to recover its result. A conflict leaves the caller’s draft untouched. Feature-off, missing scope/auth, insufficient holding, expired/replayed proof, unsafe text, unavailable eligibility and old-server errors remain refusals for the caller to handle. Do not log content bodies, credentials or creator signatures.

launch() and dryRunLaunch() take the shared generated launch fields. Omit wallet or use wallet: "embedded" to pay from the account’s embedded wallet. Name a TEE wallet by label, id or address, or pass { linkedWalletId, privyWalletId } for an existing SDK integration. A named wallet’s chain is inferred; supply chain: "hood" for an explicit Hood wallet object. Conflicting chains or quote assets are refused before building. The SDK uses your configured privyAppId and secretStore for TEE signing, and solanaRpcUrl / evmRpcUrl for caller broadcasts.

await candle.launch({
wallet: "spider-01",
name: "Trend Coin",
symbol: "TREND",
imageUrl: "https://example.com/logo.png",
buy: "0.1", // optional, whole units of the quote asset (SOL by default)
})

buy is a decimal string: SOL has 9 decimals, USDC/CNDL/USDG 6, ETH 18. Empty or zero means no first buy. Excess precision and passing both buy and deprecated raw buyAmount are refused locally. socials accepts only website, twitter, telegram and discord, each an http(s) URL. The remaining limits, defaults and field help come from the shared launch definition; the server validates ranges and eligibility.

On Hood, where the server has HOOD_GEN2_LAUNCH_ENABLED on, launch() and dryRunLaunch() send the generation 2 options as top-level request keys (never nested under hoodGen2Options): launchRules (including snipeFeeStartBps 0 to 2500 paired with snipeFeeDecaySecs 0 to 600, and up to 10,000 0x allowlist addresses), snipeExempt (0 to 32 0x addresses), feeWallet (0x EOA or Safe), creatorFeeBps (whole integer 0 to 9999 with 100 + creatorFeeBps + snipeFeeStartBps < 10000), and teamAllocation ({ recipient, percent, cliffDays, vestingDays }). Solana launches keep creatorFeeBps at 0 | 100 | 200 and refuse the Hood-only fields client-side before any request. See Hood generation 2 launch options.

Embedded launches use /launch/headless with or without a buy. TEE launches use /launch/self/build and the existing sign/broadcast/confirm flow; a Solana TEE buy signs the returned bundle and sends it to /launch/atomic/submit. Dry runs use the selected family’s /dry-run. Existing server gates still apply: embedded-wallet allowance, launch availability, and TEE tier and first-buy switches. No server switch is enabled by this SDK release. launchAsync() remains embedded-only.

Migration for this release: replace selfLaunch({ linkedWalletId, privyWalletId, ...fields }) with launch({ wallet: { linkedWalletId, privyWalletId }, ...fields }). Replace raw buyAmount with whole-unit buy. selfLaunch(), buildSelfLaunch() and dryRunSelfLaunch() are deprecated for one release; existing calls still work. confirmSelfLaunch() remains the recovery method. TEE launch() preserves SelfLaunchOutcomeError on Hood: after a create-curve broadcast, recover by confirming its original id and hashes, never by starting another launch. Embedded launch retries and Solana same-id recovery retain their existing behavior.

new CandleClient({ apiUrl, apiKey?, fetch?, maxRetries?, allowInsecureHttp?, privyAppId?, secretStore?, solanaRpcUrl?, evmRpcUrl?, evmRpcUrls?, hyperliquidBuilder?, hyperliquidNetwork? })

apiUrl must be https://. Every authenticated call sends x-api-key, so a cleartext http:// URL hands the key to anything on the path, and a redirect to HTTPS does not help because the first request has already gone. The constructor throws rather than letting that happen. Loopback (localhost, 127.0.0.0/8, ::1) is exempt and needs no flag; for a trusted local endpoint that is not loopback, such as a devcontainer reaching its host, pass allowInsecureHttp: true.

The signing options are needed only on the paths that sign locally:

  • privyAppId: Privy’s public app id, the one the sign relay uses. Required to sign for a linked or TEE wallet.
  • secretStore: where the wallet’s own P-256 signer lives (KeychainSecretStore, EncryptedFileSecretStore for a passphrase-encrypted file on Node, or InMemorySecretStore for tests and short runs). Candle never sees it.
  • solanaRpcUrl / evmRpcUrl: the RPCs broadcastSignedTransaction() and the linked-wallet one-shots (trade(), selfLaunch()) read and send over. A Hood linked payer needs evmRpcUrl. evmRpcUrls is a map from chain slug to EVM RPC URL for any other registry EVM chain; evmRpcUrl stays as the Hood endpoint, and a per-chain entry overrides it.
  • hyperliquidBuilder / hyperliquidNetwork: the perps builder to pin, and mainnet (default) or testnet.

apiKey is required by the write paths (launch, dry run, jobs, activity reporting, image upload, wallet import, self-signed launches, trades) and not required by the public reads (it is sent with them when set). getAgentTier() is the one exception: the endpoint accepts either an agent key or a Privy session, so it sends whichever apiKey the client was built with, key or none. Pass your own fetch to route through a proxy or to test without a network.

MethodWhat it does
getQuotePairs(chain?)The launch matrix, with matrixVersion
getHolderExit(curve, account?), getHolderExits(account)Where a holder stands if a Hood launch does not migrate (HolderExit: state, Recovery window, fixed rate and progress, rescue request, team vesting escrow, actions that would succeed now, and disclosure to show verbatim), per curve and per account. No key. MarketState.holderExit carries the same read, or holderExitUnavailable: true when it failed
buildHolderExit({ curve, account, action, amountRaw? }), recordHolderExit({ curve, account, txHash })The unsigned calls for the holder’s own wallet (nothing signed, no calldata encoded by the SDK), and recording a sent exit. No key
holderExit({ curve, action, amountRaw?, dryRun?, wallet?, linkedSigning? }), submitHolderExit(...)The exit on an agent key: Candle signs with the embedded Hood wallet, and a linked wallet gets signing[] for submitHolderExit. Results use the fee claim’s per-call not_sent, submitted_unknown, confirmed and reverted plus a sequence outcome. A refusal is a HolderExitError (a CandleApiError) with the API’s code, details and, for an incomplete sequence, outcome, calls and warnings. No request has a destination field
getPresets()First-party named launch configurations
expandPreset(presets, name, overrides?)Local merge of a preset into a launch body. No request
dryRunLaunch(req)Full validation with no spend and no cap slot consumed
launch(req)Launch from the named wallet (embedded by default); embedded retries, TEE signing and recovery. The result and every error carry the clientLaunchId it sent. feeWallet (Solana creator-fee recipient, or 0x EOA/Safe on Hood generation 2) and feeWalletMultisig ({ address, vaultIndex }, a Squads v4 vault on Solana) pass through as on the headless launch request, alongside top-level launchRules, snipeExempt, creatorFeeBps and teamAllocation on Hood generation 2
launchAsync(req)Returns once accepted, with a jobUrl to poll. An error carries the clientLaunchId it sent
getLaunchJob(clientLaunchId)One attempt’s ledger row
waitForLaunch(clientLaunchId, opts?)Polls until the job reaches a terminal state
getMarket(chain, mint)Lifecycle, tradability, migration status
getQuote(chain, mint, opts)Exact-integer quote for one side
getFeed(bucket, chain?)Public feed buckets (finalstretch returns at most the 200 most complete tokens)
editTokenMetadata(request, opts?)As the token’s creator, set Candle’s copy of its description and links (socials takes website, twitter, telegram, discord; "" or null removes one). Needs a launch:write key from the launching account; sends an Idempotency-Key, opts.idempotencyKey to retry. Nothing is written on chain.
tokenMetadataHistory(params)A token’s metadata edits, newest first, with the previous values. Public; no key needed
getTokenEvents(chain, mint, opts?)One token’s signals, callouts and tracked-wallet trades, newest first. Keyless; kind filters the page locally, since/limit go to the route, nextCursor continues via before.
getTokenCard(chain, mint, opts?)The token card’s data for one token: market, all-time high since launch, forensics coverage, hacc’s safety and same-name facts, tracked wallets in the last hour, and sources. Free and the same for every caller; no key needed. tag is a card source tag carried on links.token.
verify(chain, mint)Is this a genuine Candle launch
getTokenClusters(mint, { chain? })Optional third-party cluster estimates for a Solana token, with a linked-wallet caveat. Resolves status: "unavailable" with a reason instead of throwing, transport_error when the request fails. No key
reportActivity(chain, signature)Report a client-executed transaction
getAgentProfile(idOrWallet)Public agent track record
getAgentTier()The calling account’s tier snapshot: display/live tier, fee rate, lifetime fee totals, and the plan table as planTable
getPlans()The plan table this deployment serves, no key: each plan’s price, agent fee, perps builder fee, limits and capabilities, plus promoMaxDays. planTableRows() and planTableMarkdown() render it
uploadImage(bytes, contentType)Hosted image, returns a launch-ready imageUrl
importWallet(params)Ciphertext-only import of an existing wallet as a spend-capable linked wallet (Pro/Max)
buildSelfLaunch(req)Deprecated for one release; use launch({ wallet }). Unsigned launch transaction (or Hood calldata) for a linked wallet to sign itself
confirmSelfLaunch(req)Verifies a self-signed launch’s own broadcast, records it like launch() does. The result carries the clientLaunchId
buildTrade(req)Build a trade; executes inline for a main payer, or returns an unsigned artifact for a linked one
confirmTrade(req)Confirm a linked payer’s broadcast trade after it signs and sends it
submit(req)Hand Candle already-signed legs to broadcast and confirm in one call, instead of broadcasting yourself
trade(req)One-shot build, sign through the relay, and submit. Solana submits server-side; Hood broadcasts client-side. The result and every error carry the clientTradeId it sent
getTradeJob(clientTradeId)One trade’s ledger row, without sending anything: the read after a trade() that threw or timed out. Needs swap:write; a missing row throws JOB_NOT_FOUND
signLinkedTransaction(params)Authorize a build-bound artifact with the wallet’s own P-256 signer, through the Candle sign relay
broadcastSignedTransaction(...)Broadcast bytes you already signed yourself
swapFromLinked(req)Cross-chain: SOL on a linked wallet into ETH or USDG, own-wallets-only destinations
selfLaunch(req)Deprecated for one release; use launch({ wallet }). One-shot self-signed launch: build, sign, confirm. The result and every error carry the clientLaunchId it sent
buildAtomicLaunch(req)Assemble a launch plus 1 to 4 first buys as one Jito bundle (Pro/Max, Solana). The result and every error carry the clientLaunchId it sent
dryRunAtomicLaunch(req)The same body and checks as buildAtomicLaunch() (payers, plan, the Believer check, each leg’s fee and spend limits, the key’s transaction cap) and the same refusals, plus the launch preview and one fill per first buy. Records, reserves and draws nothing, and the clientLaunchId stays unused. It does not check balances or the day cap.
submitAtomicLaunch(req)Submit that bundle. Returns landed, failed, or timeout as a value, never a throw
launchAtomic(req)Build and submit the atomic bundle in one call. Returns the outcome plus clientLaunchId; an error carries it too, with the bundleId
operationIds(error)A function, not a client method: the { clientTradeId?, clientLaunchId?, bundleId? } on an error from one of the six one-call write methods, {} from anything else
listWallets(opts)The account’s linked wallets
getProfilePnl(keyPrefix)One profile’s realized P&L, fees and marked open positions, split by paying wallet (byWallet) and by chain (byChain), with chain on every position
getPortfolio()What the account’s embedded and TEE wallets hold on Solana and Hood, with prices. Hood is in hood; needs account:read
getSpendLimits()The calling key’s own spend caps and, in txLimitUse, how much of its USD txLimit it has used and when the window resets (GET /agent/keys/self/limits)
getProfileWallets(keyPrefix), setProfileWallets(keyPrefix, walletIds), setProfileWalletScope(keyPrefix, scope)Read or replace which wallets a profile may spend from, and its selected or all scope; see Agent wallets
getProfileTrades(keyPrefix, opts?)One profile’s trade history, failed trades and its swaps included (kind: "swap", ProfileSwapRow)
swap(req)One-shot base-asset swap through the account’s embedded wallets, bridging between Solana and Hood when the pair spans them. Moves real funds; clientSwapId makes it idempotent
wallets.swapReceipt(hash)A one-shot swap’s settlement, by any of its hashes
wallets.selfBalances(opts?)Balances of exactly the wallets this key may spend from, with optional extra mints and a cursor
previewCloseEmptyAccounts(req?)The embedded Solana wallet’s empty token accounts and the rent a close returns, or with wallet (a TEE wallet’s linked-wallet id) that TEE wallet’s. Read-only
closeEmptyAccounts(req)Close them and return the rent to the same wallet. The embedded wallet needs swap:write or transfer:write. With wallet and privyWalletId, a Solana TEE wallet bound to the key (swap:write): build, signLinkedTransaction() per transaction, then submit the whole batch; recovering means a transaction may still land, so read the job. clientTradeId makes it idempotent. See Closing empty token accounts
getCloseEmptyAccountsJob(clientTradeId, opts?)Read a close run without sending anything; { wallet } reads a TEE wallet’s run, reconciled against the chain
perpsSetup(ref)Hyperliquid perps: approve Candle’s builder fee once (0.1%) and report the account’s mode and balance; signs nothing when the approval is already there
perpsOpen(params)Open or add to a perps position (market without price, limit with it, optional takeProfit / stopLoss): build, check, sign through the relay, submit to Hyperliquid
perpsClose(params)Close all or part of a position with a reduce-only IOC order
perpsCancel(params)Cancel an order Candle built, by its cloid
perpsModify(params)Change a resting order’s price or size; the replacement gets a new cloid
perpsLeverage(params)Set a market’s leverage and margin mode, within the key’s maximum leverage
perpsMargin(params)Add or remove isolated margin on an isolated position
perpsClose({ ..., pct }), perpsLeverage({ ..., mode })Close a percentage of the position (rounded down to the size step), or set the margin mode keeping the current leverage; the answer reports the requested and the confirmed mode
perpsTpsl(params)Attach, move or remove the position’s take-profit / stop-loss; a move cancels the old leg first. Returns every step and whether the plan completed
perpsScheduleCancel(params)Set (seconds, at least 5) or clear (clear: true) Hyperliquid’s wallet-wide cancel-all timer
perpsFlatten(ref)Cancel every main-perp order, then close every main-perp position, then read again; at most 100 signed steps a call
getPerpsRisk()The calling key’s perps risk thresholds, stored and effective. An older API reports none, and the defaults are returned, labelled as such.
setPerpsRisk(fields)Tighten the calling key’s own thresholds (PUT /keys/self/perps-risk). Anything looser than the effective set is refused with 403 LOOSEN_REQUIRES_SESSION.
setKeyPerpsRisk(keyPrefix, fields, { bearerToken })The owner’s write on any of the account’s keys (PUT /keys/:prefix/perps-risk): may loosen or clear. Needs an owner credential (the CLI’s device token or a Privy session token) as a bearer token; the API key is not sent.
perpsPortfolioSection(wallets)The portfolio’s Hyperliquid section for EVM TEE addresses: account value, unrealized P&L, positions and risk level per account, and a subtotal. Live from Hyperliquid, never part of a portfolio total.
getPerpsReduceOnly(), setPerpsReduceOnly(true), setKeyPerpsReduceOnly(prefix, on, owner)Read the key’s reduce-only setting, turn it on for this key, or (owner credential) set it on any of the account’s keys
getPerpMarket(coin)In @candledottv/agent-sdk 0.6.27 and later (BE-3777). One Hyperliquid perp market (dex:COIN for a builder dex) with its public figures, the last 24 hours of funding and the published Candle agents long and short in it (open positions and recent closed rounds). No key; no wallet address is returned
perpsPositions(walletId), perpsOrders(walletId), perpsFills(walletId), perpsFunding(walletId, startTime?)Live reads from Hyperliquid by the wallet’s address, and Candle’s record of every action it built
perpsConfig()The server’s network, Candle’s builder, this key’s fee and its limits
perpsSpotMarkets({ all?, limit? })In @candledottv/agent-sdk 0.6.33 and later (BE-4216). The USDC-quoted Hyperliquid spot pairs Candle trades, with mid, 24 h volume and fees; all: true adds the pairs Candle refuses, each with its refusal
perpsSpotBalances(walletId)0.6.33 and later. The EVM TEE wallet’s Hyperliquid spot balances, separate from its perps balance; hold is the part resting in open orders
perpsSpotOrder(params)0.6.33 and later. Buy or sell a spot pair (HYPE/USDC or @107, size in the base token) from the key’s EVM TEE wallet: build, check against this machine’s own Hyperliquid read, sign through the relay, submit. A buy spends the wallet’s spot USDC. hide: true (0.6.35 and later, BE-4235) keeps the order’s fills out of the public activity stream; a build without the hide: true echo is refused before signing (HIDE_NOT_CONFIRMED). walletId: "embedded" is refused
perpsSpotCancel({ walletId, cloid })0.6.33 and later. Cancel a resting spot order Candle built, by its cloid, checked against Hyperliquid before signing
perpsDeposit(params), perpsDepositStatus(clientDepositId)Fund the Hyperliquid account from a TEE wallet through Relay, and read the deposit’s job. perpsDepositProblem(build, params) is the check the client runs on the build before signing

The perps methods sign from a linked EVM TEE wallet, so they need privyAppId and a secretStore holding the wallet’s signer, like signLinkedTransaction(), and a key with perps:write. Every build is checked before anything is signed: the client recomputes the action hash from the plaintext action, checks that the action type is one Candle builds and that the builder is Candle’s, and refuses otherwise with no relay call. Pin Candle’s builder with the hyperliquidBuilder option; unset, the release’s CANDLE_HYPERLIQUID_BUILDER_ADDRESS applies when it carries one, else the builder perpsConfig() reports the first time. hyperliquidNetwork: "testnet" trades testnet. A failed submit keeps the signature, which stays valid until the nonce leaves Hyperliquid’s two-day window.

Keeping an order out of the public stream (hide)

Section titled “Keeping an order out of the public stream (hide)”

hide?: boolean is accepted by swap(), buildTrade(), trade(), swapFromLinked(), the Hood swap build and every launch request (the field comes from the shared launch definition). It keeps the order out of Candle’s public activity stream: no agent mark and no handle. It is sent only when true; the same true, "true" and 1 the API reads are accepted, and any other unreadable value throws.

The API echoes hide: true. A successful response without that echo throws CandleApiError with code HIDE_NOT_CONFIRMED, before signing wherever the caller signs (linked swap, self launch, atomic build). With the embedded wallet the build is the executed order, so there the error says the order may have been placed publicly. The API rejects hide while it is switched off on the server, and currently refuses it on swaps, so swap() with hide fails until the API supports it. A hidden launch removes Candle’s identity layer, but the creator wallet is public on chain.

Embedded launch() reuses the same clientLaunchId across retries, which is what makes retrying safe: the server resolves whether the original attempt already landed instead of minting a second token. It retries network errors, 5xx responses, and the retryable in-flight 409, with jittered exponential backoff bounded by maxRetries (default 3). It never retries a non-retryable envelope.

Two deliberate exceptions, both to keep control with the caller:

  • 429 rate limits are not auto-retried. RATE_LIMITED and DAILY_CAP_REACHED mean waiting minutes or until tomorrow, which is a scheduling decision your agent should make, not a blocking sleep inside a library call.
  • waitForLaunch returns a failed job as a normal terminal result rather than throwing. Branch on status; only exceeding the timeout throws.

That reuse holds only inside one launch() call. Six methods send an idempotency id and generate one when you pass none: trade(), launch(), launchAsync(), selfLaunch(), buildAtomicLaunch() and launchAtomic(). The server treats the id as the whole identity of the operation: the same id is a replay, a new id is a second, independent trade or launch. A call that threw or timed out may still have executed.

  1. Pass your own id for anything that moves funds, and store it before the call. An error can carry the id only if the process is still running to catch it. A crash or a kill mid-call leaves nothing.
  2. If you did not, read the id from the result or the error and send it back on the retry with the same request body. Each of the six exposes the id it sent on the result (result.clientTradeId, result.clientLaunchId) and on every error thrown after its first request was sent: operationIds(error) returns { clientTradeId?, clientLaunchId?, bundleId? }, and {} when nothing was sent.
  3. Never retry without the id. A call with no id, or a new one, is a second trade or launch. The SDK does not remember ids between calls and adds no retry of its own to trade(), selfLaunch() or launchAtomic().
import { operationIds } from "@candledottv/agent-sdk"
try {
return await candle.trade(req)
} catch (error) {
const { clientTradeId } = operationIds(error)
if (!clientTradeId) throw error // nothing was sent
return await candle.trade({ ...req, clientTradeId }) // from: "main" only: a replay, not a second trade
}

What to do with the id depends on who broadcasts:

  • trade() from the embedded wallet (from: "main"). Read getTradeJob(id), or call trade() again with the same id and body. Both are safe. On the read, 404 JOB_NOT_FOUND means the write never began, so call again with the same id. confirmed means it landed and signature is on the job. failed with errorCode: "TRADE_REVERTED" means it landed and reverted, and a new trade needs a new id. Any other failed is not confirmed and may still be on chain: call again with the same id, which is the check. built is in flight or unresolved: a same-id trade() answers IDEMPOTENCY_CONFLICT, and if that carries stage: "unconfirmed" and retryable: false, check its signature on chain and do not retry.
  • Embedded launch() and launchAsync(). Retry with the same id, or read getLaunchJob(id). The rules are in Headless launch, Idempotency.
  • TEE launch(), deprecated selfLaunch() and a linked trade(). You sign and broadcast here, so the id is necessary and not sufficient: an error after the broadcast may sit on a transaction that landed, and calling again under the same id builds and broadcasts a new one. Read the job first (getLaunchJob(id), getTradeJob(id)); if it is not confirmed, check the wallet’s recent transactions before sending again. The example above is not safe for these flows.
  • launchAtomic(). timeout and failed are returned values and carry clientLaunchId. bundleId is dead once /submit has been called and is never resubmitted; it is there for log correlation. After a timeout, a failed, or an error that carries clientLaunchId:
    1. Read getLaunchJob(clientLaunchId). This needs launch:read on the key. The Write and Withdraw access levels hold it; a key whose scopes were named one by one holds it only if it was named, so add launch:read to any key that runs atomic launches. A scope refusal is not “not found”.
    2. confirmed: the bundle landed. The mint is on the job. Stop.
    3. 404 JOB_NOT_FOUND: the build never began. Call launchAtomic() again with the same id.
    4. failed: the bundle did not land. Call launchAtomic() again with the same id; the server starts a clean attempt under it.
    5. Any other status: the bundle may still land. Wait, then read the job again or call launchAtomic() again with the same id and the same body. The server resolves the first attempt before doing anything new. It answers 409 IDEMPOTENCY_CONFLICT while the first attempt is unresolved or has just been found landed, so on that 409 read the job again. It builds a fresh bundle only when the first is proven reverted. This call can take about 95 seconds to answer.
    6. Never send a new id while the job is not failed. That is a second token. This includes the 409 whose message says “use a new clientLaunchId to launch again”: read the job first, because that message is also what you see for a launch you do not yet know landed.
    7. One state has no terminal answer today: the same-id call keeps answering 409 “This launch was sent; its original attempt must be resolved” and the job is still neither confirmed nor failed, a few minutes after the submit (a blockhash lives about 90 seconds and the rebuild itself can take about 95). Stop. Do not send a new id on a timer; report the clientLaunchId and bundleId to whoever operates the key.
    8. Treat every timeout as unresolved. retryable is false on every timeout the server returns today, and it is never permission to relaunch under a new id.

Hidden orders (@candledottv/agent-sdk 0.6.23). swap(), buildTrade(), trade(), swapFromLinked() and every launch method take hide?: boolean, sent only when true (true, "true" or 1; any other unreadable value throws). It keeps the order out of the public activity stream. The API echoes hide: true; a successful response without the echo throws CandleApiError with code: "HIDE_NOT_CONFIRMED", before signing where you sign (linked swap, self launch, atomic build). With the embedded wallet the build is the executed order, so there the error says the order may have been placed publicly: read it back before you send another. The API refuses hide on swaps until it supports hide there. A hidden launch removes Candle’s identity layer, but the creator wallet is public on chain.

Every structured error response becomes a CandleApiError carrying code, status, retryable, and field where the API supplied one. A refused build (reason: "presign_refused") also carries refusal (the pre-sign check that fired) and detail (its sentence for why, for example that the price moved past maxSlippageBps) from 0.6.37; nothing was signed or sent, so it is safe to build again. Branch on code, never on message text. Responses that are not structured envelopes throw the same error type with code set to HTTP_<status>.

From the six one-call write methods, a CandleApiError or JsonRpcError also carries the idempotency id the call sent (clientTradeId or clientLaunchId, and bundleId from launchAtomic()). Any other failure after the first request was sent, such as a rejected fetch or a 2xx body that is not JSON, is a CandleOperationError carrying the same fields, with the original as error.cause. Before 0.5.0 that case surfaced as the raw error, so code that matched error instanceof TypeError on these calls should read error.cause.

The SDK also exports OWNER_CONFIRM_ERROR_CODES (OWNER_CONFIRM_REQUIRED, OWNER_CONFIRM_NOT_FOUND, OWNER_CONFIRM_EXPIRED) and the OwnerConfirmDetail type for callers of the owner routes with a cndl_dvc_ device token; the SDK’s own agent-key requests never see them. On 403 OWNER_CONFIRM_REQUIRED nothing changed and the response body’s error.ownerConfirm (an OwnerConfirmDetail: confirmId, userCode, verificationUriComplete, …) carries the approval link and code. CandleApiError does not carry it, so read the response yourself. After the owner approves in the browser, resend the identical request with the Candle-Owner-Confirm: <confirmId> header.

try {
await candle.launch(req)
} catch (err) {
if (err instanceof CandleApiError && err.code === "INSUFFICIENT_OWNER_BALANCE") {
await topUpWallet()
}
}
import { verifyWebhookSignature } from "@candledottv/agent-sdk"
const ok = verifyWebhookSignature(
process.env.CANDLE_WEBHOOK_SECRET,
req.headers["x-candle-signature"],
rawBody,
Math.floor(Date.now() / 1000),
)

Constant-time comparison and a 300 second default tolerance window. Pass the raw body text exactly as received, not a re-serialized object. See Webhooks for the full delivery contract.

hacc client (signals, preflight, intel, exports)

Section titled “hacc client (signals, preflight, intel, exports)”

From @candledottv/agent-sdk 0.6.42, createHaccClient reads hacc directly (default https://api.hacc.fun; pass apiUrl, HTTPS only. The client does not read the environment: use apiUrl: resolveHaccApiUrl(process.env) to honour CANDLE_HACC_URL or HACC_API_URL) with a production agent key (cndl_live_). It is separate from CandleClient, read-only, and never signs or trades.

import { createHaccClient } from "@candledottv/agent-sdk"
const hacc = createHaccClient({ apiKey: process.env.CANDLE_AGENT_API_KEY! })
const signals = await hacc.signals.list({ chain: "solana", pattern: "confluence", limit: 20 })
for await (const event of hacc.signals.stream({ chain: "solana", after_id: lastId })) {
// `gap` frames mark a missed range; resume from the last id you saw
}
const pre = await hacc.preflight.get("solana", mint, { usd: 500 })
GroupMethods
signalslist, catalog, stream (SSE or WebSocket, after_id cursor resume, explicit gap frames, me: true for your own alert-rule signals)
preflightget(chain, mint), batch(items) (1 to 50 items)
marketprices, tokensBatch (up to 50 addresses), developerTrades, riskReport, tradeFee, clusters
walletleaderboardPnl, tokenPnl (up to 50 wallets)
labledgerExport (paged, 1 to 500 rows), alphaExport (90-day dataset, ndjson or parquet), alphaExportLines (streaming line iterator)

Batch limits and chain names are checked before any request (HaccValidationError). On HTTP 402 the client throws PaymentRequiredError, unless you pass onPaymentRequired: it receives the parsed x402 offer and may return a payment proof, and the request is retried once with X-PAYMENT. The CLI (candle signals list|catalog|stream, candle preflight, candle intel) and the stdio MCP server (candle_signals, candle_signal_catalog, candle_preflight, candle_market_intel) carry the same reads.