@panoptic-eng/sdk 1.0.3 → 1.0.5

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/README.md CHANGED
@@ -1,139 +1,211 @@
1
1
  # @panoptic-eng/sdk
2
2
 
3
- TypeScript SDK for interacting with Panoptic v2 protocol.
3
+ TypeScript SDK for interacting with the Panoptic v2 perpetual options protocol on EVM chains.
4
4
 
5
- ## Prerequisites
5
+ ## Quick Start
6
6
 
7
- - **Node.js** `>=20.19.0 <23.0.0` (see `.nvmrc` in repo root)
8
- - **pnpm** package manager
9
-
10
- ## Setup
11
-
12
- ### 1. Install Node.js (via nvm)
13
-
14
- ```sh
15
- # Install nvm if you don't have it
16
- curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
7
+ ```bash
8
+ npm install @panoptic-eng/sdk viem
9
+ ```
17
10
 
18
- # Restart terminal, then install the correct Node version
19
- nvm install
20
- nvm use
11
+ ```typescript
12
+ import { createPublicClient, createWalletClient, http, parseUnits } from 'viem'
13
+ import { sepolia } from 'viem/chains'
14
+ import { privateKeyToAccount } from 'viem/accounts'
15
+ import {
16
+ getPool,
17
+ fetchPoolId,
18
+ approveAndWait,
19
+ depositAndWait,
20
+ createTokenIdBuilder,
21
+ simulateOpenPosition,
22
+ openPositionAndWait,
23
+ tickLimits,
24
+ formatTokenAmount,
25
+ } from '@panoptic-eng/sdk/v2'
26
+
27
+ // 1. Setup clients
28
+ const account = privateKeyToAccount('0xYOUR_PRIVATE_KEY')
29
+ const client = createPublicClient({ chain: sepolia, transport: http() })
30
+ const walletClient = createWalletClient({ account, chain: sepolia, transport: http() })
31
+
32
+ // 2. Read pool data
33
+ const pool = await getPool({ client, poolAddress: '0x...', chainId: 11155111n })
34
+
35
+ // 3. Approve + deposit collateral
36
+ await approveAndWait({
37
+ client,
38
+ walletClient,
39
+ account: account.address,
40
+ tokenAddress: pool.poolKey.currency0,
41
+ spenderAddress: pool.collateralTracker0.address,
42
+ amount: 2n ** 256n - 1n,
43
+ })
44
+ await depositAndWait({
45
+ client,
46
+ walletClient,
47
+ account: account.address,
48
+ collateralTrackerAddress: pool.collateralTracker0.address,
49
+ assets: parseUnits('1', 18),
50
+ })
51
+
52
+ // 4. Build a position and simulate
53
+ const { poolId } = await fetchPoolId({ client, poolAddress: '0x...' })
54
+ const tokenId = createTokenIdBuilder(poolId)
55
+ .addCall({ strike: 200_000n, width: 10n, optionRatio: 1n })
56
+ .build()
57
+
58
+ const limits = tickLimits(pool.currentTick, 500n)
59
+ const sim = await simulateOpenPosition({
60
+ client,
61
+ poolAddress: '0x...',
62
+ account: account.address,
63
+ tokenId,
64
+ positionSize: 10n ** 15n,
65
+ existingPositionIds: [],
66
+ tickLimitLow: limits.low,
67
+ tickLimitHigh: limits.high,
68
+ })
69
+
70
+ if (!sim.success) throw new Error(`Simulation failed: ${sim.error}`)
71
+ console.log('Gas estimate:', sim.gasEstimate)
72
+ console.log(
73
+ 'Token0 required:',
74
+ formatTokenAmount(sim.data.amount0Required, BigInt(pool.collateralTracker0.decimals), 6n),
75
+ )
76
+
77
+ // 5. Execute
78
+ await openPositionAndWait({
79
+ client,
80
+ walletClient,
81
+ account: account.address,
82
+ poolAddress: '0x...',
83
+ tokenId,
84
+ positionSize: 10n ** 15n,
85
+ existingPositionIds: [],
86
+ tickLimitLow: limits.low,
87
+ tickLimitHigh: limits.high,
88
+ })
21
89
  ```
22
90
 
23
- ### 2. Install pnpm
91
+ ## Feature Overview
24
92
 
25
- ```sh
26
- # Option A: via corepack (recommended, built into Node 16.13+)
27
- corepack enable
93
+ | Category | Capabilities |
94
+ |----------|-------------|
95
+ | **Pool Data** | Full pool state, utilization, oracle, risk parameters, liquidity distribution, interest rates |
96
+ | **Trading** | Open, close, roll positions with simulation-first workflow; tick limit slippage control |
97
+ | **Collateral** | ERC-4626 vault deposits/withdrawals, approval helpers, collateral estimation, max position sizing |
98
+ | **TokenId Builder** | Chainable builder for calls, puts, loans, credits; multi-leg spreads (up to 4 legs) |
99
+ | **Risk & Margin** | Margin buffer, liquidation prices, net liquidation value, collateral-across-ticks analysis |
100
+ | **Liquidation** | Liquidation checks, simulation, execution; force exercise for ITM longs |
101
+ | **Greeks** | Client-side value, delta, gamma in natural token units; swap-aware delta; loan effective delta |
102
+ | **Events** | WebSocket watcher, resilient subscription with auto-reconnect, HTTP polling |
103
+ | **Position Tracking** | Event-based sync with resumable checkpoints; file and memory storage adapters |
104
+ | **Trade History** | Local trade history with filters, realized PnL aggregation |
105
+ | **Price History** | Historical tick/sqrtPriceX96 data, streamia (premia) history, Uniswap fee history |
106
+ | **Bot Utilities** | Data freshness assertions, pool health checks, safe mode guards, RPC error classifiers |
107
+ | **Oracle** | Oracle state reads, poke with epoch rate-limit handling |
108
+ | **Pool Deployment** | Mine vanity pool addresses, simulate and deploy new Panoptic pools |
109
+ | **Formatters** | Prices, token amounts, BPS, utilization, WAD values — all with explicit precision |
110
+ | **Errors** | Typed error classes for every failure mode (revert decoding, RPC, validation) |
28
111
 
