Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.parquet.exchange/llms.txt

Use this file to discover all available pages before exploring further.

The Parquet TypeScript SDK is a thin, instruction-building wrapper around the five on-chain programs that make up the protocol. Every method name ends in Ix and returns an Anchor TransactionInstruction. The SDK never sends transactions on your behalf — you compose, sign, and submit. That keeps the surface predictable: you can batch instructions, attach compute-budget directives, route through your own priority-fee logic, or hand off to a wallet adapter without fighting an opinionated client.
Every state-changing instruction reads the oracle via oracle_adapter and reverts with PriceStale outside US Regular Trading Hours. When building scheduled bots or backend services, gate submissions on the indexer’s GET /market-hours — submitting outside RTH burns transaction fees on guaranteed reverts.

Install and provider setup

The SDK is named @parquet/sdk in package.json but is not yet published to the npm registry. For now, consumers build from source.
git clone https://github.com/parquet-exchange/parquet.git
cd parquet/sdk
npm install
npm run build
If you depend on the SDK from a sibling workspace, reference it through the monorepo via npm workspace and let your bundler pick up the freshly built dist/.
An npm publish under @parquet/sdk is pending. Once published, the install command will reduce to npm install @parquet/sdk and the import paths in the examples below will be unchanged.
Each client takes an Anchor Program in its constructor, so you set up a provider once and instantiate clients per program.
import { AnchorProvider, Program, Wallet } from "@coral-xyz/anchor";
import { Connection, Keypair } from "@solana/web3.js";
import {
  PoolClient,
  PerpClient,
  OracleClient,
  FeeDistributorClient,
  StakingClient,
} from "@parquet/sdk";
import poolIdl from "@parquet/sdk/idl/pool_program.json";
import perpIdl from "@parquet/sdk/idl/perp_engine.json";
import oracleIdl from "@parquet/sdk/idl/oracle_adapter.json";
import feeIdl from "@parquet/sdk/idl/fee_distributor.json";
import stakingIdl from "@parquet/sdk/idl/staking.json";

const connection = new Connection(process.env.RPC_URL!, "confirmed");
const wallet = new Wallet(Keypair.fromSecretKey(/* ... */));
const provider = new AnchorProvider(connection, wallet, { commitment: "confirmed" });

