@megatao/sdk 1.1.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.
Files changed (228) hide show
  1. package/.env.example +37 -0
  2. package/CHANGELOG.md +19 -0
  3. package/README.md +199 -0
  4. package/bin/alf +4 -0
  5. package/cli/README.md +198 -0
  6. package/cli/TEST_MANUAL.md +577 -0
  7. package/cli/commands/account.ts +545 -0
  8. package/cli/commands/funding.ts +481 -0
  9. package/cli/commands/liquidation.ts +523 -0
  10. package/cli/commands/market.ts +590 -0
  11. package/cli/commands/orders.ts +395 -0
  12. package/cli/commands/position.ts +1085 -0
  13. package/cli/commands/shared/positionUtils.ts +239 -0
  14. package/cli/commands/trading.ts +483 -0
  15. package/cli/commands/utils.ts +281 -0
  16. package/cli/commands/vault.ts +522 -0
  17. package/cli/index.ts +169 -0
  18. package/cli/interactive.ts +530 -0
  19. package/cli/utils/client.ts +457 -0
  20. package/cli/utils/config.ts +226 -0
  21. package/cli/utils/display.ts +258 -0
  22. package/cli/utils/index.ts +10 -0
  23. package/cli/utils/prompts.ts +364 -0
  24. package/config.example.json +23 -0
  25. package/dist/AlphaFuturesClient.d.ts +36 -0
  26. package/dist/AlphaFuturesClient.d.ts.map +1 -0
  27. package/dist/AlphaFuturesClient.js +116 -0
  28. package/dist/AlphaFuturesClient.js.map +1 -0
  29. package/dist/abi/Alpha.json +5987 -0
  30. package/dist/abi/abis.d.ts +319 -0
  31. package/dist/abi/abis.d.ts.map +1 -0
  32. package/dist/abi/abis.js +128 -0
  33. package/dist/abi/abis.js.map +1 -0
  34. package/dist/abi/index.d.ts +11 -0
  35. package/dist/abi/index.d.ts.map +1 -0
  36. package/dist/abi/index.js +15 -0
  37. package/dist/abi/index.js.map +1 -0
  38. package/dist/config/contracts.config.d.ts +70 -0
  39. package/dist/config/contracts.config.d.ts.map +1 -0
  40. package/dist/config/contracts.config.js +137 -0
  41. package/dist/config/contracts.config.js.map +1 -0
  42. package/dist/config/environments/alpha.config.d.ts +17 -0
  43. package/dist/config/environments/alpha.config.d.ts.map +1 -0
  44. package/dist/config/environments/alpha.config.js +140 -0
  45. package/dist/config/environments/alpha.config.js.map +1 -0
  46. package/dist/config/environments/beta.config.d.ts +16 -0
  47. package/dist/config/environments/beta.config.d.ts.map +1 -0
  48. package/dist/config/environments/beta.config.js +131 -0
  49. package/dist/config/environments/beta.config.js.map +1 -0
  50. package/dist/config/environments/dev.config.d.ts +13 -0
  51. package/dist/config/environments/dev.config.d.ts.map +1 -0
  52. package/dist/config/environments/dev.config.js +123 -0
  53. package/dist/config/environments/dev.config.js.map +1 -0
  54. package/dist/config/environments/index.d.ts +48 -0
  55. package/dist/config/environments/index.d.ts.map +1 -0
  56. package/dist/config/environments/index.js +81 -0
  57. package/dist/config/environments/index.js.map +1 -0
  58. package/dist/config/environments/localhost.config.d.ts +16 -0
  59. package/dist/config/environments/localhost.config.d.ts.map +1 -0
  60. package/dist/config/environments/localhost.config.js +152 -0
  61. package/dist/config/environments/localhost.config.js.map +1 -0
  62. package/dist/config/environments/prod.config.d.ts +20 -0
  63. package/dist/config/environments/prod.config.d.ts.map +1 -0
  64. package/dist/config/environments/prod.config.js +143 -0
  65. package/dist/config/environments/prod.config.js.map +1 -0
  66. package/dist/config/index.d.ts +7 -0
  67. package/dist/config/index.d.ts.map +1 -0
  68. package/dist/config/index.js +41 -0
  69. package/dist/config/index.js.map +1 -0
  70. package/dist/constants/assets.d.ts +76 -0
  71. package/dist/constants/assets.d.ts.map +1 -0
  72. package/dist/constants/assets.js +277 -0
  73. package/dist/constants/assets.js.map +1 -0
  74. package/dist/constants/contracts.d.ts +41 -0
  75. package/dist/constants/contracts.d.ts.map +1 -0
  76. package/dist/constants/contracts.js +57 -0
  77. package/dist/constants/contracts.js.map +1 -0
  78. package/dist/constants/index.d.ts +36 -0
  79. package/dist/constants/index.d.ts.map +1 -0
  80. package/dist/constants/index.js +75 -0
  81. package/dist/constants/index.js.map +1 -0
  82. package/dist/constants/networks.d.ts +32 -0
  83. package/dist/constants/networks.d.ts.map +1 -0
  84. package/dist/constants/networks.js +174 -0
  85. package/dist/constants/networks.js.map +1 -0
  86. package/dist/contracts/index.d.ts +5 -0
  87. package/dist/contracts/index.d.ts.map +1 -0
  88. package/dist/contracts/index.js +21 -0
  89. package/dist/contracts/index.js.map +1 -0
  90. package/dist/contracts/viem/AlphaViem.d.ts +518 -0
  91. package/dist/contracts/viem/AlphaViem.d.ts.map +1 -0
  92. package/dist/contracts/viem/AlphaViem.js +1287 -0
  93. package/dist/contracts/viem/AlphaViem.js.map +1 -0
  94. package/dist/contracts/viem/PriceOracleViem.d.ts +71 -0
  95. package/dist/contracts/viem/PriceOracleViem.d.ts.map +1 -0
  96. package/dist/contracts/viem/PriceOracleViem.js +212 -0
  97. package/dist/contracts/viem/PriceOracleViem.js.map +1 -0
  98. package/dist/contracts/viem/index.d.ts +9 -0
  99. package/dist/contracts/viem/index.d.ts.map +1 -0
  100. package/dist/contracts/viem/index.js +17 -0
  101. package/dist/contracts/viem/index.js.map +1 -0
  102. package/dist/errors/index.d.ts +44 -0
  103. package/dist/errors/index.d.ts.map +1 -0
  104. package/dist/errors/index.js +83 -0
  105. package/dist/errors/index.js.map +1 -0
  106. package/dist/index.d.ts +19 -0
  107. package/dist/index.d.ts.map +1 -0
  108. package/dist/index.js +60 -0
  109. package/dist/index.js.map +1 -0
  110. package/dist/types/alpha.d.ts +299 -0
  111. package/dist/types/alpha.d.ts.map +1 -0
  112. package/dist/types/alpha.js +6 -0
  113. package/dist/types/alpha.js.map +1 -0
  114. package/dist/types/client.d.ts +24 -0
  115. package/dist/types/client.d.ts.map +1 -0
  116. package/dist/types/client.js +13 -0
  117. package/dist/types/client.js.map +1 -0
  118. package/dist/types/contracts.d.ts +48 -0
  119. package/dist/types/contracts.d.ts.map +1 -0
  120. package/dist/types/contracts.js +6 -0
  121. package/dist/types/contracts.js.map +1 -0
  122. package/dist/types/funding.d.ts +27 -0
  123. package/dist/types/funding.d.ts.map +1 -0
  124. package/dist/types/funding.js +6 -0
  125. package/dist/types/funding.js.map +1 -0
  126. package/dist/types/index.d.ts +92 -0
  127. package/dist/types/index.d.ts.map +1 -0
  128. package/dist/types/index.js +47 -0
  129. package/dist/types/index.js.map +1 -0
  130. package/dist/types/liquidation.d.ts +20 -0
  131. package/dist/types/liquidation.d.ts.map +1 -0
  132. package/dist/types/liquidation.js +6 -0
  133. package/dist/types/liquidation.js.map +1 -0
  134. package/dist/types/margin.d.ts +29 -0
  135. package/dist/types/margin.d.ts.map +1 -0
  136. package/dist/types/margin.js +6 -0
  137. package/dist/types/margin.js.map +1 -0
  138. package/dist/types/oracle.d.ts +21 -0
  139. package/dist/types/oracle.d.ts.map +1 -0
  140. package/dist/types/oracle.js +6 -0
  141. package/dist/types/oracle.js.map +1 -0
  142. package/dist/types/positions.d.ts +43 -0
  143. package/dist/types/positions.d.ts.map +1 -0
  144. package/dist/types/positions.js +13 -0
  145. package/dist/types/positions.js.map +1 -0
  146. package/dist/utils/calculations.d.ts +84 -0
  147. package/dist/utils/calculations.d.ts.map +1 -0
  148. package/dist/utils/calculations.js +155 -0
  149. package/dist/utils/calculations.js.map +1 -0
  150. package/dist/utils/errors.d.ts +24 -0
  151. package/dist/utils/errors.d.ts.map +1 -0
  152. package/dist/utils/errors.js +129 -0
  153. package/dist/utils/errors.js.map +1 -0
  154. package/dist/utils/events.d.ts +40 -0
  155. package/dist/utils/events.d.ts.map +1 -0
  156. package/dist/utils/events.js +73 -0
  157. package/dist/utils/events.js.map +1 -0
  158. package/dist/utils/format.d.ts +40 -0
  159. package/dist/utils/format.d.ts.map +1 -0
  160. package/dist/utils/format.js +86 -0
  161. package/dist/utils/format.js.map +1 -0
  162. package/dist/utils/index.d.ts +10 -0
  163. package/dist/utils/index.d.ts.map +1 -0
  164. package/dist/utils/index.js +26 -0
  165. package/dist/utils/index.js.map +1 -0
  166. package/dist/utils/network.d.ts +52 -0
  167. package/dist/utils/network.d.ts.map +1 -0
  168. package/dist/utils/network.js +192 -0
  169. package/dist/utils/network.js.map +1 -0
  170. package/dist/utils/positionCalculations.d.ts +145 -0
  171. package/dist/utils/positionCalculations.d.ts.map +1 -0
  172. package/dist/utils/positionCalculations.js +278 -0
  173. package/dist/utils/positionCalculations.js.map +1 -0
  174. package/dist/utils/validation.d.ts +28 -0
  175. package/dist/utils/validation.d.ts.map +1 -0
  176. package/dist/utils/validation.js +68 -0
  177. package/dist/utils/validation.js.map +1 -0
  178. package/docs/README.md +40 -0
  179. package/docs/api/API.md +831 -0
  180. package/docs/guides/GETTING_STARTED.md +316 -0
  181. package/docs/guides/TRADING_GUIDE.md +677 -0
  182. package/docs/integration/INTEGRATION_GUIDE.md +1679 -0
  183. package/docs/integration/VIEM_INTEGRATION.md +294 -0
  184. package/docs/reference/CLI_QUICK_REFERENCE.md +197 -0
  185. package/docs/reference/TROUBLESHOOTING.md +922 -0
  186. package/package.json +113 -0
  187. package/src/AlphaFuturesClient.ts +158 -0
  188. package/src/abi/.gitkeep +1 -0
  189. package/src/abi/Alpha.json +5987 -0
  190. package/src/abi/README.md +99 -0
  191. package/src/abi/abis.ts +131 -0
  192. package/src/abi/index.ts +13 -0
  193. package/src/config/contracts.config.ts +186 -0
  194. package/src/config/environments/alpha.config.ts +139 -0
  195. package/src/config/environments/beta.config.ts +130 -0
  196. package/src/config/environments/dev.config.ts +122 -0
  197. package/src/config/environments/index.ts +87 -0
  198. package/src/config/environments/localhost.config.ts +153 -0
  199. package/src/config/environments/prod.config.ts +142 -0
  200. package/src/config/index.ts +29 -0
  201. package/src/constants/assets.ts +299 -0
  202. package/src/constants/contracts.ts +64 -0
  203. package/src/constants/index.ts +69 -0
  204. package/src/constants/networks.ts +182 -0
  205. package/src/contracts/index.ts +5 -0
  206. package/src/contracts/viem/AlphaViem.ts +1615 -0
  207. package/src/contracts/viem/PriceOracleViem.ts +272 -0
  208. package/src/contracts/viem/index.ts +11 -0
  209. package/src/errors/index.ts +87 -0
  210. package/src/index.ts +59 -0
  211. package/src/types/VIEM_TYPES_README.md +70 -0
  212. package/src/types/alpha.ts +358 -0
  213. package/src/types/client.ts +27 -0
  214. package/src/types/contracts.ts +74 -0
  215. package/src/types/funding.ts +31 -0
  216. package/src/types/index.ts +108 -0
  217. package/src/types/liquidation.ts +23 -0
  218. package/src/types/margin.ts +34 -0
  219. package/src/types/oracle.ts +24 -0
  220. package/src/types/positions.ts +48 -0
  221. package/src/utils/calculations.ts +175 -0
  222. package/src/utils/errors.ts +147 -0
  223. package/src/utils/events.ts +98 -0
  224. package/src/utils/format.ts +84 -0
  225. package/src/utils/index.ts +10 -0
  226. package/src/utils/network.ts +212 -0
  227. package/src/utils/positionCalculations.ts +317 -0
  228. package/src/utils/validation.ts +76 -0