29
- # Option B: via npm
30
- npm install -g pnpm
31
- ```
112
+ ## Documentation
32
113
 
33
- ### 3. Install dependencies
114
+ | Document | Description |
115
+ | -------------------------------------------- | ---------------------------------------------------------------------------------- |
116
+ | [Getting Started](./docs/GETTING_STARTED.md) | Full walkthrough: setup → deposit → trade → greeks → risk → events → bots → deployment |
117
+ | [API Reference](./docs/SDK_API_REFERENCE.md) | Every exported function grouped by module with signatures and descriptions |
118
+ | [Examples](./src/panoptic/v2/examples/) | Runnable example scripts (bots, fork tests, common workflows) |
34
119
 
35
- From the monorepo root:
120
+ ## Notes
36
121
 
37
- ```sh
38
- pnpm install
39
- pnpm add @panoptic-eng/sdk react viem wagmi
40
- ```
122
+ - `GetVaultHistory` applies `first`/`skip` independently per event stream. For unified timeline pagination, merge and sort all streams client-side first, then page that merged array (for example, with a helper like `fetchVaultHistoryRows`).
41
123
 
42
- ### 4. Generate types
124
+ ### Example Bots
43
125
 
44
- The SDK uses code generation for contract ABIs and GraphQL types:
126
+ | Directory | Description |
127
+ |-----------|-------------|
128
+ | [`examples/liquidation-bot/`](./src/panoptic/v2/examples/liquidation-bot/) | Monitors accounts, detects undercollateralized positions, and executes liquidations |
129
+ | [`examples/oracle-poker/`](./src/panoptic/v2/examples/oracle-poker/) | Keeps Panoptic oracle observations fresh by poking within epoch constraints |
130
+ | [`examples/reverse-gamma-scalping/`](./src/panoptic/v2/examples/reverse-gamma-scalping/) | Delta-hedged strategy using loans, credits, and swap-aware greeks |
45
131
 
46
- ```sh
47
- cd packages/sdk
48
- pnpm codegen
49
- ```
132
+ ---
50
133
 
51
- This runs:
52
- - `codegen:graphql` - Generates TypeScript types from GraphQL schema
53
- - `codegen:wagmi` - Generates TypeScript types from contract ABIs
134
+ ## Contributing
54
135
 
55
- ### 5. Set up environment (for fork tests)
136
+ ### Prerequisites
56
137
 
57
- ```sh
58
- cp .env.template .env
59
- # Add your Alchemy API key to .env
60
- ```
138
+ - **Node.js** `>=20.19.0 <23.0.0` (see `.nvmrc` in repo root)
139
+ - **pnpm** package manager
61
140
 
62
- ## Development
141
+ ### Setup
63
142
 
64
143
  ```sh
65
- # Build the SDK
66
- pnpm build
144
+ # Install Node.js via nvm
145
+ nvm install && nvm use
67
146
 
