@augustdigital/sdk 4.24.9 → 4.24.10-alpha-4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/lib/abis/RwaRedeem.d.ts +76 -0
  2. package/lib/abis/RwaRedeem.js +55 -0
  3. package/lib/abis/RwaRedeem.js.map +1 -0
  4. package/lib/abis/TokenizedVaultV2WithDepositWithPermit.d.ts +85 -0
  5. package/lib/abis/TokenizedVaultV2WithDepositWithPermit.js +1878 -0
  6. package/lib/abis/TokenizedVaultV2WithDepositWithPermit.js.map +1 -0
  7. package/lib/adapters/solana/getters.d.ts +2 -2
  8. package/lib/adapters/solana/getters.js +36 -100
  9. package/lib/adapters/solana/getters.js.map +1 -1
  10. package/lib/adapters/solana/index.d.ts +2 -2
  11. package/lib/adapters/solana/utils.d.ts +2 -2
  12. package/lib/adapters/solana/utils.js +1 -8
  13. package/lib/adapters/solana/utils.js.map +1 -1
  14. package/lib/adapters/stellar/actions.d.ts +3 -0
  15. package/lib/adapters/stellar/actions.js +11 -0
  16. package/lib/adapters/stellar/actions.js.map +1 -0
  17. package/lib/adapters/stellar/constants.d.ts +10 -0
  18. package/lib/adapters/stellar/constants.js +16 -0
  19. package/lib/adapters/stellar/constants.js.map +1 -0
  20. package/lib/adapters/stellar/getters.d.ts +4 -0
  21. package/lib/adapters/stellar/getters.js +51 -0
  22. package/lib/adapters/stellar/getters.js.map +1 -0
  23. package/lib/adapters/stellar/index.d.ts +24 -0
  24. package/lib/adapters/stellar/index.js +68 -0
  25. package/lib/adapters/stellar/index.js.map +1 -0
  26. package/lib/adapters/stellar/types.d.ts +15 -0
  27. package/lib/adapters/stellar/types.js +3 -0
  28. package/lib/adapters/stellar/types.js.map +1 -0
  29. package/lib/adapters/stellar/utils.d.ts +12 -0
  30. package/lib/adapters/stellar/utils.js +31 -0
  31. package/lib/adapters/stellar/utils.js.map +1 -0
  32. package/lib/adapters/sui/transformer.js +4 -9
  33. package/lib/adapters/sui/transformer.js.map +1 -1
  34. package/lib/core/base.class.d.ts +3 -2
  35. package/lib/core/base.class.js +14 -7
  36. package/lib/core/base.class.js.map +1 -1
  37. package/lib/core/constants/core.d.ts +6 -3
  38. package/lib/core/constants/core.js +3 -0
  39. package/lib/core/constants/core.js.map +1 -1
  40. package/lib/core/constants/hardcoded-vaults.d.ts +7 -0
  41. package/lib/core/constants/hardcoded-vaults.js +179 -0
  42. package/lib/core/constants/hardcoded-vaults.js.map +1 -0
  43. package/lib/core/constants/ovault.d.ts +13 -0
  44. package/lib/core/constants/ovault.js +160 -0
  45. package/lib/core/constants/ovault.js.map +1 -0
  46. package/lib/core/constants/rwa-vaults.d.ts +4 -0
  47. package/lib/core/constants/rwa-vaults.js +27 -0
  48. package/lib/core/constants/rwa-vaults.js.map +1 -0
  49. package/lib/core/constants/web3.d.ts +5 -0
  50. package/lib/core/constants/web3.js +9 -0
  51. package/lib/core/constants/web3.js.map +1 -1
  52. package/lib/core/constants.adapters.d.ts +117 -0
  53. package/lib/core/constants.adapters.js +160 -0
  54. package/lib/core/constants.adapters.js.map +1 -0
  55. package/lib/core/constants.core.d.ts +78 -0
  56. package/lib/core/constants.core.js +75 -0
  57. package/lib/core/constants.core.js.map +1 -0
  58. package/lib/core/constants.vaults.d.ts +64 -0
  59. package/lib/core/constants.vaults.js +156 -0
  60. package/lib/core/constants.vaults.js.map +1 -0
  61. package/lib/core/constants.web3.d.ts +31 -0
  62. package/lib/core/constants.web3.js +100 -0
  63. package/lib/core/constants.web3.js.map +1 -0
  64. package/lib/core/fetcher.d.ts +4 -4
  65. package/lib/core/fetcher.js +9 -2
  66. package/lib/core/fetcher.js.map +1 -1
  67. package/lib/core/helpers/address-utils.d.ts +3 -0
  68. package/lib/core/helpers/address-utils.js +18 -0
  69. package/lib/core/helpers/address-utils.js.map +1 -0
  70. package/lib/core/helpers/vaults.js +37 -29
  71. package/lib/core/helpers/vaults.js.map +1 -1
  72. package/lib/core/helpers/web3.d.ts +3 -2
  73. package/lib/core/helpers/web3.js +17 -1
  74. package/lib/core/helpers/web3.js.map +1 -1
  75. package/lib/core/helpers.adapters.d.ts +9 -0
  76. package/lib/core/helpers.adapters.js +28 -0
  77. package/lib/core/helpers.adapters.js.map +1 -0
  78. package/lib/core/helpers.core.d.ts +48 -0
  79. package/lib/core/helpers.core.js +210 -0
  80. package/lib/core/helpers.core.js.map +1 -0
  81. package/lib/core/helpers.signer.d.ts +9 -0
  82. package/lib/core/helpers.signer.js +54 -0
  83. package/lib/core/helpers.signer.js.map +1 -0
  84. package/lib/core/helpers.vaults.d.ts +36 -0
  85. package/lib/core/helpers.vaults.js +145 -0
  86. package/lib/core/helpers.vaults.js.map +1 -0
  87. package/lib/core/helpers.web3.d.ts +95 -0
  88. package/lib/core/helpers.web3.js +376 -0
  89. package/lib/core/helpers.web3.js.map +1 -0
  90. package/lib/index.d.ts +1 -0
  91. package/lib/index.js +1 -0
  92. package/lib/index.js.map +1 -1
  93. package/lib/main.d.ts +2 -0
  94. package/lib/main.js +3 -2
  95. package/lib/main.js.map +1 -1
  96. package/lib/modules/vaults/getters.d.ts +29 -2
  97. package/lib/modules/vaults/getters.js +516 -83
  98. package/lib/modules/vaults/getters.js.map +1 -1
  99. package/lib/modules/vaults/main.d.ts +6 -0
  100. package/lib/modules/vaults/main.js +92 -33
  101. package/lib/modules/vaults/main.js.map +1 -1
  102. package/lib/modules/vaults/utils/call-data-decoder.d.ts +14 -0
  103. package/lib/modules/vaults/utils/call-data-decoder.js +138 -0
  104. package/lib/modules/vaults/utils/call-data-decoder.js.map +1 -0
  105. package/lib/modules/vaults/utils/date-utils.d.ts +11 -0
  106. package/lib/modules/vaults/utils/date-utils.js +39 -0
  107. package/lib/modules/vaults/utils/date-utils.js.map +1 -0
  108. package/lib/modules/vaults/utils.d.ts +2 -0
  109. package/lib/modules/vaults/utils.js +117 -1
  110. package/lib/modules/vaults/utils.js.map +1 -1
  111. package/lib/modules/vaults/write.actions.js +15 -2
  112. package/lib/modules/vaults/write.actions.js.map +1 -1
  113. package/lib/services/layerzero/builder.d.ts +7 -0
  114. package/lib/services/layerzero/builder.js +251 -0
  115. package/lib/services/layerzero/builder.js.map +1 -0
  116. package/lib/services/layerzero/ovault-deposit.d.ts +6 -0
  117. package/lib/services/layerzero/ovault-deposit.js +73 -0
  118. package/lib/services/layerzero/ovault-deposit.js.map +1 -0
  119. package/lib/services/layerzero/ovault-redeem.d.ts +4 -0
  120. package/lib/services/layerzero/ovault-redeem.js +46 -0
  121. package/lib/services/layerzero/ovault-redeem.js.map +1 -0
  122. package/lib/types/ovault.d.ts +78 -0
  123. package/lib/types/ovault.js +3 -0
  124. package/lib/types/ovault.js.map +1 -0
  125. package/lib/types/rwa-redemption.d.ts +12 -0
  126. package/lib/types/rwa-redemption.js +3 -0
  127. package/lib/types/rwa-redemption.js.map +1 -0
  128. package/lib/types/vaults.d.ts +40 -8
  129. package/lib/types/vaults.js.map +1 -1
  130. package/lib/types/web3.d.ts +5 -0
  131. package/lib/types/web3.js +10 -0
  132. package/lib/types/web3.js.map +1 -1
  133. package/lib/types/webserver.d.ts +11 -2
  134. package/lib/verify.d.ts +2 -0
  135. package/lib/verify.js +33 -0
  136. package/lib/verify.js.map +1 -0
  137. package/package.json +12 -12
