@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
package/.env.example ADDED
@@ -0,0 +1,37 @@
1
+ # Required Configuration
2
+ PRIVATE_KEY=your_private_key_here
3
+
4
+ # Network Configuration (optional)
5
+ NETWORK=mainnet
6
+ RPC_URL=https://your-rpc-endpoint.com
7
+
8
+ # Contract Addresses (optional - uses defaults if not specified)
9
+ POSITION_MANAGER_ADDRESS=0x0000000000000000000000000000000000000000
10
+ MARGIN_ACCOUNT_ADDRESS=0x0000000000000000000000000000000000000000
11
+ FUNDING_RATE_ADDRESS=0x0000000000000000000000000000000000000000
12
+ LIQUIDATION_ENGINE_ADDRESS=0x0000000000000000000000000000000000000000
13
+ PROTOCOL_VAULT_ADDRESS=0x0000000000000000000000000000000000000000
14
+ PRICE_ORACLE_ADDRESS=0x0000000000000000000000000000000000000000
15
+
16
+ # Trading Settings (optional)
17
+ DEFAULT_LEVERAGE=3
18
+ DEFAULT_SLIPPAGE=0.5
19
+ MAX_LEVERAGE=10
20
+ MIN_POSITION_SIZE=100
21
+
22
+ # Gas Settings (optional)
23
+ GAS_PRICE_MULTIPLIER=1.1
24
+ MAX_GAS_PRICE=100
25
+ GAS_LIMIT=500000
26
+
27
+ # Display Settings (optional)
28
+ DISPLAY_CURRENCY=USD
29
+ DISPLAY_DECIMALS=2
30
+
31
+ # API Keys (if using external services)
32
+ COINGECKO_API_KEY=
33
+ ETHERSCAN_API_KEY=
34
+
35
+ # Development Settings
36
+ DEBUG=false
37
+ LOG_LEVEL=info
package/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ ## 1.1.0
4
+
5
+ - Maker/taker fee support
6
+ - Configurable funding parameters
7
+ - Improved error handling with full custom error decoding
8
+ - `simulateAndWriteContract` walks viem error chain for decoded error names
9
+ - Added `contractErrorName` and `contractErrorArgs` to simulation errors
10
+
11
+ ## 1.0.0
12
+
13
+ - Initial release
14
+ - Viem-based contract interactions for Alpha Futures protocol
15
+ - Position management (open, close, liquidate)
16
+ - Margin management (deposit, withdraw)
17
+ - Order management (limit orders, cancel)
18
+ - Market data queries (depth, spread, funding)
19
+ - CLI tool (`alf`)
package/README.md ADDED
@@ -0,0 +1,199 @@
1
+ # @megatao/sdk
2
+
3
+ TypeScript SDK for the Alpha Futures perpetual futures protocol on Bittensor EVM.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @megatao/sdk
9
+ ```
10
+
11
+ **Peer dependency:** requires `viem ^2.0.0`
12
+
13
+ ## Quick Start
14
+
15
+ ```typescript
16
+ import { AlphaFuturesClient, parseEther } from '@megatao/sdk';
17
+
18
+ const client = new AlphaFuturesClient('localhost', {
19
+ rpcUrl: 'http://localhost:8545',
20
+ privateKey: '0x...',
21
+ });
22
+
23
+ const alpha = client.getAlpha();
24
+
25
+ await alpha.deposit(parseEther('100'));
26
+ await alpha.openMarketPosition(
27
+ '0xMarketAddress',
28
+ true, // isLong
29
+ parseEther('10'), // margin
30
+ 3000000000000000000n, // 3x leverage (1e18 format)
31
+ 100n, // maxSlippage (bps)
32
+ );
33
+ ```
34
+
35
+ ## Architecture
36
+
37
+ `AlphaFuturesClient` creates viem clients internally and exposes two contract wrappers:
38
+
39
+ - **`client.getAlpha()`** → `AlphaViem` — all trading, margin, positions, orders, vault, and market operations
40
+ - **`client.oracle`** → `PriceOracleViem` — price feeds from the on-chain oracle
41
+
42
+ All value parameters use native `bigint`. Prices, leverage, and margin use **1e18** precision. Slippage is in **basis points**.
43
+
44
+ ## API Reference
45
+
46
+ ### Trading
47
+
48
+ | Method | Params | Description |
49
+ |--------|--------|-------------|
50
+ | `openMarketPosition` | `market, isLong, margin, leverage, maxSlippage` | Open a market position with slippage protection |
51
+ | `openMarketPositionWithStruct` | `MarketPositionParams` | Open position using a params struct |
52
+ | `closePosition` | `positionId, sizeToClose` | Close (or partially close) a position |
53
+ | `closeAllPositions` | `positionIds[]` | Batch-close multiple positions via multicall |
54
+ | `multicall` | `{functionName, args}[]` | Batch arbitrary contract calls in one tx |
55
+ | `placeLimitOrder` | `market, isBuy, margin, leverage, price, reduceOnlyType?` | Place a limit order on the orderbook |
56
+ | `placeLimitOrderWithStruct` | `LimitOrderParams` | Place limit order using a params struct |
57
+ | `cancelOrder` | `orderId` | Cancel a specific limit order |
58
+ | `cancelAllOrders` | `market` | Cancel all orders in a market |
59
+
60
+ ### Margin
61
+
62
+ | Method | Params | Description |
63
+ |--------|--------|-------------|
64
+ | `deposit` | `amount` | Deposit collateral (sends native value for native token) |
65
+ | `withdraw` | `amount` | Withdraw available margin |
66
+ | `getMarginBalance` | `trader` | Raw deposited balance (excludes unrealized PnL) |
67
+ | `getAccountSummary` | `trader` | Balance, equity, unrealized PnL, locked and available margin |
68
+ | `getLockedMargin` | `trader` | Margin locked in open positions |
69
+ | `getAvailableMargin` | `trader` | Free margin available for new trades |
70
+ | `getMaxUserDeposit` | — | Per-user deposit cap |
71
+ | `getMaxGlobalDeposits` | — | Protocol-wide deposit cap |
72
+ | `getTotalDeposits` | — | Total deposits across all users |
73
+
74
+ ### Positions
75
+
76
+ | Method | Params | Description |
77
+ |--------|--------|-------------|
78
+ | `getPosition` | `positionId` | Full position data (margin, notional, entry price, etc.) |
79
+ | `getPositionDetails` | `positionId` | Extended position details struct |
80
+ | `getPositionId` | `trader, market` | Derive position ID from trader + market |
81
+ | `hasPosition` | `trader, market` | Check if a position exists |
82
+ | `getUserPositions` | `trader` | All position IDs for a trader |
83
+ | `getUserPositionsSummary` | `trader` | Aggregate stats across all positions |
84
+ | `calculateUnrealizedPnl` | `positionId` | Current unrealized PnL |
85
+ | `getMarginRatio` | `positionId` | Current margin ratio |
86
+ | `isLiquidatable` | `positionId` | Whether position can be liquidated |
87
+ | `getLiquidationStatus` | `positionId` | Liquidatable flag, margin ratio, required margin, liq price |
88
+
89
+ ### Orders
90
+
91
+ | Method | Params | Description |
92
+ |--------|--------|-------------|
93
+ | `getBestBid` | `market` | Best bid order ID |
94
+ | `getBestAsk` | `market` | Best ask order ID |
95
+ | `getUserOrders` | `trader, market` | All open order IDs for a trader in a market |
96
+ | `getOrderDetails` | `orderId` | Order info (trader, direction, notional, price, reduceOnly) |
97
+
98
+ ### Markets
99
+
100
+ | Method | Params | Description |
101
+ |--------|--------|-------------|
102
+ | `getMarketInfo` | `market` | OI, funding rate, active status, leverage/margin params |
103
+ | `getMarketOpenInterest` | `market` | Long and short open interest |
104
+ | `getFundingRate` | `market` | Current funding rate |
105
+ | `getFundingState` | `market` | Rate, cumulative index, last update, next funding time |
106
+ | `getMaxPositionSize` | `market` | Maximum allowed position size |
107
+ | `getMarketDepth` | `market, isBuy, levels` | Orderbook depth levels and total liquidity |
108
+ | `getBidAskSpread` | `market` | Current bid-ask spread info |
109
+ | `getVWAP` | `market, size, isBuy` | Volume-weighted average price for a given size |
110
+ | `estimateMarketImpact` | `market, size, isBuy` | Price impact estimate (avg/worst price, slippage) |
111
+ | `getMarketLiquidityAnalysis` | `market` | Comprehensive liquidity analysis struct |
112
+
113
+ ### Oracle (`client.oracle`)
114
+
115
+ | Method | Params | Description |
116
+ |--------|--------|-------------|
117
+ | `getPrice` | `asset` | Current price from on-chain reserves |
118
+ | `getLatestPriceData` | `asset` | Price + timestamp |
119
+ | `getPriceData` | `asset` | Price, timestamp, and confidence |
120
+ | `getMultiplePrices` | `assets[]` | Batch price fetch for multiple assets |
121
+ | `subscribeToPriceUpdates` | `callback, asset?` | Watch for PriceUpdated events |
122
+
123
+ ### Vault
124
+
125
+ | Method | Params | Description |
126
+ |--------|--------|-------------|
127
+ | `getVaultStats` | — | Total reserves, available reserves, exposure, unrealized PnL |
128
+ | `getVaultBalance` | — | Raw vault balance |
129
+ | `getVaultState` | — | Full vault state struct |
130
+ | `getVaultExposure` | `market` | Long/short/net exposure and utilization rate |
131
+
132
+ ### Execution
133
+
134
+ | Method | Params | Description |
135
+ |--------|--------|-------------|
136
+ | `calculateVaultSlippage` | `market, size, isBuy` | Estimated slippage from vault fill |
137
+ | `getOptimalExecutionPlan` | `market, size, isLong, maxSlippage` | Optimal split between orderbook and vault |
138
+ | `getExecutionStrategyAnalysis` | `market, size, isLong, maxSlippage` | Detailed execution strategy breakdown |
139
+
140
+ ### Keeper / Liquidation
141
+
142
+ | Method | Params | Description |
143
+ |--------|--------|-------------|
144
+ | `liquidatePosition` | `positionId` | Liquidate an under-margined position |
145
+ | `claimKeeperRewards` | — | Claim accumulated keeper rewards |
146
+ | `updateFundingRates` | `markets[]` | Trigger funding rate update for markets |
147
+
148
+ ### Events
149
+
150
+ | Method | Description |
151
+ |--------|-------------|
152
+ | `parsePositionOpenedEvent(receipt)` | Extract PositionOpened from tx receipt |
153
+ | `parsePositionClosedEvent(receipt)` | Extract PositionClosed from tx receipt |
154
+ | `parseOrderPlacedEvent(receipt)` | Extract OrderPlaced from tx receipt |
155
+ | `parseHybridOrderExecutedEvent(receipt)` | Extract HybridOrderExecuted from tx receipt |
156
+ | `watchPositionOpenedEvent(callback)` | Subscribe to PositionOpened events |
157
+ | `watchMarginDepositedEvent(callback)` | Subscribe to MarginDeposited events |
158
+ | `watchMarginWithdrawnEvent(callback)` | Subscribe to MarginWithdrawn events |
159
+ | `getPositionOpenedEvents(from?, to?, trader?)` | Query past PositionOpened events |
160
+ | `getMarginDepositedEvents(from?, to?, trader?)` | Query past MarginDeposited events |
161
+ | `getMarginWithdrawnEvents(from?, to?, trader?)` | Query past MarginWithdrawn events |
162
+
163
+ ### Helpers
164
+
165
+ | Method | Description |
166
+ |--------|-------------|
167
+ | `waitForTransaction(hash)` | Wait for tx confirmation and return receipt |
168
+ | `getContractAddress()` | Alpha contract address |
169
+ | `getConstants()` | All protocol constants (precision, max leverage, fees, etc.) |
170
+ | `readContract({functionName, args})` | Generic read for unlisted view functions |
171
+ | `estimateGas(functionName, args)` | Estimate gas for any contract call |
172
+
173
+ ## Error Handling
174
+
175
+ ```typescript
176
+ import { ContractError } from '@megatao/sdk';
177
+
178
+ try {
179
+ await alpha.openMarketPosition(market, true, margin, leverage, slippage);
180
+ } catch (err) {
181
+ if (err instanceof ContractError) {
182
+ console.error(err.contractName, err.method, err.message);
183
+ }
184
+ }
185
+ ```
186
+
187
+ ## CLI
188
+
189
+ The SDK ships a CLI binary called `alf`:
190
+
191
+ ```bash
192
+ npx alf --help
193
+ npx alf account balance
194
+ npx alf position list
195
+ ```
196
+
197
+ ## License
198
+
199
+ MIT
package/bin/alf ADDED
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+
3
+ require('tsx/cjs');
4
+ require('../cli/index.ts');
package/cli/README.md ADDED
@@ -0,0 +1,198 @@
1
+ # Alpha Futures CLI
2
+
3
+ A comprehensive command-line interface for interacting with the Alpha Futures perpetual futures protocol.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install -g @alpha-futures/sdk
9
+ ```
10
+
11
+ Or run directly with npx:
12
+ ```bash
13
+ npx @alpha-futures/sdk
14
+ ```
15
+
16
+ ## Quick Start
17
+
18
+ ### Set up your environment
19
+ ```bash
20
+ # Configure your private key (never share this!)
21
+ export PRIVATE_KEY=your_private_key_here
22
+
23
+ # Or save it in the config
24
+ alpha-futures config set privateKey YOUR_KEY
25
+ ```
26
+
27
+ ### Basic Commands
28
+
29
+ ```bash
30
+ # Check your balance
31
+ alpha-futures account balance
32
+
33
+ # Deposit TAO to your margin account
34
+ alpha-futures account deposit 100
35
+
36
+ # Open a position
37
+ alpha-futures trade market -a ALPHA -s buy -z 1000 -m 100
38
+
39
+ # List your positions
40
+ alpha-futures position list
41
+
42
+ # Close a position
43
+ alpha-futures position close 0x00000000000000000000000000000001
44
+ ```
45
+
46
+ ## Interactive Mode
47
+
48
+ Start an interactive trading session:
49
+ ```bash
50
+ alpha-futures interactive
51
+ ```
52
+
53
+ ## Commands Overview
54
+
55
+ ### Account Management
56
+ - `account balance [address]` - Check margin account balance
57
+ - `account deposit <amount>` - Deposit TAO to margin account
58
+ - `account withdraw <amount>` - Withdraw TAO from margin account
59
+ - `account history` - View transaction history
60
+
61
+ ### Position Management
62
+ - `position list` - List all positions
63
+ - `position info <positionId>` - Get detailed position information
64
+ - `position open` - Open a new position (interactive)
65
+ - `position close <positionId> [size]` - Close a position
66
+ - `position modify <positionId>` - Add or remove margin
67
+
68
+ **Note:** Position IDs must be in bytes16 format (32 hex characters after 0x).
69
+ Use `position find` to get your position IDs. Example: `0x00000000000000000000000000000001`
70
+
71
+ ### Trading
72
+ - `trade market` - Execute a market order
73
+ - `trade limit` - Place a limit order (coming soon)
74
+ - `trade quick` - Quick trade with prompts
75
+ - `trade close-all` - Close all open positions
76
+ - `trade calc` - Position sizing calculator
77
+
78
+ ### Market Data
79
+ - `market price <asset>` - Get current price
80
+ - `market funding [asset]` - View funding rates
81
+ - `market oi [asset]` - View open interest
82
+ - `market stats` - Protocol statistics
83
+ - `market list` - List all markets
84
+
85
+ ### Liquidations
86
+ - `liquidation check` - Check for liquidatable positions
87
+ - `liquidation execute <id>` - Execute a liquidation
88
+ - `liquidation monitor` - Monitor for opportunities
89
+ - `liquidation history` - View liquidation history
90
+
91
+ ### Vault Information
92
+ - `vault info` - Get vault overview
93
+ - `vault exposure [asset]` - View vault exposure
94
+ - `vault performance` - Performance metrics
95
+ - `vault health` - Health check
96
+
97
+ ### Configuration
98
+ - `config set <key> <value>` - Set configuration value
99
+ - `config get <key>` - Get configuration value
100
+ - `config list` - List all configuration
101
+ - `config reset` - Reset to defaults
102
+
103
+ ## Configuration Options
104
+
105
+ The CLI can be configured using:
106
+ 1. Command-line flags
107
+ 2. Environment variables
108
+ 3. Configuration file (`~/.alpha-futures/config.json`)
109
+
110
+ ### Available Options
111
+
112
+ | Option | Flag | Environment | Description |
113
+ |--------|------|-------------|-------------|
114
+ | Network | `-n, --network` | `ALPHA_NETWORK` | Network to connect to |
115
+ | RPC URL | `-r, --rpc` | `RPC_URL` | Custom RPC endpoint |
116
+ | Private Key | `-k, --key` | `PRIVATE_KEY` | Private key for transactions |
117
+ | Default Asset | - | - | Default trading asset |
118
+ | Default Leverage | - | - | Default leverage (1-10) |
119
+ | Confirmations | - | - | Require confirmations |
120
+
121
+ ## Examples
122
+
123
+ ### Open a 3x leveraged long position
124
+ ```bash
125
+ alpha-futures trade market -a ALPHA -s buy -z 3000 -m 1000
126
+ ```
127
+
128
+ ### Monitor liquidations with auto-execution
129
+ ```bash
130
+ alpha-futures liquidation monitor --auto --interval 10
131
+ ```
132
+
133
+ ### Watch a position in real-time
134
+ ```bash
135
+ alpha-futures position info 0x00000000000000000000000000000001 --watch
136
+ ```
137
+
138
+ ### Quick deposit and trade
139
+ ```bash
140
+ # Deposit 500 TAO
141
+ alpha-futures account deposit 500
142
+
143
+ # Open interactive trade
144
+ alpha-futures trade quick
145
+ ```
146
+
147
+ ## Safety Tips
148
+
149
+ 1. **Never share your private key**
150
+ 2. **Always verify transaction details before confirming**
151
+ 3. **Start with small positions to understand the platform**
152
+ 4. **Monitor your margin ratio to avoid liquidations**
153
+ 5. **Understand funding rates before opening positions**
154
+
155
+ ## Advanced Usage
156
+
157
+ ### Using with scripts
158
+ ```bash
159
+ # Get position data as JSON
160
+ alpha-futures position list --json | jq '.positions[] | select(.asset=="ALPHA")'
161
+
162
+ # Batch operations
163
+ alpha-futures position list --json | \
164
+ jq -r '.positions[] | select(.pnl < 0) | .id' | \
165
+ xargs -I {} alpha-futures position close {}
166
+
167
+ # Note: Position IDs in JSON output are already in correct bytes16 format
168
+ ```
169
+
170
+ ### Custom RPC endpoints
171
+ ```bash
172
+ alpha-futures --rpc https://your-rpc-endpoint.com market price ALPHA
173
+ ```
174
+
175
+ ## Troubleshooting
176
+
177
+ ### Connection Issues
178
+ - Check your internet connection
179
+ - Verify RPC endpoint is accessible
180
+ - Ensure private key is correctly formatted
181
+
182
+ ### Transaction Failures
183
+ - Check account balance for sufficient funds
184
+ - Verify gas price settings
185
+ - Review error messages for specific issues
186
+
187
+ ### Getting Help
188
+ ```bash
189
+ # Show general help
190
+ alpha-futures --help
191
+
192
+ # Show command-specific help
193
+ alpha-futures trade market --help
194
+ ```
195
+
196
+ ## License
197
+
198
+ MIT