@percolatorct/sdk 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,492 @@
1
+ # @percolator/sdk
2
+
3
+ TypeScript SDK for building clients, bots, and UIs on top of the [Percolator](https://github.com/dcccrypto/percolator) perpetual futures protocol on Solana.
4
+
5
+ > **⚠️ DISCLAIMER: FOR EDUCATIONAL PURPOSES ONLY** — This code has NOT been audited. Do NOT use in production or with real funds.
6
+
7
+ [![npm](https://img.shields.io/npm/v/@percolator/sdk?color=14F195)](https://www.npmjs.com/package/@percolator/sdk)
8
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
9
+
10
+ ---
11
+
12
+ ## Installation
13
+
14
+ ```bash
15
+ pnpm add @percolator/sdk
16
+ # or
17
+ npm install @percolator/sdk
18
+ ```
19
+
20
+ **Peer dependency:** `@solana/web3.js ^1.95`
21
+
22
+ ---
23
+
24
+ ## Quick Start
25
+
26
+ ```typescript
27
+ import {
28
+ getProgramId,
29
+ deriveVaultAuthority,
30
+ buildInitUserIxData,
31
+ buildDepositCollateralIxData,
32
+ buildTradeNoCpiIxData,
33
+ parseSlab,
34
+ computeMarkPnl,
35
+ computeLiqPrice,
36
+ simulateOrSend,
37
+ } from "@percolator/sdk";
38
+
39
+ // Get program ID (defaults to devnet)
40
+ const programId = getProgramId("devnet");
41
+
42
+ // Derive vault authority PDA
43
+ const [vaultAuth, bump] = deriveVaultAuthority(programId, slabPubkey);
44
+
45
+ // Read and parse on-chain slab account
46
+ const slabData = await connection.getAccountInfo(slabPubkey);
47
+ const { header, config, accounts } = parseSlab(slabData.data);
48
+
49
+ // Compute PnL for a position
50
+ const pnl = computeMarkPnl(positionSize, entryPrice, oraclePrice);
51
+ const liqPrice = computeLiqPrice(entryPrice, capital, positionSize, 500n);
52
+ ```
53
+
54
+ ---
55
+
56
+ ## Features
57
+
58
+ ### ABI Encoding & Decoding
59
+
60
+ Type-safe instruction builders matching the on-chain Rust layout byte-for-byte:
61
+
62
+ ```typescript
63
+ import { buildInitMarketIxData, buildTradeNoCpiIxData, IX_TAG } from "@percolator/sdk";
64
+
65
+ // Build InitMarket instruction data (256 bytes)
66
+ const data = buildInitMarketIxData({
67
+ admin: adminPubkey,
68
+ collateralMint: mintPubkey,
69
+ indexFeedId: pythFeedId,
70
+ maxStaleSecs: 60n,
71
+ confFilterBps: 250,
72
+ invert: false,
73
+ unitScale: 1_000_000_000, // lamports per unit
74
+ riskParams: { /* ... */ },
75
+ });
76
+
77
+ // Build trade instruction
78
+ const tradeData = buildTradeNoCpiIxData({
79
+ userIdx: 0,
80
+ lpIdx: 0,
81
+ requestedSize: 1_000_000n, // positive = long, negative = short
82
+ maxSlippage: 50, // bps
83
+ });
84
+ ```
85
+
86
+ **Supported instructions:** `InitMarket`, `InitUser`, `InitLP`, `DepositCollateral`, `WithdrawCollateral`, `KeeperCrank`, `TradeNoCpi`, `TradeCpi`, `LiquidateAtOracle`, `CloseAccount`, `TopUpInsurance`, `SetRiskThreshold`, `UpdateAdmin`, `UpdateConfig`, `SetMaintenanceFee`, `PushOraclePrice`, `ResolveMarket`, `SetOiImbalanceHardBlock`, `SetOracleAuthority`, and more.
87
+
88
+ ### Admin Instructions
89
+
90
+ #### SetOiImbalanceHardBlock (tag=71)
91
+
92
+ Prevents new trades from pushing the long/short OI skew above a configurable threshold.
93
+ When triggered, the on-chain error `OiImbalanceHardBlock` (code 59) is returned.
94
+
95
+ ```typescript
96
+ import {
97
+ encodeSetOiImbalanceHardBlock,
98
+ ACCOUNTS_SET_OI_IMBALANCE_HARD_BLOCK,
99
+ buildAccountMetas,
100
+ buildIx,
101
+ simulateOrSend,
102
+ } from "@percolator/sdk";
103
+
104
+ // threshold_bps = 0 → hard block disabled (default)
105
+ // threshold_bps = 5_000 → block trades that push skew above 50%
106
+ // threshold_bps = 8_000 → block trades that push skew above 80%
107
+ // threshold_bps = 10_000 → lock dominant side once any OI exists
108
+
109
+ const data = encodeSetOiImbalanceHardBlock({ thresholdBps: 8_000 });
110
+ const keys = buildAccountMetas(ACCOUNTS_SET_OI_IMBALANCE_HARD_BLOCK, [
111
+ adminPublicKey, // [signer]
112
+ slabPublicKey, // [writable]
113
+ ]);
114
+ const ix = buildIx({ programId, keys, data });
115
+
116
+ const result = await simulateOrSend({ connection, ix, signers: [admin] });
117
+ console.log("signature:", result.signature);
118
+ ```
119
+
120
+ #### SetOracleAuthority (tag=16)
121
+
122
+ Delegates the `PushOraclePrice` right to a specific keypair (e.g. a crank bot).
123
+ Pass `PublicKey.default` (all zeros) to revoke — the program then falls back to Pyth/Chainlink.
124
+
125
+ ```typescript
126
+ import { PublicKey } from "@solana/web3.js";
127
+ import {
128
+ encodeSetOracleAuthority,
129
+ ACCOUNTS_SET_ORACLE_AUTHORITY,
130
+ buildAccountMetas,
131
+ buildIx,
132
+ simulateOrSend,
133
+ } from "@percolator/sdk";
134
+
135
+ // Delegate to a crank bot
136
+ const data = encodeSetOracleAuthority({ newAuthority: crankBot.publicKey });
137
+ const keys = buildAccountMetas(ACCOUNTS_SET_ORACLE_AUTHORITY, [
138
+ adminPublicKey, // [signer, writable]
139
+ slabPublicKey, // [writable]
140
+ ]);
141
+ const ix = buildIx({ programId, keys, data });
142
+
143
+ await simulateOrSend({ connection, ix, signers: [admin] });
144
+
145
+ // Revoke — fall back to Pyth/Chainlink
146
+ const revokeData = encodeSetOracleAuthority({ newAuthority: PublicKey.default });
147
+ ```
148
+
149
+ See [`examples/admin-instructions.ts`](examples/admin-instructions.ts) for full end-to-end examples.
150
+
151
+ ### Account Deserialization
152
+
153
+ Parse the on-chain slab account into typed TypeScript objects:
154
+
155
+ ```typescript
156
+ import { parseSlab, parseSlabHeader, parseMarketConfig } from "@percolator/sdk";
157
+
158
+ const { header, config, accounts } = parseSlab(accountData);
159
+
160
+ // header.magic, header.version, header.admin, header.nonce
161
+ // header.resolved, header.paused
162
+
163
+ // config.collateralMint, config.vaultPubkey, config.indexFeedId
164
+ // config.maxStalenessSlots, config.confFilterBps
165
+ // config.fundingHorizonSlots, config.fundingKBps
166
+ // config.threshFloor, config.threshRiskBps
167
+
168
+ // accounts[i].owner, accounts[i].capital, accounts[i].pnl, accounts[i].positionSize
169
+ ```
170
+
171
+ ### PDA Derivation
172
+
173
+ All program-derived addresses with correct seeds:
174
+
175
+ ```typescript
176
+ import {
177
+ deriveVaultAuthority,
178
+ deriveLpPda,
179
+ deriveInsuranceLpMint,
180
+ } from "@percolator/sdk";
181
+
182
+ const [vaultAuth, bump] = deriveVaultAuthority(programId, slab);
183
+ const [lpPda, lpBump] = deriveLpPda(programId, slab, lpIndex);
184
+ const [insMint, insBump] = deriveInsuranceLpMint(programId, slab);
185
+ ```
186
+
187
+ ### Trading Math
188
+
189
+ Coin-margined perpetual math utilities (all BigInt, no floating-point):
190
+
191
+ ```typescript
192
+ import {
193
+ computeMarkPnl,
194
+ computeLiqPrice,
195
+ computeEntryPrice,
196
+ computeEffectiveLeverage,
197
+ } from "@percolator/sdk";
198
+
199
+ // Mark-to-market PnL (in native token units)
200
+ const pnl = computeMarkPnl(positionSize, entryPriceE6, oraclePriceE6);
201
+
202
+ // Liquidation price given capital and maintenance margin
203
+ const liqPrice = computeLiqPrice(entryPriceE6, capital, positionSize, 500n);
204
+
205
+ // All values use e6 format: 1 USD = 1_000_000
206
+ ```
207
+
208
+ ### Oracle Price Router
209
+
210
+ Automatic oracle discovery and ranking for any Solana token:
211
+
212
+ ```typescript
213
+ import { resolvePrice } from "@percolator/sdk";
214
+
215
+ const result = await resolvePrice(tokenMint);
216
+ // result.bestSource — highest-confidence price source
217
+ // result.allSources — all discovered sources ranked by liquidity
218
+ ```
219
+
220
+ Supports **Pyth**, **DexScreener** (Raydium, Orca, Meteora), and **Jupiter** price feeds.
221
+
222
+ ### Program ID Configuration
223
+
224
+ Network-aware program ID resolution:
225
+
226
+ ```typescript
227
+ import { getProgramId, getMatcherProgramId } from "@percolator/sdk";
228
+
229
+ // Defaults to devnet
230
+ const programId = getProgramId();
231
+
232
+ // Explicit network selection
233
+ const mainnetId = getProgramId("mainnet");
234
+
235
+ // Environment variable override: PROGRAM_ID=<your-id>
236
+ ```
237
+
238
+ ### Auto-Deleveraging (ADL)
239
+
240
+ ADL (Auto-Deleveraging) reduces the most-profitable opposing positions when the insurance fund is depleted. The SDK provides both on-chain and API-based ADL utilities.
241
+
242
+ #### Checking if ADL is triggered
243
+
244
+ ```typescript
245
+ import { isAdlTriggered } from "@percolator/sdk";
246
+
247
+ const accountInfo = await connection.getAccountInfo(slabKey);
248
+ if (isAdlTriggered(accountInfo!.data)) {
249
+ console.log("Insurance fund depleted — ADL is active");
250
+ }
251
+ ```
252
+
253
+ #### Ranking positions for ADL
254
+
255
+ ```typescript
256
+ import { fetchAdlRankedPositions } from "@percolator/sdk";
257
+
258
+ const { ranked, longs, shorts, isTriggered } = await fetchAdlRankedPositions(
259
+ connection,
260
+ slabKey,
261
+ );
262
+ // ranked — all positions sorted by PnL% descending (ADL priority order)
263
+ // longs — top-ranked long position (ADL target if insurance negative on short side)
264
+ // shorts — top-ranked short position
265
+ // isTriggered — whether pnl_pos_tot exceeds max_pnl_cap on-chain
266
+ ```
267
+
268
+ #### Building an ADL instruction
269
+
270
+ ```typescript
271
+ import { buildAdlInstruction, buildAdlTransaction, getProgramId } from "@percolator/sdk";
272
+
273
+ const programId = getProgramId("devnet");
274
+
275
+ // Build instruction directly (caller already has target index)
276
+ const ix = buildAdlInstruction(
277
+ callerPublicKey, // keeper / crank wallet
278
+ slabPublicKey,
279
+ oracleFeedPublicKey,
280
+ programId,
281
+ targetAccountIndex, // number — index of account to deleverage
282
+ );
283
+
284
+ // OR: fetch + rank + pick top target automatically
285
+ const ix2 = await buildAdlTransaction(
286
+ connection,
287
+ callerPublicKey,
288
+ slabPublicKey,
289
+ oracleFeedPublicKey,
290
+ programId,
291
+ "long", // side to deleverage ("long" | "short")
292
+ );
293
+ ```
294
+
295
+ #### Decoding on-chain ADL events
296
+
297
+ ```typescript
298
+ import { parseAdlEvent } from "@percolator/sdk";
299
+
300
+ // After sending / confirming an ExecuteAdl transaction:
301
+ const tx = await connection.getTransaction(sig, { commitment: "confirmed" });
302
+ const event = parseAdlEvent(tx?.meta?.logMessages ?? []);
303
+ // event.tag — 0xAD1E_0001 (2904424449)
304
+ // event.targetIdx — account index that was deleveraged
305
+ // event.price — oracle price at execution (e6)
306
+ // event.closedAbs — absolute position size closed (i128)
307
+ ```
308
+
309
+ #### Fetching ADL rankings via HTTP API
310
+
311
+ ```typescript
312
+ import { fetchAdlRankings } from "@percolator/sdk";
313
+
314
+ const result = await fetchAdlRankings(
315
+ "https://api.percolatorlaunch.com",
316
+ slabAddress,
317
+ );
318
+ // result.slabAddress — slab public key (base58)
319
+ // result.adlNeeded — true if ADL is triggered (capExceeded or utilizationTriggered)
320
+ // result.capExceeded — true if pnlPosTot > maxPnlCap
321
+ // result.insuranceDepleted — true if insurance fund balance == 0
322
+ // result.utilizationTriggered — true if utilization BPS exceeds the configured ADL threshold
323
+ // result.pnlPosTot — aggregate profitable PnL (decimal string)
324
+ // result.maxPnlCap — max PnL cap from market config (decimal string, "0" if unconfigured)
325
+ // result.excess — excess PnL above cap (decimal string)
326
+ // result.insuranceFundBalance — insurance fund balance (decimal string)
327
+ // result.insuranceFundFeeRevenue — insurance fund lifetime fee revenue (decimal string)
328
+ // result.insuranceUtilizationBps — insurance utilization in basis points (0–10000)
329
+ // result.rankings — AdlApiRanking[] sorted by rank (1 = first to deleverage)
330
+ // .rank — rank (1 = highest PnL%, deleveraged first)
331
+ // .idx — slab account index (pass as targetIdx to buildAdlInstruction)
332
+ // .pnlAbs — absolute PnL in lamports (decimal string)
333
+ // .capital — capital at entry in lamports (decimal string)
334
+ // .pnlPctMillionths — pnl * 1_000_000 / capital (decimal string)
335
+ ```
336
+
337
+ #### ADL error codes (61–65)
338
+
339
+ | Code | Name | Description |
340
+ |------|------|-------------|
341
+ | 61 | `EngineSideBlocked` | ADL blocked — dominant side already at cap |
342
+ | 62 | `EngineCorruptState` | Slab state corrupt — contact support |
343
+ | 63 | `InsuranceFundNotDepleted` | ADL not triggered yet (insurance fund healthy) |
344
+ | 64 | `NoAdlCandidates` | No eligible positions to deleverage |
345
+ | 65 | `BankruptPositionAlreadyClosed` | Target position already closed |
346
+
347
+ ---
348
+
349
+ ### Transaction Helpers
350
+
351
+ Build, simulate, and send transactions with error parsing:
352
+
353
+ ```typescript
354
+ import { buildIx, simulateOrSend } from "@percolator/sdk";
355
+
356
+ const ix = buildIx({ programId, keys: accountMetas, data: ixData });
357
+
358
+ const result = await simulateOrSend({
359
+ connection,
360
+ ix,
361
+ signers: [payer],
362
+ simulate: false, // true = simulate only
363
+ computeUnitLimit: 400_000,
364
+ });
365
+
366
+ // result.signature, result.slot, result.err, result.logs
367
+ // Errors are automatically parsed from logs into human-readable messages
368
+ ```
369
+
370
+ ### Client-Side Validation
371
+
372
+ Validate parameters before submitting transactions:
373
+
374
+ ```typescript
375
+ import { validateRiskParams, validateTradeParams } from "@percolator/sdk";
376
+
377
+ const errors = validateRiskParams(params);
378
+ if (errors.length > 0) {
379
+ console.error("Invalid risk params:", errors);
380
+ }
381
+ ```
382
+
383
+ ---
384
+
385
+ ## Architecture
386
+
387
+ ```
388
+ @percolator/sdk
389
+ ├── abi/ # Binary encoding/decoding matching on-chain layout
390
+ │ ├── instructions.ts # Instruction data builders (all 28+ instructions)
391
+ │ ├── accounts.ts # Account struct deserialization
392
+ │ ├── encode.ts # Low-level binary encoding (u8/u16/u32/u64/i128/pubkey)
393
+ │ ├── errors.ts # On-chain error code → human-readable parsing
394
+ │ └── index.ts
395
+ ├── solana/ # Solana-specific helpers
396
+ │ ├── slab.ts # Slab account parser (header + config + accounts)
397
+ │ ├── pda.ts # PDA derivation (vault, LP, insurance mint)
398
+ │ ├── discovery.ts # Market discovery (find all Percolator markets)
399
+ │ ├── dex-oracle.ts # DEX oracle price integration
400
+ │ ├── token-program.ts # SPL Token helpers
401
+ │ ├── ata.ts # Associated Token Account helpers
402
+ │ └── index.ts
403
+ ├── runtime/ # Transaction building and submission
404
+ │ ├── tx.ts # buildIx, simulateOrSend, error handling
405
+ │ └── index.ts
406
+ ├── math/ # Trading math (all BigInt)
407
+ │ ├── trading.ts # PnL, liquidation price, leverage, entry price
408
+ │ └── index.ts
409
+ ├── oracle/ # Price feed integration
410
+ │ └── price-router.ts # Multi-source oracle resolution (Pyth, DEX, Jupiter)
411
+ ├── config/ # Configuration
412
+ │ └── program-ids.ts # Network-aware program IDs
413
+ ├── validation.ts # Client-side parameter validation
414
+ └── index.ts # Public API re-exports
415
+ ```
416
+
417
+ ---
418
+
419
+ ## Development
420
+
421
+ ### Prerequisites
422
+
423
+ - Node.js 20+ and pnpm 9+
424
+
425
+ ### Commands
426
+
427
+ ```bash
428
+ pnpm install # Install dependencies
429
+ pnpm build # Build with tsup (outputs to dist/)
430
+ pnpm test # Run test suite (vitest)
431
+ pnpm lint # Type-check (tsc --noEmit)
432
+ ```
433
+
434
+ ### Testing
435
+
436
+ Tests cover ABI encoding roundtrips, PDA derivation, slab parsing, validation, and trading math:
437
+
438
+ ```bash
439
+ pnpm test # Run all tests
440
+ pnpm test -- --watch # Watch mode
441
+ ```
442
+
443
+ ### Publishing
444
+
445
+ ```bash
446
+ pnpm build
447
+ npm publish --access public
448
+ ```
449
+
450
+ ---
451
+
452
+ ## Configuration
453
+
454
+ | Environment Variable | Description | Default |
455
+ |---------------------|-------------|---------|
456
+ | `PROGRAM_ID` | Override Percolator program ID | Network default |
457
+ | `MATCHER_PROGRAM_ID` | Override Matcher program ID | Network default |
458
+ | `NETWORK` | Target network (`devnet` / `mainnet`) | `devnet` |
459
+
460
+ ### Devnet Program Addresses
461
+
462
+ | Program | Address |
463
+ |---------|---------|
464
+ | Percolator | `FxfD37s1AZTeWfFQps9Zpebi2dNQ9QSSDtfMKdbsfKrD` |
465
+ | Matcher | `4HcGCsyjAqnFua5ccuXyt8KRRQzKFbGTJkVChpS7Yfzy` |
466
+
467
+ ---
468
+
469
+ ## Browser Compatibility
470
+
471
+ The SDK uses `DataView` for all binary reads (no Node.js `Buffer` dependency). Works in:
472
+ - Node.js 20+
473
+ - Modern browsers (Chrome, Firefox, Safari, Edge)
474
+ - React Native (via `@solana/web3.js`)
475
+
476
+ ---
477
+
478
+ ## Related Repositories
479
+
480
+ | Repository | Description |
481
+ |-----------|-------------|
482
+ | [percolator](https://github.com/dcccrypto/percolator) | Core risk engine crate (Rust) |
483
+ | [percolator-prog](https://github.com/dcccrypto/percolator-prog) | Solana on-chain program (wrapper) |
484
+ | [percolator-matcher](https://github.com/dcccrypto/percolator-matcher) | Reference matcher program for LP pricing |
485
+ | [percolator-stake](https://github.com/dcccrypto/percolator-stake) | Insurance LP staking program |
486
+ | [percolator-ops](https://github.com/dcccrypto/percolator-ops) | Operations dashboard |
487
+ | [percolator-mobile](https://github.com/dcccrypto/percolator-mobile) | Solana Seeker mobile trading app |
488
+ | [percolator-launch](https://github.com/dcccrypto/percolator-launch) | Full-stack launch platform (monorepo) |
489
+
490
+ ## License
491
+
492
+ Apache 2.0 — see [LICENSE](LICENSE).