@defisaver/positions-sdk 2.1.127-midnight-1-dev → 2.1.127-midnight-3-dev

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 (76) hide show
  1. package/cjs/aaveV3/index.js +7 -1
  2. package/cjs/aaveV4/lend.js +3 -3
  3. package/cjs/claiming/index.d.ts +2 -1
  4. package/cjs/claiming/index.js +3 -1
  5. package/cjs/claiming/uniswap.d.ts +5 -0
  6. package/cjs/claiming/uniswap.js +75 -0
  7. package/cjs/config/contracts.d.ts +22 -0
  8. package/cjs/config/contracts.js +9 -1
  9. package/cjs/contracts.d.ts +35 -0
  10. package/cjs/contracts.js +2 -1
  11. package/cjs/curveUsd/index.js +1 -1
  12. package/cjs/helpers/morphoBlueHelpers/index.js +1 -0
  13. package/cjs/helpers/morphoMidnightHelpers/index.d.ts +45 -7
  14. package/cjs/helpers/morphoMidnightHelpers/index.js +101 -13
  15. package/cjs/llamaLend/index.js +1 -1
  16. package/cjs/markets/aaveV4/index.d.ts +2 -0
  17. package/cjs/markets/aaveV4/index.js +14 -1
  18. package/cjs/morphoBlue/index.d.ts +8 -6
  19. package/cjs/morphoBlue/index.js +69 -40
  20. package/cjs/portfolio/index.js +31 -2
  21. package/cjs/savings/summerVaults/options.js +10 -10
  22. package/cjs/staking/staking.js +3 -0
  23. package/cjs/types/aaveV4.d.ts +2 -1
  24. package/cjs/types/aaveV4.js +1 -0
  25. package/cjs/types/claiming.d.ts +10 -0
  26. package/cjs/types/claiming.js +2 -0
  27. package/cjs/types/morphoBlue.d.ts +9 -0
  28. package/cjs/types/morphoMidnight.d.ts +9 -0
  29. package/esm/aaveV3/index.js +7 -1
  30. package/esm/aaveV4/lend.js +3 -3
  31. package/esm/claiming/index.d.ts +2 -1
  32. package/esm/claiming/index.js +2 -1
  33. package/esm/claiming/uniswap.d.ts +5 -0
  34. package/esm/claiming/uniswap.js +67 -0
  35. package/esm/config/contracts.d.ts +22 -0
  36. package/esm/config/contracts.js +8 -0
  37. package/esm/contracts.d.ts +35 -0
  38. package/esm/contracts.js +1 -0
  39. package/esm/curveUsd/index.js +1 -1
  40. package/esm/helpers/morphoBlueHelpers/index.js +1 -0
  41. package/esm/helpers/morphoMidnightHelpers/index.d.ts +45 -7
  42. package/esm/helpers/morphoMidnightHelpers/index.js +98 -13
  43. package/esm/llamaLend/index.js +1 -1
  44. package/esm/markets/aaveV4/index.d.ts +2 -0
  45. package/esm/markets/aaveV4/index.js +12 -0
  46. package/esm/morphoBlue/index.d.ts +8 -6
  47. package/esm/morphoBlue/index.js +62 -39
  48. package/esm/portfolio/index.js +32 -3
  49. package/esm/savings/summerVaults/options.js +10 -10
  50. package/esm/staking/staking.js +3 -0
  51. package/esm/types/aaveV4.d.ts +2 -1
  52. package/esm/types/aaveV4.js +1 -0
  53. package/esm/types/claiming.d.ts +10 -0
  54. package/esm/types/claiming.js +2 -0
  55. package/esm/types/morphoBlue.d.ts +9 -0
  56. package/esm/types/morphoMidnight.d.ts +9 -0
  57. package/package.json +2 -2
  58. package/src/aaveV3/index.ts +13 -1
  59. package/src/aaveV4/lend.ts +3 -3
  60. package/src/claiming/index.ts +2 -0
  61. package/src/claiming/uniswap.ts +70 -0
  62. package/src/config/contracts.ts +9 -0
  63. package/src/contracts.ts +2 -0
  64. package/src/curveUsd/index.ts +1 -1
  65. package/src/helpers/morphoBlueHelpers/index.ts +1 -0
  66. package/src/helpers/morphoMidnightHelpers/index.ts +142 -17
  67. package/src/llamaLend/index.ts +1 -1
  68. package/src/markets/aaveV4/index.ts +13 -0
  69. package/src/morphoBlue/index.ts +101 -44
  70. package/src/portfolio/index.ts +32 -3
  71. package/src/savings/summerVaults/options.ts +10 -10
  72. package/src/staking/staking.ts +2 -0
  73. package/src/types/aaveV4.ts +1 -0
  74. package/src/types/claiming.ts +11 -0
  75. package/src/types/morphoBlue.ts +11 -0
  76. package/src/types/morphoMidnight.ts +12 -0