const pool = new PoolClient(new Program(poolIdl, provider));
const perp = new PerpClient(new Program(perpIdl, provider));
const oracle = new OracleClient(new Program(oracleIdl, provider));
const fees = new FeeDistributorClient(new Program(feeIdl, provider));
const staking = new StakingClient(new Program(stakingIdl, provider));
Program IDs live in /network/contracts. The IDLs ship inside the SDK build output; load them from @parquet/sdk/idl/* or from target/idl/ if you are working against a local build.

PoolClient

PoolClient wraps the liquidity pool program — LP deposits, withdrawals, fee accrual, and the v4 payout-queue cranks.
MethodArgs (summary)ReturnsWhat it does
initializePoolIxauthority, pool configTransactionInstructionOne-time pool init; sets fee splits, caps, queue parameters
updatePoolConfigIxconfig patchTransactionInstructionAuthority-only config update
depositIxlp, usdcAmountTransactionInstructionMints LP shares against a USDC deposit
withdrawIxlp, shareAmountTransactionInstructionBurns shares and returns USDC pro-rata
sweepFeesIxcallerTransactionInstructionPushes accumulated trading fees into the fee distributor
accrueFeeIxcallerTransactionInstructionSnapshots per-share fee index for LP accounting
harvestIxlpTransactionInstructionv4 — drains an LP’s mature queue claims back into available liquidity
voidQueueClaimIxclaim, reasonTransactionInstructionv4 — cancels a stale or invalid payout-queue entry
drainPhantomCreditIxlpTransactionInstructionv4 — clears residual credit dust after queue reconciliation
The trailing three methods are the new v4 surface introduced by the LP payout queue redesign. Indexer keepers call them on a schedule; LP UIs surface harvestIx to end users so they can pull matured claims at will.
import { Transaction } from "@solana/web3.js";

const ix = await pool.depositIx({
  lp: provider.wallet.publicKey,
  usdcAmount: 1_000_000_000n, // 1,000 USDC at 6 decimals
});

const tx = new Transaction().add(ix);
const sig = await provider.sendAndConfirm(tx);
console.log("deposit confirmed:", sig);

PerpClient

PerpClient wraps the perp engine — markets, positions, orders, liquidations, and the on-chain referral system.
MethodArgs (summary)ReturnsWhat it does
initializeMarketIxmarketId, configTransactionInstructionAuthority-only market init
updateMarketConfigIxconfig patchTransactionInstructionAdjusts max leverage, fees, OI caps
openPositionIxtrader, market, walletCollateral, fromQueueAmount, size, sideTransactionInstructionOpens a perp position; v4 splits collateral source
closePositionIxtrader, market, closeSize | nullTransactionInstructionCloses full or partial size; null closes the entire position
updatePositionMarginIxdeltaTransactionInstructionAdds or removes margin from an existing position
updateFundingRateIxmarketTransactionInstructionKeeper crank — recomputes funding from skew
createOrderIxorder paramsTransactionInstructionPosts a conditional/limit order on-chain
cancelOrderIxorderTransactionInstructionCancels an outstanding order
executeOrderIxorderTransactionInstructionKeeper-only — fills a triggered order
liquidateIxposition, liquidatorTransactionInstructionPermissionless liquidation when margin falls below maintenance
configureReferralTiersIxtier tableTransactionInstructionAuthority — sets affiliate tier thresholds
setReferralTierIxreferrer, tierTransactionInstructionAuthority — manually pins a referrer’s tier
createReferralCodeIxreferrer, codeTransactionInstructionRegisters a referral code PDA
setTraderReferralIxtrader, codeTransactionInstructionBinds a trader to a referrer at first use
claimAffiliateRewardIxreferrerTransactionInstructionAffiliate-facing — claims accrued referral rewards
v4 breaking change — openPositionIx. The v4 perp engine splits position collateral into two sources: walletCollateral (transferred from the trader’s USDC token account at open time) and fromQueueAmount (drawn from an LP payout-queue credit the trader already holds). v3 took a single collateralUsdc; that field no longer exists. Front-ends that always pay from wallet pass fromQueueAmount: 0n. See /trade/payout-queue for the queue-drawn collateral semantics.
closePositionIx supports partial closes via the closeSize parameter — pass a BN for partial, or null to close the entire position. The full feature page lives at /developer/partial-close, including realized-PnL math and the per-market minimum size rules.
import BN from "bn.js";

const ix = await perp.openPositionIx({
  trader: provider.wallet.publicKey,
  market: marketPda,
  walletCollateral: new BN(500_000_000),   // 500 USDC from wallet
  fromQueueAmount: new BN(0),              // none drawn from queue
  size: new BN(2_000_000_000),             // 2,000 USDC notional
  side: { long: {} },
  acceptablePrice: new BN(45_000_000_000), // slippage guard, 6 decimals
});

const tx = new Transaction().add(ix);
await provider.sendAndConfirm(tx);

OracleClient

OracleClient exposes a single instruction-builder:
MethodArgs (summary)ReturnsWhat it does
registerMarketOracleIxmarket, priceFeedTransactionInstructionAuthority-only — binds a market to its PriceFeed account
Price reads themselves happen via CPI from the perp engine and pool program at instruction time, not via SDK calls. If you need to inspect a current oracle price off-chain, fetch the PriceFeed account directly and decode bytes at the offsets documented in the project’s pricefeed-layout reference; the SDK does not provide a readPrice() helper because off-chain reads never participate in settlement.

FeeDistributorClient

FeeDistributorClient is the operator-side surface for fee routing.
MethodArgs (summary)ReturnsWhat it does
distributeFeesIxcallerTransactionInstructionSplits the fee pool by configured percentages
updateFeeSplitIxnew splitTransactionInstructionAuthority — adjusts LP / treasury / staking / referral split
updateFeePoolAccountsIxaccount mapTransactionInstructionAuthority — repoints destination token accounts
withdrawTreasuryIxamount, destTransactionInstructionAuthority — pulls from the treasury bucket
disburseReferralIxreferrerTransactionInstructionInternal — moves accrued amount into the referrer’s claimable balance
The affiliate-facing claim flow lives on PerpClient.claimAffiliateRewardIx, not here. FeeDistributorClient handles the operator/admin side: sweeping fees, adjusting splits, treasury withdrawal, and the underlying disburseReferralIx that feeds the claimable balance the affiliate later withdraws.

StakingClient

StakingClient covers stake/unstake and reward distribution across multiple emission pools.
MethodArgs (summary)ReturnsWhat it does
stakeIxstaker, amountTransactionInstructionLocks tokens into a staking pool
unstakeIxstaker, amountTransactionInstructionWithdraws stake subject to any cooldown
claimRewardIxstaker, poolTransactionInstructionClaims accrued rewards from one pool
updateRewardIndexIxpoolTransactionInstructionCrank — advances the per-share reward index
initializeEmissionPoolIxpool configTransactionInstructionAuthority — creates an emission-schedule pool
claimAndRestakeIxstakerTransactionInstructionAtomic — claims LP-emission rewards and restakes into the protocol-token pool in one instruction
reclaimUnallocatedIxpoolTransactionInstructionAuthority — pulls unemitted tokens back from a wound-down pool
Each pool carries a reward_source discriminator. BalanceBased pools pay out of a deposited reward balance and stop when it runs dry; EmissionSchedule pools accrue at a fixed rate over a window and ignore the on-chain balance until claim time. claimAndRestakeIx is the headline ergonomics win for stakers — instead of claim → swap → stake across three transactions, an LP staker compounds emissions into the protocol-token pool atomically.

Error handling

Anchor wraps every program error in AnchorError with a stable numeric code and a human-readable name. Catch and switch on err.error.errorCode.number:
import { AnchorError } from "@coral-xyz/anchor";

try {
  await provider.sendAndConfirm(tx);
} catch (err) {
  if (err instanceof AnchorError) {
    const code = err.error.errorCode.number;
    console.error(`anchor error ${code}: ${err.error.errorCode.code}`);
    console.error(err.error.errorMessage);
  } else {
    throw err;
  }
}
Common codes you will see during normal SDK use:
CodeNameOriginCause
2005OiCapExceededperp_engineOpen interest cap for the side would be breached by this open/increase ($50,000 per side per market)
2006BelowMinCollateralperp_enginePosition margin would fall below the $10 minimum after the operation
3007FeeSettingsWrongOwnerfee_distributorFeeSettings PDA passed to the instruction is owned by a different program than expected
6000PriceStaleoracle_adapterOracle price is older than the staleness threshold — the market is outside US Regular Trading Hours, or the price-pusher is unhealthy
2005 and 2006 are user-actionable — surface them as “market full” and “increase margin” respectively. 6000 is the canonical RTH-halt error and should be surfaced as “markets closed — try again at the next open” rather than a generic failure. 3007 is a wiring bug; if you see it in production it almost always means the client was pointed at the wrong program ID or a stale PDA cache. Cross-check the program IDs listed in /network/contracts.

See also