@gearbox-protocol/sdk 16.3.0-next.2 → 16.3.0-next.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/cjs/model/errors/index.js +0 -1
  2. package/dist/cjs/model/errors/operation-errors.js +1 -1
  3. package/dist/cjs/model/errors/prepare-errors.js +0 -8
  4. package/dist/cjs/model/index.js +2 -3
  5. package/dist/cjs/model/rwa.js +4 -4
  6. package/dist/cjs/model/rwa.schema.js +4 -4
  7. package/dist/cjs/offchain/opportunities/OffchainOpportunities.js +1 -1
  8. package/dist/cjs/onchain/accounts/CreditAccountsServiceV310.js +1 -3
  9. package/dist/cjs/onchain/accounts/intents/guards.js +4 -4
  10. package/dist/cjs/onchain/accounts/liquidations/LiquidationsService.js +1 -1
  11. package/dist/cjs/onchain/market/credit/CreditSuite.js +26 -12
  12. package/dist/cjs/onchain/market/rwa/midas/MidasDegenNFT.js +45 -5
  13. package/dist/cjs/onchain/market/rwa/securitize/SecuritizeDegenNFT.js +56 -12
  14. package/dist/cjs/onchain/market/rwa/securitize/SecuritizeRWAFactory.js +0 -37
  15. package/dist/cjs/onchain/opportunities/MultichainOpportunitiesService.js +8 -2
  16. package/dist/cjs/onchain/opportunities/OpportunitiesService.js +16 -4
  17. package/dist/cjs/onchain/preview/parse/parseRWAFactoryOperationCalldata.js +2 -2
  18. package/dist/cjs/onchain/validation/bundles/checkCreditOperation.js +3 -2
  19. package/dist/cjs/onchain/validation/bundles/checkDraw.js +3 -3
  20. package/dist/cjs/onchain/validation/bundles/checkRWAOpenRequirements.js +9 -9
  21. package/dist/cjs/onchain/validation/bundles/checkRWAOpening.js +6 -5
  22. package/dist/cjs/onchain/validation/checkSimulation.js +11 -14
  23. package/dist/cjs/onchain/validation/checks/checkDebtLimits.js +3 -2
  24. package/dist/cjs/sdk/execute/ExecuteApi.js +2 -2
  25. package/dist/cjs/sdk/index.js +0 -1
  26. package/dist/cjs/sdk/opportunities/OpportunitiesNamespace.js +9 -3
  27. package/dist/cjs/sdk/prepare/PrepareApi.js +27 -8
  28. package/dist/cjs/sdk/prepare/index.js +0 -1
  29. package/dist/esm/model/errors/index.js +2 -2
  30. package/dist/esm/model/errors/operation-errors.js +1 -1
  31. package/dist/esm/model/errors/prepare-errors.js +1 -8
  32. package/dist/esm/model/index.js +4 -4
  33. package/dist/esm/model/rwa.js +4 -4
  34. package/dist/esm/model/rwa.schema.js +5 -5
  35. package/dist/esm/offchain/opportunities/OffchainOpportunities.js +1 -1
  36. package/dist/esm/onchain/accounts/CreditAccountsServiceV310.js +1 -3
  37. package/dist/esm/onchain/accounts/intents/guards.js +4 -4
  38. package/dist/esm/onchain/accounts/liquidations/LiquidationsService.js +1 -1
  39. package/dist/esm/onchain/market/credit/CreditSuite.js +26 -12
  40. package/dist/esm/onchain/market/rwa/midas/MidasDegenNFT.js +45 -5
  41. package/dist/esm/onchain/market/rwa/securitize/SecuritizeDegenNFT.js +55 -10
  42. package/dist/esm/onchain/market/rwa/securitize/SecuritizeRWAFactory.js +0 -37
  43. package/dist/esm/onchain/opportunities/MultichainOpportunitiesService.js +8 -2
  44. package/dist/esm/onchain/opportunities/OpportunitiesService.js +16 -4
  45. package/dist/esm/onchain/preview/parse/parseRWAFactoryOperationCalldata.js +2 -2
  46. package/dist/esm/onchain/validation/bundles/checkCreditOperation.js +3 -2
  47. package/dist/esm/onchain/validation/bundles/checkDraw.js +3 -3
  48. package/dist/esm/onchain/validation/bundles/checkRWAOpenRequirements.js +9 -9
  49. package/dist/esm/onchain/validation/bundles/checkRWAOpening.js +6 -5
  50. package/dist/esm/onchain/validation/checkSimulation.js +11 -14
  51. package/dist/esm/onchain/validation/checks/checkDebtLimits.js +3 -2
  52. package/dist/esm/sdk/execute/ExecuteApi.js +2 -2
  53. package/dist/esm/sdk/index.js +2 -2
  54. package/dist/esm/sdk/opportunities/OpportunitiesNamespace.js +9 -3
  55. package/dist/esm/sdk/prepare/PrepareApi.js +28 -9
  56. package/dist/esm/sdk/prepare/index.js +2 -2
  57. package/dist/types/model/errors/index.d.ts +2 -2
  58. package/dist/types/model/errors/operation-errors.d.ts +10 -4
  59. package/dist/types/model/errors/prepare-errors.d.ts +1 -10
  60. package/dist/types/model/index.d.ts +4 -4
  61. package/dist/types/model/opportunities.d.ts +4 -5
  62. package/dist/types/model/rwa.d.ts +47 -27
  63. package/dist/types/model/rwa.schema.d.ts +3 -3
  64. package/dist/types/offchain/opportunities/OffchainOpportunities.d.ts +1 -2
  65. package/dist/types/offchain/opportunities/types.d.ts +1 -4
  66. package/dist/types/onchain/accounts/types.d.ts +4 -2
  67. package/dist/types/onchain/index.d.ts +3 -3
  68. package/dist/types/onchain/market/credit/CreditSuite.d.ts +8 -3
  69. package/dist/types/onchain/market/credit/types.d.ts +2 -2
  70. package/dist/types/onchain/market/index.d.ts +2 -2
  71. package/dist/types/onchain/market/rwa/index.d.ts +2 -2
  72. package/dist/types/onchain/market/rwa/midas/MidasDegenNFT.d.ts +19 -4
  73. package/dist/types/onchain/market/rwa/securitize/SecuritizeDegenNFT.d.ts +24 -4
  74. package/dist/types/onchain/market/rwa/securitize/SecuritizeRWAFactory.d.ts +2 -14
  75. package/dist/types/onchain/market/rwa/types.d.ts +39 -37
  76. package/dist/types/onchain/opportunities/MultichainOpportunitiesService.d.ts +5 -1
  77. package/dist/types/onchain/opportunities/OpportunitiesService.d.ts +10 -3
  78. package/dist/types/onchain/opportunities/types.d.ts +6 -1
  79. package/dist/types/onchain/validation/bundles/checkRWAOpenRequirements.d.ts +2 -2
  80. package/dist/types/onchain/validation/bundles/checkRWAOpening.d.ts +3 -3
  81. package/dist/types/onchain/validation/checkSimulation.d.ts +9 -20
  82. package/dist/types/onchain/validation/checks/checkDebtLimits.d.ts +4 -0
  83. package/dist/types/onchain/validation/index.d.ts +2 -2
  84. package/dist/types/sdk/index.d.ts +4 -3
  85. package/dist/types/sdk/opportunities/OpportunitiesNamespace.d.ts +5 -1
  86. package/dist/types/sdk/opportunities/types.d.ts +9 -3
  87. package/dist/types/sdk/prepare/PrepareApi.d.ts +6 -5
  88. package/dist/types/sdk/prepare/index.d.ts +4 -3
  89. package/dist/types/sdk/prepare/types.d.ts +47 -21
  90. package/package.json +1 -1