@@ -57,22 +57,32 @@ exports.getVaultHistoricalTimeseries = getVaultHistoricalTimeseries;
57
57
  exports.getVaultAnnualizedApy = getVaultAnnualizedApy;
58
58
  exports.getVaultSummary = getVaultSummary;
59
59
  exports.getVaultWithdrawals = getVaultWithdrawals;
60
+ exports.getVaultPendingRedemptions = getVaultPendingRedemptions;
60
61
  exports.getPreviewRedemption = getPreviewRedemption;
62
+ exports.getWithdrawalRequestsWithStatus = getWithdrawalRequestsWithStatus;
61
63
  const abis_1 = require("../../abis");
62
64
  const types_1 = require("../../types");
63
65
  const core_1 = require("../../core");
64
66
  const ethers_1 = require("ethers");
67
+ const utils_1 = require("./utils");
65
68
  const subgraph_1 = require("../../services/subgraph");
66
69
  const vaults_1 = require("../../services/subgraph/vaults");
67
70
  const debank_1 = require("../../services/debank");
68
- const utils_1 = require("../../adapters/solana/utils");
71
+ const utils_2 = require("../../adapters/solana/utils");
69
72
  const SolanaGetters = __importStar(require("../../adapters/solana/getters"));
70
73
  const SolanaConstants = __importStar(require("../../adapters/solana/constants"));
74
+ const StellarGetters = __importStar(require("../../adapters/stellar/getters"));
75
+ const utils_3 = require("../../adapters/stellar/utils");
76
+ const constants_1 = require("../../adapters/stellar/constants");
71
77
  const EVM = __importStar(require("../../adapters/evm"));
72
78
  const TokenizedVaultV2_1 = require("../../abis/TokenizedVaultV2");
73
79
  const TokenizedVaultV2Receipt_1 = require("../../abis/TokenizedVaultV2Receipt");
74
80
  const ethereum_block_by_date_1 = __importDefault(require("ethereum-block-by-date"));
75
81
  const octavfi_1 = require("../../services/octavfi");
