defi-dash-sdk 0.1.3 → 0.1.4

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 (181) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +199 -97
  3. package/dist/__tests__/deleverageEstimate.unit.test.d.ts +10 -0
  4. package/dist/__tests__/deleverageEstimate.unit.test.d.ts.map +1 -0
  5. package/dist/__tests__/deleverageEstimate.unit.test.js +116 -0
  6. package/dist/__tests__/deleverageEstimate.unit.test.js.map +1 -0
  7. package/dist/__tests__/findBestLeverageRoute.test.d.ts +12 -0
  8. package/dist/__tests__/findBestLeverageRoute.test.d.ts.map +1 -0
  9. package/dist/__tests__/findBestLeverageRoute.test.js +177 -0
  10. package/dist/__tests__/findBestLeverageRoute.test.js.map +1 -0
  11. package/dist/__tests__/getAssetApy.test.d.ts +2 -0
  12. package/dist/__tests__/getAssetApy.test.d.ts.map +1 -0
  13. package/dist/__tests__/getAssetApy.test.js +133 -0
  14. package/dist/__tests__/getAssetApy.test.js.map +1 -0
  15. package/dist/__tests__/getAssetRiskParams.test.d.ts +11 -0
  16. package/dist/__tests__/getAssetRiskParams.test.d.ts.map +1 -0
  17. package/dist/__tests__/getAssetRiskParams.test.js +183 -0
  18. package/dist/__tests__/getAssetRiskParams.test.js.map +1 -0
  19. package/dist/__tests__/internal.getAssetApy.test.d.ts +2 -0
  20. package/dist/__tests__/internal.getAssetApy.test.d.ts.map +1 -0
  21. package/dist/__tests__/internal.getAssetApy.test.js +140 -0
  22. package/dist/__tests__/internal.getAssetApy.test.js.map +1 -0
  23. package/dist/__tests__/internal.getAssetRiskParams.test.d.ts +22 -0
  24. package/dist/__tests__/internal.getAssetRiskParams.test.d.ts.map +1 -0
  25. package/dist/__tests__/internal.getAssetRiskParams.test.js +194 -0
  26. package/dist/__tests__/internal.getAssetRiskParams.test.js.map +1 -0
  27. package/dist/__tests__/internal.getPosition.test.d.ts +22 -0
  28. package/dist/__tests__/internal.getPosition.test.d.ts.map +1 -0
  29. package/dist/__tests__/internal.getPosition.test.js +153 -0
  30. package/dist/__tests__/internal.getPosition.test.js.map +1 -0
  31. package/dist/__tests__/leveragePreview.unit.test.d.ts +10 -0
  32. package/dist/__tests__/leveragePreview.unit.test.d.ts.map +1 -0
  33. package/dist/__tests__/leveragePreview.unit.test.js +168 -0
  34. package/dist/__tests__/leveragePreview.unit.test.js.map +1 -0
  35. package/dist/__tests__/leverageRoute.unit.test.d.ts +10 -0
  36. package/dist/__tests__/leverageRoute.unit.test.d.ts.map +1 -0
  37. package/dist/__tests__/leverageRoute.unit.test.js +159 -0
  38. package/dist/__tests__/leverageRoute.unit.test.js.map +1 -0
  39. package/dist/__tests__/previewLeverage.test.d.ts +13 -0
  40. package/dist/__tests__/previewLeverage.test.d.ts.map +1 -0
  41. package/dist/__tests__/previewLeverage.test.js +217 -0
  42. package/dist/__tests__/previewLeverage.test.js.map +1 -0
  43. package/dist/__tests__/sdk.bestRoute.test.d.ts +22 -0
  44. package/dist/__tests__/sdk.bestRoute.test.d.ts.map +1 -0
  45. package/dist/__tests__/sdk.bestRoute.test.js +186 -0
  46. package/dist/__tests__/sdk.bestRoute.test.js.map +1 -0
  47. package/dist/__tests__/sdk.bestRoute.unit.test.d.ts +16 -0
  48. package/dist/__tests__/sdk.bestRoute.unit.test.d.ts.map +1 -0
  49. package/dist/__tests__/sdk.bestRoute.unit.test.js +165 -0
  50. package/dist/__tests__/sdk.bestRoute.unit.test.js.map +1 -0
  51. package/dist/__tests__/sdk.deleverage.test.d.ts +21 -0
  52. package/dist/__tests__/sdk.deleverage.test.d.ts.map +1 -0
  53. package/dist/__tests__/sdk.deleverage.test.js +130 -0
  54. package/dist/__tests__/sdk.deleverage.test.js.map +1 -0
  55. package/dist/__tests__/sdk.deleverage.unit.test.d.ts +21 -0
  56. package/dist/__tests__/sdk.deleverage.unit.test.d.ts.map +1 -0
  57. package/dist/__tests__/sdk.deleverage.unit.test.js +141 -0
  58. package/dist/__tests__/sdk.deleverage.unit.test.js.map +1 -0
  59. package/dist/__tests__/sdk.leverage.test.d.ts +19 -0
  60. package/dist/__tests__/sdk.leverage.test.d.ts.map +1 -0
  61. package/dist/__tests__/sdk.leverage.test.js +188 -0
  62. package/dist/__tests__/sdk.leverage.test.js.map +1 -0
  63. package/dist/__tests__/sdk.portfolio.test.d.ts +17 -0
  64. package/dist/__tests__/sdk.portfolio.test.d.ts.map +1 -0
  65. package/dist/__tests__/sdk.portfolio.test.js +162 -0
  66. package/dist/__tests__/sdk.portfolio.test.js.map +1 -0
  67. package/dist/__tests__/sdk.position.test.d.ts +16 -0
  68. package/dist/__tests__/sdk.position.test.d.ts.map +1 -0
  69. package/dist/__tests__/sdk.position.test.js +193 -0
  70. package/dist/__tests__/sdk.position.test.js.map +1 -0
  71. package/dist/__tests__/sdk.preview.test.d.ts +23 -0
  72. package/dist/__tests__/sdk.preview.test.d.ts.map +1 -0
  73. package/dist/__tests__/sdk.preview.test.js +226 -0
  74. package/dist/__tests__/sdk.preview.test.js.map +1 -0
  75. package/dist/__tests__/sdk.preview.unit.test.d.ts +18 -0
  76. package/dist/__tests__/sdk.preview.unit.test.d.ts.map +1 -0
  77. package/dist/__tests__/sdk.preview.unit.test.js +175 -0
  78. package/dist/__tests__/sdk.preview.unit.test.js.map +1 -0
  79. package/dist/__tests__/utils.normalizeCoinType.test.d.ts +7 -0
  80. package/dist/__tests__/utils.normalizeCoinType.test.d.ts.map +1 -0
  81. package/dist/__tests__/utils.normalizeCoinType.test.js +42 -0
  82. package/dist/__tests__/utils.normalizeCoinType.test.js.map +1 -0
  83. package/dist/index.d.ts +19 -11
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +24 -40
  86. package/dist/index.js.map +1 -1
  87. package/dist/protocols/base-adapter.d.ts +42 -75
  88. package/dist/protocols/base-adapter.d.ts.map +1 -1
  89. package/dist/protocols/base-adapter.js +34 -77
  90. package/dist/protocols/base-adapter.js.map +1 -1
  91. package/dist/protocols/navi/adapter.d.ts +22 -2
  92. package/dist/protocols/navi/adapter.d.ts.map +1 -1
  93. package/dist/protocols/navi/adapter.js +145 -11
  94. package/dist/protocols/navi/adapter.js.map +1 -1
  95. package/dist/protocols/scallop/adapter.d.ts +26 -6
  96. package/dist/protocols/scallop/adapter.d.ts.map +1 -1
  97. package/dist/protocols/scallop/adapter.js +206 -43
  98. package/dist/protocols/scallop/adapter.js.map +1 -1
  99. package/dist/protocols/scallop/flash-loan.d.ts +18 -3
  100. package/dist/protocols/scallop/flash-loan.d.ts.map +1 -1
  101. package/dist/protocols/scallop/flash-loan.js +79 -20
  102. package/dist/protocols/scallop/flash-loan.js.map +1 -1
  103. package/dist/protocols/scallop/types.d.ts.map +1 -1
  104. package/dist/protocols/scallop/types.js +4 -1
  105. package/dist/protocols/scallop/types.js.map +1 -1
  106. package/dist/protocols/suilend/adapter.d.ts +19 -1
  107. package/dist/protocols/suilend/adapter.d.ts.map +1 -1
  108. package/dist/protocols/suilend/adapter.js +196 -51
  109. package/dist/protocols/suilend/adapter.js.map +1 -1
  110. package/dist/sdk.d.ts +107 -148
  111. package/dist/sdk.d.ts.map +1 -1
  112. package/dist/sdk.js +171 -523
  113. package/dist/sdk.js.map +1 -1
  114. package/dist/strategies/common.d.ts +42 -0
  115. package/dist/strategies/common.d.ts.map +1 -0
  116. package/dist/strategies/common.js +81 -0
  117. package/dist/strategies/common.js.map +1 -0
  118. package/dist/strategies/deleverage.d.ts.map +1 -1
  119. package/dist/strategies/deleverage.js +44 -62
  120. package/dist/strategies/deleverage.js.map +1 -1
  121. package/dist/strategies/index.d.ts +9 -1
  122. package/dist/strategies/index.d.ts.map +1 -1
  123. package/dist/strategies/index.js +11 -2
  124. package/dist/strategies/index.js.map +1 -1
  125. package/dist/strategies/leverage-preview.d.ts +27 -0
  126. package/dist/strategies/leverage-preview.d.ts.map +1 -0
  127. package/dist/strategies/leverage-preview.js +120 -0
  128. package/dist/strategies/leverage-preview.js.map +1 -0
  129. package/dist/strategies/leverage-route.d.ts +29 -0
  130. package/dist/strategies/leverage-route.d.ts.map +1 -0
  131. package/dist/strategies/leverage-route.js +112 -0
  132. package/dist/strategies/leverage-route.js.map +1 -0
  133. package/dist/strategies/leverage.d.ts +4 -44
  134. package/dist/strategies/leverage.d.ts.map +1 -1
  135. package/dist/strategies/leverage.js +43 -112
  136. package/dist/strategies/leverage.js.map +1 -1
  137. package/dist/strategies/scallop-leverage.d.ts +34 -0
  138. package/dist/strategies/scallop-leverage.d.ts.map +1 -0
  139. package/dist/strategies/scallop-leverage.js +143 -0
  140. package/dist/strategies/scallop-leverage.js.map +1 -0
  141. package/dist/types/config.d.ts +0 -7
  142. package/dist/types/config.d.ts.map +1 -1
  143. package/dist/types/constants.d.ts +8 -0
  144. package/dist/types/constants.d.ts.map +1 -1
  145. package/dist/types/constants.js +9 -1
  146. package/dist/types/constants.js.map +1 -1
  147. package/dist/types/index.d.ts +3 -3
  148. package/dist/types/index.d.ts.map +1 -1
  149. package/dist/types/index.js +2 -1
  150. package/dist/types/index.js.map +1 -1
  151. package/dist/types/position.d.ts +7 -3
  152. package/dist/types/position.d.ts.map +1 -1
  153. package/dist/types/protocol.d.ts +101 -0
  154. package/dist/types/protocol.d.ts.map +1 -1
  155. package/dist/types/strategy.d.ts +82 -38
  156. package/dist/types/strategy.d.ts.map +1 -1
  157. package/dist/utils/calculations.d.ts +10 -137
  158. package/dist/utils/calculations.d.ts.map +1 -1
  159. package/dist/utils/calculations.js +11 -162
  160. package/dist/utils/calculations.js.map +1 -1
  161. package/dist/utils/coin.d.ts +16 -7
  162. package/dist/utils/coin.d.ts.map +1 -1
  163. package/dist/utils/coin.js +32 -25
  164. package/dist/utils/coin.js.map +1 -1
  165. package/dist/utils/errors.d.ts +0 -18
  166. package/dist/utils/errors.d.ts.map +1 -1
  167. package/dist/utils/errors.js +2 -40
  168. package/dist/utils/errors.js.map +1 -1
  169. package/dist/utils/execution.d.ts +38 -0
  170. package/dist/utils/execution.d.ts.map +1 -0
  171. package/dist/utils/execution.js +110 -0
  172. package/dist/utils/execution.js.map +1 -0
  173. package/dist/utils/gas.d.ts +0 -37
  174. package/dist/utils/gas.d.ts.map +1 -1
  175. package/dist/utils/gas.js +2 -60
  176. package/dist/utils/gas.js.map +1 -1
  177. package/dist/utils/index.d.ts +1 -1
  178. package/dist/utils/index.d.ts.map +1 -1
  179. package/dist/utils/index.js +1 -1
  180. package/dist/utils/index.js.map +1 -1
  181. package/package.json +15 -45
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ /**
3
+ * DeFi Dash SDK - Leverage Preview
4
+ *
5
+ * Pure-calculation module for previewing a leveraged position without executing.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.previewLeverage = previewLeverage;
9
+ const sdk_ts_1 = require("@7kprotocol/sdk-ts");
10
+ const types_1 = require("../types");
11
+ const flash_loan_1 = require("../protocols/scallop/flash-loan");
12
+ const utils_1 = require("../utils");
13
+ const calculations_1 = require("../utils/calculations");
14
+ const errors_1 = require("../utils/errors");
15
+ // ── Main function ────────────────────────────────────────────────────────────
16
+ /**
17
+ * Calculate a full leverage-position preview.
18
+ *
19
+ * Includes risk params, APY breakdown, flash-loan fee (on-chain),
20
+ * and swap slippage from a live 7k quote.
21
+ */
22
+ async function previewLeverage(params, deps) {
23
+ const { coinType, multiplier } = params;
24
+ const { protocol, swapClient, suiClient } = deps;
25
+ // ── Input validation ───────────────────────────────────────────────────────
26
+ if (!params.depositAmount && !params.depositValueUsd) {
27
+ throw new errors_1.InvalidParameterError("Either depositAmount or depositValueUsd must be provided");
28
+ }
29
+ if (params.depositAmount && params.depositValueUsd) {
30
+ throw new errors_1.InvalidParameterError("Cannot provide both depositAmount and depositValueUsd. Choose one.");
31
+ }
32
+ const decimals = (0, utils_1.getDecimals)(coinType);
33
+ // ── Risk parameters ────────────────────────────────────────────────────────
34
+ const riskParams = await protocol.getAssetRiskParams(coinType);
35
+ if (multiplier > riskParams.maxMultiplier) {
36
+ throw new errors_1.InvalidParameterError(`Multiplier ${multiplier}x exceeds protocol max ${riskParams.maxMultiplier.toFixed(2)}x`);
37
+ }
38
+ // ── Deposit amount resolution ──────────────────────────────────────────────
39
+ let depositAmountStr;
40
+ const price = await (0, sdk_ts_1.getTokenPrice)(coinType);
41
+ if (params.depositValueUsd) {
42
+ const amountInToken = params.depositValueUsd / price;
43
+ depositAmountStr = amountInToken.toFixed(decimals);
44
+ }
45
+ else {
46
+ depositAmountStr = params.depositAmount;
47
+ }
48
+ const depositAmount = (0, utils_1.parseUnits)(depositAmountStr, decimals);
49
+ const depositAmountHuman = Number(depositAmount) / Math.pow(10, decimals);
50
+ const initialEquityUsd = depositAmountHuman * price;
51
+ // ── Flash loan calculation ─────────────────────────────────────────────────
52
+ const flashLoanUsd = initialEquityUsd * (multiplier - 1);
53
+ const flashLoanUsdc = BigInt(Math.ceil(flashLoanUsd * 1e6));
54
+ const flashLoanFeeRate = await flash_loan_1.ScallopFlashLoanClient.fetchFlashLoanFeeRate(suiClient, types_1.COIN_TYPES.USDC);
55
+ const flashLoanFeeUsd = (Number(flashLoanUsdc) / 1e6) * flashLoanFeeRate;
56
+ const totalPositionUsd = initialEquityUsd * multiplier;
57
+ const debtUsd = flashLoanUsd + flashLoanFeeUsd;
58
+ const ltvPercent = (debtUsd / totalPositionUsd) * 100;
59
+ // ── Liquidation ────────────────────────────────────────────────────────────
60
+ const totalCollateralAmount = depositAmountHuman * multiplier;
61
+ const { liquidationPrice, priceDropBuffer } = (0, calculations_1.calculateLiquidationMetrics)(debtUsd, totalCollateralAmount, riskParams.liquidationThreshold, price);
62
+ // ── APY & Earnings ─────────────────────────────────────────────────────────
63
+ const depositApy = await protocol.getAssetApy(coinType);
64
+ const usdcCoinType = types_1.COIN_TYPES.USDC;
65
+ const borrowApyData = await protocol.getAssetApy(usdcCoinType);
66
+ const annualSupplyEarnings = totalPositionUsd * depositApy.totalSupplyApy;
67
+ const annualBorrowCost = debtUsd * borrowApyData.borrowApy;
68
+ const annualNetEarningsUsd = annualSupplyEarnings - annualBorrowCost;
69
+ const netApy = initialEquityUsd > 0 ? annualNetEarningsUsd / initialEquityUsd : 0;
70
+ // ── Swap slippage (7k quote) ───────────────────────────────────────────────
71
+ let swapSlippagePct = 1.0;
72
+ let effectiveMultiplier = multiplier;
73
+ const swapQuotes = await swapClient.quote({
74
+ amountIn: flashLoanUsdc.toString(),
75
+ coinTypeIn: types_1.COIN_TYPES.USDC,
76
+ coinTypeOut: coinType,
77
+ });
78
+ if (swapQuotes.length > 0) {
79
+ const bestQuote = [...swapQuotes].sort((a, b) => Number(b.amountOut) - Number(a.amountOut))[0];
80
+ const actualAmountOut = Number(bestQuote.amountOut) / Math.pow(10, decimals);
81
+ const theoreticalAmountOut = Number(flashLoanUsdc) / 1e6 / price;
82
+ if (theoreticalAmountOut > 0) {
83
+ const slippageRatio = (theoreticalAmountOut - actualAmountOut) / theoreticalAmountOut;
84
+ swapSlippagePct = Math.max(0, slippageRatio * 100);
85
+ }
86
+ const actualTotalToken = depositAmountHuman + actualAmountOut;
87
+ effectiveMultiplier =
88
+ actualAmountOut > 0
89
+ ? actualTotalToken / depositAmountHuman
90
+ : multiplier;
91
+ }
92
+ return {
93
+ initialEquityUsd,
94
+ flashLoanUsdc,
95
+ flashLoanFeeUsd,
96
+ totalPositionUsd,
97
+ debtUsd,
98
+ effectiveMultiplier,
99
+ maxMultiplier: riskParams.maxMultiplier,
100
+ assetLtv: riskParams.ltv,
101
+ ltvPercent,
102
+ liquidationThreshold: riskParams.liquidationThreshold,
103
+ liquidationPrice,
104
+ priceDropBuffer,
105
+ supplyApyBreakdown: {
106
+ base: depositApy.supplyApy,
107
+ reward: depositApy.rewardApy,
108
+ total: depositApy.totalSupplyApy,
109
+ },
110
+ borrowApyBreakdown: {
111
+ gross: borrowApyData.borrowApy + borrowApyData.borrowRewardApy,
112
+ rebate: borrowApyData.borrowRewardApy,
113
+ net: borrowApyData.borrowApy,
114
+ },
115
+ netApy,
116
+ annualNetEarningsUsd,
117
+ swapSlippagePct,
118
+ };
119
+ }
120
+ //# sourceMappingURL=leverage-preview.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"leverage-preview.js","sourceRoot":"","sources":["../../src/strategies/leverage-preview.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AAqCH,0CA0IC;AA5KD,+CAA2D;AAC3D,oCAIkB;AAClB,gEAAyE;AACzE,oCAAmD;AACnD,wDAAoE;AACpE,4CAAwD;AAiBxD,gFAAgF;AAEhF;;;;;GAKG;AACI,KAAK,UAAU,eAAe,CACnC,MAA6B,EAC7B,IAAyB;IAEzB,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,GAAG,MAAM,CAAC;IACxC,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;IAEjD,8EAA8E;IAC9E,IAAI,CAAC,MAAM,CAAC,aAAa,IAAI,CAAC,MAAM,CAAC,eAAe,EAAE,CAAC;QACrD,MAAM,IAAI,8BAAqB,CAC7B,0DAA0D,CAC3D,CAAC;IACJ,CAAC;IACD,IAAI,MAAM,CAAC,aAAa,IAAI,MAAM,CAAC,eAAe,EAAE,CAAC;QACnD,MAAM,IAAI,8BAAqB,CAC7B,oEAAoE,CACrE,CAAC;IACJ,CAAC;IAED,MAAM,QAAQ,GAAG,IAAA,mBAAW,EAAC,QAAQ,CAAC,CAAC;IAEvC,8EAA8E;IAC9E,MAAM,UAAU,GAAG,MAAM,QAAQ,CAAC,kBAAkB,CAAC,QAAQ,CAAC,CAAC;IAE/D,IAAI,UAAU,GAAG,UAAU,CAAC,aAAa,EAAE,CAAC;QAC1C,MAAM,IAAI,8BAAqB,CAC7B,cAAc,UAAU,0BAA0B,UAAU,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CACzF,CAAC;IACJ,CAAC;IAED,8EAA8E;IAC9E,IAAI,gBAAwB,CAAC;IAC7B,MAAM,KAAK,GAAG,MAAM,IAAA,sBAAa,EAAC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C;QACvD,MAAM,oBAAoB,GAAG,MAAM,CAAC,aAAa,CAAC,GAAG,GAAG,GAAG,KAAK,CAAC;QAEjE,IAAI,oBAAoB,GAAG,CAAC,EAAE,CAAC;YAC7B,MAAM,aAAa,GACjB,CAAC,oBAAoB,GAAG,eAAe,CAAC,GAAG,oBAAoB,CAAC;YAClE,eAAe,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,aAAa,GAAG,GAAG,CAAC,CAAC;QACrD,CAAC;QAED,MAAM,gBAAgB,GAAG,kBAAkB,GAAG,eAAe,CAAC;QAC9D,mBAAmB;YACjB,eAAe,GAAG,CAAC;gBACjB,CAAC,CAAC,gBAAgB,GAAG,kBAAkB;gBACvC,CAAC,CAAC,UAAU,CAAC;IACnB,CAAC;IAED,OAAO;QACL,gBAAgB;QAChB,aAAa;QACb,eAAe;QACf,gBAAgB;QAChB,OAAO;QACP,mBAAmB;QACnB,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,QAAQ,EAAE,UAAU,CAAC,GAAG;QACxB,UAAU;QACV,oBAAoB,EAAE,UAAU,CAAC,oBAAoB;QACrD,gBAAgB;QAChB,eAAe;QACf,kBAAkB,EAAE;YAClB,IAAI,EAAE,UAAU,CAAC,SAAS;YAC1B,MAAM,EAAE,UAAU,CAAC,SAAS;YAC5B,KAAK,EAAE,UAAU,CAAC,cAAc;SACjC;QACD,kBAAkB,EAAE;YAClB,KAAK,EAAE,aAAa,CAAC,SAAS,GAAG,aAAa,CAAC,eAAe;YAC9D,MAAM,EAAE,aAAa,CAAC,eAAe;YACrC,GAAG,EAAE,aAAa,CAAC,SAAS;SAC7B;QACD,MAAM;QACN,oBAAoB;QACpB,eAAe;KAChB,CAAC;AACJ,CAAC"}
@@ -0,0 +1,29 @@
1
+ /**
2
+ * DeFi Dash SDK - Leverage Route Finder
3
+ *
4
+ * Discovers the best protocol for leverage given an asset,
5
+ * comparing maxMultiplier and net APY across all initialized protocols.
6
+ */
7
+ import { LendingProtocol, ILendingProtocol, LeveragePreview, LeverageRouteResult, FindBestRouteParams } from "../types";
8
+ export interface FindBestRouteDeps {
9
+ /** Map of all initialized protocol adapters */
10
+ protocols: Map<LendingProtocol, ILendingProtocol>;
11
+ /** Function to call previewLeverage for a given protocol + params */
12
+ previewFn: (protocol: LendingProtocol, params: {
13
+ depositAsset: string;
14
+ depositAmount?: string;
15
+ depositValueUsd?: number;
16
+ multiplier: number;
17
+ }) => Promise<LeveragePreview>;
18
+ /** Resolve asset symbol to coin type */
19
+ resolveCoinType: (asset: string) => string;
20
+ }
21
+ /**
22
+ * Find the best leverage route across all initialized protocols.
23
+ *
24
+ * Returns two recommendations:
25
+ * 1. **bestMaxMultiplier** — the protocol offering the highest possible leverage
26
+ * 2. **bestApy** — the protocol with the highest net APY at a safe multiplier
27
+ */
28
+ export declare function findBestLeverageRoute(params: FindBestRouteParams, deps: FindBestRouteDeps): Promise<LeverageRouteResult>;
29
+ //# sourceMappingURL=leverage-route.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"leverage-route.d.ts","sourceRoot":"","sources":["../../src/strategies/leverage-route.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,eAAe,EACf,gBAAgB,EAChB,eAAe,EACf,mBAAmB,EACnB,mBAAmB,EAEpB,MAAM,UAAU,CAAC;AAWlB,MAAM,WAAW,iBAAiB;IAChC,+CAA+C;IAC/C,SAAS,EAAE,GAAG,CAAC,eAAe,EAAE,gBAAgB,CAAC,CAAC;IAClD,qEAAqE;IACrE,SAAS,EAAE,CACT,QAAQ,EAAE,eAAe,EACzB,MAAM,EAAE;QACN,YAAY,EAAE,MAAM,CAAC;QACrB,aAAa,CAAC,EAAE,MAAM,CAAC;QACvB,eAAe,CAAC,EAAE,MAAM,CAAC;QACzB,UAAU,EAAE,MAAM,CAAC;KACpB,KACE,OAAO,CAAC,eAAe,CAAC,CAAC;IAC9B,wCAAwC;IACxC,eAAe,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC;CAC5C;AAID;;;;;;GAMG;AACH,wBAAsB,qBAAqB,CACzC,MAAM,EAAE,mBAAmB,EAC3B,IAAI,EAAE,iBAAiB,GACtB,OAAO,CAAC,mBAAmB,CAAC,CA0I9B"}
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ /**
3
+ * DeFi Dash SDK - Leverage Route Finder
4
+ *
5
+ * Discovers the best protocol for leverage given an asset,
6
+ * comparing maxMultiplier and net APY across all initialized protocols.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.findBestLeverageRoute = findBestLeverageRoute;
10
+ const types_1 = require("../types");
11
+ const errors_1 = require("../utils/errors");
12
+ /** Safety margin subtracted from maxMultiplier when requesting a near-max preview */
13
+ const MAX_MULT_SAFETY_MARGIN = 0.01;
14
+ /** Minimum safe multiplier floor (below this leverage has negligible effect) */
15
+ const MIN_SAFE_MULTIPLIER = 1.1;
16
+ // ── Main function ────────────────────────────────────────────────────────────
17
+ /**
18
+ * Find the best leverage route across all initialized protocols.
19
+ *
20
+ * Returns two recommendations:
21
+ * 1. **bestMaxMultiplier** — the protocol offering the highest possible leverage
22
+ * 2. **bestApy** — the protocol with the highest net APY at a safe multiplier
23
+ */
24
+ async function findBestLeverageRoute(params, deps) {
25
+ // ── Input validation ───────────────────────────────────────────────────────
26
+ if (!params.depositAmount && !params.depositValueUsd) {
27
+ throw new errors_1.InvalidParameterError("Either depositAmount or depositValueUsd must be provided");
28
+ }
29
+ if (params.depositAmount && params.depositValueUsd) {
30
+ throw new errors_1.InvalidParameterError("Cannot provide both depositAmount and depositValueUsd. Choose one.");
31
+ }
32
+ const coinType = deps.resolveCoinType(params.depositAsset);
33
+ const allProtocols = Array.from(deps.protocols.keys());
34
+ // ── Phase 1: Risk params (lightweight) ─────────────────────────────────────
35
+ const riskResults = await Promise.allSettled(allProtocols.map((protocol) => deps.protocols
36
+ .get(protocol)
37
+ .getAssetRiskParams(coinType)
38
+ .then((riskParams) => ({ protocol, riskParams }))));
39
+ const successfulRisk = [];
40
+ const failedProtocols = [];
41
+ riskResults.forEach((result, i) => {
42
+ if (result.status === "fulfilled") {
43
+ successfulRisk.push(result.value);
44
+ }
45
+ else {
46
+ failedProtocols.push({
47
+ protocol: allProtocols[i],
48
+ error: result.reason?.message || String(result.reason),
49
+ });
50
+ }
51
+ });
52
+ if (successfulRisk.length === 0) {
53
+ throw new errors_1.InvalidParameterError(`No protocol supports asset "${params.depositAsset}" for leverage. ` +
54
+ `Errors: ${failedProtocols.map((f) => `${f.protocol}: ${f.error}`).join("; ")}`);
55
+ }
56
+ // ── Safe multiplier ────────────────────────────────────────────────────────
57
+ const minMaxMultiplier = Math.min(...successfulRisk.map((r) => r.riskParams.maxMultiplier));
58
+ const safeMultiplier = Math.max(MIN_SAFE_MULTIPLIER, minMaxMultiplier - types_1.LEVERAGE_MULTIPLIER_BUFFER);
59
+ // ── Best max-multiplier protocol ───────────────────────────────────────────
60
+ const bestMaxEntry = successfulRisk.reduce((best, curr) => curr.riskParams.maxMultiplier > best.riskParams.maxMultiplier
61
+ ? curr
62
+ : best);
63
+ // ── Phase 2: Previews ─────────────────────────────────────────────────────
64
+ const maxMultPreviewPromise = deps.previewFn(bestMaxEntry.protocol, {
65
+ depositAsset: params.depositAsset,
66
+ depositAmount: params.depositAmount,
67
+ depositValueUsd: params.depositValueUsd,
68
+ multiplier: Math.round((bestMaxEntry.riskParams.maxMultiplier - MAX_MULT_SAFETY_MARGIN) * 100) / 100,
69
+ });
70
+ const safePreviewResults = await Promise.allSettled(successfulRisk.map(({ protocol }) => deps
71
+ .previewFn(protocol, {
72
+ depositAsset: params.depositAsset,
73
+ depositAmount: params.depositAmount,
74
+ depositValueUsd: params.depositValueUsd,
75
+ multiplier: safeMultiplier,
76
+ })
77
+ .then((preview) => ({ protocol, preview }))));
78
+ const safeSuccessful = [];
79
+ safePreviewResults.forEach((result, i) => {
80
+ if (result.status === "fulfilled") {
81
+ safeSuccessful.push(result.value);
82
+ }
83
+ else {
84
+ failedProtocols.push({
85
+ protocol: successfulRisk[i].protocol,
86
+ error: `Failed at safe multiplier ${safeMultiplier}x: ${result.reason?.message}`,
87
+ });
88
+ }
89
+ });
90
+ if (safeSuccessful.length === 0) {
91
+ throw new errors_1.InvalidParameterError(`No protocol could preview at safe multiplier ${safeMultiplier}x for "${params.depositAsset}"`);
92
+ }
93
+ // ── Best APY protocol ──────────────────────────────────────────────────────
94
+ const bestApyEntry = safeSuccessful.reduce((best, curr) => curr.preview.netApy > best.preview.netApy ? curr : best);
95
+ const maxMultPreview = await maxMultPreviewPromise;
96
+ return {
97
+ bestMaxMultiplier: {
98
+ protocol: bestMaxEntry.protocol,
99
+ multiplier: Math.round((bestMaxEntry.riskParams.maxMultiplier - MAX_MULT_SAFETY_MARGIN) * 100) / 100,
100
+ preview: maxMultPreview,
101
+ },
102
+ bestApy: {
103
+ protocol: bestApyEntry.protocol,
104
+ multiplier: safeMultiplier,
105
+ preview: bestApyEntry.preview,
106
+ },
107
+ safeMultiplier,
108
+ allPreviews: safeSuccessful,
109
+ failedProtocols,
110
+ };
111
+ }
112
+ //# sourceMappingURL=leverage-route.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"leverage-route.js","sourceRoot":"","sources":["../../src/strategies/leverage-route.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;AA8CH,sDA6IC;AAzLD,oCAOkB;AAClB,4CAAwD;AAExD,qFAAqF;AACrF,MAAM,sBAAsB,GAAG,IAAI,CAAC;AAEpC,gFAAgF;AAChF,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAqBhC,gFAAgF;AAEhF;;;;;;GAMG;AACI,KAAK,UAAU,qBAAqB,CACzC,MAA2B,EAC3B,IAAuB;IAEvB,8EAA8E;IAC9E,IAAI,CAAC,MAAM,CAAC,aAAa,IAAI,CAAC,MAAM,CAAC,eAAe,EAAE,CAAC;QACrD,MAAM,IAAI,8BAAqB,CAC7B,0DAA0D,CAC3D,CAAC;IACJ,CAA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,CAAC,KAAK,CAAC,CAAC,YAAY,CAAC,UAAU,CAAC,aAAa,GAAG,sBAAsB,CAAC,GAAG,GAAG,CAAC,GAAG,GAAG;YAC1F,OAAO,EAAE,cAAc;SACxB;QACD,OAAO,EAAE;YACP,QAAQ,EAAE,YAAY,CAAC,QAAQ;YAC/B,UAAU,EAAE,cAAc;YAC1B,OAAO,EAAE,YAAY,CAAC,OAAO;SAC9B;QACD,cAAc;QACd,WAAW,EAAE,cAAc;QAC3B,eAAe;KAChB,CAAC;AACJ,CAAC"}
@@ -6,7 +6,7 @@
6
6
  import { Transaction } from "@mysten/sui/transactions";
