@kasufinance/kasu-sdk 2.8.0 → 2.10.1

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 (91) hide show
  1. package/README.md +120 -9
  2. package/dist/bundle.cjs.js +2077 -476
  3. package/dist/bundle.esm.js +2039 -478
  4. package/dist/domain/batch-proof.d.ts +210 -0
  5. package/dist/domain/batch-proof.js +384 -0
  6. package/dist/domain/batch-proof.js.map +1 -0
  7. package/dist/domain/explorer-urls.d.ts +33 -0
  8. package/dist/domain/explorer-urls.js +38 -0
  9. package/dist/domain/explorer-urls.js.map +1 -0
  10. package/dist/domain/fixed-term.d.ts +74 -0
  11. package/dist/domain/fixed-term.js +86 -0
  12. package/dist/domain/fixed-term.js.map +1 -0
  13. package/dist/domain/index.d.ts +12 -2
  14. package/dist/domain/index.js +7 -2
  15. package/dist/domain/index.js.map +1 -1
  16. package/dist/domain/partners.d.ts +29 -0
  17. package/dist/domain/partners.js +20 -0
  18. package/dist/domain/partners.js.map +1 -1
  19. package/dist/domain/requests.d.ts +24 -0
  20. package/dist/domain/requests.js +33 -0
  21. package/dist/domain/requests.js.map +1 -1
  22. package/dist/domain/sponsored-calls.d.ts +74 -0
  23. package/dist/domain/sponsored-calls.js +156 -0
  24. package/dist/domain/sponsored-calls.js.map +1 -0
  25. package/dist/domain/yields.d.ts +121 -0
  26. package/dist/domain/yields.js +151 -0
  27. package/dist/domain/yields.js.map +1 -0
  28. package/dist/facade/calls.d.ts +59 -0
  29. package/dist/facade/calls.js +89 -0
  30. package/dist/facade/calls.js.map +1 -0
  31. package/dist/facade/chain-configs.js +5 -0
  32. package/dist/facade/chain-configs.js.map +1 -1
  33. package/dist/facade/flows.d.ts +24 -3
  34. package/dist/facade/flows.js +22 -2
  35. package/dist/facade/flows.js.map +1 -1
  36. package/dist/facade/index.d.ts +3 -1
  37. package/dist/facade/index.js +1 -0
  38. package/dist/facade/index.js.map +1 -1
  39. package/dist/facade/kasu.d.ts +8 -2
  40. package/dist/facade/kasu.js +17 -5
  41. package/dist/facade/kasu.js.map +1 -1
  42. package/dist/facade/strategies.d.ts +43 -2
  43. package/dist/facade/strategies.js +80 -4
  44. package/dist/facade/strategies.js.map +1 -1
  45. package/dist/facade/types.d.ts +18 -0
  46. package/dist/flows/batch-errors.d.ts +74 -0
  47. package/dist/flows/batch-errors.js +83 -0
  48. package/dist/flows/batch-errors.js.map +1 -0
  49. package/dist/flows/batch-submission.d.ts +223 -0
  50. package/dist/flows/batch-submission.js +321 -0
  51. package/dist/flows/batch-submission.js.map +1 -0
  52. package/dist/flows/deposit-flow.d.ts +13 -20
  53. package/dist/flows/deposit-flow.js +14 -25
  54. package/dist/flows/deposit-flow.js.map +1 -1
  55. package/dist/flows/index.d.ts +6 -2
  56. package/dist/flows/index.js +4 -2
  57. package/dist/flows/index.js.map +1 -1
  58. package/dist/flows/withdraw-flow.d.ts +95 -4
  59. package/dist/flows/withdraw-flow.js +107 -2
  60. package/dist/flows/withdraw-flow.js.map +1 -1
  61. package/dist/services/DataService/queries.js +1 -0
  62. package/dist/services/DataService/queries.js.map +1 -1
  63. package/dist/services/Portfolio/portfolio.js +11 -0
  64. package/dist/services/Portfolio/portfolio.js.map +1 -1
  65. package/dist/services/UserLending/user-lending.d.ts +13 -0
  66. package/dist/services/UserLending/user-lending.js +25 -4
  67. package/dist/services/UserLending/user-lending.js.map +1 -1
  68. package/package.json +1 -1
  69. package/src/domain/batch-proof.ts +576 -0
  70. package/src/domain/explorer-urls.ts +74 -0
  71. package/src/domain/fixed-term.ts +115 -0
  72. package/src/domain/index.ts +56 -0
  73. package/src/domain/partners.ts +35 -0
  74. package/src/domain/requests.ts +37 -0
  75. package/src/domain/sponsored-calls.ts +213 -0
  76. package/src/domain/yields.ts +189 -0
  77. package/src/facade/calls.ts +135 -0
  78. package/src/facade/chain-configs.ts +5 -0
  79. package/src/facade/flows.ts +23 -2
  80. package/src/facade/index.ts +3 -0
  81. package/src/facade/kasu.ts +31 -2
  82. package/src/facade/strategies.ts +98 -7
  83. package/src/facade/types.ts +19 -0
  84. package/src/flows/batch-errors.ts +118 -0
  85. package/src/flows/batch-submission.ts +511 -0
  86. package/src/flows/deposit-flow.ts +27 -33
  87. package/src/flows/index.ts +33 -2
  88. package/src/flows/withdraw-flow.ts +219 -10
  89. package/src/services/DataService/queries.ts +1 -0
  90. package/src/services/Portfolio/portfolio.ts +14 -0
  91. package/src/services/UserLending/user-lending.ts +38 -10