82
+ const date_utils_1 = require("./utils/date-utils");
83
+ const call_data_decoder_1 = require("./utils/call-data-decoder");
84
+ const deposits_1 = require("../../services/layerzero/deposits");
85
+ const redeems_1 = require("../../services/layerzero/redeems");
76
86
  async function getVault({ vault, loans = false, allocations = false, options, loadSubaccounts, loadSnapshots, }) {
77
87
  let returnedVault;
78
88
  try {
@@ -81,7 +91,12 @@ async function getVault({ vault, loans = false, allocations = false, options, lo
81
91
  const vaultVersion = (0, core_1.getVaultVersionV2)(tokenizedVault);
82
92
  switch (vaultVersion) {
83
93
  case 'sol-0': {
84
- return await SolanaGetters.getSolanaVault(tokenizedVault, options);
94
+ returnedVault = await SolanaGetters.getSolanaVault(tokenizedVault, options);
95
+ break;
96
+ }
97
+ case 'stellar-0': {
98
+ returnedVault = await StellarGetters.getStellarVault(tokenizedVault, options);
99
+ break;
85
100
  }
86
101
  case 'evm-2': {
87
102
  returnedVault = await EVM.getEvmVaultV2(tokenizedVault, options);
@@ -100,7 +115,13 @@ async function getVault({ vault, loans = false, allocations = false, options, lo
100
115
  core_1.Logger.log.error('getVault', err, { vault });
101
116
  throw new Error(`#getVault::${vault}: ${err?.message}`);
102
117
  }
103
- if (!(0, core_1.isBadVault)(vault)) {
118
+ const isEvmVault = returnedVault.version !== 'sol-0' &&
119
+ returnedVault.version !== 'stellar-0' &&
120
+ returnedVault.version !== 'sui-0';
121
+ if (!isEvmVault && (loans || allocations)) {
122
+ core_1.Logger.log.warn('getVault', 'Loans/allocations enrichment is not supported for non-EVM vaults — skipping', { vault, version: returnedVault.version });
123
+ }
124
+ if (isEvmVault && !(0, core_1.isBadVault)(vault)) {
104
125
  if (loans) {
105
126
  try {
106
127
  returnedVault = {
@@ -204,7 +225,6 @@ async function getVaultAllocations(vault, options) {
204
225
  const protocolExposure = [];
205
226
  const tokenExposure = [];
206
227
  let cefiExposure = [];
207
- const cefiBorrowerResponses = {};
208
228
  const otcPositions = {};
209
229
  const defiPerBorrower = {};
210
230
  const exposurePerCategory = {
@@ -322,21 +342,26 @@ async function getVaultAllocations(vault, options) {
322
342
  try {
323
343
  const cefiResponse = await (0, core_1.fetchAugustWithKey)(options.augustKey, core_1.WEBSERVER_ENDPOINTS.subaccount.cefi(borrower), { headers: options?.headers });
324
344
  if (cefiResponse.status !== 200) {
325
- console.error('#getVaultAllocations::cefi:', cefiResponse.status, cefiResponse.statusText);
345
+ core_1.Logger.log.error('getVaultAllocations:cefi', cefiResponse.statusText, {
346
+ borrower,
347
+ status: cefiResponse.status,
348
+ });
326
349
  }
327
350
  if (cefiResponse.status === 200) {
328
351
  const cefiRes = (await cefiResponse.json());
329
- cefiBorrowerResponses[borrower] = cefiRes;
330
- cefiExposure = cefiRes;
352
+ cefiExposure = [...cefiExposure, ...cefiRes];
331
353
  }
332
354
  }
333
355
  catch (e) {
334
- console.error('#getVaultAllocations::cefi:', e);
356
+ core_1.Logger.log.error('getVaultAllocations:cefi', e, { borrower });
335
357
  }
336
358
  try {
337
359
  const otcResponse = await (0, core_1.fetchAugustWithKey)(options.augustKey, core_1.WEBSERVER_ENDPOINTS.subaccount.otc_positions(borrower), { headers: options?.headers });
338
360
  if (otcResponse.status !== 200) {
339
- console.error('#getVaultAllocations::otc:', otcResponse.status, otcResponse.statusText);
361
+ core_1.Logger.log.error('getVaultAllocations:otc', otcResponse.statusText, {
362
+ borrower,
363
+ status: otcResponse.status,
364
+ });
340
365
  }
341
366
  if (otcResponse.status === 200) {
342
367
  const otcRes = (await otcResponse.json());
@@ -344,7 +369,7 @@ async function getVaultAllocations(vault, options) {
344
369
  }
345
370
  }
346
371
  catch (e) {
347
- console.error('#getVaultAllocations::otc:', e);
372
+ core_1.Logger.log.error('getVaultAllocations:otc', e, { borrower });
348
373
  }
349
374
  }
350
375
  }
@@ -371,6 +396,17 @@ async function getVaultAllocations(vault, options) {
371
396
  }
372
397
  async function getVaultAvailableRedemptions({ vault, wallet, options, }) {
373
398
  try {
399
+ if ((0, utils_3.isStellarAddress)(vault)) {
400
+ core_1.Logger.log.warn('getVaultAvailableRedemptions', `Available redemptions is not yet supported for Stellar vaults: ${vault}`);
401
+ return {
402
+ availableRedemptions: [],
403
+ pendingRedemptions: [],
404
+ ...(options.verbose && {
405
+ processedWithdrawals: [],
406
+ requestedWithdrawals: [],
407
+ }),
408
+ };
409
+ }
374
410
  const provider = (0, core_1.createProvider)(options.rpcUrl);
375
411
  const tokenizedVault = (await (0, core_1.fetchTokenizedVault)(vault, options?.headers, false, false))?.[0];
376
412
  if (!tokenizedVault) {
@@ -408,14 +444,14 @@ async function getVaultAvailableRedemptions({ vault, wallet, options, }) {
408
444
  core_1.Logger.log.warn('getVaultAvailableRedemptions', `Skipping invalid event: ${ev}`);
409
445
  continue;
410
446
  }
411
- const date = new Date(Number(ev.timestamp_) * 1000);
412
447
  let month;
413
448
  let day;
414
449
  let year;
415
450
  if (version === 'evm-2') {
416
- month = date.getMonth() + 1;
417
- day = date.getDate();
418
- year = date.getFullYear();
451
+ const claimable = (0, date_utils_1.computeClaimableDate)(Number(ev.timestamp_), lagDuration);
452
+ year = claimable.year;
453
+ month = claimable.month;
454
+ day = claimable.day;
419
455
  }
420
456
  if (!ev.year || !ev.month || !ev.day || !ev.receiverAddr) {
421
457
  if (version !== 'evm-2') {
@@ -432,22 +468,34 @@ async function getVaultAvailableRedemptions({ vault, wallet, options, }) {
432
468
  }
433
469
  }
434
470
  const fullDate = version === 'evm-2'
435
- ? new Date(Number(ev.timestamp_) * 1000)
471
+ ? new Date(Date.UTC(year, month - 1, day))
436
472
  : new Date(Number(ev.year), Number(ev.month) - 1, Number(ev.day));
437
- const foundRedemptionAgainstClaim = withdrawalProcesseds.find((h) => version === 'evm-2'
438
- ? new Date(h.timestamp_).toDateString() === fullDate.toDateString() &&
439
- h.receiverAddr === ev.receiverAddr
440
- : new Date(h.processedOn).toDateString() === fullDate.toDateString() &&
441
- h.receiverAddr === ev.receiverAddr);
473
+ const requestDateKey = version === 'evm-2'
474
+ ? (0, date_utils_1.formatDateKey)(year, month, day)
475
+ : (0, date_utils_1.formatDateKey)(Number(ev.year), Number(ev.month), Number(ev.day));
476
+ const foundRedemptionAgainstClaim = withdrawalProcesseds.find((h) => {
477
+ const proc = h;
478
+ if (proc.receiverAddr !== ev.receiverAddr)
479
+ return false;
480
+ if (version === 'evm-2') {
481
+ const procDate = new Date(Number(proc.timestamp_) * 1000);
482
+ const procKey = (0, date_utils_1.formatDateKey)(procDate.getUTCFullYear(), procDate.getUTCMonth() + 1, procDate.getUTCDate());
483
+ return procKey === requestDateKey;
484
+ }
485
+ const procDate = new Date(proc.processedOn);
486
+ const procKey = (0, date_utils_1.formatDateKey)(procDate.getUTCFullYear(), procDate.getUTCMonth() + 1, procDate.getUTCDate());
487
+ return procKey === requestDateKey;
488
+ });
442
489
  if (wallet && (0, ethers_1.isAddress)(wallet)) {
443
490
  if (ev?.receiverAddr?.toLowerCase() === wallet.toLowerCase()) {
444
491
  const alreadyRedeemed = version === 'evm-2'
445
492
  ? withdrawalProcesseds.find((red) => {
446
- if (Number(ev.timestamp_) * 1000 + lagDuration * 1000 <=
447
- 1000 * Number(red.timestamp_) &&
448
- red.receiverAddr.toLowerCase() === wallet.toLowerCase()) {
449
- return red;
493
+ if (red.receiverAddr.toLowerCase() !== wallet.toLowerCase()) {
494
+ return false;
450
495
  }
496
+ const redDate = new Date(Number(red.timestamp_) * 1000);
497
+ const redKey = (0, date_utils_1.formatDateKey)(redDate.getUTCFullYear(), redDate.getUTCMonth() + 1, redDate.getUTCDate());
498
+ return redKey === requestDateKey;
451
499
  })
452
500
  : availableRedemptions.find((red) => BigInt(red.day.raw) === BigInt(ev.day) &&
453
501
  BigInt(red.month.raw) === BigInt(ev.month) &&
@@ -463,14 +511,9 @@ async function getVaultAvailableRedemptions({ vault, wallet, options, }) {
463
511
  }
464
512
  }
465
513
  if (!alreadyRedeemed) {
466
- const pendingCondition = Number(ev.timestamp_) * 1000 + 1000 * lagDuration <
467
- Date.now();
514
+ const claimable = (0, date_utils_1.computeClaimableDate)(Number(ev.timestamp_), lagDuration);
515
+ const pendingCondition = (0, date_utils_1.isClaimableNow)(claimable.epoch, Math.floor(Date.now() / 1000));
468
516
  if (pendingCondition) {
469
- const date = new Date(Number(year), Number(month) - 1, Number(day));
470
- date.setDate(date.getDate() + lagDuration / (24 * 60 * 60));
471
- year = date.getFullYear();
472
- month = date.getMonth() + 1;
473
- day = date.getDate();
474
517
  try {
475
518
  const burnableAmount = (await vaultContract?.getBurnableAmountByReceiver?.(BigInt(year), BigInt(month), BigInt(day), (0, ethers_1.getAddress)(ev.receiverAddr))) || BigInt(0);
476
519
  const claimAmount = BigInt(ev.shares) || BigInt(0);
@@ -515,15 +558,13 @@ async function getVaultAvailableRedemptions({ vault, wallet, options, }) {
515
558
  default: {
516
559
  const trueClaimableAmount = await vaultContract?.getClaimableAmountByReceiver?.(BigInt(ev.year), BigInt(ev.month), BigInt(ev.day), (0, ethers_1.getAddress)(wallet));
517
560
  if (trueClaimableAmount > BigInt(0)) {
518
- const pendingCondition = Number(ev.timestamp_) * 1000 + 1000 * lagDuration <
519
- Date.now();
561
+ const v1Claimable = (0, date_utils_1.computeClaimableDate)(Number(ev.timestamp_), lagDuration);
562
+ const pendingCondition = (0, date_utils_1.isClaimableNow)(v1Claimable.epoch, Math.floor(Date.now() / 1000));
520
563
  if (pendingCondition) {
521
564
  try {
522
- const date = new Date(Number(ev.year), Number(ev.month) - 1, Number(ev.day));
523
- date.setDate(date.getDate() + lagDuration / (24 * 60 * 60));
524
- year = date.getFullYear();
525
- month = date.getMonth() + 1;
526
- day = date.getDate();
565
+ year = v1Claimable.year;
566
+ month = v1Claimable.month;
567
+ day = v1Claimable.day;
527
568
  const burnableAmount = (await vaultContract?.getBurnableAmountByReceiver?.(BigInt(year), BigInt(month), BigInt(day), (0, ethers_1.getAddress)(ev.receiverAddr))) || BigInt(0);
528
569
  const claimAmount = trueClaimableAmount || BigInt(0);
529
570
  if (burnableAmount >= claimAmount) {
@@ -617,58 +658,113 @@ async function getVaultAvailableRedemptions({ vault, wallet, options, }) {
617
658
  }
618
659
  async function getVaultRedemptionHistory({ vault, wallet, options, }) {
619
660
  try {
661
+ if ((0, utils_3.isStellarAddress)(vault)) {
662
+ core_1.Logger.log.warn('getVaultRedemptionHistory', `Redemption history is not yet supported for Stellar vaults: ${vault}`);
663
+ return [];
664
+ }
620
665
  const provider = (0, core_1.createProvider)(options.rpcUrl);
621
- const tokenizedVault = (await (0, core_1.fetchTokenizedVault)(vault, options?.headers))?.[0];
666
+ const tokenizedVault = (await (0, core_1.fetchTokenizedVault)(vault, options?.headers, false, false))?.[0];
622
667
  if (!tokenizedVault) {
623
668
  return [];
624
669
  }
625
670
  const chainId = tokenizedVault.chain;
671
+ const version = (0, core_1.getVaultVersionV2)(tokenizedVault);
672
+ const isV2 = version === 'evm-2';
673
+ const vaultAbi = isV2 ? TokenizedVaultV2_1.ABI_TOKENIZED_VAULT_V2 : abis_1.ABI_LENDING_POOL_V2;
626
674
  const poolContract = (0, core_1.createContract)({
627
675
  address: vault,
628
- abi: abis_1.ABI_LENDING_POOL_V2,
676
+ abi: vaultAbi,
629
677
  provider,
630
678
  });
631
- const logPromises = [];
632
679
  const currentBlock = await provider.getBlockNumber();
633
- let startingBlock = currentBlock - (0, core_1.determineBlockSkipInternal)(chainId);
634
- let endBlock = currentBlock;
680
+ const blockSkip = (0, core_1.determineBlockSkipInternal)(chainId);
635
681
  const cutoffBlock = currentBlock - (0, core_1.determineBlockCutoff)(chainId);
682
+ const BATCH_SIZE = 20;
683
+ core_1.Logger.log.info('getVaultRedemptionHistory', {
684
+ vault,
685
+ version,
686
+ isV2,
687
+ chainId,
688
+ currentBlock,
689
+ cutoffBlock,
690
+ blockSkip,
691
+ totalRangeBlocks: currentBlock - cutoffBlock,
692
+ });
693
+ const ranges = [];
694
+ let endBlock = currentBlock;
636
695
  while (endBlock >= cutoffBlock) {
637
- const logBloomsPromises = poolContract.queryFilter('WithdrawalProcessed', BigInt(startingBlock), BigInt(endBlock));
638
- logPromises.push(logBloomsPromises);
639
- startingBlock -= (0, core_1.determineBlockSkipInternal)(chainId);
640
- endBlock -= (0, core_1.determineBlockSkipInternal)(chainId);
641
- }
642
- const logs = (await Promise.all(logPromises.flat())).flat();
643
- const iface = new ethers_1.ethers.Interface([
644
- 'event WithdrawalProcessed (uint256 assetsAmount, uint256 processedOn, address receiverAddr, uint256 requestedOn)',
645
- ]);
646
- const events = logs.map((log) => iface.parseLog(log));
696
+ const fromBlock = Math.max(endBlock - blockSkip, cutoffBlock);
697
+ ranges.push({ from: fromBlock, to: endBlock });
698
+ endBlock = fromBlock - 1;
699
+ }
700
+ core_1.Logger.log.info('getVaultRedemptionHistory', {
701
+ totalBatches: Math.ceil(ranges.length / BATCH_SIZE),
702
+ totalChunks: ranges.length,
703
+ firstRange: ranges[0],
704
+ lastRange: ranges[ranges.length - 1],
705
+ });
706
+ const logs = [];
707
+ for (let i = 0; i < ranges.length; i += BATCH_SIZE) {
708
+ const batch = ranges.slice(i, i + BATCH_SIZE);
709
+ const batchResults = await Promise.all(batch.map((r) => poolContract.queryFilter('WithdrawalProcessed', BigInt(r.from), BigInt(r.to))));
710
+ const batchLogs = batchResults.flat();
711
+ logs.push(...batchLogs);
712
+ }
713
+ const iface = new ethers_1.ethers.Interface(isV2
714
+ ? [
715
+ 'event WithdrawalProcessed(uint256 assetsAmount, address indexed receiverAddr)',
716
+ ]
717
+ : [
718
+ 'event WithdrawalProcessed(uint256 assetsAmount, uint256 processedOn, address receiverAddr, uint256 requestedOn)',
719
+ ]);
647
720
  const decimals = await (0, core_1.getDecimals)(provider, vault);
721
+ let blockTimestamps;
722
+ if (isV2 && logs.length > 0) {
723
+ const uniqueBlocks = [...new Set(logs.map((l) => l.blockNumber))];
724
+ const blockResults = await Promise.all(uniqueBlocks.map((bn) => provider.getBlock(bn)));
725
+ blockTimestamps = new Map();
726
+ blockResults.forEach((block) => {
727
+ if (block)
728
+ blockTimestamps.set(block.number, block.timestamp);
729
+ });
730
+ }
648
731
  const redemptions = [];
649
- events?.forEach((ev) => {
732
+ logs.forEach((log) => {
733
+ const ev = iface.parseLog(log);
650
734
  if (!ev?.args)
651
735
  return;
652
- const [assetsAmount, processedOn, receiverAddr, requestedOn] = ev.args;
653
- if (wallet) {
654
- if (String(receiverAddr)?.toLowerCase() === wallet.toLowerCase()) {
655
- redemptions.push({
656
- receiver: receiverAddr,
657
- amount: (0, core_1.toNormalizedBn)(assetsAmount, decimals),
658
- processed: new Date(Number(processedOn) * 1000),
659
- requested: new Date(Number(requestedOn) * 1000),
660
- vault,
661
- });
662
- }
736
+ let item;
737
+ if (isV2) {
738
+ const [assetsAmount, receiverAddr] = ev.args;
739
+ const blockTs = blockTimestamps?.get(log.blockNumber) ?? 0;
740
+ const blockDate = new Date(blockTs * 1000);
741
+ item = {
742
+ receiver: receiverAddr,
743
+ amount: (0, core_1.toNormalizedBn)(assetsAmount, decimals),
744
+ processed: blockDate,
745
+ requested: new Date(0),
746
+ vault,
747
+ transactionHash: log.transactionHash,
748
+ };
663
749
  }
664
750
  else {
665
- redemptions.push({
751
+ const [assetsAmount, processedOn, receiverAddr, requestedOn] = ev.args;
752
+ item = {
666
753
  receiver: receiverAddr,
667
754
  amount: (0, core_1.toNormalizedBn)(assetsAmount, decimals),
668
755
  processed: new Date(Number(processedOn) * 1000),
669
756
  requested: new Date(Number(requestedOn) * 1000),
670
757
  vault,
671
- });
758
+ transactionHash: log.transactionHash,
759
+ };
760
+ }
761
+ if (wallet) {
762
+ if (item.receiver?.toLowerCase() === wallet.toLowerCase()) {
763
+ redemptions.push(item);
764
+ }
765
+ }
766
+ else {
767
+ redemptions.push(item);
672
768
  }
673
769
  });
674
770
  core_1.Logger.log.info('getVaultRedemptionHistory', redemptions.slice(0, 1));
@@ -694,10 +790,10 @@ async function getVaultPositions({ vault, wallet, solanaWallet, options, }) {
694
790
  }
695
791
  const promises = await Promise.all(tokenizedVaults.map(async (v) => {
696
792
  try {
697
- if (utils_1.SolanaUtils.isSolanaAddress(v.address)) {
793
+ if (utils_2.SolanaUtils.isSolanaAddress(v.address)) {
698
794
  let balance = (0, core_1.toNormalizedBn)(0);
699
- if (utils_1.SolanaUtils.isSolanaAddress(solanaWallet)) {
700
- const vaultProgramId = utils_1.SolanaUtils.resolveProgramId(String(v.address), v.solana_vault_metadata);
795
+ if (utils_2.SolanaUtils.isSolanaAddress(solanaWallet)) {
796
+ const vaultProgramId = utils_2.SolanaUtils.resolveProgramId(String(v.address), v.solana_vault_metadata);
701
797
  const vaultStateRes = await options.solanaService.getVaultState(vaultProgramId, SolanaConstants.vaultIdl, v.solana_vault_metadata?.vault_state_pda ?? undefined);
702
798
  if (vaultStateRes &&
703
799
  vaultStateRes?.vaultState?.shareMint) {
@@ -713,6 +809,17 @@ async function getVaultPositions({ vault, wallet, solanaWallet, options, }) {
713
809
  walletBalance: balance,
714
810
  };
715
811
  }
812
+ if ((0, utils_3.isStellarAddress)(v.address)) {
813
+ core_1.Logger.log.warn('getVaultPositions', 'Position tracking not yet available for Stellar vaults', { vault: v.address });
814
+ return {
815
+ vault: v.address,
816
+ status: 'NOT_SUPPORTED',
817
+ availableRedemptions: [],
818
+ pendingRedemptions: [],
819
+ redeemable: (0, core_1.toNormalizedBn)(0),
820
+ walletBalance: (0, core_1.toNormalizedBn)(0),
821
+ };
822
+ }
716
823
  const provider = (0, core_1.createProvider)(options.rpcUrl);
717
824
  let decimals;
718
825
  const version = (0, core_1.getVaultVersionV2)(v);
@@ -933,6 +1040,24 @@ async function getVaultTvl({ vault, options, historical, }) {
933
1040
  }
934
1041
  if (!historical) {
935
1042
  const version = (0, core_1.getVaultVersionV2)(_vaultExists);
1043
+ if (version === 'sol-0') {
1044
+ return [
1045
+ {
1046
+ value: (0, core_1.toNormalizedBn)(0),
1047
+ timestamp: new Date().toISOString(),
1048
+ },
1049
+ ];
1050
+ }
1051
+ if (version === 'stellar-0') {
1052
+ const stellarDecimals = _vaultExists?.stellar_vault_metadata?.deposit_token_decimals ??
1053
+ constants_1.STELLAR_FALLBACK_DECIMALS;
1054
+ return [
1055
+ {
1056
+ value: (0, utils_1.backendTvlToNormalizedBn)(_vaultExists?.latest_reported_tvl, stellarDecimals),
1057
+ timestamp: new Date().toISOString(),
1058
+ },
1059
+ ];
1060
+ }
936
1061
  const provider = (0, core_1.createProvider)(options.rpcUrl);
937
1062
  switch (version) {
938
1063
  case 'evm-2': {
@@ -951,14 +1076,6 @@ async function getVaultTvl({ vault, options, historical, }) {
951
1076
  },
952
1077
  ];
953
1078
  }
954
- case 'sol-0': {
955
- return [
956
- {
957
- value: (0, core_1.toNormalizedBn)(0),
958
- timestamp: new Date().toISOString(),
959
- },
960
- ];
961
- }
962
1079
  default: {
963
1080
  const vaultContract = (0, core_1.createContract)({
964
1081
  address: vault,
@@ -977,12 +1094,16 @@ async function getVaultTvl({ vault, options, historical, }) {
977
1094
  }
978
1095
  }
979
1096
  else {
1097
+ const version = (0, core_1.getVaultVersionV2)(_vaultExists);
1098
+ if (version === 'stellar-0' || version === 'sol-0') {
1099
+ core_1.Logger.log.warn('getVaultTvl:historical', 'Historical TVL not supported for non-EVM vaults', { vault, version });
1100
+ return [];
1101
+ }
980
1102
  if (typeof historical !== 'undefined' && !historical.order)
981
1103
  historical.order = 'desc';
982
1104
  if (typeof historical !== 'undefined' && !historical.interval)
983
1105
  historical.interval = 'days';
984
1106
  const provider = (0, core_1.createProvider)(options.rpcUrl);
985
- const version = (0, core_1.getVaultVersionV2)(_vaultExists);
986
1107
  const vaultContract = (0, core_1.createContract)({
987
1108
  address: vault,
988
1109
  abi: version === 'evm-2' ? TokenizedVaultV2_1.ABI_TOKENIZED_VAULT_V2 : abis_1.ABI_LENDING_POOL_V2,
@@ -1197,7 +1318,8 @@ async function getYieldLastRealizedOn({ vault, options, }) {
1197
1318
  assetsUpdatedOn = await contract.assetsUpdatedOn();
1198
1319
  break;
1199
1320
  }
1200
- case 'sol-0': {
1321
+ case 'sol-0':
1322
+ case 'stellar-0': {
1201
1323
  return 0;
1202
1324
  }
1203
1325
  default: {
@@ -1218,6 +1340,7 @@ async function getVaultUserLifetimePnl({ vault, wallet, options, }) {
1218
1340
  throw new Error('Vault input parameter is undefined.');
1219
1341
  if (!wallet)
1220
1342
  throw new Error('Wallet input parameter is undefined.');
1343
+ (0, utils_3.assertNotStellar)(vault, 'Lifetime PnL');
1221
1344
  if (!(0, ethers_1.isAddress)(vault))
1222
1345
  throw new Error(`Vault input parameter is not an address: ${String(vault)}`);
1223
1346
  if (!(0, ethers_1.isAddress)(wallet))
@@ -1237,6 +1360,30 @@ async function getVaultUserLifetimePnl({ vault, wallet, options, }) {
1237
1360
  if (!tokenizedVault) {
1238
1361
  throw new Error(`Vault ${vault} not found`);
1239
1362
  }
1363
+ const lzVaultKey = (0, deposits_1.isLayerZeroVault)(vault);
1364
+ let lzDeposits = [];
1365
+ let lzRedeems = [];
1366
+ if (lzVaultKey) {
1367
+ const lzPromises = [
1368
+ (0, deposits_1.queryLayerZeroDeposits)(lzVaultKey, wallet)
1369
+ .then((d) => {
1370
+ lzDeposits = d;
1371
+ })
1372
+ .catch((e) => {
1373
+ core_1.Logger.log.warn('getVaultUserLifetimePnl:lzDeposits', `Failed to fetch LZ deposits for ${lzVaultKey}: ${e}`);
1374
+ }),
1375
+ ];
1376
+ if (lzVaultKey === 'earnAUSD') {
1377
+ lzPromises.push((0, redeems_1.queryLayerZeroRedeems)(wallet)
1378
+ .then((r) => {
1379
+ lzRedeems = r;
1380
+ })
1381
+ .catch((e) => {
1382
+ core_1.Logger.log.warn('getVaultUserLifetimePnl:lzRedeems', `Failed to fetch LZ redeems for ${lzVaultKey}: ${e}`);
1383
+ }));
1384
+ }
1385
+ await Promise.all(lzPromises);
1386
+ }
1240
1387
  const version = (0, core_1.getVaultVersionV2)(tokenizedVault);
1241
1388
  const currentPosition = positions.find((pos) => pos.vault?.toLowerCase() === vault.toLowerCase());
1242
1389
  const underlyingSymbolPromise = (async () => {
@@ -1293,9 +1440,22 @@ async function getVaultUserLifetimePnl({ vault, wallet, options, }) {
1293
1440
  totalWithdrawalsInAssets += amount;
1294
1441
  }
1295
1442
  }
1443
+ if (lzVaultKey && lzDeposits.length > 0) {
1444
+ for (const lzDeposit of lzDeposits) {
1445
+ const assetKey = 'lz-default';
1446
+ const amount = BigInt(lzDeposit.assetAmt);
1447
+ const current = depositsByAsset.get(assetKey) ?? BigInt(0);
1448
+ depositsByAsset.set(assetKey, current + amount);
1449
+ }
1450
+ }
1451
+ if (lzVaultKey && lzRedeems.length > 0) {
1452
+ for (const lzRedeem of lzRedeems) {
1453
+ totalWithdrawalsInShares += BigInt(lzRedeem.shareAmt);
1454
+ }
1455
+ }
1296
1456
  const assetDecimals = new Map();
1297
1457
  await Promise.all(Array.from(depositsByAsset.keys()).map(async (assetAddress) => {
1298
- if (assetAddress === 'default') {
1458
+ if (assetAddress === 'default' || assetAddress === 'lz-default') {
1299
1459
  assetDecimals.set(assetAddress, decimals);
1300
1460
  }
1301
1461
  else {
@@ -1311,7 +1471,7 @@ async function getVaultUserLifetimePnl({ vault, wallet, options, }) {
1311
1471
  const assetPrices = new Map();
1312
1472
  if (tokenizedVault.chain) {
1313
1473
  await Promise.all(Array.from(depositsByAsset.keys()).map(async (assetAddress) => {
1314
- if (assetAddress === 'default') {
1474
+ if (assetAddress === 'default' || assetAddress === 'lz-default') {
1315
1475
  assetPrices.set(assetAddress, 0);
1316
1476
  }
1317
1477
  else {
@@ -1353,6 +1513,33 @@ async function getVaultUserLifetimePnl({ vault, wallet, options, }) {
1353
1513
  else {
1354
1514
  currentShares = await vaultContract.balanceOf(wallet);
1355
1515
  }
1516
+ if (lzVaultKey && tokenizedVault.receipt_token_integrations?.length) {
1517
+ const remoteBalances = await Promise.all(tokenizedVault.receipt_token_integrations
1518
+ .filter((rti) => rti.chain !== tokenizedVault.chain && rti.address && rti.chain)
1519
+ .map(async (rti) => {
1520
+ try {
1521
+ const rpcUrls = (0, core_1.getFallbackRpcUrls)(rti.chain);
1522
+ if (!rpcUrls.length) {
1523
+ core_1.Logger.log.warn('getVaultUserLifetimePnl:lzRemoteBalance', `No RPC URL for chain ${rti.chain}, skipping balance check`);
1524
+ return BigInt(0);
1525
+ }
1526
+ const remoteProvider = (0, core_1.createProvider)(rpcUrls[0]);
1527
+ const remoteTokenContract = (0, core_1.createContract)({
1528
+ provider: remoteProvider,
1529
+ address: rti.address,
1530
+ abi: abis_1.ABI_ERC20,
1531
+ });
1532
+ return (await remoteTokenContract.balanceOf(wallet));
1533
+ }
1534
+ catch (e) {
1535
+ core_1.Logger.log.warn('getVaultUserLifetimePnl:lzRemoteBalance', `Failed to fetch balance on chain ${rti.chain}: ${e}`);
1536
+ return BigInt(0);
1537
+ }
1538
+ }));
1539
+ for (const bal of remoteBalances) {
1540
+ currentShares += bal;
1541
+ }
1542
+ }
1356
1543
  if (version === 'evm-2') {
1357
1544
  sharePriceRaw = await vaultContract.getSharePrice();
1358
1545
  }
@@ -1393,7 +1580,7 @@ async function getVaultUserLifetimePnl({ vault, wallet, options, }) {
1393
1580
  }
1394
1581
  let totalDepositedUsd = 0;
1395
1582
  for (const [assetAddress, normalizedAmount] of totalDepositedRaw) {
1396
- const assetPrice = assetAddress === 'default'
1583
+ const assetPrice = assetAddress === 'default' || assetAddress === 'lz-default'
1397
1584
  ? effectiveTokenPrice
1398
1585
  : assetPrices.get(assetAddress) || effectiveTokenPrice;
1399
1586
  totalDepositedUsd += Number(normalizedAmount.normalized) * assetPrice;
@@ -1439,6 +1626,7 @@ async function getVaultPnl({ vault, options, }) {
1439
1626
  try {
1440
1627
  if (!vault)
1441
1628
  throw new Error('Vault input parameter is undefined.');
1629
+ (0, utils_3.assertNotStellar)(vault, 'Vault PnL');
1442
1630
  if (!(0, ethers_1.isAddress)(vault))
1443
1631
  throw new Error(`Vault input parameter is not an address: ${String(vault)}`);
1444
1632
  const vaultData = await getVault({
@@ -1560,6 +1748,7 @@ async function getVaultSummary({ vault, options, }) {
1560
1748
  if (!vault) {
1561
1749
  throw new Error('Vault address parameter is undefined.');
1562
1750
  }
1751
+ (0, utils_3.assertNotStellar)(vault, 'Vault summary');
1563
1752
  if (!(0, ethers_1.isAddress)(vault)) {
1564
1753
  throw new Error(`Vault parameter is not an address: ${String(vault)}`);
1565
1754
  }
@@ -1584,6 +1773,7 @@ async function getVaultWithdrawals({ vault, chain, options, }) {
1584
1773
  if (!vault) {
1585
1774
  throw new Error('Vault address parameter is undefined.');
1586
1775
  }
1776
+ (0, utils_3.assertNotStellar)(vault, 'Vault withdrawals');
1587
1777
  if (!(0, ethers_1.isAddress)(vault)) {
1588
1778
  throw new Error(`Vault parameter is not an address: ${String(vault)}`);
1589
1779
  }
@@ -1606,10 +1796,78 @@ async function getVaultWithdrawals({ vault, chain, options, }) {
1606
1796
  throw new Error(`#getVaultWithdrawals::${vault}::${chain}:${errorMessage}`);
1607
1797
  }
1608
1798
  }
1799
+ async function getVaultPendingRedemptions({ vault, pastDays, futureDays, options, }) {
1800
+ try {
1801
+ if (!vault)
1802
+ throw new Error('Vault address parameter is undefined.');
1803
+ if (!(0, ethers_1.isAddress)(vault))
1804
+ throw new Error(`Vault parameter is not an address: ${String(vault)}`);
1805
+ if (pastDays !== undefined && (pastDays < 1 || pastDays > 30))
1806
+ throw new Error('pastDays must be between 1 and 30');
1807
+ if (futureDays !== undefined && (futureDays < 1 || futureDays > 30))
1808
+ throw new Error('futureDays must be between 1 and 30');
1809
+ const params = new URLSearchParams();
1810
+ if (pastDays !== undefined)
1811
+ params.set('past_days', pastDays.toString());
1812
+ if (futureDays !== undefined)
1813
+ params.set('future_days', futureDays.toString());
1814
+ const qs = params.toString();
1815
+ const endpoint = `${core_1.WEBSERVER_ENDPOINTS.public.vaults.pendingRedemptions(vault)}${qs ? `?${qs}` : ''}`;
1816
+ const response = await (0, core_1.fetchAugustPublic)(endpoint, {
1817
+ headers: options?.headers,
1818
+ server: 'public',
1819
+ });
1820
+ if (!response.ok) {
1821
+ throw new Error(`Failed to fetch pending redemptions: ${response.statusText}`);
1822
+ }
1823
+ const raw = await response.json();
1824
+ return {
1825
+ vault: {
1826
+ address: raw.vault.address,
1827
+ chainId: raw.vault.chain_id,
1828
+ name: raw.vault.name,
1829
+ symbol: raw.vault.symbol,
1830
+ },
1831
+ asset: {
1832
+ address: raw.asset.address,
1833
+ symbol: raw.asset.symbol,
1834
+ decimals: raw.asset.decimals,
1835
+ },
1836
+ liquidity: {
1837
+ available: raw.liquidity.available,
1838
+ },
1839
+ summary: {
1840
+ totalPending: raw.summary.total_pending,
1841
+ pendingCount: raw.summary.pending_count,
1842
+ pendingToLiquidityRatio: raw.summary.pending_to_liquidity_ratio,
1843
+ isLiquiditySufficient: raw.summary.is_liquidity_sufficient,
1844
+ shortfall: raw.summary.shortfall,
1845
+ nextRedemptionDate: raw.summary.next_redemption_date,
1846
+ isOverdue: raw.summary.is_overdue,
1847
+ },
1848
+ redemptionsByDate: raw.redemptions_by_date.map((item) => ({
1849
+ date: item.date,
1850
+ assets: item.assets,
1851
+ daysUntilDue: item.days_until_due,
1852
+ isOverdue: item.is_overdue,
1853
+ })),
1854
+ };
1855
+ }
1856
+ catch (e) {
1857
+ core_1.Logger.log.error('getVaultPendingRedemptions', e, {
1858
+ vault,
1859
+ pastDays,
1860
+ futureDays,
1861
+ });
1862
+ const errorMessage = e instanceof Error ? e.message : String(e);
1863
+ throw new Error(`#getVaultPendingRedemptions::${vault}:${errorMessage}`);
1864
+ }
1865
+ }
1609
1866
  async function getPreviewRedemption({ vault, sharesAmount, options, }) {
1610
1867
  try {
1611
1868
  if (!vault)
1612
1869
  throw new Error('Vault address parameter is undefined.');
1870
+ (0, utils_3.assertNotStellar)(vault, 'Preview redemption');
1613
1871
  if (!(0, ethers_1.isAddress)(vault)) {
1614
1872
  throw new Error(`Vault parameter is not an address: ${String(vault)}`);
1615
1873
  }
@@ -1652,4 +1910,179 @@ async function getPreviewRedemption({ vault, sharesAmount, options, }) {
1652
1910
  throw new Error(`Failed to preview redemption for ${vault}: ${e instanceof Error ? e.message : 'Unknown error'}`);
1653
1911
  }
1654
1912
  }
1913
+ async function decodeProcessingTransaction(txHash, provider, iface) {
1914
+ const tx = await provider.getTransaction(txHash);
1915
+ if (!tx) {
1916
+ return {
1917
+ functionName: 'unknown',
1918
+ year: 0,
1919
+ month: 0,
1920
+ day: 0,
1921
+ error: 'Transaction not found',
1922
+ };
1923
+ }
1924
+ return (0, call_data_decoder_1.decodeWithdrawalProcessing)(tx.data, iface);
1925
+ }
1926
+ async function getWithdrawalRequestsWithStatus(params) {
1927
+ try {
1928
+ const { vault, receiver, options } = params;
1929
+ if (!vault || !(0, ethers_1.isAddress)(vault)) {
1930
+ throw new Error('Invalid vault address');
1931
+ }
1932
+ const vaultAddress = (0, ethers_1.getAddress)(vault);
1933
+ const provider = (0, core_1.createProvider)(options.rpcUrl);
1934
+ const tokenizedVault = (await (0, core_1.fetchTokenizedVault)(vaultAddress, options?.headers, false, false))?.[0];
1935
+ if (!tokenizedVault) {
1936
+ return [];
1937
+ }
1938
+ const version = (0, core_1.getVaultVersionV2)(tokenizedVault);
1939
+ const isV2 = version === 'evm-2';
1940
+ const vaultAbi = isV2 ? TokenizedVaultV2_1.ABI_TOKENIZED_VAULT_V2 : abis_1.ABI_LENDING_POOL_V2;
1941
+ const vaultContract = (0, core_1.createContract)({
1942
+ address: vaultAddress,
1943
+ abi: vaultAbi,
1944
+ provider,
1945
+ });
1946
+ let lagDuration = 86400;
1947
+ try {
1948
+ const lagValue = await vaultContract.lagDuration?.();
1949
+ if (lagValue !== undefined && lagValue !== null) {
1950
+ lagDuration = Number(lagValue);
1951
+ }
1952
+ }
1953
+ catch (e) {
1954
+ core_1.Logger.log.warn(`Failed to fetch lagDuration from vault, using default 1 day: ${e instanceof Error ? e.message : 'Unknown error'}`);
1955
+ }
1956
+ const [withdrawalRequests, processedEvents] = await Promise.all([
1957
+ (0, vaults_1.getSubgraphWithdrawRequests)(vaultAddress, provider),
1958
+ getVaultRedemptionHistory({
1959
+ vault: vaultAddress,
1960
+ wallet: receiver,
1961
+ options,
1962
+ }),
1963
+ ]);
1964
+ if (!withdrawalRequests.length) {
1965
+ return [];
1966
+ }
1967
+ const filteredRequests = receiver
1968
+ ? withdrawalRequests.filter((req) => req.receiverAddr?.toLowerCase() === receiver.toLowerCase())
1969
+ : withdrawalRequests;
1970
+ const iface = new ethers_1.Interface(vaultAbi);
1971
+ const decodedProcessed = await Promise.all((processedEvents || []).map(async (processed) => {
1972
+ if (processed.transactionHash) {
1973
+ try {
1974
+ const decoded = await decodeProcessingTransaction(processed.transactionHash, provider, iface);
1975
+ if (!decoded.error) {
1976
+ return {
1977
+ ...processed,
1978
+ decodedDate: {
1979
+ year: decoded.year,
1980
+ month: decoded.month,
1981
+ day: decoded.day,
1982
+ },
1983
+ };
1984
+ }
1985
+ }
1986
+ catch (e) {
1987
+ core_1.Logger.log.warn(`Failed to decode processed transaction ${processed.transactionHash}: ${e instanceof Error ? e.message : 'Unknown error'}`);
1988
+ }
1989
+ }
1990
+ const requestedEpoch = Math.floor(processed.requested.getTime() / 1000);
1991
+ if (requestedEpoch > 0) {
1992
+ const fallbackDate = (0, date_utils_1.computeClaimableDate)(requestedEpoch, lagDuration);
1993
+ return {
1994
+ ...processed,
1995
+ decodedDate: {
1996
+ year: fallbackDate.year,
1997
+ month: fallbackDate.month,
1998
+ day: fallbackDate.day,
1999
+ },
2000
+ };
2001
+ }
2002
+ const processedDate = processed.processed;
2003
+ return {
2004
+ ...processed,
2005
+ decodedDate: {
2006
+ year: processedDate.getUTCFullYear(),
2007
+ month: processedDate.getUTCMonth() + 1,
2008
+ day: processedDate.getUTCDate(),
2009
+ },
2010
+ };
2011
+ }));
2012
+ const processedMap = new Map();
2013
+ for (const processed of decodedProcessed) {
2014
+ if (!processed.decodedDate) {
2015
+ continue;
2016
+ }
2017
+ const dateKey = (0, date_utils_1.formatDateKey)(processed.decodedDate.year, processed.decodedDate.month, processed.decodedDate.day);
2018
+ const key = `${processed.receiver.toLowerCase()}:${dateKey}`;
2019
+ if (processedMap.has(key)) {
2020
+ core_1.Logger.log.warn('getWithdrawalRequestsWithStatus', `Duplicate processed event for key ${key}, overwriting previous entry`);
2021
+ }
2022
+ processedMap.set(key, processed);
2023
+ }
2024
+ const chainId = tokenizedVault.chain;
2025
+ const effectiveLookbackBlocks = params.lookbackBlocks ?? (0, core_1.determineBlockCutoff)(chainId);
2026
+ const lookbackSeconds = effectiveLookbackBlocks * (0, core_1.determineSecondsPerBlock)(chainId);
2027
+ const results = [];
2028
+ const now = Math.floor(Date.now() / 1000);
2029
+ const lookbackCutoff = now - lookbackSeconds;
2030
+ for (const req of filteredRequests) {
2031
+ const requestTimestamp = Number(req.timestamp_);
2032
+ const claimableDate = (0, date_utils_1.computeClaimableDate)(requestTimestamp, lagDuration);
2033
+ let status = 'pending';
2034
+ let processedTxHash;
2035
+ let assetsReceived;
2036
+ const dateKey = (0, date_utils_1.formatDateKey)(claimableDate.year, claimableDate.month, claimableDate.day);
2037
+ const lookupKey = `${req.receiverAddr.toLowerCase()}:${dateKey}`;
2038
+ const processedEvent = processedMap.get(lookupKey);
2039
+ if (processedEvent) {
2040
+ status = 'processed';
2041
+ processedTxHash = processedEvent.transactionHash;
2042
+ try {
2043
+ assetsReceived = BigInt(processedEvent.amount.raw);
2044
+ }
2045
+ catch (e) {
2046
+ core_1.Logger.log.warn(`Failed to parse assets as BigInt: ${e}`);
2047
+ }
2048
+ }
2049
+ else if (claimableDate.epoch < lookbackCutoff) {
2050
+ continue;
2051
+ }
2052
+ else if ((0, date_utils_1.isClaimableNow)(claimableDate.epoch, now)) {
2053
+ status = 'ready_to_claim';
2054
+ }
2055
+ results.push({
2056
+ transactionHash: req.transactionHash_,
2057
+ requestTimestamp,
2058
+ shares: (() => {
2059
+ try {
2060
+ return BigInt(req.shares);
2061
+ }
2062
+ catch {
2063
+ return BigInt(Math.trunc(Number(req.shares)));
2064
+ }
2065
+ })(),
2066
+ receiver: req.receiverAddr,
2067
+ claimableDate: {
2068
+ year: claimableDate.year,
2069
+ month: claimableDate.month,
2070
+ day: claimableDate.day,
2071
+ },
2072
+ claimableEpoch: claimableDate.epoch,
2073
+ status,
2074
+ processedTransactionHash: processedTxHash,
2075
+ assetsReceived,
2076
+ });
2077
+ }
2078
+ return results;
2079
+ }
2080
+ catch (e) {
2081
+ core_1.Logger.log.error('getWithdrawalRequestsWithStatus', e, {
2082
+ vaultAddress: params.vault,
2083
+ hasReceiver: !!params.receiver,
2084
+ });
2085
+ throw new Error(`Failed to get withdrawal requests with status: ${e instanceof Error ? e.message : 'Unknown error'}`);
2086
+ }
2087
+ }
1655
2088
  //# sourceMappingURL=getters.js.map