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.
| Method | Args (summary) | Returns | What it does |
|---|
initializePoolIx | authority, pool config | TransactionInstruction | One-time pool init; sets fee splits, caps, queue parameters |
updatePoolConfigIx | config patch | TransactionInstruction | Authority-only config update |
depositIx | lp, usdcAmount | TransactionInstruction | Mints LP shares against a USDC deposit |
withdrawIx | lp, shareAmount | TransactionInstruction | Burns shares and returns USDC pro-rata |
sweepFeesIx | caller | TransactionInstruction | Pushes accumulated trading fees into the fee distributor |
accrueFeeIx | caller | TransactionInstruction | Snapshots per-share fee index for LP accounting |
harvestIx | lp | TransactionInstruction | v4 — drains an LP’s mature queue claims back into available liquidity |
voidQueueClaimIx | claim, reason | TransactionInstruction | v4 — cancels a stale or invalid payout-queue entry |
drainPhantomCreditIx | lp | TransactionInstruction | v4 — 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.
| Method | Args (summary) | Returns | What it does |
|---|
initializeMarketIx | marketId, config | TransactionInstruction | Authority-only market init |
updateMarketConfigIx | config patch | TransactionInstruction | Adjusts max leverage, fees, OI caps |
openPositionIx | trader, market, walletCollateral, fromQueueAmount, size, side | TransactionInstruction | Opens a perp position; v4 splits collateral source |
closePositionIx | trader, market, closeSize | null | TransactionInstruction | Closes full or partial size; null closes the entire position |
updatePositionMarginIx | delta | TransactionInstruction | Adds or removes margin from an existing position |
updateFundingRateIx | market | TransactionInstruction | Keeper crank — recomputes funding from skew |
createOrderIx | order params | TransactionInstruction | Posts a conditional/limit order on-chain |
cancelOrderIx | order | TransactionInstruction | Cancels an outstanding order |
executeOrderIx | order | TransactionInstruction | Keeper-only — fills a triggered order |
liquidateIx | position, liquidator | TransactionInstruction | Permissionless liquidation when margin falls below maintenance |
configureReferralTiersIx | tier table | TransactionInstruction | Authority — sets affiliate tier thresholds |
setReferralTierIx | referrer, tier | TransactionInstruction | Authority — manually pins a referrer’s tier |
createReferralCodeIx | referrer, code | TransactionInstruction | Registers a referral code PDA |
setTraderReferralIx | trader, code | TransactionInstruction | Binds a trader to a referrer at first use |
claimAffiliateRewardIx | referrer | TransactionInstruction | Affiliate-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:
| Method | Args (summary) | Returns | What it does |
|---|
registerMarketOracleIx | market, priceFeed | TransactionInstruction | Authority-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.
| Method | Args (summary) | Returns | What it does |
|---|
distributeFeesIx | caller | TransactionInstruction | Splits the fee pool by configured percentages |
updateFeeSplitIx | new split | TransactionInstruction | Authority — adjusts LP / treasury / staking / referral split |
updateFeePoolAccountsIx | account map | TransactionInstruction | Authority — repoints destination token accounts |
withdrawTreasuryIx | amount, dest | TransactionInstruction | Authority — pulls from the treasury bucket |
disburseReferralIx | referrer | TransactionInstruction | Internal — 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.
| Method | Args (summary) | Returns | What it does |
|---|
stakeIx | staker, amount | TransactionInstruction | Locks tokens into a staking pool |
unstakeIx | staker, amount | TransactionInstruction | Withdraws stake subject to any cooldown |
claimRewardIx | staker, pool | TransactionInstruction | Claims accrued rewards from one pool |
updateRewardIndexIx | pool | TransactionInstruction | Crank — advances the per-share reward index |
initializeEmissionPoolIx | pool config | TransactionInstruction | Authority — creates an emission-schedule pool |
claimAndRestakeIx | staker | TransactionInstruction | Atomic — claims LP-emission rewards and restakes into the protocol-token pool in one instruction |
reclaimUnallocatedIx | pool | TransactionInstruction | Authority — 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:
| Code | Name | Origin | Cause |
|---|
| 2005 | OiCapExceeded | perp_engine | Open interest cap for the side would be breached by this open/increase ($50,000 per side per market) |
| 2006 | BelowMinCollateral | perp_engine | Position margin would fall below the $10 minimum after the operation |
| 3007 | FeeSettingsWrongOwner | fee_distributor | FeeSettings PDA passed to the instruction is owned by a different program than expected |
| 6000 | PriceStale | oracle_adapter | Oracle 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