7
7
  import { SuiClient } from "@mysten/sui/client";
8
8
  import { MetaAg } from "@7kprotocol/sdk-ts";
9
- import { ILendingProtocol, LeveragePreview } from "../types";
9
+ import { ILendingProtocol } from "../types";
10
10
  import { ScallopFlashLoanClient } from "../protocols/scallop/flash-loan";
11
11
  export interface LeverageBuildParams {
12
12
  protocol: ILendingProtocol;
@@ -18,46 +18,6 @@ export interface LeverageBuildParams {
18
18
  depositAmount: bigint;
19
19
  multiplier: number;
20
20
  }
21
- /**
22
- * Calculate leverage position preview without executing
23
- *
24
- * Computes expected position metrics including flash loan amount,
25
- * total position value, LTV, and liquidation parameters.
26
- *
27
- * @param params - Preview calculation parameters
28
- * @param params.depositCoinType - Full coin type of deposit asset
29
- * @param params.depositAmount - Deposit amount in raw units (bigint)
30
- * @param params.multiplier - Target leverage multiplier (e.g., 2.0 for 2x)
31
- *
32
- * @returns Preview containing position metrics and risk parameters
33
- *
34
- * @example
35
- * ```typescript
36
- * const preview = await calculateLeveragePreview({
37
- * depositCoinType: '0x2::sui::SUI',
38
- * depositAmount: 1000000000n, // 1 SUI
39
- * multiplier: 2.0
40
- * });
41
- *
42
- * console.log(`Flash loan needed: ${preview.flashLoanUsdc / 1e6} USDC`);
43
- * console.log(`Total position: $${preview.totalPositionUsd}`);
44
- * console.log(`LTV: ${preview.ltvPercent}%`);
45
- * ```
46
- *
47
- * @remarks
48
- * - Fetches current market prices from 7k Protocol
49
- * - Assumes 60% LTV threshold for liquidation calculations
50
- * - Adds 2% buffer to flash loan amount for safety
51
- *
52
- * @note This function is intentionally placed here as it's tightly coupled
53
- * with the leverage strategy logic. Consider moving to a separate preview
54
- * module if reuse across strategies is needed.
55
- */
56
- export declare function calculateLeveragePreview(params: {
57
- depositCoinType: string;
58
- depositAmount: bigint;
59
- multiplier: number;
60
- }): Promise<LeveragePreview>;
61
21
  /**
62
22
  * Build leverage transaction as a Programmable Transaction Block (PTB)
63
23
  *
@@ -65,9 +25,9 @@ export declare function calculateLeveragePreview(params: {
65
25
  *
66
26
  * **Transaction Flow:**
67
27
  * 1. Borrow USDC via flash loan from Scallop
68
- * 2. Swap USDC to deposit asset via 7k Protocol aggregator
69
- * 3. Merge user's deposit with swapped amount
70
- * 4. Refresh protocol oracles
28
+ * 2. Refresh protocol oracles (before swap to avoid Pyth conflicts)
29
+ * 3. Swap USDC to deposit asset via 7k Protocol aggregator
30
+ * 4. Merge user's deposit with swapped amount
71
31
  * 5. Deposit total collateral to lending protocol
72
32
  * 6. Borrow USDC from protocol to repay flash loan
73
33
  * 7. Repay flash loan (transaction fails if not repaid)
@@ -1 +1 @@
1
- {"version":3,"file":"leverage.d.ts","sourceRoot":"","sources":["../../src/strategies/leverage.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC/C,OAAO,EAAE,MAAM,EAAiB,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EACL,gBAAgB,EAEhB,eAAe,EAGhB,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AAIzE,MAAM,WAAW,mBAAmB;IAClC,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,eAAe,EAAE,sBAAsB,CAAC;IACxC,UAAU,EAAE,M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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsDG;AACH,wBAAsB,wBAAwB,CAC5C,EAAE,EAAE,WAAW,EACf,MAAM,EAAE,mBAAmB,GAC1B,OAAO,CAAC,IAAI,CAAC,CA0If"}
@@ -5,76 +5,11 @@
5
5
  * Builds leverage transactions using flash loan + swap + deposit + borrow
6
6
  */
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
- exports.calculateLeveragePreview = calculateLeveragePreview;
9
8
  exports.buildLeverageTransaction = buildLeverageTransaction;
10
9
  const sdk_ts_1 = require("@7kprotocol/sdk-ts");
11
10
  const types_1 = require("../types");
12
11
  const utils_1 = require("../utils");
13
- const constants_1 = require("../protocols/suilend/constants");
14
- /**
15
- * Calculate leverage position preview without executing
16
- *
17
- * Computes expected position metrics including flash loan amount,
18
- * total position value, LTV, and liquidation parameters.
19
- *
20
- * @param params - Preview calculation parameters
21
- * @param params.depositCoinType - Full coin type of deposit asset
22
- * @param params.depositAmount - Deposit amount in raw units (bigint)
23
- * @param params.multiplier - Target leverage multiplier (e.g., 2.0 for 2x)
24
- *
25
- * @returns Preview containing position metrics and risk parameters
26
- *
27
- * @example
28
- * ```typescript
29
- * const preview = await calculateLeveragePreview({
30
- * depositCoinType: '0x2::sui::SUI',
31
- * depositAmount: 1000000000n, // 1 SUI
32
- * multiplier: 2.0
33
- * });
34
- *
35
- * console.log(`Flash loan needed: ${preview.flashLoanUsdc / 1e6} USDC`);
36
- * console.log(`Total position: $${preview.totalPositionUsd}`);
37
- * console.log(`LTV: ${preview.ltvPercent}%`);
38
- * ```
39
- *
40
- * @remarks
41
- * - Fetches current market prices from 7k Protocol
42
- * - Assumes 60% LTV threshold for liquidation calculations
43
- * - Adds 2% buffer to flash loan amount for safety
44
- *
45
- * @note This function is intentionally placed here as it's tightly coupled
46
- * with the leverage strategy logic. Consider moving to a separate preview
47
- * module if reuse across strategies is needed.
48
- */
49
- async function calculateLeveragePreview(params) {
50
- const { depositCoinType, depositAmount, multiplier } = params;
51
- const normalized = (0, utils_1.normalizeCoinType)(depositCoinType);
52
- const reserve = (0, constants_1.getReserveByCoinType)(normalized);
53
- const decimals = reserve?.decimals || 8;
54
- const depositPrice = await (0, sdk_ts_1.getTokenPrice)(normalized);
55
- const depositAmountHuman = Number(depositAmount) / Math.pow(10, decimals);
56
- const initialEquityUsd = depositAmountHuman * depositPrice;
57
- // Flash loan amount = Initial Equity * (Multiplier - 1)
58
- const flashLoanUsd = initialEquityUsd * (multiplier - 1);
59
- const flashLoanUsdc = BigInt(Math.ceil(flashLoanUsd * 1e6 * 1.02)); // 2% buffer
60
- const totalPositionUsd = initialEquityUsd * multiplier;
61
- const debtUsd = flashLoanUsd;
62
- const ltvPercent = (debtUsd / totalPositionUsd) * 100;
63
- // Assume 60% LTV for liquidation calculation
64
- const LTV = 0.6;
65
- const liquidationPrice = debtUsd / (depositAmountHuman * multiplier) / LTV;
66
- const priceDropBuffer = (1 - liquidationPrice / depositPrice) * 100;
67
- return {
68
- initialEquityUsd,
69
- flashLoanUsdc,
70
- totalPositionUsd,
71
- debtUsd,
72
- effectiveMultiplier: multiplier,
73
- ltvPercent,
74
- liquidationPrice,
75
- priceDropBuffer,
76
- };
77
- }
12
+ const common_1 = require("./common");
78
13
  /**
79
14
  * Build leverage transaction as a Programmable Transaction Block (PTB)
80
15
  *
@@ -82,9 +17,9 @@ async function calculateLeveragePreview(params) {
82
17
  *
83
18
  * **Transaction Flow:**
84
19
  * 1. Borrow USDC via flash loan from Scallop
85
- * 2. Swap USDC to deposit asset via 7k Protocol aggregator
86
- * 3. Merge user's deposit with swapped amount
87
- * 4. Refresh protocol oracles
20
+ * 2. Refresh protocol oracles (before swap to avoid Pyth conflicts)
21
+ * 3. Swap USDC to deposit asset via 7k Protocol aggregator
22
+ * 4. Merge user's deposit with swapped amount
88
23
  * 5. Deposit total collateral to lending protocol
89
24
  * 6. Borrow USDC from protocol to repay flash loan
90
25
  * 7. Repay flash loan (transaction fails if not repaid)
@@ -136,37 +71,30 @@ async function buildLeverageTransaction(tx, params) {
136
71
  // These cannot be used as collateral because we borrow USDC to repay the flash loan
137
72
  const normalizedDeposit = (0, utils_1.normalizeCoinType)(depositCoinType);
138
73
  if (types_1.UNSUPPORTED_COIN_TYPES.includes(normalizedDeposit)) {
139
- // Check ❌: What about listing errors like solidity contract styles to avoid gerneral error message or using enum for erros.
74
+ // TODO(#6): Use typed UnsupportedAssetError instead of generic Error
140
75
  throw new Error(`Unsupported deposit asset for leverage strategy. Stablecoins like USDC cannot be used as collateral.`);
141
76
  }
142
- // Use SDK-level COIN_DECIMALS for decimal info, fallback to reserve lookup
143
- // TODO: Future improvement - make protocol adapters provide decimal info
144
77
  const normalized = normalizedDeposit;
145
- const reserve = (0, constants_1.getReserveByCoinType)(normalized);
146
- const decimals = types_1.COIN_DECIMALS[normalized] ?? reserve?.decimals ?? 8;
147
- // Calculate preview to get flash loan amount
148
- const preview = await calculateLeveragePreview({
149
- depositCoinType: normalized,
150
- depositAmount,
151
- multiplier,
152
- });
153
- const flashLoanUsdc = preview.flashLoanUsdc;
78
+ const decimals = (0, utils_1.getDecimals)(normalized);
79
+ // Calculate flash loan amount directly
80
+ const depositPrice = await (0, sdk_ts_1.getTokenPrice)(normalized);
81
+ const initialEquityUsd = (Number(depositAmount) / 10 ** decimals) * depositPrice;
82
+ const flashLoanUsdc = BigInt(Math.ceil(initialEquityUsd * (multiplier - 1) * 1e6));
154
83
  // 1. Flash loan USDC from Scallop
155
- // TODO: Support other flash loan assets (USDT) in the future
84
+ // TODO(#7): Support other flash loan assets (USDT) in the future
156
85
  const FLASH_LOAN_ASSET = "usdc";
157
86
  const [loanCoin, receipt] = flashLoanClient.borrowFlashLoan(tx, flashLoanUsdc, FLASH_LOAN_ASSET);
158
- // 2. Swap USDC deposit asset
87
+ // 2. Refresh oracles BEFORE swap to avoid Pyth hot potato conflicts.
88
+ // The 7k swap may add Pyth oracle update commands for DEX routing.
89
+ // If refreshOracles also adds Pyth updates for the same feeds AFTER
90
+ // the swap, both create Pyth hot potatoes for the same price feeds,
91
+ // causing dynamic_field::add abort. Refreshing first ensures the
92
+ // protocol's Pyth lifecycle completes before the swap starts.
93
+ await protocol.refreshOracles(tx, [normalized, types_1.USDC_COIN_TYPE], userAddress);
94
+ // 3. Swap USDC → deposit asset
159
95
  // Note: Stablecoins are already rejected above, so swap is always needed
160
- const swapQuotes = await swapClient.quote({
161
- amountIn: flashLoanUsdc.toString(),
162
- coinTypeIn: types_1.USDC_COIN_TYPE,
163
- coinTypeOut: normalized,
164
- });
165
- if (swapQuotes.length === 0) {
166
- throw new Error(`No swap quotes found for USDC → ${reserve?.symbol ?? normalized}`);
167
- }
168
- const bestQuote = swapQuotes.sort((a, b) => Number(b.amountOut) - Number(a.amountOut))[0];
169
- // TODO: Make slippage configurable via leverage params
96
+ const { quote: bestQuote } = await (0, common_1.findBestSwapQuote)(swapClient, flashLoanUsdc.toString(), types_1.USDC_COIN_TYPE, normalized, `USDC \u2192 ${normalized.split("::").pop() ?? normalized}`);
97
+ // TODO(#8): Make slippage configurable via leverage params
170
98
  const SLIPPAGE_BPS = 100; // 1%
171
99
  const swappedAsset = await swapClient.swap({
172
100
  quote: bestQuote,
@@ -174,29 +102,36 @@ async function buildLeverageTransaction(tx, params) {
174
102
  coinIn: loanCoin,
175
103
  tx: tx,
176
104
  }, SLIPPAGE_BPS);
177
- // 3. Prepare deposit coin (merge user's asset with swapped)
105
+ // 4. Prepare deposit coin (merge user's asset with swapped)
178
106
  let depositCoin;
179
107
  const isSui = normalized.endsWith("::sui::SUI");
180
108
  if (isSui) {
181
109
  // For SUI: swappedAsset is already Coin<SUI> from swap
182
110
  // Split user's deposit from gas and merge INTO swapped asset
183
- // TODO: Optimize SUI handling - consider checking balance first
111
+ // TODO(#9): Optimize SUI handling - consider checking balance first
184
112
  const [userDeposit] = tx.splitCoins(tx.gas, [tx.pure.u64(depositAmount)]);
185
113
  tx.mergeCoins(swappedAsset, [userDeposit]);
186
114
  depositCoin = swappedAsset;
187
115
  }
188
116
  else {
189
- // For non-SUI: fetch user's coins, merge, split exact amount
190
- const userCoins = await suiClient.getCoins({
191
- owner: userAddress,
192
- coinType: normalized,
193
- });
194
- if (userCoins.data.length === 0) {
195
- throw new Error(`No ${reserve?.symbol} coins found in wallet`);
117
+ // For non-SUI: fetch ALL user's coins (paginated), merge, split exact amount
118
+ const allCoins = [];
119
+ let cursor = undefined;
120
+ do {
121
+ const page = await suiClient.getCoins({
122
+ owner: userAddress,
123
+ coinType: normalized,
124
+ cursor: cursor ?? undefined,
125
+ });
126
+ allCoins.push(...page.data);
127
+ cursor = page.hasNextPage ? page.nextCursor : null;
128
+ } while (cursor);
129
+ if (allCoins.length === 0) {
130
+ throw new Error(`No ${normalized.split("::").pop()} coins found in wallet`);
196
131
  }
197
- const primaryCoin = tx.object(userCoins.data[0].coinObjectId);
198
- if (userCoins.data.length > 1) {
199
- const otherCoins = userCoins.data
132
+ const primaryCoin = tx.object(allCoins[0].coinObjectId);
133
+ if (allCoins.length > 1) {
134
+ const otherCoins = allCoins
200
135
  .slice(1)
201
136
  .map((c) => tx.object(c.coinObjectId));
202
137
  tx.mergeCoins(primaryCoin, otherCoins);
@@ -208,18 +143,14 @@ async function buildLeverageTransaction(tx, params) {
208
143
  tx.mergeCoins(swappedAsset, [userContribution]);
209
144
  depositCoin = swappedAsset;
210
145
  }
211
- // 4. Refresh oracles (required before deposit/borrow operations)
212
- await protocol.refreshOracles(tx, [normalized, types_1.USDC_COIN_TYPE], userAddress);
213
146
  // 5. Deposit to lending protocol
214
147
  await protocol.deposit(tx, depositCoin, normalized, userAddress);
215
148
  // 6. Calculate repayment amount (flash loan + fee + borrow interest buffer)
216
- // TODO: Consider adding flash loan fee query method to protocol SDK
149
+ // TODO(#10): Consider adding flash loan fee query method to protocol SDK
217
150
  // const flashLoanFee = ScallopFlashLoanClient.calculateFee(flashLoanUsdc);
218
151
  const repaymentAmount = flashLoanUsdc;
219
- // Add 0.5% buffer for borrow interest that accrues immediately
220
- // This ensures we borrow enough to cover the flash loan repayment
221
- const BORROW_FEE_BUFFER = 1.005;
222
- const borrowAmount = BigInt(Math.ceil(Number(repaymentAmount) * BORROW_FEE_BUFFER));
152
+ // Add buffer for borrow interest that accrues immediately
153
+ const borrowAmount = BigInt(Math.ceil(Number(repaymentAmount) * common_1.BORROW_FEE_BUFFER));
223
154
  // 7. Borrow USDC to repay flash loan
224
155
  const borrowedUsdc = await protocol.borrow(tx, types_1.USDC_COIN_TYPE, borrowAmount.toString(), userAddress, true);
225
156
  // 8. Repay flash loan (excess amount is returned to user)
@@ -1 +1 @@
1
- {"version":3,"file":"leverage.js","sourceRoot":"","sources":["../../src/strategies/leverage.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;AA8DH,4DAsCC;AAyDD,4DAkJC;AA3SD,+CAA2D;AAC3D,oCAMkB;AAElB,oCAA6C;AAC7C,8DAAsE;AAatE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACI,KAAK,UAAU,wBAAwB,CAAC,MAI9C;IACC,MAAM,EAAE,eAAe,EAAE,aAAa,EAAE,UAAU,EAAE,GAAG,MAAM,CAAC;IAE9D,MAAM,UAAU,GAAG,IAAA,yBAAiB,EAAC,eAAe,CAAC,CAAC;IACtD,MAAM,OAAO,GAAG,IAAA,gCAAoB,EAAC,UAAU,CAAC,CAAC;IACjD,MAAM,QAAQ,GAAG,OAAO,EAAE,QAAQ,IAAI,CAAC,CAAC;IAExC,MAAM,YAAY,GAAG,MAAM,IAAA,sBAAa,EAAC,UAAU,CAAC,CAAC;IACrD,MAAM,kBAAkB,GAAG,MAAM,CAAC,aAAa,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;IAC1E,MAAM,gBAAgB,GAAG,kBAAkB,GAAG,YAAY,CAAC;IAE3D,wDAAwD;IACxD,MAAM,YAAY,GAAG,gBAAgB,GAAG,CAAC,UAAU,GAAG,CAAC,CAA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,CAAC;IAEjE,4EAA4E;IAC5E,yEAAyE;IACzE,2EAA2E;IAC3E,MAAM,eAAe,GAAG,aAAa,CAAC;IAEtC,0DAA0D;IAC1D,MAAM,YAAY,GAAG,MAAM,CACzB,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,GAAG,0BAAiB,CAAC,CACvD,CAAC;IAEF,qCAAqC;IACrC,MAAM,YAAY,GAAG,MAAM,QAAQ,CAAC,MAAM,CACxC,EAAE,EACF,sBAAc,EACd,YAAY,CAAC,QAAQ,EAAE,EACvB,WAAW,EACX,IAAI,CACL,CAAC;IAEF,0DAA0D;IAC1D,eAAe,CAAC,cAAc,CAAC,EAAE,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,CAAC,CAAC;AAC9E,CAAC"}
@@ -0,0 +1,34 @@
1
+ /**
2
+ * DeFi Dash SDK - Scallop Leverage Transaction Builder
3
+ *
4
+ * Builds leverage transactions using the native Scallop SDK builder,
5
+ * which handles oracle price updates via updateAssetPricesQuick.
6
+ */
7
+ import { SuiClient } from "@mysten/sui/client";
8
+ import { MetaAg } from "@7kprotocol/sdk-ts";
9
+ export interface ScallopLeverageBuildParams {
10
+ coinType: string;
11
+ depositAmount?: string;
12
+ depositValueUsd?: number;
13
+ multiplier: number;
14
+ userAddress: string;
15
+ secretKey: string;
16
+ }
17
+ export interface ScallopLeverageDeps {
18
+ suiClient: SuiClient;
19
+ swapClient: MetaAg;
20
+ }
21
+ export interface ScallopLeverageBuildResult {
22
+ /** Scallop txBlock (builder.createTxBlock()) — call `builder.signAndSendTxBlock(tx)` to execute */
23
+ tx: any;
24
+ /** Scallop builder instance (needed for signAndSendTxBlock) */
25
+ builder: any;
26
+ }
27
+ /**
28
+ * Build a Scallop leverage transaction using the native Scallop SDK builder.
29
+ *
30
+ * Returns the built txBlock and builder so the caller can handle
31
+ * dry-run / execution logic.
32
+ */
33
+ export declare function buildScallopLeverageTransaction(params: ScallopLeverageBuildParams, deps: ScallopLeverageDeps): Promise<ScallopLeverageBuildResult>;
34
+ //# sourceMappingURL=scallop-leverage.d.ts.map