@gearbox-protocol/sdk 16.0.0-next.51 → 16.0.0-next.52
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/model/index.js +1 -0
- package/dist/cjs/model/result.js +10 -0
- package/dist/cjs/onchain/accounts/intents/leverage-band.js +1 -1
- package/dist/cjs/onchain/accounts/intents/maxWithdrawCollateral.js +8 -19
- package/dist/cjs/onchain/accounts/intents/open-strategy.js +1 -1
- package/dist/cjs/onchain/accounts/intents/realize.js +1 -1
- package/dist/cjs/onchain/accounts/intents/testing/market.js +6 -5
- package/dist/cjs/onchain/accounts/intents/testing/sdk-mock.js +21 -74
- package/dist/cjs/onchain/accounts/intents/utils/pick-token.js +1 -1
- package/dist/cjs/onchain/accounts/intents/utils/price-impact.js +2 -2
- package/dist/cjs/onchain/accounts/intents/utils/router-path.js +1 -1
- package/dist/cjs/onchain/accounts/intents/view.js +1 -1
- package/dist/cjs/onchain/accounts/liquidations/LiquidationsService.js +3 -3
- package/dist/cjs/onchain/index.js +1 -1
- package/dist/cjs/onchain/market/MarketSuite.js +0 -28
- package/dist/cjs/onchain/market/credit/collateralUtils.js +2 -2
- package/dist/cjs/onchain/market/index.js +1 -1
- package/dist/cjs/onchain/market/oracle/PriceOracleBaseContract.js +66 -13
- package/dist/cjs/onchain/market/oracle/TestPriceOracle.mock.js +215 -0
- package/dist/cjs/onchain/market/oracle/index.js +1 -1
- package/dist/cjs/onchain/positions/PositionsService.js +5 -7
- package/dist/cjs/onchain/positions/calcHealthFactor.js +4 -3
- package/dist/cjs/onchain/router/AbstractRouterContract.js +2 -24
- package/dist/cjs/onchain/router/RouterV310Contract.js +1 -12
- package/dist/cjs/preview/preview/buildDelayedStrategyPositionOperationPreview.js +26 -38
- package/dist/cjs/preview/preview/previewAdjustStrategyPosition.js +2 -3
- package/dist/cjs/preview/preview/previewExitOrRepayStrategyPosition.js +4 -5
- package/dist/cjs/preview/preview/previewOpenStrategyPosition.js +3 -7
- package/dist/cjs/preview/preview/previewOperation.js +1 -2
- package/dist/esm/model/index.js +2 -2
- package/dist/esm/model/result.js +10 -1
- package/dist/esm/onchain/accounts/intents/leverage-band.js +1 -1
- package/dist/esm/onchain/accounts/intents/maxWithdrawCollateral.js +8 -19
- package/dist/esm/onchain/accounts/intents/open-strategy.js +1 -1
- package/dist/esm/onchain/accounts/intents/realize.js +1 -1
- package/dist/esm/onchain/accounts/intents/testing/market.js +6 -5
- package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +22 -75
- package/dist/esm/onchain/accounts/intents/utils/pick-token.js +1 -1
- package/dist/esm/onchain/accounts/intents/utils/price-impact.js +2 -2
- package/dist/esm/onchain/accounts/intents/utils/router-path.js +1 -1
- package/dist/esm/onchain/accounts/intents/view.js +1 -1
- package/dist/esm/onchain/accounts/liquidations/LiquidationsService.js +3 -3
- package/dist/esm/onchain/index.js +1 -1
- package/dist/esm/onchain/market/MarketSuite.js +0 -28
- package/dist/esm/onchain/market/credit/collateralUtils.js +2 -2
- package/dist/esm/onchain/market/index.js +1 -1
- package/dist/esm/onchain/market/oracle/PriceOracleBaseContract.js +66 -13
- package/dist/esm/onchain/market/oracle/TestPriceOracle.mock.js +213 -0
- package/dist/esm/onchain/market/oracle/index.js +1 -1
- package/dist/esm/onchain/positions/PositionsService.js +5 -7
- package/dist/esm/onchain/positions/calcHealthFactor.js +4 -3
- package/dist/esm/onchain/router/AbstractRouterContract.js +2 -24
- package/dist/esm/onchain/router/RouterV310Contract.js +1 -12
- package/dist/esm/preview/preview/buildDelayedStrategyPositionOperationPreview.js +26 -38
- package/dist/esm/preview/preview/previewAdjustStrategyPosition.js +2 -3
- package/dist/esm/preview/preview/previewExitOrRepayStrategyPosition.js +4 -5
- package/dist/esm/preview/preview/previewOpenStrategyPosition.js +3 -7
- package/dist/esm/preview/preview/previewOperation.js +1 -2
- package/dist/types/model/index.d.ts +2 -2
- package/dist/types/model/previews.d.ts +4 -3
- package/dist/types/model/result.d.ts +16 -1
- package/dist/types/onchain/accounts/intents/maxWithdrawCollateral.d.ts +5 -3
- package/dist/types/onchain/accounts/intents/testing/market.d.ts +5 -1
- package/dist/types/onchain/accounts/intents/testing/sdk-mock.d.ts +1 -2
- package/dist/types/onchain/index.d.ts +2 -2
- package/dist/types/onchain/market/MarketSuite.d.ts +2 -29
- package/dist/types/onchain/market/index.d.ts +2 -2
- package/dist/types/onchain/market/oracle/PriceOracleBaseContract.d.ts +15 -5
- package/dist/types/onchain/market/oracle/types.d.ts +40 -28
- package/dist/types/onchain/positions/calcHealthFactor.d.ts +7 -3
- package/dist/types/onchain/router/AbstractRouterContract.d.ts +0 -4
- package/dist/types/preview/preview/buildDelayedStrategyPositionOperationPreview.d.ts +4 -6
- package/package.json +2 -10
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { iPriceOracleV310Abi } from "../../../abi/310/generated.js";
|
|
2
|
+
import { getChain } from "../../chain/chains.js";
|
|
3
|
+
import "../../chain/index.js";
|
|
4
|
+
import "../../constants/address-provider.js";
|
|
5
|
+
import "../../constants/math.js";
|
|
6
|
+
import "../../constants/index.js";
|
|
7
|
+
import { toBN } from "../../utils/formatter.js";
|
|
8
|
+
import "../../utils/index.js";
|
|
9
|
+
import { ChainContractsRegister } from "../../base/ChainContractsRegister.js";
|
|
10
|
+
import "../../base/index.js";
|
|
11
|
+
import { PriceFeedRef } from "../pricefeeds/PriceFeedRef.js";
|
|
12
|
+
import "../pricefeeds/index.js";
|
|
13
|
+
import { PriceOracleBaseContract } from "./PriceOracleBaseContract.js";
|
|
14
|
+
import { bytesToHex, createPublicClient, custom, getAddress, hexToBytes } from "viem";
|
|
15
|
+
//#region src/onchain/market/oracle/TestPriceOracle.mock.ts
|
|
16
|
+
/**
|
|
17
|
+
* Well-known mainnet tokens for tests. The oracle prefills their metadata;
|
|
18
|
+
* a seed can then be as small as `{ price: 2000 }`.
|
|
19
|
+
**/
|
|
20
|
+
const MockTokens = {
|
|
21
|
+
WETH: getAddress("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),
|
|
22
|
+
USDC: getAddress("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"),
|
|
23
|
+
DAI: getAddress("0x6B175474E89094C44Da98b954EedeAC495271d0F"),
|
|
24
|
+
cbETH: getAddress("0xBe9895146f7AF43049ca1c1AE358B0541Ea49704"),
|
|
25
|
+
dcUSDC: getAddress("0x50A9C808cd114E8fEA72f03aE2B1A8825677D56D"),
|
|
26
|
+
ACRED: getAddress("0x17418038ecF73BA4026c4f428547BF099706F27B"),
|
|
27
|
+
srpACRED_USDC: getAddress("0xe4a38b653B2580C9D72a50F190Ddd6E2d2D2a412")
|
|
28
|
+
};
|
|
29
|
+
const MOCK_TOKEN_META = {
|
|
30
|
+
[MockTokens.WETH]: {
|
|
31
|
+
decimals: 18,
|
|
32
|
+
symbol: "WETH",
|
|
33
|
+
name: "Wrapped Ether"
|
|
34
|
+
},
|
|
35
|
+
[MockTokens.USDC]: {
|
|
36
|
+
decimals: 6,
|
|
37
|
+
symbol: "USDC",
|
|
38
|
+
name: "USD Coin"
|
|
39
|
+
},
|
|
40
|
+
[MockTokens.DAI]: {
|
|
41
|
+
decimals: 18,
|
|
42
|
+
symbol: "DAI",
|
|
43
|
+
name: "Dai Stablecoin"
|
|
44
|
+
},
|
|
45
|
+
[MockTokens.cbETH]: {
|
|
46
|
+
decimals: 18,
|
|
47
|
+
symbol: "cbETH",
|
|
48
|
+
name: "Coinbase Wrapped Staked ETH"
|
|
49
|
+
},
|
|
50
|
+
[MockTokens.dcUSDC]: {
|
|
51
|
+
decimals: 6,
|
|
52
|
+
symbol: "dcUSDC",
|
|
53
|
+
name: "Default compliant USD Coin"
|
|
54
|
+
},
|
|
55
|
+
[MockTokens.ACRED]: {
|
|
56
|
+
decimals: 6,
|
|
57
|
+
symbol: "ACRED",
|
|
58
|
+
name: "Apollo Diversified Credit Securitize Fund"
|
|
59
|
+
},
|
|
60
|
+
[MockTokens.srpACRED_USDC]: {
|
|
61
|
+
decimals: 6,
|
|
62
|
+
symbol: "srpACRED_USDC",
|
|
63
|
+
name: "Securitize pending redemption Apollo Diversified Credit Securitize Fund to USD Coin"
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
const TEST_ORACLE_ADDRESS = getAddress("0x040ac1e000000000000000000000000000000310");
|
|
67
|
+
const FAILED_ANSWER = {
|
|
68
|
+
price: 0n,
|
|
69
|
+
success: false,
|
|
70
|
+
updatedAt: 0n
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* Register whose client rejects any RPC request: the oracle never talks to a
|
|
74
|
+
* node. `addressProvider.getAddress` answers `AP_WETH_TOKEN` with mainnet WETH
|
|
75
|
+
* so `#priceableToken` and `safeConvertMinUSD` exercise their real native
|
|
76
|
+
* branches.
|
|
77
|
+
**/
|
|
78
|
+
var TestOracleSdk = class extends ChainContractsRegister {
|
|
79
|
+
addressProvider = { getAddress: (contract, version) => {
|
|
80
|
+
if (contract === "WETH_TOKEN") return MockTokens.WETH;
|
|
81
|
+
throw new Error(`Address ${contract}, version: ${version} not found`);
|
|
82
|
+
} };
|
|
83
|
+
priceFeeds = { generatePriceFeedsUpdateTxs: () => {
|
|
84
|
+
throw new Error("TestPriceOracle: no priceFeeds");
|
|
85
|
+
} };
|
|
86
|
+
};
|
|
87
|
+
/**
|
|
88
|
+
* A real {@link PriceOracleBaseContract} seeded from plain records, for tests.
|
|
89
|
+
*
|
|
90
|
+
* Conversion, safe-price fallback, and native-through-WETH all run the
|
|
91
|
+
* production code. Feed-tree methods (`priceFeedData`, `priceUpdatesFor*`, …)
|
|
92
|
+
* are not wired and throw if touched.
|
|
93
|
+
**/
|
|
94
|
+
var TestPriceOracle = class extends PriceOracleBaseContract {
|
|
95
|
+
constructor(tokens = {}) {
|
|
96
|
+
const register = new TestOracleSdk(createPublicClient({
|
|
97
|
+
chain: getChain("Mainnet"),
|
|
98
|
+
transport: custom({ request: async () => {
|
|
99
|
+
throw new Error("not implemented");
|
|
100
|
+
} })
|
|
101
|
+
}));
|
|
102
|
+
super(register, {
|
|
103
|
+
abi: iPriceOracleV310Abi,
|
|
104
|
+
addr: TEST_ORACLE_ADDRESS,
|
|
105
|
+
name: "TestPriceOracle"
|
|
106
|
+
}, {
|
|
107
|
+
priceFeedMap: [],
|
|
108
|
+
priceFeedTree: []
|
|
109
|
+
});
|
|
110
|
+
for (const [token, meta] of Object.entries(MOCK_TOKEN_META)) {
|
|
111
|
+
const addr = getAddress(token);
|
|
112
|
+
this.register.tokensMeta.upsert(addr, {
|
|
113
|
+
addr,
|
|
114
|
+
...meta
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
for (const [token, cfg] of Object.entries(tokens)) this.addToken(token, cfg);
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Registers token meta and optional feed answers. Chainable, like all
|
|
121
|
+
* modifiers.
|
|
122
|
+
**/
|
|
123
|
+
addToken(token, cfg) {
|
|
124
|
+
const addr = getAddress(token);
|
|
125
|
+
const known = MOCK_TOKEN_META[addr];
|
|
126
|
+
const symbol = cfg.symbol ?? known?.symbol ?? `T_${addr.slice(2, 8)}`;
|
|
127
|
+
this.register.tokensMeta.upsert(addr, {
|
|
128
|
+
addr,
|
|
129
|
+
symbol,
|
|
130
|
+
name: cfg.name ?? known?.name ?? symbol,
|
|
131
|
+
decimals: cfg.decimals ?? known?.decimals ?? 18
|
|
132
|
+
});
|
|
133
|
+
if (cfg.price !== void 0) this.setMainPrice(addr, cfg.price);
|
|
134
|
+
if (cfg.reservePrice !== void 0) this.setReservePrice(addr, cfg.reservePrice);
|
|
135
|
+
return this;
|
|
136
|
+
}
|
|
137
|
+
setMainPrice(token, price) {
|
|
138
|
+
this.#setAnswer(token, "main", rawPrice(price));
|
|
139
|
+
return this;
|
|
140
|
+
}
|
|
141
|
+
setReservePrice(token, price) {
|
|
142
|
+
this.#setAnswer(token, "reserve", rawPrice(price));
|
|
143
|
+
return this;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Feed stays configured, its answer failed — {@link PriceFeedAnswerMap.price}
|
|
147
|
+
* throws. Distinct from {@link removeMainFeed}.
|
|
148
|
+
**/
|
|
149
|
+
failMainAnswer(token) {
|
|
150
|
+
this.#failAnswer(token, "main");
|
|
151
|
+
return this;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Feed stays configured, its answer failed. Distinct from
|
|
155
|
+
* {@link removeReserveFeed}: `safeConvertMinUSD` treats a present-but-failed
|
|
156
|
+
* reserve feed as an error, and a missing one as an untrusted 0.
|
|
157
|
+
**/
|
|
158
|
+
failReserveAnswer(token) {
|
|
159
|
+
this.#failAnswer(token, "reserve");
|
|
160
|
+
return this;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* No main feed at all: distinct from a failed answer.
|
|
164
|
+
**/
|
|
165
|
+
removeMainFeed(token) {
|
|
166
|
+
this.mainPriceFeeds.delete(token);
|
|
167
|
+
this.mainPrices.delete(token);
|
|
168
|
+
return this;
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* No reserve feed at all: distinct from a failed answer, and what
|
|
172
|
+
* `safeConvertMinUSD` treats as an untrusted token (value 0, no error).
|
|
173
|
+
**/
|
|
174
|
+
removeReserveFeed(token) {
|
|
175
|
+
this.reservePriceFeeds.delete(token);
|
|
176
|
+
this.reservePrices.delete(token);
|
|
177
|
+
return this;
|
|
178
|
+
}
|
|
179
|
+
async updateAndConvert(_from, _to, _amount) {
|
|
180
|
+
throw new Error("TestPriceOracle: updateAndConvert needs a node");
|
|
181
|
+
}
|
|
182
|
+
#setAnswer(token, kind, price) {
|
|
183
|
+
this.#ensureFeed(token, kind);
|
|
184
|
+
this.#answers(kind).upsert(token, {
|
|
185
|
+
price,
|
|
186
|
+
success: true,
|
|
187
|
+
updatedAt: 0n
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
#failAnswer(token, kind) {
|
|
191
|
+
this.#ensureFeed(token, kind);
|
|
192
|
+
this.#answers(kind).upsert(token, FAILED_ANSWER);
|
|
193
|
+
}
|
|
194
|
+
#ensureFeed(token, kind) {
|
|
195
|
+
const feeds = kind === "main" ? this.mainPriceFeeds : this.reservePriceFeeds;
|
|
196
|
+
if (!feeds.has(token)) feeds.upsert(token, new PriceFeedRef(this.register, feedAddr(token, kind), 0));
|
|
197
|
+
}
|
|
198
|
+
#answers(kind) {
|
|
199
|
+
return kind === "main" ? this.mainPrices : this.reservePrices;
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
/** Human USD → 8-decimal fixed point; bigint passes through. */
|
|
203
|
+
function rawPrice(price) {
|
|
204
|
+
return typeof price === "bigint" ? price : toBN(String(price), 8);
|
|
205
|
+
}
|
|
206
|
+
/** Deterministic unused address per token feed; never resolved. */
|
|
207
|
+
function feedAddr(token, kind) {
|
|
208
|
+
const bytes = hexToBytes(getAddress(token));
|
|
209
|
+
bytes[0] = kind === "main" ? 254 : 253;
|
|
210
|
+
return getAddress(bytesToHex(bytes));
|
|
211
|
+
}
|
|
212
|
+
//#endregion
|
|
213
|
+
export { MockTokens, TEST_ORACLE_ADDRESS, TestPriceOracle };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { collateralPriceInUnderlying } from "./collateralPriceInUnderlying.js";
|
|
2
|
+
import { unpriceableTokenError } from "./errors.js";
|
|
2
3
|
import { PriceOracleV310Contract } from "./PriceOracleV310Contract.js";
|
|
3
4
|
import { createPriceOracle } from "./createPriceOracle.js";
|
|
4
|
-
import { unpriceableTokenError } from "./errors.js";
|
|
5
5
|
import "./types.js";
|
|
6
6
|
export { PriceOracleV310Contract, collateralPriceInUnderlying, createPriceOracle, unpriceableTokenError };
|
|
@@ -292,15 +292,12 @@ var PositionsService = class extends SDKConstruct {
|
|
|
292
292
|
quota: priceOracle.toTokenAmount(market.underlying, t.quota),
|
|
293
293
|
withdrawals: withdrawals.get(t.token) ?? []
|
|
294
294
|
});
|
|
295
|
-
if (recomputeTotals)
|
|
296
|
-
const usd = priceOracle.safeConvertToUSD(t.token, t.balance) || 0n;
|
|
297
|
-
totalValueUSD += usd;
|
|
298
|
-
}
|
|
295
|
+
if (recomputeTotals) totalValueUSD += priceOracle.safeConvertToUSD(t.token, t.balance).value;
|
|
299
296
|
}
|
|
300
|
-
if (recomputeTotals) totalValue =
|
|
297
|
+
if (recomputeTotals) totalValue = priceOracle.safeConvertAssets(ca.tokens.map((t) => ({
|
|
301
298
|
token: t.token,
|
|
302
299
|
balance: t.balance
|
|
303
|
-
}))).value;
|
|
300
|
+
})), market.underlying).value;
|
|
304
301
|
const snapshot = {
|
|
305
302
|
...accountSnapshotFromCreditAccountData(ca),
|
|
306
303
|
totalValue
|
|
@@ -308,7 +305,8 @@ var PositionsService = class extends SDKConstruct {
|
|
|
308
305
|
const borrowRate = this.borrowRate(snapshot);
|
|
309
306
|
const timeToLiquidation = this.timeToLiquidation(snapshot);
|
|
310
307
|
const liquidationPrice = this.liquidationPrice(snapshot);
|
|
311
|
-
|
|
308
|
+
let totalDebtUSD = ca.totalDebtUSD;
|
|
309
|
+
if (priceFailed) totalDebtUSD = priceOracle.safeConvertToUSD(market.underlying, totalDebtValue).value;
|
|
312
310
|
return {
|
|
313
311
|
kind: "strategy",
|
|
314
312
|
chainId: this.sdk.chainId,
|
|
@@ -23,10 +23,11 @@ function calcHealthFactor(props) {
|
|
|
23
23
|
const active = new AddressMap(Object.entries(activeQuotas));
|
|
24
24
|
const priceOf = (token, forCollateral) => {
|
|
25
25
|
const main = pricesByToken.get(token);
|
|
26
|
-
if (!safePrices || !forCollateral) return main;
|
|
26
|
+
if (!safePrices || !forCollateral || isAddressEqual(token, underlying)) return main;
|
|
27
|
+
if (main === void 0) return;
|
|
27
28
|
const reserve = reservePricesByToken.get(token);
|
|
28
|
-
if (
|
|
29
|
-
return main
|
|
29
|
+
if (reserve === void 0) return 0n;
|
|
30
|
+
return BigIntMath.min(main, reserve);
|
|
30
31
|
};
|
|
31
32
|
const convertToUSD = (token, amount, forCollateral = false) => {
|
|
32
33
|
const price = priceOf(token, forCollateral);
|
|
@@ -85,7 +85,7 @@ var AbstractRouterContract = class extends BaseContract {
|
|
|
85
85
|
leftoverBalances.upsert(token, limitLeftover(balance, token) ?? balance);
|
|
86
86
|
if (isEnabled && !keepAssets.has(token)) usdBalances.push({
|
|
87
87
|
token,
|
|
88
|
-
balance:
|
|
88
|
+
balance: priceOracle.safeConvertToUSD(token, balance).value
|
|
89
89
|
});
|
|
90
90
|
}
|
|
91
91
|
usdBalances.sort((a, b) => {
|
|
@@ -98,7 +98,7 @@ var AbstractRouterContract = class extends BaseContract {
|
|
|
98
98
|
const lt = this.sdk.marketRegister.findCreditManager(ca.creditManager).creditManager.liquidationThresholds.mustGet(highestToken.token);
|
|
99
99
|
const requiredDebtUSD = ca.totalDebtUSD * PERCENTAGE_FACTOR / BigInt(lt);
|
|
100
100
|
if (highestToken.balance < requiredDebtUSD) return;
|
|
101
|
-
const tokenAmount =
|
|
101
|
+
const tokenAmount = priceOracle.safeConvertFromUSD(highestToken.token, requiredDebtUSD).value;
|
|
102
102
|
if (tokenAmount === 0n) return;
|
|
103
103
|
let leftoverBalance = leftoverBalances.get(highestToken.token) ?? 0n;
|
|
104
104
|
leftoverBalance -= tokenAmount;
|
|
@@ -113,28 +113,6 @@ var AbstractRouterContract = class extends BaseContract {
|
|
|
113
113
|
tokensToClaim: new AssetsMap()
|
|
114
114
|
};
|
|
115
115
|
}
|
|
116
|
-
safeConvertToUSD(priceOracle, token, balance) {
|
|
117
|
-
try {
|
|
118
|
-
return priceOracle.convertToUSD(token, balance);
|
|
119
|
-
} catch {
|
|
120
|
-
try {
|
|
121
|
-
return priceOracle.convertToUSD(token, balance, true);
|
|
122
|
-
} catch {
|
|
123
|
-
return 0n;
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
safeConvertFromUSD(priceOracle, token, balance) {
|
|
128
|
-
try {
|
|
129
|
-
return priceOracle.convertFromUSD(token, balance);
|
|
130
|
-
} catch {
|
|
131
|
-
try {
|
|
132
|
-
return priceOracle.convertFromUSD(token, balance, true);
|
|
133
|
-
} catch {
|
|
134
|
-
return 0n;
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
116
|
};
|
|
139
117
|
//#endregion
|
|
140
118
|
export { AbstractRouterContract };
|
|
@@ -227,7 +227,7 @@ var RouterV310Contract = class extends AbstractRouterContract {
|
|
|
227
227
|
}).map(({ token, balance }) => {
|
|
228
228
|
return {
|
|
229
229
|
token,
|
|
230
|
-
balance:
|
|
230
|
+
balance: priceOracle.safeConvertToUSD(token, balance).value
|
|
231
231
|
};
|
|
232
232
|
}).sort((a, b) => {
|
|
233
233
|
return a.balance > b.balance ? -1 : 1;
|
|
@@ -240,17 +240,6 @@ var RouterV310Contract = class extends AbstractRouterContract {
|
|
|
240
240
|
for (const [token, numSplits] of this.#numSplits.entries()) map.upsert(token, numSplits);
|
|
241
241
|
return (token) => map.get(token) ?? 1n;
|
|
242
242
|
}
|
|
243
|
-
/**
|
|
244
|
-
* Tries to get some value even when prices are broken, since it's only needed for sorting
|
|
245
|
-
* @param oracle
|
|
246
|
-
* @param token
|
|
247
|
-
* @param amount
|
|
248
|
-
* @returns
|
|
249
|
-
*/
|
|
250
|
-
#convertToUSDForSort(oracle, token, amount) {
|
|
251
|
-
const scale = 10n ** BigInt(this.tokensMeta.get(token)?.decimals ?? 0);
|
|
252
|
-
return amount * (oracle.mainPrices.get(token)?.price || oracle.reservePrices.get(token)?.price || scale) / scale;
|
|
253
|
-
}
|
|
254
243
|
#debugTokenData(tData) {
|
|
255
244
|
return tData.map((t) => ({
|
|
256
245
|
token: this.labelAddress(t.token),
|
|
@@ -3,7 +3,6 @@ import { BigIntMath } from "../../onchain/utils/bigint-math.js";
|
|
|
3
3
|
import { DUST_THRESHOLD } from "../../onchain/constants/math.js";
|
|
4
4
|
import { asEstimated } from "../../model/previews.js";
|
|
5
5
|
import "../../model/index.js";
|
|
6
|
-
import { unpriceableTokenError } from "../../onchain/market/oracle/errors.js";
|
|
7
6
|
import "../../onchain/index.js";
|
|
8
7
|
import { isAddressEqual } from "viem";
|
|
9
8
|
//#region src/preview/preview/buildDelayedStrategyPositionOperationPreview.ts
|
|
@@ -13,10 +12,9 @@ import { isAddressEqual } from "viem";
|
|
|
13
12
|
* the claim itself followed by the intent-specific tail
|
|
14
13
|
*
|
|
15
14
|
* Pure function: the input states are never mutated and no network access is performed.
|
|
16
|
-
* Swaps are
|
|
17
|
-
* priced
|
|
18
|
-
*
|
|
19
|
-
* preview.
|
|
15
|
+
* Swaps and remaining holdings are priced by the market oracle. Tokens that
|
|
16
|
+
* cannot be priced contribute nothing and set a non-fatal `unpriceableToken`
|
|
17
|
+
* warning on the preview.
|
|
20
18
|
*
|
|
21
19
|
* The changes (e.g. `totalDebtChange`) are reported relative to the account
|
|
22
20
|
* state before the whole transaction.
|
|
@@ -30,36 +28,26 @@ import { isAddressEqual } from "viem";
|
|
|
30
28
|
* @param sdk - Market data source for the position metrics of the resulting
|
|
31
29
|
* state; read synchronously, no network access.
|
|
32
30
|
*/
|
|
33
|
-
function buildDelayedStrategyPositionOperationPreview(afterInstant, before, detected,
|
|
31
|
+
function buildDelayedStrategyPositionOperationPreview(afterInstant, before, detected, receivedToken, sdk) {
|
|
34
32
|
const { request, intent } = detected;
|
|
35
33
|
const post = afterInstant.clone();
|
|
36
|
-
const
|
|
34
|
+
const oracle = sdk.marketRegister.findByCreditManager(post.creditManager).priceOracle;
|
|
35
|
+
let warning;
|
|
36
|
+
const convert = (from, to, amount) => {
|
|
37
|
+
const priced = oracle.safeConvert(from, to, amount);
|
|
38
|
+
warning ??= priced.error;
|
|
39
|
+
return priced.value;
|
|
40
|
+
};
|
|
37
41
|
const claimed = applyClaim(post, request);
|
|
38
42
|
const collateralWithdrawn = new AssetsMap();
|
|
39
43
|
switch (intent?.type) {
|
|
40
|
-
case "CLOSE_ACCOUNT": return buildClosePreview(post,
|
|
44
|
+
case "CLOSE_ACCOUNT": return buildClosePreview(post, receivedToken, sdk, warning);
|
|
41
45
|
case "DECREASE_LEVERAGE":
|
|
42
|
-
repayFromClaim(post, request.claimToken,
|
|
46
|
+
repayFromClaim(post, request.claimToken, convert, claimed);
|
|
43
47
|
break;
|
|
44
|
-
case "WITHDRAW_COLLATERAL": applyWithdrawCollateral(post, request, intent,
|
|
48
|
+
case "WITHDRAW_COLLATERAL": applyWithdrawCollateral(post, request, intent, convert, collateralWithdrawn);
|
|
45
49
|
}
|
|
46
|
-
return buildAdjustPreview(post, before, collateralWithdrawn,
|
|
47
|
-
}
|
|
48
|
-
function makeSafeConverter(convert) {
|
|
49
|
-
let warning;
|
|
50
|
-
return {
|
|
51
|
-
convert: (token, to, amount) => {
|
|
52
|
-
try {
|
|
53
|
-
return convert(token, to, amount);
|
|
54
|
-
} catch {
|
|
55
|
-
warning ??= unpriceableTokenError(token);
|
|
56
|
-
return 0n;
|
|
57
|
-
}
|
|
58
|
-
},
|
|
59
|
-
get warning() {
|
|
60
|
-
return warning;
|
|
61
|
-
}
|
|
62
|
-
};
|
|
50
|
+
return buildAdjustPreview(post, before, collateralWithdrawn, sdk, warning);
|
|
63
51
|
}
|
|
64
52
|
/**
|
|
65
53
|
* Claim step, common to all intents: burns the phantom token (balance and
|
|
@@ -105,7 +93,7 @@ function applyClaim(post, request) {
|
|
|
105
93
|
* debt with them, but no more than the intent's `debtRepaid` target;
|
|
106
94
|
* whatever is not spent on repayment stays on the account as underlying.
|
|
107
95
|
*/
|
|
108
|
-
function applyWithdrawCollateral(post, request, intent,
|
|
96
|
+
function applyWithdrawCollateral(post, request, intent, convert, collateralWithdrawn) {
|
|
109
97
|
const { withdrawToken, withdrawAmount, debtRepaid } = intent;
|
|
110
98
|
const { claimToken } = request;
|
|
111
99
|
const sameToken = isAddressEqual(withdrawToken, claimToken);
|
|
@@ -115,19 +103,19 @@ function applyWithdrawCollateral(post, request, intent, converter, collateralWit
|
|
|
115
103
|
const missing = withdrawAmount - fromBalance;
|
|
116
104
|
if (missing > 0n && !sameToken) {
|
|
117
105
|
const available = post.balances.getOrZero(claimToken);
|
|
118
|
-
const cost =
|
|
106
|
+
const cost = convert(withdrawToken, claimToken, missing);
|
|
119
107
|
if (cost > 0n && cost <= available) {
|
|
120
108
|
post.balances.dec(claimToken, cost);
|
|
121
109
|
withdrawn += missing;
|
|
122
110
|
} else if (available > 0n) {
|
|
123
111
|
post.balances.dec(claimToken, available);
|
|
124
|
-
withdrawn +=
|
|
112
|
+
withdrawn += convert(claimToken, withdrawToken, available);
|
|
125
113
|
}
|
|
126
114
|
}
|
|
127
115
|
if (withdrawn > 0n) collateralWithdrawn.upsert(withdrawToken, withdrawn);
|
|
128
116
|
const remaining = post.balances.getOrZero(claimToken);
|
|
129
117
|
if (remaining > 0n) {
|
|
130
|
-
const proceeds =
|
|
118
|
+
const proceeds = convert(claimToken, post.underlying, remaining);
|
|
131
119
|
post.balances.dec(claimToken, remaining);
|
|
132
120
|
post.balances.inc(post.underlying, proceeds);
|
|
133
121
|
post.repay(BigIntMath.min(proceeds, debtRepaid));
|
|
@@ -151,10 +139,10 @@ function repayFromClaim(post, claimToken, convert, amount) {
|
|
|
151
139
|
* underlying, the debt is repaid in full and the remainder is withdrawn to
|
|
152
140
|
* the user as `receivedToken`.
|
|
153
141
|
*/
|
|
154
|
-
function buildClosePreview(post,
|
|
142
|
+
function buildClosePreview(post, receivedToken, sdk, warning) {
|
|
155
143
|
const market = sdk.marketRegister.findByCreditManager(post.creditManager);
|
|
156
|
-
const priced = market.valueInUnderlying(post.balances.toAssets(), 0n);
|
|
157
144
|
const oracle = market.priceOracle;
|
|
145
|
+
const priced = oracle.safeConvertAssets(post.balances.toAssets(), market.underlying);
|
|
158
146
|
const suite = sdk.marketRegister.findCreditManager(post.creditManager);
|
|
159
147
|
return {
|
|
160
148
|
operation: "CloseCreditAccount",
|
|
@@ -170,15 +158,15 @@ function buildClosePreview(post, converter, receivedToken, sdk) {
|
|
|
170
158
|
name: suite.accountStrategyName(post.creditAccount),
|
|
171
159
|
targetCollateral: suite.accountTargetCollateral(post.creditAccount),
|
|
172
160
|
receivedAmount: oracle.toTokenAmount(receivedToken, BigIntMath.max(priced.value - post.totalDebt, 0n)),
|
|
173
|
-
warning:
|
|
161
|
+
warning: warning ?? priced.error
|
|
174
162
|
};
|
|
175
163
|
}
|
|
176
|
-
function buildAdjustPreview(post, before, collateralWithdrawn,
|
|
164
|
+
function buildAdjustPreview(post, before, collateralWithdrawn, sdk, warning) {
|
|
177
165
|
const market = sdk.marketRegister.findByCreditManager(post.creditManager);
|
|
178
|
-
const
|
|
166
|
+
const oracle = market.priceOracle;
|
|
167
|
+
const priced = oracle.safeConvertAssets(post.balances.toAssets(), market.underlying);
|
|
179
168
|
const snap = post.toSnapshot(priced.value);
|
|
180
169
|
const suite = sdk.marketRegister.findCreditManager(post.creditManager);
|
|
181
|
-
const oracle = market.priceOracle;
|
|
182
170
|
return {
|
|
183
171
|
operation: "AdjustCreditAccount",
|
|
184
172
|
...asEstimated(sdk.positions.projection(snap, { availableLiquidityChange: before.totalDebt - post.totalDebt })),
|
|
@@ -193,7 +181,7 @@ function buildAdjustPreview(post, before, collateralWithdrawn, converter, sdk) {
|
|
|
193
181
|
...oracle.toAmount(market.underlying, q.balance)
|
|
194
182
|
})),
|
|
195
183
|
assetsChange: post.balances.difference(before.balances).toAssets(DUST_THRESHOLD).map((a) => oracle.toTokenAmount(a.token, a.balance)),
|
|
196
|
-
warning:
|
|
184
|
+
warning: warning ?? priced.error
|
|
197
185
|
};
|
|
198
186
|
}
|
|
199
187
|
//#endregion
|
|
@@ -2,7 +2,6 @@ import { AP_WETH_TOKEN } from "../../onchain/constants/address-provider.js";
|
|
|
2
2
|
import { DUST_THRESHOLD } from "../../onchain/constants/math.js";
|
|
3
3
|
import { asEstimated } from "../../model/previews.js";
|
|
4
4
|
import "../../model/index.js";
|
|
5
|
-
import { unpriceableTokenError } from "../../onchain/market/oracle/errors.js";
|
|
6
5
|
import "../../onchain/index.js";
|
|
7
6
|
import { replayMulticall } from "./replayMulticall.js";
|
|
8
7
|
import { unwrapNativeCollateral } from "./unwrapNativeCollateral.js";
|
|
@@ -25,8 +24,8 @@ function previewAdjustStrategyPosition(input, operation, options) {
|
|
|
25
24
|
const { assets: collateralAdded, warning: unwrapWarning } = unwrapNativeCollateral(after.collateralAdded.toAssets(), value, sdk.addressProvider.getAddress(AP_WETH_TOKEN, 0));
|
|
26
25
|
warning ??= unwrapWarning;
|
|
27
26
|
const assetsChange = account.balances.difference(before.balances).toAssets(DUST_THRESHOLD);
|
|
28
|
-
const priced =
|
|
29
|
-
|
|
27
|
+
const priced = oracle.safeConvertAssets(account.balances.toAssets(), market.underlying);
|
|
28
|
+
warning ??= priced.error;
|
|
30
29
|
const snap = account.toSnapshot(priced.value);
|
|
31
30
|
return {
|
|
32
31
|
operation: "AdjustCreditAccount",
|
|
@@ -2,7 +2,6 @@ import { AP_WETH_TOKEN } from "../../onchain/constants/address-provider.js";
|
|
|
2
2
|
import "../../onchain/constants/math.js";
|
|
3
3
|
import { asEstimated } from "../../model/previews.js";
|
|
4
4
|
import "../../model/index.js";
|
|
5
|
-
import { unpriceableTokenError } from "../../onchain/market/oracle/errors.js";
|
|
6
5
|
import "../../onchain/index.js";
|
|
7
6
|
import { classifyCloseOrRepay } from "./detectCloseOrRepay.js";
|
|
8
7
|
import { replayMulticall } from "./replayMulticall.js";
|
|
@@ -28,8 +27,8 @@ function previewCloseCreditAccount(input, operation, permanent, replay) {
|
|
|
28
27
|
const { before, after, warning: replayWarning } = replay;
|
|
29
28
|
const account = after.account;
|
|
30
29
|
let warning = replayWarning;
|
|
31
|
-
const priced = market.
|
|
32
|
-
|
|
30
|
+
const priced = market.priceOracle.safeConvertAssets(account.balances.toAssets(), market.underlying);
|
|
31
|
+
warning ??= priced.error;
|
|
33
32
|
const suite = sdk.marketRegister.findCreditManager(operation.creditManager);
|
|
34
33
|
let receivedToken = market.underlying;
|
|
35
34
|
for (const m of operation.multicall) if (m.operation === "WithdrawCollateral" && m.amount === 115792089237316195423570985008687907853269984665640564039457584007913129639935n) {
|
|
@@ -59,8 +58,8 @@ function previewRepayCreditAccount(input, operation, permanent, replay) {
|
|
|
59
58
|
const account = after.account;
|
|
60
59
|
const { assets: collateralAdded, warning: unwrapWarning } = unwrapNativeCollateral(after.collateralAdded.toAssets(), value, sdk.addressProvider.getAddress(AP_WETH_TOKEN, 0));
|
|
61
60
|
let warning = replayWarning ?? unwrapWarning;
|
|
62
|
-
const priced = market.
|
|
63
|
-
|
|
61
|
+
const priced = market.priceOracle.safeConvertAssets(account.balances.toAssets(), market.underlying);
|
|
62
|
+
warning ??= priced.error;
|
|
64
63
|
const suite = sdk.marketRegister.findCreditManager(operation.creditManager);
|
|
65
64
|
return {
|
|
66
65
|
operation: "RepayCreditAccount",
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { AP_WETH_TOKEN } from "../../onchain/constants/address-provider.js";
|
|
2
2
|
import { asEstimated } from "../../model/previews.js";
|
|
3
3
|
import "../../model/index.js";
|
|
4
|
-
import { unpriceableTokenError } from "../../onchain/market/oracle/errors.js";
|
|
5
4
|
import "../../onchain/index.js";
|
|
6
5
|
import { CreditAccountState } from "./CreditAccountState.js";
|
|
7
6
|
import { makeReplayState, replayInnerOperations } from "./replayInnerOperations.js";
|
|
@@ -16,12 +15,9 @@ function previewOpenStrategyPosition(input, operation) {
|
|
|
16
15
|
const account = state.account;
|
|
17
16
|
let priceWarning;
|
|
18
17
|
const netValue = state.collateralAdded.sum((token, balance) => {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
priceWarning ??= unpriceableTokenError(token);
|
|
23
|
-
return 0n;
|
|
24
|
-
}
|
|
18
|
+
const priced = oracle.safeConvert(token, market.underlying, balance);
|
|
19
|
+
priceWarning ??= priced.error;
|
|
20
|
+
return priced.value;
|
|
25
21
|
});
|
|
26
22
|
const { assets: collateral, warning: unwrapWarning } = unwrapNativeCollateral(state.collateralAdded.toAssets(), value, sdk.addressProvider.getAddress(AP_WETH_TOKEN, 0));
|
|
27
23
|
warning ??= unwrapWarning ?? priceWarning;
|
|
@@ -80,7 +80,6 @@ async function previewMulticallOperation(input, operation, options) {
|
|
|
80
80
|
}
|
|
81
81
|
const { before, after } = replayMulticall(sdk, operation, options);
|
|
82
82
|
const market = sdk.marketRegister.findByCreditManager(operation.creditManager);
|
|
83
|
-
const convert = (token, to, amount) => market.priceOracle.convert(token, to, amount);
|
|
84
83
|
const meta = sdk.tokensMeta.get(market.underlying);
|
|
85
84
|
const receivedToken = meta && sdk.tokensMeta.isRWAUnderlying(meta) ? meta.asset : market.underlying;
|
|
86
85
|
const suite = sdk.marketRegister.findCreditManager(operation.creditManager);
|
|
@@ -93,7 +92,7 @@ async function previewMulticallOperation(input, operation, options) {
|
|
|
93
92
|
intent: delayed.intent,
|
|
94
93
|
estClaimableAt: estimateClaimableAt(sdk, delayed.request.phantomToken),
|
|
95
94
|
instantPreview,
|
|
96
|
-
delayedPreview: buildDelayedStrategyPositionOperationPreview(after.account, before, delayed,
|
|
95
|
+
delayedPreview: buildDelayedStrategyPositionOperationPreview(after.account, before, delayed, receivedToken, sdk)
|
|
97
96
|
});
|
|
98
97
|
}
|
|
99
98
|
//#endregion
|
|
@@ -20,7 +20,7 @@ import { borrowRateBreakdownSchema, pnlBreakdownSchema, pointsProgramPnLSchema,
|
|
|
20
20
|
import { amountSchema, assetTypeSchema, bpsSchema, chainIdSchema, leverageSchema, timestampSchema, tokenAmountSchema, tokenSchema, txCallSchema, underlyingTokenSchema } from "./primitives.schema.js";
|
|
21
21
|
import { ChainFailed, ChainMetadata, ChainScoped, ChainSucceeded, DataResponse, DataSource, ResponseMetadata } from "./response.js";
|
|
22
22
|
import { chainFailedSchema, chainMetadataSchema, chainSucceededSchema, dataSourceSchema, responseMetadataSchema, responseSchema } from "./response.schema.js";
|
|
23
|
-
import { SDKError, SDKResult, SDKReturn, isSDKError, sdkErr, sdkOk } from "./result.js";
|
|
23
|
+
import { SDKError, SDKResult, SDKReturn, SafeValue, isSDKError, safeValue, sdkErr, sdkOk } from "./result.js";
|
|
24
24
|
import { PositionClaimableWithdrawal, PositionPendingWithdrawal, PositionWithdrawals, WithdrawalOutputAmount } from "./withdrawals.js";
|
|
25
25
|
import { positionClaimableWithdrawalSchema, positionPendingWithdrawalSchema, positionWithdrawalsSchema, withdrawalOutputAmountSchema } from "./withdrawals.schema.js";
|
|
26
|
-
export { AccountHoldings, AccountMetrics, AccountProjection, AccountStateChange, AdapterCallOutsideBracketError, AdjustStrategyPositionPreview, Amount, ApyBreakdown, Asset, AssetType, BorrowRateBreakdown, Bps, CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, ChainFailed, ChainId, ChainMetadata, ChainScoped, ChainScopedFilter, ChainSucceeded, ChartBundle, ChartDenomination, ChartMetric, ChartQuery, ChartRange, ChartSeries, ChartSeriesOk, ChartSeriesUnavailable, ChartUnavailableCode, ChartUnit, ChartValue, ChartWindow, CompareTag, CompareTolerance, CreditOperationMarket, Curator, CuratorName, DataResponse, DataSource, DelayedAddCollateralIntent, DelayedCloseAccountIntent, DelayedDecreaseLeverageIntent, DelayedDepositAndIncreaseLeverageIntent, DelayedDepositIntent, DelayedIncreaseLeverageIntent, DelayedIntent, DelayedReceivedAsset, DelayedStrategyPositionOperationPreview, DelayedWithdrawCollateralIntent, Estimated, EstimatedProjection, ExitStrategyPositionPreview, FILTER_ALL, FilterAll, Filterable, GridSampling, IGearboxError, InstantReceivedAsset, InstantStrategyPositionOperationPreview, InvalidTransactionValueError, Leverage, LiquidatableAccount, LiquidatableAccountFilter, LiquidationApproval, LiquidationDetails, LiquidationPosition, MalformedBracketError, MalformedBracketKind, MalformedPreviewError, NonAdapterCallInBracketError, Notice, NoticeKind, NoticeSubject, OpenStrategyPositionPreview, OperationPreview, OperationPreviewError, Opportunity, OpportunityBase, OpportunityChartMetric, OpportunityDetail, OpportunityFilter, OpportunityId, OpportunityKey, OpportunityKind, OpportunityTotals, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, PnlBreakdown, PointRewards, PointsProgram, PointsProgramPnL, PointsRewardsPnL, PoolOperationType, PoolOpportunity, PoolOpportunityChartMetric, PoolOpportunityDetail, PoolOpportunityKey, PoolOpportunityRef, PoolPosition, PoolPositionChartMetric, PoolPositionKey, PoolPositionOperationPreview, PoolPositionRef, Position, PositionChartMetric, PositionClaimableWithdrawal, PositionCollateral, PositionFilter, PositionId, PositionKey, PositionKind, PositionPendingWithdrawal, PositionTransaction, PositionTransactionKind, PositionWithdrawals, PositionsTotals, PreviewOperationInput, PreviewOperationOptions, PriceFeedData, PriceFeedSummary, QuotaAsset, RateCurve, RateCurvePoint, ReceivedAsset, RepayStrategyPositionPreview, ResponseMetadata, Rewards, RewardsPnL, RoutedField, SDKError, SDKResult, SDKReturn, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, StrategyOpportunity, StrategyOpportunityChartMetric, StrategyOpportunityDetail, StrategyOpportunityKey, StrategyOpportunityRef, StrategyPosition, StrategyPositionChartMetric, StrategyPositionKey, StrategyPositionRef, Timestamp, Token, TokenAmount, TokenQuotaRate, TokenRewards, TokenRewardsPnL, ToleranceCompareTag, TxCall, UnderlyingToken, UnpreviewableAdapterCallError, UnsupportedOutOfBracketCallError, WithdrawalOutputAmount, amountSchema, apyBreakdownSchema, asEstimated, assetTypeSchema, backendPreferred, booleanParamSchema, borrowRateBreakdownSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, chartBundleSchemaFor, chartDenominationSchema, chartMetricSchema, chartQueryCodec, chartQueryParamsSchema, chartQuerySchema, chartRangeSchema, chartSeriesSchema, chartValueSchema, chartWindowSchema, compareTagOf, curatorNameSchema, curatorSchema, dataSourceSchema, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, instantReceivedAssetSchema, isFilterSet, isSDKError, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, noticeKindSchema, noticeSchema, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, positionClaimableWithdrawalSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionPendingWithdrawalSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionWithdrawalsSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, sdkErr, sdkOk, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema, underlyingTokenSchema, withdrawalOutputAmountSchema };
|
|
26
|
+
export { AccountHoldings, AccountMetrics, AccountProjection, AccountStateChange, AdapterCallOutsideBracketError, AdjustStrategyPositionPreview, Amount, ApyBreakdown, Asset, AssetType, BorrowRateBreakdown, Bps, CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, ChainFailed, ChainId, ChainMetadata, ChainScoped, ChainScopedFilter, ChainSucceeded, ChartBundle, ChartDenomination, ChartMetric, ChartQuery, ChartRange, ChartSeries, ChartSeriesOk, ChartSeriesUnavailable, ChartUnavailableCode, ChartUnit, ChartValue, ChartWindow, CompareTag, CompareTolerance, CreditOperationMarket, Curator, CuratorName, DataResponse, DataSource, DelayedAddCollateralIntent, DelayedCloseAccountIntent, DelayedDecreaseLeverageIntent, DelayedDepositAndIncreaseLeverageIntent, DelayedDepositIntent, DelayedIncreaseLeverageIntent, DelayedIntent, DelayedReceivedAsset, DelayedStrategyPositionOperationPreview, DelayedWithdrawCollateralIntent, Estimated, EstimatedProjection, ExitStrategyPositionPreview, FILTER_ALL, FilterAll, Filterable, GridSampling, IGearboxError, InstantReceivedAsset, InstantStrategyPositionOperationPreview, InvalidTransactionValueError, Leverage, LiquidatableAccount, LiquidatableAccountFilter, LiquidationApproval, LiquidationDetails, LiquidationPosition, MalformedBracketError, MalformedBracketKind, MalformedPreviewError, NonAdapterCallInBracketError, Notice, NoticeKind, NoticeSubject, OpenStrategyPositionPreview, OperationPreview, OperationPreviewError, Opportunity, OpportunityBase, OpportunityChartMetric, OpportunityDetail, OpportunityFilter, OpportunityId, OpportunityKey, OpportunityKind, OpportunityTotals, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, PnlBreakdown, PointRewards, PointsProgram, PointsProgramPnL, PointsRewardsPnL, PoolOperationType, PoolOpportunity, PoolOpportunityChartMetric, PoolOpportunityDetail, PoolOpportunityKey, PoolOpportunityRef, PoolPosition, PoolPositionChartMetric, PoolPositionKey, PoolPositionOperationPreview, PoolPositionRef, Position, PositionChartMetric, PositionClaimableWithdrawal, PositionCollateral, PositionFilter, PositionId, PositionKey, PositionKind, PositionPendingWithdrawal, PositionTransaction, PositionTransactionKind, PositionWithdrawals, PositionsTotals, PreviewOperationInput, PreviewOperationOptions, PriceFeedData, PriceFeedSummary, QuotaAsset, RateCurve, RateCurvePoint, ReceivedAsset, RepayStrategyPositionPreview, ResponseMetadata, Rewards, RewardsPnL, RoutedField, SDKError, SDKResult, SDKReturn, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, SafeValue, StrategyOpportunity, StrategyOpportunityChartMetric, StrategyOpportunityDetail, StrategyOpportunityKey, StrategyOpportunityRef, StrategyPosition, StrategyPositionChartMetric, StrategyPositionKey, StrategyPositionRef, Timestamp, Token, TokenAmount, TokenQuotaRate, TokenRewards, TokenRewardsPnL, ToleranceCompareTag, TxCall, UnderlyingToken, UnpreviewableAdapterCallError, UnsupportedOutOfBracketCallError, WithdrawalOutputAmount, amountSchema, apyBreakdownSchema, asEstimated, assetTypeSchema, backendPreferred, booleanParamSchema, borrowRateBreakdownSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, chartBundleSchemaFor, chartDenominationSchema, chartMetricSchema, chartQueryCodec, chartQueryParamsSchema, chartQuerySchema, chartRangeSchema, chartSeriesSchema, chartValueSchema, chartWindowSchema, compareTagOf, curatorNameSchema, curatorSchema, dataSourceSchema, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, instantReceivedAssetSchema, isFilterSet, isSDKError, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, noticeKindSchema, noticeSchema, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, positionClaimableWithdrawalSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionPendingWithdrawalSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionWithdrawalsSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, safeValue, sdkErr, sdkOk, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema, underlyingTokenSchema, withdrawalOutputAmountSchema };
|
|
@@ -290,9 +290,10 @@ interface AccountMetrics {
|
|
|
290
290
|
**/
|
|
291
291
|
healthFactor: Bps;
|
|
292
292
|
/**
|
|
293
|
-
* The same factor with collateral valued at safe prices —
|
|
294
|
-
* token's main and reserve
|
|
295
|
-
* switches to for a call that hands funds over.
|
|
293
|
+
* The same factor with collateral valued at safe prices — `min` of each
|
|
294
|
+
* token's main and reserve feeds (0 when there is no reserve), which is
|
|
295
|
+
* what the credit manager switches to for a call that hands funds over.
|
|
296
|
+
* The underlying is always priced at the main feed.
|
|
296
297
|
*
|
|
297
298
|
* Always reported, whether or not the operation in question hands anything
|
|
298
299
|
* over: which of the two factors decides a transaction is a property of the
|
|
@@ -35,6 +35,21 @@ interface SDKError<E extends IGearboxError = IGearboxError> {
|
|
|
35
35
|
* to handle, checked by the compiler.
|
|
36
36
|
**/
|
|
37
37
|
type SDKReturn<T, E extends IGearboxError> = SDKResult<T> | SDKError<E>;
|
|
38
|
+
/**
|
|
39
|
+
* Best-effort result: `value` is always present (zero / empty when nothing
|
|
40
|
+
* worked), `error` is set when it was degraded.
|
|
41
|
+
*
|
|
42
|
+
* Opposite of {@link SDKReturn}, which is exclusive (ok XOR error: a refusal).
|
|
43
|
+
* Later safe-priced figures reuse this type.
|
|
44
|
+
**/
|
|
45
|
+
interface SafeValue<T, E extends IGearboxError = IGearboxError> {
|
|
46
|
+
value: T;
|
|
47
|
+
error?: E;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Builds a {@link SafeValue}. Omits `error` when the value was not degraded.
|
|
51
|
+
**/
|
|
52
|
+
declare function safeValue<T, E extends IGearboxError = IGearboxError>(value: T, error?: E): SafeValue<T, E>;
|
|
38
53
|
/** The success half, built. */
|
|
39
54
|
declare function sdkOk<T>(data: T): SDKResult<T>;
|
|
40
55
|
/** The failure half, built. */
|
|
@@ -45,4 +60,4 @@ declare function sdkErr<E extends IGearboxError>(error: E): SDKError<E>;
|
|
|
45
60
|
**/
|
|
46
61
|
declare function isSDKError<T, E extends IGearboxError>(answer: SDKReturn<T, E>): answer is SDKError<E>;
|
|
47
62
|
//#endregion
|
|
48
|
-
export { SDKError, SDKResult, SDKReturn, isSDKError, sdkErr, sdkOk };
|
|
63
|
+
export { SDKError, SDKResult, SDKReturn, SafeValue, isSDKError, safeValue, sdkErr, sdkOk };
|