@varla/sdk 1.11.4 → 1.13.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.
Files changed (238) hide show
  1. package/AGENTS.md +82 -95
  2. package/CHANGELOG.md +359 -0
  3. package/README.md +227 -275
  4. package/dist/abi/full/OpinionCtfExecutionEngineAdapter.js +1 -0
  5. package/dist/abi/full/OpinionCtfExecutionEngineAdapter.js.map +1 -0
  6. package/dist/abi/full/OracleUpdaterRouter.d.ts +30 -9
  7. package/dist/abi/full/OracleUpdaterRouter.d.ts.map +1 -1
  8. package/dist/abi/full/OracleUpdaterRouter.js +37 -9
  9. package/dist/abi/full/OracleUpdaterRouter.js.map +1 -0
  10. package/dist/abi/full/PolymarketCtfAdapter.js +1 -0
  11. package/dist/abi/full/PolymarketCtfAdapter.js.map +1 -0
  12. package/dist/abi/full/VarlaAccessManager.js +1 -0
  13. package/dist/abi/full/VarlaAccessManager.js.map +1 -0
  14. package/dist/abi/full/VarlaConvertLiquidator.js +1 -0
  15. package/dist/abi/full/VarlaConvertLiquidator.js.map +1 -0
  16. package/dist/abi/full/VarlaCore.js +1 -0
  17. package/dist/abi/full/VarlaCore.js.map +1 -0
  18. package/dist/abi/full/VarlaInterestRateStrategy.js +1 -0
  19. package/dist/abi/full/VarlaInterestRateStrategy.js.map +1 -0
  20. package/dist/abi/full/VarlaLiquidator.d.ts +1 -1
  21. package/dist/abi/full/VarlaLiquidator.js +2 -1
  22. package/dist/abi/full/VarlaLiquidator.js.map +1 -0
  23. package/dist/abi/full/VarlaMergeLiquidator.js +1 -0
  24. package/dist/abi/full/VarlaMergeLiquidator.js.map +1 -0
  25. package/dist/abi/full/VarlaOracle.js +1 -0
  26. package/dist/abi/full/VarlaOracle.js.map +1 -0
  27. package/dist/abi/full/VarlaPool.js +1 -0
  28. package/dist/abi/full/VarlaPool.js.map +1 -0
  29. package/dist/abi/full/VarlaProxyAdmin.js +1 -0
  30. package/dist/abi/full/VarlaProxyAdmin.js.map +1 -0
  31. package/dist/abi/index.js +1 -0
  32. package/dist/abi/index.js.map +1 -0
  33. package/dist/abi/subsets/VarlaOracle.registry.js +1 -0
  34. package/dist/abi/subsets/VarlaOracle.registry.js.map +1 -0
  35. package/dist/abi.js +1 -0
  36. package/dist/abi.js.map +1 -0
  37. package/dist/actions/admin.js +1 -0
  38. package/dist/actions/admin.js.map +1 -0
  39. package/dist/actions/core.js +1 -0
  40. package/dist/actions/core.js.map +1 -0
  41. package/dist/actions/erc1155.js +1 -0
  42. package/dist/actions/erc1155.js.map +1 -0
  43. package/dist/actions/erc20.js +1 -0
  44. package/dist/actions/erc20.js.map +1 -0
  45. package/dist/actions/index.d.ts +7 -7
  46. package/dist/actions/index.d.ts.map +1 -1
  47. package/dist/actions/index.js +8 -7
  48. package/dist/actions/index.js.map +1 -0
  49. package/dist/actions/liquidator.js +1 -0
  50. package/dist/actions/liquidator.js.map +1 -0
  51. package/dist/actions/oracle.d.ts +1 -2
  52. package/dist/actions/oracle.d.ts.map +1 -1
  53. package/dist/actions/oracle.js +1 -0
  54. package/dist/actions/oracle.js.map +1 -0
  55. package/dist/actions/oracleUpdaterRouter.d.ts +8 -1
  56. package/dist/actions/oracleUpdaterRouter.d.ts.map +1 -1
  57. package/dist/actions/oracleUpdaterRouter.js +14 -1
  58. package/dist/actions/oracleUpdaterRouter.js.map +1 -0
  59. package/dist/actions/pool.js +1 -0
  60. package/dist/actions/pool.js.map +1 -0
  61. package/dist/actions/rbac.js +1 -0
  62. package/dist/actions/rbac.js.map +1 -0
  63. package/dist/actions/tx.js +1 -0
  64. package/dist/actions/tx.js.map +1 -0
  65. package/dist/actions/utils.js +1 -0
  66. package/dist/actions/utils.js.map +1 -0
  67. package/dist/addresses/bsc.js +1 -0
  68. package/dist/addresses/bsc.js.map +1 -0
  69. package/dist/addresses/index.js +1 -0
  70. package/dist/addresses/index.js.map +1 -0
  71. package/dist/addresses/polygon.js +1 -0
  72. package/dist/addresses/polygon.js.map +1 -0
  73. package/dist/addresses.js +1 -0
  74. package/dist/addresses.js.map +1 -0
  75. package/dist/batch.js +1 -0
  76. package/dist/batch.js.map +1 -0
  77. package/dist/contracts.d.ts +1 -2
  78. package/dist/contracts.d.ts.map +1 -1
  79. package/dist/contracts.js +2 -2
  80. package/dist/contracts.js.map +1 -0
  81. package/dist/errors.d.ts +87 -0
  82. package/dist/errors.d.ts.map +1 -0
  83. package/dist/errors.js +240 -0
  84. package/dist/errors.js.map +1 -0
  85. package/dist/events/decode.js +1 -0
  86. package/dist/events/decode.js.map +1 -0
  87. package/dist/events/defs.js +1 -0
  88. package/dist/events/defs.js.map +1 -0
  89. package/dist/events/index.d.ts +3 -3
  90. package/dist/events/index.d.ts.map +1 -1
  91. package/dist/events/index.js +4 -3
  92. package/dist/events/index.js.map +1 -0
  93. package/dist/events/logs.js +1 -0
  94. package/dist/events/logs.js.map +1 -0
  95. package/dist/events/oracleRegistrySync.js +1 -0
  96. package/dist/events/oracleRegistrySync.js.map +1 -0
  97. package/dist/events/recent.d.ts +1 -1
  98. package/dist/events/recent.d.ts.map +1 -1
  99. package/dist/events/recent.js +2 -1
  100. package/dist/events/recent.js.map +1 -0
  101. package/dist/format.js +1 -0
  102. package/dist/format.js.map +1 -0
  103. package/dist/generated.d.ts +31 -10
  104. package/dist/generated.d.ts.map +1 -1
  105. package/dist/generated.js +1 -0
  106. package/dist/generated.js.map +1 -0
  107. package/dist/index.d.ts +6 -5
  108. package/dist/index.d.ts.map +1 -1
  109. package/dist/index.js +12 -9
  110. package/dist/index.js.map +1 -0
  111. package/dist/leverage/deleverageExecute.d.ts +36 -0
  112. package/dist/leverage/deleverageExecute.d.ts.map +1 -0
  113. package/dist/leverage/deleverageExecute.js +53 -0
  114. package/dist/leverage/deleverageExecute.js.map +1 -0
  115. package/dist/leverage/execute.d.ts +62 -0
  116. package/dist/leverage/execute.d.ts.map +1 -0
  117. package/dist/leverage/execute.js +84 -0
  118. package/dist/leverage/execute.js.map +1 -0
  119. package/dist/leverage/index.d.ts +32 -0
  120. package/dist/leverage/index.d.ts.map +1 -0
  121. package/dist/leverage/index.js +12 -0
  122. package/dist/leverage/index.js.map +1 -0
  123. package/dist/leverage/math.d.ts +119 -0
  124. package/dist/leverage/math.d.ts.map +1 -0
  125. package/dist/leverage/math.js +304 -0
  126. package/dist/leverage/math.js.map +1 -0
  127. package/dist/leverage/plan.d.ts +143 -0
  128. package/dist/leverage/plan.d.ts.map +1 -0
  129. package/dist/leverage/plan.js +204 -0
  130. package/dist/leverage/plan.js.map +1 -0
  131. package/dist/leverage/preflight.d.ts +27 -0
  132. package/dist/leverage/preflight.d.ts.map +1 -0
  133. package/dist/leverage/preflight.js +34 -0
  134. package/dist/leverage/preflight.js.map +1 -0
  135. package/dist/leverage/types.d.ts +157 -0
  136. package/dist/leverage/types.d.ts.map +1 -0
  137. package/dist/leverage/types.js +43 -0
  138. package/dist/leverage/types.js.map +1 -0
  139. package/dist/meta.d.ts +42 -0
  140. package/dist/meta.d.ts.map +1 -0
  141. package/dist/meta.js +47 -0
  142. package/dist/meta.js.map +1 -0
  143. package/dist/types.js +1 -0
  144. package/dist/types.js.map +1 -0
  145. package/dist/views/accessManager.js +1 -0
  146. package/dist/views/accessManager.js.map +1 -0
  147. package/dist/views/adapters.js +1 -0
  148. package/dist/views/adapters.js.map +1 -0
  149. package/dist/views/admin.d.ts.map +1 -1
  150. package/dist/views/admin.js +1 -0
  151. package/dist/views/admin.js.map +1 -0
  152. package/dist/views/core.d.ts.map +1 -1
  153. package/dist/views/core.js +1 -0
  154. package/dist/views/core.js.map +1 -0
  155. package/dist/views/index.d.ts +5 -5
  156. package/dist/views/index.d.ts.map +1 -1
  157. package/dist/views/index.js +6 -5
  158. package/dist/views/index.js.map +1 -0
  159. package/dist/views/lenders.js +1 -0
  160. package/dist/views/lenders.js.map +1 -0
  161. package/dist/views/liquidators.js +1 -0
  162. package/dist/views/liquidators.js.map +1 -0
  163. package/dist/views/oracle.js +1 -0
  164. package/dist/views/oracle.js.map +1 -0
  165. package/dist/views/pool.js +1 -0
  166. package/dist/views/pool.js.map +1 -0
  167. package/dist/views/system.d.ts.map +1 -1
  168. package/dist/views/system.js +1 -0
  169. package/dist/views/system.js.map +1 -0
  170. package/package.json +18 -5
  171. package/src/abi/README.md +17 -0
  172. package/src/abi/full/OpinionCtfExecutionEngineAdapter.ts +320 -0
  173. package/src/abi/full/OracleUpdaterRouter.ts +528 -0
  174. package/src/abi/full/PolymarketCtfAdapter.ts +312 -0
  175. package/src/abi/full/VarlaAccessManager.ts +1171 -0
  176. package/src/abi/full/VarlaConvertLiquidator.ts +834 -0
  177. package/src/abi/full/VarlaCore.ts +2277 -0
  178. package/src/abi/full/VarlaInterestRateStrategy.ts +442 -0
  179. package/src/abi/full/VarlaLiquidator.ts +914 -0
  180. package/src/abi/full/VarlaMergeLiquidator.ts +797 -0
  181. package/src/abi/full/VarlaOracle.ts +1825 -0
  182. package/src/abi/full/VarlaPool.ts +1637 -0
  183. package/src/abi/full/VarlaProxyAdmin.ts +301 -0
  184. package/src/abi/index.ts +17 -0
  185. package/src/abi/subsets/VarlaOracle.registry.ts +784 -0
  186. package/src/abi.ts +2 -0
  187. package/src/actions/admin.ts +357 -0
  188. package/src/actions/core.ts +68 -0
  189. package/src/actions/erc1155.ts +22 -0
  190. package/src/actions/erc20.ts +22 -0
  191. package/src/actions/index.ts +13 -0
  192. package/src/actions/liquidator.ts +76 -0
  193. package/src/actions/oracle.ts +618 -0
  194. package/src/actions/oracleUpdaterRouter.ts +233 -0
  195. package/src/actions/pool.ts +76 -0
  196. package/src/actions/rbac.ts +72 -0
  197. package/src/actions/tx.ts +16 -0
  198. package/src/actions/utils.ts +15 -0
  199. package/src/addresses/README.md +17 -0
  200. package/src/addresses/bsc.json +16 -0
  201. package/src/addresses/bsc.ts +15 -0
  202. package/src/addresses/index.ts +6 -0
  203. package/src/addresses/polygon.json +16 -0
  204. package/src/addresses/polygon.ts +15 -0
  205. package/src/addresses.ts +2 -0
  206. package/src/batch.ts +55 -0
  207. package/src/contracts.ts +232 -0
  208. package/src/errors.ts +305 -0
  209. package/src/events/decode.ts +37 -0
  210. package/src/events/defs.ts +70 -0
  211. package/src/events/index.ts +7 -0
  212. package/src/events/logs.ts +42 -0
  213. package/src/events/oracleRegistrySync.ts +206 -0
  214. package/src/events/recent.ts +39 -0
  215. package/src/format.ts +121 -0
  216. package/src/generated.ts +27 -0
  217. package/src/index.ts +18 -0
  218. package/src/leverage/deleverageExecute.ts +111 -0
  219. package/src/leverage/execute.ts +172 -0
  220. package/src/leverage/index.ts +88 -0
  221. package/src/leverage/math.ts +446 -0
  222. package/src/leverage/plan.ts +356 -0
  223. package/src/leverage/preflight.ts +63 -0
  224. package/src/leverage/types.ts +204 -0
  225. package/src/meta.ts +82 -0
  226. package/src/types.ts +25 -0
  227. package/src/views/accessManager.ts +286 -0
  228. package/src/views/adapters.ts +27 -0
  229. package/src/views/admin.ts +92 -0
  230. package/src/views/core.ts +1370 -0
  231. package/src/views/index.ts +11 -0
  232. package/src/views/lenders.ts +65 -0
  233. package/src/views/liquidators.ts +227 -0
  234. package/src/views/oracle.ts +739 -0
  235. package/src/views/pool.ts +277 -0
  236. package/src/views/system.ts +42 -0
  237. package/BACKEND.md +0 -405
  238. package/FRONTEND.md +0 -485