@@ -0,0 +1,831 @@
1
+ # Alpha Futures SDK API Reference
2
+
3
+ ## Table of Contents
4
+
5
+ - [Overview](#overview)
6
+ - [Client Initialization](#client-initialization)
7
+ - [Margin Account Management](#margin-account-management)
8
+ - [Position Management](#position-management)
9
+ - [Price Oracle](#price-oracle)
10
+ - [Funding Rates](#funding-rates)
11
+ - [Liquidation](#liquidation)
12
+ - [Protocol Vault](#protocol-vault)
13
+ - [Utilities](#utilities)
14
+ - [Types](#types)
15
+ - [Error Handling](#error-handling)
16
+
17
+ ## Overview
18
+
19
+ The Alpha Futures SDK provides a comprehensive TypeScript/JavaScript interface for interacting with the Alpha Futures perpetual futures protocol on Bittensor EVM.
20
+
21
+ ### Installation
22
+
23
+ ```bash
24
+ npm install @alpha-futures/sdk
25
+ ```
26
+
27
+ ### Basic Usage
28
+
29
+ ```typescript
30
+ import { AlphaFuturesClient } from '@alpha-futures/sdk';
31
+
32
+ const client = new AlphaFuturesClient({
33
+ rpcUrl: 'https://your-rpc-url',
34
+ privateKey: 'your-private-key',
35
+ network: 'mainnet'
36
+ });
37
+ ```
38
+
39
+ ## Client Initialization
40
+
41
+ ### AlphaFuturesClient
42
+
43
+ The main entry point for interacting with the protocol.
44
+
45
+ #### Constructor
46
+
47
+ ```typescript
48
+ new AlphaFuturesClient(config: ClientConfig)
49
+ ```
50
+
51
+ **Parameters:**
52
+ - `config: ClientConfig` - Client configuration object
53
+
54
+ **ClientConfig:**
55
+ ```typescript
56
+ interface ClientConfig {
57
+ provider?: Provider; // Ethers provider instance
58
+ signer?: Signer; // Ethers signer instance
59
+ rpcUrl?: string; // RPC URL (alternative to provider)
60
+ privateKey?: string; // Private key (alternative to signer)
61
+ network?: string; // Network name ('mainnet', 'testnet', 'localhost')
62
+ networkConfig?: NetworkConfig; // Custom network configuration
63
+ }
64
+ ```
65
+
66
+ **Example:**
67
+ ```typescript
68
+ // Using RPC URL and private key
69
+ const client = new AlphaFuturesClient({
70
+ rpcUrl: 'https://eth-mainnet.alchemyapi.io/v2/your-api-key',
71
+ privateKey: '0x...',
72
+ network: 'mainnet'
73
+ });
74
+
75
+ // Using existing provider and signer
76
+ const provider = new ethers.JsonRpcProvider(rpcUrl);
77
+ const signer = new ethers.Wallet(privateKey, provider);
78
+ const client = new AlphaFuturesClient({
79
+ provider,
80
+ signer,
81
+ network: 'mainnet'
82
+ });
83
+ ```
84
+
85
+ ## Margin Account Management
86
+
87
+ ### marginAccount.getMarginAccount()
88
+
89
+ Get margin account information for a trader.
90
+
91
+ ```typescript
92
+ async getMarginAccount(trader: string): Promise<MarginAccountInfo>
93
+ ```
94
+
95
+ **Parameters:**
96
+ - `trader: string` - Ethereum address of the trader
97
+
98
+ **Returns:** `MarginAccountInfo`
99
+ ```typescript
100
+ interface MarginAccountInfo {
101
+ user: string; // Trader address
102
+ totalDeposited: bigint; // Total TAO deposited
103
+ totalWithdrawn: bigint; // Total TAO withdrawn
104
+ availableMargin: bigint; // Available margin for new positions
105
+ usedMargin: bigint; // Margin locked in positions
106
+ unrealizedPnL: bigint; // Unrealized profit/loss
107
+ marginRatio: bigint; // Current margin ratio in basis points
108
+ }
109
+ ```
110
+
111
+ ### marginAccount.deposit()
112
+
113
+ Deposit TAO as margin.
114
+
115
+ ```typescript
116
+ async deposit(amount: bigint, options?: TransactionOptions): Promise<TransactionResponse>
117
+ ```
118
+
119
+ **Parameters:**
120
+ - `amount: bigint` - Amount of TAO to deposit (in wei)
121
+ - `options?: TransactionOptions` - Optional transaction parameters
122
+
123
+ **Example:**
124
+ ```typescript
125
+ const amount = parseEther('1000'); // 1000 TAO (using viem)
126
+ const tx = await client.marginAccount.deposit(amount);
127
+ await tx.wait();
128
+ ```
129
+
130
+ ### marginAccount.withdraw()
131
+
132
+ Withdraw available margin.
133
+
134
+ ```typescript
135
+ async withdraw(amount: bigint, options?: TransactionOptions): Promise<TransactionResponse>
136
+ ```
137
+
138
+ **Parameters:**
139
+ - `amount: bigint` - Amount of TAO to withdraw (in wei)
140
+ - `options?: TransactionOptions` - Optional transaction parameters
141
+
142
+ ### marginAccount.getTransactionHistory()
143
+
144
+ Get deposit/withdrawal history.
145
+
146
+ ```typescript
147
+ async getTransactionHistory(
148
+ trader: string,
149
+ fromBlock?: number,
150
+ toBlock?: number
151
+ ): Promise<TransactionHistory[]>
152
+ ```
153
+
154
+ ## Position Management
155
+
156
+ ### positionManager.openPosition()
157
+
158
+ Open a new leveraged position.
159
+
160
+ ```typescript
161
+ async openPosition(params: OpenPositionParams, options?: TransactionOptions): Promise<TransactionResponse>
162
+ ```
163
+
164
+ **Parameters:**
165
+ - `params: OpenPositionParams` - Position parameters
166
+ - `options?: TransactionOptions` - Optional transaction parameters
167
+
168
+ **OpenPositionParams:**
169
+ ```typescript
170
+ interface OpenPositionParams {
171
+ asset: string; // Asset symbol (e.g., 'ALPHA')
172
+ size: bigint; // Position size in TAO (in wei)
173
+ leverage: number; // Leverage (1-10)
174
+ isLong: boolean; // true for long, false for short
175
+ slippage?: number; // Max slippage in basis points
176
+ deadline?: number; // Transaction deadline timestamp
177
+ }
178
+ ```
179
+
180
+ **Example:**
181
+ ```typescript
182
+ const tx = await client.positionManager.openPosition({
183
+ asset: 'ALPHA',
184
+ size: ethers.parseEther('3000'),
185
+ leverage: 3,
186
+ isLong: true,
187
+ slippage: 50 // 0.5%
188
+ });
189
+ await tx.wait();
190
+ ```
191
+
192
+ ### positionManager.closePosition()
193
+
194
+ Close an existing position.
195
+
196
+ ```typescript
197
+ async closePosition(
198
+ positionId: bigint,
199
+ options?: TransactionOptions
200
+ ): Promise<TransactionResponse>
201
+ ```
202
+
203
+ **Parameters:**
204
+ - `positionId: bigint` - ID of the position to close
205
+ - `options?: TransactionOptions` - Optional transaction parameters
206
+
207
+ ### positionManager.modifyPosition()
208
+
209
+ Add or remove margin from a position.
210
+
211
+ ```typescript
212
+ async modifyPosition(
213
+ positionId: bigint,
214
+ marginDelta: bigint,
215
+ isAdd: boolean,
216
+ options?: TransactionOptions
217
+ ): Promise<TransactionResponse>
218
+ ```
219
+
220
+ **Parameters:**
221
+ - `positionId: bigint` - ID of the position
222
+ - `marginDelta: bigint` - Amount of margin to add/remove (in wei)
223
+ - `isAdd: boolean` - true to add margin, false to remove
224
+ - `options?: TransactionOptions` - Optional transaction parameters
225
+
226
+ ### positionManager.getPosition()
227
+
228
+ Get details of a specific position.
229
+
230
+ ```typescript
231
+ async getPosition(positionId: bigint): Promise<Position>
232
+ ```
233
+
234
+ **Returns:** `Position`
235
+ ```typescript
236
+ interface Position {
237
+ id: bigint;
238
+ trader: string;
239
+ asset: string;
240
+ size: bigint;
241
+ isLong: boolean;
242
+ leverage: bigint;
243
+ entryPrice: bigint;
244
+ margin: bigint;
245
+ lastFundingIndex: bigint;
246
+ openTimestamp: bigint;
247
+ unrealizedPnL?: bigint;
248
+ marginRatio?: bigint;
249
+ liquidationPrice?: bigint;
250
+ }
251
+ ```
252
+
253
+ ### positionManager.getAllPositions()
254
+
255
+ Get all positions for a trader.
256
+
257
+ ```typescript
258
+ async getAllPositions(trader: string): Promise<Position[]>
259
+ ```
260
+
261
+ ### positionManager.getPositionsByAsset()
262
+
263
+ Get all positions for a specific asset.
264
+
265
+ ```typescript
266
+ async getPositionsByAsset(asset: string): Promise<Position[]>
267
+ ```
268
+
269
+ ## Price Oracle
270
+
271
+ ### priceOracle.getPrice()
272
+
273
+ Get the current price of an asset.
274
+
275
+ ```typescript
276
+ async getPrice(asset: string): Promise<bigint>
277
+ ```
278
+
279
+ **Parameters:**
280
+ - `asset: string` - Asset symbol
281
+
282
+ **Returns:** Current price in wei (18 decimals)
283
+
284
+ ### priceOracle.getAllPrices()
285
+
286
+ Get prices for all supported assets.
287
+
288
+ ```typescript
289
+ async getAllPrices(): Promise<PriceInfo[]>
290
+ ```
291
+
292
+ **Returns:** Array of `PriceInfo`
293
+ ```typescript
294
+ interface PriceInfo {
295
+ asset: string;
296
+ price: bigint;
297
+ timestamp: number;
298
+ confidence?: bigint; // Price confidence in basis points
299
+ source?: string; // Price source identifier
300
+ }
301
+ ```
302
+
303
+ ### priceOracle.isPriceFresh()
304
+
305
+ Check if a price is fresh (not stale).
306
+
307
+ ```typescript
308
+ async isPriceFresh(asset: string, maxAge: number): Promise<boolean>
309
+ ```
310
+
311
+ **Parameters:**
312
+ - `asset: string` - Asset symbol
313
+ - `maxAge: number` - Maximum age in seconds
314
+
315
+ ## Funding Rates
316
+
317
+ ### fundingRate.getCurrentFundingRate()
318
+
319
+ Get the current funding rate for an asset.
320
+
321
+ ```typescript
322
+ async getCurrentFundingRate(asset: string): Promise<FundingRateInfo>
323
+ ```
324
+
325
+ **Returns:** `FundingRateInfo`
326
+ ```typescript
327
+ interface FundingRateInfo {
328
+ asset: string;
329
+ rate: bigint; // Rate in basis points (always positive)
330
+ isPositive: boolean; // true if longs pay shorts
331
+ nextUpdateTime: bigint; // Next funding rate update timestamp
332
+ accumulatedIndex: bigint; // Accumulated funding index
333
+ }
334
+ ```
335
+
336
+ ### fundingRate.getAllFundingRates()
337
+
338
+ Get funding rates for all assets.
339
+
340
+ ```typescript
341
+ async getAllFundingRates(): Promise<FundingRateInfo[]>
342
+ ```
343
+
344
+ ### fundingRate.getAccumulatedFunding()
345
+
346
+ Calculate accumulated funding between two indices.
347
+
348
+ ```typescript
349
+ async getAccumulatedFunding(
350
+ asset: string,
351
+ startIndex: bigint,
352
+ endIndex: bigint
353
+ ): Promise<bigint>
354
+ ```
355
+
356
+ ### fundingRate.applyFunding()
357
+
358
+ Apply funding to a specific position.
359
+
360
+ ```typescript
361
+ async applyFunding(
362
+ positionId: bigint,
363
+ options?: TransactionOptions
364
+ ): Promise<TransactionResponse>
365
+ ```
366
+
367
+ ## Liquidation
368
+
369
+ ### liquidationEngine.checkLiquidationStatus()
370
+
371
+ Check if a position can be liquidated.
372
+
373
+ ```typescript
374
+ async checkLiquidationStatus(positionId: bigint): Promise<LiquidationStatus>
375
+ ```
376
+
377
+ **Returns:** `LiquidationStatus`
378
+ ```typescript
379
+ interface LiquidationStatus {
380
+ canLiquidate: boolean;
381
+ marginRatio: bigint; // Current margin ratio in basis points
382
+ requiredMargin: bigint; // Required maintenance margin
383
+ currentMargin: bigint; // Current position margin
384
+ liquidationPrice: bigint; // Price at which position will be liquidated
385
+ }
386
+ ```
387
+
388
+ ### liquidationEngine.liquidatePosition()
389
+
390
+ Liquidate an underwater position.
391
+
392
+ ```typescript
393
+ async liquidatePosition(
394
+ positionId: bigint,
395
+ options?: TransactionOptions
396
+ ): Promise<TransactionResponse>
397
+ ```
398
+
399
+ ### liquidationEngine.getAtRiskPositions()
400
+
401
+ Get all positions at risk of liquidation.
402
+
403
+ ```typescript
404
+ async getAtRiskPositions(threshold?: bigint): Promise<AtRiskPosition[]>
405
+ ```
406
+
407
+ **Parameters:**
408
+ - `threshold?: bigint` - Margin ratio threshold (default: 250 = 25%)
409
+
410
+ **Returns:** Array of `AtRiskPosition`
411
+ ```typescript
412
+ interface AtRiskPosition {
413
+ positionId: bigint;
414
+ marginRatio: bigint;
415
+ liquidationPrice: bigint;
416
+ trader: string;
417
+ asset: string;
418
+ }
419
+ ```
420
+
421
+ ### liquidationEngine.getLiquidationHistory()
422
+
423
+ Get liquidation history.
424
+
425
+ ```typescript
426
+ async getLiquidationHistory(
427
+ fromBlock?: number,
428
+ toBlock?: number
429
+ ): Promise<LiquidationEvent[]>
430
+ ```
431
+
432
+ ## Protocol Vault
433
+
434
+ ### protocolVault.getVaultStats()
435
+
436
+ Get protocol vault statistics.
437
+
438
+ ```typescript
439
+ async getVaultStats(): Promise<VaultStats>
440
+ ```
441
+
442
+ **Returns:** `VaultStats`
443
+ ```typescript
444
+ interface VaultStats {
445
+ totalReserves: bigint; // Total TAO in vault
446
+ totalBorrowed: bigint; // TAO borrowed for positions
447
+ utilizationRate: bigint; // Utilization in basis points
448
+ availableLiquidity: bigint; // Available for new positions
449
+ insuranceFund: bigint; // Insurance fund balance
450
+ totalFees24h: bigint; // Fees collected in last 24h
451
+ apy: bigint; // Annual percentage yield in basis points
452
+ }
453
+ ```
454
+
455
+ ### protocolVault.getVaultBalance()
456
+
457
+ Get current vault balance.
458
+
459
+ ```typescript
460
+ async getVaultBalance(): Promise<bigint>
461
+ ```
462
+
463
+ ### protocolVault.getVaultPerformance()
464
+
465
+ Get vault performance metrics.
466
+
467
+ ```typescript
468
+ async getVaultPerformance(): Promise<VaultPerformance>
469
+ ```
470
+
471
+ **Returns:** `VaultPerformance`
472
+ ```typescript
473
+ interface VaultPerformance {
474
+ totalFees: bigint;
475
+ totalLiquidations: bigint;
476
+ apy: bigint;
477
+ utilizationHistory: UtilizationPoint[];
478
+ }
479
+ ```
480
+
481
+ ## Utilities
482
+
483
+ ### Calculation Utilities
484
+
485
+ ```typescript
486
+ import {
487
+ calculateInitialMargin,
488
+ calculateMaintenanceMargin,
489
+ calculateLeverage,
490
+ calculatePositionSize,
491
+ calculateUnrealizedPnL,
492
+ calculateMarginRatio,
493
+ calculateLiquidationPrice,
494
+ calculateTradingFee,
495
+ calculateFundingPayment,
496
+ calculatePriceImpact
497
+ } from '@alpha-futures/sdk/utils';
498
+ ```
499
+
500
+ #### calculateInitialMargin()
501
+ ```typescript
502
+ function calculateInitialMargin(positionSize: bigint): bigint
503
+ ```
504
+ Calculate required initial margin for a position size.
505
+
506
+ #### calculateUnrealizedPnL()
507
+ ```typescript
508
+ function calculateUnrealizedPnL(
509
+ isLong: boolean,
510
+ size: bigint,
511
+ entryPrice: bigint,
512
+ currentPrice: bigint
513
+ ): bigint
514
+ ```
515
+ Calculate unrealized profit/loss for a position.
516
+
517
+ #### calculateLiquidationPrice()
518
+ ```typescript
519
+ function calculateLiquidationPrice(
520
+ isLong: boolean,
521
+ entryPrice: bigint,
522
+ margin: bigint,
523
+ positionSize: bigint
524
+ ): bigint
525
+ ```
526
+ Calculate the liquidation price for a position.
527
+
528
+ ### Format Utilities
529
+
530
+ ```typescript
531
+ import {
532
+ formatAmount,
533
+ formatPrice,
534
+ formatPercentage,
535
+ formatLeverage,
536
+ parseAmount,
537
+ shortenAddress,
538
+ formatTimestamp
539
+ } from '@alpha-futures/sdk/utils';
540
+ ```
541
+
542
+ #### formatAmount()
543
+ ```typescript
544
+ function formatAmount(amount: bigint, decimals?: number): string
545
+ ```
546
+ Format TAO amount for display (e.g., "1,234.56").
547
+
548
+ #### formatPrice()
549
+ ```typescript
550
+ function formatPrice(price: bigint): string
551
+ ```
552
+ Format price for display (e.g., "$123.45").
553
+
554
+ #### formatPercentage()
555
+ ```typescript
556
+ function formatPercentage(basisPoints: bigint, decimals?: number): string
557
+ ```
558
+ Format basis points as percentage (e.g., "12.34%").
559
+
560
+ ### Validation Utilities
561
+
562
+ ```typescript
563
+ import {
564
+ validateAddress,
565
+ validatePositionSize,
566
+ validateLeverage,
567
+ validatePositiveAmount,
568
+ validateAsset,
569
+ validateMargin
570
+ } from '@alpha-futures/sdk/utils';
571
+ ```
572
+
573
+ All validation functions throw `ValidationError` on failure.
574
+
575
+ ## Types
576
+
577
+ ### Core Types
578
+
579
+ ```typescript
580
+ // Position information
581
+ interface Position {
582
+ id: bigint;
583
+ trader: string;
584
+ asset: string;
585
+ size: bigint;
586
+ isLong: boolean;
587
+ leverage: bigint;
588
+ entryPrice: bigint;
589
+ margin: bigint;
590
+ lastFundingIndex: bigint;
591
+ openTimestamp: bigint;
592
+ unrealizedPnL?: bigint;
593
+ marginRatio?: bigint;
594
+ liquidationPrice?: bigint;
595
+ }
596
+
597
+ // Transaction options
598
+ interface TransactionOptions {
599
+ gasLimit?: bigint;
600
+ gasPrice?: bigint;
601
+ maxFeePerGas?: bigint;
602
+ maxPriorityFeePerGas?: bigint;
603
+ nonce?: number;
604
+ value?: bigint;
605
+ }
606
+
607
+ // Network configuration
608
+ interface NetworkConfig {
609
+ chainId: number;
610
+ name: string;
611
+ rpcUrl?: string;
612
+ contracts: {
613
+ marginAccount: string;
614
+ positionManager: string;
615
+ fundingRate: string;
616
+ liquidationEngine: string;
617
+ protocolVault: string;
618
+ priceOracle: string;
619
+ taoToken: string;
620
+ alphaFuturesOrderBook?: string;
621
+ };
622
+ blockExplorer?: string;
623
+ }
624
+ ```
625
+
626
+ ## Error Handling
627
+
628
+ The SDK provides custom error types for better error handling:
629
+
630
+ ### ValidationError
631
+
632
+ Thrown when input validation fails.
633
+
634
+ ```typescript
635
+ class ValidationError extends Error {
636
+ field: string;
637
+ value?: any;
638
+ }
639
+ ```
640
+
641
+ ### ContractError
642
+
643
+ Thrown when contract calls fail.
644
+
645
+ ```typescript
646
+ class ContractError extends Error {
647
+ code: string;
648
+ reason?: string;
649
+ }
650
+ ```
651
+
652
+ ### NetworkError
653
+
654
+ Thrown on network-related issues.
655
+
656
+ ```typescript
657
+ class NetworkError extends Error {
658
+ code: string;
659
+ }
660
+ ```
661
+
662
+ ### Example Error Handling
663
+
664
+ ```typescript
665
+ try {
666
+ await client.positionManager.openPosition({
667
+ asset: 'ALPHA',
668
+ size: ethers.parseEther('1000'),
669
+ leverage: 3,
670
+ isLong: true
671
+ });
672
+ } catch (error) {
673
+ if (error instanceof ValidationError) {
674
+ console.error(`Validation failed for ${error.field}: ${error.message}`);
675
+ } else if (error instanceof ContractError) {
676
+ console.error(`Contract error: ${error.reason || error.message}`);
677
+ } else if (error instanceof NetworkError) {
678
+ console.error(`Network error: ${error.message}`);
679
+ } else {
680
+ console.error(`Unknown error: ${error.message}`);
681
+ }
682
+ }
683
+ ```
684
+
685
+ ## Event Listening
686
+
687
+ The SDK supports listening to protocol events:
688
+
689
+ ```typescript
690
+ // Listen for position opened events
691
+ client.positionManager.on('PositionOpened', (
692
+ positionId: bigint,
693
+ trader: string,
694
+ asset: string,
695
+ size: bigint,
696
+ isLong: boolean,
697
+ leverage: bigint
698
+ ) => {
699
+ console.log(`Position ${positionId} opened`);
700
+ });
701
+
702
+ // Listen for liquidation events
703
+ client.liquidationEngine.on('PositionLiquidated', (
704
+ positionId: bigint,
705
+ liquidator: string,
706
+ remainingMargin: bigint,
707
+ liquidationBonus: bigint
708
+ ) => {
709
+ console.log(`Position ${positionId} liquidated`);
710
+ });
711
+
712
+ // Query historical events
713
+ const events = await client.positionManager.queryFilter(
714
+ client.positionManager.filters.PositionOpened(null, traderAddress),
715
+ fromBlock,
716
+ toBlock
717
+ );
718
+ ```
719
+
720
+ ## Gas Estimation
721
+
722
+ The SDK provides gas estimation for all transactions:
723
+
724
+ ```typescript
725
+ // Estimate gas before sending transaction
726
+ const estimatedGas = await client.positionManager.estimateGas.openPosition({
727
+ asset: 'ALPHA',
728
+ size: ethers.parseEther('1000'),
729
+ leverage: 3,
730
+ isLong: true
731
+ });
732
+
733
+ // Use estimated gas with buffer
734
+ const tx = await client.positionManager.openPosition(
735
+ {
736
+ asset: 'ALPHA',
737
+ size: ethers.parseEther('1000'),
738
+ leverage: 3,
739
+ isLong: true
740
+ },
741
+ {
742
+ gasLimit: estimatedGas * 120n / 100n // 20% buffer
743
+ }
744
+ );
745
+ ```
746
+
747
+ ## Constants
748
+
749
+ The SDK exports useful constants:
750
+
751
+ ```typescript
752
+ import {
753
+ PRECISION, // 10^18
754
+ BASIS_POINTS, // 10^4
755
+ MIN_POSITION_SIZE, // Minimum position size
756
+ MAX_LEVERAGE, // Maximum leverage (10x)
757
+ INITIAL_MARGIN_RATIO, // Initial margin requirement (3333 = 33.33%)
758
+ MAINTENANCE_MARGIN_RATIO, // Maintenance margin (2000 = 20%)
759
+ LIQUIDATION_BONUS, // Liquidation incentive (500 = 5%)
760
+ TRADING_FEE, // Trading fee (10 = 0.1%)
761
+ SUPPORTED_ASSETS // Array of supported asset symbols
762
+ } from '@alpha-futures/sdk/constants';
763
+ ```
764
+
765
+ ## Advanced Usage
766
+
767
+ ### Custom Network Configuration
768
+
769
+ ```typescript
770
+ const customConfig: NetworkConfig = {
771
+ chainId: 1337,
772
+ name: 'custom-network',
773
+ rpcUrl: 'http://localhost:8545',
774
+ contracts: {
775
+ marginAccount: '0x...',
776
+ positionManager: '0x...',
777
+ fundingRate: '0x...',
778
+ liquidationEngine: '0x...',
779
+ protocolVault: '0x...',
780
+ priceOracle: '0x...',
781
+ taoToken: '0x...'
782
+ }
783
+ };
784
+
785
+ const client = new AlphaFuturesClient({
786
+ rpcUrl: customConfig.rpcUrl,
787
+ privateKey: 'your-private-key',
788
+ networkConfig: customConfig
789
+ });
790
+ ```
791
+
792
+ ### Batch Operations
793
+
794
+ ```typescript
795
+ // Open multiple positions in sequence
796
+ const positions = [
797
+ { asset: 'ALPHA', size: ethers.parseEther('1000'), leverage: 2, isLong: true },
798
+ { asset: 'BETA', size: ethers.parseEther('2000'), leverage: 3, isLong: false }
799
+ ];
800
+
801
+ const txHashes = [];
802
+ for (const pos of positions) {
803
+ const tx = await client.positionManager.openPosition(pos);
804
+ txHashes.push(tx.hash);
805
+ await tx.wait(); // Wait for confirmation
806
+ }
807
+ ```
808
+
809
+ ### Error Recovery
810
+
811
+ ```typescript
812
+ async function openPositionWithRetry(params: OpenPositionParams, maxRetries = 3) {
813
+ for (let i = 0; i < maxRetries; i++) {
814
+ try {
815
+ const tx = await client.positionManager.openPosition(params);
816
+ return await tx.wait();
817
+ } catch (error) {
818
+ if (i === maxRetries - 1) throw error;
819
+
820
+ // Check if error is retryable
821
+ if (error.message.includes('nonce too low')) {
822
+ // Wait and retry
823
+ await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
824
+ continue;
825
+ }
826
+
827
+ throw error; // Non-retryable error
828
+ }
829
+ }
830
+ }
831
+ ```