@0dotxyz/p0-ts-sdk 1.0.0-alpha.2

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 P0 Protocol
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,467 @@
1
+ # Project 0 TypeScript SDK
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@0dotxyz/p0-ts-sdk.svg)](https://www.npmjs.com/package/@0dotxyz/p0-ts-sdk)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.5-blue.svg)](https://www.typescriptlang.org/)
6
+
7
+ A modern, type-safe TypeScript SDK for interacting with the P0 Protocol on Solana. Lend, borrow, and manage leveraged DeFi positions with a clean, developer-friendly API.
8
+
9
+ ## Features
10
+
11
+ - ๐Ÿ”’ **Type-safe**: Full TypeScript support with comprehensive type definitions
12
+ - ๐Ÿ“ฆ **Tree-shakeable**: Optimized ESM and CJS builds (<1MB)
13
+ - ๐Ÿงช **Well-tested**: Unit and integration tests with Vitest
14
+ - ๐Ÿ“š **Rich examples**: 7+ runnable examples covering all core features
15
+ - ๐Ÿ”„ **Modern tooling**: Built with tsup, ESLint, Prettier
16
+ - ๐ŸŽฏ **Solana-native**: Built on Anchor with full on-chain integration
17
+ - โšก **Production-ready**: Used in production applications
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ npm install @0dotxyz/p0-ts-sdk
23
+ # or
24
+ yarn add @0dotxyz/p0-ts-sdk
25
+ # or
26
+ pnpm add @0dotxyz/p0-ts-sdk
27
+ ```
28
+
29
+ ## Quick Start
30
+
31
+ ### 1. Initialize the Client
32
+
33
+ ```typescript
34
+ import { Connection, PublicKey } from "@solana/web3.js";
35
+ import { Project0Client, getConfig } from "@0dotxyz/p0-ts-sdk";
36
+
37
+ // Connect to Solana
38
+ const connection = new Connection("https://api.mainnet-beta.solana.com", "confirmed");
39
+
40
+ // Get configuration (mainnet-beta)
41
+ const config = getConfig("production");
42
+
43
+ // Initialize the client (loads all banks and oracle prices)
44
+ const client = await Project0Client.initialize(connection, config);
45
+
46
+ console.log(`Loaded ${client.banks.length} banks`);
47
+ ```
48
+
49
+ ### 2. Load Your Account
50
+
51
+ ```typescript
52
+ import { MarginfiAccount, MarginfiAccountWrapper } from "@0dotxyz/p0-ts-sdk";
53
+
54
+ const accountAddress = new PublicKey("YOUR_MARGINFI_ACCOUNT_ADDRESS");
55
+
56
+ // Fetch your account
57
+ const account = await MarginfiAccount.fetch(accountAddress, client.program);
58
+
59
+ // Wrap it for cleaner API
60
+ const wrappedAccount = new MarginfiAccountWrapper(account, client);
61
+ ```
62
+
63
+ ### 3. Find a Bank
64
+
65
+ ```typescript
66
+ import { AssetTag } from "@0dotxyz/p0-ts-sdk";
67
+
68
+ // Option 1: Get bank by address
69
+ const bank = client.getBank(new PublicKey("BANK_ADDRESS"));
70
+
71
+ // Option 2: Get all banks for a mint (e.g., USDC)
72
+ const USDC_MINT = new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
73
+ const usdcBanks = client.getBanksByMint(USDC_MINT);
74
+ ```
75
+
76
+ ### 4. Deposit Tokens
77
+
78
+ ```typescript
79
+ // Build deposit transaction
80
+ const depositTx = await wrappedAccount.makeDepositTx(
81
+ usdcBank.address,
82
+ "100" // Amount in UI units (100 USDC)
83
+ );
84
+
85
+ // Simulate (optional, but recommended)
86
+ const simulation = await connection.simulateTransaction(depositTx);
87
+ console.log(`Compute units: ${simulation.value.unitsConsumed}`);
88
+
89
+ // Sign and send
90
+ // depositTx.sign([wallet]);
91
+ // await connection.sendTransaction(depositTx);
92
+ ```
93
+
94
+ ### 5. Borrow Against Collateral
95
+
96
+ ```typescript
97
+ // Check how much you can borrow
98
+ const maxBorrow = wrappedAccount.computeMaxBorrowForBank(usdcBank.address);
99
+ console.log(`Max borrow: $${maxBorrow.toString()}`);
100
+
101
+ // Build borrow transaction
102
+ const borrowTx = await wrappedAccount.makeBorrowTx(
103
+ usdcBank.address,
104
+ "100" // Borrow 100 USDC
105
+ );
106
+
107
+ // Send transaction...
108
+ ```
109
+
110
+ ### 6. Monitor Account Health
111
+
112
+ ```typescript
113
+ import { MarginRequirementType } from "@0dotxyz/p0-ts-sdk";
114
+
115
+ // Get free collateral in USD
116
+ const freeCollateral = wrappedAccount.computeFreeCollateral();
117
+ console.log(`Free collateral: $${freeCollateral.toString()}`);
118
+
119
+ // Get health components
120
+ const health = wrappedAccount.computeHealthComponents(MarginRequirementType.Initial);
121
+
122
+ const healthFactor = health.assets.div(health.liabilities);
123
+ console.log(`Health factor: ${healthFactor.toString()}`);
124
+ ```
125
+
126
+ ## ๐Ÿ“š Examples
127
+
128
+ Check out the [`examples/`](./examples) directory for complete, runnable examples:
129
+
130
+ - **[01-deposit.ts](./examples/01-deposit.ts)** - Deposit tokens and earn interest
131
+ - **[02-borrow.ts](./examples/02-borrow.ts)** - Borrow against your collateral
132
+ - **[03-withdraw.ts](./examples/03-withdraw.ts)** - Withdraw your deposits
133
+ - **[04-repay.ts](./examples/04-repay.ts)** - Repay borrowed amounts
134
+ - **[05-oracle-prices.ts](./examples/05-oracle-prices.ts)** - Work with oracle price feeds
135
+ - **[06a-account-health-simulated.ts](./examples/06a-account-health-simulated.ts)** - Monitor account health
136
+ - **[06b-account-health-calculated.ts](./examples/06b-account-health-calculated.ts)** - Calculate health metrics
137
+
138
+ Each example includes:
139
+
140
+ - โœ… Full setup instructions
141
+ - โœ… Detailed comments
142
+ - โœ… Error handling
143
+ - โœ… Transaction simulation
144
+
145
+ ### Running Examples
146
+
147
+ ```bash
148
+ cd examples
149
+ cp .env.example .env
150
+ # Edit .env with your values
151
+ tsx 01-deposit.ts
152
+ ```
153
+
154
+ ## ๐Ÿ—๏ธ Core Concepts
155
+
156
+ ### Project0Client
157
+
158
+ The main SDK client that manages protocol interactions.
159
+
160
+ ```typescript
161
+ const client = await Project0Client.initialize(connection, config);
162
+
163
+ // Pre-loaded data (fetched once at initialization)
164
+ client.banks // All available banks
165
+ client.bankMap // Banks indexed by address
166
+ client.oraclePriceByBank // Latest oracle prices
167
+ client.mintDataByBank // Token mint metadata
168
+ client.addressLookupTables // For transaction optimization
169
+
170
+ // Methods
171
+ client.getBank(address) // Get bank by address
172
+ client.getBanksByMint(mint, tag?) // Get all banks for a mint
173
+ ```
174
+
175
+ **Benefits:**
176
+
177
+ - Single initialization loads all chain data
178
+ - Reuse throughout your application
179
+ - Automatic oracle price caching
180
+ - Built-in lookup table support
181
+
182
+ ### MarginfiAccount & Wrapper
183
+
184
+ Your lending account on the protocol.
185
+
186
+ ```typescript
187
+ // Fetch raw account
188
+ const account = await MarginfiAccount.fetch(address, client.program);
189
+
190
+ // Wrap for clean API (recommended)
191
+ const wrapped = new MarginfiAccountWrapper(account, client);
192
+
193
+ // All methods have access to banks, oracles, etc.
194
+ wrapped.computeMaxBorrowForBank(bankAddress);
195
+ wrapped.makeDepositTx(bankAddress, amount);
196
+ wrapped.computeFreeCollateral();
197
+ ```
198
+
199
+ ### Bank
200
+
201
+ A lending pool for a specific token.
202
+
203
+ ```typescript
204
+ const bank = client.getBank(bankAddress);
205
+
206
+ bank.mint; // Token mint address
207
+ bank.config; // Interest rates, weights, limits
208
+ bank.config.assetWeightInit; // Collateral factor (LTV)
209
+ bank.config.liabilityWeightInit; // Borrow weight
210
+ ```
211
+
212
+ ### Balance
213
+
214
+ Your position in a specific bank.
215
+
216
+ ```typescript
217
+ const balance = account.balances[0];
218
+
219
+ balance.bankPk; // Bank address
220
+ balance.assetShares; // Deposit shares
221
+ balance.liabilityShares; // Borrow shares
222
+ balance.active; // Is position active?
223
+ ```
224
+
225
+ ## ๐Ÿ“ฆ Package Structure
226
+
227
+ The SDK provides optimized entry points:
228
+
229
+ ```typescript
230
+ // Main SDK (core functionality)
231
+ import { Project0Client, MarginfiAccount, getConfig } from "@0dotxyz/p0-ts-sdk";
232
+
233
+ // Vendor utilities (oracle integrations, Jupiter, etc.)
234
+ import { fetchOracleData, OraclePrice } from "@0dotxyz/p0-ts-sdk/vendor";
235
+ ```
236
+
237
+ **Why separate vendor exports?**
238
+
239
+ - Reduces bundle size for simple use cases
240
+ - Oracle libraries (Pyth, Switchboard) are large
241
+ - Tree-shake what you don't need
242
+
243
+ ## ๐ŸŽฏ Key Features
244
+
245
+ ### Type Safety
246
+
247
+ Full TypeScript support with exported types:
248
+
249
+ ```typescript
250
+ import type {
251
+ MarginfiAccountType,
252
+ BankType,
253
+ BalanceType,
254
+ OraclePrice,
255
+ MarginRequirementType,
256
+ Project0Config,
257
+ } from "@0dotxyz/p0-ts-sdk";
258
+ ```
259
+
260
+ ### Multiple Bank Support
261
+
262
+ Handle cases where multiple banks exist for the same mint:
263
+
264
+ ```typescript
265
+ // Get ALL SOL banks (main + Kamino)
266
+ const solBanks = client.getBanksByMint(WSOL_MINT);
267
+
268
+ // Filter by tag
269
+ const mainSolBanks = client.getBanksByMint(WSOL_MINT, AssetTag.SOL);
270
+ const kaminoBanks = client.getBanksByMint(WSOL_MINT, AssetTag.KAMINO);
271
+ ```
272
+
273
+ ### Health Calculations
274
+
275
+ Built-in account health monitoring:
276
+
277
+ ```typescript
278
+ import { MarginRequirementType } from "@0dotxyz/p0-ts-sdk";
279
+
280
+ // Free collateral (how much you can still borrow)
281
+ const free = wrapped.computeFreeCollateral();
282
+
283
+ // Health components (assets vs liabilities)
284
+ const health = wrapped.computeHealthComponents(
285
+ MarginRequirementType.Initial // or Maintenance
286
+ );
287
+
288
+ // Max amounts
289
+ const maxBorrow = wrapped.computeMaxBorrowForBank(bankAddress);
290
+ const maxWithdraw = wrapped.computeMaxWithdrawForBank(bankAddress);
291
+ ```
292
+
293
+ ## ๐Ÿงช Testing
294
+
295
+ The SDK includes comprehensive tests:
296
+
297
+ ```bash
298
+ # Unit tests (fast, no RPC needed)
299
+ pnpm test:unit
300
+
301
+ # Integration tests (requires RPC)
302
+ SOLANA_RPC_URL=https://api.mainnet-beta.solana.com pnpm test:integration
303
+
304
+ # All tests
305
+ pnpm test
306
+
307
+ # With coverage
308
+ pnpm test:coverage
309
+ ```
310
+
311
+ **Testing Strategy:**
312
+
313
+ - **Unit tests**: Pure calculations, conversions, validations
314
+ - **Integration tests**: Real chain data, transaction building, simulations
315
+
316
+ See [TESTING.md](./TESTING.md) for details.
317
+
318
+ ## ๐Ÿ› ๏ธ Development
319
+
320
+ ### Prerequisites
321
+
322
+ - Node.js >= 18.0.0
323
+ - pnpm (recommended)
324
+
325
+ ### Setup
326
+
327
+ ```bash
328
+ # Install dependencies
329
+ pnpm install
330
+
331
+ # Build the SDK
332
+ pnpm build
333
+
334
+ # Watch mode (for development)
335
+ pnpm dev
336
+
337
+ # Type check
338
+ pnpm typecheck
339
+
340
+ # Lint and format
341
+ pnpm lint
342
+ pnpm format
343
+ ```
344
+
345
+ ### Project Structure
346
+
347
+ ```
348
+ p0-ts-sdk/
349
+ โ”œโ”€โ”€ src/
350
+ โ”‚ โ”œโ”€โ”€ index.ts # Main SDK exports
351
+ โ”‚ โ”œโ”€โ”€ vendor/ # Vendor entry point (oracles, etc.)
352
+ โ”‚ โ”œโ”€โ”€ config.ts # Network configurations
353
+ โ”‚ โ”œโ”€โ”€ models/ # Core models
354
+ โ”‚ โ”‚ โ”œโ”€โ”€ client.ts # Project0Client
355
+ โ”‚ โ”‚ โ”œโ”€โ”€ account.ts # MarginfiAccount
356
+ โ”‚ โ”‚ โ”œโ”€โ”€ account-wrapper.ts # MarginfiAccountWrapper
357
+ โ”‚ โ”‚ โ”œโ”€โ”€ bank.ts # Bank model
358
+ โ”‚ โ”‚ โ””โ”€โ”€ ...
359
+ โ”‚ โ”œโ”€โ”€ services/ # Business logic
360
+ โ”‚ โ”‚ โ”œโ”€โ”€ account/ # Account operations
361
+ โ”‚ โ”‚ โ”œโ”€โ”€ price/ # Oracle price fetching
362
+ โ”‚ โ”‚ โ””โ”€โ”€ ...
363
+ โ”‚ โ”œโ”€โ”€ instructions/ # Transaction builders
364
+ โ”‚ โ”œโ”€โ”€ types/ # TypeScript types
365
+ โ”‚ โ”œโ”€โ”€ idl/ # Anchor IDL
366
+ โ”‚ โ””โ”€โ”€ utils/ # Helpers
367
+ โ”œโ”€โ”€ tests/
368
+ โ”‚ โ”œโ”€โ”€ unit/ # Unit tests (mocked)
369
+ โ”‚ โ”œโ”€โ”€ integration/ # Integration tests (real RPC)
370
+ โ”‚ โ””โ”€โ”€ fixtures/ # Test data
371
+ โ”œโ”€โ”€ examples/ # 7+ runnable examples
372
+ โ””โ”€โ”€ dist/ # Build output
373
+ โ”œโ”€โ”€ index.js # ESM bundle
374
+ โ”œโ”€โ”€ index.cjs # CJS bundle
375
+ โ”œโ”€โ”€ index.d.ts # Type definitions
376
+ โ””โ”€โ”€ vendor.* # Vendor bundles
377
+ ```
378
+
379
+ ### Available Scripts
380
+
381
+ | Script | Description |
382
+ | ----------------------- | -------------------------- |
383
+ | `pnpm build` | Build ESM + CJS bundles |
384
+ | `pnpm dev` | Watch mode for development |
385
+ | `pnpm test` | Run all tests |
386
+ | `pnpm test:unit` | Run unit tests only |
387
+ | `pnpm test:integration` | Run integration tests |
388
+ | `pnpm test:coverage` | Generate coverage report |
389
+ | `pnpm lint` | Lint with ESLint |
390
+ | `pnpm format` | Format with Prettier |
391
+ | `pnpm typecheck` | TypeScript type checking |
392
+ | `pnpm clean` | Remove build artifacts |
393
+ | `pnpm changeset` | Create a changeset for releases |
394
+ | `pnpm version` | Bump version from changesets |
395
+ | `pnpm release` | Build and publish to npm |
396
+
397
+ ## ๐Ÿ“ฆ Publishing
398
+
399
+ This package uses [Changesets](https://github.com/changesets/changesets) for version management and npm publishing.
400
+
401
+ See [RELEASING.md](./RELEASING.md) for detailed instructions, or [.changeset/QUICKSTART.md](./.changeset/QUICKSTART.md) for a quick reference.
402
+
403
+ **Quick publish:**
404
+ ```bash
405
+ npm login
406
+ pnpm changeset # Document changes
407
+ pnpm version # Bump version
408
+ pnpm release # Publish to npm
409
+ git push --follow-tags
410
+ ```
411
+
412
+ ## ๐Ÿค Contributing
413
+
414
+ We welcome contributions! Please see our contributing guidelines:
415
+
416
+ 1. Fork the repository
417
+ 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
418
+ 3. Make your changes with tests
419
+ 4. Run `pnpm test` and `pnpm lint`
420
+ 5. Commit your changes (`git commit -m 'Add amazing feature'`)
421
+ 6. Push to the branch (`git push origin feature/amazing-feature`)
422
+ 7. Open a Pull Request
423
+
424
+ ### Development Workflow
425
+
426
+ ```bash
427
+ # 1. Make changes
428
+ vim src/models/client.ts
429
+
430
+ # 2. Add tests
431
+ vim tests/unit/models/client.test.ts
432
+
433
+ # 3. Run tests
434
+ pnpm test:unit
435
+
436
+ # 4. Build
437
+ pnpm build
438
+
439
+ # 5. Test with examples
440
+ cd examples && tsx 01-deposit.ts
441
+ ```
442
+
443
+ ## ๐Ÿ“„ License
444
+
445
+ This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.
446
+
447
+ ## ๐Ÿ™ Acknowledgments
448
+
449
+ This SDK is built on top of the [marginfi protocol](https://github.com/mrgnlabs/marginfi-v2), leveraging its on-chain programs and infrastructure.
450
+
451
+ Additional thanks to:
452
+
453
+ - [Solana Web3.js](https://github.com/solana-labs/solana-web3.js) - Solana JavaScript API
454
+ - [Anchor](https://github.com/coral-xyz/anchor) - Solana development framework
455
+
456
+ ## โš ๏ธ Disclaimer
457
+
458
+ This SDK is provided as-is. Always:
459
+
460
+ - Understand the risks of DeFi protocols
461
+ - Monitor your account health
462
+ - Use appropriate risk management
463
+ - Audit your integration code
464
+
465
+ ---
466
+
467
+ **Built for builders** ๐Ÿ› ๏ธ by the P0 team