68
- # Watch mode (rebuilds on changes)
69
- pnpm dev
147
+ # Enable pnpm
148
+ corepack enable
70
149
 
71
- # Type checking
72
- pnpm typecheck
150
+ # Install dependencies (from monorepo root)
151
+ pnpm install
73
152
 
74
- # Linting
75
- pnpm lint
76
- pnpm lint:fix
153
+ # Generate contract types
154
+ cd packages/sdk
155
+ pnpm codegen
77
156
  ```
78
157
 
79
- ## Testing
158
+ ### Development
80
159
 
81
160
  ```sh
82
- # Run unit tests
83
- pnpm test
84
-
85
- # Run fork tests (requires ALCHEMY_API_KEY)
86
- pnpm test:fork
161
+ pnpm build # Build the SDK
162
+ pnpm dev # Watch mode
163
+ pnpm typecheck # Type checking
164
+ pnpm lint # Linting
165
+ pnpm lint:fix # Auto-fix lint issues
166
+ ```
87
167
 
88
- # Watch mode for fork tests
89
- pnpm test:fork:watch
168
+ ### Testing
90
169
 
91
- # Run all tests (unit + fork)
92
- pnpm test:examples
170
+ ```sh
171
+ pnpm test # Unit tests
172
+ pnpm test:fork # Fork tests (requires ALCHEMY_API_KEY in .env)
173
+ pnpm test:fork:watch # Watch mode for fork tests
174
+ pnpm test:examples # All tests (unit + fork)
93
175
  ```
94
176
 
95
- ## Project Structure
177
+ ### Project Structure
96
178
 
97
- ```
179
+ ```text
98
180
  packages/sdk/
181
+ ├── docs/ # SDK documentation
99
182
  ├── src/
100
183
  │ ├── panoptic/
101
- │ │ └── v2/ # Panoptic v2 SDK
102
- │ │ ├── clients/ # Client utilities (getBlockMeta, etc.)
103
- │ │ ├── errors/ # Error types
104
- │ │ ├── simulations/ # Transaction simulations
105
- │ │ ├── sync/ # Position sync and tracking
106
- │ │ ├── types/ # TypeScript types
107
- │ │ ├── utils/ # Utility functions
108
- │ │ └── examples/ # Example implementations
109
- │ │ ├── basic/ # Basic read/write examples
110
- │ │ ├── liquidation-bot/ # Liquidation bot example
111
- │ │ └── oracle-poker/ # Oracle poker bot example
112
- └── generated/ # Auto-generated contract types
113
- ├── contracts/ # Contract ABIs (synced from contracts repo)
114
- ├── graphql/ # GraphQL schema and queries
115
- └── scripts/ # Build and sync scripts
184
+ │ │ └── v2/ # Panoptic v2 SDK
185
+ │ │ ├── reads/ # Pool, position, account reads
186
+ │ │ ├── writes/ # Transaction functions
187
+ │ │ ├── simulations/ # Dry-run simulations
188
+ │ │ ├── tokenId/ # TokenId encoding/decoding
189
+ │ │ ├── sync/ # Position tracking via events
190
+ │ │ ├── events/ # Event watching and polling
191
+ │ │ ├── formatters/ # Display formatters
192
+ │ │ ├── greeks/ # Client-side greeks
193
+ │ │ ├── bot/ # Bot utilities
194
+ │ │ ├── clients/ # viem client helpers
195
+ │ ├── storage/ # Storage adapters
196
+ │ │ ├── errors/ # Typed error classes
197
+ │ │ ├── types/ # TypeScript types
198
+ │ │ ├── utils/ # Constants
199
+ │ │ └── examples/ # Example scripts
200
+ │ └── generated/ # Auto-generated contract types
201
+ ├── contracts/ # Contract ABIs
202
+ └── scripts/ # Build and sync scripts
116
203
  ```
117
204
 
118
- ## Contract ABIs
205
+ ### Contract ABIs
119
206
 
120
207
  Contract ABIs are synced from the main contracts repository. See [ABI_GENERATION.md](./ABI_GENERATION.md) for details.
121
208
 
122
- To sync ABIs:
123
-
124
209
  ```sh
125
210
  pnpm sync-contracts
126
211
  ```
127
-
128
- ## Usage
129
-
130
- ```typescript
131
- import {
132
- simulateOpenPosition,
133
- simulateClosePosition,
134
- getBlockMeta,
135
- TokenIdBuilder,
136
- } from '@panoptic-eng/sdk'
137
- ```
138
-
139
- See the [examples](./src/panoptic/v2/examples/) directory for usage patterns.