@@ -64,9 +64,15 @@ function _getAaveV3MarketData(provider_1, network_1, market_1) {
64
64
  const aaveIncentivesContract = (0, contracts_1.AaveIncentiveDataProviderV3ContractViem)(provider, network);
65
65
  const marketAddress = market.providerAddress;
66
66
  const networksWithIncentives = [common_1.NetworkNumber.Eth, common_1.NetworkNumber.Arb, common_1.NetworkNumber.Opt, common_1.NetworkNumber.Linea, common_1.NetworkNumber.Plasma];
67
+ // Limit each view call to 10 tokens, run chunks concurrently, then combine their results into loanInfo.
68
+ const addressesPerRequest = 10;
69
+ const addressChunks = _addresses.length > addressesPerRequest
70
+ ? Array.from({ length: Math.ceil(_addresses.length / addressesPerRequest) }, (_, index) => _addresses.slice(index * addressesPerRequest, (index + 1) * addressesPerRequest))
71
+ : [_addresses];
72
+ const loanInfoPromise = Promise.all(addressChunks.map((addresses) => loanInfoContract.read.getFullTokensInfo([marketAddress, addresses], (0, viem_1.setViemBlockNumber)(blockNumber)))).then((loanInfoChunks) => loanInfoChunks.flat());
67
73
  // eslint-disable-next-line prefer-const
68
74
  let [loanInfo, eModesInfo, rewardInfo, merkleRewardsMap, meritRewardsMap] = yield Promise.all([
69
- loanInfoContract.read.getFullTokensInfo([marketAddress, _addresses], (0, viem_1.setViemBlockNumber)(blockNumber)),
75
+ loanInfoPromise,
70
76
  loanInfoContract.read.getAllEmodes([marketAddress], (0, viem_1.setViemBlockNumber)(blockNumber)),
71
77
  networksWithIncentives.includes(network) ? aaveIncentivesContract.read.getReservesIncentivesData([marketAddress], (0, viem_1.setViemBlockNumber)(blockNumber)) : null,
72
78
  (0, merkl_1.getMerkleCampaigns)(network),
@@ -34,9 +34,9 @@ exports.AAVE_V4_TOKENIZED_SPOKES = {
34
34
  GHO_PRIME: '0x900fD46d565d1ac8995928c0179052ec02a6D0E1',
35
35
  USDC_PRIME: '0x486415fb1F8b062c89ED548f871cf64304AACb31',
36
36
  USDT_PRIME: '0x46c588DD8453aC259c1f6a54b4C9A93C2aC3762D',
37
- USDC_PAXOS: '0x4131E0B2E7AFeCEAf3d3b4225aA61a3B2B7535b8',
38
- USDT_PAXOS: '0x8Dabe53E8cB991c57f0307F6f419E6D469b0deAA',
39
- PT_USDG_Sep_PAXOS: '0x27eF1140364948A0E30E248297FfDFE5a4091ec4',
37
+ USDC_PAXOS: '0xaed7c529bD2878170B61C758DfAa215AC7a4FD07',
38
+ USDT_PAXOS: '0xa0e97e45C2f89003730E467Bd484fA3eEcE5B4Cf',
39
+ PT_USDG_Sep_PAXOS: '0x7Df10B4A01350D2A1d95cFbE7c9207d7210A2663',
40
40
  };
41
41
  exports.AAVE_V4_TOKENIZED_SPOKE_ADDRESSES = {
42
42
  [common_1.NetworkNumber.Eth]: Object.values(exports.AAVE_V4_TOKENIZED_SPOKES),
@@ -2,4 +2,5 @@ import * as aaveV3Claim from './aaveV3';
2
2
  import * as compV3Claim from './compV3';
3
3
  import * as kingV3Claim from './king';
4
4
  import * as sparkClaim from './spark';
5
- export { aaveV3Claim, compV3Claim, kingV3Claim, sparkClaim, };
5
+ import * as uniswapClaim from './uniswap';
6
+ export { aaveV3Claim, compV3Claim, kingV3Claim, sparkClaim, uniswapClaim, };
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.sparkClaim = exports.kingV3Claim = exports.compV3Claim = exports.aaveV3Claim = void 0;
36
+ exports.uniswapClaim = exports.sparkClaim = exports.kingV3Claim = exports.compV3Claim = exports.aaveV3Claim = void 0;
37
37
  const aaveV3Claim = __importStar(require("./aaveV3"));
38
38
  exports.aaveV3Claim = aaveV3Claim;
39
39
  const compV3Claim = __importStar(require("./compV3"));
@@ -42,3 +42,5 @@ const kingV3Claim = __importStar(require("./king"));
42
42
  exports.kingV3Claim = kingV3Claim;
43
43
  const sparkClaim = __importStar(require("./spark"));
44
44
  exports.sparkClaim = sparkClaim;
45
+ const uniswapClaim = __importStar(require("./uniswap"));
46
+ exports.uniswapClaim = uniswapClaim;
@@ -0,0 +1,5 @@
1
+ import { Client } from 'viem';
2
+ import { EthAddress, NetworkNumber } from '../types';
3
+ import { UniswapAirdropClaimableToken } from '../types/claiming';
4
+ export declare const fetchUniswapRewardsData: (walletAddress: EthAddress) => Promise<any>;
5
+ export declare const getUniswapRewards: (provider: Client, network: NetworkNumber, walletAddresses: EthAddress[]) => Promise<Record<string, UniswapAirdropClaimableToken[]>>;
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.getUniswapRewards = exports.fetchUniswapRewardsData = void 0;
16
+ const decimal_js_1 = __importDefault(require("decimal.js"));
17
+ const tokens_1 = require("@defisaver/tokens");
18
+ const contracts_1 = require("../contracts");
19
+ const claiming_1 = require("../types/claiming");
20
+ const EMPTY_DATA = (walletAddress) => ({
21
+ address: walletAddress, index: 0, amount: '0x0', proof: [],
22
+ });
23
+ const fetchUniswapRewardsData = (walletAddress) => __awaiter(void 0, void 0, void 0, function* () {
24
+ try {
25
+ const res = yield fetch(`https://fe.defisaver.com/api/rewards/uniswap?user=${walletAddress}`, { signal: AbortSignal.timeout(5000) });
26
+ if (!res.ok)
27
+ throw new Error(yield res.text());
28
+ const data = yield res.json();
29
+ if (data.data.error)
30
+ return EMPTY_DATA(walletAddress);
31
+ return data.data;
32
+ }
33
+ catch (err) {
34
+ return EMPTY_DATA(walletAddress);
35
+ }
36
+ });
37
+ exports.fetchUniswapRewardsData = fetchUniswapRewardsData;
38
+ const getUniswapRewards = (provider, network, walletAddresses) => __awaiter(void 0, void 0, void 0, function* () {
39
+ // Fetch all API data in parallel (these are external API calls, can't be batched with multicall)
40
+ const apiDataPromises = walletAddresses.map(address => (0, exports.fetchUniswapRewardsData)(address));
41
+ const apiDataArray = yield Promise.all(apiDataPromises);
42
+ // Batch all contract calls using multicall
43
+ const contract = (0, contracts_1.UniswapTokenDistributorViem)(provider, network);
44
+ const cumulativePromises = apiDataArray.map(data => (data.index ? contract.read.isClaimed([data.index]) : Promise.resolve(false)));
45
+ const cumulativeResults = yield Promise.all(cumulativePromises);
46
+ // Process results
47
+ const results = {};
48
+ for (let i = 0; i < walletAddresses.length; i++) {
49
+ const walletAddress = walletAddresses[i];
50
+ const data = apiDataArray[i];
51
+ const cumulative = cumulativeResults[i];
52
+ const amountToClaim = new decimal_js_1.default(data.amount);
53
+ if (amountToClaim.lessThanOrEqualTo('0') || cumulative) {
54
+ results[walletAddress.toLowerCase()] = [];
55
+ }
56
+ else {
57
+ results[walletAddress.toLowerCase()] = [{
58
+ symbol: 'UNI',
59
+ underlyingSymbol: 'UNI',
60
+ label: 'Uniswap Airdrop',
61
+ tokenAddress: '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984',
62
+ amount: (0, tokens_1.assetAmountInEth)(amountToClaim.toString(), 'UNI'),
63
+ walletAddress,
64
+ claimType: claiming_1.ClaimType.UNI_REWARDS,
65
+ additionalClaimFields: {
66
+ index: data.index,
67
+ isClaimed: cumulative,
68
+ proof: data.proof,
69
+ },
70
+ }];
71
+ }
72
+ }
73
+ return results;
74
+ });
75
+ exports.getUniswapRewards = getUniswapRewards;
@@ -99340,3 +99340,25 @@ export declare const AaveV4View: {
99340
99340
  };
99341
99341
  };
99342
99342
  };
99343
+ export declare const UniswapTokenDistributor: {
99344
+ readonly abi: readonly [{
99345
+ readonly inputs: readonly [{
99346
+ readonly internalType: "uint256";
99347
+ readonly name: "index";
99348
+ readonly type: "uint256";
99349
+ }];
99350
+ readonly name: "isClaimed";
99351
+ readonly outputs: readonly [{
99352
+ readonly internalType: "bool";
99353
+ readonly name: "";
99354
+ readonly type: "bool";
99355
+ }];
99356
+ readonly stateMutability: "view";
99357
+ readonly type: "function";
99358
+ }];
99359
+ readonly networks: {
99360
+ readonly "1": {
99361
+ readonly address: "0x090D4613473dEE047c3f2706764f49E0821D256e";
99362
+ };
99363
+ };
99364
+ };
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.LiquityView = exports.crvUSDFactory = exports.crvUSDView = exports.crvUSDsfrxETHAmm = exports.crvUSDtBTCAmm = exports.crvUSDWBTCAmm = exports.crvUSDETHAmm = exports.crvUSDwstETHAmm = exports.crvUSDsfrxETHController = exports.crvUSDtBTCController = exports.crvUSDWBTCController = exports.crvUSDETHController = exports.crvUSDwstETHController = exports.SparkProtocolDataProvider = exports.SparkPoolAddressesProvider = exports.SparkLendingPool = exports.SparkIncentiveDataProvider = exports.SparkView = exports.Pot = exports.IAToken = exports.IVariableDebtToken = exports.Comptroller = exports.CompoundLoanInfo = exports.AaveLendingPoolV2 = exports.AaveProtocolDataProvider = exports.LendingPoolAddressesProvider = exports.AaveLoanInfoV2 = exports.wstETH = exports.CompV3BulkerL2 = exports.CompV3BulkerMainnetETH = exports.CompV3BulkerMainnetUSDC = exports.CompV3View = exports.cWstETHv3 = exports.cUSDSv3 = exports.cUSDTv3 = exports.cETHv3 = exports.cUSDbCv3 = exports.cUSDCev3 = exports.cUSDCv3 = exports.AaveUiIncentiveDataProviderV3 = exports.AaveV3EtherfiProtocolDataProvider = exports.AaveV3LidoProtocolDataProvider = exports.AaveV3ProtocolDataProvider = exports.AaveV3EtherfiLendingPool = exports.AaveV3LidoLendingPool = exports.AaveV3LendingPool = exports.AaveV3EtherfiPoolAddressesProvider = exports.AaveV3LidoPoolAddressesProvider = exports.AaveV3PoolAddressesProvider = exports.AaveV3View = void 0;
5
5
  exports.YearnV3Vault = exports.SkySavings = exports.SparkSavingsVault = exports.MakerDsr = exports.YearnView = exports.YearnVault = exports.MorphoVault = exports.StkAAVE = exports.LiquityV2sBoldVault = exports.LiquityV2ActivePool = exports.AaveRewardsController = exports.SparkRewardsController = exports.SparkAirdrop = exports.UUPS = exports.LiquityStabilityPool = exports.LiquityLQTYStaking = exports.AaveUmbrellaView = exports.Erc4626 = exports.Erc20 = exports.AaveIncentivesController = exports.McdCdpManager = exports.McdGetCdps = exports.FluidView = exports.LiquityV2StabilityPool = exports.EulerV2View = exports.LiquityV2TroveNFT = exports.LiquityV2CollSurplusPool = exports.LiquityV2View = exports.LiquityV2LegacyView = exports.LlamaLendControllerAbi = exports.LlamaLendView = exports.DFSFeedRegistry = exports.FeedRegistry = exports.MidnightView = exports.MorphoBlueView = exports.WeETHPriceFeed = exports.WstETHPriceFeed = exports.USDCPriceFeed = exports.BTCPriceFeed = exports.ETHPriceFeed = exports.COMPPriceFeed = exports.McdDog = exports.McdJug = exports.McdVat = exports.McdSpotter = exports.McdView = exports.LiquityActivePool = exports.PriceFeed = exports.TroveManager = exports.CollSurplusPool = void 0;
6
- exports.AaveV4View = void 0;
6
+ exports.UniswapTokenDistributor = exports.AaveV4View = void 0;
7
7
  exports.AaveV3View = {
8
8
  "abi": [{ "inputs": [], "name": "AAVE_REFERRAL_CODE", "outputs": [{ "internalType": "uint16", "name": "", "type": "uint16" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_umbrella", "type": "address" }, { "internalType": "address", "name": "_user", "type": "address" }], "name": "getAdditionalUmbrellaStakingData", "outputs": [{ "components": [{ "internalType": "address", "name": "stkToken", "type": "address" }, { "internalType": "uint256", "name": "totalShares", "type": "uint256" }, { "internalType": "address", "name": "stkUnderlyingToken", "type": "address" }, { "internalType": "address", "name": "aToken", "type": "address" }, { "internalType": "uint256", "name": "cooldownPeriod", "type": "uint256" }, { "internalType": "uint256", "name": "unstakeWindow", "type": "uint256" }, { "internalType": "uint256", "name": "stkTokenToWaTokenRate", "type": "uint256" }, { "internalType": "uint256", "name": "waTokenToATokenRate", "type": "uint256" }, { "internalType": "uint256[]", "name": "rewardsEmissionRates", "type": "uint256[]" }, { "internalType": "uint256", "name": "userCooldownAmount", "type": "uint256" }, { "internalType": "uint256", "name": "userEndOfCooldown", "type": "uint256" }, { "internalType": "uint256", "name": "userWithdrawalWindow", "type": "uint256" }], "internalType": "struct AaveV3View.UmbrellaStkData[]", "name": "retVal", "type": "tuple[]" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_market", "type": "address" }], "name": "getAllEmodes", "outputs": [{ "components": [{ "internalType": "uint16", "name": "ltv", "type": "uint16" }, { "internalType": "uint16", "name": "liquidationThreshold", "type": "uint16" }, { "internalType": "uint16", "name": "liquidationBonus", "type": "uint16" }, { "internalType": "uint128", "name": "collateralBitmap", "type": "uint128" }, { "internalType": "bool", "name": "isolated", "type": "bool" }, { "internalType": "string", "name": "label", "type": "string" }, { "internalType": "uint128", "name": "borrowableBitmap", "type": "uint128" }, { "internalType": "uint128", "name": "ltvzeroBitmap", "type": "uint128" }], "internalType": "struct DataTypes.EModeCategoryNew[]", "name": "emodesData", "type": "tuple[]" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_market", "type": "address" }, { "components": [{ "internalType": "address", "name": "reserveAddress", "type": "address" }, { "internalType": "uint256", "name": "liquidityAdded", "type": "uint256" }, { "internalType": "uint256", "name": "liquidityTaken", "type": "uint256" }, { "internalType": "bool", "name": "isDebtAsset", "type": "bool" }], "internalType": "struct AaveV3View.LiquidityChangeParams[]", "name": "_reserveParams", "type": "tuple[]" }], "name": "getApyAfterValuesEstimation", "outputs": [{ "components": [{ "internalType": "address", "name": "reserveAddress", "type": "address" }, { "internalType": "uint256", "name": "supplyRate", "type": "uint256" }, { "internalType": "uint256", "name": "variableBorrowRate", "type": "uint256" }], "internalType": "struct AaveV3View.EstimatedRates[]", "name": "", "type": "tuple[]" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_market", "type": "address" }, { "internalType": "address", "name": "_tokenAddr", "type": "address" }], "name": "getAssetPrice", "outputs": [{ "internalType": "uint256", "name": "price", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_market", "type": "address" }, { "internalType": "address[]", "name": "_tokens", "type": "address[]" }], "name": "getCollFactors", "outputs": [{ "internalType": "uint256[]", "name": "collFactors", "type": "uint256[]" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "uint256", "name": "emodeCategory", "type": "uint256" }, { "internalType": "contract IPoolV3", "name": "lendingPool", "type": "address" }], "name": "getEModeCollateralFactor", "outputs": [{ "internalType": "uint16", "name": "", "type": "uint16" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_asset", "type": "address" }, { "internalType": "address", "name": "_eoa", "type": "address" }, { "internalType": "address", "name": "_proxy", "type": "address" }, { "internalType": "address", "name": "_market", "type": "address" }], "name": "getEOAApprovalsAndBalances", "outputs": [{ "components": [{ "internalType": "address", "name": "asset", "type": "address" }, { "internalType": "address", "name": "aToken", "type": "address" }, { "internalType": "address", "name": "variableDebtToken", "type": "address" }, { "internalType": "uint256", "name": "assetApproval", "type": "uint256" }, { "internalType": "uint256", "name": "aTokenApproval", "type": "uint256" }, { "internalType": "uint256", "name": "variableDebtDelegation", "type": "uint256" }, { "internalType": "uint256", "name": "borrowedVariableAmount", "type": "uint256" }, { "internalType": "uint256", "name": "eoaBalance", "type": "uint256" }, { "internalType": "uint256", "name": "aTokenBalance", "type": "uint256" }], "internalType": "struct AaveV3View.EOAApprovalData", "name": "approvalData", "type": "tuple" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_eoa", "type": "address" }, { "internalType": "address", "name": "_proxy", "type": "address" }, { "internalType": "address", "name": "_market", "type": "address" }], "name": "getEOAApprovalsAndBalancesForAllTokens", "outputs": [{ "components": [{ "internalType": "address", "name": "asset", "type": "address" }, { "internalType": "address", "name": "aToken", "type": "address" }, { "internalType": "address", "name": "variableDebtToken", "type": "address" }, { "internalType": "uint256", "name": "assetApproval", "type": "uint256" }, { "internalType": "uint256", "name": "aTokenApproval", "type": "uint256" }, { "internalType": "uint256", "name": "variableDebtDelegation", "type": "uint256" }, { "internalType": "uint256", "name": "borrowedVariableAmount", "type": "uint256" }, { "internalType": "uint256", "name": "eoaBalance", "type": "uint256" }, { "internalType": "uint256", "name": "aTokenBalance", "type": "uint256" }], "internalType": "struct AaveV3View.EOAApprovalData[]", "name": "approvalData", "type": "tuple[]" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "contract IPoolV3", "name": "_lendingPool", "type": "address" }, { "internalType": "uint8", "name": "_id", "type": "uint8" }], "name": "getEmodeData", "outputs": [{ "components": [{ "internalType": "uint16", "name": "ltv", "type": "uint16" }, { "internalType": "uint16", "name": "liquidationThreshold", "type": "uint16" }, { "internalType": "uint16", "name": "liquidationBonus", "type": "uint16" }, { "internalType": "uint128", "name": "collateralBitmap", "type": "uint128" }, { "internalType": "bool", "name": "isolated", "type": "bool" }, { "internalType": "string", "name": "label", "type": "string" }, { "internalType": "uint128", "name": "borrowableBitmap", "type": "uint128" }, { "internalType": "uint128", "name": "ltvzeroBitmap", "type": "uint128" }], "internalType": "struct DataTypes.EModeCategoryNew", "name": "emodeData", "type": "tuple" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_market", "type": "address" }, { "internalType": "address[]", "name": "_tokenAddresses", "type": "address[]" }], "name": "getFullTokensInfo", "outputs": [{ "components": [{ "internalType": "address", "name": "aTokenAddress", "type": "address" }, { "internalType": "address", "name": "underlyingTokenAddress", "type": "address" }, { "internalType": "uint16", "name": "assetId", "type": "uint16" }, { "internalType": "uint256", "name": "supplyRate", "type": "uint256" }, { "internalType": "uint256", "name": "borrowRateVariable", "type": "uint256" }, { "internalType": "uint256", "name": "borrowRateStable", "type": "uint256" }, { "internalType": "uint256", "name": "totalSupply", "type": "uint256" }, { "internalType": "uint256", "name": "availableLiquidity", "type": "uint256" }, { "internalType": "uint256", "name": "totalBorrow", "type": "uint256" }, { "internalType": "uint256", "name": "totalBorrowVar", "type": "uint256" }, { "internalType": "uint256", "name": "totalBorrowStab", "type": "uint256" }, { "internalType": "uint256", "name": "collateralFactor", "type": "uint256" }, { "internalType": "uint256", "name": "liquidationRatio", "type": "uint256" }, { "internalType": "uint256", "name": "price", "type": "uint256" }, { "internalType": "uint256", "name": "supplyCap", "type": "uint256" }, { "internalType": "uint256", "name": "borrowCap", "type": "uint256" }, { "internalType": "uint256", "name": "emodeCategory", "type": "uint256" }, { "internalType": "uint256", "name": "debtCeilingForIsolationMode", "type": "uint256" }, { "internalType": "uint256", "name": "isolationModeTotalDebt", "type": "uint256" }, { "internalType": "bool", "name": "usageAsCollateralEnabled", "type": "bool" }, { "internalType": "bool", "name": "borrowingEnabled", "type": "bool" }, { "internalType": "bool", "name": "stableBorrowRateEnabled", "type": "bool" }, { "internalType": "bool", "name": "isolationModeBorrowingEnabled", "type": "bool" }, { "internalType": "bool", "name": "isSiloedForBorrowing", "type": "bool" }, { "internalType": "uint256", "name": "eModeCollateralFactor", "type": "uint256" }, { "internalType": "bool", "name": "isFlashLoanEnabled", "type": "bool" }, { "internalType": "uint16", "name": "ltv", "type": "uint16" }, { "internalType": "uint16", "name": "liquidationThreshold", "type": "uint16" }, { "internalType": "uint16", "name": "liquidationBonus", "type": "uint16" }, { "internalType": "address", "name": "priceSource", "type": "address" }, { "internalType": "string", "name": "label", "type": "string" }, { "internalType": "bool", "name": "isActive", "type": "bool" }, { "internalType": "bool", "name": "isPaused", "type": "bool" }, { "internalType": "bool", "name": "isFrozen", "type": "bool" }, { "internalType": "address", "name": "debtTokenAddress", "type": "address" }], "internalType": "struct AaveV3View.TokenInfoFull[]", "name": "tokens", "type": "tuple[]" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_market", "type": "address" }, { "internalType": "address", "name": "_user", "type": "address" }], "name": "getHealthFactor", "outputs": [{ "internalType": "uint256", "name": "healthFactor", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_market", "type": "address" }, { "internalType": "address", "name": "_user", "type": "address" }], "name": "getLoanData", "outputs": [{ "components": [{ "internalType": "address", "name": "user", "type": "address" }, { "internalType": "uint128", "name": "ratio", "type": "uint128" }, { "internalType": "uint256", "name": "eMode", "type": "uint256" }, { "internalType": "address[]", "name": "collAddr", "type": "address[]" }, { "internalType": "bool[]", "name": "enabledAsColl", "type": "bool[]" }, { "internalType": "address[]", "name": "borrowAddr", "type": "address[]" }, { "internalType": "uint256[]", "name": "collAmounts", "type": "uint256[]" }, { "internalType": "uint256[]", "name": "borrowStableAmounts", "type": "uint256[]" }, { "internalType": "uint256[]", "name": "borrowVariableAmounts", "type": "uint256[]" }, { "internalType": "uint16", "name": "ltv", "type": "uint16" }, { "internalType": "uint16", "name": "liquidationThreshold", "type": "uint16" }, { "internalType": "uint16", "name": "liquidationBonus", "type": "uint16" }, { "internalType": "address", "name": "priceSource", "type": "address" }, { "internalType": "string", "name": "label", "type": "string" }], "internalType": "struct AaveV3View.LoanData", "name": "data", "type": "tuple" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_market", "type": "address" }, { "internalType": "address[]", "name": "_users", "type": "address[]" }], "name": "getLoanDataArr", "outputs": [{ "components": [{ "internalType": "address", "name": "user", "type": "address" }, { "internalType": "uint128", "name": "ratio", "type": "uint128" }, { "internalType": "uint256", "name": "eMode", "type": "uint256" }, { "internalType": "address[]", "name": "collAddr", "type": "address[]" }, { "internalType": "bool[]", "name": "enabledAsColl", "type": "bool[]" }, { "internalType": "address[]", "name": "borrowAddr", "type": "address[]" }, { "internalType": "uint256[]", "name": "collAmounts", "type": "uint256[]" }, { "internalType": "uint256[]", "name": "borrowStableAmounts", "type": "uint256[]" }, { "internalType": "uint256[]", "name": "borrowVariableAmounts", "type": "uint256[]" }, { "internalType": "uint16", "name": "ltv", "type": "uint16" }, { "internalType": "uint16", "name": "liquidationThreshold", "type": "uint16" }, { "internalType": "uint16", "name": "liquidationBonus", "type": "uint16" }, { "internalType": "address", "name": "priceSource", "type": "address" }, { "internalType": "string", "name": "label", "type": "string" }], "internalType": "struct AaveV3View.LoanData[]", "name": "loans", "type": "tuple[]" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_market", "type": "address" }, { "internalType": "address[]", "name": "_tokens", "type": "address[]" }], "name": "getPrices", "outputs": [{ "internalType": "uint256[]", "name": "prices", "type": "uint256[]" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_market", "type": "address" }, { "internalType": "address", "name": "_user", "type": "address" }], "name": "getRatio", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_market", "type": "address" }, { "internalType": "address[]", "name": "_users", "type": "address[]" }], "name": "getRatios", "outputs": [{ "internalType": "uint256[]", "name": "ratios", "type": "uint256[]" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_market", "type": "address" }, { "internalType": "address", "name": "_user", "type": "address" }], "name": "getSafetyRatio", "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_market", "type": "address" }, { "internalType": "address", "name": "_user", "type": "address" }, { "internalType": "address[]", "name": "_tokens", "type": "address[]" }], "name": "getTokenBalances", "outputs": [{ "components": [{ "internalType": "address", "name": "token", "type": "address" }, { "internalType": "uint256", "name": "balance", "type": "uint256" }, { "internalType": "uint256", "name": "borrowsStable", "type": "uint256" }, { "internalType": "uint256", "name": "borrowsVariable", "type": "uint256" }, { "internalType": "uint256", "name": "stableBorrowRate", "type": "uint256" }, { "internalType": "bool", "name": "enabledAsCollateral", "type": "bool" }], "internalType": "struct AaveV3View.UserToken[]", "name": "userTokens", "type": "tuple[]" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_market", "type": "address" }, { "internalType": "address", "name": "_tokenAddr", "type": "address" }], "name": "getTokenInfoFull", "outputs": [{ "components": [{ "internalType": "address", "name": "aTokenAddress", "type": "address" }, { "internalType": "address", "name": "underlyingTokenAddress", "type": "address" }, { "internalType": "uint16", "name": "assetId", "type": "uint16" }, { "internalType": "uint256", "name": "supplyRate", "type": "uint256" }, { "internalType": "uint256", "name": "borrowRateVariable", "type": "uint256" }, { "internalType": "uint256", "name": "borrowRateStable", "type": "uint256" }, { "internalType": "uint256", "name": "totalSupply", "type": "uint256" }, { "internalType": "uint256", "name": "availableLiquidity", "type": "uint256" }, { "internalType": "uint256", "name": "totalBorrow", "type": "uint256" }, { "internalType": "uint256", "name": "totalBorrowVar", "type": "uint256" }, { "internalType": "uint256", "name": "totalBorrowStab", "type": "uint256" }, { "internalType": "uint256", "name": "collateralFactor", "type": "uint256" }, { "internalType": "uint256", "name": "liquidationRatio", "type": "uint256" }, { "internalType": "uint256", "name": "price", "type": "uint256" }, { "internalType": "uint256", "name": "supplyCap", "type": "uint256" }, { "internalType": "uint256", "name": "borrowCap", "type": "uint256" }, { "internalType": "uint256", "name": "emodeCategory", "type": "uint256" }, { "internalType": "uint256", "name": "debtCeilingForIsolationMode", "type": "uint256" }, { "internalType": "uint256", "name": "isolationModeTotalDebt", "type": "uint256" }, { "internalType": "bool", "name": "usageAsCollateralEnabled", "type": "bool" }, { "internalType": "bool", "name": "borrowingEnabled", "type": "bool" }, { "internalType": "bool", "name": "stableBorrowRateEnabled", "type": "bool" }, { "internalType": "bool", "name": "isolationModeBorrowingEnabled", "type": "bool" }, { "internalType": "bool", "name": "isSiloedForBorrowing", "type": "bool" }, { "internalType": "uint256", "name": "eModeCollateralFactor", "type": "uint256" }, { "internalType": "bool", "name": "isFlashLoanEnabled", "type": "bool" }, { "internalType": "uint16", "name": "ltv", "type": "uint16" }, { "internalType": "uint16", "name": "liquidationThreshold", "type": "uint16" }, { "internalType": "uint16", "name": "liquidationBonus", "type": "uint16" }, { "internalType": "address", "name": "priceSource", "type": "address" }, { "internalType": "string", "name": "label", "type": "string" }, { "internalType": "bool", "name": "isActive", "type": "bool" }, { "internalType": "bool", "name": "isPaused", "type": "bool" }, { "internalType": "bool", "name": "isFrozen", "type": "bool" }, { "internalType": "address", "name": "debtTokenAddress", "type": "address" }], "internalType": "struct AaveV3View.TokenInfoFull", "name": "_tokenInfo", "type": "tuple" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "_market", "type": "address" }, { "internalType": "address[]", "name": "_tokenAddresses", "type": "address[]" }], "name": "getTokensInfo", "outputs": [{ "components": [{ "internalType": "address", "name": "aTokenAddress", "type": "address" }, { "internalType": "address", "name": "underlyingTokenAddress", "type": "address" }, { "internalType": "uint256", "name": "collateralFactor", "type": "uint256" }, { "internalType": "uint256", "name": "price", "type": "uint256" }], "internalType": "struct AaveV3View.TokenInfo[]", "name": "tokens", "type": "tuple[]" }], "stateMutability": "view", "type": "function" }, { "inputs": [{ "internalType": "address", "name": "", "type": "address" }], "name": "isBorrowAllowed", "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }], "stateMutability": "pure", "type": "function" }],
9
9
  "networks": {
@@ -1363,3 +1363,11 @@ exports.AaveV4View = {
1363
1363
  }
1364
1364
  }
1365
1365
  };
1366
+ exports.UniswapTokenDistributor = {
1367
+ "abi": [{ "inputs": [{ "internalType": "uint256", "name": "index", "type": "uint256" }], "name": "isClaimed", "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }], "stateMutability": "view", "type": "function" }],
1368
+ "networks": {
1369
+ "1": {
1370
+ "address": "0x090D4613473dEE047c3f2706764f49E0821D256e",
1371
+ }
1372
+ }
1373
+ };
@@ -619752,3 +619752,38 @@ export declare const AaveV4ViewContractViem: (client: Client, network: NetworkNu
619752
619752
  readonly type: "function";
619753
619753
  }];
619754
619754
  };
619755
+ export declare const UniswapTokenDistributorViem: (client: Client, network: NetworkNumber, block?: Blockish) => {
619756
+ read: {
619757
+ isClaimed: (args: readonly [bigint], options?: import("viem").Prettify<import("viem").UnionOmit<import("viem").ReadContractParameters<readonly [{
619758
+ readonly inputs: readonly [{
619759
+ readonly internalType: "uint256";
619760
+ readonly name: "index";
619761
+ readonly type: "uint256";
619762
+ }];
619763
+ readonly name: "isClaimed";
619764
+ readonly outputs: readonly [{
619765
+ readonly internalType: "bool";
619766
+ readonly name: "";
619767
+ readonly type: "bool";
619768
+ }];
619769
+ readonly stateMutability: "view";
619770
+ readonly type: "function";
619771
+ }], "isClaimed", readonly [bigint]>, "address" | "args" | "abi" | "functionName">> | undefined) => Promise<boolean>;
619772
+ };
619773
+ address: `0x${string}`;
619774
+ abi: readonly [{
619775
+ readonly inputs: readonly [{
619776
+ readonly internalType: "uint256";
619777
+ readonly name: "index";
619778
+ readonly type: "uint256";
619779
+ }];
619780
+ readonly name: "isClaimed";
619781
+ readonly outputs: readonly [{
619782
+ readonly internalType: "bool";
619783
+ readonly name: "";
619784
+ readonly type: "bool";
619785
+ }];
619786
+ readonly stateMutability: "view";
619787
+ readonly type: "function";
619788
+ }];
619789
+ };
package/cjs/contracts.js CHANGED
@@ -34,7 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.UUPSViem = exports.LiquityStabilityPoolViem = exports.LiquityLQTYStakingViem = exports.AaveUmbrellaViewViem = exports.AaveIncentivesControllerViem = exports.FluidViewContractViem = exports.LiquityV2LegacyViewContractViem = exports.LiquityV2ViewContractViem = exports.LiquityActivePoolContractViem = exports.LiquityPriceFeedContractViem = exports.LiquityTroveManagerContractViem = exports.LiquityCollSurplusPoolContractViem = exports.LiquityViewContractViem = exports.BTCPriceFeedContractViem = exports.WeETHPriceFeedContractViem = exports.ComptrollerContractViem = exports.CompoundLoanInfoContractViem = exports.McdJugContractViem = exports.McdDogContractViem = exports.McdSpotterContractViem = exports.McdVatContractViem = exports.McdViewContractViem = exports.McdGetCdpsContractViem = exports.LlamaLendViewContractViem = exports.CrvUSDFactoryContractViem = exports.CrvUSDViewContractViem = exports.EulerV2ViewContractViem = exports.SparkIncentiveDataProviderContractViem = exports.SparkViewContractViem = exports.CompV3ViewContractViem = exports.WstETHPriceFeedContractViem = exports.USDCPriceFeedContractViem = exports.ETHPriceFeedContractViem = exports.COMPPriceFeedContractViem = exports.DFSFeedRegistryContractViem = exports.FeedRegistryContractViem = exports.AaveIncentiveDataProviderV3ContractViem = exports.AaveV3ViewContractViem = exports.AaveLoanInfoV2ContractViem = exports.MorphoMidnightViewContractViem = exports.MorphoBlueViewContractViem = exports.getYearnV3VaultContractViem = exports.getErc4626ContractViem = exports.getErc20ContractViem = exports.getSparkSavingsVaultContractViem = exports.getYearnVaultContractViem = exports.getMorphoVaultContractViem = exports.createViemContractFromConfigFunc = exports.getConfigContractAbi = exports.getConfigContractAddress = void 0;
37
- exports.AaveV4ViewContractViem = exports.SkySavingsContractView = exports.MakerDsrContractViem = exports.YearnViewContractViem = exports.StkAAVEViem = exports.LiquityV2sBoldVaultViem = exports.AaveRewardsControllerViem = exports.SparkRewardsControllerViem = void 0;
37
+ exports.UniswapTokenDistributorViem = exports.AaveV4ViewContractViem = exports.SkySavingsContractView = exports.MakerDsrContractViem = exports.YearnViewContractViem = exports.StkAAVEViem = exports.LiquityV2sBoldVaultViem = exports.AaveRewardsControllerViem = exports.SparkRewardsControllerViem = void 0;
38
38
  const viem_1 = require("viem");
39
39
  const configRaw = __importStar(require("./config/contracts"));
40
40
  // @ts-ignore
@@ -188,3 +188,4 @@ exports.YearnViewContractViem = (0, exports.createViemContractFromConfigFunc)('Y
188
188
  exports.MakerDsrContractViem = (0, exports.createViemContractFromConfigFunc)('MakerDsr');
189
189
  exports.SkySavingsContractView = (0, exports.createViemContractFromConfigFunc)('SkySavings');
190
190
  exports.AaveV4ViewContractViem = (0, exports.createViemContractFromConfigFunc)('AaveV4View');
191
+ exports.UniswapTokenDistributorViem = (0, exports.createViemContractFromConfigFunc)('UniswapTokenDistributor');
@@ -30,7 +30,7 @@ const getAndFormatBands = (provider, network, selectedMarket, _minBand, _maxBand
30
30
  // getBandsData uses a lot of gas to get all of the bands at once, so we use pagination and fetch 200 bands at a time
31
31
  let i = minBand;
32
32
  while (i < maxBand) {
33
- i += 200;
33
+ i += 20;
34
34
  if (i > maxBand) {
35
35
  pivots.push(maxBand);
36
36
  }
@@ -361,6 +361,7 @@ const getRewardsForMarket = (marketId_1, ...args_1) => __awaiter(void 0, [market
361
361
  query: REWARDS_QUERY,
362
362
  variables: { marketId, chainId: network },
363
363
  }),
364
+ signal: AbortSignal.timeout(utils_1.LONGER_TIMEOUT),
364
365
  });
365
366
  const data = yield response.json();
366
367
  const marketData = (_a = data === null || data === void 0 ? void 0 : data.data) === null || _a === void 0 ? void 0 : _a.marketById;
@@ -1,6 +1,6 @@
1
1
  import Dec from 'decimal.js';
2
- import { MMUsedAssets } from '../../types/common';
3
- import { MorphoMidnightAggregatedPositionData, MorphoMidnightAssetsData, MorphoMidnightMarketInfo } from '../../types';
2
+ import { MMUsedAssets, NetworkNumber } from '../../types/common';
3
+ import { MorphoMidnightAggregatedPositionData, MorphoMidnightAssetsData, MorphoMidnightMarketData, MorphoMidnightMarketInfo, MorphoMidnightParsedBook } from '../../types';
4
4
  /**
5
5
  * Aggregate a Morpho Midnight position. Midnight markets are multi-collateral, so the borrow limit is
6
6
  * the sum of each collateral's USD value times its own lltv (Aave-v4 style), rather than a single pair.
@@ -34,6 +34,23 @@ export interface MorphoMidnightBorrowQuote {
34
34
  }
35
35
  export declare const midnightTimeToMaturityDays: (maturity: number, atSeconds?: number) => number;
36
36
  export declare const midnightApyFromPrice: (price: Dec.Value, ttmDays: Dec.Value) => string;
37
+ /**
38
+ * Inverse of `midnightApyFromPrice`: the loan-per-unit price a borrow APY implies,
39
+ * price = (1 + rate)^(−ttmDays / 365).
40
+ *
41
+ * This is what turns an absolute rate ceiling into an on-chain `maxUnits` cap (units = assets / price),
42
+ * and equally the principal a unit of borrow power is worth — Midnight debt is recorded at its maturity
43
+ * face value, so borrowing the full limit as principal would overshoot it by the interest.
44
+ */
45
+ export declare const midnightPriceFromApy: (ratePercent: Dec.Value, ttmDays: Dec.Value) => string;
46
+ /**
47
+ * Coerce a slippage into what the quote endpoint accepts: 0.1–100 with at most one decimal place. The
48
+ * validation is lexical, so a computed value (`4.15066671050631467`) is rejected outright — without this
49
+ * the request 400s and the quote looks unavailable.
50
+ *
51
+ * Rounded **down**, since a wider slippage is a looser cap than the caller asked for.
52
+ */
53
+ export declare const midnightSlippageParam: (slippagePercent: Dec.Value) => string;
37
54
  /**
38
55
  * Current borrower rate + debt breakdown from the Midnight transactions API. On-chain we can only read the
39
56
  * total debt at maturity (`units`); the base-vs-interest split and the effective borrow rate require the
@@ -42,9 +59,30 @@ export declare const midnightApyFromPrice: (price: Dec.Value, ttmDays: Dec.Value
42
59
  */
43
60
  export declare const getMorphoMidnightUserBorrowInfo: (account: string, marketId: string, maturity: number, loanTokenSymbol: string) => Promise<MorphoMidnightBorrowInfo>;
44
61
  /**
45
- * Estimate the borrow rate + slippage cap for a prospective borrow by quoting the Midnight order book.
46
- * `assetsRaw` (and the returned `newUnits`/`maxUnits`) are raw loan-token base unitscallers convert to/from
47
- * human amounts. `maxUnits` (from the slippage-adjusted worst price) is the cap sent on-chain to protect the
48
- * user if better offers get filled first. Throws if the book can't fill the amount (caller handles).
62
+ * A market's resting bids, as rates rather than the API's WAD-scaled loan-per-unit prices. Annualizing
63
+ * each price against time-to-maturity gives the rate a borrower filling that offer paysverified
64
+ * against Morpho's fixed-market UI, where per-offer rates match to the cent.
65
+ *
66
+ * Returns `null` for an empty book: there is nothing to borrow against, so a market listing should skip
67
+ * the market rather than advertise it at a 0% rate. Throws when the request fails — an error response is
68
+ * rarely JSON, so without the `res.ok` check it parses as an empty book and the market silently vanishes.
69
+ */
70
+ export declare const getMorphoMidnightMarketBook: (market: MorphoMidnightMarketData, network: NetworkNumber) => Promise<MorphoMidnightParsedBook | null>;
71
+ /**
72
+ * Quote a prospective borrow against the Midnight order book: the estimated rate, the debt units it adds,
73
+ * and the `maxUnits` cap sent on-chain to protect the user if better offers get filled first. `assetsRaw`
74
+ * (and the returned `newUnits`/`maxUnits`) are raw loan-token base units — callers convert to/from human
75
+ * amounts. Throws if the book can't fill the amount (caller handles).
76
+ *
77
+ * Two ways to set the cap:
78
+ * - `maxBorrowRate` — an absolute APY ceiling, honoured **exactly**: the cap price is derived locally via
79
+ * `midnightPriceFromApy`. Prefer this when a user pins a max rate.
80
+ * - otherwise `slippagePercent`, the API's own knob. Note it is a **price**-level slippage, not APY points:
81
+ * near maturity the annualisation factor (365 / ttmDays) multiplies it heavily, so on a 22-day market a
82
+ * slippage of 0.5 permitted an APY ~9pp above the estimate, not 0.5pp. It also saturates at the book's
83
+ * cheapest bid. `maxRate` therefore reports what the cap actually permits, derived from the cap price.
84
+ *
85
+ * A `maxBorrowRate` below `estBorrowRate` yields `maxUnits < newUnits` — the borrow would revert on-chain.
86
+ * Compare the two before submitting and tell the user their ceiling is under the market rate.
49
87
  */
50
- export declare const getMorphoMidnightBorrowQuote: (marketId: string, assetsRaw: string, slippagePercent: Dec.Value, maturity: number) => Promise<MorphoMidnightBorrowQuote>;
88
+ export declare const getMorphoMidnightBorrowQuote: (marketId: string, assetsRaw: string, slippagePercent: Dec.Value, maturity: number, maxBorrowRate?: Dec.Value) => Promise<MorphoMidnightBorrowQuote>;
@@ -12,7 +12,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
12
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.getMorphoMidnightBorrowQuote = exports.getMorphoMidnightUserBorrowInfo = exports.midnightApyFromPrice = exports.midnightTimeToMaturityDays = exports.getMorphoMidnightAggregatedPositionData = void 0;
15
+ exports.getMorphoMidnightBorrowQuote = exports.getMorphoMidnightMarketBook = exports.getMorphoMidnightUserBorrowInfo = exports.midnightSlippageParam = exports.midnightPriceFromApy = exports.midnightApyFromPrice = exports.midnightTimeToMaturityDays = exports.getMorphoMidnightAggregatedPositionData = void 0;
16
16
  const decimal_js_1 = __importDefault(require("decimal.js"));
17
17
  const tokens_1 = require("@defisaver/tokens");
18
18
  const moneymarket_1 = require("../../moneymarket");
@@ -86,6 +86,13 @@ exports.getMorphoMidnightAggregatedPositionData = getMorphoMidnightAggregatedPos
86
86
  // loan-per-unit ratios (< 1 for a discounted fixed-term borrow); annualizing them yields the borrow APY.
87
87
  const MIDNIGHT_API_BASE = 'https://api.morpho.org/v0/midnight';
88
88
  const nowInSeconds = () => Math.floor(Date.now() / 1000);
89
+ // The book endpoint is markedly slower than the rest of the API — `LONGER_TIMEOUT` (5s) aborts it often
90
+ // enough that markets drop out of the list for no reason.
91
+ const MIDNIGHT_BOOK_TIMEOUT = 30000;
92
+ // The quote endpoint's `slippage` query param is validated as a string: 0.1–100, at most one decimal
93
+ // place (`0.50` is rejected even though `0.5` passes). See `midnightSlippageParam`.
94
+ const MIDNIGHT_SLIPPAGE_MIN = 0.1;
95
+ const MIDNIGHT_SLIPPAGE_MAX = 100;
89
96
  // Days remaining until maturity, optionally measured at a past timestamp (for historical fills).
90
97
  const midnightTimeToMaturityDays = (maturity, atSeconds = nowInSeconds()) => new decimal_js_1.default(maturity).sub(atSeconds).div(constants_1.SECONDS_PER_DAY).toNumber();
91
98
  exports.midnightTimeToMaturityDays = midnightTimeToMaturityDays;
@@ -101,6 +108,31 @@ const midnightApyFromPrice = (price, ttmDays) => {
101
108
  .toString();
102
109
  };
103
110
  exports.midnightApyFromPrice = midnightApyFromPrice;
111
+ /**
112
+ * Inverse of `midnightApyFromPrice`: the loan-per-unit price a borrow APY implies,
113
+ * price = (1 + rate)^(−ttmDays / 365).
114
+ *
115
+ * This is what turns an absolute rate ceiling into an on-chain `maxUnits` cap (units = assets / price),
116
+ * and equally the principal a unit of borrow power is worth — Midnight debt is recorded at its maturity
117
+ * face value, so borrowing the full limit as principal would overshoot it by the interest.
118
+ */
119
+ const midnightPriceFromApy = (ratePercent, ttmDays) => {
120
+ const rate = new decimal_js_1.default(ratePercent);
121
+ const ttm = new decimal_js_1.default(ttmDays);
122
+ if (rate.lte(0) || ttm.lte(0))
123
+ return '1';
124
+ return new decimal_js_1.default(1).div(new decimal_js_1.default(1).add(rate.div(100)).pow(ttm.div(365))).toString();
125
+ };
126
+ exports.midnightPriceFromApy = midnightPriceFromApy;
127
+ /**
128
+ * Coerce a slippage into what the quote endpoint accepts: 0.1–100 with at most one decimal place. The
129
+ * validation is lexical, so a computed value (`4.15066671050631467`) is rejected outright — without this
130
+ * the request 400s and the quote looks unavailable.
131
+ *
132
+ * Rounded **down**, since a wider slippage is a looser cap than the caller asked for.
133
+ */
134
+ const midnightSlippageParam = (slippagePercent) => decimal_js_1.default.min(decimal_js_1.default.max(new decimal_js_1.default(slippagePercent), MIDNIGHT_SLIPPAGE_MIN), MIDNIGHT_SLIPPAGE_MAX).toDP(1, decimal_js_1.default.ROUND_DOWN).toString();
135
+ exports.midnightSlippageParam = midnightSlippageParam;
104
136
  /**
105
137
  * Current borrower rate + debt breakdown from the Midnight transactions API. On-chain we can only read the
106
138
  * total debt at maturity (`units`); the base-vs-interest split and the effective borrow rate require the
@@ -136,25 +168,81 @@ const getMorphoMidnightUserBorrowInfo = (account, marketId, maturity, loanTokenS
136
168
  });
137
169
  exports.getMorphoMidnightUserBorrowInfo = getMorphoMidnightUserBorrowInfo;
138
170
  /**
139
- * Estimate the borrow rate + slippage cap for a prospective borrow by quoting the Midnight order book.
140
- * `assetsRaw` (and the returned `newUnits`/`maxUnits`) are raw loan-token base unitscallers convert to/from
141
- * human amounts. `maxUnits` (from the slippage-adjusted worst price) is the cap sent on-chain to protect the
142
- * user if better offers get filled first. Throws if the book can't fill the amount (caller handles).
171
+ * A market's resting bids, as rates rather than the API's WAD-scaled loan-per-unit prices. Annualizing
172
+ * each price against time-to-maturity gives the rate a borrower filling that offer paysverified
173
+ * against Morpho's fixed-market UI, where per-offer rates match to the cent.
174
+ *
175
+ * Returns `null` for an empty book: there is nothing to borrow against, so a market listing should skip
176
+ * the market rather than advertise it at a 0% rate. Throws when the request fails — an error response is
177
+ * rarely JSON, so without the `res.ok` check it parses as an empty book and the market silently vanishes.
178
+ */
179
+ const getMorphoMidnightMarketBook = (market, network) => __awaiter(void 0, void 0, void 0, function* () {
180
+ var _a;
181
+ const loanSymbol = (0, tokens_1.getAssetInfoByAddress)(market.loanToken, network).symbol;
182
+ const res = yield fetch(`${MIDNIGHT_API_BASE}/books/${market.marketId}`, { signal: AbortSignal.timeout(MIDNIGHT_BOOK_TIMEOUT) });
183
+ if (!res.ok)
184
+ throw new Error(`Midnight book request failed for ${market.value} (${res.status})`);
185
+ const json = yield res.json();
186
+ const ttmDays = (0, exports.midnightTimeToMaturityDays)(market.maturity);
187
+ const offers = (((_a = json === null || json === void 0 ? void 0 : json.data) === null || _a === void 0 ? void 0 : _a.bids) || [])
188
+ .map((bid) => ({
189
+ rate: (0, exports.midnightApyFromPrice)(new decimal_js_1.default(bid.price).div(constants_1.WAD), ttmDays),
190
+ liquidity: (0, tokens_1.assetAmountInEth)(bid.assets, loanSymbol),
191
+ }))
192
+ .sort((a, b) => new decimal_js_1.default(a.rate).minus(b.rate).toNumber());
193
+ if (offers.length === 0)
194
+ return null;
195
+ return {
196
+ bestRate: offers[0].rate,
197
+ totalLiquidity: offers.reduce((sum, offer) => sum.add(offer.liquidity), new decimal_js_1.default(0)).toString(),
198
+ offers,
199
+ };
200
+ });
201
+ exports.getMorphoMidnightMarketBook = getMorphoMidnightMarketBook;
202
+ // The API says why a quote failed — NOT_FOUND (market matured or not open yet), INSUFFICIENT_LIQUIDITY
203
+ // (book can't fill the size), VALIDATION_ERROR (bad param, with the offending field in `details`).
204
+ // Callers surface this to the user, so keep the reason rather than collapsing everything into one string.
205
+ const midnightQuoteError = (error) => {
206
+ const detail = ((error === null || error === void 0 ? void 0 : error.details) || []).map(({ issue }) => issue).filter(Boolean).join('; ');
207
+ const reason = detail || (error === null || error === void 0 ? void 0 : error.message) || (error === null || error === void 0 ? void 0 : error.code);
208
+ return reason ? `Morpho Midnight quote unavailable: ${reason}` : 'Morpho Midnight quote unavailable';
209
+ };
210
+ /**
211
+ * Quote a prospective borrow against the Midnight order book: the estimated rate, the debt units it adds,
212
+ * and the `maxUnits` cap sent on-chain to protect the user if better offers get filled first. `assetsRaw`
213
+ * (and the returned `newUnits`/`maxUnits`) are raw loan-token base units — callers convert to/from human
214
+ * amounts. Throws if the book can't fill the amount (caller handles).
215
+ *
216
+ * Two ways to set the cap:
217
+ * - `maxBorrowRate` — an absolute APY ceiling, honoured **exactly**: the cap price is derived locally via
218
+ * `midnightPriceFromApy`. Prefer this when a user pins a max rate.
219
+ * - otherwise `slippagePercent`, the API's own knob. Note it is a **price**-level slippage, not APY points:
220
+ * near maturity the annualisation factor (365 / ttmDays) multiplies it heavily, so on a 22-day market a
221
+ * slippage of 0.5 permitted an APY ~9pp above the estimate, not 0.5pp. It also saturates at the book's
222
+ * cheapest bid. `maxRate` therefore reports what the cap actually permits, derived from the cap price.
223
+ *
224
+ * A `maxBorrowRate` below `estBorrowRate` yields `maxUnits < newUnits` — the borrow would revert on-chain.
225
+ * Compare the two before submitting and tell the user their ceiling is under the market rate.
143
226
  */
144
- const getMorphoMidnightBorrowQuote = (marketId, assetsRaw, slippagePercent, maturity) => __awaiter(void 0, void 0, void 0, function* () {
145
- const url = `${MIDNIGHT_API_BASE}/books/${marketId}/bids/quote?assets=${assetsRaw}&slippage=${slippagePercent}`;
227
+ const getMorphoMidnightBorrowQuote = (marketId, assetsRaw, slippagePercent, maturity, maxBorrowRate) => __awaiter(void 0, void 0, void 0, function* () {
228
+ const url = `${MIDNIGHT_API_BASE}/books/${marketId}/bids/quote?assets=${assetsRaw}&slippage=${(0, exports.midnightSlippageParam)(slippagePercent)}`;
146
229
  const res = yield fetch(url, { signal: AbortSignal.timeout(utils_1.LONGER_TIMEOUT) });
147
230
  const json = yield res.json();
148
231
  const d = json === null || json === void 0 ? void 0 : json.data;
149
232
  if (!(d === null || d === void 0 ? void 0 : d.average_best_price))
150
- throw new Error('Morpho Midnight quote unavailable');
233
+ throw new Error(midnightQuoteError(json === null || json === void 0 ? void 0 : json.error));
151
234
  const bestPrice = new decimal_js_1.default(d.average_best_price).div(constants_1.WAD).toString();
152
- const worstPrice = new decimal_js_1.default(d.average_worst_price).div(constants_1.WAD).toString();
235
+ const worstPrice = new decimal_js_1.default(d.average_worst_price || 0).div(constants_1.WAD).toString();
153
236
  const ttmDays = (0, exports.midnightTimeToMaturityDays)(maturity);
154
237
  const estBorrowRate = (0, exports.midnightApyFromPrice)(bestPrice, ttmDays);
155
- const maxRate = new decimal_js_1.default(estBorrowRate).add(slippagePercent).toString();
238
+ // Price the cap sits at, and the rate that price represents — one derivation, so `maxRate` and
239
+ // `maxUnits` can never disagree about what the user is protected at.
240
+ const capPrice = maxBorrowRate !== undefined && new decimal_js_1.default(maxBorrowRate).gt(0)
241
+ ? (0, exports.midnightPriceFromApy)(maxBorrowRate, ttmDays)
242
+ : worstPrice;
243
+ const maxRate = (0, exports.midnightApyFromPrice)(capPrice, ttmDays);
156
244
  const newUnits = new decimal_js_1.default(bestPrice).lte(0) ? '0' : new decimal_js_1.default(assetsRaw).div(bestPrice).toFixed(0);
157
- const maxUnits = new decimal_js_1.default(worstPrice).lte(0) ? '0' : new decimal_js_1.default(assetsRaw).div(worstPrice).toFixed(0);
245
+ const maxUnits = new decimal_js_1.default(capPrice).lte(0) ? '0' : new decimal_js_1.default(assetsRaw).div(capPrice).toFixed(0);
158
246
  return {
159
247
  bestPrice,
160
248
  worstPrice,
@@ -162,8 +250,8 @@ const getMorphoMidnightBorrowQuote = (marketId, assetsRaw, slippagePercent, matu
162
250
  maxRate,
163
251
  newUnits,
164
252
  maxUnits,
165
- availableAssets: d.available_assets,
166
- availableUnits: d.available_units,
253
+ availableAssets: d.available_assets || '0',
254
+ availableUnits: d.available_units || '0',
167
255
  takeableOffers: d.takeable_offers || [],
168
256
  };
169
257
  });
@@ -31,7 +31,7 @@ const getAndFormatBands = (provider, network, selectedMarket, _minBand, _maxBand
31
31
  // getBandsData uses a lot of gas to get all of the bands at once, so we use pagination and fetch 200 bands at a time
32
32
  let i = minBand;
33
33
  while (i < maxBand) {
34
- i += 200;
34
+ i += 20;
35
35
  if (i > maxBand) {
36
36
  pivots.push(maxBand);
37
37
  }
@@ -22,6 +22,7 @@ export declare const AAVE_V4_LIDO_SPOKE: (networkId: NetworkNumber) => AaveV4Spo
22
22
  export declare const AAVE_V4_LOMBARD_BTC_SPOKE: (networkId: NetworkNumber) => AaveV4SpokeInfo;
23
23
  export declare const AAVE_V4_MAIN_SPOKE: (networkId: NetworkNumber) => AaveV4SpokeInfo;
24
24
  export declare const AAVE_V4_USDG_PENDLE_SPOKE: (networkId: NetworkNumber) => AaveV4SpokeInfo;
25
+ export declare const AAVE_V4_USDG_MAPLE_SPOKE: (networkId: NetworkNumber) => AaveV4SpokeInfo;
25
26
  export declare const AaveV4Spokes: (networkId: NetworkNumber) => {
26
27
  readonly aave_v4_bluechip_spoke: AaveV4SpokeInfo;
27
28
  readonly aave_v4_ethena_correlated_spoke: AaveV4SpokeInfo;
@@ -34,6 +35,7 @@ export declare const AaveV4Spokes: (networkId: NetworkNumber) => {
34
35
  readonly aave_v4_lombard_btc_spoke: AaveV4SpokeInfo;
35
36
  readonly aave_v4_main_spoke: AaveV4SpokeInfo;
36
37
  readonly aave_v4_usdg_pendle_spoke: AaveV4SpokeInfo;
38
+ readonly aave_v4_usdg_maple_spoke: AaveV4SpokeInfo;
37
39
  };
38
40
  export declare const getAaveV4SpokeTypeInfo: (type: AaveV4SpokesType, network?: NetworkNumber) => AaveV4SpokeInfo;
39
41
  export declare const findAaveV4SpokeByAddress: (networkId: NetworkNumber, address: string) => AaveV4SpokeInfo | undefined;