@gearbox-protocol/sdk 16.0.0-next.17 → 16.0.0-next.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/common-utils/index.js +3 -21
- package/dist/cjs/common-utils/test-utils/index.js +4 -3
- package/dist/cjs/common-utils/utils/index.js +3 -22
- package/dist/cjs/common-utils/utils/strategies/index.js +3 -0
- package/dist/cjs/common-utils/utils/strategies/strategy-info/cm-availability-condition.js +5 -5
- package/dist/cjs/common-utils/utils/strategies/strategy-info/credit-manager-issues.js +135 -0
- package/dist/cjs/common-utils/utils/strategies/strategy-info/get-cm-you-can-earn.js +12 -23
- package/dist/cjs/common-utils/utils/strategies/strategy-info/index.js +3 -0
- package/dist/cjs/onchain/accounts/index.js +2 -3
- package/dist/cjs/onchain/accounts/intents/guards.js +55 -50
- package/dist/cjs/onchain/accounts/intents/index.js +24 -16
- package/dist/cjs/onchain/accounts/intents/leverage-band.js +2 -2
- package/dist/cjs/onchain/accounts/intents/math.js +15 -22
- package/dist/cjs/onchain/accounts/intents/open-strategy.js +5 -5
- package/dist/cjs/onchain/accounts/intents/plan.js +27 -41
- package/dist/cjs/onchain/accounts/intents/realize.js +14 -21
- package/dist/cjs/onchain/accounts/intents/tail.js +2 -2
- package/dist/cjs/onchain/accounts/intents/testing/sdk-mock.js +2 -1
- package/dist/cjs/onchain/accounts/intents/view.js +1 -0
- package/dist/cjs/onchain/constants/index.js +1 -0
- package/dist/cjs/onchain/constants/math.js +11 -0
- package/dist/cjs/onchain/index.js +32 -3
- package/dist/cjs/onchain/market/credit/CreditManagerV310Contract.js +2 -2
- package/dist/cjs/onchain/market/math.js +23 -11
- package/dist/cjs/onchain/validation/checks.js +250 -0
- package/dist/cjs/onchain/validation/index.js +29 -0
- package/dist/cjs/onchain/{accounts/intents → validation}/refusal.js +12 -1
- package/dist/cjs/onchain/validation/token.js +29 -0
- package/dist/cjs/preview/index.js +10 -0
- package/dist/cjs/preview/preview/buildDelayedPreview.js +1 -0
- package/dist/cjs/preview/preview/previewAdjustCreditAccount.js +1 -0
- package/dist/cjs/preview/preview/previewOpenCreditAccount.js +1 -0
- package/dist/cjs/preview/validate/checkOperation.js +173 -0
- package/dist/cjs/preview/validate/checkSimulation.js +52 -0
- package/dist/cjs/preview/validate/index.js +6 -0
- package/dist/cjs/sdk/index.js +4 -0
- package/dist/cjs/sdk/prepare/PrepareApi.js +23 -17
- package/dist/cjs/sdk/prepare/index.js +4 -0
- package/dist/cjs/sdk/prepare/types.js +4 -0
- package/dist/esm/common-utils/index.js +2 -11
- package/dist/esm/common-utils/test-utils/index.js +4 -3
- package/dist/esm/common-utils/utils/index.js +2 -12
- package/dist/esm/common-utils/utils/strategies/index.js +2 -1
- package/dist/esm/common-utils/utils/strategies/strategy-info/cm-availability-condition.js +5 -5
- package/dist/esm/common-utils/utils/strategies/strategy-info/credit-manager-issues.js +133 -0
- package/dist/esm/common-utils/utils/strategies/strategy-info/get-cm-you-can-earn.js +12 -23
- package/dist/esm/common-utils/utils/strategies/strategy-info/index.js +2 -1
- package/dist/esm/dev/AccountOpener.js +1 -1
- package/dist/esm/dev/withdrawalUtils.js +1 -1
- package/dist/esm/onchain/accounts/CreditAccountsServiceV310.js +2 -2
- package/dist/esm/onchain/accounts/index.js +2 -2
- package/dist/esm/onchain/accounts/intents/guards.js +55 -50
- package/dist/esm/onchain/accounts/intents/index.js +23 -14
- package/dist/esm/onchain/accounts/intents/leverage-band.js +2 -2
- package/dist/esm/onchain/accounts/intents/math.js +14 -21
- package/dist/esm/onchain/accounts/intents/open-strategy.js +4 -4
- package/dist/esm/onchain/accounts/intents/plan.js +15 -29
- package/dist/esm/onchain/accounts/intents/realize.js +12 -19
- package/dist/esm/onchain/accounts/intents/tail.js +1 -1
- package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +2 -1
- package/dist/esm/onchain/accounts/intents/view.js +1 -0
- package/dist/esm/onchain/accounts/liquidations/LiquidationsService.js +1 -1
- package/dist/esm/onchain/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.js +1 -1
- package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.js +1 -1
- package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.js +1 -1
- package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.js +1 -1
- package/dist/esm/onchain/base/TokensMeta.js +3 -3
- package/dist/esm/onchain/chain/detectNetwork.js +1 -1
- package/dist/esm/onchain/constants/index.js +2 -2
- package/dist/esm/onchain/constants/math.js +11 -1
- package/dist/esm/onchain/core/createAddressProvider.js +1 -1
- package/dist/esm/onchain/index.js +7 -3
- package/dist/esm/onchain/market/adapters/contracts/AccountMigratorAdapterContract.js +1 -1
- package/dist/esm/onchain/market/adapters/contracts/ERC4626AdapterContract.js +1 -1
- package/dist/esm/onchain/market/credit/CreditFacadeV310BaseContract.js +1 -1
- package/dist/esm/onchain/market/credit/CreditManagerV310Contract.js +2 -2
- package/dist/esm/onchain/market/math.js +23 -11
- package/dist/esm/onchain/market/pool/PoolV310Contract.js +1 -1
- package/dist/esm/onchain/market/zapper/IETHZapperContract.js +1 -1
- package/dist/esm/onchain/market/zapper/ZapperContract.js +1 -1
- package/dist/esm/onchain/pools/PoolService.js +1 -1
- package/dist/esm/onchain/utils/viem/simulateWithPriceUpdates.js +1 -1
- package/dist/esm/onchain/validation/checks.js +230 -0
- package/dist/esm/onchain/validation/index.js +4 -0
- package/dist/esm/onchain/{accounts/intents → validation}/refusal.js +12 -2
- package/dist/esm/onchain/validation/token.js +27 -0
- package/dist/esm/preview/index.js +5 -1
- package/dist/esm/preview/preview/buildDelayedPreview.js +1 -0
- package/dist/esm/preview/preview/previewAdjustCreditAccount.js +1 -0
- package/dist/esm/preview/preview/previewOpenCreditAccount.js +1 -0
- package/dist/esm/preview/simulate/simulatePoolOperation.js +1 -1
- package/dist/esm/preview/trace/extractTransfers.js +1 -1
- package/dist/esm/preview/validate/checkOperation.js +171 -0
- package/dist/esm/preview/validate/checkSimulation.js +51 -0
- package/dist/esm/preview/validate/index.js +3 -0
- package/dist/esm/sdk/index.js +2 -1
- package/dist/esm/sdk/prepare/PrepareApi.js +21 -15
- package/dist/esm/sdk/prepare/index.js +2 -1
- package/dist/esm/sdk/prepare/types.js +2 -1
- package/dist/types/common-utils/index.d.ts +2 -12
- package/dist/types/common-utils/utils/index.d.ts +2 -13
- package/dist/types/common-utils/utils/strategies/index.d.ts +2 -1
- package/dist/types/common-utils/utils/strategies/strategy-info/credit-manager-issues.d.ts +34 -0
- package/dist/types/common-utils/utils/strategies/strategy-info/index.d.ts +2 -1
- package/dist/types/model/previews.d.ts +22 -0
- package/dist/types/onchain/accounts/index.d.ts +2 -2
- package/dist/types/onchain/accounts/intents/guards.d.ts +8 -4
- package/dist/types/onchain/accounts/intents/index.d.ts +20 -10
- package/dist/types/onchain/accounts/intents/leverage-band.d.ts +7 -2
- package/dist/types/onchain/accounts/intents/math.d.ts +2 -1
- package/dist/types/onchain/accounts/intents/plan.d.ts +3 -0
- package/dist/types/onchain/accounts/intents/types.d.ts +7 -1
- package/dist/types/onchain/constants/index.d.ts +2 -2
- package/dist/types/onchain/constants/math.d.ts +9 -1
- package/dist/types/onchain/index.d.ts +7 -3
- package/dist/types/onchain/market/credit/CreditManagerV310Contract.d.ts +1 -1
- package/dist/types/onchain/market/credit/types.d.ts +4 -3
- package/dist/types/onchain/market/math.d.ts +20 -9
- package/dist/types/onchain/validation/checks.d.ts +167 -0
- package/dist/types/onchain/validation/index.d.ts +4 -0
- package/dist/types/onchain/{accounts/intents → validation}/refusal.d.ts +100 -31
- package/dist/types/onchain/validation/token.d.ts +17 -0
- package/dist/types/preview/index.d.ts +5 -1
- package/dist/types/preview/validate/checkOperation.d.ts +46 -0
- package/dist/types/preview/validate/checkSimulation.d.ts +34 -0
- package/dist/types/preview/validate/index.d.ts +3 -0
- package/dist/types/sdk/index.d.ts +2 -2
- package/dist/types/sdk/prepare/PrepareApi.d.ts +3 -3
- package/dist/types/sdk/prepare/index.d.ts +2 -2
- package/dist/types/sdk/prepare/types.d.ts +8 -4
- package/package.json +1 -1
- package/dist/cjs/common-utils/utils/strategies/strategy-info/get-cm-you-can-earn.spec.js +0 -267
- package/dist/cjs/common-utils/utils/validation/index.js +0 -23
- package/dist/cjs/common-utils/utils/validation/is-zero-balance.js +0 -7
- package/dist/cjs/common-utils/utils/validation/validate-balance.js +0 -22
- package/dist/cjs/common-utils/utils/validation/validate-balance.spec.js +0 -54
- package/dist/cjs/common-utils/utils/validation/validate-balances.js +0 -17
- package/dist/cjs/common-utils/utils/validation/validate-balances.spec.js +0 -45
- package/dist/cjs/common-utils/utils/validation/validate-credit-manager.js +0 -8
- package/dist/cjs/common-utils/utils/validation/validate-credit-manager.spec.js +0 -36
- package/dist/cjs/common-utils/utils/validation/validate-hf.js +0 -10
- package/dist/cjs/common-utils/utils/validation/validate-hf.spec.js +0 -26
- package/dist/cjs/common-utils/utils/validation/validate-open-account-pool-quota-status.js +0 -14
- package/dist/cjs/common-utils/utils/validation/validate-open-account-pool-quota-status.spec.js +0 -29
- package/dist/cjs/common-utils/utils/validation/validate-open-account-pool-status.js +0 -37
- package/dist/cjs/common-utils/utils/validation/validate-open-account-pool-status.spec.js +0 -98
- package/dist/cjs/common-utils/utils/validation/validate-open-account.js +0 -18
- package/dist/cjs/common-utils/utils/validation/validate-open-account.spec.js +0 -56
- package/dist/cjs/common-utils/utils/validation/validate-quota.js +0 -23
- package/dist/cjs/common-utils/utils/validation/validate-quota.spec.js +0 -88
- package/dist/cjs/common-utils/utils/validation/validate-token-to-obtain.js +0 -18
- package/dist/cjs/common-utils/utils/validation/validate-token-to-obtain.spec.js +0 -36
- package/dist/cjs/common-utils/utils/validation/validation-types.js +0 -1
- package/dist/esm/common-utils/utils/strategies/strategy-info/get-cm-you-can-earn.spec.js +0 -264
- package/dist/esm/common-utils/utils/validation/index.js +0 -12
- package/dist/esm/common-utils/utils/validation/is-zero-balance.js +0 -6
- package/dist/esm/common-utils/utils/validation/validate-balance.js +0 -21
- package/dist/esm/common-utils/utils/validation/validate-balance.spec.js +0 -54
- package/dist/esm/common-utils/utils/validation/validate-balances.js +0 -16
- package/dist/esm/common-utils/utils/validation/validate-balances.spec.js +0 -45
- package/dist/esm/common-utils/utils/validation/validate-credit-manager.js +0 -7
- package/dist/esm/common-utils/utils/validation/validate-credit-manager.spec.js +0 -36
- package/dist/esm/common-utils/utils/validation/validate-hf.js +0 -8
- package/dist/esm/common-utils/utils/validation/validate-hf.spec.js +0 -26
- package/dist/esm/common-utils/utils/validation/validate-open-account-pool-quota-status.js +0 -13
- package/dist/esm/common-utils/utils/validation/validate-open-account-pool-quota-status.spec.js +0 -29
- package/dist/esm/common-utils/utils/validation/validate-open-account-pool-status.js +0 -36
- package/dist/esm/common-utils/utils/validation/validate-open-account-pool-status.spec.js +0 -98
- package/dist/esm/common-utils/utils/validation/validate-open-account.js +0 -17
- package/dist/esm/common-utils/utils/validation/validate-open-account.spec.js +0 -56
- package/dist/esm/common-utils/utils/validation/validate-quota.js +0 -22
- package/dist/esm/common-utils/utils/validation/validate-quota.spec.js +0 -88
- package/dist/esm/common-utils/utils/validation/validate-token-to-obtain.js +0 -17
- package/dist/esm/common-utils/utils/validation/validate-token-to-obtain.spec.js +0 -36
- package/dist/esm/common-utils/utils/validation/validation-types.js +0 -1
- package/dist/types/common-utils/utils/strategies/strategy-info/get-cm-you-can-earn.spec.d.ts +0 -1
- package/dist/types/common-utils/utils/validation/index.d.ts +0 -12
- package/dist/types/common-utils/utils/validation/is-zero-balance.d.ts +0 -4
- package/dist/types/common-utils/utils/validation/validate-balance.d.ts +0 -25
- package/dist/types/common-utils/utils/validation/validate-balance.spec.d.ts +0 -1
- package/dist/types/common-utils/utils/validation/validate-balances.d.ts +0 -13
- package/dist/types/common-utils/utils/validation/validate-balances.spec.d.ts +0 -1
- package/dist/types/common-utils/utils/validation/validate-credit-manager.d.ts +0 -13
- package/dist/types/common-utils/utils/validation/validate-credit-manager.spec.d.ts +0 -1
- package/dist/types/common-utils/utils/validation/validate-hf.d.ts +0 -12
- package/dist/types/common-utils/utils/validation/validate-hf.spec.d.ts +0 -1
- package/dist/types/common-utils/utils/validation/validate-open-account-pool-quota-status.d.ts +0 -10
- package/dist/types/common-utils/utils/validation/validate-open-account-pool-quota-status.spec.d.ts +0 -1
- package/dist/types/common-utils/utils/validation/validate-open-account-pool-status.d.ts +0 -26
- package/dist/types/common-utils/utils/validation/validate-open-account-pool-status.spec.d.ts +0 -1
- package/dist/types/common-utils/utils/validation/validate-open-account.d.ts +0 -25
- package/dist/types/common-utils/utils/validation/validate-open-account.spec.d.ts +0 -1
- package/dist/types/common-utils/utils/validation/validate-quota.d.ts +0 -24
- package/dist/types/common-utils/utils/validation/validate-quota.spec.d.ts +0 -1
- package/dist/types/common-utils/utils/validation/validate-token-to-obtain.d.ts +0 -17
- package/dist/types/common-utils/utils/validation/validate-token-to-obtain.spec.d.ts +0 -1
- package/dist/types/common-utils/utils/validation/validation-types.d.ts +0 -10
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { MAX_UINT256, PERCENTAGE_FACTOR } from "../../constants/math.js";
|
|
2
2
|
import "../../constants/index.js";
|
|
3
|
-
import { IntentPreviewError } from "
|
|
3
|
+
import { IntentPreviewError } from "../../validation/refusal.js";
|
|
4
|
+
import { toToken, toTokenAmount } from "../../validation/token.js";
|
|
4
5
|
import { eq } from "./utils/common.js";
|
|
5
6
|
import { assertDebtInBand, assertLeverageAtLeastOne, debtForLeverage, proportionalDebt } from "./math.js";
|
|
6
7
|
//#region src/onchain/accounts/intents/plan.ts
|
|
@@ -24,14 +25,8 @@ function planAdjustLeverage(intent, view) {
|
|
|
24
25
|
if (delta > 0n) return [borrow(delta), convert(U, T, delta)];
|
|
25
26
|
const shortfall = -delta - view.balanceOf(U);
|
|
26
27
|
if (shortfall > 0n && eq(T, U)) throw new IntentPreviewError("insufficientSourceBalance", {
|
|
27
|
-
required:
|
|
28
|
-
|
|
29
|
-
balance: -delta
|
|
30
|
-
},
|
|
31
|
-
held: {
|
|
32
|
-
token: U,
|
|
33
|
-
balance: view.balanceOf(U)
|
|
34
|
-
}
|
|
28
|
+
required: toTokenAmount(view.sdk, U, -delta),
|
|
29
|
+
held: toTokenAmount(view.sdk, U, view.balanceOf(U))
|
|
35
30
|
}, `adjustLeverage: needs ${-delta} underlying, account holds ${view.balanceOf(U)}`);
|
|
36
31
|
return [...shortfall > 0n ? [convert(T, U, view.price(U, T, shortfall))] : [], repay(-delta)];
|
|
37
32
|
}
|
|
@@ -39,11 +34,11 @@ function planAdjustLeverage(intent, view) {
|
|
|
39
34
|
function planDeposit(intent, view) {
|
|
40
35
|
assertPositive(intent.amount, "deposit");
|
|
41
36
|
const U = view.underlying;
|
|
42
|
-
if (!eq(intent.token, U) && !(view.rwaAsset && eq(intent.token, view.rwaAsset))) throw new IntentPreviewError("unsupportedCollateralToken", { token: intent.token }, `deposit: only ${U}${view.rwaAsset ? ` or ${view.rwaAsset}` : ""} can be deposited, got ${intent.token}`);
|
|
37
|
+
if (!eq(intent.token, U) && !(view.rwaAsset && eq(intent.token, view.rwaAsset))) throw new IntentPreviewError("unsupportedCollateralToken", { token: toToken(view.sdk, intent.token) }, `deposit: only ${U}${view.rwaAsset ? ` or ${view.rwaAsset}` : ""} can be deposited, got ${intent.token}`);
|
|
43
38
|
const aU = view.price(intent.token, U, intent.amount);
|
|
44
39
|
const debtDelta = intent.targetLeverage === void 0 ? proportionalDebt(view, aU) : debtForLeverage(view.collateral + aU, intent.targetLeverage) - view.debt;
|
|
45
40
|
if (debtDelta < 0n) throw new IntentPreviewError("leverageOutOfRange", void 0, `deposit: target leverage ${intent.targetLeverage} would require repaying debt`);
|
|
46
|
-
assertDebtInBand(view.debt + debtDelta, view.band, U);
|
|
41
|
+
assertDebtInBand(view.sdk, view.debt + debtDelta, view.band, U);
|
|
47
42
|
const T = intent.positionToken ?? positionToken(view, "deposit");
|
|
48
43
|
const depositStays = eq(intent.token, T);
|
|
49
44
|
return [
|
|
@@ -70,24 +65,15 @@ function planRepay(intent, view) {
|
|
|
70
65
|
assertPositive(intent.amount, "repay");
|
|
71
66
|
const U = view.underlying;
|
|
72
67
|
const fundsInU = eq(intent.token, U);
|
|
73
|
-
if (!fundsInU && !(view.rwaAsset && eq(intent.token, view.rwaAsset))) throw new IntentPreviewError("unsupportedCollateralToken", { token: intent.token }, `repay: only ${U}${view.rwaAsset ? ` or ${view.rwaAsset}` : ""} can be repaid with, got ${intent.token}`);
|
|
68
|
+
if (!fundsInU && !(view.rwaAsset && eq(intent.token, view.rwaAsset))) throw new IntentPreviewError("unsupportedCollateralToken", { token: toToken(view.sdk, intent.token) }, `repay: only ${U}${view.rwaAsset ? ` or ${view.rwaAsset}` : ""} can be repaid with, got ${intent.token}`);
|
|
74
69
|
if (view.debt <= 0n) throw new IntentPreviewError("debtOutOfRange", {
|
|
75
|
-
requested:
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
},
|
|
79
|
-
minDebt: {
|
|
80
|
-
token: U,
|
|
81
|
-
balance: view.band.minDebt
|
|
82
|
-
},
|
|
83
|
-
maxDebt: {
|
|
84
|
-
token: U,
|
|
85
|
-
balance: view.band.maxDebt
|
|
86
|
-
}
|
|
70
|
+
requested: toTokenAmount(view.sdk, U, view.debt),
|
|
71
|
+
minDebt: toTokenAmount(view.sdk, U, view.band.minDebt),
|
|
72
|
+
maxDebt: toTokenAmount(view.sdk, U, view.band.maxDebt)
|
|
87
73
|
}, "repay: the account owes nothing");
|
|
88
74
|
const funding = everything(intent.amount) ? view.price(U, intent.token, withMargin(view.debt)) : intent.amount;
|
|
89
75
|
const repaid = min(view.price(intent.token, U, funding), view.debt);
|
|
90
|
-
assertDebtInBand(view.debt - repaid, view.band,
|
|
76
|
+
assertDebtInBand(view.sdk, view.debt - repaid, view.band, view.underlying);
|
|
91
77
|
return [
|
|
92
78
|
add(intent.token, funding, intent.value),
|
|
93
79
|
...fundsInU ? [] : [convert(intent.token, U, funding)],
|
|
@@ -155,7 +141,7 @@ function planWithdrawDelayed(intent, view) {
|
|
|
155
141
|
}
|
|
156
142
|
}];
|
|
157
143
|
}
|
|
158
|
-
if (!eq(T, U) && !(view.rwaAsset && eq(T, view.rwaAsset))) throw new IntentPreviewError("noDelayedRoute", { token: T }, `withdraw: a delayed route cannot pay out in ${T}`);
|
|
144
|
+
if (!eq(T, U) && !(view.rwaAsset && eq(T, view.rwaAsset))) throw new IntentPreviewError("noDelayedRoute", { token: toToken(view.sdk, T) }, `withdraw: a delayed route cannot pay out in ${T}`);
|
|
159
145
|
const payoutIsSource = eq(T, S);
|
|
160
146
|
return [{
|
|
161
147
|
kind: "request",
|
|
@@ -211,7 +197,7 @@ function planFinishWithdraw(intent, claimable, claimed, view) {
|
|
|
211
197
|
const U = view.underlying;
|
|
212
198
|
const T = intent.withdrawToken;
|
|
213
199
|
const W = intent.withdrawAmount;
|
|
214
|
-
if (!eq(T, U) && !(view.rwaAsset && eq(T, view.rwaAsset))) throw new IntentPreviewError("noDelayedRoute", { token: T }, `finishWithdraw: cannot pay out in ${T}`);
|
|
200
|
+
if (!eq(T, U) && !(view.rwaAsset && eq(T, view.rwaAsset))) throw new IntentPreviewError("noDelayedRoute", { token: toToken(view.sdk, T) }, `finishWithdraw: cannot pay out in ${T}`);
|
|
215
201
|
if (intent.debtRepaid === 0n) return [
|
|
216
202
|
claim(claimable),
|
|
217
203
|
convert(claimed.token, T, claimed.amount),
|
|
@@ -316,7 +302,7 @@ function withdrawShape(intent, view) {
|
|
|
316
302
|
};
|
|
317
303
|
}
|
|
318
304
|
const dD = proportionalDebt(view, WU);
|
|
319
|
-
assertDebtInBand(view.debt - dD, view.band,
|
|
305
|
+
assertDebtInBand(view.sdk, view.debt - dD, view.band, view.underlying);
|
|
320
306
|
return {
|
|
321
307
|
U,
|
|
322
308
|
T,
|
|
@@ -335,7 +321,7 @@ function leverageShape(intent, view) {
|
|
|
335
321
|
assertLeverageAtLeastOne(intent.targetLeverage);
|
|
336
322
|
if (view.collateral <= 0n) throw new IntentPreviewError("insufficientSourceBalance", void 0, "adjustLeverage: account has no collateral to lever");
|
|
337
323
|
const target = debtForLeverage(view.collateral, intent.targetLeverage);
|
|
338
|
-
assertDebtInBand(target, view.band, view.underlying);
|
|
324
|
+
assertDebtInBand(view.sdk, target, view.band, view.underlying);
|
|
339
325
|
return {
|
|
340
326
|
U: view.underlying,
|
|
341
327
|
delta: target - view.debt
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { calcPositionLeverage } from "../../market/math.js";
|
|
2
|
-
import { IntentPreviewError } from "
|
|
2
|
+
import { IntentPreviewError } from "../../validation/refusal.js";
|
|
3
|
+
import { toToken, toTokenAmount } from "../../validation/token.js";
|
|
3
4
|
import { eq, toTargetDecimals } from "./utils/common.js";
|
|
4
5
|
import { convertAmount } from "./utils/convert-amount.js";
|
|
5
6
|
import { isRedemptionPhantomToken } from "./utils/pick-token.js";
|
|
@@ -63,14 +64,8 @@ async function realize(steps, props) {
|
|
|
63
64
|
const assertHolds = (token, amount, what) => {
|
|
64
65
|
const held = ledger.balanceOf(token);
|
|
65
66
|
if (amount <= 0n || held < amount) throw new IntentPreviewError("insufficientSourceBalance", {
|
|
66
|
-
required:
|
|
67
|
-
|
|
68
|
-
balance: amount
|
|
69
|
-
},
|
|
70
|
-
held: {
|
|
71
|
-
token,
|
|
72
|
-
balance: held
|
|
73
|
-
}
|
|
67
|
+
required: toTokenAmount(sdk, token, amount),
|
|
68
|
+
held: toTokenAmount(sdk, token, held)
|
|
74
69
|
}, `${what}: needs ${amount} of ${token}, account holds ${held}`);
|
|
75
70
|
};
|
|
76
71
|
for (const step of steps) switch (step.kind) {
|
|
@@ -84,7 +79,7 @@ async function realize(steps, props) {
|
|
|
84
79
|
}));
|
|
85
80
|
break;
|
|
86
81
|
case "borrow":
|
|
87
|
-
assertCanBorrow(suite, step.amount);
|
|
82
|
+
assertCanBorrow(sdk, suite, step.amount);
|
|
88
83
|
push(buildIncreaseDebtOperation({
|
|
89
84
|
amount: step.amount,
|
|
90
85
|
creditAccount,
|
|
@@ -156,7 +151,7 @@ async function realize(steps, props) {
|
|
|
156
151
|
case "closeAll": {
|
|
157
152
|
const balances = ledger.snapshot().assets.filter((a) => !eq(a.token, underlying) && a.balance > DUST);
|
|
158
153
|
const pending = balances.find((a) => isRedemptionPhantomToken(sdk, a.token));
|
|
159
|
-
if (pending) throw new IntentPreviewError("withdrawalInProgress", { inFlight: pending }, `closeAll: ${pending.token} is a pending withdrawal, claim it first`);
|
|
154
|
+
if (pending) throw new IntentPreviewError("withdrawalInProgress", { inFlight: toTokenAmount(sdk, pending.token, pending.balance) }, `closeAll: ${pending.token} is a pending withdrawal, claim it first`);
|
|
160
155
|
if (balances.length > 0) {
|
|
161
156
|
const leg = await paths.closeAll({ balances });
|
|
162
157
|
if (leg.probe) probes.push(leg.probe);
|
|
@@ -185,10 +180,7 @@ async function realize(steps, props) {
|
|
|
185
180
|
}
|
|
186
181
|
case "request": {
|
|
187
182
|
const asset = await delayedConfig(sdk, creditAccount, step.token);
|
|
188
|
-
if (ledger.balanceOf(asset.withdrawalPhantomToken) > 0n) throw new IntentPreviewError("withdrawalInProgress", { inFlight: {
|
|
189
|
-
token: asset.withdrawalPhantomToken,
|
|
190
|
-
balance: ledger.balanceOf(asset.withdrawalPhantomToken)
|
|
191
|
-
} }, `request: ${asset.withdrawalPhantomToken} already holds a pending withdrawal`);
|
|
183
|
+
if (ledger.balanceOf(asset.withdrawalPhantomToken) > 0n) throw new IntentPreviewError("withdrawalInProgress", { inFlight: toTokenAmount(sdk, asset.withdrawalPhantomToken, ledger.balanceOf(asset.withdrawalPhantomToken)) }, `request: ${asset.withdrawalPhantomToken} already holds a pending withdrawal`);
|
|
192
184
|
assertHolds(step.token, step.amount + step.reserve, "request");
|
|
193
185
|
const preview = await sdk.accounts.previewDelayedWithdrawal({
|
|
194
186
|
creditAccount: creditAccount.creditAccount,
|
|
@@ -265,7 +257,7 @@ async function realize(steps, props) {
|
|
|
265
257
|
convert: price
|
|
266
258
|
});
|
|
267
259
|
if (!cleared && quotas.quotaIncrease.length + quotas.quotaDecrease.length > 0) {
|
|
268
|
-
assertQuotaHeadroom(market, quotas.quotaIncrease);
|
|
260
|
+
assertQuotaHeadroom(sdk, market, quotas.quotaIncrease);
|
|
269
261
|
push(buildQuotaUpdateOperation({
|
|
270
262
|
update: quotas,
|
|
271
263
|
creditAccount,
|
|
@@ -283,6 +275,7 @@ async function realize(steps, props) {
|
|
|
283
275
|
const projectedPool = { availableLiquidityChange: creditAccount.accountDebt - debt };
|
|
284
276
|
const metrics = {
|
|
285
277
|
healthFactor: sdk.positions.healthFactor(snapshot),
|
|
278
|
+
safeHealthFactor: paysOut ? sdk.positions.healthFactor(snapshot, { safePrices: true }) : void 0,
|
|
286
279
|
borrowRate: sdk.positions.borrowRate(snapshot, projectedPool),
|
|
287
280
|
timeToLiquidation: sdk.positions.timeToLiquidation(snapshot, projectedPool),
|
|
288
281
|
liquidationPrice: sdk.positions.liquidationPrice(snapshot)
|
|
@@ -320,11 +313,11 @@ async function realize(steps, props) {
|
|
|
320
313
|
*/
|
|
321
314
|
async function delayedConfig(sdk, creditAccount, token) {
|
|
322
315
|
const compressor = sdk.withdrawalCompressor;
|
|
323
|
-
if (!compressor) throw new IntentPreviewError("noDelayedRoute", { token }, "request: chain has no withdrawal compressor");
|
|
316
|
+
if (!compressor) throw new IntentPreviewError("noDelayedRoute", { token: toToken(sdk, token) }, "request: chain has no withdrawal compressor");
|
|
324
317
|
const assets = await compressor.findWithdrawableAssets(creditAccount.creditManager, token);
|
|
325
|
-
if (assets.length === 0) throw new IntentPreviewError("noDelayedRoute", { token }, `request: ${token} has no delayed withdrawal config`);
|
|
318
|
+
if (assets.length === 0) throw new IntentPreviewError("noDelayedRoute", { token: toToken(sdk, token) }, `request: ${token} has no delayed withdrawal config`);
|
|
326
319
|
if (assets.length > 1) throw new IntentPreviewError("multipleDelayedWithdrawals", {
|
|
327
|
-
token,
|
|
320
|
+
token: toToken(sdk, token),
|
|
328
321
|
venues: assets.length
|
|
329
322
|
}, `request: ${token} has ${assets.length} delayed withdrawal configs`);
|
|
330
323
|
return assets[0];
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { IntentPreviewError } from "
|
|
1
|
+
import { IntentPreviewError } from "../../validation/refusal.js";
|
|
2
2
|
import { createOraclePaths } from "./utils/router-path.js";
|
|
3
3
|
import { planFinishClaimOnly, planFinishCloseAccount, planFinishDecreaseLeverage, planFinishWithdraw } from "./plan.js";
|
|
4
4
|
import { instantOutput } from "./operations.js";
|
|
@@ -182,7 +182,7 @@ function buildMockSdk(args) {
|
|
|
182
182
|
liquidationThresholds,
|
|
183
183
|
collateralTokens,
|
|
184
184
|
feeInterest: args.feeInterest ?? 0,
|
|
185
|
-
maxLeverage: (collateral) => calcMaxLeverage(liquidationThresholds.get(collateral) ?? 0)
|
|
185
|
+
maxLeverage: (collateral, targetHF) => calcMaxLeverage(liquidationThresholds.get(collateral) ?? 0, targetHF)
|
|
186
186
|
},
|
|
187
187
|
creditFacade: {
|
|
188
188
|
address: args.creditFacade,
|
|
@@ -297,6 +297,7 @@ function buildMockSdk(args) {
|
|
|
297
297
|
decimals: decimalsOf(token),
|
|
298
298
|
contractType: phantoms.has(token.toLowerCase()) ? "PHANTOM_TOKEN::SECURITIZE_RD" : void 0
|
|
299
299
|
}),
|
|
300
|
+
getToken: tokenOf,
|
|
300
301
|
mustGetToken: tokenOf,
|
|
301
302
|
rwaUnderlyings: { get: (token) => {
|
|
302
303
|
const asset = args.rwaAssets?.[token.toLowerCase()];
|
|
@@ -17,6 +17,7 @@ function accountView(creditAccount, sdk) {
|
|
|
17
17
|
for (const t of creditAccount.tokens) totalValue += price(t.token, underlying, t.balance);
|
|
18
18
|
return {
|
|
19
19
|
underlying,
|
|
20
|
+
sdk,
|
|
20
21
|
rwaAsset: sdk.tokensMeta.rwaUnderlyings.get(underlying)?.asset,
|
|
21
22
|
debt: creditAccount.accountDebt,
|
|
22
23
|
collateral: totalValue - creditAccount.accountDebt,
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { iLiquidationCompressorV313Abi } from "../../../abi/ILiquidationCompressorV313.js";
|
|
1
2
|
import { AddressSet } from "../../utils/AddressSet.js";
|
|
2
3
|
import { bytes32ToString } from "../../utils/bytes32ToString.js";
|
|
3
4
|
import { ADDRESS_0X0 } from "../../constants/addresses.js";
|
|
@@ -19,7 +20,6 @@ import { SecuritizeLiquidatorContract } from "../../market/rwa/securitize/Securi
|
|
|
19
20
|
import "../../market/rwa/securitize/index.js";
|
|
20
21
|
import "../../market/index.js";
|
|
21
22
|
import { LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS } from "./constants.js";
|
|
22
|
-
import { iLiquidationCompressorV313Abi } from "../../../abi/ILiquidationCompressorV313.js";
|
|
23
23
|
//#region src/onchain/accounts/liquidations/LiquidationsService.ts
|
|
24
24
|
/**
|
|
25
25
|
* Service for discovering liquidatable credit accounts and previewing manual
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { iRedemptionLoggerV310Abi } from "../../../abi/iRedemptionLoggerV310.js";
|
|
1
2
|
import { BaseContract } from "../../base/BaseContract.js";
|
|
2
3
|
import "../../base/index.js";
|
|
3
4
|
import { decodeDelayedIntent } from "./intent-codec.js";
|
|
4
|
-
import { iRedemptionLoggerV310Abi } from "../../../abi/iRedemptionLoggerV310.js";
|
|
5
5
|
import { InvalidDelayedIntentError } from "./errors.js";
|
|
6
6
|
//#region src/onchain/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.ts
|
|
7
7
|
const abi = iRedemptionLoggerV310Abi;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { AbstractWithdrawalCompressorContract } from "./AbstractWithdrawalCompressorContract.js";
|
|
2
1
|
import { iWithdrawalCompressorV310Abi } from "../../../abi/IWithdrawalCompressorV310.js";
|
|
2
|
+
import { AbstractWithdrawalCompressorContract } from "./AbstractWithdrawalCompressorContract.js";
|
|
3
3
|
//#region src/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.ts
|
|
4
4
|
const abi = iWithdrawalCompressorV310Abi;
|
|
5
5
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { AbstractWithdrawalCompressorContract } from "./AbstractWithdrawalCompressorContract.js";
|
|
2
1
|
import { iWithdrawalCompressorV311Abi } from "../../../abi/IWithdrawalCompressorV311.js";
|
|
2
|
+
import { AbstractWithdrawalCompressorContract } from "./AbstractWithdrawalCompressorContract.js";
|
|
3
3
|
//#region src/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.ts
|
|
4
4
|
const abi = iWithdrawalCompressorV311Abi;
|
|
5
5
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { iWithdrawalCompressorV313Abi } from "../../../abi/IWithdrawalCompressorV313.js";
|
|
1
2
|
import { encodeDelayedIntent } from "./intent-codec.js";
|
|
2
3
|
import { AbstractWithdrawalCompressorContract, iCreditAccountAbi, toClaimableWithdrawal, toPendingWithdrawal, toRequestableWithdrawal } from "./AbstractWithdrawalCompressorContract.js";
|
|
3
|
-
import { iWithdrawalCompressorV313Abi } from "../../../abi/IWithdrawalCompressorV313.js";
|
|
4
4
|
import { toWithdrawalStatus } from "./types.js";
|
|
5
5
|
//#region src/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.ts
|
|
6
6
|
const abi = iWithdrawalCompressorV313Abi;
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
+
import { iExpirableAbi } from "../../abi/iExpirable.js";
|
|
2
|
+
import { iStateSerializerAbi } from "../../abi/iStateSerializer.js";
|
|
3
|
+
import { iVersionAbi } from "../../abi/iVersion.js";
|
|
1
4
|
import { AddressMap } from "../utils/AddressMap.js";
|
|
2
5
|
import { AddressSet } from "../utils/AddressSet.js";
|
|
3
6
|
import { bytes32ToString } from "../utils/bytes32ToString.js";
|
|
4
7
|
import { getAssetType } from "../chain/chains.js";
|
|
5
8
|
import { formatBN } from "../utils/formatter.js";
|
|
6
9
|
import "../utils/index.js";
|
|
7
|
-
import { iExpirableAbi } from "../../abi/iExpirable.js";
|
|
8
|
-
import { iStateSerializerAbi } from "../../abi/iStateSerializer.js";
|
|
9
|
-
import { iVersionAbi } from "../../abi/iVersion.js";
|
|
10
10
|
import { SdkRWADataNotLoadedError } from "../core/errors.js";
|
|
11
11
|
import { executeMulticallBatches } from "../utils/viem/executeMulticallBatches.js";
|
|
12
12
|
//#region src/onchain/base/TokensMeta.ts
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_RWA_COMPRESSOR, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, NO_VERSION } from "./address-provider.js";
|
|
2
2
|
import { ADDRESS_0X0, MULTICALL_ADDRESS, NATIVE_ADDRESS, NOT_DEPLOYED } from "./addresses.js";
|
|
3
3
|
import { BotPermissions, botPermissionsToString } from "./bot-permissions.js";
|
|
4
|
-
import { DUST_THRESHOLD, LEVERAGE_DECIMALS, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PRICE_DECIMALS, PRICE_DECIMALS_POW, RAY, RAY_DECIMALS_POW, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, WAD, WAD_DECIMALS_POW, halfRAY } from "./math.js";
|
|
4
|
+
import { DUST_THRESHOLD, LEVERAGE_DECIMALS, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PRICE_DECIMALS, PRICE_DECIMALS_POW, RAY, RAY_DECIMALS_POW, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, WAD, WAD_DECIMALS_POW, halfRAY, isZeroBalance } from "./math.js";
|
|
5
5
|
import { BLOCKS_PER_WEEK_BY_NETWORK, RAMP_DURATION_BY_NETWORK } from "./networks.js";
|
|
6
6
|
import { PERIPHERY_CONTRACTS } from "./periphery.js";
|
|
7
7
|
import { VERSION_RANGE_310, isV310, isVersionRange } from "./versions.js";
|
|
8
|
-
export { ADDRESS_0X0, ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_RWA_COMPRESSOR, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, BLOCKS_PER_WEEK_BY_NETWORK, BotPermissions, DUST_THRESHOLD, LEVERAGE_DECIMALS, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, MULTICALL_ADDRESS, NATIVE_ADDRESS, NOT_DEPLOYED, NO_VERSION, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PERIPHERY_CONTRACTS, PRICE_DECIMALS, PRICE_DECIMALS_POW, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, VERSION_RANGE_310, WAD, WAD_DECIMALS_POW, botPermissionsToString, halfRAY, isV310, isVersionRange };
|
|
8
|
+
export { ADDRESS_0X0, ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_RWA_COMPRESSOR, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, BLOCKS_PER_WEEK_BY_NETWORK, BotPermissions, DUST_THRESHOLD, LEVERAGE_DECIMALS, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, MULTICALL_ADDRESS, NATIVE_ADDRESS, NOT_DEPLOYED, NO_VERSION, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PERIPHERY_CONTRACTS, PRICE_DECIMALS, PRICE_DECIMALS_POW, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, VERSION_RANGE_310, WAD, WAD_DECIMALS_POW, botPermissionsToString, halfRAY, isV310, isVersionRange, isZeroBalance };
|
|
@@ -20,5 +20,15 @@ const SLIPPAGE_DECIMALS = 100n;
|
|
|
20
20
|
* Token balances at or below this threshold are treated as dust and ignored.
|
|
21
21
|
**/
|
|
22
22
|
const DUST_THRESHOLD = 10n;
|
|
23
|
+
/**
|
|
24
|
+
* Whether a balance is nothing worth acting on.
|
|
25
|
+
*
|
|
26
|
+
* The threshold is a dust floor, not a zero test: rounding leaves amounts that
|
|
27
|
+
* are technically non-zero and worthless, and a form that offered to spend one
|
|
28
|
+
* would build a transaction nobody wants.
|
|
29
|
+
*/
|
|
30
|
+
function isZeroBalance(balance) {
|
|
31
|
+
return (balance ?? 0n) <= DUST_THRESHOLD;
|
|
32
|
+
}
|
|
23
33
|
//#endregion
|
|
24
|
-
export { DUST_THRESHOLD, LEVERAGE_DECIMALS, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PRICE_DECIMALS, PRICE_DECIMALS_POW, RAY, RAY_DECIMALS_POW, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, WAD, WAD_DECIMALS_POW, halfRAY };
|
|
34
|
+
export { DUST_THRESHOLD, LEVERAGE_DECIMALS, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PRICE_DECIMALS, PRICE_DECIMALS_POW, RAY, RAY_DECIMALS_POW, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, WAD, WAD_DECIMALS_POW, halfRAY, isZeroBalance };
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
+
import { iVersionAbi } from "../../abi/iVersion.js";
|
|
1
2
|
import { AP_MARKET_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR } from "../constants/address-provider.js";
|
|
2
3
|
import { isV310 } from "../constants/versions.js";
|
|
3
4
|
import "../constants/index.js";
|
|
4
5
|
import { hexEq } from "../utils/hex.js";
|
|
5
|
-
import { iVersionAbi } from "../../abi/iVersion.js";
|
|
6
6
|
import { AddressProviderV310Contract } from "./AddressProviderV310Contract.js";
|
|
7
7
|
//#region src/onchain/core/createAddressProvider.ts
|
|
8
8
|
const OVERRIDE_ADDRESSES = { Mainnet: {
|
|
@@ -14,7 +14,7 @@ import { etherscanApiUrl, etherscanUrl } from "./utils/etherscan.js";
|
|
|
14
14
|
import { ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_RWA_COMPRESSOR, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, NO_VERSION } from "./constants/address-provider.js";
|
|
15
15
|
import { ADDRESS_0X0, MULTICALL_ADDRESS, NATIVE_ADDRESS, NOT_DEPLOYED } from "./constants/addresses.js";
|
|
16
16
|
import { BotPermissions, botPermissionsToString } from "./constants/bot-permissions.js";
|
|
17
|
-
import { DUST_THRESHOLD, LEVERAGE_DECIMALS, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PRICE_DECIMALS, PRICE_DECIMALS_POW, RAY, RAY_DECIMALS_POW, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, WAD, WAD_DECIMALS_POW, halfRAY } from "./constants/math.js";
|
|
17
|
+
import { DUST_THRESHOLD, LEVERAGE_DECIMALS, MAX_INT, MAX_UINT16, MAX_UINT256, MIN_INT96, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PRICE_DECIMALS, PRICE_DECIMALS_POW, RAY, RAY_DECIMALS_POW, SECONDS_PER_YEAR, SLIPPAGE_DECIMALS, WAD, WAD_DECIMALS_POW, halfRAY, isZeroBalance } from "./constants/math.js";
|
|
18
18
|
import { TypedObjectUtils } from "./utils/mappers.js";
|
|
19
19
|
import { BLOCKS_PER_WEEK_BY_NETWORK, RAMP_DURATION_BY_NETWORK } from "./constants/networks.js";
|
|
20
20
|
import { PERIPHERY_CONTRACTS } from "./constants/periphery.js";
|
|
@@ -192,7 +192,10 @@ import "./market/index.js";
|
|
|
192
192
|
import { CreditAccountCompressorV310Contract } from "./accounts/credit-account-compressor/CreditAccountCompressorV310Contract.js";
|
|
193
193
|
import { CreditAccountCompressor } from "./accounts/credit-account-compressor/CreditAccountCompressor.js";
|
|
194
194
|
import { CreditAccountsServiceV310 } from "./accounts/CreditAccountsServiceV310.js";
|
|
195
|
-
import {
|
|
195
|
+
import { MIN_HEALTH_FACTOR_FACADE, MIN_HEALTH_FACTOR_FORM, MIN_HF_LIMITED, MIN_SAFE_HEALTH_FACTOR_FORM, amountOf, checkBorrowLimit, checkCollateralised, checkCreditManagerPaused, checkDebtInBand, checkForbiddenToken, checkFunding, checkLeverageAtLeastOne, checkMarketExpired, checkPoolPaused, checkPoolPayout, checkPoolSunset, checkPreviewError, checkQuotaCount, checkQuotaLimit, isMalformedPreviewError } from "./validation/checks.js";
|
|
196
|
+
import { IntentPreviewError, raise, refuse } from "./validation/refusal.js";
|
|
197
|
+
import { toToken, toTokenAmount } from "./validation/token.js";
|
|
198
|
+
import { borrowable } from "./accounts/intents/guards.js";
|
|
196
199
|
import { fetchCreditAccountSlice, toCreditAccountSlice } from "./accounts/intents/utils/credit-account-slice.js";
|
|
197
200
|
import { CreditAccountOperationsService } from "./accounts/intents/index.js";
|
|
198
201
|
import { LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS } from "./accounts/liquidations/constants.js";
|
|
@@ -238,4 +241,5 @@ import { OnchainSDK, STATE_VERSION } from "./OnchainSDK.js";
|
|
|
238
241
|
import { MultichainSDK } from "./MultichainSDK.js";
|
|
239
242
|
import { attachOptionsSchema, onchainSDKOptionsSchema } from "./options.js";
|
|
240
243
|
import "./types/index.js";
|
|
241
|
-
|
|
244
|
+
import "./validation/index.js";
|
|
245
|
+
export { ADDRESS_0X0, ADDRESS_PROVIDER_V310, AP_ACCOUNT_FACTORY, AP_ACL, AP_BOT_LIST, AP_BYTECODE_REPOSITORY, AP_CONTRACTS_REGISTER, AP_CONTROLLER_TIMELOCK, AP_CREDIT_ACCOUNT_COMPRESSOR, AP_CREDIT_SUITE_COMPRESSOR, AP_DATA_COMPRESSOR, AP_DELEVERAGE_BOT_HV, AP_DELEVERAGE_BOT_LV, AP_DELEVERAGE_BOT_PEGGED, AP_GAUGE_COMPRESSOR, AP_GEAR_STAKING, AP_GEAR_TOKEN, AP_INFLATION_ATTACK_BLOCKER, AP_INSOLVENCY_CHECKER, AP_MARKET_COMPRESSOR, AP_MARKET_CONFIGURATOR, AP_PARTIAL_LIQUIDATION_BOT, AP_PERIPHERY_COMPRESSOR, AP_PRICE_FEED_COMPRESSOR, AP_PRICE_FEED_STORE, AP_PRICE_ORACLE, AP_REDEMPTION_LOGGER, AP_REWARDS_COMPRESSOR, AP_ROUTER, AP_RWA_COMPRESSOR, AP_TOKEN_COMPRESSOR, AP_TREASURY, AP_WETH_GATEWAY, AP_WETH_TOKEN, AP_ZAPPER_REGISTER, AP_ZERO_PRICE_FEED, AbstractAdapterContract, AbstractLPPriceFeedContract, AbstractPriceFeedContract, AbstractWithdrawalCompressorContract, AccountBotsService, AccountMigratorAdapterContract, AdapterType, AddressMap, AddressProviderV310Contract, AddressSet, AssetsMap, BLOCKS_PER_WEEK_BY_NETWORK, BalancerStablePriceFeedContract, BalancerV3PoolStatus, BalancerV3RouterAdapterContract, BalancerV3WrapperAdapterContract, BalancerWeightedPriceFeedContract, BaseContract, BasePlugin, BigIntMath, BotPermissions, BoundedPriceFeedContract, CamelotV3AdapterContract, ChainContractsRegister, ChainNotConfiguredError, CompositePriceFeedContract, Construct, ContractParseError, ConvexV1BaseRewardPoolAdapterContract, ConvexV1BoosterAdapterContract, CreditAccountCompressor, CreditAccountCompressorV310Contract, CreditAccountOperationsService, CreditAccountsServiceV310, CreditConfiguratorV310Contract, CreditFacadeV310BaseContract, CreditFacadeV310Contract, CreditManagerV310Contract, CreditSuite, Curve2AssetsAdapterContract, Curve3AssetsAdapterContract, Curve4AssetsAdapterContract, CurveCryptoPriceFeedContract, CurveStablePriceFeedContract, CurveUSDPriceFeedContract, CurveV1AdapterStETHContract, CurveV1StableNGAdapterContract, DEFAULT_QUOTA_BUFFER_BPS, DELAYED_INTENT_TYPES, DELAYED_INTENT_VERSION, DUST_THRESHOLD, DaiUsdsAdapterContract, ERC4626AdapterContract, ERC4626ReferralAdapterContract, Erc4626PriceFeedContract, ExternalPriceFeedContract, FluidDexAdapterContract, GaugeContract, IERC20ZapperContract, IETHZapperContract, InfinifiGatewayAdapterContract, InfinifiUnwindingGatewayAdapterContract, IntentPreviewError, InvalidDelayedIntentError, KelpLRTDepositPoolAdapterContract, KelpLRTWithdrawalManagerAdapterContract, LEVERAGE_DECIMALS, LIQUIDATION_APPROVAL_BUFFER, LIQUIDATION_COMPRESSOR_V313_ADDRESS, LidoV1AdapterContract, LinearInterestRateModelContract, LiquidationsService, MAX_INT, MAX_LEVERAGE_BUFFER_BPS, MAX_UINT16, MAX_UINT256, MIN_HEALTH_FACTOR_FACADE, MIN_HEALTH_FACTOR_FORM, MIN_HF_LIMITED, MIN_INT96, MIN_SAFE_HEALTH_FACTOR_FORM, MULTICALL_ADDRESS, MarketRegister, MarketSuite, MellowClaimerAdapterContract, MellowDVVAdapterContract, MellowERC4626VaultAdapterContract, MellowLRTPriceFeedContract, MellowWrapperAdapterContract, MidasGatewayAdapterContract, MidasIssuanceVaultAdapterContract, MidasLiquidatorContract, MidasRedemptionVaultAdapterContract, MissingSerializedParamsError, MultichainConstruct, MultichainLiquidationsService, MultichainOpportunitiesService, MultichainPositionsService, MultichainSDK, NATIVE_ADDRESS, NON_STRATEGY_PHANTOM_TOKEN_TYPES, NOT_DEPLOYED, NO_VERSION, NetworkType, OnchainSDK, OpportunitiesService, PARTIAL_LIQUIDATION_BUFFER_BPS, PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR, PERCENTAGE_FACTOR_1KK, PERIPHERY_CONTRACTS, PHANTOM_TOKEN_CONTRACT_TYPES, PHANTOM_TOKEN_MIDAS_REDEMPTION, PHANTOM_TOKEN_SECURITIZE_REDEMPTION, PRICE_DECIMALS, PRICE_DECIMALS_POW, PartialPriceFeedInitError, PendlePairStatus, PendleRouterAdapterContract, PendleTWAPPTPriceFeed, PendleTokenType, PeripheryCompressorV310Contract, PluginStateVersionError, PoolService, PoolSuite, PoolV310Contract, PositionsService, PriceFeedRef, PriceFeedRegister, PriceOracleV310Contract, PythPriceFeed, RAMP_DURATION_BY_NETWORK, RAY, RAY_DECIMALS_POW, RWARegistry, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, RWA_LIQUIDATOR_MIDAS, RWA_LIQUIDATOR_SECURITIZE, RWA_ON_DEMAND_LP_MONOPOLIZED, RWA_UNDERLYING_DEFAULT, RWA_UNDERLYING_ON_DEMAND, RedemptionLoggerV310Contract, RedstonePriceFeedContract, RouterV310Contract, SDKConstruct, SECONDS_PER_YEAR, SECURITIZE_REGISTER_VAULT_TYPES, SLIPPAGE_DECIMALS, STATE_VERSION, SUPPORTED_NETWORKS, SdkAlreadyAttachedError, SdkChainMismatchError, SdkMissingChainStateError, SdkNotAttachedError, SdkRWADataNotLoadedError, SdkStateVersionMismatchError, SdkSyncFailedError, SecuritizeLiquidatorContract, SecuritizeOnRampAdapterContract, SecuritizeRWAFactory, SecuritizeRedemptionGatewayAdapterContract, SimulateWithPriceUpdatesError, SimulationError, StakingRewardsAdapterContract, TokensMeta, TraderJoePoolVersion, TraderJoeRouterAdapterContract, TypedObjectUtils, UniswapV2AdapterContract, UniswapV3AdapterContract, UniswapV4AdapterContract, UnsupportedZapperFunctionError, UpshiftVaultAdapterContract, VERSION_RANGE_310, VelodromeV2RouterAdapterContract, VotingContractStatus, WAD, WAD_DECIMALS_POW, WithdrawalCompressorV310Contract, WithdrawalCompressorV311Contract, WithdrawalCompressorV313Contract, WstETHPriceFeedContract, WstETHV1AdapterContract, YearnPriceFeedContract, ZapperContract, ZeroPriceFeedContract, ZodAddress, ZodBigInt, ZodHex, accountSnapshotFromCreditAccountData, adapterActionAbi, adapterActionSelectors, adapterActionSignatures, adapterConstructorAbi, allTransfersAsTokenAmounts, amountOf, assetsMap, attachOptionsSchema, borrowable, botPermissionsToString, bpsToRay, bytes32ToString, calcBorrowApy, calcBorrowRate, calcEffectiveBorrowApy, calcHealthFactor, calcLiquidationPrice, calcLiquidationPriceForTarget, calcMaxLeverage, calcNetStrategyApy, calcPositionLeverage, calcQuotaRate, calcTimeToLiquidationMs, calcUtilization, calcUtilizationRaw, chains, checkBorrowLimit, checkCollateralised, checkCreditManagerPaused, checkDebtInBand, checkForbiddenToken, checkFunding, checkLeverageAtLeastOne, checkMarketExpired, checkPoolPaused, checkPoolPayout, checkPoolSunset, checkPreviewError, checkQuotaCount, checkQuotaLimit, childLogger, classifyCurveOperation, createAdapter, createAddressProvider, createPriceOracle, createRawTx, createRedemptionLogger, createRouter, createWithdrawalCompressor, createZapper, abi as creditFacadeV310Abi, curveAddLiquidityFromTransfers, curveRemoveLiquidityFromTransfers, decodeDelayedIntent, detectNetwork, dominantCollateral, encodeDelayedIntent, erc4626ReferralAdapterAbi, estimateRawTxGas, etherscanApiUrl, etherscanUrl, executeDelegatedMulticalls, executeMulticallBatches, expectedBalanceDeltas, fetchCreditAccountSlice, fetchRedstonePayloads, filterDust, filterDustUSD, findCuratorMarketConfigurator, fmtBinaryMask, fnSigToName, formatBN, formatBNvalue, formatDuration, formatLeverage, formatNumberToString_, formatPercentage, formatTimestamp, functionArgsToMap, functionArgsToRecord, generateCastTraceCall, getAccountTargetCollateral, getAdapterActionAbi, getAdapterDeployParamsAbi, getAdapterType, getAssetType, getCastTraceArgs, getChain, getCuratorName, getFunctionSignature, getLegacyStrategyTarget, getNetworkType, getRawPriceUpdates, getSimulateWithPriceUpdatesError, getWithdrawalCompressorAddress, halfRAY, hasAdapterDeployParamsAbi, healthFactorBps, hexEq, hydrateAddressProvider, iBalancerV3RouterAbi, iBalancerV3RouterAdapterAbi, iBalancerV3WrapperAbi, iBalancerV3WrapperAdapterAbi, iBaseOnRampAbi, iBaseRewardPoolAbi, iBoosterAbi, iCamelotV3AdapterAbi, iCamelotV3RouterAbi, iConvexV1BaseRewardPoolAdapterAbi, iConvexV1BoosterAdapterAbi, iCreditAccountAbi, iCurvePoolAbi, iCurvePoolStableNGAbi, iCurvePool_2Abi, iCurvePool_3Abi, iCurvePool_4Abi, iCurveV1StableNgAdapterAbi, iCurveV1_2AssetsAdapterAbi, iCurveV1_3AssetsAdapterAbi, iCurveV1_4AssetsAdapterAbi, iDaiUsdsAbi, iDaiUsdsAdapterAbi, iERC4626Abi, iERC4626ReferralAbi, iFluidDexAbi, iFluidDexAdapterAbi, iInfinifiGatewayAbi, iInfinifiGatewayAdapterAbi, iInfinifiUnwindingGatewayAbi, iInfinifiUnwindingGatewayAdapterAbi, iKelpLRTDepositPoolGatewayAbi, iKelpLRTWithdrawalManagerGatewayAbi, iKelpLrtDepositPoolAdapterAbi, iKelpLrtDepositPoolGatewayAbi, iKelpLrtWithdrawalManagerAdapterAbi, iKelpLrtWithdrawalManagerGatewayAbi, iLidoV1AdapterAbi, iMellow4626VaultAdapterAbi, iMellowClaimerAbi, iMellowClaimerAdapterAbi, iMellowWrapperAbi, iMellowWrapperAdapterAbi, iMidasGatewayAdapterV311Abi, iMidasGatewayV311Abi, iMidasIssuanceVaultAdapterV310Abi, iMidasIssuanceVaultV310Abi, iMidasRedemptionVaultAdapterV310Abi, iMidasRedemptionVaultGatewayV310Abi, iPendleRouterAbi, iPendleRouterAdapterAbi, iSecuritizeOnRampAbi, iSecuritizeOnRampAdapterV310Abi, iSecuritizeRedemptionGatewayAdapterV311Abi, iSecuritizeRedemptionGatewayV311Abi, iStakingRewardsAbi, iStakingRewardsAdapterAbi, iTraderJoeRouterAbi, iTraderJoeRouterAdapterAbi, iUniswapV2AdapterAbi, iUniswapV2Router02Abi, iUniswapV3Abi, iUniswapV3AdapterAbi, iUniswapV4AdapterAbi, iUniswapV4GatewayAbi, iUpshiftVaultAdapterAbi, iUpshiftVaultGatewayAbi, iVelodromeV2RouterAbi, iVelodromeV2RouterAdapterAbi, isDust, isLPPriceFeed, isMalformedPreviewError, isPublicNetwork, isRWAFactory, isRWAToken, isStrategyCollateral, isSunsetPool, isSunsetStrategy, isSupportedNetwork, isUpdatablePriceFeed, isV310, isVersionRange, isZeroBalance, iwstETHAbi, iwstEthv1AdapterAbi, json_parse, json_stringify, lidoV1_WETHGatewayAbi, mellowDvvAdapterAbi, minSeizedAmount, numberWithCommas, onchainSDKOptionsSchema, optimalHFForPartialLiquidation, optimalRepaidAmount, parseAdapterAction, parseAdapterDeployParams, parsePosNegAmount, percentFmt, pickStrategyTargetCollateral, raise, rayToBps, rayToNumber, refuse, retry, rewardsFromTransfers, sendRawTx, shortAddress, shortHash, simulateCall, simulateMulticall, simulateWithPriceUpdates, strategyName, swapFromTransfers, toAddress, toBN, toBigInt, toChainIds, toClaimableWithdrawal, toCreditAccountSlice, toNetTransfers, toPendingWithdrawal, toRequestableWithdrawal, toShares, toSharesUp, toSignificant, toToken, toTokenAmount, toWithdrawalStatus, usdToNumber, watchBlocksAsync };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { AbstractAdapterContract } from "./AbstractAdapter.js";
|
|
2
1
|
import { accountMigratorAbi } from "../../../../abi/AccountMigrator.js";
|
|
2
|
+
import { AbstractAdapterContract } from "./AbstractAdapter.js";
|
|
3
3
|
//#region src/onchain/market/adapters/contracts/AccountMigratorAdapterContract.ts
|
|
4
4
|
const abi = accountMigratorAbi;
|
|
5
5
|
const protocolAbi = accountMigratorAbi;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { ierc4626AdapterAbi } from "../../../../abi/ierc4626Adapter.js";
|
|
1
2
|
import { MissingSerializedParamsError } from "../../../base/errors.js";
|
|
2
3
|
import "../../../base/index.js";
|
|
3
|
-
import { ierc4626AdapterAbi } from "../../../../abi/ierc4626Adapter.js";
|
|
4
4
|
import { iERC4626Abi } from "../abi/targetContractAbi.js";
|
|
5
5
|
import { fnSigToName, swapFromTransfers } from "../transferHelpers.js";
|
|
6
6
|
import { AbstractAdapterContract } from "./AbstractAdapter.js";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { iPausableAbi } from "../../../abi/iPausable.js";
|
|
1
2
|
import { iCreditFacadeMulticallV310Abi, iCreditFacadeV310Abi } from "../../../abi/310/generated.js";
|
|
2
3
|
import { BaseContract } from "../../base/BaseContract.js";
|
|
3
4
|
import "../../base/index.js";
|
|
4
|
-
import { iPausableAbi } from "../../../abi/iPausable.js";
|
|
5
5
|
//#region src/onchain/market/credit/CreditFacadeV310BaseContract.ts
|
|
6
6
|
const abi = [
|
|
7
7
|
...iCreditFacadeV310Abi,
|
|
@@ -65,8 +65,8 @@ var CreditManagerV310Contract = class extends BaseContract {
|
|
|
65
65
|
/**
|
|
66
66
|
* {@inheritDoc ICreditManagerContract.maxLeverage}
|
|
67
67
|
*/
|
|
68
|
-
maxLeverage(collateral) {
|
|
69
|
-
return calcMaxLeverage(this.liquidationThresholds.mustGet(collateral));
|
|
68
|
+
maxLeverage(collateral, targetHF) {
|
|
69
|
+
return calcMaxLeverage(this.liquidationThresholds.mustGet(collateral), targetHF);
|
|
70
70
|
}
|
|
71
71
|
/**
|
|
72
72
|
* {@inheritDoc ICreditManagerContract.liquidationPremium}
|
|
@@ -162,24 +162,36 @@ function calcNetStrategyApy(opportunity, totalCollateralApy, leverage, mode = "s
|
|
|
162
162
|
**/
|
|
163
163
|
const MAX_LEVERAGE_BUFFER_BPS = 500;
|
|
164
164
|
/**
|
|
165
|
-
* Highest total-value leverage a liquidation threshold allows, floored
|
|
166
|
-
*
|
|
167
|
-
* `liquidationThreshold × totalValue`, leaving
|
|
168
|
-
* equity per unit of exposure;
|
|
169
|
-
*
|
|
165
|
+
* Highest total-value leverage a liquidation threshold allows, floored.
|
|
166
|
+
*
|
|
167
|
+
* At HF = 1, debt is `liquidationThreshold × totalValue`, leaving
|
|
168
|
+
* `1 − liquidationThreshold` of equity per unit of exposure; a maxed position
|
|
169
|
+
* has to stay some way off that boundary. Given a `targetHF`, that distance is
|
|
170
|
+
* solved for — `HF = liquidationThreshold × L / (L − 1)` inverts to
|
|
171
|
+
* `L = targetHF / (targetHF − liquidationThreshold)`.
|
|
172
|
+
*
|
|
173
|
+
* Without one it falls back on a flat {@link MAX_LEVERAGE_BUFFER_BPS}, which
|
|
174
|
+
* under-buffers as the threshold rises — at 95% it allows 19x, or HF ≈ 1.0028.
|
|
175
|
+
* That branch is scaffolding, kept so this parameter moves no number before
|
|
176
|
+
* the callers name a target, and goes away with the constant.
|
|
177
|
+
*
|
|
178
|
+
* @param targetHF - Health factor the maxed position should leave, in basis
|
|
179
|
+
* points. Omitted keeps the legacy buffer.
|
|
170
180
|
*
|
|
171
181
|
* @example
|
|
172
182
|
* ```ts
|
|
173
183
|
* // liquidationThreshold: 9000 bps = 90%
|
|
174
|
-
* calcMaxLeverage(9000)
|
|
184
|
+
* calcMaxLeverage(9000) // floor((1 − 0.05) / (1 − 0.9)) = 9x
|
|
185
|
+
* calcMaxLeverage(9000, 10100) // floor(1.01 / (1.01 − 0.9)) = 9x
|
|
175
186
|
* ```
|
|
176
|
-
* @throws If `liquidationThreshold` is 100% or more,
|
|
177
|
-
* leverage
|
|
187
|
+
* @throws If `liquidationThreshold` is 100% or more, or reaches a named
|
|
188
|
+
* `targetHF` — either way no leverage clears the bar.
|
|
178
189
|
**/
|
|
179
|
-
function calcMaxLeverage(liquidationThreshold) {
|
|
190
|
+
function calcMaxLeverage(liquidationThreshold, targetHF) {
|
|
180
191
|
if (liquidationThreshold >= FULL) throw new Error("cannot compute max leverage: liquidation threshold is 100% or more");
|
|
181
|
-
|
|
182
|
-
|
|
192
|
+
if (targetHF === void 0) return Math.max(Math.floor((FULL - 500) / (FULL - liquidationThreshold)), 1);
|
|
193
|
+
if (liquidationThreshold >= targetHF) throw new Error("cannot compute max leverage: liquidation threshold reaches the target health factor");
|
|
194
|
+
return Math.max(Math.floor(targetHF / (targetHF - liquidationThreshold)), 1);
|
|
183
195
|
}
|
|
184
196
|
/**
|
|
185
197
|
* Converts a credit account's health factor from the 18-decimal fixed point the
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { iPausableAbi } from "../../../abi/iPausable.js";
|
|
1
2
|
import { iPoolV310Abi } from "../../../abi/310/generated.js";
|
|
2
3
|
import { AddressMap } from "../../utils/AddressMap.js";
|
|
3
4
|
import { RAY } from "../../constants/math.js";
|
|
@@ -7,7 +8,6 @@ import "../../utils/index.js";
|
|
|
7
8
|
import { SdkRWADataNotLoadedError } from "../../core/errors.js";
|
|
8
9
|
import { BaseContract } from "../../base/BaseContract.js";
|
|
9
10
|
import "../../base/index.js";
|
|
10
|
-
import { iPausableAbi } from "../../../abi/iPausable.js";
|
|
11
11
|
//#region src/onchain/market/pool/PoolV310Contract.ts
|
|
12
12
|
const abi = [...iPoolV310Abi, ...iPausableAbi];
|
|
13
13
|
var PoolV310Contract = class extends BaseContract {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { ZapperContract } from "./ZapperContract.js";
|
|
2
1
|
import { iethZapperAbi } from "../../../abi/iETHZapper.js";
|
|
2
|
+
import { ZapperContract } from "./ZapperContract.js";
|
|
3
3
|
//#region src/onchain/market/zapper/IETHZapperContract.ts
|
|
4
4
|
const abi = iethZapperAbi;
|
|
5
5
|
var IETHZapperContract = class extends ZapperContract {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { iZapperAbi } from "../../../abi/iZapper.js";
|
|
1
2
|
import { BaseContract } from "../../base/BaseContract.js";
|
|
2
3
|
import "../../base/index.js";
|
|
3
|
-
import { iZapperAbi } from "../../../abi/iZapper.js";
|
|
4
4
|
import { UnsupportedZapperFunctionError } from "./errors.js";
|
|
5
5
|
//#region src/onchain/market/zapper/ZapperContract.ts
|
|
6
6
|
/**
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { AddressSet } from "../utils/AddressSet.js";
|
|
2
1
|
import { ierc20Abi } from "../../abi/iERC20.js";
|
|
2
|
+
import { AddressSet } from "../utils/AddressSet.js";
|
|
3
3
|
import "../constants/addresses.js";
|
|
4
4
|
import { PERCENTAGE_FACTOR, RAY } from "../constants/math.js";
|
|
5
5
|
import "../constants/index.js";
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { errorAbis } from "../../../abi/errors.js";
|
|
2
|
-
import { generateCastTraceCall } from "./cast.js";
|
|
3
2
|
import { iUpdatablePriceFeedAbi } from "../../../abi/iUpdatablePriceFeed.js";
|
|
3
|
+
import { generateCastTraceCall } from "./cast.js";
|
|
4
4
|
import { simulateMulticall } from "./simulateMulticall.js";
|
|
5
5
|
import { BaseError, CallExecutionError, ContractFunctionRevertedError, decodeFunctionData, decodeFunctionResult, encodeFunctionData, parseAbi } from "viem";
|
|
6
6
|
import { getAction, parseAccount } from "viem/utils";
|