@@ -2033,7 +2033,7 @@ function isSource(source) {
2033
2033
  * Given a GraphQL source, parses it into a Document.
2034
2034
  * Throws GraphQLError if a syntax error is encountered.
2035
2035
  */
2036
- function parse(source, options) {
2036
+ function parse$1(source, options) {
2037
2037
  const parser = new Parser(source, options);
2038
2038
  const document = parser.parseDocument();
2039
2039
  Object.defineProperty(document, 'tokenCount', {
@@ -4296,7 +4296,7 @@ const resolveRequestDocument = (document) => {
4296
4296
  if (typeof document === `string`) {
4297
4297
  let operationName = undefined;
4298
4298
  try {
4299
- const parsedDocument = parse(document);
4299
+ const parsedDocument = parse$1(document);
4300
4300
  operationName = extractOperationName(parsedDocument);
4301
4301
  }
4302
4302
  catch (err) {
@@ -15811,6 +15811,7 @@ const getPoolOverviewQuery = (ids) => gql `
15811
15811
  fixedTermDepositStatus
15812
15812
  fixedTermDepositAllowlist{
15813
15813
  id
15814
+ isAllowlisted
15814
15815
  user{
15815
15816
  id
15816
15817
  }
@@ -17240,10 +17241,32 @@ class UserLending {
17240
17241
  return yield this._lendingPoolManagerAbi.requestWithdrawal(lendingPool, tranche, amount);
17241
17242
  });
17242
17243
  }
17243
- requestWithdrawalInAsset(lendingPool, tranche, assetAmount) {
17244
+ /**
17245
+ * The tranche shares a withdrawal of `assetAmount` requests — the
17246
+ * tranche's own `convertToShares`, read now. `requestWithdrawalInAsset`
17247
+ * and the sponsored `kasu.calls.requestWithdrawal` both use this, so the
17248
+ * two paths cannot convert differently.
17249
+ */
17250
+ getWithdrawalSharesForAssets(tranche, assetAmount) {
17251
+ return __awaiter(this, void 0, void 0, function* () {
17252
+ const trancheContract = ILendingPoolTrancheAbi__factory.connect(tranche, this._signerOrProvider);
17253
+ return yield trancheContract.convertToShares(assetAmount);
17254
+ });
17255
+ }
17256
+ /**
17257
+ * Every tranche share `user` holds — what a max withdrawal requests
17258
+ * (`balanceOf(user)` on the tranche, read now). Shared by
17259
+ * `requestWithdrawalMax` and the sponsored `kasu.calls.requestWithdrawal`.
17260
+ */
17261
+ getWithdrawalSharesMax(tranche, user) {
17244
17262
  return __awaiter(this, void 0, void 0, function* () {
17245
17263
  const trancheContract = ILendingPoolTrancheAbi__factory.connect(tranche, this._signerOrProvider);
17246
- const shareAmount = yield trancheContract.convertToShares(assetAmount);
17264
+ return yield trancheContract['balanceOf(address)'](user);
17265
+ });
17266
+ }
17267
+ requestWithdrawalInAsset(lendingPool, tranche, assetAmount) {
17268
+ return __awaiter(this, void 0, void 0, function* () {
17269
+ const shareAmount = yield this.getWithdrawalSharesForAssets(tranche, assetAmount);
17247
17270
  return yield this._lendingPoolManagerAbi.requestWithdrawal(lendingPool, tranche, shareAmount);
17248
17271
  });
17249
17272
  }
@@ -17255,8 +17278,7 @@ class UserLending {
17255
17278
  }
17256
17279
  requestWithdrawalMax(lendingPool, tranche, user) {
17257
17280
  return __awaiter(this, void 0, void 0, function* () {
17258
- const trancheContract = ILendingPoolTrancheAbi__factory.connect(tranche, this._signerOrProvider);
17259
- const userShares = yield trancheContract['balanceOf(address)'](user);
17281
+ const userShares = yield this.getWithdrawalSharesMax(tranche, user);
17260
17282
  return yield this._lendingPoolManagerAbi.requestWithdrawal(lendingPool, tranche, userShares);
17261
17283
  });
17262
17284
  }
@@ -17831,6 +17853,17 @@ class Portfolio {
17831
17853
  weeklyYieldEarnings +=
17832
17854
  investedAmount * parseFloat(tranche.interestRate);
17833
17855
  for (const fixedDeposits of tranche.fixedLoans) {
17856
+ // A matured lock's principal is already inside
17857
+ // `investedAmount`: getPortfolioLendingData subtracts only
17858
+ // the LOCKED loans from the tranche balance. Its lifetime
17859
+ // yield is earned and stays counted (the tranche's own
17860
+ // lifetime had every lock's yield taken out), but its
17861
+ // amount must not be added to the investment, weekly or
17862
+ // APY sums a second time.
17863
+ if (!fixedDeposits.isLocked) {
17864
+ totalYieldEarned += parseFloat(fixedDeposits.yieldEarnings.lifetime);
17865
+ continue;
17866
+ }
17834
17867
  const ftdConfig = tranche.fixedTermConfig.find((ftd) => ftd.configId === fixedDeposits.configId);
17835
17868
  if (!ftdConfig)
17836
17869
  continue;
@@ -20462,7 +20495,7 @@ function toFormData$1(obj, formData, options) {
20462
20495
  *
20463
20496
  * @returns {string} The encoded string.
20464
20497
  */
20465
- function encode$1(str) {
20498
+ function encode$2(str) {
20466
20499
  const charMap = {
20467
20500
  '!': '%21',
20468
20501
  "'": '%27',
@@ -20498,8 +20531,8 @@ prototype.append = function append(name, value) {
20498
20531
 
20499
20532
  prototype.toString = function toString(encoder) {
20500
20533
  const _encode = encoder
20501
- ? (value) => encoder.call(this, value, encode$1)
20502
- : encode$1;
20534
+ ? (value) => encoder.call(this, value, encode$2)
20535
+ : encode$2;
20503
20536
 
20504
20537
  return this._pairs
20505
20538
  .map(function each(pair) {
@@ -20516,7 +20549,7 @@ prototype.toString = function toString(encoder) {
20516
20549
  *
20517
20550
  * @returns {string} The encoded value.
20518
20551
  */
20519
- function encode(val) {
20552
+ function encode$1(val) {
20520
20553
  return encodeURIComponent(val)
20521
20554
  .replace(/%3A/gi, ':')
20522
20555
  .replace(/%24/g, '$')
@@ -20548,7 +20581,7 @@ function buildURL(url, params, options) {
20548
20581
  // Read serializer options pollution-safely: own properties and methods on a
20549
20582
  // class/template prototype are honored, but values injected onto a polluted
20550
20583
  // Object.prototype are ignored.
20551
- const _encode = utils$1.getSafeProp(_options, 'encode') || encode;
20584
+ const _encode = utils$1.getSafeProp(_options, 'encode') || encode$1;
20552
20585
  const serializeFn = utils$1.getSafeProp(_options, 'serialize');
20553
20586
 
20554
20587
  let serializedParams;
@@ -21188,7 +21221,7 @@ let CanceledError$1 = class CanceledError extends AxiosError$1 {
21188
21221
  *
21189
21222
  * @returns {object} The response.
21190
21223
  */
21191
- function settle(resolve, reject, response) {
21224
+ function settle$1(resolve, reject, response) {
21192
21225
  const validateStatus = response.config.validateStatus;
21193
21226
  if (!response.status || !validateStatus || validateStatus(response.status)) {
21194
21227
  resolve(response);
@@ -21951,7 +21984,7 @@ var xhrAdapter = isXHRAdapterSupported &&
21951
21984
  request,
21952
21985
  };
21953
21986
 
21954
- settle(
21987
+ settle$1(
21955
21988
  function _resolve(value) {
21956
21989
  resolve(value);
21957
21990
  done();
@@ -23009,7 +23042,7 @@ const factory = (env) => {
23009
23042
  !isStreamResponse && unsubscribe && unsubscribe();
23010
23043
 
23011
23044
  return await new Promise((resolve, reject) => {
23012
- settle(resolve, reject, {
23045
+ settle$1(resolve, reject, {
23013
23046
  data: responseData,
23014
23047
  headers: AxiosHeaders$1.from(response.headers),
23015
23048
  status: response.status,
@@ -24185,6 +24218,238 @@ class SdkConfig {
24185
24218
  }
24186
24219
  }
24187
24220
 
24221
+ /**
24222
+ * The single-call `LendingPoolManager` requests a sponsored relay may carry,
24223
+ * encoded by the SDK so no application hand-builds calldata or hand-maps the
24224
+ * relay's `kind` for them.
24225
+ *
24226
+ * Every function here is PURE: addresses and ids in, `{ kind, call }` out.
24227
+ * Reading the chain (the shares a withdrawal is for) is the facade's job —
24228
+ * `kasu.calls` — and sending is the application's.
24229
+ *
24230
+ * Each call is `{ to, data }` and nothing else: no `value` (none of these
24231
+ * functions is payable), no `from` (the manager acts for `msg.sender`, the
24232
+ * lender's own account, which is why none of them takes a user argument).
24233
+ * `data` is ethers' ABI encoding, which is canonical by construction — the
24234
+ * relay re-encodes what it decodes and refuses anything that differs, so a
24235
+ * hand-tweaked blob never gets through, and an SDK-built one always matches.
24236
+ */
24237
+ /**
24238
+ * The relay's name for each shape. Carried beside the call so the app posts
24239
+ * `kind` from the SDK, never from a table of its own — a request declaring the
24240
+ * wrong kind is refused (`invalid_calls`), so a hand-mapped table that drifts
24241
+ * turns into a lender who cannot withdraw.
24242
+ */
24243
+ const SPONSORED_CALL_KINDS = [
24244
+ /** `LendingPoolManager.requestWithdrawal(pool, tranche, shares)`. */
24245
+ 'withdrawal',
24246
+ /** `LendingPoolManager.cancelDepositRequest(pool, dNftID)`. */
24247
+ 'cancel_deposit',
24248
+ /** `LendingPoolManager.cancelWithdrawalRequest(pool, wNftID)`. */
24249
+ 'cancel_withdrawal',
24250
+ /** `LendingPoolManager.requestFixedTermDepositWithdrawal(pool, lockId)`. */
24251
+ 'withdraw_at_expiry',
24252
+ ];
24253
+ /**
24254
+ * Widened to the plain `Interface`: the typechain one overloads
24255
+ * `encodeFunctionData` per literal name, and the name here comes from
24256
+ * `FUNCTION_OF`.
24257
+ */
24258
+ const LENDING_POOL_MANAGER$2 = ILendingPoolManagerAbi__factory.createInterface();
24259
+ /** The `LendingPoolManager` function behind each kind. */
24260
+ const FUNCTION_OF = Object.freeze({
24261
+ withdrawal: 'requestWithdrawal',
24262
+ cancel_deposit: 'cancelDepositRequest',
24263
+ cancel_withdrawal: 'cancelWithdrawalRequest',
24264
+ withdraw_at_expiry: 'requestFixedTermDepositWithdrawal',
24265
+ });
24266
+ /**
24267
+ * The 4-byte selector of each kind's function, DERIVED from the generated
24268
+ * `ILendingPoolManager` ABI — never typed in by hand, so an ABI change moves
24269
+ * it and the cross-check spec against the relay's own pins goes red.
24270
+ */
24271
+ const SPONSORED_CALL_SELECTORS = Object.freeze({
24272
+ withdrawal: LENDING_POOL_MANAGER$2.getSighash(FUNCTION_OF.withdrawal),
24273
+ cancel_deposit: LENDING_POOL_MANAGER$2.getSighash(FUNCTION_OF.cancel_deposit),
24274
+ cancel_withdrawal: LENDING_POOL_MANAGER$2.getSighash(FUNCTION_OF.cancel_withdrawal),
24275
+ withdraw_at_expiry: LENDING_POOL_MANAGER$2.getSighash(FUNCTION_OF.withdraw_at_expiry),
24276
+ });
24277
+ /**
24278
+ * What an encoder throws for an input it will not encode. `code` names the
24279
+ * argument; the message names no party, so a wallet-rejection classifier can
24280
+ * never read it as something the lender did. Nothing has been sent when this
24281
+ * is thrown.
24282
+ */
24283
+ class SponsoredCallInputError extends Error {
24284
+ constructor(code) {
24285
+ super(`Sponsored call input refused (${code})`);
24286
+ this.name = 'SponsoredCallInputError';
24287
+ this.code = code;
24288
+ Object.setPrototypeOf(this, SponsoredCallInputError.prototype);
24289
+ }
24290
+ }
24291
+ const ADDRESS_RE$2 = /^0x[0-9a-fA-F]{40}$/;
24292
+ function assertAddress(value, code) {
24293
+ if (typeof value !== 'string' || !ADDRESS_RE$2.test(value)) {
24294
+ throw new SponsoredCallInputError(code);
24295
+ }
24296
+ }
24297
+ /** A uint256 — an NFT or lock id. Zero is a valid id as far as encoding goes. */
24298
+ function toUint256(value, code) {
24299
+ let parsed;
24300
+ try {
24301
+ parsed = ethers.BigNumber.from(value);
24302
+ }
24303
+ catch (_a) {
24304
+ throw new SponsoredCallInputError(code);
24305
+ }
24306
+ if (parsed.isNegative() || parsed.gt(ethers.constants.MaxUint256)) {
24307
+ throw new SponsoredCallInputError(code);
24308
+ }
24309
+ return parsed;
24310
+ }
24311
+ function encode(kind, lendingPoolManager, args) {
24312
+ return {
24313
+ kind,
24314
+ call: {
24315
+ to: lendingPoolManager,
24316
+ data: LENDING_POOL_MANAGER$2.encodeFunctionData(FUNCTION_OF[kind], args),
24317
+ },
24318
+ };
24319
+ }
24320
+ /**
24321
+ * `requestWithdrawal(poolId, trancheId, shares)` — `withdrawal`.
24322
+ *
24323
+ * `shares` are tranche SHARES, not assets: `kasu.calls.requestWithdrawal`
24324
+ * converts an asset amount (or `'max'`) into them exactly as
24325
+ * `UserLending.requestWithdrawalInAsset` / `requestWithdrawalMax` do. Zero
24326
+ * shares is refused here: the contract reverts on it
24327
+ * (`RequestWithdrawSharesAreZero`) and the relay refuses it before that.
24328
+ */
24329
+ function encodeRequestWithdrawalCall(lendingPoolManager, poolId, trancheId, shares) {
24330
+ assertAddress(lendingPoolManager, 'lending-pool-manager');
24331
+ assertAddress(poolId, 'pool');
24332
+ assertAddress(trancheId, 'tranche');
24333
+ const amount = toUint256(shares, 'shares');
24334
+ if (amount.isZero())
24335
+ throw new SponsoredCallInputError('zero-shares');
24336
+ return encode('withdrawal', lendingPoolManager, [
24337
+ poolId,
24338
+ trancheId,
24339
+ amount,
24340
+ ]);
24341
+ }
24342
+ /** `cancelDepositRequest(poolId, dNftId)` — `cancel_deposit`. */
24343
+ function encodeCancelDepositCall(lendingPoolManager, poolId, dNftId) {
24344
+ assertAddress(lendingPoolManager, 'lending-pool-manager');
24345
+ assertAddress(poolId, 'pool');
24346
+ return encode('cancel_deposit', lendingPoolManager, [
24347
+ poolId,
24348
+ toUint256(dNftId, 'nft-id'),
24349
+ ]);
24350
+ }
24351
+ /** `cancelWithdrawalRequest(poolId, wNftId)` — `cancel_withdrawal`. */
24352
+ function encodeCancelWithdrawalCall(lendingPoolManager, poolId, wNftId) {
24353
+ assertAddress(lendingPoolManager, 'lending-pool-manager');
24354
+ assertAddress(poolId, 'pool');
24355
+ return encode('cancel_withdrawal', lendingPoolManager, [
24356
+ poolId,
24357
+ toUint256(wNftId, 'nft-id'),
24358
+ ]);
24359
+ }
24360
+ /**
24361
+ * `requestFixedTermDepositWithdrawal(poolId, fixedTermDepositId)` —
24362
+ * `withdraw_at_expiry`. The contract function takes the pool and the LOCK id
24363
+ * only (no tranche): the manager forwards to the fixed-term contract on the
24364
+ * lender's behalf, which knows the lock's tranche.
24365
+ */
24366
+ function encodeWithdrawAtExpiryCall(lendingPoolManager, poolId, fixedTermDepositId) {
24367
+ assertAddress(lendingPoolManager, 'lending-pool-manager');
24368
+ assertAddress(poolId, 'pool');
24369
+ return encode('withdraw_at_expiry', lendingPoolManager, [
24370
+ poolId,
24371
+ toUint256(fixedTermDepositId, 'lock-id'),
24372
+ ]);
24373
+ }
24374
+
24375
+ const ADDRESS_RE$1 = /^0x[0-9a-fA-F]{40}$/;
24376
+ /**
24377
+ * Encoded, ready-to-sponsor `LendingPoolManager` calls — read, then encode,
24378
+ * NEVER send. Each returns `{ kind, call }`: post `kind` and `[call]` to a
24379
+ * sponsored relay (or `submitSponsoredCall`), unchanged.
24380
+ *
24381
+ * ```ts
24382
+ * const { kind, call } = kasu.calls.cancelDepositRequest(poolId, dNftId);
24383
+ * ```
24384
+ *
24385
+ * `call.to` is always THIS chain's `LendingPoolManager`, from the chain
24386
+ * config — the same address the deposit flow approves and calls — so no app
24387
+ * supplies the one argument whose wrong value the relay refuses outright.
24388
+ *
24389
+ * Works on a read-only instance: the only chain access is the share read a
24390
+ * withdrawal needs, and nothing is signed or sent here.
24391
+ */
24392
+ class CallsFacade {
24393
+ constructor(_userLending, _lendingPoolManager) {
24394
+ this._userLending = _userLending;
24395
+ this._lendingPoolManager = _lendingPoolManager;
24396
+ }
24397
+ /**
24398
+ * `requestWithdrawal(pool, tranche, shares)` for an asset amount or
24399
+ * `'max'`, converted into shares exactly as the direct path does it
24400
+ * (`UserLending.requestWithdrawalInAsset` / `requestWithdrawalMax`): the
24401
+ * tranche's `convertToShares(amount)`, or the lender's whole
24402
+ * `balanceOf(userAddress)`, read now.
24403
+ *
24404
+ * Rejects with `SponsoredCallInputError` — before anything is sent — for
24405
+ * a non-positive amount, a malformed address, or a conversion that comes
24406
+ * to ZERO shares (an empty position, or dust below one share), which the
24407
+ * contract would revert and the relay refuses.
24408
+ */
24409
+ requestWithdrawal(params) {
24410
+ return __awaiter(this, void 0, void 0, function* () {
24411
+ const { poolId, trancheId, amount, userAddress } = params;
24412
+ if (typeof userAddress !== 'string' || !ADDRESS_RE$1.test(userAddress)) {
24413
+ throw new SponsoredCallInputError('user');
24414
+ }
24415
+ if (typeof poolId !== 'string' || !ADDRESS_RE$1.test(poolId)) {
24416
+ throw new SponsoredCallInputError('pool');
24417
+ }
24418
+ if (typeof trancheId !== 'string' || !ADDRESS_RE$1.test(trancheId)) {
24419
+ throw new SponsoredCallInputError('tranche');
24420
+ }
24421
+ let shares;
24422
+ if (amount === 'max') {
24423
+ // Lowercased, as `WithdrawFlow` hands `withdrawMax` the address.
24424
+ shares = yield this._userLending.getWithdrawalSharesMax(trancheId, userAddress.toLowerCase());
24425
+ }
24426
+ else {
24427
+ if (!ethers.BigNumber.isBigNumber(amount) || amount.lte(0)) {
24428
+ throw new SponsoredCallInputError('non-positive-amount');
24429
+ }
24430
+ shares = yield this._userLending.getWithdrawalSharesForAssets(trancheId, amount);
24431
+ }
24432
+ return encodeRequestWithdrawalCall(this._lendingPoolManager, poolId, trancheId, shares);
24433
+ });
24434
+ }
24435
+ /** `cancelDepositRequest(pool, dNftId)` — the pending deposit's NFT id. */
24436
+ cancelDepositRequest(poolId, dNftId) {
24437
+ return encodeCancelDepositCall(this._lendingPoolManager, poolId, dNftId);
24438
+ }
24439
+ /** `cancelWithdrawalRequest(pool, wNftId)` — the pending withdrawal's NFT id. */
24440
+ cancelWithdrawalRequest(poolId, wNftId) {
24441
+ return encodeCancelWithdrawalCall(this._lendingPoolManager, poolId, wNftId);
24442
+ }
24443
+ /**
24444
+ * `requestFixedTermDepositWithdrawal(pool, fixedTermDepositId)` — what
24445
+ * `UserLending.withdrawAtExpiry(pool, lockId)` sends: the pool and the
24446
+ * LOCK id, no tranche.
24447
+ */
24448
+ withdrawAtExpiry(poolId, fixedTermDepositId) {
24449
+ return encodeWithdrawAtExpiryCall(this._lendingPoolManager, poolId, fixedTermDepositId);
24450
+ }
24451
+ }
24452
+
24188
24453
  /**
24189
24454
  * Browser-viable XDC RPCs only. `rpc.xdc.org` / `erpc.xdc.org` answer OPTIONS
24190
24455
  * without `access-control-allow-origin`, so a browser call hangs on preflight
@@ -24242,6 +24507,7 @@ const CHAIN_CONFIGS = {
24242
24507
  'https://base-rpc.publicnode.com',
24243
24508
  'https://mainnet.base.org',
24244
24509
  ],
24510
+ blockExplorerUrl: 'https://basescan.org',
24245
24511
  },
24246
24512
  xdc: {
24247
24513
  chainId: 50,
@@ -24277,6 +24543,7 @@ const CHAIN_CONFIGS = {
24277
24543
  currencyCode: 'AUD',
24278
24544
  },
24279
24545
  rpcUrls: XDC_RPC_URLS,
24546
+ blockExplorerUrl: 'https://xdcscan.com',
24280
24547
  },
24281
24548
  'xdc-usdc': {
24282
24549
  chainId: 50,
@@ -24308,6 +24575,7 @@ const CHAIN_CONFIGS = {
24308
24575
  currencyCode: 'USD',
24309
24576
  },
24310
24577
  rpcUrls: XDC_RPC_URLS,
24578
+ blockExplorerUrl: 'https://xdcscan.com',
24311
24579
  },
24312
24580
  plume: {
24313
24581
  chainId: 98866,
@@ -24348,6 +24616,8 @@ const CHAIN_CONFIGS = {
24348
24616
  // pointing at an endpoint nobody maintains. Pass your own
24349
24617
  // `signerOrProvider` to read the frozen history.
24350
24618
  rpcUrls: [],
24619
+ // The explorer still serves the frozen history.
24620
+ blockExplorerUrl: 'https://explorer.plume.org',
24351
24621
  retired: true,
24352
24622
  },
24353
24623
  };
@@ -24467,114 +24737,1070 @@ class DepositsFacade {
24467
24737
  }
24468
24738
 
24469
24739
  /**
24470
- * The tiny observable-state kernel both flows are built on.
24740
+ * The errors an atomic-batch submitter throws, in one module both
24741
+ * `DepositFlow` and `submitBatch` import — so `instanceof` is one class
24742
+ * whichever of them a consumer imports it through.
24743
+ */
24744
+ /**
24745
+ * What a `depositBatch` port throws when it KNOWS the batch reverted — from a
24746
+ * simulation before sending, from the submitter refusing to broadcast a batch
24747
+ * that would revert, or from a mined receipt whose user operation reverted.
24748
+ * The run ends `{ step: 'request', reason: 'reverted', revertError }`.
24471
24749
  *
24472
- * Deliberately not a framework store: no React, no signals, no dependency.
24473
- * A flow is a long asynchronous run that has to publish every transition to
24474
- * whatever is rendering it, and has to be able to abandon a run that the
24475
- * consumer walked away from. That is the whole requirement, and it is 60 lines.
24750
+ * `revertError` is the custom error the contract named (`'ClearingIsPending'`,
24751
+ * `'UserNotKycd'`, …), exactly as the ABI declares it. Pass `''` when the
24752
+ * batch is known to revert but not why: the consumer then renders its generic
24753
+ * `reverted` copy, which is what an unknown name gets anyway.
24476
24754
  *
24477
- * The `generation` counter is the abandonment mechanism. `reset()` bumps it;
24478
- * an in-flight run captured the previous value, so every later `patch` it
24479
- * attempts is dropped and every `isCurrent` checkpoint tells it to stop. It is
24480
- * what makes `reset()` safe to call mid-flight — the run cannot resurrect a
24481
- * dead state or, worse, drive the UI back into a phase the consumer has left.
24755
+ * A revert is DEFINITIVE — nothing was deposited. Throw it only when that is
24756
+ * known; anything less certain is a `BatchPendingError`.
24482
24757
  */
24483
- class FlowStore {
24484
- constructor(_initial) {
24485
- this._initial = _initial;
24486
- this._generation = 0;
24487
- this._listeners = new Set();
24488
- this._state = _initial;
24489
- }
24490
- get state() {
24491
- return this._state;
24492
- }
24493
- /** The run token an in-flight pipeline captures at `start()`. */
24494
- get generation() {
24495
- return this._generation;
24496
- }
24497
- /** False once `reset()` (or a later `start()`) has superseded `token`. */
24498
- isCurrent(token) {
24499
- return this._generation === token;
24500
- }
24501
- /**
24502
- * Subscribe to every transition. Returns the unsubscribe function; calling
24503
- * it twice is harmless.
24504
- *
24505
- * Listeners are NOT called on subscribe — read `state` for the current
24506
- * value. A listener that throws is not allowed to break the pipeline or
24507
- * starve the listeners registered after it, so throws are swallowed.
24508
- */
24509
- subscribe(listener) {
24510
- this._listeners.add(listener);
24511
- return () => {
24512
- this._listeners.delete(listener);
24513
- };
24758
+ class BatchRevertedError extends Error {
24759
+ constructor(revertError, message) {
24760
+ super(message !== null && message !== void 0 ? message : `DepositFlow: the batch reverted${revertError ? ` with ${revertError}` : ''}`);
24761
+ this.name = 'BatchRevertedError';
24762
+ this.revertError = revertError;
24763
+ // Keeps `instanceof` honest under a down-levelled build.
24764
+ Object.setPrototypeOf(this, BatchRevertedError.prototype);
24514
24765
  }
24515
- /**
24516
- * Merge `next` into the state and notify, unless `token` names a
24517
- * superseded run.
24518
- */
24519
- patch(next, token) {
24520
- if (token !== undefined && !this.isCurrent(token))
24521
- return;
24522
- this._state = Object.assign(Object.assign({}, this._state), next);
24523
- for (const listener of [...this._listeners]) {
24524
- try {
24525
- listener(this._state);
24526
- }
24527
- catch (_a) {
24528
- // A consumer's rendering fault is its own problem; the pipeline
24529
- // owns real money and keeps going.
24530
- }
24766
+ }
24767
+ /**
24768
+ * Every non-revert failure of a batch submission, carrying its outcome and a
24769
+ * short code (`'status_timeout'`, `'receipt_unavailable'`, …).
24770
+ *
24771
+ * The message is fixed and names no party: the wallet-error classifier reads a
24772
+ * thrown error's text for a USER rejection, and a relay outage worded "…wallet
24773
+ * refused…" must never reach the lender as something they did.
24774
+ *
24775
+ * `outcome` has NO default. `failed` is the one outcome that invites a second
24776
+ * deposit, so a port author has to spell it out — a `throw new
24777
+ * BatchSubmissionError(code)` written in a catch block after the POST left
24778
+ * must not quietly become "try again".
24779
+ */
24780
+ class BatchSubmissionError extends Error {
24781
+ constructor(code, outcome, options) {
24782
+ super(`Batch submission ${outcome} (${code})`);
24783
+ this.name = 'BatchSubmissionError';
24784
+ this.code = code;
24785
+ this.outcome = outcome;
24786
+ // Set by hand: `Error`'s own `cause` option is ES2022.
24787
+ if (options && 'cause' in options) {
24788
+ Object.defineProperty(this, 'cause', {
24789
+ value: options.cause,
24790
+ enumerable: false,
24791
+ writable: true,
24792
+ configurable: true,
24793
+ });
24531
24794
  }
24795
+ Object.setPrototypeOf(this, BatchSubmissionError.prototype);
24532
24796
  }
24533
- /**
24534
- * Back to the initial state, abandoning any in-flight run.
24535
- *
24536
- * Subscribers are kept: the consumer that was watching the last run is the
24537
- * one that will watch the next.
24538
- */
24539
- reset() {
24540
- this._generation += 1;
24541
- this.patch(this._initial);
24542
- }
24543
- /** Claim the next run token. Any earlier run is abandoned. */
24544
- beginRun() {
24545
- this._generation += 1;
24546
- return this._generation;
24797
+ }
24798
+ /**
24799
+ * The ambiguous outcome: the batch may have landed. An instance of
24800
+ * `BatchSubmissionError` with `outcome: 'pending'`.
24801
+ */
24802
+ class BatchPendingError extends BatchSubmissionError {
24803
+ constructor(code, options) {
24804
+ super(code, 'pending', options);
24805
+ this.name = 'BatchPendingError';
24806
+ Object.setPrototypeOf(this, BatchPendingError.prototype);
24547
24807
  }
24548
24808
  }
24809
+ /** The outcome a thrown error stands for, or `null` if it is not a submission error. */
24810
+ function batchOutcomeOf(err) {
24811
+ return err instanceof BatchSubmissionError ? err.outcome : null;
24812
+ }
24813
+ /**
24814
+ * Nothing was deposited and nothing can be: a known revert, or a definitive
24815
+ * `failed` refusal. Everything else — including an error this SDK did not
24816
+ * produce — is NOT proof of that, and a consumer must not invite a retry on it.
24817
+ */
24818
+ function isDefinitivelyNotSubmitted(err) {
24819
+ return (err instanceof BatchRevertedError || batchOutcomeOf(err) === 'failed');
24820
+ }
24549
24821
 
24822
+ // ---------------------------------------------------------------------------
24823
+ // The selector tables
24824
+ // ---------------------------------------------------------------------------
24550
24825
  /**
24551
- * The run lifecycle both flows share: one run at a time, every transition
24552
- * published, and a `reset()` that is safe to call in the middle of one.
24553
- *
24554
- * `DepositFlow` and `WithdrawFlow` each carried their own copy of this — the
24555
- * re-entrancy guard, the `try/finally` around the run, `state`, `isRunning`,
24556
- * `subscribe`, `reset`. Two copies of a guard is two places for a guard to be
24557
- * wrong, on the money path, which is the same reason the pipelines themselves
24558
- * moved out of the applications.
24559
- *
24560
- * ## The guard and the run token are separate, and both matter
24826
+ * OpenZeppelin v5's ERC-20 errors. They are not in either Kasu ABI because no
24827
+ * Kasu contract declares them — they arrive from the TOKEN, through the
24828
+ * manager's `transferFrom`, and they are the modern spelling of the string
24829
+ * reverts below.
24830
+ */
24831
+ const ERC20_ERROR_ABI = [
24832
+ 'error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed)',
24833
+ 'error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed)',
24834
+ ];
24835
+ /**
24836
+ * The protocol errors that mean the ERC-20 transfer failed rather than the
24837
+ * protocol refusing.
24561
24838
  *
24562
- * `_runToken` is the re-entrancy guard: claimed synchronously, before the
24563
- * first `await`, so a double tap cannot launch two pipelines. The store's
24564
- * `generation` is the abandonment mechanism: an in-flight run holds the value
24565
- * it claimed, and every `patch` and `isCurrent` checkpoint it makes after
24566
- * `reset()` is dropped.
24839
+ * `SafeERC20FailedOperation` is OpenZeppelin's wrapper around a token call
24840
+ * that returned false or reverted, which on this path IS the `transferFrom`;
24841
+ * `AddressInsufficientBalance` is its native-value sibling. Both belong with
24842
+ * the balance case, not with the pool conditions — a lender who sees one of
24843
+ * them really does need to fund or re-approve.
24844
+ */
24845
+ const ERC20_FAMILY_NAMES = new Set([
24846
+ 'AddressInsufficientBalance',
24847
+ 'ERC20InsufficientAllowance',
24848
+ 'ERC20InsufficientBalance',
24849
+ 'SafeERC20FailedOperation',
24850
+ ]);
24851
+ /** Solidity's `Error(string)`, the selector every `require` reason arrives under. */
24852
+ const STRING_REVERT_SELECTOR = '0x08c379a0';
24853
+ /**
24854
+ * The `require` reasons that are a balance or an allowance, across the token
24855
+ * implementations in circulation: OpenZeppelin v4's sentences, and the
24856
+ * shorthand the minimal implementations use.
24857
+ */
24858
+ const ERC20_REASON_PATTERNS = [
24859
+ /exceeds\s+balance/,
24860
+ /exceeds\s+allowance/,
24861
+ /insufficient\s+balance/,
24862
+ /insufficient\s+allowance/,
24863
+ /transfer_from_failed/,
24864
+ /transferfrom\s+failed/,
24865
+ /low-level\s+call\s+failed/,
24866
+ ];
24867
+ /**
24868
+ * selector → error name, built once on first use.
24567
24869
  *
24568
- * `reset()` releases the guard IMMEDIATELY rather than waiting for the
24569
- * abandoned run to notice. It has to: a run parked on a wallet prompt that
24570
- * never answers is a promise that may never settle, and a consumer that has
24571
- * left that screen must be able to start a new run in the same tick. The
24572
- * abandoned run's `finally` therefore releases the guard only if it still
24573
- * holds it — by then a NEW run may own it, and clearing it there would let a
24574
- * third run start alongside the second.
24870
+ * Lazily, because a consumer that never sees a revert should not pay for three
24871
+ * `Interface` constructions at import. The two Kasu tables are the GENERATED
24872
+ * typechain ABIs, so this cannot drift from the contracts: regenerate the ABIs
24873
+ * and the new errors are recognised with no edit here.
24575
24874
  */
24576
- class Flow {
24577
- constructor(initial) {
24875
+ let selectorTable = null;
24876
+ function selectors() {
24877
+ if (selectorTable)
24878
+ return selectorTable;
24879
+ const table = new Map();
24880
+ const interfaces = [
24881
+ // The manager the deposit is called against, and the allow list it
24882
+ // delegates the KYC and block-window checks to.
24883
+ ILendingPoolManagerAbi__factory.createInterface(),
24884
+ IKasuAllowListAbi__factory.createInterface(),
24885
+ new ethers.ethers.utils.Interface(ERC20_ERROR_ABI),
24886
+ ];
24887
+ for (const iface of interfaces) {
24888
+ for (const fragment of Object.values(iface.errors)) {
24889
+ // First writer wins: the same name declared by both ABIs is the
24890
+ // same selector, so the duplicate would be a no-op anyway.
24891
+ const sighash = iface.getSighash(fragment);
24892
+ if (!table.has(sighash))
24893
+ table.set(sighash, fragment.name);
24894
+ }
24895
+ }
24896
+ selectorTable = table;
24897
+ return table;
24898
+ }
24899
+ // ---------------------------------------------------------------------------
24900
+ // Getting the bytes out of the envelope
24901
+ // ---------------------------------------------------------------------------
24902
+ /**
24903
+ * How deep to look for the revert data. Providers nest it differently —
24904
+ * ethers' own error wraps the provider's, which wraps the RPC body — and a
24905
+ * bound is what keeps a self-referencing error object from being walked
24906
+ * forever.
24907
+ */
24908
+ const MAX_DEPTH = 6;
24909
+ /** The keys ethers and the providers under it put a wrapped error on. */
24910
+ const NESTED_KEYS = [
24911
+ 'data',
24912
+ 'error',
24913
+ 'originalError',
24914
+ 'info',
24915
+ 'cause',
24916
+ 'body',
24917
+ ];
24918
+ /** At least a 4-byte selector, and a whole number of bytes. */
24919
+ function isRevertData(value) {
24920
+ return (value.length >= 10 &&
24921
+ value.length % 2 === 0 &&
24922
+ /^0x[0-9a-fA-F]+$/.test(value));
24923
+ }
24924
+ /**
24925
+ * Find the revert data on an error, wherever the provider left it.
24926
+ *
24927
+ * ethers v5 raises `UNPREDICTABLE_GAS_LIMIT` with the provider's own error
24928
+ * attached, and each provider nests the bytes one layer differently:
24929
+ * `error.data`, `error.error.data`, `error.data.originalError.data`, or only
24930
+ * inside the JSON `body` of a `SERVER_ERROR`. Rather than enumerate the
24931
+ * products, walk a fixed set of keys to a fixed depth and take the first value
24932
+ * that is shaped like revert data.
24933
+ */
24934
+ function extractRevertData(err) {
24935
+ return walk(err, 0);
24936
+ }
24937
+ function walk(node, depth) {
24938
+ if (node == null || depth > MAX_DEPTH)
24939
+ return null;
24940
+ if (typeof node === 'string') {
24941
+ if (isRevertData(node))
24942
+ return node;
24943
+ // A `SERVER_ERROR`'s body: the RPC's JSON reply, verbatim.
24944
+ if (!node.startsWith('{'))
24945
+ return null;
24946
+ try {
24947
+ return walk(JSON.parse(node), depth + 1);
24948
+ }
24949
+ catch (_a) {
24950
+ return null;
24951
+ }
24952
+ }
24953
+ if (typeof node !== 'object')
24954
+ return null;
24955
+ const record = node;
24956
+ for (const key of NESTED_KEYS) {
24957
+ const found = walk(record[key], depth + 1);
24958
+ if (found)
24959
+ return found;
24960
+ }
24961
+ return null;
24962
+ }
24963
+ // ---------------------------------------------------------------------------
24964
+ // Decoding
24965
+ // ---------------------------------------------------------------------------
24966
+ /**
24967
+ * Decode a failed call's revert into the error the contract named, or `null`
24968
+ * when there is nothing recognisable to name.
24969
+ *
24970
+ * `null` is the honest answer for an unknown selector, an unrelated `require`
24971
+ * string, or an error with no revert data at all — the caller keeps whatever
24972
+ * it did before rather than inventing a diagnosis from bytes it cannot read.
24973
+ */
24974
+ function decodeRevert(err) {
24975
+ const data = extractRevertData(err);
24976
+ if (!data)
24977
+ return null;
24978
+ const selector = data.slice(0, 10).toLowerCase();
24979
+ if (selector === STRING_REVERT_SELECTOR) {
24980
+ const reason = decodeStringRevert(data);
24981
+ if (reason === null)
24982
+ return null;
24983
+ return isErc20Reason(reason)
24984
+ ? { name: 'Error', family: 'erc20', reason }
24985
+ : null;
24986
+ }
24987
+ const name = selectors().get(selector);
24988
+ if (!name)
24989
+ return null;
24990
+ return {
24991
+ name,
24992
+ family: ERC20_FAMILY_NAMES.has(name) ? 'erc20' : 'protocol',
24993
+ };
24994
+ }
24995
+ function decodeStringRevert(data) {
24996
+ try {
24997
+ const [reason] = ethers.ethers.utils.defaultAbiCoder.decode(['string'], `0x${data.slice(10)}`);
24998
+ return reason;
24999
+ }
25000
+ catch (_a) {
25001
+ return null;
25002
+ }
25003
+ }
25004
+ function isErc20Reason(reason) {
25005
+ const lower = reason.toLowerCase();
25006
+ return ERC20_REASON_PATTERNS.some((pattern) => pattern.test(lower));
25007
+ }
25008
+
25009
+ /**
25010
+ * The money-path checks around an atomic, sponsored deposit batch — the
25011
+ * `approve + requestDepositWithKyc` pair `DepositFlow` hands its
25012
+ * `depositBatch` port.
25013
+ *
25014
+ * Two questions, both PURE:
25015
+ *
25016
+ * 1. Before anything is signed: is this batch exactly the deposit this run
25017
+ * asked for? (`validateDepositBatchCalls`)
25018
+ * 2. After it is mined: did THIS receipt deposit THIS amount, for THIS
25019
+ * lender, into THIS tranche? (`proveDepositInReceipt`)
25020
+ *
25021
+ * Neither knows a relay, a wallet vendor or a URL; the app's submitter calls
25022
+ * them.
25023
+ */
25024
+ /**
25025
+ * ERC-4337 EntryPoint v0.7 — the contract a bundler calls `handleOps` on. The
25026
+ * proof reads the user operation's outcome from ITS events, and from no other
25027
+ * contract's.
25028
+ */
25029
+ const ENTRY_POINT_V07 = '0x0000000071727De22E5E9d8BAf0edAc6f37da032';
25030
+ /** EntryPoint v0.7 events (eth-infinitism `IEntryPoint`). */
25031
+ const ENTRY_POINT_EVENTS = new ethers.utils.Interface([
25032
+ 'event UserOperationEvent(bytes32 indexed userOpHash, address indexed sender, address indexed paymaster, uint256 nonce, bool success, uint256 actualGasCost, uint256 actualGasUsed)',
25033
+ 'event UserOperationRevertReason(bytes32 indexed userOpHash, address indexed sender, uint256 nonce, bytes revertReason)',
25034
+ 'event BeforeExecution()',
25035
+ ]);
25036
+ /** kasu-contracts `IPendingPool` — emitted by the strategy's pending pool. */
25037
+ const PENDING_POOL_EVENTS = new ethers.utils.Interface([
25038
+ 'event DepositRequested(address indexed user, address indexed tranche, uint256 indexed dNftID, uint256 epochId, uint256 amount)',
25039
+ ]);
25040
+ const USER_OPERATION_EVENT = ENTRY_POINT_EVENTS.getEventTopic('UserOperationEvent');
25041
+ const USER_OPERATION_REVERT_REASON = ENTRY_POINT_EVENTS.getEventTopic('UserOperationRevertReason');
25042
+ const BEFORE_EXECUTION = ENTRY_POINT_EVENTS.getEventTopic('BeforeExecution');
25043
+ const DEPOSIT_REQUESTED = PENDING_POOL_EVENTS.getEventTopic('DepositRequested');
25044
+ const ERC20$1 = IERC20MetadataAbi__factory.createInterface();
25045
+ const LENDING_POOL_MANAGER$1 = ILendingPoolManagerAbi__factory.createInterface();
25046
+ const ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
25047
+ /**
25048
+ * Case-insensitive address equality; `false` for anything that is not a
25049
+ * 20-byte hex address. Checksums are not enforced — an all-lowercase address
25050
+ * is the subgraph's own spelling.
25051
+ */
25052
+ function sameAddress(a, b) {
25053
+ return (typeof a === 'string' &&
25054
+ typeof b === 'string' &&
25055
+ ADDRESS_RE.test(a) &&
25056
+ ADDRESS_RE.test(b) &&
25057
+ a.toLowerCase() === b.toLowerCase());
25058
+ }
25059
+ function isHexData(value) {
25060
+ return typeof value === 'string' && ethers.utils.isHexString(value);
25061
+ }
25062
+ /**
25063
+ * What `validateDepositBatchCalls` throws. `code` says which pin failed; the
25064
+ * message names no party, so a wallet-rejection classifier can never read it
25065
+ * as something the lender did.
25066
+ */
25067
+ class DepositBatchMismatchError extends Error {
25068
+ constructor(code) {
25069
+ super(`Deposit batch does not match the run (${code})`);
25070
+ this.name = 'DepositBatchMismatchError';
25071
+ this.code = code;
25072
+ Object.setPrototypeOf(this, DepositBatchMismatchError.prototype);
25073
+ }
25074
+ }
25075
+ function mismatch(code) {
25076
+ throw new DepositBatchMismatchError(code);
25077
+ }
25078
+ function isCallShape(call) {
25079
+ if (call === null || typeof call !== 'object')
25080
+ return false;
25081
+ const { to, data } = call;
25082
+ return typeof to === 'string' && ADDRESS_RE.test(to) && isHexData(data);
25083
+ }
25084
+ function isZeroValue(value) {
25085
+ if (value === undefined)
25086
+ return true;
25087
+ try {
25088
+ return ethers.BigNumber.from(value).isZero();
25089
+ }
25090
+ catch (_a) {
25091
+ return false;
25092
+ }
25093
+ }
25094
+ function sameAmount(a, b) {
25095
+ return ethers.BigNumber.isBigNumber(a) && a.eq(b);
25096
+ }
25097
+ /**
25098
+ * Decode `data` as a call to `name` on `iface`, and refuse it unless it is
25099
+ * the CANONICAL encoding of what it decodes to. The ABI decoder tolerates
25100
+ * trailing bytes and non-minimal offsets; a signature over bytes that decode
25101
+ * "the same" but are not the bytes the SDK produced is not a signature over
25102
+ * this run's deposit.
25103
+ */
25104
+ function decodeCanonical(iface, name, data, code) {
25105
+ let parsed;
25106
+ try {
25107
+ parsed = iface.parseTransaction({ data });
25108
+ }
25109
+ catch (_a) {
25110
+ return mismatch(code);
25111
+ }
25112
+ if (parsed.name !== name)
25113
+ return mismatch(code);
25114
+ let canonical;
25115
+ try {
25116
+ canonical = iface.encodeFunctionData(parsed.functionFragment, parsed.args);
25117
+ }
25118
+ catch (_b) {
25119
+ return mismatch(code);
25120
+ }
25121
+ if (canonical.toLowerCase() !== data.toLowerCase()) {
25122
+ return mismatch('non-canonical-encoding');
25123
+ }
25124
+ return parsed.args;
25125
+ }
25126
+ /**
25127
+ * Pin a deposit batch to the run that produced it — PURE; throws a
25128
+ * `DepositBatchMismatchError` on ANY deviation, before the lender's key signs
25129
+ * anything.
25130
+ *
25131
+ * The batch must be exactly two calls, in this order, with no native value:
25132
+ *
25133
+ * 0. `stableAsset.approve(spender, A)`;
25134
+ * 1. `spender.requestDepositWithKyc(poolId, trancheId, A, '0x', fixedTermConfigId, …)`;
25135
+ *
25136
+ * with `A` the run's own amount in BOTH — never more, never unlimited (house
25137
+ * rule: exact-amount approvals) — the run's own fixed-term config, each call
25138
+ * the canonical ABI encoding of its arguments, and no swap data. The deposit
25139
+ * data and KYC signature are not pinned here: they are signatures the
25140
+ * contract and the backend verify.
25141
+ *
25142
+ * This is the client's half; a relaying backend checks the same shape again.
25143
+ */
25144
+ function validateDepositBatchCalls(calls, expected) {
25145
+ const amount = ethers.BigNumber.from(expected.amount);
25146
+ if (amount.lte(0))
25147
+ mismatch('non-positive-amount');
25148
+ if (!Array.isArray(calls) || calls.length !== 2)
25149
+ mismatch('call-count');
25150
+ const [approveCall, depositCall] = calls;
25151
+ for (const call of [approveCall, depositCall]) {
25152
+ if (!isCallShape(call))
25153
+ mismatch('malformed-call');
25154
+ if (!isZeroValue(call.value))
25155
+ mismatch('native-value');
25156
+ }
25157
+ // 0 — the approval.
25158
+ if (!sameAddress(approveCall.to, expected.stableAsset)) {
25159
+ mismatch('approve-token');
25160
+ }
25161
+ const [approveSpender, approveAmount] = decodeCanonical(ERC20$1, 'approve', approveCall.data, 'approve-call');
25162
+ if (!sameAddress(approveSpender, expected.spender)) {
25163
+ mismatch('approve-spender');
25164
+ }
25165
+ // 1 — the deposit.
25166
+ if (!sameAddress(depositCall.to, expected.spender)) {
25167
+ mismatch('deposit-target');
25168
+ }
25169
+ const [pool, tranche, maxAmount, swapData, fixedTermConfigId] = decodeCanonical(LENDING_POOL_MANAGER$1, 'requestDepositWithKyc', depositCall.data, 'deposit-call');
25170
+ if (!sameAddress(pool, expected.poolId))
25171
+ mismatch('deposit-pool');
25172
+ if (!sameAddress(tranche, expected.trancheId))
25173
+ mismatch('deposit-tranche');
25174
+ if (swapData !== '0x')
25175
+ mismatch('swap-data');
25176
+ if (!sameAmount(fixedTermConfigId, ethers.BigNumber.from(expected.fixedTermConfigId))) {
25177
+ mismatch('fixed-term-config');
25178
+ }
25179
+ // EXACT amount, on both calls, equal to the run's.
25180
+ if (!sameAmount(approveAmount, amount))
25181
+ mismatch('approve-amount');
25182
+ if (!sameAmount(maxAmount, amount))
25183
+ mismatch('deposit-amount');
25184
+ return { tranche: tranche, amount };
25185
+ }
25186
+ /** A log's first topic, lowercased; `undefined` for a log without a topic array. */
25187
+ function topicOf(log) {
25188
+ var _a;
25189
+ return Array.isArray(log.topics)
25190
+ ? (_a = log.topics[0]) === null || _a === void 0 ? void 0 : _a.toLowerCase()
25191
+ : undefined;
25192
+ }
25193
+ function parse(iface, log) {
25194
+ try {
25195
+ return iface.parseLog({ topics: [...log.topics], data: log.data });
25196
+ }
25197
+ catch (_a) {
25198
+ return null;
25199
+ }
25200
+ }
25201
+ /**
25202
+ * Did THIS receipt deposit for THIS lender? — PURE.
25203
+ *
25204
+ * A sponsored batch lands as a bundler's `handleOps` transaction, and that
25205
+ * transaction's `status` is success even when the user operation inside it
25206
+ * reverted: the EntryPoint catches the revert, the account rolls back both
25207
+ * calls, nothing is deposited. So `status` decides NOTHING. What does:
25208
+ *
25209
+ * 1. The EntryPoint's `UserOperationEvent` for OUR operation — emitted BY
25210
+ * the EntryPoint, `sender` = lender, and `userOpHash` = the known hash
25211
+ * when there is one.
25212
+ * 2. Its `success` flag. `false` → `reverted`, naming the protocol error
25213
+ * from the matching `UserOperationRevertReason` when it decodes.
25214
+ * 3. A `DepositRequested` with `user` = lender, `tranche` = the run's and
25215
+ * `amount` = the run's, INSIDE our operation's execution: the logs after
25216
+ * the previous operation's event (or `BeforeExecution`, which precedes
25217
+ * the first) and before ours. A deposit from another operation in the
25218
+ * same bundle does not count, and neither does one emitted by a contract
25219
+ * that is not the pending pool, when the pending pool is known.
25220
+ *
25221
+ * Anything short of all three is `unproven`, which a consumer must treat as
25222
+ * PENDING — the money may have moved — and never as a failure.
25223
+ */
25224
+ function proveDepositInReceipt(receipt, expected) {
25225
+ // Typed as an array, but a receipt is foreign data: check before reading.
25226
+ if (!Array.isArray(receipt.logs)) {
25227
+ return { kind: 'unproven', reason: 'malformed-receipt' };
25228
+ }
25229
+ const amount = ethers.BigNumber.from(expected.amount);
25230
+ const op = locateUserOperation(receipt.logs, {
25231
+ sender: expected.lender,
25232
+ userOperationHash: expected.userOperationHash,
25233
+ entryPoint: expected.entryPoint,
25234
+ });
25235
+ if (op === null)
25236
+ return { kind: 'unproven', reason: 'no-user-operation' };
25237
+ if (op === 'ambiguous') {
25238
+ return { kind: 'unproven', reason: 'ambiguous-operation' };
25239
+ }
25240
+ if (!op.success) {
25241
+ return { kind: 'reverted', revertError: op.revertError() };
25242
+ }
25243
+ for (const log of op.window) {
25244
+ if (topicOf(log) !== DEPOSIT_REQUESTED)
25245
+ continue;
25246
+ if (expected.pendingPool !== undefined &&
25247
+ !sameAddress(log.address, expected.pendingPool)) {
25248
+ continue;
25249
+ }
25250
+ const decoded = parse(PENDING_POOL_EVENTS, log);
25251
+ if ((decoded === null || decoded === void 0 ? void 0 : decoded.name) !== 'DepositRequested')
25252
+ continue;
25253
+ if (!sameAddress(decoded.args.user, expected.lender))
25254
+ continue;
25255
+ if (!sameAddress(decoded.args.tranche, expected.tranche))
25256
+ continue;
25257
+ if (!sameAmount(decoded.args.amount, amount))
25258
+ continue;
25259
+ return {
25260
+ kind: 'deposited',
25261
+ dNftId: decoded.args.dNftID,
25262
+ blockNumber: receipt.blockNumber,
25263
+ };
25264
+ }
25265
+ return { kind: 'unproven', reason: 'no-deposit-requested' };
25266
+ }
25267
+ /**
25268
+ * Did THIS receipt execute the sender's user operation? — PURE. The
25269
+ * single-call sibling of `proveDepositInReceipt`, for a sponsored
25270
+ * `requestWithdrawal`, a cancel or a fixed-term withdrawal: the same
25271
+ * EntryPoint `UserOperationEvent` from the same contract, for the same
25272
+ * sender (and hash, when known), read the same way — the `handleOps`
25273
+ * transaction's own `status` decides NOTHING, because it is a success even
25274
+ * when the operation inside it reverted.
25275
+ *
25276
+ * `executed` needs the operation's `success` flag. A single-call operation
25277
+ * that succeeded executed its one call; there is no event to match beyond
25278
+ * that, so pass the `userOperationHash` whenever the submitter reports one —
25279
+ * without it, the sender's ONLY operation in the bundle is the one read, and a
25280
+ * bundle holding two of theirs is `ambiguous-operation` (pending), never the
25281
+ * first one's verdict: with one succeeded and one reverted, "executed" would
25282
+ * tell the lender their request is queued when it is not.
25283
+ */
25284
+ function proveUserOperationInReceipt(receipt, expected) {
25285
+ if (!Array.isArray(receipt.logs)) {
25286
+ return { kind: 'unproven', reason: 'malformed-receipt' };
25287
+ }
25288
+ const op = locateUserOperation(receipt.logs, expected);
25289
+ if (op === null)
25290
+ return { kind: 'unproven', reason: 'no-user-operation' };
25291
+ if (op === 'ambiguous') {
25292
+ return { kind: 'unproven', reason: 'ambiguous-operation' };
25293
+ }
25294
+ if (!op.success) {
25295
+ return { kind: 'reverted', revertError: op.revertError() };
25296
+ }
25297
+ return { kind: 'executed', blockNumber: receipt.blockNumber };
25298
+ }
25299
+ /**
25300
+ * The sender's user operation in a `handleOps` receipt — its `success` flag
25301
+ * and its execution window — `null` when the receipt does not show one, or
25302
+ * `'ambiguous'` when no hash was given and it shows more than one of theirs.
25303
+ *
25304
+ * - The `UserOperationEvent` must be emitted BY the EntryPoint, with
25305
+ * `sender` = the expected sender and, when one is known, `userOpHash` =
25306
+ * the expected hash. Without a hash the sender must have exactly ONE
25307
+ * operation in the bundle: a bundler may pack two of theirs (sequential
25308
+ * nonces, or parallel nonce keys), and reading the first would attribute
25309
+ * the other one's verdict to this call.
25310
+ * - The window is the logs after the previous operation's event (or
25311
+ * `BeforeExecution`, which precedes the first) and before ours: what our
25312
+ * operation's calls emitted, and nothing another operation in the same
25313
+ * bundle did.
25314
+ */
25315
+ function locateUserOperation(logs, expected) {
25316
+ var _a, _b, _c;
25317
+ const entryPoint = (_a = expected.entryPoint) !== null && _a !== void 0 ? _a : ENTRY_POINT_V07;
25318
+ const wantedHash = (_c = (_b = expected.userOperationHash) === null || _b === void 0 ? void 0 : _b.toLowerCase()) !== null && _c !== void 0 ? _c : null;
25319
+ const fromEntryPoint = (log) => sameAddress(log.address, entryPoint);
25320
+ let opIndex = -1;
25321
+ let success = false;
25322
+ for (let i = 0; i < logs.length; i += 1) {
25323
+ const log = logs[i];
25324
+ if (!fromEntryPoint(log) || topicOf(log) !== USER_OPERATION_EVENT) {
25325
+ continue;
25326
+ }
25327
+ const decoded = parse(ENTRY_POINT_EVENTS, log);
25328
+ if ((decoded === null || decoded === void 0 ? void 0 : decoded.name) !== 'UserOperationEvent')
25329
+ continue;
25330
+ const userOpHash = String(decoded.args.userOpHash).toLowerCase();
25331
+ if (wantedHash !== null && userOpHash !== wantedHash)
25332
+ continue;
25333
+ if (!sameAddress(decoded.args.sender, expected.sender))
25334
+ continue;
25335
+ // A second operation of this sender, and no hash to tell them apart.
25336
+ if (opIndex >= 0)
25337
+ return 'ambiguous';
25338
+ opIndex = i;
25339
+ success = decoded.args.success === true;
25340
+ // A hash names exactly one operation; without one, keep scanning so
25341
+ // a second operation of the sender is noticed.
25342
+ if (wantedHash !== null)
25343
+ break;
25344
+ }
25345
+ if (opIndex < 0)
25346
+ return null;
25347
+ // Our operation's execution window.
25348
+ let windowStart = 0;
25349
+ for (let i = opIndex - 1; i >= 0; i -= 1) {
25350
+ const log = logs[i];
25351
+ const topic = topicOf(log);
25352
+ if (fromEntryPoint(log) &&
25353
+ (topic === USER_OPERATION_EVENT || topic === BEFORE_EXECUTION)) {
25354
+ windowStart = i + 1;
25355
+ break;
25356
+ }
25357
+ }
25358
+ const window = logs.slice(windowStart, opIndex);
25359
+ return {
25360
+ success,
25361
+ window,
25362
+ revertError: () => revertErrorIn(window, expected.sender, fromEntryPoint),
25363
+ };
25364
+ }
25365
+ /**
25366
+ * The protocol error a reverted operation named, or `''`. Only a PROTOCOL
25367
+ * error is passed on: an `Error(string)` or an ERC-20 failure is not a name a
25368
+ * consumer has words for.
25369
+ */
25370
+ function revertErrorIn(window, lender, fromEntryPoint) {
25371
+ for (const log of window) {
25372
+ if (!fromEntryPoint(log))
25373
+ continue;
25374
+ // Through the same guard as the main loop: a malformed log beside the
25375
+ // revert reason must not turn a DEFINITIVE revert into "pending".
25376
+ if (topicOf(log) !== USER_OPERATION_REVERT_REASON)
25377
+ continue;
25378
+ const decoded = parse(ENTRY_POINT_EVENTS, log);
25379
+ if ((decoded === null || decoded === void 0 ? void 0 : decoded.name) !== 'UserOperationRevertReason')
25380
+ continue;
25381
+ if (!sameAddress(decoded.args.sender, lender))
25382
+ continue;
25383
+ const revert = decodeRevert(decoded.args.revertReason);
25384
+ return (revert === null || revert === void 0 ? void 0 : revert.family) === 'protocol' ? revert.name : '';
25385
+ }
25386
+ return '';
25387
+ }
25388
+
25389
+ /**
25390
+ * First read at once, then 3 s backing off ×1.5 to a 10 s ceiling, for up to
25391
+ * 10 minutes. Running out of time is PENDING: the batch was accepted and may
25392
+ * still land.
25393
+ */
25394
+ const DEFAULT_BATCH_POLLING_POLICY = Object.freeze({
25395
+ initialMs: 3000,
25396
+ maxMs: 10000,
25397
+ backoff: 1.5,
25398
+ timeoutMs: 10 * 60 * 1000,
25399
+ });
25400
+ function resolvePolicy(policy) {
25401
+ var _a, _b, _c, _d;
25402
+ const resolved = {
25403
+ initialMs: (_a = policy === null || policy === void 0 ? void 0 : policy.initialMs) !== null && _a !== void 0 ? _a : DEFAULT_BATCH_POLLING_POLICY.initialMs,
25404
+ maxMs: (_b = policy === null || policy === void 0 ? void 0 : policy.maxMs) !== null && _b !== void 0 ? _b : DEFAULT_BATCH_POLLING_POLICY.maxMs,
25405
+ backoff: (_c = policy === null || policy === void 0 ? void 0 : policy.backoff) !== null && _c !== void 0 ? _c : DEFAULT_BATCH_POLLING_POLICY.backoff,
25406
+ timeoutMs: (_d = policy === null || policy === void 0 ? void 0 : policy.timeoutMs) !== null && _d !== void 0 ? _d : DEFAULT_BATCH_POLLING_POLICY.timeoutMs,
25407
+ };
25408
+ const { initialMs, maxMs, backoff, timeoutMs } = resolved;
25409
+ if (!(Number.isFinite(initialMs) && initialMs > 0) ||
25410
+ !(Number.isFinite(maxMs) && maxMs >= initialMs) ||
25411
+ !(Number.isFinite(backoff) && backoff >= 1) ||
25412
+ !(Number.isFinite(timeoutMs) && timeoutMs > 0)) {
25413
+ throw new TypeError('submitBatch: invalid polling policy');
25414
+ }
25415
+ return resolved;
25416
+ }
25417
+ /**
25418
+ * Submit `calls` and return once the submitter ACCEPTED them; `wait()` then
25419
+ * polls and proves. Use it as the body of a `DepositFlow` `depositBatch`
25420
+ * port, after `validateDepositBatchCalls` and the app's own signing:
25421
+ *
25422
+ * ```ts
25423
+ * depositBatch: (calls) => {
25424
+ * const { tranche, amount } = validateDepositBatchCalls(calls, expected);
25425
+ * return submitBatch(
25426
+ * // `pendingPool`: the strategy's pending pool, so only ITS
25427
+ * // `DepositRequested` can prove the deposit.
25428
+ * { calls, expect: { lender, tranche, amount, pendingPool } },
25429
+ * { post, getStatus, getReceipt, now: Date.now, sleep },
25430
+ * );
25431
+ * },
25432
+ * ```
25433
+ *
25434
+ * | what happened | outcome |
25435
+ * | ---------------------------------------------------- | ---------------------------------------- |
25436
+ * | `post` throws `BatchRevertedError` | rethrown — reverted, nothing deposited |
25437
+ * | `post` throws `BatchSubmissionError` | rethrown with its own outcome |
25438
+ * | `post` throws anything else | `BatchPendingError('post_unknown')` |
25439
+ * | `post` resolves without a transaction id | `BatchPendingError('malformed_answer')` |
25440
+ * | status `reverted` | `BatchRevertedError('')` |
25441
+ * | status `unknown` | `BatchPendingError(code)` |
25442
+ * | polling runs out of time | `BatchPendingError('status_timeout')` |
25443
+ * | receipt unreadable | `BatchPendingError('receipt_unavailable')` |
25444
+ * | receipt: user operation reverted | `BatchRevertedError(revertError)` |
25445
+ * | receipt: this deposit not shown | `BatchPendingError('deposit_unproven:<reason>')` |
25446
+ * | receipt: this lender's deposit, tranche and amount | resolves `ProvenBatch` |
25447
+ *
25448
+ * Nothing on this path ever produces a `failed` outcome: by the time a batch
25449
+ * has been posted, only a revert proves that nothing was deposited.
25450
+ */
25451
+ function submitBatch(input, ports, policy) {
25452
+ return __awaiter(this, void 0, void 0, function* () {
25453
+ const resolved = resolvePolicy(policy);
25454
+ const transactionId = yield postOnce(() => ports.post(input.calls));
25455
+ let settled = null;
25456
+ return {
25457
+ transactionId,
25458
+ // Memoised: a second `wait()` reads the same outcome instead of
25459
+ // polling the submitter twice.
25460
+ wait: () => (settled !== null && settled !== void 0 ? settled : (settled = settle(transactionId, input.expect, ports, resolved))),
25461
+ };
25462
+ });
25463
+ }
25464
+ /**
25465
+ * The post, and what its answer means: the transaction id, or the error the
25466
+ * outcome table names. Shared by both submitters, so the two cannot come to
25467
+ * disagree about which throws are ambiguous.
25468
+ */
25469
+ function postOnce(post) {
25470
+ return __awaiter(this, void 0, void 0, function* () {
25471
+ let accepted;
25472
+ try {
25473
+ accepted = yield post();
25474
+ }
25475
+ catch (err) {
25476
+ if (err instanceof BatchRevertedError)
25477
+ throw err;
25478
+ if (err instanceof BatchSubmissionError)
25479
+ throw err;
25480
+ throw new BatchPendingError('post_unknown', { cause: err });
25481
+ }
25482
+ const transactionId = accepted === null || accepted === void 0 ? void 0 : accepted.transactionId;
25483
+ if (typeof transactionId !== 'string' || transactionId === '') {
25484
+ throw new BatchPendingError('malformed_answer');
25485
+ }
25486
+ return transactionId;
25487
+ });
25488
+ }
25489
+ function readStatus(ports, transactionId) {
25490
+ return __awaiter(this, void 0, void 0, function* () {
25491
+ try {
25492
+ return yield ports.getStatus(transactionId);
25493
+ }
25494
+ catch (_a) {
25495
+ return { kind: 'again' };
25496
+ }
25497
+ });
25498
+ }
25499
+ /** Poll until a mined hash, or a typed reason there will not be one. */
25500
+ function waitForMined(transactionId, ports, policy) {
25501
+ return __awaiter(this, void 0, void 0, function* () {
25502
+ var _a;
25503
+ const deadline = ports.now() + policy.timeoutMs;
25504
+ let userOperationHash = null;
25505
+ let delay = policy.initialMs;
25506
+ for (;;) {
25507
+ const read = yield readStatus(ports, transactionId);
25508
+ switch (read.kind) {
25509
+ case 'mined':
25510
+ if (typeof read.txHash !== 'string' || read.txHash === '') {
25511
+ break; // a malformed "mined" is not an answer; ask again
25512
+ }
25513
+ return {
25514
+ txHash: read.txHash,
25515
+ userOperationHash: (_a = read.userOperationHash) !== null && _a !== void 0 ? _a : userOperationHash,
25516
+ };
25517
+ case 'reverted':
25518
+ throw new BatchRevertedError('');
25519
+ case 'unknown':
25520
+ throw new BatchPendingError(read.code);
25521
+ case 'again':
25522
+ if (read.userOperationHash) {
25523
+ userOperationHash = read.userOperationHash;
25524
+ }
25525
+ break;
25526
+ }
25527
+ if (ports.now() + delay > deadline) {
25528
+ throw new BatchPendingError('status_timeout');
25529
+ }
25530
+ yield ports.sleep(delay);
25531
+ delay = Math.min(policy.maxMs, Math.round(delay * policy.backoff));
25532
+ }
25533
+ });
25534
+ }
25535
+ /** Poll to a mined hash and read its receipt; a receipt read that throws is PENDING. */
25536
+ function minedReceipt(transactionId, ports, policy) {
25537
+ return __awaiter(this, void 0, void 0, function* () {
25538
+ const mined = yield waitForMined(transactionId, ports, policy);
25539
+ try {
25540
+ return {
25541
+ receipt: yield ports.getReceipt(mined.txHash),
25542
+ txHash: mined.txHash,
25543
+ userOperationHash: mined.userOperationHash,
25544
+ };
25545
+ }
25546
+ catch (err) {
25547
+ throw new BatchPendingError('receipt_unavailable', { cause: err });
25548
+ }
25549
+ });
25550
+ }
25551
+ function settle(transactionId, expect, ports, policy) {
25552
+ return __awaiter(this, void 0, void 0, function* () {
25553
+ const mined = yield minedReceipt(transactionId, ports, policy);
25554
+ let proof;
25555
+ try {
25556
+ proof = proveDepositInReceipt(mined.receipt, Object.assign(Object.assign({}, expect), { userOperationHash: mined.userOperationHash }));
25557
+ }
25558
+ catch (err) {
25559
+ // A receipt the proof cannot even read proves nothing either way.
25560
+ throw new BatchPendingError('deposit_unproven', { cause: err });
25561
+ }
25562
+ if (proof.kind === 'reverted')
25563
+ throw new BatchRevertedError(proof.revertError);
25564
+ if (proof.kind === 'unproven') {
25565
+ // The proof's reason rides in the code: "no-user-operation" (the hash
25566
+ // is not this lender's operation at all) and "no-deposit-requested"
25567
+ // (the operation ran and shows no deposit) are the two things an
25568
+ // operator reading the alert needs to tell apart first.
25569
+ throw new BatchPendingError(`deposit_unproven:${proof.reason}`);
25570
+ }
25571
+ return { proof, receipt: mined.receipt, txHash: mined.txHash };
25572
+ });
25573
+ }
25574
+ /**
25575
+ * What became of an earlier submission that ended PENDING — ONE status read,
25576
+ * no polling — for an app's guard against lending twice:
25577
+ *
25578
+ * - `deposited` — mined, and the receipt proves the deposit;
25579
+ * - `not-deposited` — definitively reverted (vendor status or the user
25580
+ * operation's own flag);
25581
+ * - `unknown` — anything else, including a read or receipt that failed.
25582
+ *
25583
+ * Only `not-deposited` may let a new lend proceed unprompted; `deposited`
25584
+ * means the lender is told the earlier one landed (`already-submitted`).
25585
+ */
25586
+ function checkBatchOutcome(transactionId, expect, ports) {
25587
+ return __awaiter(this, void 0, void 0, function* () {
25588
+ var _a;
25589
+ let read;
25590
+ try {
25591
+ read = yield ports.getStatus(transactionId);
25592
+ }
25593
+ catch (_b) {
25594
+ return 'unknown';
25595
+ }
25596
+ if (read.kind === 'reverted')
25597
+ return 'not-deposited';
25598
+ if (read.kind !== 'mined' || typeof read.txHash !== 'string') {
25599
+ return 'unknown';
25600
+ }
25601
+ try {
25602
+ const receipt = yield ports.getReceipt(read.txHash);
25603
+ const proof = proveDepositInReceipt(receipt, Object.assign(Object.assign({}, expect), { userOperationHash: (_a = read.userOperationHash) !== null && _a !== void 0 ? _a : null }));
25604
+ if (proof.kind === 'deposited')
25605
+ return 'deposited';
25606
+ if (proof.kind === 'reverted')
25607
+ return 'not-deposited';
25608
+ return 'unknown';
25609
+ }
25610
+ catch (_c) {
25611
+ return 'unknown';
25612
+ }
25613
+ });
25614
+ }
25615
+ /**
25616
+ * `submitBatch` for ONE sponsored `LendingPoolManager` call — the body of a
25617
+ * `WithdrawFlow` `submitCall` port, and of an app's cancel or
25618
+ * withdraw-at-expiry action. Same post, same polling policy, same outcome
25619
+ * table; the proof is `proveUserOperationInReceipt` (the sender's operation
25620
+ * succeeded) instead of the deposit proof, and an unproven receipt is
25621
+ * `call_unproven:<reason>`.
25622
+ *
25623
+ * ```ts
25624
+ * submitCall: (call) =>
25625
+ * submitSponsoredCall(
25626
+ * { call, expect: { sender: lender } },
25627
+ * { post: (c) => postToMyRelay(c.kind, [c.call]), getStatus, getReceipt, now, sleep },
25628
+ * ),
25629
+ * ```
25630
+ *
25631
+ * The call is checked against its kind before anything is posted — a known
25632
+ * kind, exactly `{ to, data }`, and `data` opening with that kind's selector —
25633
+ * and a mismatch is `BatchSubmissionError('call_mismatch', 'failed')`: nothing
25634
+ * was sent. Build calls with `kasu.calls`, and this never fires.
25635
+ *
25636
+ * As on the deposit path, nothing after the post ever produces `failed`.
25637
+ */
25638
+ function submitSponsoredCall(input, ports, policy) {
25639
+ return __awaiter(this, void 0, void 0, function* () {
25640
+ const resolved = resolvePolicy(policy);
25641
+ if (!isWellFormedSponsoredCall(input.call)) {
25642
+ throw new BatchSubmissionError('call_mismatch', 'failed');
25643
+ }
25644
+ const transactionId = yield postOnce(() => ports.post(input.call));
25645
+ let settled = null;
25646
+ return {
25647
+ transactionId,
25648
+ wait: () => (settled !== null && settled !== void 0 ? settled : (settled = settleCall(transactionId, input.expect, ports, resolved))),
25649
+ };
25650
+ });
25651
+ }
25652
+ function isWellFormedSponsoredCall(value) {
25653
+ if (value === null || typeof value !== 'object')
25654
+ return false;
25655
+ const { kind, call } = value;
25656
+ if (typeof kind !== 'string' ||
25657
+ !SPONSORED_CALL_KINDS.includes(kind)) {
25658
+ return false;
25659
+ }
25660
+ if (call === null || typeof call !== 'object')
25661
+ return false;
25662
+ const keys = Object.keys(call);
25663
+ if (keys.length !== 2 || !keys.includes('to') || !keys.includes('data')) {
25664
+ return false;
25665
+ }
25666
+ const { to, data } = call;
25667
+ return (typeof to === 'string' &&
25668
+ /^0x[0-9a-fA-F]{40}$/.test(to) &&
25669
+ typeof data === 'string' &&
25670
+ /^0x(?:[0-9a-fA-F]{2})*$/.test(data) &&
25671
+ data
25672
+ .toLowerCase()
25673
+ .startsWith(SPONSORED_CALL_SELECTORS[kind]));
25674
+ }
25675
+ function settleCall(transactionId, expect, ports, policy) {
25676
+ return __awaiter(this, void 0, void 0, function* () {
25677
+ const mined = yield minedReceipt(transactionId, ports, policy);
25678
+ let proof;
25679
+ try {
25680
+ proof = proveUserOperationInReceipt(mined.receipt, Object.assign(Object.assign({}, expect), { userOperationHash: mined.userOperationHash }));
25681
+ }
25682
+ catch (err) {
25683
+ throw new BatchPendingError('call_unproven', { cause: err });
25684
+ }
25685
+ if (proof.kind === 'reverted') {
25686
+ throw new BatchRevertedError(proof.revertError);
25687
+ }
25688
+ if (proof.kind === 'unproven') {
25689
+ throw new BatchPendingError(`call_unproven:${proof.reason}`);
25690
+ }
25691
+ return { proof, receipt: mined.receipt, txHash: mined.txHash };
25692
+ });
25693
+ }
25694
+
25695
+ /**
25696
+ * The tiny observable-state kernel both flows are built on.
25697
+ *
25698
+ * Deliberately not a framework store: no React, no signals, no dependency.
25699
+ * A flow is a long asynchronous run that has to publish every transition to
25700
+ * whatever is rendering it, and has to be able to abandon a run that the
25701
+ * consumer walked away from. That is the whole requirement, and it is 60 lines.
25702
+ *
25703
+ * The `generation` counter is the abandonment mechanism. `reset()` bumps it;
25704
+ * an in-flight run captured the previous value, so every later `patch` it
25705
+ * attempts is dropped and every `isCurrent` checkpoint tells it to stop. It is
25706
+ * what makes `reset()` safe to call mid-flight — the run cannot resurrect a
25707
+ * dead state or, worse, drive the UI back into a phase the consumer has left.
25708
+ */
25709
+ class FlowStore {
25710
+ constructor(_initial) {
25711
+ this._initial = _initial;
25712
+ this._generation = 0;
25713
+ this._listeners = new Set();
25714
+ this._state = _initial;
25715
+ }
25716
+ get state() {
25717
+ return this._state;
25718
+ }
25719
+ /** The run token an in-flight pipeline captures at `start()`. */
25720
+ get generation() {
25721
+ return this._generation;
25722
+ }
25723
+ /** False once `reset()` (or a later `start()`) has superseded `token`. */
25724
+ isCurrent(token) {
25725
+ return this._generation === token;
25726
+ }
25727
+ /**
25728
+ * Subscribe to every transition. Returns the unsubscribe function; calling
25729
+ * it twice is harmless.
25730
+ *
25731
+ * Listeners are NOT called on subscribe — read `state` for the current
25732
+ * value. A listener that throws is not allowed to break the pipeline or
25733
+ * starve the listeners registered after it, so throws are swallowed.
25734
+ */
25735
+ subscribe(listener) {
25736
+ this._listeners.add(listener);
25737
+ return () => {
25738
+ this._listeners.delete(listener);
25739
+ };
25740
+ }
25741
+ /**
25742
+ * Merge `next` into the state and notify, unless `token` names a
25743
+ * superseded run.
25744
+ */
25745
+ patch(next, token) {
25746
+ if (token !== undefined && !this.isCurrent(token))
25747
+ return;
25748
+ this._state = Object.assign(Object.assign({}, this._state), next);
25749
+ for (const listener of [...this._listeners]) {
25750
+ try {
25751
+ listener(this._state);
25752
+ }
25753
+ catch (_a) {
25754
+ // A consumer's rendering fault is its own problem; the pipeline
25755
+ // owns real money and keeps going.
25756
+ }
25757
+ }
25758
+ }
25759
+ /**
25760
+ * Back to the initial state, abandoning any in-flight run.
25761
+ *
25762
+ * Subscribers are kept: the consumer that was watching the last run is the
25763
+ * one that will watch the next.
25764
+ */
25765
+ reset() {
25766
+ this._generation += 1;
25767
+ this.patch(this._initial);
25768
+ }
25769
+ /** Claim the next run token. Any earlier run is abandoned. */
25770
+ beginRun() {
25771
+ this._generation += 1;
25772
+ return this._generation;
25773
+ }
25774
+ }
25775
+
25776
+ /**
25777
+ * The run lifecycle both flows share: one run at a time, every transition
25778
+ * published, and a `reset()` that is safe to call in the middle of one.
25779
+ *
25780
+ * `DepositFlow` and `WithdrawFlow` each carried their own copy of this — the
25781
+ * re-entrancy guard, the `try/finally` around the run, `state`, `isRunning`,
25782
+ * `subscribe`, `reset`. Two copies of a guard is two places for a guard to be
25783
+ * wrong, on the money path, which is the same reason the pipelines themselves
25784
+ * moved out of the applications.
25785
+ *
25786
+ * ## The guard and the run token are separate, and both matter
25787
+ *
25788
+ * `_runToken` is the re-entrancy guard: claimed synchronously, before the
25789
+ * first `await`, so a double tap cannot launch two pipelines. The store's
25790
+ * `generation` is the abandonment mechanism: an in-flight run holds the value
25791
+ * it claimed, and every `patch` and `isCurrent` checkpoint it makes after
25792
+ * `reset()` is dropped.
25793
+ *
25794
+ * `reset()` releases the guard IMMEDIATELY rather than waiting for the
25795
+ * abandoned run to notice. It has to: a run parked on a wallet prompt that
25796
+ * never answers is a promise that may never settle, and a consumer that has
25797
+ * left that screen must be able to start a new run in the same tick. The
25798
+ * abandoned run's `finally` therefore releases the guard only if it still
25799
+ * holds it — by then a NEW run may own it, and clearing it there would let a
25800
+ * third run start alongside the second.
25801
+ */
25802
+ class Flow {
25803
+ constructor(initial) {
24578
25804
  /**
24579
25805
  * The token of the run currently holding the guard, or `null` when none
24580
25806
  * does. Not a boolean: releasing the guard has to be attributable to the
@@ -24778,219 +26004,32 @@ function buildLoanAgreementSignMessage(p) {
24778
26004
  * and the body sent must agree exactly, INCLUDING the address casing. This
24779
26005
  * builder lowercases, and the request body must carry the same lowercased
24780
26006
  * address; that is what both apps signing this format do today.
24781
- *
24782
- * The backend takes this path whenever the four human-readable display fields
24783
- * are absent, and documents it as permanent until the legacy app is
24784
- * decommissioned. `/contract/resolve` has no other format — every consumer
24785
- * signs this one to retrieve an existing agreement.
24786
- *
24787
- * @param timestampMs ms-epoch, and the same value sent as the body's
24788
- * `timestamp`.
24789
- */
24790
- function buildLegacyContractRequestMessage(address, timestampMs) {
24791
- return `I request contract content for ${address.toLowerCase()} at ${timestampMs}.`;
24792
- }
24793
- /**
24794
- * The `POST /contract/fullname` message.
24795
- *
24796
- * ⚠️ BYTE-EXACT PROTOCOL STRING, on the same terms as
24797
- * `buildLegacyContractRequestMessage`: kasu-backend rebuilds
24798
- * `` `I request my full name for ${address} at ${timestamp}.` `` from the
24799
- * request body and verifies the signature against it, so the body must carry
24800
- * the same lowercased address this builder signs.
24801
- *
24802
- * @param timestampMs ms-epoch, and the same value sent as the body's
24803
- * `timestamp`.
24804
- */
24805
- function buildFullNameRequestMessage(address, timestampMs) {
24806
- return `I request my full name for ${address.toLowerCase()} at ${timestampMs}.`;
24807
- }
24808
-
24809
- // ---------------------------------------------------------------------------
24810
- // The selector tables
24811
- // ---------------------------------------------------------------------------
24812
- /**
24813
- * OpenZeppelin v5's ERC-20 errors. They are not in either Kasu ABI because no
24814
- * Kasu contract declares them — they arrive from the TOKEN, through the
24815
- * manager's `transferFrom`, and they are the modern spelling of the string
24816
- * reverts below.
24817
- */
24818
- const ERC20_ERROR_ABI = [
24819
- 'error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed)',
24820
- 'error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed)',
24821
- ];
24822
- /**
24823
- * The protocol errors that mean the ERC-20 transfer failed rather than the
24824
- * protocol refusing.
24825
- *
24826
- * `SafeERC20FailedOperation` is OpenZeppelin's wrapper around a token call
24827
- * that returned false or reverted, which on this path IS the `transferFrom`;
24828
- * `AddressInsufficientBalance` is its native-value sibling. Both belong with
24829
- * the balance case, not with the pool conditions — a lender who sees one of
24830
- * them really does need to fund or re-approve.
24831
- */
24832
- const ERC20_FAMILY_NAMES = new Set([
24833
- 'AddressInsufficientBalance',
24834
- 'ERC20InsufficientAllowance',
24835
- 'ERC20InsufficientBalance',
24836
- 'SafeERC20FailedOperation',
24837
- ]);
24838
- /** Solidity's `Error(string)`, the selector every `require` reason arrives under. */
24839
- const STRING_REVERT_SELECTOR = '0x08c379a0';
24840
- /**
24841
- * The `require` reasons that are a balance or an allowance, across the token
24842
- * implementations in circulation: OpenZeppelin v4's sentences, and the
24843
- * shorthand the minimal implementations use.
24844
- */
24845
- const ERC20_REASON_PATTERNS = [
24846
- /exceeds\s+balance/,
24847
- /exceeds\s+allowance/,
24848
- /insufficient\s+balance/,
24849
- /insufficient\s+allowance/,
24850
- /transfer_from_failed/,
24851
- /transferfrom\s+failed/,
24852
- /low-level\s+call\s+failed/,
24853
- ];
24854
- /**
24855
- * selector → error name, built once on first use.
24856
- *
24857
- * Lazily, because a consumer that never sees a revert should not pay for three
24858
- * `Interface` constructions at import. The two Kasu tables are the GENERATED
24859
- * typechain ABIs, so this cannot drift from the contracts: regenerate the ABIs
24860
- * and the new errors are recognised with no edit here.
24861
- */
24862
- let selectorTable = null;
24863
- function selectors() {
24864
- if (selectorTable)
24865
- return selectorTable;
24866
- const table = new Map();
24867
- const interfaces = [
24868
- // The manager the deposit is called against, and the allow list it
24869
- // delegates the KYC and block-window checks to.
24870
- ILendingPoolManagerAbi__factory.createInterface(),
24871
- IKasuAllowListAbi__factory.createInterface(),
24872
- new ethers.ethers.utils.Interface(ERC20_ERROR_ABI),
24873
- ];
24874
- for (const iface of interfaces) {
24875
- for (const fragment of Object.values(iface.errors)) {
24876
- // First writer wins: the same name declared by both ABIs is the
24877
- // same selector, so the duplicate would be a no-op anyway.
24878
- const sighash = iface.getSighash(fragment);
24879
- if (!table.has(sighash))
24880
- table.set(sighash, fragment.name);
24881
- }
24882
- }
24883
- selectorTable = table;
24884
- return table;
24885
- }
24886
- // ---------------------------------------------------------------------------
24887
- // Getting the bytes out of the envelope
24888
- // ---------------------------------------------------------------------------
24889
- /**
24890
- * How deep to look for the revert data. Providers nest it differently —
24891
- * ethers' own error wraps the provider's, which wraps the RPC body — and a
24892
- * bound is what keeps a self-referencing error object from being walked
24893
- * forever.
24894
- */
24895
- const MAX_DEPTH = 6;
24896
- /** The keys ethers and the providers under it put a wrapped error on. */
24897
- const NESTED_KEYS = [
24898
- 'data',
24899
- 'error',
24900
- 'originalError',
24901
- 'info',
24902
- 'cause',
24903
- 'body',
24904
- ];
24905
- /** At least a 4-byte selector, and a whole number of bytes. */
24906
- function isRevertData(value) {
24907
- return (value.length >= 10 &&
24908
- value.length % 2 === 0 &&
24909
- /^0x[0-9a-fA-F]+$/.test(value));
24910
- }
24911
- /**
24912
- * Find the revert data on an error, wherever the provider left it.
24913
- *
24914
- * ethers v5 raises `UNPREDICTABLE_GAS_LIMIT` with the provider's own error
24915
- * attached, and each provider nests the bytes one layer differently:
24916
- * `error.data`, `error.error.data`, `error.data.originalError.data`, or only
24917
- * inside the JSON `body` of a `SERVER_ERROR`. Rather than enumerate the
24918
- * products, walk a fixed set of keys to a fixed depth and take the first value
24919
- * that is shaped like revert data.
24920
- */
24921
- function extractRevertData(err) {
24922
- return walk(err, 0);
24923
- }
24924
- function walk(node, depth) {
24925
- if (node == null || depth > MAX_DEPTH)
24926
- return null;
24927
- if (typeof node === 'string') {
24928
- if (isRevertData(node))
24929
- return node;
24930
- // A `SERVER_ERROR`'s body: the RPC's JSON reply, verbatim.
24931
- if (!node.startsWith('{'))
24932
- return null;
24933
- try {
24934
- return walk(JSON.parse(node), depth + 1);
24935
- }
24936
- catch (_a) {
24937
- return null;
24938
- }
24939
- }
24940
- if (typeof node !== 'object')
24941
- return null;
24942
- const record = node;
24943
- for (const key of NESTED_KEYS) {
24944
- const found = walk(record[key], depth + 1);
24945
- if (found)
24946
- return found;
24947
- }
24948
- return null;
26007
+ *
26008
+ * The backend takes this path whenever the four human-readable display fields
26009
+ * are absent, and documents it as permanent until the legacy app is
26010
+ * decommissioned. `/contract/resolve` has no other format — every consumer
26011
+ * signs this one to retrieve an existing agreement.
26012
+ *
26013
+ * @param timestampMs ms-epoch, and the same value sent as the body's
26014
+ * `timestamp`.
26015
+ */
26016
+ function buildLegacyContractRequestMessage(address, timestampMs) {
26017
+ return `I request contract content for ${address.toLowerCase()} at ${timestampMs}.`;
24949
26018
  }
24950
- // ---------------------------------------------------------------------------
24951
- // Decoding
24952
- // ---------------------------------------------------------------------------
24953
26019
  /**
24954
- * Decode a failed call's revert into the error the contract named, or `null`
24955
- * when there is nothing recognisable to name.
26020
+ * The `POST /contract/fullname` message.
24956
26021
  *
24957
- * `null` is the honest answer for an unknown selector, an unrelated `require`
24958
- * string, or an error with no revert data at all — the caller keeps whatever
24959
- * it did before rather than inventing a diagnosis from bytes it cannot read.
26022
+ * ⚠️ BYTE-EXACT PROTOCOL STRING, on the same terms as
26023
+ * `buildLegacyContractRequestMessage`: kasu-backend rebuilds
26024
+ * `` `I request my full name for ${address} at ${timestamp}.` `` from the
26025
+ * request body and verifies the signature against it, so the body must carry
26026
+ * the same lowercased address this builder signs.
26027
+ *
26028
+ * @param timestampMs ms-epoch, and the same value sent as the body's
26029
+ * `timestamp`.
24960
26030
  */
24961
- function decodeRevert(err) {
24962
- const data = extractRevertData(err);
24963
- if (!data)
24964
- return null;
24965
- const selector = data.slice(0, 10).toLowerCase();
24966
- if (selector === STRING_REVERT_SELECTOR) {
24967
- const reason = decodeStringRevert(data);
24968
- if (reason === null)
24969
- return null;
24970
- return isErc20Reason(reason)
24971
- ? { name: 'Error', family: 'erc20', reason }
24972
- : null;
24973
- }
24974
- const name = selectors().get(selector);
24975
- if (!name)
24976
- return null;
24977
- return {
24978
- name,
24979
- family: ERC20_FAMILY_NAMES.has(name) ? 'erc20' : 'protocol',
24980
- };
24981
- }
24982
- function decodeStringRevert(data) {
24983
- try {
24984
- const [reason] = ethers.ethers.utils.defaultAbiCoder.decode(['string'], `0x${data.slice(10)}`);
24985
- return reason;
24986
- }
24987
- catch (_a) {
24988
- return null;
24989
- }
24990
- }
24991
- function isErc20Reason(reason) {
24992
- const lower = reason.toLowerCase();
24993
- return ERC20_REASON_PATTERNS.some((pattern) => pattern.test(lower));
26031
+ function buildFullNameRequestMessage(address, timestampMs) {
26032
+ return `I request my full name for ${address.toLowerCase()} at ${timestampMs}.`;
24994
26033
  }
24995
26034
 
24996
26035
  /**
@@ -25148,31 +26187,6 @@ function classifyWalletFailure(step, err) {
25148
26187
  : { step, reason: 'failed', error: err };
25149
26188
  }
25150
26189
 
25151
- /**
25152
- * What a `depositBatch` port throws when it KNOWS the batch reverted — from a
25153
- * simulation before sending, or from the submitter refusing to broadcast a
25154
- * batch that would revert. The run ends `{ step: 'request', reason:
25155
- * 'reverted', revertError }`.
25156
- *
25157
- * `revertError` is the custom error the contract named (`'ClearingIsPending'`,
25158
- * `'UserNotKycd'`, …), exactly as the ABI declares it. Pass `''` when the
25159
- * batch is known to revert but not why: the consumer then renders its generic
25160
- * `reverted` copy, which is what an unknown name gets anyway.
25161
- *
25162
- * Any OTHER throw from the port is read the way a direct deposit's is — a
25163
- * wallet rejection is `cancelled`, a decodable revert is `reverted`, and
25164
- * everything else is `failed` with the error kept. A port that cannot tell is
25165
- * better off throwing what it has than guessing a name.
25166
- */
25167
- class BatchRevertedError extends Error {
25168
- constructor(revertError, message) {
25169
- super(message !== null && message !== void 0 ? message : `DepositFlow: the batch reverted${revertError ? ` with ${revertError}` : ''}`);
25170
- this.name = 'BatchRevertedError';
25171
- this.revertError = revertError;
25172
- // Keeps `instanceof` honest under a down-levelled build.
25173
- Object.setPrototypeOf(this, BatchRevertedError.prototype);
25174
- }
25175
- }
25176
26190
  /** Generated agreements are valid for five minutes upstream. */
25177
26191
  const CONTRACT_TTL_MS = 5 * 60 * 1000;
25178
26192
  /** What a run without a spender, from either source, fails with. */
@@ -25287,6 +26301,16 @@ function classifyRequest(err) {
25287
26301
  * deposit's throw is, so a non-wallet error can never become `cancelled`.
25288
26302
  */
25289
26303
  function classifyBatch(err) {
26304
+ // A submission outcome is read FIRST and taken at its word. It must never
26305
+ // reach the revert-data walk below: that walk follows `cause`, and an
26306
+ // ambiguous outcome whose cause happens to carry revert bytes would read
26307
+ // as `reverted` or `insufficient-balance` — "nothing was deposited, try
26308
+ // again" — on a batch that may have moved the money.
26309
+ if (err instanceof BatchSubmissionError) {
26310
+ return err.outcome === 'failed'
26311
+ ? { step: 'request', reason: 'failed', error: err }
26312
+ : { step: 'request', reason: err.outcome, error: err };
26313
+ }
25290
26314
  if (err instanceof BatchRevertedError) {
25291
26315
  return {
25292
26316
  step: 'request',
@@ -25812,16 +26836,50 @@ const INITIAL = {
25812
26836
  phase: 'idle',
25813
26837
  step: null,
25814
26838
  isMax: false,
26839
+ sponsored: false,
25815
26840
  failure: null,
25816
26841
  };
25817
26842
  /** What a KYC pre-check with no `buildKycParams` to call fails with. */
25818
26843
  const NO_KYC_PARAMS_MESSAGE = 'WithdrawFlow: getKycSignature was supplied without buildKycParams; build the flow with kasu.flows.withdraw() or pass both';
26844
+ /** What a sponsored run with no `encodeWithdrawal` to call fails with. */
26845
+ const NO_WITHDRAWAL_ENCODER_MESSAGE = 'WithdrawFlow: submitCall was supplied without encodeWithdrawal; build the flow with kasu.flows.withdraw() or pass both';
26846
+ /** What a sponsored run fails with when the encoder returned another kind of call. */
26847
+ const NOT_A_WITHDRAWAL_CALL_MESSAGE = 'WithdrawFlow: encodeWithdrawal returned a call that is not a withdrawal';
26848
+ /**
26849
+ * A `submitCall` / `wait()` rejection, read with the batch path's taxonomy. A
26850
+ * submission outcome is taken at its word FIRST — never through the wallet
26851
+ * classifier, which would read a relay's "request rejected" as the lender's
26852
+ * own doing. Then, from `submitCall` only, a wallet rejection is `cancelled`:
26853
+ * the lender declined to sign and nothing was posted — the same reading a raw
26854
+ * `depositBatch` throw gets. From `wait()` the call has already left, so a
26855
+ * rejection-worded error there is as ambiguous as any other. Everything
26856
+ * unrecognised is `pending`: it may have left.
26857
+ */
26858
+ function classifySponsored(err, from) {
26859
+ if (err instanceof BatchSubmissionError) {
26860
+ return err.outcome === 'failed'
26861
+ ? { step: 'request', reason: 'failed', error: err }
26862
+ : { step: 'request', reason: err.outcome, error: err };
26863
+ }
26864
+ if (err instanceof BatchRevertedError) {
26865
+ return {
26866
+ step: 'request',
26867
+ reason: 'reverted',
26868
+ revertError: err.revertError,
26869
+ error: err,
26870
+ };
26871
+ }
26872
+ if (from === 'submit' && isUserRejected(err)) {
26873
+ return { step: 'request', reason: 'cancelled' };
26874
+ }
26875
+ return { step: 'request', reason: 'pending', error: err };
26876
+ }
25819
26877
  // ---------------------------------------------------------------------------
25820
26878
  // The flow
25821
26879
  // ---------------------------------------------------------------------------
25822
26880
  class WithdrawFlow extends Flow {
25823
26881
  constructor(_ports) {
25824
- super(INITIAL);
26882
+ super(Object.assign(Object.assign({}, INITIAL), { sponsored: typeof _ports.submitCall === 'function' }));
25825
26883
  this._ports = _ports;
25826
26884
  }
25827
26885
  _run(input, token) {
@@ -25852,6 +26910,10 @@ class WithdrawFlow extends Flow {
25852
26910
  if (!this._store.isCurrent(token))
25853
26911
  return;
25854
26912
  }
26913
+ if (ports.submitCall) {
26914
+ yield this._runSponsored(input, token, isMax);
26915
+ return;
26916
+ }
25855
26917
  // 2. The submission. This one IS a wallet call, so it keeps the
25856
26918
  // `cancelled` / `failed` split.
25857
26919
  this._store.patch({ phase: 'request-sign', step: 'request', isMax }, token);
@@ -25878,6 +26940,72 @@ class WithdrawFlow extends Flow {
25878
26940
  this._store.patch({ phase: 'success' }, token);
25879
26941
  });
25880
26942
  }
26943
+ /**
26944
+ * 2'. The sponsored submission: encode, re-check the run, submit, settle.
26945
+ *
26946
+ * The encode reads the chain (the shares), so a run abandoned during it
26947
+ * must stop BEFORE `submitCall` — nothing has been sent yet, and an
26948
+ * abandoned run must never send. A throw while encoding is `failed`:
26949
+ * nothing left. After `submitCall` is called, only the taxonomy decides.
26950
+ */
26951
+ _runSponsored(input, token, isMax) {
26952
+ return __awaiter(this, void 0, void 0, function* () {
26953
+ const ports = this._ports;
26954
+ // Only reached when `submitCall` is supplied; narrows it for below.
26955
+ if (!ports.submitCall)
26956
+ return;
26957
+ this._store.patch({ phase: 'request-sign', step: 'request', isMax }, token);
26958
+ let call;
26959
+ try {
26960
+ if (!ports.encodeWithdrawal) {
26961
+ throw new Error(NO_WITHDRAWAL_ENCODER_MESSAGE);
26962
+ }
26963
+ call = yield ports.encodeWithdrawal({
26964
+ poolId: input.poolId,
26965
+ trancheId: input.trancheId,
26966
+ amount: input.amount,
26967
+ userAddress: input.userAddress,
26968
+ });
26969
+ if ((call === null || call === void 0 ? void 0 : call.kind) !== 'withdrawal') {
26970
+ throw new Error(NOT_A_WITHDRAWAL_CALL_MESSAGE);
26971
+ }
26972
+ }
26973
+ catch (err) {
26974
+ this._store.patch({
26975
+ phase: 'error',
26976
+ failure: { step: 'request', reason: 'failed', error: err },
26977
+ }, token);
26978
+ return;
26979
+ }
26980
+ if (!this._store.isCurrent(token))
26981
+ return;
26982
+ let tx;
26983
+ try {
26984
+ tx = yield ports.submitCall(call);
26985
+ }
26986
+ catch (err) {
26987
+ this._store.patch({ phase: 'error', failure: classifySponsored(err, 'submit') }, token);
26988
+ return;
26989
+ }
26990
+ // The call has left. A run abandoned meanwhile stops HERE, without
26991
+ // `wait()`: nothing it could learn would be published, and a sponsored
26992
+ // `wait()` is minutes of polling against the submitter, not a cheap
26993
+ // receipt read. The submission itself cannot be taken back.
26994
+ if (!this._store.isCurrent(token))
26995
+ return;
26996
+ this._store.patch({ phase: 'request-confirm' }, token);
26997
+ try {
26998
+ yield tx.wait();
26999
+ }
27000
+ catch (err) {
27001
+ this._store.patch({ phase: 'error', failure: classifySponsored(err, 'wait') }, token);
27002
+ return;
27003
+ }
27004
+ if (!this._store.isCurrent(token))
27005
+ return;
27006
+ this._store.patch({ phase: 'success' }, token);
27007
+ });
27008
+ }
25881
27009
  }
25882
27010
 
25883
27011
  /**
@@ -25924,12 +27052,20 @@ class FlowsFacade {
25924
27052
  * approve. `undefined` for a hand-built config without `stableAsset`,
25925
27053
  * in which case a run never batches: it does not guess a token.
25926
27054
  */
25927
- _stableAsset) {
27055
+ _stableAsset,
27056
+ /**
27057
+ * This instance's call encoders — the sponsored withdraw path's
27058
+ * default `encodeWithdrawal`. Optional so a hand-built facade keeps
27059
+ * constructing; without it a sponsored run fails (`failed`, nothing
27060
+ * sent) unless the consumer passes `encodeWithdrawal` itself.
27061
+ */
27062
+ _calls) {
25928
27063
  this._deposits = _deposits;
25929
27064
  this._erc20 = _erc20;
25930
27065
  this._isReadOnly = _isReadOnly;
25931
27066
  this._spender = _spender;
25932
27067
  this._stableAsset = _stableAsset;
27068
+ this._calls = _calls;
25933
27069
  }
25934
27070
  /**
25935
27071
  * A deposit pipeline. `readAllowance`, `approve`, `deposit` and
@@ -25976,10 +27112,13 @@ class FlowsFacade {
25976
27112
  /**
25977
27113
  * A withdrawal pipeline. Both write ports and `buildKycParams` default to
25978
27114
  * this instance; supplying `getKycSignature` turns the KYC pre-check on.
27115
+ * Supplying `submitCall` turns the sponsored path on, and its encoder
27116
+ * defaults to `kasu.calls.requestWithdrawal` on this instance — which
27117
+ * reads, never writes, so it works on a read-only instance too.
25979
27118
  * Defaults are applied per key, for the reason `deposit()` gives.
25980
27119
  */
25981
27120
  withdraw(ports = {}) {
25982
- var _a, _b, _c;
27121
+ var _a, _b, _c, _d;
25983
27122
  return new WithdrawFlow({
25984
27123
  buildKycParams: (_a = ports.buildKycParams) !== null && _a !== void 0 ? _a : ((userAddress) => this._deposits.buildKycParams(userAddress)),
25985
27124
  getKycSignature: ports.getKycSignature,
@@ -25989,8 +27128,17 @@ class FlowsFacade {
25989
27128
  amount: params.amount,
25990
27129
  })),
25991
27130
  withdrawMax: (_c = ports.withdrawMax) !== null && _c !== void 0 ? _c : ((poolId, trancheId, userAddress) => this._deposits.withdrawMax(poolId, trancheId, userAddress)),
27131
+ submitCall: ports.submitCall,
27132
+ encodeWithdrawal: (_d = ports.encodeWithdrawal) !== null && _d !== void 0 ? _d : this._defaultEncoder(),
25992
27133
  });
25993
27134
  }
27135
+ /** `kasu.calls.requestWithdrawal`, when this facade was given the encoders. */
27136
+ _defaultEncoder() {
27137
+ const calls = this._calls;
27138
+ if (!calls)
27139
+ return undefined;
27140
+ return (params) => calls.requestWithdrawal(params);
27141
+ }
25994
27142
  _assertWritable() {
25995
27143
  if (this._isReadOnly) {
25996
27144
  throw new Error(READ_ONLY_MESSAGE);
@@ -26285,9 +27433,72 @@ function maxNetRateCeiling(pools, feePercent) {
26285
27433
  * Handles epoch fetching internally so callers never need to know about epochs.
26286
27434
  */
26287
27435
  class StrategiesFacade {
26288
- constructor(_dataService, _userLending) {
27436
+ constructor(_dataService, _userLending,
27437
+ /**
27438
+ * Chain pool id → the pool id its CMS record is keyed by (XDC pools
27439
+ * share their Base counterpart's editorial record). Lowercase keys.
27440
+ */
27441
+ _poolMetadataMapping = {}) {
26289
27442
  this._dataService = _dataService;
26290
27443
  this._userLending = _userLending;
27444
+ this._poolMetadataMapping = _poolMetadataMapping;
27445
+ }
27446
+ /**
27447
+ * The pool's loss rate and first-loss capital, from its CMS
27448
+ * risk-management record. `null` when the pool has no record.
27449
+ *
27450
+ * Each figure is a NUMBER or `null` — never a guess. The CMS returns
27451
+ * "numeric" fields as a number, a numeric string, an empty string or
27452
+ * null, and an empty string must not become a confident `0`: anything that
27453
+ * is not a finite number reads as `null` (render "—"). `poolLossRate` is a
27454
+ * 0..1 fraction.
27455
+ *
27456
+ * Requires `directusUrl`; without it the call rejects with
27457
+ * `NO_DIRECTUS_URL_MESSAGE`, like every CMS-only read.
27458
+ */
27459
+ getRiskPerformance(poolId) {
27460
+ return __awaiter(this, void 0, void 0, function* () {
27461
+ const metadataId = this._metadataIdOf(poolId);
27462
+ const records = yield this._dataService.getRiskManagement();
27463
+ const record = records.find((r) => String(r.poolIdFK).toLowerCase() === metadataId);
27464
+ if (!record)
27465
+ return null;
27466
+ const performance = record.riskPerformance;
27467
+ return {
27468
+ poolLossRate: finiteOrNull(performance === null || performance === void 0 ? void 0 : performance.poolLossRate),
27469
+ firstLossCapital: finiteOrNull(performance === null || performance === void 0 ? void 0 : performance.firstLossCapital),
27470
+ };
27471
+ });
27472
+ }
27473
+ /**
27474
+ * The credit originator's profile and lending history for a pool — the
27475
+ * CMS record whose `otherKASUPools` lists it. `null` when none does.
27476
+ *
27477
+ * Matched on the chain pool id, then on its metadata id, case-
27478
+ * insensitively. The record is returned as the service maps it; its
27479
+ * numeric fields are CMS-authored, so read them defensively.
27480
+ *
27481
+ * The service filters `otherKASUPools` through the CURRENT chain's
27482
+ * subgraph with the CMS record's (Base-keyed) ids, so on an XDC
27483
+ * deployment every profile lists no pools and this resolves `null` —
27484
+ * the same answer kasu-ui's own lookup gives there today. The metadata
27485
+ * candidate becomes live once the service resolves the mapping.
27486
+ */
27487
+ getOriginator(poolId) {
27488
+ return __awaiter(this, void 0, void 0, function* () {
27489
+ var _a;
27490
+ const candidates = new Set([
27491
+ poolId.toLowerCase(),
27492
+ this._metadataIdOf(poolId),
27493
+ ]);
27494
+ const profiles = yield this._dataService.getPoolDelegateProfileAndHistory();
27495
+ return ((_a = profiles.find((profile) => profile.otherKASUPools.some((pool) => candidates.has(String(pool.id).toLowerCase())))) !== null && _a !== void 0 ? _a : null);
27496
+ });
27497
+ }
27498
+ _metadataIdOf(poolId) {
27499
+ var _a;
27500
+ const lower = poolId.toLowerCase();
27501
+ return ((_a = this._poolMetadataMapping[lower]) !== null && _a !== void 0 ? _a : lower).toLowerCase();
26291
27502
  }
26292
27503
  /**
26293
27504
  * Fetch all active lending strategies.
@@ -26366,9 +27577,7 @@ class StrategiesFacade {
26366
27577
  */
26367
27578
  calculateDepositLimits(tranche) {
26368
27579
  const raw = tranche._raw;
26369
- const min = parseFloat(raw.minimumDeposit) < 1
26370
- ? '1'
26371
- : raw.minimumDeposit;
27580
+ const min = parseFloat(raw.minimumDeposit) < 1 ? '1' : raw.minimumDeposit;
26372
27581
  const max = parseFloat(raw.maximumDeposit) > parseFloat(raw.poolCapacity)
26373
27582
  ? raw.poolCapacity
26374
27583
  : raw.maximumDeposit;
@@ -26416,14 +27625,146 @@ class StrategiesFacade {
26416
27625
  };
26417
27626
  }
26418
27627
  }
27628
+ /**
27629
+ * A CMS "numeric" field as a finite number, or `null`. An empty or blank
27630
+ * string is UNAUTHORED, not zero.
27631
+ */
27632
+ function finiteOrNull(value) {
27633
+ if (typeof value === 'number')
27634
+ return Number.isFinite(value) ? value : null;
27635
+ if (typeof value === 'string') {
27636
+ if (value.trim() === '')
27637
+ return null;
27638
+ const numeric = Number(value);
27639
+ return Number.isFinite(numeric) ? numeric : null;
27640
+ }
27641
+ return null;
27642
+ }
27643
+
27644
+ var UserRequestStatus;
27645
+ (function (UserRequestStatus) {
27646
+ UserRequestStatus["REQUESTED"] = "Requested";
27647
+ UserRequestStatus["PROCESSING"] = "Processing";
27648
+ UserRequestStatus["PROCESSED"] = "Processed";
27649
+ })(UserRequestStatus || (UserRequestStatus = {}));
27650
+
27651
+ /**
27652
+ * Cycles and the clearing window — the protocol's weekly clock, as numbers.
27653
+ *
27654
+ * Lifted verbatim from kasu-ui's `features/portfolio/lib/settlement-window.ts`
27655
+ * and `features/lending/lib/cycle-dates.ts`. The two formatters that live
27656
+ * beside `deriveCycleDates` there (`formatCycleDate`, `formatCycleCloseUtc`)
27657
+ * print words and stay in the applications; everything here is unix seconds in
27658
+ * and unix seconds out.
27659
+ *
27660
+ * The clearing window is the fixed 48 hours immediately preceding an epoch
27661
+ * end. Inside it, pending requests are being processed and cannot be modified,
27662
+ * and the countdown runs to the epoch end. Outside it, the countdown runs to
27663
+ * the next clearing-window start.
27664
+ *
27665
+ * The epoch end comes straight from the chain (`nextEpochStartTimestamp`, i.e.
27666
+ * the SDK's `getNextEpochDate`) — the same value the protocol's own
27667
+ * `getNextClearingPeriodDate` derives from — so the window always lines up
27668
+ * with the real weekly schedule (Tue 06:00 → Thu 06:00 UTC on Base) instead of
27669
+ * a projected subgraph timestamp that can drift off the grid.
27670
+ */
27671
+ /**
27672
+ * Clearing-window length — a fixed 48h protocol constant. Exported so every
27673
+ * consumer derives the window from the same number this module runs on.
27674
+ */
27675
+ const CLEARING_WINDOW_SECONDS = 48 * 60 * 60;
27676
+ /**
27677
+ * Weekly cadence — the epoch schedule is fixed weekly (Tue → Thu UTC on Base).
27678
+ * Used only to roll a cycle forward when a request lands inside a window that
27679
+ * has already closed.
27680
+ */
27681
+ const WEEK_SECONDS = 7 * 24 * 60 * 60;
27682
+ /**
27683
+ * Which phase of the weekly cycle `nowSeconds` falls in, and how long is left
27684
+ * of it.
27685
+ *
27686
+ * `'unknown'` when no epoch boundary has been loaded yet, or when the one on
27687
+ * hand is stale (it has already elapsed — the on-chain value refetches to the
27688
+ * next boundary shortly after rollover). A caller must render its "no cycle
27689
+ * loaded" state there, never a zeroed countdown.
27690
+ */
27691
+ function computeSettlementWindow({ nowSeconds, nextEpochStart, clearingWindowSeconds = CLEARING_WINDOW_SECONDS, }) {
27692
+ // No epoch boundary loaded yet, or a stale one that already elapsed.
27693
+ if (nextEpochStart <= 0 || nextEpochStart <= nowSeconds) {
27694
+ return { phase: 'unknown' };
27695
+ }
27696
+ const clearingStart = nextEpochStart - clearingWindowSeconds;
27697
+ if (nowSeconds < clearingStart) {
27698
+ return {
27699
+ phase: 'awaiting',
27700
+ secondsUntilClearing: clearingStart - nowSeconds,
27701
+ nextClearingStart: clearingStart,
27702
+ };
27703
+ }
27704
+ // nowSeconds is in [clearingStart, nextEpochStart) — inside the window.
27705
+ return {
27706
+ phase: 'clearing',
27707
+ secondsUntilEpochEnd: nextEpochStart - nowSeconds,
27708
+ epochEnd: nextEpochStart,
27709
+ };
27710
+ }
27711
+ /**
27712
+ * The next cycle boundary strictly after `nowSeconds`, in unix seconds — the
27713
+ * cycle close (`nextEpochStart − 48h`) while the window is still open, the
27714
+ * epoch end once we are inside it.
27715
+ *
27716
+ * `undefined` when there is no boundary left to wait for: no epoch boundary
27717
+ * loaded, or a cached one that has already elapsed — the same staleness rule
27718
+ * `computeSettlementWindow` applies before it reports `'unknown'`.
27719
+ *
27720
+ * Split out of the state machine because some consumers need the INSTANT
27721
+ * rather than the phase: one to flush the cycle-dependent caches when the
27722
+ * clock crosses it, one to move a pre-commit screen's snapshot clock at the
27723
+ * same moment.
27724
+ */
27725
+ function nextCycleBoundary(nextEpochStart, nowSeconds, clearingWindowSeconds = CLEARING_WINDOW_SECONDS) {
27726
+ if (!nextEpochStart || nextEpochStart <= 0)
27727
+ return undefined;
27728
+ const clearingStart = nextEpochStart - clearingWindowSeconds;
27729
+ if (nowSeconds < clearingStart)
27730
+ return clearingStart;
27731
+ if (nowSeconds < nextEpochStart)
27732
+ return nextEpochStart;
27733
+ return undefined;
27734
+ }
27735
+ /**
27736
+ * The cycle-close and outcome dates for a request submitted `now`.
27737
+ *
27738
+ * - The cycle "closes" (stops accepting requests, starts processing) at the
27739
+ * start of the 48h clearing window, i.e. 48h before the epoch end.
27740
+ * - Processing takes up to 48h, so the outcome is confirmed by the epoch end
27741
+ * (close + 48h).
27742
+ *
27743
+ * Returns `null` when the epoch boundary is not available or is stale — a
27744
+ * caller then omits the dates entirely (omit, don't stub).
27745
+ *
27746
+ * The common case is a request submitted OUTSIDE the clearing window: the
27747
+ * close is `nextEpochStart − 48h` and the outcome is `nextEpochStart`. When
27748
+ * the request lands INSIDE the current clearing window (that close is already
27749
+ * in the past), it queues for the NEXT weekly cycle, so the close is advanced
27750
+ * by whole weeks until it is in the future.
27751
+ */
27752
+ function deriveCycleDates(nextEpochStart, nowSeconds) {
27753
+ // No boundary loaded, or a stale one that already elapsed — the same
27754
+ // staleness rule as `computeSettlementWindow`.
27755
+ if (!nextEpochStart || nextEpochStart <= nowSeconds)
27756
+ return null;
27757
+ let close = nextEpochStart - CLEARING_WINDOW_SECONDS;
27758
+ let outcome = nextEpochStart;
27759
+ // Inside the current clearing window the close already passed; a request
27760
+ // now is queued for the next weekly cycle.
27761
+ while (close <= nowSeconds) {
27762
+ close += WEEK_SECONDS;
27763
+ outcome += WEEK_SECONDS;
27764
+ }
27765
+ return { close, outcome };
27766
+ }
26419
27767
 
26420
- var UserRequestStatus;
26421
- (function (UserRequestStatus) {
26422
- UserRequestStatus["REQUESTED"] = "Requested";
26423
- UserRequestStatus["PROCESSING"] = "Processing";
26424
- UserRequestStatus["PROCESSED"] = "Processed";
26425
- })(UserRequestStatus || (UserRequestStatus = {}));
26426
-
26427
27768
  /**
26428
27769
  * Events that represent a lender SUBMISSION into the bundle. A dNFT position
26429
27770
  * aggregates every submission the lender made into the same pool/tranche this
@@ -26484,6 +27825,38 @@ function lastEventTimestamp(events, fallback) {
26484
27825
  function isCycleClosed(request) {
26485
27826
  return !request.canCancel;
26486
27827
  }
27828
+ /**
27829
+ * Until when can THIS request still be cancelled? — unix seconds, or `null`
27830
+ * when it cannot be cancelled at all, or when no epoch boundary is loaded.
27831
+ *
27832
+ * The answer is the next cycle close (`deriveCycleDates(...).close`): the
27833
+ * clearing window opens there, and the contract refuses a cancel while the
27834
+ * pool's clearing is pending (`CannotCancelRequestIfClearingIsPending`).
27835
+ * Inside a window whose clearing already ENDED, a still-cancellable request is
27836
+ * queued for the next cycle, so its deadline is next week's close — which is
27837
+ * exactly what `deriveCycleDates` rolls forward to.
27838
+ *
27839
+ * `null` unless the request is BOTH:
27840
+ *
27841
+ * - `canCancel` — the SDK's per-pool signal (see `isCycleClosed`);
27842
+ * - live: `statusCode` `pending`, or `partial` (a partly-filled withdrawal
27843
+ * whose remainder is back in the queue — a resolved partial has
27844
+ * `canCancel: false`). A cancelled, forced, reallocated, rejected or complete
27845
+ * request has nothing left to cancel, whatever `canCancel` says.
27846
+ *
27847
+ * `canCancel` is read ONCE, when the request was fetched. A request held
27848
+ * across a cycle boundary (`nextCycleBoundary`) must be refetched before this
27849
+ * is shown again — the deadline is a hint, the contract is the gate.
27850
+ */
27851
+ function cancelDeadline(request, nextEpochStart, nowSeconds) {
27852
+ var _a, _b;
27853
+ if (!request.canCancel)
27854
+ return null;
27855
+ if (request.statusCode !== 'pending' && request.statusCode !== 'partial') {
27856
+ return null;
27857
+ }
27858
+ return (_b = (_a = deriveCycleDates(nextEpochStart, nowSeconds)) === null || _a === void 0 ? void 0 : _a.close) !== null && _b !== void 0 ? _b : null;
27859
+ }
26487
27860
  const isCancelled = (events) => events.some((e) => e.requestType === 'Cancelled');
26488
27861
  const isForced = (events) => events.some((e) => e.requestType === 'Forced');
26489
27862
  const initiatedEvent = (events) => events.find((e) => e.requestType === 'Initiated');
@@ -26710,8 +28083,8 @@ class PortfolioFacade {
26710
28083
  /**
26711
28084
  * High-level entry point for external integrators.
26712
28085
  *
26713
- * Provides four domain facades — `strategies`, `deposits`, `portfolio`,
26714
- * `flows` — and exposes the underlying `KasuSdk` services via `.services` for
28086
+ * Provides five domain facades — `strategies`, `deposits`, `portfolio`,
28087
+ * `flows`, `calls` — and exposes the underlying `KasuSdk` services via `.services` for
26715
28088
  * power-users.
26716
28089
  *
26717
28090
  * ```ts
@@ -26731,19 +28104,22 @@ class PortfolioFacade {
26731
28104
  */
26732
28105
  class Kasu {
26733
28106
  constructor(sdk, chainConfig, signerOrProvider, configOverrides) {
26734
- var _a;
28107
+ var _a, _b;
26735
28108
  this._sdk = sdk;
26736
28109
  this._chainConfig = chainConfig;
26737
28110
  this._signerOrProvider = signerOrProvider;
26738
28111
  this._configOverrides = configOverrides;
26739
- this.strategies = new StrategiesFacade(sdk.DataService, sdk.UserLending);
28112
+ this.strategies = new StrategiesFacade(sdk.DataService, sdk.UserLending, normaliseMapping((_a = configOverrides.poolMetadataMapping) !== null && _a !== void 0 ? _a : chainConfig.poolMetadataMapping));
26740
28113
  // Derived ONCE and handed to every facade that needs it. Each of them
26741
28114
  // re-deriving `Signer.isSigner` is how two facades come to disagree
26742
28115
  // about whether the same instance can write.
26743
28116
  const isReadOnly = !ethers.Signer.isSigner(signerOrProvider);
26744
28117
  this.deposits = new DepositsFacade(sdk.UserLending, chainConfig.chainId.toString(), isReadOnly);
26745
28118
  this.portfolio = new PortfolioFacade(sdk.DataService, sdk.UserLending, sdk.Portfolio);
26746
- this.flows = new FlowsFacade(this.deposits, () => erc20Of(chainConfig, signerOrProvider), isReadOnly, chainConfig.contracts.LendingPoolManager, (_a = stableAssetOf(chainConfig)) === null || _a === void 0 ? void 0 : _a.address);
28119
+ // The same `LendingPoolManager` the deposit flow approves and calls:
28120
+ // the chain config's, which is what a relay allow-lists `to` against.
28121
+ this.calls = new CallsFacade(sdk.UserLending, chainConfig.contracts.LendingPoolManager);
28122
+ this.flows = new FlowsFacade(this.deposits, () => erc20Of(chainConfig, signerOrProvider), isReadOnly, chainConfig.contracts.LendingPoolManager, (_b = stableAssetOf(chainConfig)) === null || _b === void 0 ? void 0 : _b.address, this.calls);
26747
28123
  }
26748
28124
  /**
26749
28125
  * Create a Kasu instance with built-in chain config.
@@ -26928,6 +28304,14 @@ function resolveChainConfig(chain) {
26928
28304
  }
26929
28305
  return chain;
26930
28306
  }
28307
+ /** Lowercase both sides, so a lookup by any casing of a pool id matches. */
28308
+ function normaliseMapping(mapping) {
28309
+ const out = {};
28310
+ for (const [from, to] of Object.entries(mapping !== null && mapping !== void 0 ? mapping : {})) {
28311
+ out[from.toLowerCase()] = to.toLowerCase();
28312
+ }
28313
+ return out;
28314
+ }
26931
28315
 
26932
28316
  /** Directus instance holding Kasu's pool editorial content. */
26933
28317
  const DEFAULT_DIRECTUS_URL = 'https://kasu-finance.directus.app/';
@@ -27215,17 +28599,143 @@ function ceilToCents(n) {
27215
28599
  return snapped < n ? (k + 1) / CENTS : snapped;
27216
28600
  }
27217
28601
 
28602
+ const TX_HASH = /^0x[0-9a-fA-F]{64}$/;
28603
+ const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
28604
+ /** `https://host[:port][/path]`, no query, fragment, credentials or space. */
28605
+ const HTTPS_BASE = /^https:\/\/[A-Za-z0-9.-]+(:[0-9]{1,5})?(\/[A-Za-z0-9._~\-/]*)?$/;
28606
+ function explorerBase(config) {
28607
+ // Read defensively: a custom config written before 2.10.0 has no field,
28608
+ // and TypeScript only tells its author once they bump.
28609
+ const base = config === null || config === void 0 ? void 0 : config.blockExplorerUrl;
28610
+ if (typeof base !== 'string' || !HTTPS_BASE.test(base)) {
28611
+ throw new Error('explorer url: the chain config has no valid https blockExplorerUrl');
28612
+ }
28613
+ return base.replace(/\/+$/, '');
28614
+ }
28615
+ /**
28616
+ * `<blockExplorerUrl>/tx/<txHash>`. Throws unless `txHash` is exactly `0x`
28617
+ * followed by 64 hex digits.
28618
+ */
28619
+ function explorerTxUrl(config, txHash) {
28620
+ if (typeof txHash !== 'string' || !TX_HASH.test(txHash)) {
28621
+ throw new Error('explorerTxUrl: not a 32-byte 0x-prefixed hex hash');
28622
+ }
28623
+ return `${explorerBase(config)}/tx/${txHash}`;
28624
+ }
28625
+ /**
28626
+ * `<blockExplorerUrl>/address/<address>`, the address as given. Throws unless
28627
+ * `address` is `0x` followed by 40 hex digits with a valid checksum when it
28628
+ * is mixed-case (all-lower and all-upper carry no checksum and are accepted).
28629
+ */
28630
+ function explorerAddressUrl(config, address) {
28631
+ if (typeof address !== 'string' ||
28632
+ !ADDRESS.test(address) ||
28633
+ !ethers.utils.isAddress(address)) {
28634
+ throw new Error('explorerAddressUrl: not a valid 0x-prefixed address');
28635
+ }
28636
+ return `${explorerBase(config)}/address/${address}`;
28637
+ }
28638
+
28639
+ /**
28640
+ * One epoch's nominal length in days. A lock is counted in epochs, and the
28641
+ * loan-agreement text states its term from the same 7-day epoch.
28642
+ */
28643
+ const DAYS_PER_EPOCH = 7;
28644
+ /**
28645
+ * The average calendar month, 365.25 / 12. A lock is counted in epochs, so a
28646
+ * "12-month" term is 52 epochs = 364 days, and only the average-month divisor
28647
+ * lands that on 12 (364 / 30.4375 = 11.96 → 12).
28648
+ */
28649
+ const DAYS_PER_MONTH = 30.4375;
28650
+ /**
28651
+ * The shortest lock stated in months. Below it a term reads in weeks or days,
28652
+ * so nothing may claim a month count for it — a 3-epoch lock is 21 days, which
28653
+ * the average-month divisor would otherwise round UP to one month.
28654
+ */
28655
+ const MIN_DAYS_FOR_MONTHS = 30;
28656
+ /**
28657
+ * `'0'`, empty or absent is the variable-rate sentinel, not a fixed term.
28658
+ * Every surface that tags a rate "variable" or "fixed" must derive the tag
28659
+ * through this, so no screen can hardcode a tag that contradicts the rate
28660
+ * beside it.
28661
+ */
28662
+ function isFixedTermConfigId(configId) {
28663
+ if (configId == null)
28664
+ return false;
28665
+ const trimmed = configId.trim();
28666
+ return trimmed !== '' && trimmed !== '0';
28667
+ }
28668
+ /**
28669
+ * The fixed-term configs this wallet may actually select on a tranche: a
28670
+ * config open to `Everyone`, or an `AllowlistedOnly` config whose allowlist
28671
+ * names the wallet. Anything else is dropped (hide-ineligible): the contract
28672
+ * refuses a deposit into an allowlisted config from a wallet that is not on
28673
+ * it, so offering one is offering a transaction that reverts.
28674
+ *
28675
+ * Address matching is case-insensitive. An allowlist entry whose
28676
+ * `isAllowlisted` is `false` is a wallet that was REMOVED — the subgraph keeps
28677
+ * the entity and flips the flag — so it does not count. An entry that carries
28678
+ * no flag at all counts by its presence, which is how every entry read before
28679
+ * 2.9.0 arrived (the query did not select the field).
28680
+ *
28681
+ * `address` `null` / `undefined` — no wallet yet — sees only the `Everyone`
28682
+ * configs. Order is the tranche's own.
28683
+ */
28684
+ function availableFixedTermConfigs(tranche, address) {
28685
+ if (!tranche)
28686
+ return [];
28687
+ const lower = address === null || address === void 0 ? void 0 : address.toLowerCase();
28688
+ return tranche.fixedTermConfig.filter((config) => config.fixedTermDepositStatus === 'Everyone' ||
28689
+ (lower != null &&
28690
+ lower !== '' &&
28691
+ config.fixedTermDepositAllowlist.some((entry) => entry.isAllowlisted !==
28692
+ false && entry.userId.toLowerCase() === lower)));
28693
+ }
28694
+ /**
28695
+ * A lock's length in days: `epochLockDuration × 7`.
28696
+ *
28697
+ * FAILS CLOSED: an unparseable, non-finite, zero or negative epoch count
28698
+ * returns `NaN`, never `0` — a zero-day lock is not a term, and a consumer
28699
+ * that rendered it would state one.
28700
+ *
28701
+ * @param epochLockDuration the config's `epochLockDuration`, a decimal string.
28702
+ */
28703
+ function lockDurationDays(epochLockDuration) {
28704
+ const epochs = parseFloat(epochLockDuration);
28705
+ if (!Number.isFinite(epochs) || epochs <= 0)
28706
+ return NaN;
28707
+ return epochs * DAYS_PER_EPOCH;
28708
+ }
28709
+ /**
28710
+ * A lock in WHOLE months, or `null` when the epoch count is not a positive
28711
+ * number or the lock is shorter than `MIN_DAYS_FOR_MONTHS`.
28712
+ *
28713
+ * Unlike a year-rounding formatter it never rolls up into years: a 104-epoch
28714
+ * lock is 24 months. A consumer that states years does that conversion in its
28715
+ * own words.
28716
+ */
28717
+ function lockDurationMonths(epochLockDuration) {
28718
+ const days = lockDurationDays(epochLockDuration);
28719
+ if (Number.isNaN(days) || days < MIN_DAYS_FOR_MONTHS)
28720
+ return null;
28721
+ const months = Math.round(days / DAYS_PER_MONTH);
28722
+ return months > 0 ? months : null;
28723
+ }
28724
+
27218
28725
  const APXIUM = {
27219
28726
  name: 'Apxium',
27220
28727
  url: 'https://www.apxium.com/',
28728
+ region: 'Australia',
27221
28729
  };
27222
28730
  const INVOICEMATE = {
27223
28731
  name: 'InvoiceMate',
27224
28732
  url: 'https://invoicemate.net/',
28733
+ region: 'Global',
27225
28734
  };
27226
28735
  const RIXON_CAPITAL = {
27227
28736
  name: 'Rixon Capital',
27228
28737
  url: 'https://rixon.capital/',
28738
+ region: 'Australia',
27229
28739
  };
27230
28740
  function poolNameOf(pool) {
27231
28741
  var _a, _b;
@@ -27257,122 +28767,22 @@ function getCreditOriginator(pool) {
27257
28767
  function getInstitutionalLender(originator) {
27258
28768
  return originator.name === APXIUM.name ? RIXON_CAPITAL : null;
27259
28769
  }
27260
-
27261
- /**
27262
- * Cycles and the clearing window — the protocol's weekly clock, as numbers.
27263
- *
27264
- * Lifted verbatim from kasu-ui's `features/portfolio/lib/settlement-window.ts`
27265
- * and `features/lending/lib/cycle-dates.ts`. The two formatters that live
27266
- * beside `deriveCycleDates` there (`formatCycleDate`, `formatCycleCloseUtc`)
27267
- * print words and stay in the applications; everything here is unix seconds in
27268
- * and unix seconds out.
27269
- *
27270
- * The clearing window is the fixed 48 hours immediately preceding an epoch
27271
- * end. Inside it, pending requests are being processed and cannot be modified,
27272
- * and the countdown runs to the epoch end. Outside it, the countdown runs to
27273
- * the next clearing-window start.
27274
- *
27275
- * The epoch end comes straight from the chain (`nextEpochStartTimestamp`, i.e.
27276
- * the SDK's `getNextEpochDate`) — the same value the protocol's own
27277
- * `getNextClearingPeriodDate` derives from — so the window always lines up
27278
- * with the real weekly schedule (Tue 06:00 → Thu 06:00 UTC on Base) instead of
27279
- * a projected subgraph timestamp that can drift off the grid.
27280
- */
27281
- /**
27282
- * Clearing-window length — a fixed 48h protocol constant. Exported so every
27283
- * consumer derives the window from the same number this module runs on.
27284
- */
27285
- const CLEARING_WINDOW_SECONDS = 48 * 60 * 60;
27286
- /**
27287
- * Weekly cadence — the epoch schedule is fixed weekly (Tue → Thu UTC on Base).
27288
- * Used only to roll a cycle forward when a request lands inside a window that
27289
- * has already closed.
27290
- */
27291
- const WEEK_SECONDS = 7 * 24 * 60 * 60;
27292
- /**
27293
- * Which phase of the weekly cycle `nowSeconds` falls in, and how long is left
27294
- * of it.
27295
- *
27296
- * `'unknown'` when no epoch boundary has been loaded yet, or when the one on
27297
- * hand is stale (it has already elapsed — the on-chain value refetches to the
27298
- * next boundary shortly after rollover). A caller must render its "no cycle
27299
- * loaded" state there, never a zeroed countdown.
27300
- */
27301
- function computeSettlementWindow({ nowSeconds, nextEpochStart, clearingWindowSeconds = CLEARING_WINDOW_SECONDS, }) {
27302
- // No epoch boundary loaded yet, or a stale one that already elapsed.
27303
- if (nextEpochStart <= 0 || nextEpochStart <= nowSeconds) {
27304
- return { phase: 'unknown' };
27305
- }
27306
- const clearingStart = nextEpochStart - clearingWindowSeconds;
27307
- if (nowSeconds < clearingStart) {
27308
- return {
27309
- phase: 'awaiting',
27310
- secondsUntilClearing: clearingStart - nowSeconds,
27311
- nextClearingStart: clearingStart,
27312
- };
27313
- }
27314
- // nowSeconds is in [clearingStart, nextEpochStart) — inside the window.
27315
- return {
27316
- phase: 'clearing',
27317
- secondsUntilEpochEnd: nextEpochStart - nowSeconds,
27318
- epochEnd: nextEpochStart,
27319
- };
27320
- }
27321
- /**
27322
- * The next cycle boundary strictly after `nowSeconds`, in unix seconds — the
27323
- * cycle close (`nextEpochStart − 48h`) while the window is still open, the
27324
- * epoch end once we are inside it.
27325
- *
27326
- * `undefined` when there is no boundary left to wait for: no epoch boundary
27327
- * loaded, or a cached one that has already elapsed — the same staleness rule
27328
- * `computeSettlementWindow` applies before it reports `'unknown'`.
27329
- *
27330
- * Split out of the state machine because some consumers need the INSTANT
27331
- * rather than the phase: one to flush the cycle-dependent caches when the
27332
- * clock crosses it, one to move a pre-commit screen's snapshot clock at the
27333
- * same moment.
27334
- */
27335
- function nextCycleBoundary(nextEpochStart, nowSeconds, clearingWindowSeconds = CLEARING_WINDOW_SECONDS) {
27336
- if (!nextEpochStart || nextEpochStart <= 0)
27337
- return undefined;
27338
- const clearingStart = nextEpochStart - clearingWindowSeconds;
27339
- if (nowSeconds < clearingStart)
27340
- return clearingStart;
27341
- if (nowSeconds < nextEpochStart)
27342
- return nextEpochStart;
27343
- return undefined;
27344
- }
27345
28770
  /**
27346
- * The cycle-close and outcome dates for a request submitted `now`.
27347
- *
27348
- * - The cycle "closes" (stops accepting requests, starts processing) at the
27349
- * start of the 48h clearing window, i.e. 48h before the epoch end.
27350
- * - Processing takes up to 48h, so the outcome is confirmed by the epoch end
27351
- * (close + 48h).
27352
- *
27353
- * Returns `null` when the epoch boundary is not available or is stale — a
27354
- * caller then omits the dates entirely (omit, don't stub).
27355
- *
27356
- * The common case is a request submitted OUTSIDE the clearing window: the
27357
- * close is `nextEpochStart − 48h` and the outcome is `nextEpochStart`. When
27358
- * the request lands INSIDE the current clearing window (that close is already
27359
- * in the past), it queues for the NEXT weekly cycle, so the close is advanced
27360
- * by whole weeks until it is in the future.
28771
+ * The strategy's region — `'Australia'` for the Apxium family, `'Global'` for
28772
+ * PayFi — derived from its credit originator, exactly as every surface that
28773
+ * states a region must derive it.
28774
+ *
28775
+ * LOAD-BEARING ON THE MONEY PATH: this is the `region` a lender's wallet signs
28776
+ * in the loan-agreement message (`buildLoanAgreementSignMessage`). The backend
28777
+ * rebuilds that message from whatever region the client sends and treats it
28778
+ * as display-only, so nothing but this function keeps the signed word equal to
28779
+ * the word on screen. Never state a region from a constant — that is how a
28780
+ * PayFi lender came to pick "Global · Junior" and sign "Australia".
28781
+ *
28782
+ * Replace the inference with a per-pool field (in the SDK) when one ships.
27361
28783
  */
27362
- function deriveCycleDates(nextEpochStart, nowSeconds) {
27363
- // No boundary loaded, or a stale one that already elapsed — the same
27364
- // staleness rule as `computeSettlementWindow`.
27365
- if (!nextEpochStart || nextEpochStart <= nowSeconds)
27366
- return null;
27367
- let close = nextEpochStart - CLEARING_WINDOW_SECONDS;
27368
- let outcome = nextEpochStart;
27369
- // Inside the current clearing window the close already passed; a request
27370
- // now is queued for the next weekly cycle.
27371
- while (close <= nowSeconds) {
27372
- close += WEEK_SECONDS;
27373
- outcome += WEEK_SECONDS;
27374
- }
27375
- return { close, outcome };
28784
+ function getStrategyRegion(pool) {
28785
+ return getCreditOriginator(pool).region;
27376
28786
  }
27377
28787
 
27378
28788
  // Business rename (2026-07): Apxium strategies market their top retail tranche
@@ -27404,15 +28814,174 @@ function getTrancheDisplayName(trancheName, pool) {
27404
28814
  : trancheName;
27405
28815
  }
27406
28816
 
28817
+ /**
28818
+ * Forward-looking interest on a lender's CURRENT balances — the figures a
28819
+ * portfolio shows as "weekly", "daily" and the moving part of "lifetime"
28820
+ * interest, and the "≈ $Y a year" line beside a lend amount.
28821
+ *
28822
+ * Every figure is NET of the platform performance fee, the way the chain
28823
+ * credits it: `LendingPool._applyTrancheInterest` mints the lender
28824
+ * `interest × (1 − performanceFee)` at each cycle close, and only that net
28825
+ * amount ever reaches the balance. A gross projection would out-run what the
28826
+ * next close actually credits.
28827
+ *
28828
+ * Units: balances and results are display units of the deployment's stable
28829
+ * asset (not base units); rates are 0..1 fractions; `feePercent` is a
28830
+ * PERCENTAGE IN 0..100 — see `netEffectiveApy`.
28831
+ */
28832
+ /**
28833
+ * Seconds in one epoch's nominal week. The per-epoch rate covers exactly this
28834
+ * window, and the accrual spreads an epoch's interest across it.
28835
+ */
28836
+ const SECONDS_PER_WEEK = 604800;
28837
+ function isUsableFeePercent(feePercent) {
28838
+ return (feePercent !== null &&
28839
+ Number.isFinite(feePercent) &&
28840
+ feePercent >= 0 &&
28841
+ feePercent <= 100);
28842
+ }
28843
+ /**
28844
+ * Interest the slices accrue over ONE epoch, net of the fee.
28845
+ *
28846
+ * ```
28847
+ * weekly = Σ(slice.balance × slice.epochRate) × (1 − feePercent / 100)
28848
+ * ```
28849
+ *
28850
+ * **The rate is the raw per-epoch one, never the APY.** An APY is that rate
28851
+ * already compounded over `EPOCHS_IN_YEAR`; dividing it by 365 charges a day
28852
+ * of compounded annual growth to a single day and overstates it.
28853
+ *
28854
+ * FAILS CLOSED, returning `null` rather than a wrong number:
28855
+ * - a `null`, non-finite or out-of-domain fee — a fee-less projection dressed
28856
+ * up as the lender's net earnings is the failure this guards;
28857
+ * - any slice with a POSITIVE balance and a non-finite rate — skipping it
28858
+ * would return a silently partial total, quietly missing that slice.
28859
+ *
28860
+ * Non-finite and non-positive BALANCES are skipped: a slice with nothing in it
28861
+ * earns nothing whatever its rate, so it cannot hide earnings. A portfolio
28862
+ * with nothing lent is therefore a legitimate `0`, never `null`.
28863
+ */
28864
+ function weeklyInterest(slices, feePercent) {
28865
+ if (!isUsableFeePercent(feePercent))
28866
+ return null;
28867
+ let gross = 0;
28868
+ for (const slice of slices) {
28869
+ if (!Number.isFinite(slice.balance) || slice.balance <= 0)
28870
+ continue;
28871
+ if (!Number.isFinite(slice.epochRate))
28872
+ return null;
28873
+ gross += slice.balance * slice.epochRate;
28874
+ }
28875
+ return gross * (1 - feePercent / 100);
28876
+ }
28877
+ /**
28878
+ * A day's share of the epoch's net interest: a seventh of it, NOT a
28879
+ * de-compounded daily rate. The chain mints interest once per epoch, so
28880
+ * nothing compounds within the cycle and the accrual is linear across it.
28881
+ *
28882
+ * Fails closed with its input: `null` or non-finite → `null`.
28883
+ */
28884
+ function dailyInterest(weekly) {
28885
+ if (weekly === null || !Number.isFinite(weekly))
28886
+ return null;
28887
+ return weekly / 7;
28888
+ }
28889
+ /**
28890
+ * Interest accrued since each pool's OWN last cycle close — the moving part
28891
+ * of lifetime interest (lifetime = settled on chain + this).
28892
+ *
28893
+ * ```
28894
+ * accrued = Σ_pool weekly_pool × clamp(now − clearing_pool, 0, 604 800) / 604 800
28895
+ * ```
28896
+ *
28897
+ * **Per pool, because pools clear independently.** One shared anchor accrues
28898
+ * a stale pool's share from a close it never had, and when another pool
28899
+ * clears it drops the total by the stale pool's whole weekly share. Anchored
28900
+ * per pool, the total is monotonic across any single pool's clearing: that
28901
+ * pool swaps its accrued share for a capitalised one, and no other term moves.
28902
+ *
28903
+ * **The one-epoch cap is load-bearing.** Clearings are not exactly weekly,
28904
+ * and `weeklyInterest` is per EPOCH, so extrapolating past seven days would
28905
+ * promise interest the close will not credit; a late clearing under-reports
28906
+ * instead. The low clamp makes a close ahead of the local clock zero, never
28907
+ * negative.
28908
+ *
28909
+ * A non-finite term contributes nothing; a non-finite `nowSeconds` accrues
28910
+ * nothing. Callers fail closed upstream by not offering an accrual for a pool
28911
+ * whose weekly interest or anchor is unknown.
28912
+ */
28913
+ function accruedInterest(accruals, nowSeconds) {
28914
+ if (!Number.isFinite(nowSeconds))
28915
+ return 0;
28916
+ let accrued = 0;
28917
+ for (const { weeklyInterest: weekly, clearingTimestamp } of accruals) {
28918
+ if (!Number.isFinite(weekly) || !Number.isFinite(clearingTimestamp)) {
28919
+ continue;
28920
+ }
28921
+ const elapsed = Math.min(Math.max(nowSeconds - clearingTimestamp, 0), SECONDS_PER_WEEK);
28922
+ accrued += (weekly * elapsed) / SECONDS_PER_WEEK;
28923
+ }
28924
+ return accrued;
28925
+ }
28926
+ /**
28927
+ * What `amount` earns in a year at a NET rate — the "≈ $Y a year" line.
28928
+ * Feed it `netEffectiveApy(...)`, never a gross APY: the result is a lender's
28929
+ * earnings, so the fee must already be off the rate.
28930
+ *
28931
+ * FAILS CLOSED: a non-finite or negative amount or rate returns `NaN`, which
28932
+ * the consumer renders as "no figure" — exactly what `netEffectiveApy`
28933
+ * returns when the fee is unknown, so that state carries straight through.
28934
+ *
28935
+ * @param amount display units of the stable asset.
28936
+ * @param netApy the net effective annual rate as a 0..1 fraction.
28937
+ */
28938
+ function projectedAnnualEarnings(amount, netApy) {
28939
+ if (!Number.isFinite(amount) || amount < 0)
28940
+ return NaN;
28941
+ if (!Number.isFinite(netApy) || netApy < 0)
28942
+ return NaN;
28943
+ return amount * netApy;
28944
+ }
28945
+ /**
28946
+ * Balance-weighted average APY across slices, skipping non-finite and
28947
+ * non-positive balances and non-finite rates; `0` when nothing carries a
28948
+ * positive balance. Whatever basis goes in comes out — feed it NET rates for
28949
+ * an average effective (net) rate.
28950
+ */
28951
+ function weightedAverageApy(slices) {
28952
+ let totalBalance = 0;
28953
+ let weighted = 0;
28954
+ for (const slice of slices) {
28955
+ if (!Number.isFinite(slice.balance) || !Number.isFinite(slice.apy)) {
28956
+ continue;
28957
+ }
28958
+ if (slice.balance <= 0)
28959
+ continue;
28960
+ totalBalance += slice.balance;
28961
+ weighted += slice.balance * slice.apy;
28962
+ }
28963
+ if (totalBalance <= 0)
28964
+ return 0;
28965
+ return weighted / totalBalance;
28966
+ }
28967
+
27407
28968
  exports.APXIUM = APXIUM;
27408
28969
  exports.AU_ALPHA3 = AU_ALPHA3;
27409
28970
  exports.AU_MIN_CUMULATIVE_BY_STABLE = AU_MIN_CUMULATIVE_BY_STABLE;
28971
+ exports.BatchPendingError = BatchPendingError;
27410
28972
  exports.BatchRevertedError = BatchRevertedError;
28973
+ exports.BatchSubmissionError = BatchSubmissionError;
27411
28974
  exports.CHAIN_CONFIGS = CHAIN_CONFIGS;
27412
28975
  exports.CLEARING_WINDOW_SECONDS = CLEARING_WINDOW_SECONDS;
27413
28976
  exports.CONTRACT_TTL_MS = CONTRACT_TTL_MS;
28977
+ exports.CallsFacade = CallsFacade;
28978
+ exports.DAYS_PER_EPOCH = DAYS_PER_EPOCH;
28979
+ exports.DAYS_PER_MONTH = DAYS_PER_MONTH;
28980
+ exports.DEFAULT_BATCH_POLLING_POLICY = DEFAULT_BATCH_POLLING_POLICY;
28981
+ exports.DepositBatchMismatchError = DepositBatchMismatchError;
27414
28982
  exports.DepositFlow = DepositFlow;
27415
28983
  exports.DepositsFacade = DepositsFacade;
28984
+ exports.ENTRY_POINT_V07 = ENTRY_POINT_V07;
27416
28985
  exports.EPOCHS_IN_YEAR = EPOCHS_IN_YEAR;
27417
28986
  exports.Flow = Flow;
27418
28987
  exports.FlowStore = FlowStore;
@@ -27423,37 +28992,56 @@ exports.INVOICEMATE = INVOICEMATE;
27423
28992
  exports.Kasu = Kasu;
27424
28993
  exports.KasuSdk = KasuSdk;
27425
28994
  exports.MAX_LENDING_AMOUNT_FALLBACK = MAX_LENDING_AMOUNT_FALLBACK;
28995
+ exports.MIN_DAYS_FOR_MONTHS = MIN_DAYS_FOR_MONTHS;
27426
28996
  exports.MIN_LENDING_AMOUNT_FALLBACK = MIN_LENDING_AMOUNT_FALLBACK;
27427
28997
  exports.MIN_TRANCHE_CAPACITY = MIN_TRANCHE_CAPACITY;
28998
+ exports.NOT_A_WITHDRAWAL_CALL_MESSAGE = NOT_A_WITHDRAWAL_CALL_MESSAGE;
27428
28999
  exports.NO_DIRECTUS_URL_MESSAGE = NO_DIRECTUS_URL_MESSAGE;
27429
29000
  exports.NO_KYC_PARAMS_MESSAGE = NO_KYC_PARAMS_MESSAGE;
27430
29001
  exports.NO_SPENDER_MESSAGE = NO_SPENDER_MESSAGE;
29002
+ exports.NO_WITHDRAWAL_ENCODER_MESSAGE = NO_WITHDRAWAL_ENCODER_MESSAGE;
27431
29003
  exports.PortfolioFacade = PortfolioFacade;
27432
29004
  exports.READ_ONLY_MESSAGE = READ_ONLY_MESSAGE;
27433
29005
  exports.RIXON_CAPITAL = RIXON_CAPITAL;
29006
+ exports.SECONDS_PER_WEEK = SECONDS_PER_WEEK;
29007
+ exports.SPONSORED_CALL_KINDS = SPONSORED_CALL_KINDS;
29008
+ exports.SPONSORED_CALL_SELECTORS = SPONSORED_CALL_SELECTORS;
27434
29009
  exports.SdkConfig = SdkConfig;
29010
+ exports.SponsoredCallInputError = SponsoredCallInputError;
27435
29011
  exports.StrategiesFacade = StrategiesFacade;
27436
29012
  exports.UPPER_MEZZANINE = UPPER_MEZZANINE;
27437
29013
  exports.WithdrawFlow = WithdrawFlow;
29014
+ exports.accruedInterest = accruedInterest;
27438
29015
  exports.apyToEpochRate = apyToEpochRate;
27439
29016
  exports.asContractType = asContractType;
27440
29017
  exports.auMinimumRemaining = auMinimumRemaining;
27441
29018
  exports.auThresholdFor = auThresholdFor;
29019
+ exports.availableFixedTermConfigs = availableFixedTermConfigs;
29020
+ exports.batchOutcomeOf = batchOutcomeOf;
27442
29021
  exports.buildContractVersionType = buildContractVersionType;
27443
29022
  exports.buildFullNameRequestMessage = buildFullNameRequestMessage;
27444
29023
  exports.buildLegacyContractRequestMessage = buildLegacyContractRequestMessage;
27445
29024
  exports.buildLoanAgreementSignMessage = buildLoanAgreementSignMessage;
29025
+ exports.cancelDeadline = cancelDeadline;
27446
29026
  exports.ceilToCents = ceilToCents;
29027
+ exports.checkBatchOutcome = checkBatchOutcome;
27447
29028
  exports.classifyWalletFailure = classifyWalletFailure;
27448
29029
  exports.compareTrancheSeniority = compareTrancheSeniority;
27449
29030
  exports.computeSettlementWindow = computeSettlementWindow;
27450
29031
  exports.countSubmissions = countSubmissions;
29032
+ exports.dailyInterest = dailyInterest;
27451
29033
  exports.decodeRevert = decodeRevert;
27452
29034
  exports.deriveCycleDates = deriveCycleDates;
27453
29035
  exports.derivePoolStatus = derivePoolStatus;
27454
29036
  exports.deriveRequestState = deriveRequestState;
29037
+ exports.encodeCancelDepositCall = encodeCancelDepositCall;
29038
+ exports.encodeCancelWithdrawalCall = encodeCancelWithdrawalCall;
27455
29039
  exports.encodeDepositData = encodeDepositData;
29040
+ exports.encodeRequestWithdrawalCall = encodeRequestWithdrawalCall;
29041
+ exports.encodeWithdrawAtExpiryCall = encodeWithdrawAtExpiryCall;
27456
29042
  exports.epochRateToApy = epochRateToApy;
29043
+ exports.explorerAddressUrl = explorerAddressUrl;
29044
+ exports.explorerTxUrl = explorerTxUrl;
27457
29045
  exports.extractRevertData = extractRevertData;
27458
29046
  exports.fetchUnusedPoolIds = fetchUnusedPoolIds;
27459
29047
  exports.firstSubmissionTimestamp = firstSubmissionTimestamp;
@@ -27461,14 +29049,19 @@ exports.floorToCents = floorToCents;
27461
29049
  exports.formatSignTimestampUtc = formatSignTimestampUtc;
27462
29050
  exports.getCreditOriginator = getCreditOriginator;
27463
29051
  exports.getInstitutionalLender = getInstitutionalLender;
29052
+ exports.getStrategyRegion = getStrategyRegion;
27464
29053
  exports.getTrancheDisplayName = getTrancheDisplayName;
27465
29054
  exports.isAuMinimumExempt = isAuMinimumExempt;
27466
29055
  exports.isAustralianKyc = isAustralianKyc;
27467
29056
  exports.isBelowMinimumCapacity = isBelowMinimumCapacity;
27468
29057
  exports.isCycleClosed = isCycleClosed;
29058
+ exports.isDefinitivelyNotSubmitted = isDefinitivelyNotSubmitted;
29059
+ exports.isFixedTermConfigId = isFixedTermConfigId;
27469
29060
  exports.isUnpredictableGas = isUnpredictableGas;
27470
29061
  exports.isUserRejected = isUserRejected;
27471
29062
  exports.lastEventTimestamp = lastEventTimestamp;
29063
+ exports.lockDurationDays = lockDurationDays;
29064
+ exports.lockDurationMonths = lockDurationMonths;
27472
29065
  exports.maxNetRateCeiling = maxNetRateCeiling;
27473
29066
  exports.netEffectiveApy = netEffectiveApy;
27474
29067
  exports.netTrancheApyBounds = netTrancheApyBounds;
@@ -27480,10 +29073,18 @@ exports.pickDefaultTrancheId = pickDefaultTrancheId;
27480
29073
  exports.pickHighestYieldTranche = pickHighestYieldTranche;
27481
29074
  exports.poolAllTranchesFull = poolAllTranchesFull;
27482
29075
  exports.poolMaxApy = poolMaxApy;
29076
+ exports.projectedAnnualEarnings = projectedAnnualEarnings;
29077
+ exports.proveDepositInReceipt = proveDepositInReceipt;
29078
+ exports.proveUserOperationInReceipt = proveUserOperationInReceipt;
27483
29079
  exports.resolveBoundShortcuts = resolveBoundShortcuts;
27484
29080
  exports.resolveDepositBounds = resolveDepositBounds;
27485
29081
  exports.selectVisiblePools = selectVisiblePools;
27486
29082
  exports.submissionEvents = submissionEvents;
29083
+ exports.submitBatch = submitBatch;
29084
+ exports.submitSponsoredCall = submitSponsoredCall;
27487
29085
  exports.trancheApyBounds = trancheApyBounds;
27488
29086
  exports.trancheHasCapacity = trancheHasCapacity;
27489
29087
  exports.trancheRiskRank = trancheRiskRank;
29088
+ exports.validateDepositBatchCalls = validateDepositBatchCalls;
29089
+ exports.weeklyInterest = weeklyInterest;
29090
+ exports.weightedAverageApy = weightedAverageApy;