@@ -0,0 +1,277 @@
1
+ // Note: explicit .js extension is required for Node ESM resolution.
2
+
3
+ import type { Address } from "viem";
4
+
5
+ export type ReadPoolSnapshot = {
6
+ totalAssets: bigint;
7
+ totalBorrowed: bigint;
8
+ available: bigint;
9
+ utilization: bigint;
10
+ borrowRate: bigint;
11
+ supplyAPY: bigint;
12
+ borrowIndex: bigint;
13
+ };
14
+
15
+ export type ReadPoolDebtState = {
16
+ totalBorrowed: bigint;
17
+ currentBorrowIndex: bigint;
18
+ borrowRate: bigint;
19
+ };
20
+
21
+ // wraps: VarlaPool.getPoolStats
22
+ export async function readPoolSnapshot(params: {
23
+ pool: {
24
+ read: {
25
+ getPoolStats: () => Promise<unknown>;
26
+ };
27
+ };
28
+ }): Promise<ReadPoolSnapshot> {
29
+ const raw = await params.pool.read.getPoolStats();
30
+ const r: any = raw as any;
31
+
32
+ // Tuple order in VarlaPool.getPoolStats:
33
+ // (_totalAssets,_totalBorrowed,_available,_utilization,_borrowRate,_supplyAPY,_borrowIndex)
34
+ const totalAssets = r._totalAssets ?? r[0];
35
+ const totalBorrowed = r._totalBorrowed ?? r[1];
36
+ const available = r._available ?? r[2];
37
+ const utilization = r._utilization ?? r[3];
38
+ const borrowRate = r._borrowRate ?? r[4];
39
+ const supplyAPY = r._supplyAPY ?? r[5];
40
+ const borrowIndex = r._borrowIndex ?? r[6];
41
+
42
+ if (
43
+ typeof totalAssets !== "bigint" ||
44
+ typeof totalBorrowed !== "bigint" ||
45
+ typeof available !== "bigint" ||
46
+ typeof utilization !== "bigint" ||
47
+ typeof borrowRate !== "bigint" ||
48
+ typeof supplyAPY !== "bigint" ||
49
+ typeof borrowIndex !== "bigint"
50
+ ) {
51
+ throw new Error("Unexpected getPoolStats() return shape");
52
+ }
53
+
54
+ return {
55
+ totalAssets,
56
+ totalBorrowed,
57
+ available,
58
+ utilization,
59
+ borrowRate,
60
+ supplyAPY,
61
+ borrowIndex,
62
+ };
63
+ }
64
+
65
+ export type ReadPoolCaps = {
66
+ depositCap: bigint;
67
+ borrowCap: bigint;
68
+ };
69
+
70
+ /**
71
+ * Reads depositCap/borrowCap (useful for frontends + monitoring).
72
+ */
73
+ // wraps: VarlaPool.depositCap,VarlaPool.borrowCap
74
+ export async function readPoolCaps(params: {
75
+ pool: {
76
+ read: {
77
+ depositCap: () => Promise<bigint>;
78
+ borrowCap: () => Promise<bigint>;
79
+ };
80
+ };
81
+ }): Promise<ReadPoolCaps> {
82
+ const [depositCap, borrowCap] = await Promise.all([
83
+ params.pool.read.depositCap(),
84
+ params.pool.read.borrowCap(),
85
+ ]);
86
+ return { depositCap, borrowCap };
87
+ }
88
+
89
+ export type ReadPoolAccounting = {
90
+ reserveBalance: bigint;
91
+ scaledTotalBorrowed: bigint;
92
+ borrowIndex: bigint;
93
+ lastUpdateTimestamp: bigint;
94
+ };
95
+
96
+ /**
97
+ * Reads accounting/index variables that are commonly required in analytics.
98
+ */
99
+ // wraps: VarlaPool.reserveBalance,VarlaPool.scaledTotalBorrowed,VarlaPool.borrowIndex,VarlaPool.lastUpdateTimestamp
100
+ export async function readPoolAccounting(params: {
101
+ pool: {
102
+ read: {
103
+ reserveBalance: () => Promise<bigint>;
104
+ scaledTotalBorrowed: () => Promise<bigint>;
105
+ borrowIndex: () => Promise<bigint>;
106
+ lastUpdateTimestamp: () => Promise<bigint | number>;
107
+ };
108
+ };
109
+ }): Promise<ReadPoolAccounting> {
110
+ const [reserveBalance, scaledTotalBorrowed, borrowIndex, lastUpdateTimestamp] = await Promise.all(
111
+ [
112
+ params.pool.read.reserveBalance(),
113
+ params.pool.read.scaledTotalBorrowed(),
114
+ params.pool.read.borrowIndex(),
115
+ params.pool.read.lastUpdateTimestamp(),
116
+ ],
117
+ );
118
+
119
+ return {
120
+ reserveBalance,
121
+ scaledTotalBorrowed,
122
+ borrowIndex,
123
+ lastUpdateTimestamp: BigInt(lastUpdateTimestamp),
124
+ };
125
+ }
126
+
127
+ export type ReadPoolRates = {
128
+ utilization: bigint;
129
+ borrowRate: bigint;
130
+ supplyAPY: bigint;
131
+ availableLiquidity: bigint;
132
+ maxBorrow: bigint;
133
+ };
134
+
135
+ export type ReadPoolSharePrice = {
136
+ /** Total pool assets attributable to LPs (excludes reserve). */
137
+ totalAssets: bigint;
138
+ /** Total ERC4626 shares (vault token supply). */
139
+ totalShares: bigint;
140
+ /** WAD (1e18): totalAssets / totalShares. 0 when totalShares == 0. */
141
+ assetsPerShareWad: bigint;
142
+ };
143
+
144
+ export type ReadPoolHealthScore =
145
+ | {
146
+ kind: "ok";
147
+ /** Utilization in WAD (1e18 = 100%). */
148
+ utilizationWad: bigint;
149
+ /** Score in BPS (0..10_000). Higher is "safer" in this simplified metric. */
150
+ scoreBps: bigint;
151
+ }
152
+ | {
153
+ /** Pool has no LP assets. Utilization reads as 0, but a safety score would be misleading. */
154
+ kind: "no-liquidity";
155
+ };
156
+
157
+ /**
158
+ * Reads pool “rates” and near-term capacity in one convenience call.
159
+ */
160
+ // wraps: VarlaPool.getUtilization,VarlaPool.getInterestRate,VarlaPool.getSupplyAPY,VarlaPool.getAvailableLiquidity,VarlaPool.maxBorrow
161
+ export async function readPoolRates(params: {
162
+ pool: {
163
+ read: {
164
+ getUtilization: () => Promise<bigint>;
165
+ getInterestRate: () => Promise<bigint>;
166
+ getSupplyAPY: () => Promise<bigint>;
167
+ getAvailableLiquidity: () => Promise<bigint>;
168
+ maxBorrow: () => Promise<bigint>;
169
+ };
170
+ };
171
+ }): Promise<ReadPoolRates> {
172
+ const [utilization, borrowRate, supplyAPY, availableLiquidity, maxBorrow] = await Promise.all([
173
+ params.pool.read.getUtilization(),
174
+ params.pool.read.getInterestRate(),
175
+ params.pool.read.getSupplyAPY(),
176
+ params.pool.read.getAvailableLiquidity(),
177
+ params.pool.read.maxBorrow(),
178
+ ]);
179
+
180
+ return { utilization, borrowRate, supplyAPY, availableLiquidity, maxBorrow };
181
+ }
182
+
183
+ /**
184
+ * Reads the current pool "share price" (assets per share).
185
+ *
186
+ * Useful for:
187
+ * - lending UI (convert shares to assets)
188
+ * - charting / APR displays
189
+ *
190
+ * Notes:
191
+ * - This is a pure on-chain primitive. It does NOT attempt to compute user PnL.
192
+ * - Uses `totalAssets()` which already excludes protocol reserve.
193
+ */
194
+ // wraps: VarlaPool.totalAssets,VarlaPool.totalSupply
195
+ export async function readPoolSharePrice(params: {
196
+ pool: {
197
+ read: {
198
+ totalAssets: () => Promise<bigint>;
199
+ totalSupply: () => Promise<bigint>;
200
+ };
201
+ };
202
+ }): Promise<ReadPoolSharePrice> {
203
+ const [totalAssets, totalShares] = await Promise.all([
204
+ params.pool.read.totalAssets(),
205
+ params.pool.read.totalSupply(),
206
+ ]);
207
+
208
+ const assetsPerShareWad =
209
+ totalShares === 0n ? 0n : (totalAssets * 1_000_000_000_000_000_000n) / totalShares;
210
+
211
+ return { totalAssets, totalShares, assetsPerShareWad };
212
+ }
213
+
214
+ /**
215
+ * A simplified pool "safety" / "health" score for UIs.
216
+ *
217
+ * Current implementation:
218
+ * - when pool has 0 totalAssets => return { kind: "no-liquidity" }
219
+ * - otherwise score = (1 - utilization) in BPS
220
+ *
221
+ * This intentionally avoids reporting 100% for empty pools (which is misleading).
222
+ */
223
+ // wraps: VarlaPool.totalAssets,VarlaPool.getUtilization
224
+ export async function readPoolHealthScore(params: {
225
+ pool: {
226
+ read: {
227
+ totalAssets: () => Promise<bigint>;
228
+ getUtilization: () => Promise<bigint>;
229
+ };
230
+ };
231
+ }): Promise<ReadPoolHealthScore> {
232
+ const [totalAssets, utilizationWad] = await Promise.all([
233
+ params.pool.read.totalAssets(),
234
+ params.pool.read.getUtilization(),
235
+ ]);
236
+
237
+ if (totalAssets === 0n) return { kind: "no-liquidity" };
238
+
239
+ // Clamp utilizationWad into [0, 1e18] to keep score bounded.
240
+ const one = 1_000_000_000_000_000_000n;
241
+ const u = utilizationWad < 0n ? 0n : utilizationWad > one ? one : utilizationWad;
242
+ const scoreBps = ((one - u) * 10_000n) / one;
243
+
244
+ return { kind: "ok", utilizationWad: u, scoreBps };
245
+ }
246
+
247
+ /**
248
+ * Pool debt/index primitives commonly used by UIs.
249
+ */
250
+ // wraps: VarlaPool.getTotalBorrowed,VarlaPool.getCurrentBorrowIndex,VarlaPool.borrowRate
251
+ export async function readPoolDebtState(params: {
252
+ pool: {
253
+ read: {
254
+ getTotalBorrowed: () => Promise<bigint>;
255
+ getCurrentBorrowIndex: () => Promise<bigint>;
256
+ borrowRate: () => Promise<bigint>;
257
+ };
258
+ };
259
+ }): Promise<ReadPoolDebtState> {
260
+ const [totalBorrowed, currentBorrowIndex, borrowRate] = await Promise.all([
261
+ params.pool.read.getTotalBorrowed(),
262
+ params.pool.read.getCurrentBorrowIndex(),
263
+ params.pool.read.borrowRate(),
264
+ ]);
265
+ return { totalBorrowed, currentBorrowIndex, borrowRate };
266
+ }
267
+
268
+ // wraps: VarlaPool.varlaCore
269
+ export async function readPoolCoreAddress(params: {
270
+ pool: {
271
+ read: {
272
+ varlaCore: () => Promise<Address>;
273
+ };
274
+ };
275
+ }): Promise<Address> {
276
+ return params.pool.read.varlaCore();
277
+ }
@@ -0,0 +1,42 @@
1
+ // Note: explicit .js extension is required for Node ESM resolution.
2
+
3
+ import type { ReadDefaultLtvConfig, ReadLiquidationConfig } from "./core.js";
4
+ import { readDefaultLtvConfig, readLiquidationConfig } from "./core.js";
5
+ import type { ReadOracleConfig } from "./oracle.js";
6
+ import { readOracleConfig } from "./oracle.js";
7
+ import type { ReadPoolAccounting, ReadPoolCaps, ReadPoolSnapshot } from "./pool.js";
8
+ import { readPoolAccounting, readPoolCaps, readPoolSnapshot } from "./pool.js";
9
+
10
+ export type ReadSystemSnapshot = {
11
+ pool: ReadPoolSnapshot;
12
+ poolCaps: ReadPoolCaps;
13
+ poolAccounting: ReadPoolAccounting;
14
+ coreLtv: ReadDefaultLtvConfig;
15
+ coreLiquidation: ReadLiquidationConfig;
16
+ oracle: ReadOracleConfig;
17
+ };
18
+
19
+ /**
20
+ * A lightweight “global protocol state” read for dashboards.
21
+ *
22
+ * - no scanning
23
+ * - no registry enumeration
24
+ * - just the config + accounting primitives needed by frontends and monitoring
25
+ */
26
+ // wraps: VarlaPool.getPoolStats,VarlaPool.depositCap,VarlaPool.borrowCap,VarlaPool.reserveBalance,VarlaPool.scaledTotalBorrowed,VarlaPool.borrowIndex,VarlaPool.lastUpdateTimestamp,VarlaCore.getDefaultLtvConfig,VarlaCore.getLiquidationConfig,VarlaOracle.maxStaleness,VarlaOracle.liquidationGracePeriod,VarlaOracle.defaultEarlyClosureWindow
27
+ export async function readSystemSnapshot(params: {
28
+ pool: any;
29
+ core: any;
30
+ oracle: any;
31
+ }): Promise<ReadSystemSnapshot> {
32
+ const [pool, poolCaps, poolAccounting, coreLtv, coreLiquidation, oracle] = await Promise.all([
33
+ readPoolSnapshot({ pool: params.pool }),
34
+ readPoolCaps({ pool: params.pool }),
35
+ readPoolAccounting({ pool: params.pool }),
36
+ readDefaultLtvConfig({ core: params.core }),
37
+ readLiquidationConfig({ core: params.core }),
38
+ readOracleConfig({ oracle: params.oracle }),
39
+ ]);
40
+
41
+ return { pool, poolCaps, poolAccounting, coreLtv, coreLiquidation, oracle };
42
+ }
package/BACKEND.md DELETED
@@ -1,405 +0,0 @@
1
- # Backend integration guide (Node.js services: indexer + oracle updater + ops)
2
-
3
- This SDK is intentionally **batteries-not-included** for:
4
-
5
- - RPC configuration (URLs, retries, fallbacks, rate limits)
6
- - job scheduling / queues
7
- - persistence (db schemas, migrations)
8
- - reorg handling strategy (confirmations, replay windows)
9
-
10
- The SDK *does* provide:
11
-
12
- - canonical ABIs + deployed addresses
13
- - typed viem contract bindings (`getVarlaContracts` / `getRequiredVarlaContracts`)
14
- - read facades (`@varla/sdk/views`) built around multicall + paging
15
- - simulate-first write helpers (`@varla/sdk/actions`) for safer writes
16
- - event/indexer helpers (`@varla/sdk/events`) for log syncing
17
-
18
- This doc shows a recommended setup for **Node.js backend services**, split into common roles:
19
-
20
- - **Indexer / monitor** (reads + events)
21
- - **Oracle updater** (offchain prices → onchain updates)
22
- - **Ops / admin runner** (RBAC + seeding + parameter changes)
23
-
24
- ---
25
-
26
- ## 1) RPC + viem client setup (service-side)
27
-
28
- The SDK does not ship RPC URLs.
29
-
30
- Recommended:
31
- - configure explicit RPCs per chain (Polygon/BSC)
32
- - use `fallback([http(primary), http(secondary)])`
33
- - add retries/backoff at the transport layer (your code) or via a proxy provider
34
-
35
- Example `rpc.ts`:
36
-
37
- ```ts
38
- import { createPublicClient, fallback, http } from "viem";
39
- import { polygon, bsc } from "viem/chains";
40
-
41
- const POLYGON_RPC_URL = process.env.POLYGON_RPC_URL;
42
- const POLYGON_RPC_URL_BACKUP = process.env.POLYGON_RPC_URL_BACKUP;
43
- const BSC_RPC_URL = process.env.BSC_RPC_URL;
44
- const BSC_RPC_URL_BACKUP = process.env.BSC_RPC_URL_BACKUP;
45
-
46
- if (!POLYGON_RPC_URL) throw new Error("Missing POLYGON_RPC_URL");
47
- if (!BSC_RPC_URL) throw new Error("Missing BSC_RPC_URL");
48
-
49
- export const polygonClient = createPublicClient({
50
- chain: polygon,
51
- transport: fallback([
52
- http(POLYGON_RPC_URL),
53
- ...(POLYGON_RPC_URL_BACKUP ? [http(POLYGON_RPC_URL_BACKUP)] : []),
54
- ]),
55
- });
56
-
57
- export const bscClient = createPublicClient({
58
- chain: bsc,
59
- transport: fallback([
60
- http(BSC_RPC_URL),
61
- ...(BSC_RPC_URL_BACKUP ? [http(BSC_RPC_URL_BACKUP)] : []),
62
- ]),
63
- });
64
- ```
65
-
66
- Notes:
67
- - You should own your own retry policy (especially for high-volume reads).
68
- - For “safe finality” reads, prefer waiting N blocks and/or reading with a stable provider.
69
-
70
- ---
71
-
72
- ## 2) Getting Varla bindings (typed viem)
73
-
74
- ```ts
75
- import { getVarlaContracts } from "@varla/sdk";
76
- import { polygonClient } from "./rpc";
77
-
78
- const c = getVarlaContracts({ chain: "polygon", client: polygonClient });
79
-
80
- // Typed reads
81
- const stats = await c.pool.read.getPoolStats();
82
- ```
83
-
84
- If your service *requires* certain optional deployments (e.g. adapters, liquidators), use:
85
-
86
- ```ts
87
- import { getRequiredVarlaContracts } from "@varla/sdk";
88
-
89
- const c = getRequiredVarlaContracts({
90
- chain: "polygon",
91
- client: polygonClient,
92
- require: ["liquidator"],
93
- });
94
- ```
95
-
96
- ---
97
-
98
- ## 3) High-volume reads: views + batching + paging
99
-
100
- For most backend tasks, prefer SDK view helpers:
101
-
102
- ```ts
103
- import * as views from "@varla/sdk/views";
104
-
105
- const snap = await views.readSystemSnapshot({ pool: c.pool, core: c.core, oracle: c.oracle });
106
- ```
107
-
108
- ### Oracle registry (configured positionIds)
109
-
110
- The oracle can have many configured positionIds. Use paging helpers:
111
-
112
- ```ts
113
- const page = await views.readOracleRegistryPage({
114
- oracle: c.oracle,
115
- client: polygonClient,
116
- start: 0,
117
- limit: 500,
118
- });
119
-
120
- console.log(page.positionIds);
121
- ```
122
-
123
- ### Borrowers list
124
-
125
- Borrowers are tracked on-chain as a set. Use paging:
126
-
127
- ```ts
128
- const borrowers = await views.readBorrowersPage({
129
- core: c.core,
130
- client: polygonClient,
131
- start: 0,
132
- limit: 200,
133
- });
134
- ```
135
-
136
- ---
137
-
138
- ## 4) Event-driven indexing
139
-
140
- For indexers, event-driven discovery is often cheaper than full scans.
141
-
142
- The SDK provides helpers under `@varla/sdk/events` for chunked log fetching and registry sync.
143
-
144
- Typical pattern:
145
-
146
- 1) pick a block range window (e.g. 50k blocks)
147
- 2) fetch logs in chunks
148
- 3) persist a cursor (last processed block)
149
- 4) on restart, resume from the cursor
150
-
151
- If you only need the oracle registry (configured positions), use the SDK’s event sync helper
152
- and then hydrate state via multicall:
153
-
154
- ```ts
155
- import * as events from "@varla/sdk/events";
156
- import * as views from "@varla/sdk/views";
157
-
158
- // 1) discover positionIds from events
159
- const positionIds = await events.syncOracleRegistryViaEvents({
160
- oracleAddress: c.oracle.address,
161
- client: polygonClient,
162
- fromBlock: 0n,
163
- toBlock: "latest",
164
- });
165
-
166
- // 2) hydrate snapshots in multicall batches
167
- const snaps = await views.readManyPositionSnapshots({
168
- oracle: { address: c.oracle.address },
169
- client: polygonClient,
170
- positionIds,
171
- });
172
- ```
173
-
174
- Reorg handling:
175
- - Maintain a **reorg buffer** (e.g. always reprocess last 50–200 blocks).
176
- - Store both `blockNumber` and `blockHash` if you need strong guarantees.
177
-
178
- ---
179
-
180
- ## 5) Writes from a backend: wallet client + simulate-first
181
-
182
- Backend writes should be explicit and auditable:
183
-
184
- - hold operator keys securely (HSM/KMS if possible)
185
- - simulate first to catch reverts
186
- - send
187
- - wait for receipts with confirmations
188
-
189
- Example `wallet.ts`:
190
-
191
- ```ts
192
- import { createWalletClient, http } from "viem";
193
- import { privateKeyToAccount } from "viem/accounts";
194
- import { polygon } from "viem/chains";
195
-
196
- const pk = process.env.OPERATOR_PRIVATE_KEY;
197
- if (!pk) throw new Error("Missing OPERATOR_PRIVATE_KEY");
198
-
199
- export const operatorAccount = privateKeyToAccount(pk as `0x${string}`);
200
-
201
- export const polygonWallet = createWalletClient({
202
- chain: polygon,
203
- transport: http(process.env.POLYGON_RPC_URL!),
204
- account: operatorAccount,
205
- });
206
- ```
207
-
208
- Then use SDK actions:
209
-
210
- ```ts
211
- import * as actions from "@varla/sdk/actions";
212
-
213
- const sim = await actions.prepareCoreBorrow({
214
- publicClient: polygonClient,
215
- coreAddress: c.core.address,
216
- account: operatorAccount.address,
217
- amount: 1_000_000n,
218
- });
219
-
220
- const hash = await actions.sendTx({ walletClient: polygonWallet, request: sim.request });
221
- await polygonClient.waitForTransactionReceipt({ hash, confirmations: 2 });
222
- ```
223
-
224
- ---
225
-
226
- ## 6) RBAC preflight (AccessManager)
227
-
228
- The protocol uses OZ `AccessManager`.
229
-
230
- For admin services, do a preflight check before attempting writes:
231
-
232
- ```ts
233
- import * as actions from "@varla/sdk/actions";
234
-
235
- // Example: ensure caller can call `configurePositionsBatch(...)` immediately.
236
- const selector = actions.selectorFromSignature(actions.ORACLE_SIGS.configurePositionsBatch);
237
-
238
- await actions.assertCanCallImmediate({
239
- accessManager: c.accessManager,
240
- caller: operatorAccount.address,
241
- target: c.oracle.address,
242
- selector,
243
- });
244
- ```
245
-
246
- Tip: if you expect scheduled execution (delays), use the “delayed” flows and build a queue.
247
-
248
- ---
249
-
250
- ## 7) Oracle seeding (plan → prepare → execute)
251
-
252
- The SDK provides **idempotent** seeding planners. Your backend can generate JSON lists
253
- and then run the seeder.
254
-
255
- Important: some operations must be done in 2 phases.
256
-
257
- - `configureOppositePositions(yesPid, noPid)` will revert unless both PIDs are already configured.
258
-
259
- Therefore:
260
- 1) seed markets/configure positions
261
- 2) seed opposites + negRisk
262
-
263
- Node convenience helper:
264
-
265
- ```ts
266
- import * as actions from "@varla/sdk/actions";
267
-
268
- const seeded = await actions.seedOracleFromJsonFiles({
269
- oracle: c.oracle,
270
- marketsPath: "./markets.polygon.json",
271
- oppositesPath: "./opposites.polygon.json",
272
- negRiskPath: "./negrisk.polygon.json",
273
- prepare: {
274
- publicClient: polygonClient,
275
- oracleAddress: c.oracle.address,
276
- account: operatorAccount.address,
277
- },
278
- });
279
-
280
- console.log(seeded.plan);
281
-
282
- if ("prepared" in seeded) {
283
- const hashes = await actions.executeOracleSeedPlan({
284
- walletClient: polygonWallet,
285
- prepared: seeded.prepared,
286
- });
287
- console.log(hashes);
288
- }
289
- ```
290
-
291
- ---
292
-
293
- ## 8) Monitoring / alerting hooks
294
-
295
- Useful health signals to emit from a backend:
296
-
297
- - `views.readSystemSnapshot` periodically
298
- - staleness checks on configured oracle positions
299
- - borrower health factor checks (paging) and alert on `HF < 1.0`
300
- - pool utilization + borrow rates
301
-
302
- ---
303
-
304
- ## 9) Gotchas
305
-
306
- - **Viem args are arrays**: `contract.read.fn([arg1, arg2])`.
307
- - Always wait for receipts with confirmations on critical admin writes.
308
- - Treat RPC errors as expected: implement retry/backoff and fallbacks.
309
- - Keep multicalls bounded (chunking) to avoid RPC provider limits.
310
-
311
- ---
312
-
313
- ## All view helpers (generated)
314
-
315
- <!-- BEGIN GENERATED:VIEW_HELPERS -->
316
- <!--
317
- This section is auto-generated by scripts/sdk-generate-docs.ts.
318
- Do not edit manually.
319
- -->
320
-
321
- - `getInterestRateStrategyFromPool`
322
- - `hydrateOraclePositionIds`
323
- - `previewBorrow`
324
- - `previewRepay`
325
- - `readAccessManagerBasics`
326
- - `readAccountPositions`
327
- - `readAccountPositionsFull`
328
- - `readAccountSnapshot`
329
- - `readAdapterInfo`
330
- - `readBadDebtStatus`
331
- - `readBorrowLimits`
332
- - `readBorrowerState`
333
- - `readBorrowers`
334
- - `readBorrowersPage`
335
- - `readCalculateLiquidationBonus`
336
- - `readCanLiquidate`
337
- - `readConfiguredPositionIds`
338
- - `readConvertLiquidatorBasics`
339
- - `readCoreAddresses`
340
- - `readCoreGlobalDebt`
341
- - `readDefaultLtvConfig`
342
- - `readHasRole`
343
- - `readHealthFactor`
344
- - `readHypotheticalBorrowCapacity`
345
- - `readInterestRateStrategyBasics`
346
- - `readLenderSnapshot`
347
- - `readLiquidationBonusBps`
348
- - `readLiquidationConfig`
349
- - `readLiquidationParamsForPosition`
350
- - `readLiquidatorBasics`
351
- - `readLiquidity`
352
- - `readLtvForPosition`
353
- - `readManyAccountSnapshots`
354
- - `readManyBorrowLimits`
355
- - `readManyHasRole`
356
- - `readManyLiquidationBonusBps`
357
- - `readManyOraclePositionMeta`
358
- - `readManyPositionSnapshots`
359
- - `readManyTargetConfigs`
360
- - `readManyTargetFunctionRoles`
361
- - `readMaxPositionsConfig`
362
- - `readMaxRedeem`
363
- - `readMaxWithdraw`
364
- - `readMergeLiquidatorBasics`
365
- - `readNegRiskMarketPositionIds`
366
- - `readOracleBasics`
367
- - `readOracleCollateralStatus`
368
- - `readOracleConfig`
369
- - `readOracleFinalizationStatus`
370
- - `readOracleGuardsStatus`
371
- - `readOraclePositionMeta`
372
- - `readOraclePriceData`
373
- - `readOracleRegistry`
374
- - `readOracleRegistryPage`
375
- - `readOracleTiming`
376
- - `readPoolAccounting`
377
- - `readPoolCaps`
378
- - `readPoolCoreAddress`
379
- - `readPoolDebtState`
380
- - `readPoolHealthScore`
381
- - `readPoolRates`
382
- - `readPoolSharePrice`
383
- - `readPoolSnapshot`
384
- - `readPortfolioValue`
385
- - `readPositionBalance`
386
- - `readPositionBalances`
387
- - `readPositionCount`
388
- - `readPositionLiquidationConfigOverride`
389
- - `readPositionLtvOverride`
390
- - `readPositionSnapshot`
391
- - `readPreviewLiquidation`
392
- - `readPrice`
393
- - `readProxyAdminPaused`
394
- - `readRepayTiming`
395
- - `readRiskTier`
396
- - `readRoleSummary`
397
- - `readSpotPrice`
398
- - `readSystemSnapshot`
399
- - `readTargetConfig`
400
- - `readTierLiquidationConfig`
401
- - `readTieredLtvConfig`
402
- - `readTryGetPrice`
403
- - `readTwap`
404
- <!-- END GENERATED:VIEW_HELPERS -->
405
-