@@ -1,13 +1,23 @@
1
+ import { AddressSet } from "../../../utils/AddressSet.js";
2
+ import "../../../utils/index.js";
1
3
  import { BaseContract } from "../../../base/BaseContract.js";
2
4
  import "../../../base/index.js";
5
+ import { KYC_REGISTRATION_LINKS } from "../../../../model/rwa.js";
6
+ import "../../../../model/index.js";
3
7
  import { DEGEN_NFT_SECURITIZE } from "./constants.js";
4
8
  import { iSecuritizeDegenNFTAbi } from "../../../../abi/rwa/iSecuritizeDegenNFT.js";
5
- import { isAddressEqual } from "viem";
6
9
  //#region src/onchain/market/rwa/securitize/SecuritizeDegenNFT.ts
7
10
  const abi = iSecuritizeDegenNFTAbi;
11
+ /**
12
+ * Securitize always has a factory, which deploys this NFT. DS-token data,
13
+ * registrars and cached signatures live here; the factory only builds txs
14
+ * and looks up investor/wallet addresses.
15
+ */
8
16
  var SecuritizeDegenNFT = class extends BaseContract {
9
17
  protocol = "securitize";
18
+ registrationLink = KYC_REGISTRATION_LINKS.securitize;
10
19
  factory;
20
+ #sdk;
11
21
  constructor(sdk, address, factory) {
12
22
  super(sdk, {
13
23
  addr: address,
@@ -16,19 +26,54 @@ var SecuritizeDegenNFT = class extends BaseContract {
16
26
  name: "SecuritizeDegenNFT",
17
27
  abi
18
28
  });
29
+ this.#sdk = sdk;
19
30
  this.factory = factory;
20
31
  }
21
- /** Registration on Securitize is the only KYC step; pending EIP-712 signatures are not. */
22
- async checkKyc(wallet, targetCollateral) {
23
- const { factory } = this;
24
- if (!factory.getTokens().some((t) => isAddressEqual(t, targetCollateral))) return {
25
- eligible: true,
26
- token: targetCollateral
32
+ async getTokens() {
33
+ return this.factory.getTokens();
34
+ }
35
+ /**
36
+ * Registration on Securitize is the protocol-side KYC step; pending
37
+ * EIP-712 signatures are tx-side leftover, not KYC.
38
+ */
39
+ async getOpenAccountRequirements(wallet, props) {
40
+ const tokensToRegister = new AddressSet(this.factory.getTokens()).has(props.tokenOutAddress) ? new AddressSet([props.tokenOutAddress]) : new AddressSet();
41
+ if (tokensToRegister.size === 0) return {
42
+ protocol: "securitize",
43
+ factory: this.factory.address,
44
+ securitizeTokensToRegister: [],
45
+ tokensToRegister: [],
46
+ requiredSignatures: []
47
+ };
48
+ const [investorData] = await this.#sdk.rwa.getInvestorData(wallet, [this.factory.address]);
49
+ const registredTokens = new AddressSet(investorData.registeredTokens);
50
+ const signedTokens = new AddressSet(investorData.cachedSignatures.map((s) => s.token));
51
+ const unsignedTokens = tokensToRegister.difference(signedTokens);
52
+ const securitizeTokensToRegister = tokensToRegister.difference(registredTokens);
53
+ const requiredSignatures = investorData.registerVaultMessages.filter((m) => unsignedTokens.has(m.message.token));
54
+ return {
55
+ protocol: "securitize",
56
+ factory: this.factory.address,
57
+ securitizeTokensToRegister: Array.from(securitizeTokensToRegister),
58
+ tokensToRegister: Array.from(tokensToRegister),
59
+ requiredSignatures
27
60
  };
28
- const req = await factory.getOpenAccountRequirements(wallet, { tokenOutAddress: targetCollateral });
61
+ }
62
+ isRegistered(requirements) {
63
+ return requirements.securitizeTokensToRegister.length === 0;
64
+ }
65
+ /**
66
+ * A required signature is omitted when `providedArgs.signaturesToCache`
67
+ * already carries a signature for the same token: the transaction caches it
68
+ * on-chain as part of the operation.
69
+ */
70
+ getMissingRequirements(requirements, providedArgs) {
71
+ const providedTokens = new AddressSet((providedArgs?.signaturesToCache ?? []).map((s) => s.token));
72
+ const requiredSignatures = requirements.requiredSignatures.filter((message) => !providedTokens.has(message.message.token));
73
+ if (requiredSignatures.length === 0) return;
29
74
  return {
30
- eligible: !req || req.securitizeTokensToRegister.length === 0,
31
- token: req?.securitizeTokensToRegister[0] ?? targetCollateral
75
+ protocol: "securitize",
76
+ requiredSignatures
32
77
  };
33
78
  }
34
79
  };
@@ -1,5 +1,4 @@
1
1
  import { AddressMap } from "../../../utils/AddressMap.js";
2
- import { AddressSet } from "../../../utils/AddressSet.js";
3
2
  import "../../../utils/index.js";
4
3
  import { BaseContract } from "../../../base/BaseContract.js";
5
4
  import "../../../base/index.js";
@@ -11,7 +10,6 @@ import { decodeAbiParameters } from "viem";
11
10
  //#region src/onchain/market/rwa/securitize/SecuritizeRWAFactory.ts
12
11
  const abi = iSecuritizeRWAFactoryAbi;
13
12
  var SecuritizeRWAFactory = class extends BaseContract {
14
- #sdk;
15
13
  #investorCache = new AddressMap();
16
14
  degenNFT;
17
15
  owner;
@@ -23,7 +21,6 @@ var SecuritizeRWAFactory = class extends BaseContract {
23
21
  name: "SecuritizeRWAFactory",
24
22
  abi
25
23
  });
26
- this.#sdk = sdk;
27
24
  const decoded = decodeAbiParameters([
28
25
  {
29
26
  name: "owner",
@@ -184,40 +181,6 @@ var SecuritizeRWAFactory = class extends BaseContract {
184
181
  });
185
182
  }
186
183
  /**
187
- * {@inheritDoc IRWAFactory.getOpenAccountRequirements}
188
- */
189
- async getOpenAccountRequirements(investor, props) {
190
- const [investorData] = await this.#sdk.rwa.getInvestorData(investor, [this.address]);
191
- const tokensToRegister = new AddressSet([props.tokenOutAddress]);
192
- const registredTokens = new AddressSet(investorData.registeredTokens);
193
- const signedTokens = new AddressSet(investorData.cachedSignatures.map((s) => s.token));
194
- const unsignedTokens = tokensToRegister.difference(signedTokens);
195
- const securitizeTokensToRegister = tokensToRegister.difference(registredTokens);
196
- const requiredSignatures = investorData.registerVaultMessages.filter((m) => unsignedTokens.has(m.message.token));
197
- return {
198
- type: RWA_FACTORY_SECURITIZE,
199
- securitizeTokensToRegister: Array.from(securitizeTokensToRegister),
200
- tokensToRegister: Array.from(tokensToRegister),
201
- requiredSignatures
202
- };
203
- }
204
- /**
205
- * {@inheritDoc IRWAFactory.getMissingRequirements}
206
- *
207
- * A required signature is omitted when `providedArgs.signaturesToCache`
208
- * already carries a signature for the same token: the transaction caches it
209
- * on-chain as part of the operation.
210
- */
211
- getMissingRequirements(requirements, providedArgs) {
212
- const providedTokens = new AddressSet((providedArgs?.signaturesToCache ?? []).map((s) => s.token));
213
- const requiredSignatures = requirements.requiredSignatures.filter((message) => !providedTokens.has(message.message.token));
214
- if (requiredSignatures.length === 0) return;
215
- return {
216
- type: RWA_FACTORY_SECURITIZE,
217
- requiredSignatures
218
- };
219
- }
220
- /**
221
184
  * {@inheritDoc IRWAFactory.openCreditAccount}
222
185
  */
223
186
  openCreditAccount(creditManager, calls, args) {
@@ -37,12 +37,18 @@ var MultichainOpportunitiesService = class extends MultichainConstruct {
37
37
  *
38
38
  * See {@link MultichainOpportunitiesService.getPool}.
39
39
  **/
40
- async getStrategy(key, wallet) {
40
+ async getStrategy(key) {
41
41
  return this.queryChain({
42
42
  network: key.chainId,
43
- run: (sdk) => sdk.opportunities.getStrategy(key, wallet)
43
+ run: (sdk) => sdk.opportunities.getStrategy(key)
44
44
  });
45
45
  }
46
+ /**
47
+ * {@inheritDoc OpportunitiesService.isEligibleForStrategy}
48
+ **/
49
+ async isEligibleForStrategy(key, wallet) {
50
+ return this.sdk.chain(key.chainId).opportunities.isEligibleForStrategy(key, wallet);
51
+ }
46
52
  };
47
53
  //#endregion
48
54
  export { MultichainOpportunitiesService };
@@ -36,22 +36,34 @@ var OpportunitiesService = class extends SDKConstruct {
36
36
  * A single strategy opportunity plus the rate curve of the pool it borrows
37
37
  * from and the price feeds its liquidation price depends on.
38
38
  *
39
- * @param wallet - When given, `kyc` says whether this wallet must register
40
- * with the strategy's KYC provider first; `null` otherwise.
39
+ * `kyc` is the strategy's KYC gate, independent of any wallet.
41
40
  *
42
41
  * @throws If the credit manager is unknown, or does not currently offer a
43
42
  * strategy.
44
43
  **/
45
- async getStrategy(key, wallet) {
44
+ async getStrategy(key) {
46
45
  const suite = this.sdk.marketRegister.findCreditManager(key.creditManager);
47
46
  const detail = suite.strategyOpportunityDetail();
48
47
  if (!detail) throw new Error(`credit manager ${key.creditManager} does not currently offer a strategy`);
49
- const kyc = wallet ? await suite.kycRequirement(wallet, detail.targetCollateral.address) : null;
48
+ const kyc = await suite.kycRequirement(detail.targetCollateral.address);
50
49
  return {
51
50
  ...detail,
52
51
  kyc
53
52
  };
54
53
  }
54
+ /**
55
+ * Whether `wallet` may open this strategy today: `true` when it is not
56
+ * KYC-gated or the wallet already passed the gate.
57
+ *
58
+ * @throws If the credit manager is unknown, or does not currently offer a
59
+ * strategy.
60
+ **/
61
+ async isEligibleForStrategy(key, wallet) {
62
+ const suite = this.sdk.marketRegister.findCreditManager(key.creditManager);
63
+ const opportunity = suite.strategyOpportunity();
64
+ if (!opportunity) throw new Error(`credit manager ${key.creditManager} does not currently offer a strategy`);
65
+ return suite.isEligibleForStrategy(wallet, opportunity.targetCollateral.address);
66
+ }
55
67
  };
56
68
  //#endregion
57
69
  export { OpportunitiesService };
@@ -1,7 +1,7 @@
1
1
  import { hexEq } from "../../utils/hex.js";
2
2
  import { AbstractAdapterContract } from "../../market/adapters/contracts/AbstractAdapter.js";
3
3
  import { CreditFacadeV310Contract } from "../../market/credit/CreditFacadeV310Contract.js";
4
- import { RWA_FACTORY_SECURITIZE } from "../../../model/rwa.js";
4
+ import "../../../model/rwa.js";
5
5
  import "../../../model/index.js";
6
6
  import { isRWAFactory } from "../../market/rwa/types.js";
7
7
  import { classifyInnerOperations } from "./classifyInnerOperations.js";
@@ -32,7 +32,7 @@ function parseSecuritizeOperationCalldata(sdk, factory, calldata) {
32
32
  const { rawArgs } = parsed;
33
33
  const innerCalls = rawArgs.calls ?? [];
34
34
  const args = {
35
- type: RWA_FACTORY_SECURITIZE,
35
+ protocol: "securitize",
36
36
  tokensToRegister: [...rawArgs.tokensToRegister ?? []],
37
37
  signaturesToCache: [...rawArgs.signaturesToCache ?? []]
38
38
  };
@@ -32,7 +32,8 @@ async function checkCreditOperation(args) {
32
32
  minDebt: suite.creditFacade.minDebt,
33
33
  maxDebt: suite.creditFacade.maxDebt,
34
34
  underlying,
35
- allowZero: !isOpening
35
+ allowZero: !isOpening,
36
+ maxBorrowAmount: suite.maxBorrowAmount()
36
37
  }),
37
38
  ...checkDraw(suite, preview, underlying),
38
39
  ...checkObtained(suite, preview),
@@ -49,7 +50,7 @@ async function checkCreditOperation(args) {
49
50
  preview,
50
51
  sender,
51
52
  blockNumber
52
- }), preview.operation === "RWAOpenCreditAccount" ? checkRWAOpening({
53
+ }), preview.operation === "OpenCreditAccount" || preview.operation === "RWAOpenCreditAccount" ? checkRWAOpening({
53
54
  sdk,
54
55
  preview,
55
56
  sender
@@ -15,11 +15,11 @@ import "../checks/index.js";
15
15
  function checkDraw(suite, preview, underlying) {
16
16
  const drawn = preview.operation === "AdjustCreditAccount" ? preview.totalDebtChange.value : preview.totalDebt.value;
17
17
  if (drawn <= 0n) return [];
18
- const { value, limit } = suite.maxBorrowAmount();
18
+ const maxBorrowAmount = suite.maxBorrowAmount();
19
19
  return checkBorrowLimit({
20
20
  requested: drawn,
21
- available: value,
22
- limit,
21
+ available: maxBorrowAmount.amount.value,
22
+ limit: maxBorrowAmount.limit,
23
23
  underlying
24
24
  });
25
25
  }
@@ -5,24 +5,24 @@ import { toToken } from "../helpers/token.js";
5
5
  import "../helpers/index.js";
6
6
  //#region src/onchain/validation/bundles/checkRWAOpenRequirements.ts
7
7
  /**
8
- * The RWA factory is satisfied that `wallet` may open on `token` with the
8
+ * The degen NFT is satisfied that `wallet` may open on `token` with the
9
9
  * registration args already on the transaction.
10
10
  */
11
11
  async function checkRWAOpenRequirements(input) {
12
12
  const { sdk, wallet, creditManager, token, providedArgs } = input;
13
13
  try {
14
- const requirements = await sdk.accounts.getOpenAccountRequirements(wallet, creditManager, { tokenOutAddress: token });
15
- if (!requirements) return [];
16
- const { rwaFactory } = sdk.marketRegister.findByCreditManager(creditManager);
17
- if (!rwaFactory) throw new Error(`no RWA factory for credit manager ${creditManager}`);
18
- const missing = rwaFactory.getMissingRequirements(requirements, providedArgs);
19
- if (!missing && requirements.securitizeTokensToRegister.length === 0) return [];
14
+ const nft = await sdk.marketRegister.findCreditManager(creditManager).degenNFT();
15
+ if (!nft) return [];
16
+ const requirements = await nft.getOpenAccountRequirements(wallet, { tokenOutAddress: token });
17
+ const missing = nft.getMissingRequirements(requirements, providedArgs);
18
+ if (!missing && nft.isRegistered(requirements)) return [];
20
19
  return [rwaOpenRequirementsNotMet({
21
20
  token: toToken(sdk, token),
22
21
  creditManager,
23
- factory: rwaFactory.address,
22
+ protocol: nft.protocol,
23
+ registrationLink: nft.registrationLink,
24
24
  requirements,
25
- ...missing === void 0 ? {} : { missing }
25
+ missing
26
26
  })];
27
27
  } catch (cause) {
28
28
  return [unexpectedFailure(cause, "read the RWA opening requirements")];
@@ -2,21 +2,22 @@ import { AddressSet } from "../../utils/AddressSet.js";
2
2
  import { checkRWAOpenRequirements } from "./checkRWAOpenRequirements.js";
3
3
  //#region src/onchain/validation/bundles/checkRWAOpening.ts
4
4
  /**
5
- * Per factory-gated token among `collateralAdded ∪ quotas`, whether the
5
+ * Per KYC-gated token among `collateralAdded ∪ quotas`, whether the
6
6
  * borrower still has to register or sign before this opening can land.
7
7
  */
8
8
  async function checkRWAOpening(input) {
9
9
  const { sdk, preview, sender } = input;
10
- const { rwaFactory } = sdk.marketRegister.findByCreditManager(preview.creditManager);
11
- if (!rwaFactory) return [];
12
- const gated = new AddressSet(rwaFactory.getTokens());
10
+ const nft = await sdk.marketRegister.findCreditManager(preview.creditManager).degenNFT();
11
+ if (!nft) return [];
12
+ const gated = new AddressSet(await nft.getTokens());
13
13
  const candidates = new AddressSet([...preview.collateralAdded.map((a) => a.token.address), ...preview.quotas.map((q) => q.token.address)]);
14
+ const providedArgs = preview.operation === "RWAOpenCreditAccount" ? preview.rwaArgs : void 0;
14
15
  return (await Promise.all([...candidates].filter((token) => gated.has(token)).map((token) => checkRWAOpenRequirements({
15
16
  sdk,
16
17
  wallet: sender,
17
18
  creditManager: preview.creditManager,
18
19
  token,
19
- providedArgs: preview.rwaArgs
20
+ providedArgs
20
21
  })))).flat();
21
22
  }
22
23
  //#endregion
@@ -1,11 +1,11 @@
1
1
  import { toToken } from "./helpers/token.js";
2
2
  import "./helpers/index.js";
3
3
  import { checkDebtLimits } from "./checks/checkDebtLimits.js";
4
+ import { checkQuotaCount } from "./checks/checkQuotaCount.js";
4
5
  import "./checks/index.js";
5
6
  import { checkAccountQuotas } from "./bundles/checkAccountQuotas.js";
6
7
  import { checkHealthFactors } from "./bundles/checkHealthFactors.js";
7
8
  import { checkMarket } from "./bundles/checkMarket.js";
8
- import { checkPoolOperation } from "./bundles/checkPoolOperation.js";
9
9
  //#region src/onchain/validation/checkSimulation.ts
10
10
  /**
11
11
  * Whether a simulated operation clears the caller's own thresholds.
@@ -27,19 +27,12 @@ import { checkPoolOperation } from "./bundles/checkPoolOperation.js";
27
27
  * touched. The engine performed all three during the walk, so a simulation that
28
28
  * came back `ok` has already passed them.
29
29
  *
30
- * A pool operation has no account to weigh, so what is left is the pool's own
31
- * state — which the engine does not read either.
30
+ * A credit account only, opened or adjusted: a pool operation has no account
31
+ * to weigh, and the three things its own state decides are read by `prepare`
32
+ * before it answers. An opening names its quotas `averageQuota` — the branch
33
+ * the planner already weighed it as.
32
34
  */
33
35
  function checkSimulation(sdk, input, options = {}) {
34
- if ("pool" in input) {
35
- const { pool, state, isDeposit } = input;
36
- return checkPoolOperation({
37
- sdk,
38
- pool,
39
- isDeposit,
40
- tokenOut: state.tokenOut
41
- });
42
- }
43
36
  const { state } = input;
44
37
  const suite = sdk.marketRegister.findCreditManager(state.creditManager);
45
38
  return [
@@ -49,9 +42,13 @@ function checkSimulation(sdk, input, options = {}) {
49
42
  minDebt: suite.creditFacade.minDebt,
50
43
  maxDebt: suite.creditFacade.maxDebt,
51
44
  underlying: toToken(sdk, suite.market.pool.underlying),
52
- allowZero: true
45
+ allowZero: true,
46
+ maxBorrowAmount: suite.maxBorrowAmount()
53
47
  }),
54
- ...checkAccountQuotas(suite, state),
48
+ ..."averageQuota" in state ? checkQuotaCount({
49
+ count: state.averageQuota.filter((q) => q.balance > 0n).length,
50
+ max: suite.creditManager.maxEnabledTokens
51
+ }) : checkAccountQuotas(suite, state),
55
52
  ...checkHealthFactors(state, options)
56
53
  ];
57
54
  }
@@ -5,12 +5,13 @@ import "../helpers/index.js";
5
5
  //#region src/onchain/validation/checks/checkDebtLimits.ts
6
6
  /** A debt the facade would revert on. */
7
7
  function checkDebtLimits(args) {
8
- const { debt, minDebt, maxDebt, underlying, allowZero } = args;
8
+ const { debt, minDebt, maxDebt, underlying, allowZero, maxBorrowAmount } = args;
9
9
  if (!(debt > maxDebt || debt < minDebt && !(allowZero && debt === 0n))) return [];
10
10
  return [debtOutOfRange({
11
11
  requested: amountOf(underlying, debt),
12
12
  minDebt: amountOf(underlying, minDebt),
13
- maxDebt: amountOf(underlying, maxDebt)
13
+ maxDebt: amountOf(underlying, maxDebt),
14
+ maxBorrowAmount
14
15
  })];
15
16
  }
16
17
  //#endregion
@@ -73,9 +73,9 @@ async function openTx(sdk, request) {
73
73
  async function openRwaOptions(sdk, request) {
74
74
  if (!request.targetToken) return;
75
75
  const requirements = await sdk.accounts.getOpenAccountRequirements(request.wallet, request.creditManager, { tokenOutAddress: request.targetToken });
76
- if (!requirements) return;
76
+ if (requirements?.protocol !== "securitize") return;
77
77
  return {
78
- type: requirements.type,
78
+ protocol: "securitize",
79
79
  tokensToRegister: requirements.tokensToRegister,
80
80
  signaturesToCache: request.signaturesToCache ?? []
81
81
  };
@@ -1,4 +1,4 @@
1
- import { creditAccountNotEmpty, creditAccountNotFound, emptyOpenTakesNothing, noStrategyTargetCollateral, unexpectedFailure } from "../model/errors/prepare-errors.js";
1
+ import { creditAccountNotEmpty, creditAccountNotFound, noStrategyTargetCollateral, unexpectedFailure } from "../model/errors/prepare-errors.js";
2
2
  import { AllSourcesFailedError } from "./errors/AllSourcesFailedError.js";
3
3
  import { SourceChainMismatchError } from "./errors/SourceChainMismatchError.js";
4
4
  import { assertSameChains } from "./errors/assertSameChains.js";
@@ -27,4 +27,4 @@ import { PreviewNamespace } from "./preview/PreviewNamespace.js";
27
27
  import "./preview/index.js";
28
28
  import { DEFAULT_MAX_STATE_AGE, GearboxSDK } from "./GearboxSDK.js";
29
29
  import "./types.js";
30
- export { AbstractNamespace, AllSourcesFailedError, AnalyticsNamespace, DEFAULT_MAX_OFFCHAIN_LAG, DEFAULT_MAX_STATE_AGE, ExecuteApi, GearboxSDK, LiquidationsNamespace, MissingSourceError, NoSourceServedError, OpportunitiesNamespace, PositionsNamespace, PrepareApi, PreviewNamespace, SourceChainMismatchError, SourceUnavailableError, assertSameChains, creditAccountNotEmpty, creditAccountNotFound, emptyOpenTakesNothing, everyChainFailed, filterResponse, mergeChainList, mergeChainOne, noStrategyTargetCollateral, unexpectedFailure };
30
+ export { AbstractNamespace, AllSourcesFailedError, AnalyticsNamespace, DEFAULT_MAX_OFFCHAIN_LAG, DEFAULT_MAX_STATE_AGE, ExecuteApi, GearboxSDK, LiquidationsNamespace, MissingSourceError, NoSourceServedError, OpportunitiesNamespace, PositionsNamespace, PrepareApi, PreviewNamespace, SourceChainMismatchError, SourceUnavailableError, assertSameChains, creditAccountNotEmpty, creditAccountNotFound, everyChainFailed, filterResponse, mergeChainList, mergeChainOne, noStrategyTargetCollateral, unexpectedFailure };
@@ -70,15 +70,21 @@ var OpportunitiesNamespace = class extends AbstractNamespace {
70
70
  /**
71
71
  * {@inheritDoc IOpportunitiesBase.getStrategy}
72
72
  **/
73
- async getStrategy(key, wallet) {
73
+ async getStrategy(key) {
74
74
  return this.merged("get strategy opportunity", {
75
75
  chainIds: [key.chainId],
76
- fromChain: (source) => source.getStrategy(key, wallet),
77
- fromBackend: (source) => source.getStrategy(key, wallet),
76
+ fromChain: (source) => source.getStrategy(key),
77
+ fromBackend: (source) => source.getStrategy(key),
78
78
  merge: this.merge.strategy
79
79
  });
80
80
  }
81
81
  /**
82
+ * {@inheritDoc IOpportunitiesOnchainOnly.isEligibleForStrategy}
83
+ **/
84
+ async isEligibleForStrategy(key, wallet) {
85
+ return this.onchain.isEligibleForStrategy(key, wallet);
86
+ }
87
+ /**
82
88
  * {@inheritDoc IOpportunitiesBase.filter}
83
89
  **/
84
90
  filter(response, filter) {
@@ -1,9 +1,10 @@
1
1
  import { hexEq } from "../../onchain/utils/hex.js";
2
2
  import { MultichainConstruct } from "../../onchain/base/MultichainConstruct.js";
3
- import { creditAccountNotEmpty, creditAccountNotFound, emptyOpenTakesNothing, noRecordedIntent, noStrategyTargetCollateral, unexpectedFailure, unsupportedTokenPair } from "../../model/errors/prepare-errors.js";
3
+ import { creditAccountNotEmpty, creditAccountNotFound, noRecordedIntent, noStrategyTargetCollateral, unexpectedFailure, unsupportedTokenPair } from "../../model/errors/prepare-errors.js";
4
4
  import { sdkErr, sdkOk } from "../../model/result.js";
5
5
  import "../../model/index.js";
6
6
  import { toToken } from "../../onchain/validation/helpers/token.js";
7
+ import { checkPoolOperation } from "../../onchain/validation/bundles/checkPoolOperation.js";
7
8
  import { toCreditAccountSlice } from "../../onchain/accounts/intents/utils/credit-account-slice.js";
8
9
  import { CreditAccountOperationsService } from "../../onchain/accounts/intents/index.js";
9
10
  import "../../onchain/index.js";
@@ -84,6 +85,13 @@ var PrepareApi = class extends MultichainConstruct {
84
85
  tokenIn,
85
86
  tokenOut
86
87
  });
88
+ const [refusal] = checkPoolOperation({
89
+ sdk: chain,
90
+ pool: pool.pool,
91
+ isDeposit: true,
92
+ tokenOut: state.tokenOut
93
+ });
94
+ if (refusal) return sdkErr(refusal);
87
95
  const call = pools.addLiquidity({
88
96
  collateral: {
89
97
  token: state.tokenIn.token.address,
@@ -120,6 +128,13 @@ var PrepareApi = class extends MultichainConstruct {
120
128
  tokenIn,
121
129
  tokenOut
122
130
  });
131
+ const [refusal] = checkPoolOperation({
132
+ sdk: chain,
133
+ pool: pool.pool,
134
+ isDeposit: false,
135
+ tokenOut: state.tokenOut
136
+ });
137
+ if (refusal) return sdkErr(refusal);
123
138
  const { calls } = pools.removeLiquidity({
124
139
  pool: pool.pool,
125
140
  amount: params.amount,
@@ -154,6 +169,13 @@ var PrepareApi = class extends MultichainConstruct {
154
169
  tokenIn,
155
170
  tokenOut
156
171
  });
172
+ const [refusal] = checkPoolOperation({
173
+ sdk: chain,
174
+ pool: pool.pool,
175
+ isDeposit: false,
176
+ tokenOut: state.tokenOut
177
+ });
178
+ if (refusal) return sdkErr(refusal);
157
179
  const { calls } = pools.removeLiquidity({
158
180
  pool: pool.pool,
159
181
  amount: params.amount,
@@ -179,14 +201,11 @@ var PrepareApi = class extends MultichainConstruct {
179
201
  try {
180
202
  const sdk = await this.#chain(strategy.chainId);
181
203
  const at = stateBlock(sdk);
182
- if (params.empty) {
183
- if (params.collateral.length > 0 || params.creditAccount || params.leverage !== 0n) return sdkErr(emptyOpenTakesNothing());
184
- return opened(await service(sdk).openStrategyIntent({
185
- sdk,
186
- creditManager: strategy.creditManager,
187
- empty: true
188
- }), at);
189
- }
204
+ if (params.empty) return opened(await service(sdk).openStrategyIntent({
205
+ sdk,
206
+ creditManager: strategy.creditManager,
207
+ empty: true
208
+ }), at);
190
209
  const targetToken = params.targetToken ?? sdk.marketRegister.findCreditManager(strategy.creditManager).strategyTargetCollateral;
191
210
  if (!targetToken) return sdkErr(noStrategyTargetCollateral(strategy.creditManager));
192
211
  let creditAccount;
@@ -1,5 +1,5 @@
1
- import { creditAccountNotEmpty, creditAccountNotFound, emptyOpenTakesNothing, noStrategyTargetCollateral, unexpectedFailure } from "../../model/errors/prepare-errors.js";
1
+ import { creditAccountNotEmpty, creditAccountNotFound, noStrategyTargetCollateral, unexpectedFailure } from "../../model/errors/prepare-errors.js";
2
2
  import "../../model/index.js";
3
3
  import { PrepareApi } from "./PrepareApi.js";
4
4
  import "./types.js";
5
- export { PrepareApi, creditAccountNotEmpty, creditAccountNotFound, emptyOpenTakesNothing, noStrategyTargetCollateral, unexpectedFailure };
5
+ export { PrepareApi, creditAccountNotEmpty, creditAccountNotFound, noStrategyTargetCollateral, unexpectedFailure };
@@ -2,6 +2,6 @@ import { IGearboxError } from "./base.js";
2
2
  import { CreditAccountFrozenError, LiquidatorNotEligibleError, NotEmergencyLiquidatorError, creditAccountFrozen, liquidatorNotEligible, notEmergencyLiquidator } from "./liquidation-errors.js";
3
3
  import { BorrowLimitCause, CreditManagerPausedError, DebtOutOfRangeError, ForbiddenTokenError, InsufficientAllowanceError, InsufficientBalanceError, InsufficientCollateralError, InsufficientPoolLiquidityError, LeverageOutOfRangeError, MarketExpiredError, PoolPausedError, PoolSunsetError, QuotaCountExceededError, QuotaLimitReachedError, RWAOpenRequirementsError, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, rwaOpenRequirementsNotMet } from "./operation-errors.js";
4
4
  import { UnpriceableTokenError, unpriceableTokenError } from "./oracle-errors.js";
5
- import { CreditAccountNotEmptyError, CreditAccountNotFoundError, EmptyOpenTakesNothingError, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, UnexpectedFailureError, UnsupportedCollateralTokenError, UnsupportedTokenPairError, WithdrawalInProgressError, creditAccountNotEmpty, creditAccountNotFound, emptyOpenTakesNothing, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, unexpectedFailure, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress } from "./prepare-errors.js";
5
+ import { CreditAccountNotEmptyError, CreditAccountNotFoundError, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, UnexpectedFailureError, UnsupportedCollateralTokenError, UnsupportedTokenPairError, WithdrawalInProgressError, creditAccountNotEmpty, creditAccountNotFound, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, unexpectedFailure, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress } from "./prepare-errors.js";
6
6
  import { InvalidDelayedIntentError, MalformedTransactionError, PoolOperationPreviewError, UnsupportedOperationError, UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedZapperFunctionError, malformedTransaction } from "./preview-errors.js";
7
- export { BorrowLimitCause, CreditAccountFrozenError, CreditAccountNotEmptyError, CreditAccountNotFoundError, CreditManagerPausedError, DebtOutOfRangeError, EmptyOpenTakesNothingError, ForbiddenTokenError, IGearboxError, InsufficientAllowanceError, InsufficientBalanceError, InsufficientCollateralError, InsufficientPoolLiquidityError, InvalidDelayedIntentError, LeverageOutOfRangeError, LiquidatorNotEligibleError, MalformedTransactionError, MarketExpiredError, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, NotEmergencyLiquidatorError, PoolOperationPreviewError, PoolPausedError, PoolSunsetError, QuotaCountExceededError, QuotaLimitReachedError, RWAOpenRequirementsError, UnexpectedFailureError, UnpriceableTokenError, UnsupportedCollateralTokenError, UnsupportedOperationError, UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedTokenPairError, UnsupportedZapperFunctionError, WithdrawalInProgressError, creditAccountFrozen, creditAccountNotEmpty, creditAccountNotFound, creditManagerPaused, debtOutOfRange, emptyOpenTakesNothing, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, liquidatorNotEligible, malformedTransaction, marketExpired, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, notEmergencyLiquidator, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, rwaOpenRequirementsNotMet, unexpectedFailure, unpriceableTokenError, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress };
7
+ export { BorrowLimitCause, CreditAccountFrozenError, CreditAccountNotEmptyError, CreditAccountNotFoundError, CreditManagerPausedError, DebtOutOfRangeError, ForbiddenTokenError, IGearboxError, InsufficientAllowanceError, InsufficientBalanceError, InsufficientCollateralError, InsufficientPoolLiquidityError, InvalidDelayedIntentError, LeverageOutOfRangeError, LiquidatorNotEligibleError, MalformedTransactionError, MarketExpiredError, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, NotEmergencyLiquidatorError, PoolOperationPreviewError, PoolPausedError, PoolSunsetError, QuotaCountExceededError, QuotaLimitReachedError, RWAOpenRequirementsError, UnexpectedFailureError, UnpriceableTokenError, UnsupportedCollateralTokenError, UnsupportedOperationError, UnsupportedPoolFunctionError, UnsupportedTargetError, UnsupportedTokenPairError, UnsupportedZapperFunctionError, WithdrawalInProgressError, creditAccountFrozen, creditAccountNotEmpty, creditAccountNotFound, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, liquidatorNotEligible, malformedTransaction, marketExpired, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, notEmergencyLiquidator, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, rwaOpenRequirementsNotMet, unexpectedFailure, unpriceableTokenError, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress };
@@ -1,6 +1,8 @@
1
1
  import { Bps, Token, TokenAmount } from "../primitives.js";
2
2
  import { IGearboxError } from "./base.js";
3
- import { RWAMissingOpenAccountRequirements, RWAOpenAccountRequirements } from "../rwa.js";
3
+ import { RWAMissingOpenAccountRequirements, RWAOpenAccountRequirements, RWAProtocol } from "../rwa.js";
4
+ import { MaxBorrowAmount } from "../../onchain/market/credit/types.js";
5
+ import "../../onchain/index.js";
4
6
  import { Address } from "viem";
5
7
  //#region src/model/errors/operation-errors.d.ts
6
8
  /**
@@ -82,6 +84,8 @@ interface DebtOutOfRangeError extends IGearboxError {
82
84
  requested: TokenAmount;
83
85
  minDebt: TokenAmount;
84
86
  maxDebt: TokenAmount;
87
+ /** What the market will really lend; absent where the raiser only throws. */
88
+ maxBorrowAmount?: MaxBorrowAmount;
85
89
  }
86
90
  /** {@inheritDoc DebtOutOfRangeError} */
87
91
  declare function debtOutOfRange(args: Omit<DebtOutOfRangeError, "code" | "message">): DebtOutOfRangeError;
@@ -197,17 +201,19 @@ interface InsufficientAllowanceError extends IGearboxError {
197
201
  /** {@inheritDoc InsufficientAllowanceError} */
198
202
  declare function insufficientAllowance(args: Omit<InsufficientAllowanceError, "code" | "message">): InsufficientAllowanceError;
199
203
  /**
200
- * The RWA factory still wants something from the borrower before this token
204
+ * The RWA protocol still wants something from the borrower before this token
201
205
  * can be opened on.
202
206
  **/
203
207
  interface RWAOpenRequirementsError extends IGearboxError {
204
208
  code: "rwaOpenRequirementsNotMet";
205
209
  token: Token;
206
210
  creditManager: Address;
207
- factory: Address;
211
+ protocol: RWAProtocol;
212
+ /** Where the wallet completes registration with {@link protocol}. */
213
+ registrationLink: string;
208
214
  /** Always present on the error. */
209
215
  requirements: RWAOpenAccountRequirements;
210
- /** Absent when only issuer-side registration is pending. */
216
+ /** Absent when only issuer-side registration is pending (or Midas greenlist). */
211
217
  missing?: RWAMissingOpenAccountRequirements;
212
218
  }
213
219
  /** {@inheritDoc RWAOpenRequirementsError} */
@@ -96,15 +96,6 @@ interface CreditAccountNotEmptyError extends IGearboxError {
96
96
  }
97
97
  /** {@inheritDoc CreditAccountNotEmptyError} */
98
98
  declare function creditAccountNotEmpty(creditAccount: Address): CreditAccountNotEmptyError;
99
- /**
100
- * An empty opening was asked for with something to open it with: collateral to
101
- * spend, an account to reuse, or a leverage to reach.
102
- **/
103
- interface EmptyOpenTakesNothingError extends IGearboxError {
104
- code: "emptyOpenTakesNothing";
105
- }
106
- /** {@inheritDoc EmptyOpenTakesNothingError} */
107
- declare function emptyOpenTakesNothing(): EmptyOpenTakesNothingError;
108
99
  /**
109
100
  * The SDK could not answer at all: a read that failed, a chain it is not
110
101
  * connected to, a market or token address it knows nothing about, a contract
@@ -128,4 +119,4 @@ interface UnexpectedFailureError extends IGearboxError {
128
119
  **/
129
120
  declare function unexpectedFailure(thrown: unknown, action?: string): UnexpectedFailureError;
130
121
  //#endregion
131
- export { CreditAccountNotEmptyError, CreditAccountNotFoundError, EmptyOpenTakesNothingError, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, UnexpectedFailureError, UnsupportedCollateralTokenError, UnsupportedTokenPairError, WithdrawalInProgressError, creditAccountNotEmpty, creditAccountNotFound, emptyOpenTakesNothing, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, unexpectedFailure, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress };
122
+ export { CreditAccountNotEmptyError, CreditAccountNotFoundError, MultipleDelayedWithdrawalsError, NoDelayedRouteError, NoRecordedIntentError, NoStrategyTargetCollateralError, UnexpectedFailureError, UnsupportedCollateralTokenError, UnsupportedTokenPairError, WithdrawalInProgressError, creditAccountNotEmpty, creditAccountNotFound, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, unexpectedFailure, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress };