@gearbox-protocol/sdk 16.0.0-next.40 → 16.0.0-next.42

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 (49) hide show
  1. package/dist/cjs/model/errors.js +1 -0
  2. package/dist/cjs/model/index.js +1 -0
  3. package/dist/cjs/onchain/accounts/intents/open-strategy.js +1 -1
  4. package/dist/cjs/onchain/positions/PositionsService.js +1 -11
  5. package/dist/cjs/sdk/execute/ExecuteApi.js +4 -4
  6. package/dist/cjs/sdk/index.js +5 -0
  7. package/dist/cjs/sdk/prepare/PrepareApi.js +326 -93
  8. package/dist/cjs/sdk/prepare/errors.js +90 -0
  9. package/dist/cjs/sdk/prepare/index.js +5 -0
  10. package/dist/esm/dev/AccountOpener.js +1 -1
  11. package/dist/esm/dev/withdrawalUtils.js +1 -1
  12. package/dist/esm/model/errors.js +1 -0
  13. package/dist/esm/model/index.js +1 -0
  14. package/dist/esm/onchain/accounts/CreditAccountsServiceV310.js +2 -2
  15. package/dist/esm/onchain/accounts/intents/open-strategy.js +1 -1
  16. package/dist/esm/onchain/accounts/liquidations/LiquidationsService.js +1 -1
  17. package/dist/esm/onchain/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.js +1 -1
  18. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.js +1 -1
  19. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.js +1 -1
  20. package/dist/esm/onchain/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.js +1 -1
  21. package/dist/esm/onchain/base/TokensMeta.js +3 -3
  22. package/dist/esm/onchain/core/createAddressProvider.js +1 -1
  23. package/dist/esm/onchain/market/adapters/contracts/AccountMigratorAdapterContract.js +1 -1
  24. package/dist/esm/onchain/market/adapters/contracts/ERC4626AdapterContract.js +1 -1
  25. package/dist/esm/onchain/market/credit/CreditFacadeV310BaseContract.js +1 -1
  26. package/dist/esm/onchain/market/pool/PoolV310Contract.js +1 -1
  27. package/dist/esm/onchain/market/zapper/IETHZapperContract.js +1 -1
  28. package/dist/esm/onchain/market/zapper/ZapperContract.js +1 -1
  29. package/dist/esm/onchain/positions/PositionsService.js +1 -11
  30. package/dist/esm/onchain/utils/viem/simulateWithPriceUpdates.js +1 -1
  31. package/dist/esm/preview/simulate/simulatePoolOperation.js +1 -1
  32. package/dist/esm/preview/trace/extractTransfers.js +1 -1
  33. package/dist/esm/sdk/execute/ExecuteApi.js +4 -4
  34. package/dist/esm/sdk/index.js +2 -1
  35. package/dist/esm/sdk/prepare/PrepareApi.js +327 -94
  36. package/dist/esm/sdk/prepare/errors.js +86 -0
  37. package/dist/esm/sdk/prepare/index.js +2 -1
  38. package/dist/types/model/errors.d.ts +74 -0
  39. package/dist/types/model/index.d.ts +2 -1
  40. package/dist/types/onchain/accounts/intents/open-strategy.d.ts +3 -3
  41. package/dist/types/onchain/accounts/intents/types.d.ts +13 -14
  42. package/dist/types/onchain/positions/PositionsService.d.ts +0 -8
  43. package/dist/types/sdk/execute/types.d.ts +6 -6
  44. package/dist/types/sdk/index.d.ts +3 -2
  45. package/dist/types/sdk/prepare/PrepareApi.d.ts +11 -6
  46. package/dist/types/sdk/prepare/errors.d.ts +280 -0
  47. package/dist/types/sdk/prepare/index.d.ts +3 -2
  48. package/dist/types/sdk/prepare/types.d.ts +73 -46
  49. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
@@ -6,6 +6,7 @@ const require_model_charts_schema = require("./charts.schema.js");
6
6
  require("./curators.js");
7
7
  const require_model_curators_schema = require("./curators.schema.js");
8
8
  require("./delayed-intents.js");
9
+ require("./errors.js");
9
10
  const require_model_filters = require("./filters.js");
10
11
  const require_model_filters_schema = require("./filters.schema.js");
11
12
  const require_model_liquidations = require("./liquidations.js");
@@ -11,7 +11,7 @@ require("./utils/index.js");
11
11
  const NO_ACCOUNT = "0x0000000000000000000000000000000000000000";
12
12
  /**
13
13
  * Builds the state opening a leveraged position out of wallet collateral would
14
- * land in.
14
+ * reach.
15
15
  *
16
16
  * Debt follows from the target leverage against the supplied margin
17
17
  * (`debt = margin * (L - 1)`, `totalValue = margin * L`); the collateral and the
@@ -69,14 +69,6 @@ var PositionsService = class extends require_onchain_base_SDKConstruct.SDKConstr
69
69
  }
70
70
  /**
71
71
  * Returns delayed withdrawals of a strategy position
72
- *
73
- * Empty when this chain has no withdrawal compressor, or when the account's
74
- * credit manager has no withdrawal config — no config, no withdrawal, and
75
- * nothing to ask the chain about.
76
- *
77
- * The manager comes from the caller. It used to be read off the account
78
- * here, which cost an uncached read of the whole account to learn one field
79
- * every caller already knows.
80
72
  **/
81
73
  async getCurrentWithdrawals(props) {
82
74
  const { creditAccount, creditManager, blockNumber } = props;
@@ -85,9 +77,7 @@ var PositionsService = class extends require_onchain_base_SDKConstruct.SDKConstr
85
77
  pending: []
86
78
  };
87
79
  const compressor = this.sdk.withdrawalCompressor;
88
- if (!compressor) return empty;
89
- await compressor.loadWithdrawableAssets();
90
- if (compressor.getWithdrawableAssets(creditManager).length === 0) return empty;
80
+ if (!compressor?.getWithdrawableAssets(creditManager).length) return empty;
91
81
  const { priceOracle } = this.sdk.marketRegister.findByCreditManager(creditManager);
92
82
  return this.#toPositionWithdrawals(await compressor.getCurrentWithdrawals(creditAccount, blockNumber), priceOracle);
93
83
  }
@@ -12,7 +12,7 @@ var ExecuteApi = class {
12
12
  * {@inheritDoc IOpportunitiesExecute.buildTx}
13
13
  **/
14
14
  async buildTx(request) {
15
- if (!request.sim.ok) throw new Error(`cannot build a transaction from a failed ${request.kind} preparation`);
15
+ if (!request.sim.success) throw new Error(`cannot build a transaction from a failed ${request.kind} preparation`);
16
16
  const sdk = this.#chainOf(request.chainId);
17
17
  switch (request.kind) {
18
18
  case "pool": return poolTx(sdk, request);
@@ -23,7 +23,7 @@ var ExecuteApi = class {
23
23
  };
24
24
  function poolTx(sdk, request) {
25
25
  const { pool, wallet, sim } = request;
26
- const { tokenIn, tokenOut } = sim.state;
26
+ const { tokenIn, tokenOut } = sim.data.state;
27
27
  if (request.op === "deposit") {
28
28
  const meta = sdk.pools.getDepositMetadata(pool, tokenIn.token.address, tokenOut.token.address);
29
29
  const result = sdk.pools.addLiquidity({
@@ -50,7 +50,7 @@ function poolTx(sdk, request) {
50
50
  }
51
51
  async function openTx(sdk, request) {
52
52
  const { creditManager, wallet, collateral, ethAmount, sim } = request;
53
- const { state } = sim;
53
+ const { state } = sim.data;
54
54
  return sdk.accounts.openCA({
55
55
  creditManager,
56
56
  to: wallet,
@@ -83,7 +83,7 @@ async function openRwaOptions(sdk, request) {
83
83
  async function accountTx(sdk, request) {
84
84
  const account = await sdk.accounts.getCreditAccountData(request.creditAccount);
85
85
  if (!account) throw new Error(`credit account not found: ${request.creditAccount}`);
86
- return sdk.accounts.executeCaUpdate(account, request.sim.calls, { ethAmount: nativeValue(request.sim.operations) });
86
+ return sdk.accounts.executeCaUpdate(account, request.sim.data.calls, { ethAmount: nativeValue(request.sim.data.operations) });
87
87
  }
88
88
  /**
89
89
  * The coin the preparation asked the wallet for, which the facade wraps out of
@@ -13,6 +13,7 @@ const require_sdk_liquidations_LiquidationsNamespace = require("./liquidations/L
13
13
  require("./liquidations/index.js");
14
14
  const require_sdk_execute_ExecuteApi = require("./execute/ExecuteApi.js");
15
15
  require("./execute/index.js");
16
+ const require_sdk_prepare_errors = require("./prepare/errors.js");
16
17
  const require_sdk_prepare_PrepareApi = require("./prepare/PrepareApi.js");
17
18
  require("./prepare/index.js");
18
19
  const require_sdk_utils_filterResponse = require("./utils/filterResponse.js");
@@ -43,9 +44,13 @@ exports.PreviewNamespace = require_sdk_preview_PreviewNamespace.PreviewNamespace
43
44
  exports.SourceChainMismatchError = require_sdk_errors_SourceChainMismatchError.SourceChainMismatchError;
44
45
  exports.SourceUnavailableError = require_sdk_errors_SourceUnavailableError.SourceUnavailableError;
45
46
  exports.assertSameChains = require_sdk_errors_assertSameChains.assertSameChains;
47
+ exports.creditAccountNotFound = require_sdk_prepare_errors.creditAccountNotFound;
46
48
  exports.everyChainFailed = require_sdk_errors_everyChainFailed.everyChainFailed;
47
49
  exports.filterResponse = require_sdk_utils_filterResponse.filterResponse;
48
50
  exports.mergeChainList = require_sdk_utils_mergeChains.mergeChainList;
49
51
  exports.mergeChainOne = require_sdk_utils_mergeChains.mergeChainOne;
52
+ exports.noStrategyTargetCollateral = require_sdk_prepare_errors.noStrategyTargetCollateral;
50
53
  exports.raise = require_onchain_validation_refusal.raise;
51
54
  exports.refuse = require_onchain_validation_refusal.refuse;
55
+ exports.toPrepareError = require_sdk_prepare_errors.toPrepareError;
56
+ exports.unexpectedFailure = require_sdk_prepare_errors.unexpectedFailure;
@@ -1,11 +1,11 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_onchain_utils_hex = require("../../onchain/utils/hex.js");
3
3
  const require_onchain_base_MultichainConstruct = require("../../onchain/base/MultichainConstruct.js");
4
- const require_onchain_validation_refusal = require("../../onchain/validation/refusal.js");
5
4
  const require_onchain_validation_token = require("../../onchain/validation/token.js");
6
5
  const require_onchain_accounts_intents_utils_credit_account_slice = require("../../onchain/accounts/intents/utils/credit-account-slice.js");
7
6
  const require_onchain_accounts_intents_index = require("../../onchain/accounts/intents/index.js");
8
7
  require("../../onchain/index.js");
8
+ const require_sdk_prepare_errors = require("./errors.js");
9
9
  const require_sdk_prepare_withdrawable_collaterals = require("./withdrawable-collaterals.js");
10
10
  //#region src/sdk/prepare/PrepareApi.ts
11
11
  /**
@@ -18,8 +18,13 @@ const require_sdk_prepare_withdrawable_collaterals = require("./withdrawable-col
18
18
  *
19
19
  * A prepared operation names one chain, so it reads through
20
20
  * {@link MultichainConstruct.queryChain}: there is no second source to fall back
21
- * to, hence a chain the SDK does not cover, or one that fails the read, throws
22
- * rather than answering with empty metadata.
21
+ * to, hence a chain the SDK does not cover, or one that fails the read, is a
22
+ * failure of the whole request rather than a thinner answer.
23
+ *
24
+ * No method here throws. Every way a preparation can fail — the market's own
25
+ * refusals, the two the namespace decides itself, and anything the chain or the
26
+ * engine raises — comes back described in the envelope, see {@link PrepareError}.
27
+ * A caller writes one branch, not a branch and a `try`.
23
28
  **/
24
29
  var PrepareApi = class extends require_onchain_base_MultichainConstruct.MultichainConstruct {
25
30
  #ensureFresh;
@@ -32,29 +37,77 @@ var PrepareApi = class extends require_onchain_base_MultichainConstruct.Multicha
32
37
  return super.queryChain(props);
33
38
  }
34
39
  /**
40
+ * Runs a one-chain request whose answer is an envelope, describing whatever
41
+ * the chain, the read or the engine throws on the way rather than letting it
42
+ * escape.
43
+ *
44
+ * So every method below answers instead of rejecting, and a caller has one
45
+ * thing to branch on. "This cannot be done" and "we could not find out" are
46
+ * still told apart, by `error.code`: only the second is
47
+ * `unexpectedFailure`, and only it marks the chain failed in `meta`.
48
+ **/
49
+ async #answer(chainId, run) {
50
+ try {
51
+ return await this.queryChain({
52
+ network: chainId,
53
+ run
54
+ });
55
+ } catch (e) {
56
+ return {
57
+ data: {
58
+ success: false,
59
+ error: require_sdk_prepare_errors.unexpectedFailure(e)
60
+ },
61
+ meta: { chains: [failedChain(chainId, e)] }
62
+ };
63
+ }
64
+ }
65
+ /**
35
66
  * {@inheritDoc IOpportunitiesPrepare.finalize}
36
67
  **/
37
68
  async finalize(position, params) {
38
- return this.queryChain({
39
- network: position.chainId,
40
- run: async (sdk) => {
41
- const intent = resumable(params.intent ?? params.claimable.intent);
42
- if (!intent) return require_onchain_validation_refusal.refuse("noRecordedIntent", void 0);
43
- return service(sdk).finishIntent({
44
- intent,
45
- claimable: toClaimableWithdrawal(params.claimable),
46
- creditAccount: await slice(sdk, position.creditAccount),
47
- sdk,
48
- slippage: params.slippage,
49
- quotaReserve: params.quotaReserve
50
- });
51
- }
69
+ return this.#answer(position.chainId, async (sdk) => {
70
+ const intent = resumable(params.intent ?? params.claimable.intent);
71
+ if (!intent) return {
72
+ success: false,
73
+ error: require_sdk_prepare_errors.toPrepareError({
74
+ reason: "noRecordedIntent",
75
+ detail: void 0
76
+ })
77
+ };
78
+ const creditAccount = await slice(sdk, position.creditAccount);
79
+ if (!creditAccount) return {
80
+ success: false,
81
+ error: require_sdk_prepare_errors.creditAccountNotFound(position.creditAccount)
82
+ };
83
+ return planned(await service(sdk).finishIntent({
84
+ intent,
85
+ claimable: toClaimableWithdrawal(params.claimable),
86
+ creditAccount,
87
+ sdk,
88
+ slippage: params.slippage,
89
+ quotaReserve: params.quotaReserve
90
+ }));
52
91
  });
53
92
  }
54
93
  /**
55
94
  * {@inheritDoc IOpportunitiesPrepare.deposit}
56
95
  **/
57
96
  deposit(pool, params) {
97
+ try {
98
+ return this.#depositPlan(pool, params);
99
+ } catch (e) {
100
+ return {
101
+ success: false,
102
+ error: require_sdk_prepare_errors.unexpectedFailure(e)
103
+ };
104
+ }
105
+ }
106
+ /**
107
+ * The arithmetic behind {@link deposit}, which throws where the SDK holds
108
+ * nothing for the pool or the chain it was handed.
109
+ **/
110
+ #depositPlan(pool, params) {
58
111
  const chain = this.sdk.chain(pool.chainId);
59
112
  const { marketRegister, pools } = chain;
60
113
  const tokenIn = params.tokenIn ?? marketRegister.findByPool(pool.pool).pool.underlying;
@@ -77,16 +130,31 @@ var PrepareApi = class extends require_onchain_base_MultichainConstruct.Multicha
77
130
  });
78
131
  if (!call) return unroutable(chain, tokenIn, tokenOut);
79
132
  return {
80
- ok: true,
81
- operations: [],
82
- state,
83
- calls: call.calls
133
+ success: true,
134
+ data: {
135
+ operations: [],
136
+ state,
137
+ calls: call.calls
138
+ }
84
139
  };
85
140
  }
86
141
  /**
87
142
  * {@inheritDoc IOpportunitiesPrepare.withdraw}
88
143
  **/
89
144
  withdraw(pool, params) {
145
+ try {
146
+ return this.#withdrawPlan(pool, params);
147
+ } catch (e) {
148
+ return {
149
+ success: false,
150
+ error: require_sdk_prepare_errors.unexpectedFailure(e)
151
+ };
152
+ }
153
+ }
154
+ /**
155
+ * {@inheritDoc PrepareApi.depositPlan}
156
+ **/
157
+ #withdrawPlan(pool, params) {
90
158
  const chain = this.sdk.chain(pool.chainId);
91
159
  const { pools } = chain;
92
160
  const tokenIn = params.tokenIn ?? pool.pool;
@@ -107,16 +175,31 @@ var PrepareApi = class extends require_onchain_base_MultichainConstruct.Multicha
107
175
  mode: "withdraw"
108
176
  });
109
177
  return {
110
- ok: true,
111
- operations: [],
112
- state,
113
- calls
178
+ success: true,
179
+ data: {
180
+ operations: [],
181
+ state,
182
+ calls
183
+ }
114
184
  };
115
185
  }
116
186
  /**
117
187
  * {@inheritDoc IOpportunitiesPrepare.redeem}
118
188
  **/
119
189
  redeem(pool, params) {
190
+ try {
191
+ return this.#redeemPlan(pool, params);
192
+ } catch (e) {
193
+ return {
194
+ success: false,
195
+ error: require_sdk_prepare_errors.unexpectedFailure(e)
196
+ };
197
+ }
198
+ }
199
+ /**
200
+ * {@inheritDoc PrepareApi.depositPlan}
201
+ **/
202
+ #redeemPlan(pool, params) {
120
203
  const chain = this.sdk.chain(pool.chainId);
121
204
  const { pools } = chain;
122
205
  const tokenIn = params.tokenIn ?? pool.pool;
@@ -137,32 +220,34 @@ var PrepareApi = class extends require_onchain_base_MultichainConstruct.Multicha
137
220
  mode: "redeem"
138
221
  });
139
222
  return {
140
- ok: true,
141
- operations: [],
142
- state,
143
- calls
223
+ success: true,
224
+ data: {
225
+ operations: [],
226
+ state,
227
+ calls
228
+ }
144
229
  };
145
230
  }
146
231
  /**
147
232
  * {@inheritDoc IOpportunitiesPrepare.openNewStrategy}
148
233
  **/
149
234
  async openNewStrategy(strategy, params) {
150
- return this.queryChain({
151
- network: strategy.chainId,
152
- run: (sdk) => {
153
- const targetToken = params.targetToken ?? sdk.marketRegister.findCreditManager(strategy.creditManager).strategyTargetCollateral;
154
- if (!targetToken) throw new Error(`credit manager ${strategy.creditManager} has no strategy target collateral`);
155
- return service(sdk).openStrategyIntent({
156
- sdk,
157
- creditManager: strategy.creditManager,
158
- collateral: params.collateral,
159
- targetToken,
160
- leverage: params.leverage,
161
- leftoverBalances: params.leftoverBalances,
162
- slippage: params.slippage,
163
- quotaReserve: params.quotaReserve
164
- });
165
- }
235
+ return this.#answer(strategy.chainId, async (sdk) => {
236
+ const targetToken = params.targetToken ?? sdk.marketRegister.findCreditManager(strategy.creditManager).strategyTargetCollateral;
237
+ if (!targetToken) return {
238
+ success: false,
239
+ error: require_sdk_prepare_errors.noStrategyTargetCollateral(strategy.creditManager)
240
+ };
241
+ return opened(await service(sdk).openStrategyIntent({
242
+ sdk,
243
+ creditManager: strategy.creditManager,
244
+ collateral: params.collateral,
245
+ targetToken,
246
+ leverage: params.leverage,
247
+ leftoverBalances: params.leftoverBalances,
248
+ slippage: params.slippage,
249
+ quotaReserve: params.quotaReserve
250
+ }));
166
251
  });
167
252
  }
168
253
  /**
@@ -194,12 +279,19 @@ var PrepareApi = class extends require_onchain_base_MultichainConstruct.Multicha
194
279
  * {@inheritDoc IOpportunitiesPrepare.maxWithdraw}
195
280
  **/
196
281
  async maxWithdraw(position) {
197
- return this.queryChain({
198
- network: position.chainId,
199
- run: async (sdk) => service(sdk).maxWithdraw({
200
- creditAccount: await slice(sdk, position.creditAccount),
201
- sdk
202
- })
282
+ return this.#answer(position.chainId, async (sdk) => {
283
+ const creditAccount = await slice(sdk, position.creditAccount);
284
+ if (!creditAccount) return {
285
+ success: false,
286
+ error: require_sdk_prepare_errors.creditAccountNotFound(position.creditAccount)
287
+ };
288
+ return {
289
+ success: true,
290
+ data: await service(sdk).maxWithdraw({
291
+ creditAccount,
292
+ sdk
293
+ })
294
+ };
203
295
  });
204
296
  }
205
297
  /**
@@ -217,12 +309,19 @@ var PrepareApi = class extends require_onchain_base_MultichainConstruct.Multicha
217
309
  * {@inheritDoc IOpportunitiesPrepare.maxRepay}
218
310
  **/
219
311
  async maxRepay(position) {
220
- return this.queryChain({
221
- network: position.chainId,
222
- run: async (sdk) => service(sdk).maxRepay({
223
- creditAccount: await slice(sdk, position.creditAccount),
224
- sdk
225
- })
312
+ return this.#answer(position.chainId, async (sdk) => {
313
+ const creditAccount = await slice(sdk, position.creditAccount);
314
+ if (!creditAccount) return {
315
+ success: false,
316
+ error: require_sdk_prepare_errors.creditAccountNotFound(position.creditAccount)
317
+ };
318
+ return {
319
+ success: true,
320
+ data: await service(sdk).maxRepay({
321
+ creditAccount,
322
+ sdk
323
+ })
324
+ };
226
325
  });
227
326
  }
228
327
  /**
@@ -279,14 +378,21 @@ var PrepareApi = class extends require_onchain_base_MultichainConstruct.Multicha
279
378
  * {@inheritDoc IOpportunitiesPrepare.maxWithdrawCollateral}
280
379
  **/
281
380
  async maxWithdrawCollateral(position, token, targetHF) {
282
- return this.queryChain({
283
- network: position.chainId,
284
- run: async (sdk) => service(sdk).maxWithdrawCollateral({
285
- creditAccount: await slice(sdk, position.creditAccount),
286
- sdk,
287
- token,
288
- targetHF
289
- })
381
+ return this.#answer(position.chainId, async (sdk) => {
382
+ const creditAccount = await slice(sdk, position.creditAccount);
383
+ if (!creditAccount) return {
384
+ success: false,
385
+ error: require_sdk_prepare_errors.creditAccountNotFound(position.creditAccount)
386
+ };
387
+ return {
388
+ success: true,
389
+ data: await service(sdk).maxWithdrawCollateral({
390
+ creditAccount,
391
+ sdk,
392
+ token,
393
+ targetHF
394
+ })
395
+ };
290
396
  });
291
397
  }
292
398
  /**
@@ -294,42 +400,60 @@ var PrepareApi = class extends require_onchain_base_MultichainConstruct.Multicha
294
400
  * two routes to offer: one account read, one intent, both routes quoted.
295
401
  **/
296
402
  async #startRoutes(position, options, intent) {
297
- return this.queryChain({
298
- network: position.chainId,
299
- run: async (sdk) => service(sdk).intentRoutes({
300
- intent,
301
- creditAccount: await slice(sdk, position.creditAccount),
302
- sdk,
303
- slippage: options.slippage,
304
- quotaReserve: options.quotaReserve
305
- })
306
- });
403
+ try {
404
+ return await this.queryChain({
405
+ network: position.chainId,
406
+ run: async (sdk) => {
407
+ const creditAccount = await slice(sdk, position.creditAccount);
408
+ if (!creditAccount) return neitherRoute(require_sdk_prepare_errors.creditAccountNotFound(position.creditAccount));
409
+ return routed(await service(sdk).intentRoutes({
410
+ intent,
411
+ creditAccount,
412
+ sdk,
413
+ slippage: options.slippage,
414
+ quotaReserve: options.quotaReserve
415
+ }));
416
+ }
417
+ });
418
+ } catch (e) {
419
+ return {
420
+ data: neitherRoute(require_sdk_prepare_errors.unexpectedFailure(e)),
421
+ meta: { chains: [failedChain(position.chainId, e)] }
422
+ };
423
+ }
307
424
  }
308
425
  /**
309
426
  * Shared path of the five flows that act on an existing account: read the
310
427
  * account, then run the intent through the engine.
311
428
  **/
312
429
  async #startIntent(position, options, intent) {
313
- return this.queryChain({
314
- network: position.chainId,
315
- run: async (sdk) => {
316
- const creditAccount = await slice(sdk, position.creditAccount);
317
- return service(sdk).startIntent({
318
- intent,
319
- creditAccount,
320
- sdk,
321
- slippage: options.slippage,
322
- quotaReserve: options.quotaReserve
323
- });
324
- }
430
+ return this.#answer(position.chainId, async (sdk) => {
431
+ const creditAccount = await slice(sdk, position.creditAccount);
432
+ if (!creditAccount) return {
433
+ success: false,
434
+ error: require_sdk_prepare_errors.creditAccountNotFound(position.creditAccount)
435
+ };
436
+ return planned(await service(sdk).startIntent({
437
+ intent,
438
+ creditAccount,
439
+ sdk,
440
+ slippage: options.slippage,
441
+ quotaReserve: options.quotaReserve
442
+ }));
325
443
  });
326
444
  }
327
445
  };
328
446
  function service(sdk) {
329
447
  return new require_onchain_accounts_intents_index.CreditAccountOperationsService(sdk);
330
448
  }
331
- function slice(sdk, creditAccount) {
332
- return require_onchain_accounts_intents_utils_credit_account_slice.fetchCreditAccountSlice(sdk, creditAccount);
449
+ /**
450
+ * The account the request names, or nothing where the markets this SDK is
451
+ * connected to hold no such account — closed since it was listed, or named on
452
+ * the wrong chain. Read rather than thrown, so the caller gets a code for it.
453
+ **/
454
+ async function slice(sdk, creditAccount) {
455
+ const data = await sdk.accounts.getCreditAccountData(creditAccount);
456
+ return data && require_onchain_accounts_intents_utils_credit_account_slice.toCreditAccountSlice(data);
333
457
  }
334
458
  /**
335
459
  * The operation a claim resumes, or `undefined` when there is none to resume:
@@ -362,6 +486,36 @@ function toClaimableWithdrawal(claimable) {
362
486
  };
363
487
  }
364
488
  /**
489
+ * A flow with two routes, refused before either could be quoted: the error is
490
+ * the same one any other flow would report, with nothing to say about the
491
+ * routes because neither was reached.
492
+ **/
493
+ function neitherRoute(error) {
494
+ return {
495
+ success: false,
496
+ error: {
497
+ ...error,
498
+ refused: {
499
+ instant: void 0,
500
+ delayed: void 0
501
+ }
502
+ }
503
+ };
504
+ }
505
+ /**
506
+ * The chain entry for a request that was answered with
507
+ * {@link UnexpectedFailureError}: the read did not happen, so the metadata says
508
+ * so rather than reporting a block it never got.
509
+ **/
510
+ function failedChain(chainId, error) {
511
+ return {
512
+ chainId,
513
+ status: "error",
514
+ source: "onchain",
515
+ error
516
+ };
517
+ }
518
+ /**
365
519
  * A pool route the market does not offer, as the refusal a caller reads.
366
520
  *
367
521
  * `to` is absent where {@link lpRoute} found no output to name at all, which
@@ -369,10 +523,89 @@ function toClaimableWithdrawal(claimable) {
369
523
  * ours implements it.
370
524
  **/
371
525
  function unroutable(sdk, from, to) {
372
- return require_onchain_validation_refusal.refuse("unsupportedTokenPair", {
373
- from: require_onchain_validation_token.toToken(sdk, from),
374
- to: to === void 0 ? void 0 : require_onchain_validation_token.toToken(sdk, to)
375
- });
526
+ return {
527
+ success: false,
528
+ error: require_sdk_prepare_errors.toPrepareError({
529
+ reason: "unsupportedTokenPair",
530
+ detail: {
531
+ from: require_onchain_validation_token.toToken(sdk, from),
532
+ to: to === void 0 ? void 0 : require_onchain_validation_token.toToken(sdk, to)
533
+ }
534
+ })
535
+ };
536
+ }
537
+ /**
538
+ * The engine's answer, as the envelope the namespace speaks in: what the
539
+ * operation comes to under `data`, or the refusal as an error carrying its own
540
+ * numbers, see {@link toPrepareError}.
541
+ *
542
+ * The engine keeps its `ok` union — it is the shape the planners, the guards
543
+ * and their tests are written against — and the boundary is the one place the
544
+ * two vocabularies meet.
545
+ **/
546
+ function planned(result) {
547
+ if (!result.ok) return {
548
+ success: false,
549
+ error: require_sdk_prepare_errors.toPrepareError(result)
550
+ };
551
+ const { operations, state, calls } = result;
552
+ return {
553
+ success: true,
554
+ data: {
555
+ operations,
556
+ state,
557
+ calls
558
+ }
559
+ };
560
+ }
561
+ /**
562
+ * {@inheritDoc planned}
563
+ **/
564
+ function opened(result) {
565
+ return result.ok ? {
566
+ success: true,
567
+ data: { state: result.state }
568
+ } : {
569
+ success: false,
570
+ error: require_sdk_prepare_errors.toPrepareError(result)
571
+ };
572
+ }
573
+ /**
574
+ * {@inheritDoc planned}
575
+ *
576
+ * Both routes are payload, refusal and all: `refused` says why a missing one is
577
+ * missing, and it stays on the error when neither route answered, since that is
578
+ * the same question asked of a request that has no viable half at all.
579
+ **/
580
+ function routed(result) {
581
+ if (!result.ok) {
582
+ const { refused, ...issue } = result;
583
+ return {
584
+ success: false,
585
+ error: {
586
+ ...require_sdk_prepare_errors.toPrepareError(issue),
587
+ refused
588
+ }
589
+ };
590
+ }
591
+ const { instant, delayed, refused } = result;
592
+ return {
593
+ success: true,
594
+ data: {
595
+ instant: instant && {
596
+ operations: instant.operations,
597
+ state: instant.state,
598
+ calls: instant.calls
599
+ },
600
+ delayed: delayed && {
601
+ operations: delayed.operations,
602
+ state: delayed.state,
603
+ calls: delayed.calls,
604
+ delayed: delayed.delayed
605
+ },
606
+ refused
607
+ }
608
+ };
376
609
  }
377
610
  /**
378
611
  * Picks the route the operation takes out of `tokenIn`, as a value rather than