@defisaver/positions-sdk 2.1.127-midnight-dev → 2.1.127-midnight-2-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 (79) 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 +62 -0
  14. package/cjs/helpers/morphoMidnightHelpers/index.js +156 -1
  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/morphoMidnight/index.js +25 -1
  21. package/cjs/portfolio/index.js +31 -2
  22. package/cjs/savings/summerVaults/options.js +10 -10
  23. package/cjs/staking/staking.js +3 -0
  24. package/cjs/types/aaveV4.d.ts +2 -1
  25. package/cjs/types/aaveV4.js +1 -0
  26. package/cjs/types/claiming.d.ts +10 -0
  27. package/cjs/types/claiming.js +2 -0
  28. package/cjs/types/morphoBlue.d.ts +9 -0
  29. package/cjs/types/morphoMidnight.d.ts +3 -0
  30. package/esm/aaveV3/index.js +7 -1
  31. package/esm/aaveV4/lend.js +3 -3
  32. package/esm/claiming/index.d.ts +2 -1
  33. package/esm/claiming/index.js +2 -1
  34. package/esm/claiming/uniswap.d.ts +5 -0
  35. package/esm/claiming/uniswap.js +67 -0
  36. package/esm/config/contracts.d.ts +22 -0
  37. package/esm/config/contracts.js +8 -0
  38. package/esm/contracts.d.ts +35 -0
  39. package/esm/contracts.js +1 -0
  40. package/esm/curveUsd/index.js +1 -1
  41. package/esm/helpers/morphoBlueHelpers/index.js +1 -0
  42. package/esm/helpers/morphoMidnightHelpers/index.d.ts +62 -0
  43. package/esm/helpers/morphoMidnightHelpers/index.js +149 -0
  44. package/esm/llamaLend/index.js +1 -1
  45. package/esm/markets/aaveV4/index.d.ts +2 -0
  46. package/esm/markets/aaveV4/index.js +12 -0
  47. package/esm/morphoBlue/index.d.ts +8 -6
  48. package/esm/morphoBlue/index.js +62 -39
  49. package/esm/morphoMidnight/index.js +26 -2
  50. package/esm/portfolio/index.js +32 -3
  51. package/esm/savings/summerVaults/options.js +10 -10
  52. package/esm/staking/staking.js +3 -0
  53. package/esm/types/aaveV4.d.ts +2 -1
  54. package/esm/types/aaveV4.js +1 -0
  55. package/esm/types/claiming.d.ts +10 -0
  56. package/esm/types/claiming.js +2 -0
  57. package/esm/types/morphoBlue.d.ts +9 -0
  58. package/esm/types/morphoMidnight.d.ts +3 -0
  59. package/package.json +2 -2
  60. package/src/aaveV3/index.ts +13 -1
  61. package/src/aaveV4/lend.ts +3 -3
  62. package/src/claiming/index.ts +2 -0
  63. package/src/claiming/uniswap.ts +70 -0
  64. package/src/config/contracts.ts +9 -0
  65. package/src/contracts.ts +2 -0
  66. package/src/curveUsd/index.ts +1 -1
  67. package/src/helpers/morphoBlueHelpers/index.ts +1 -0
  68. package/src/helpers/morphoMidnightHelpers/index.ts +206 -0
  69. package/src/llamaLend/index.ts +1 -1
  70. package/src/markets/aaveV4/index.ts +13 -0
  71. package/src/morphoBlue/index.ts +101 -44
  72. package/src/morphoMidnight/index.ts +29 -2
  73. package/src/portfolio/index.ts +32 -3
  74. package/src/savings/summerVaults/options.ts +10 -10
  75. package/src/staking/staking.ts +2 -0
  76. package/src/types/aaveV4.ts +1 -0
  77. package/src/types/claiming.ts +11 -0
  78. package/src/types/morphoBlue.ts +11 -0
  79. package/src/types/morphoMidnight.ts +6 -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,3 +1,4 @@
1
+ import Dec from 'decimal.js';
1
2
  import { MMUsedAssets } from '../../types/common';
2
3
  import { MorphoMidnightAggregatedPositionData, MorphoMidnightAssetsData, MorphoMidnightMarketInfo } from '../../types';
3
4
  /**
@@ -14,3 +15,64 @@ export declare const getMorphoMidnightAggregatedPositionData: ({ usedAssets, ass
14
15
  assetsData: MorphoMidnightAssetsData;
15
16
  marketInfo: MorphoMidnightMarketInfo;
16
17
  }) => MorphoMidnightAggregatedPositionData;
18
+ export interface MorphoMidnightBorrowInfo {
19
+ borrowRate: string;
20
+ debtBase: string;
21
+ debtInterest: string;
22
+ debtTotal: string;
23
+ }
24
+ export interface MorphoMidnightBorrowQuote {
25
+ bestPrice: string;
26
+ worstPrice: string;
27
+ estBorrowRate: string;
28
+ maxRate: string;
29
+ newUnits: string;
30
+ maxUnits: string;
31
+ availableAssets: string;
32
+ availableUnits: string;
33
+ takeableOffers: any[];
34
+ }
35
+ export declare const midnightTimeToMaturityDays: (maturity: number, atSeconds?: number) => number;
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;
54
+ /**
55
+ * Current borrower rate + debt breakdown from the Midnight transactions API. On-chain we can only read the
56
+ * total debt at maturity (`units`); the base-vs-interest split and the effective borrow rate require the
57
+ * fill history. Per fill the rate is (units / seller_assets)^(365 / ttmAtFill) − 1, weighted by base amount.
58
+ * The caller swallows errors — a missing rate must never block position rendering.
59
+ */
60
+ export declare const getMorphoMidnightUserBorrowInfo: (account: string, marketId: string, maturity: number, loanTokenSymbol: string) => Promise<MorphoMidnightBorrowInfo>;
61
+ /**
62
+ * Quote a prospective borrow against the Midnight order book: the estimated rate, the debt units it adds,
63
+ * and the `maxUnits` cap sent on-chain to protect the user if better offers get filled first. `assetsRaw`
64
+ * (and the returned `newUnits`/`maxUnits`) are raw loan-token base units — callers convert to/from human
65
+ * amounts. Throws if the book can't fill the amount (caller handles).
66
+ *
67
+ * Two ways to set the cap:
68
+ * - `maxBorrowRate` — an absolute APY ceiling, honoured **exactly**: the cap price is derived locally via
69
+ * `midnightPriceFromApy`. Prefer this when a user pins a max rate.
70
+ * - otherwise `slippagePercent`, the API's own knob. Note it is a **price**-level slippage, not APY points:
71
+ * near maturity the annualisation factor (365 / ttmDays) multiplies it heavily, so on a 22-day market a
72
+ * slippage of 0.5 permitted an APY ~9pp above the estimate, not 0.5pp. It also saturates at the book's
73
+ * cheapest bid. `maxRate` therefore reports what the cap actually permits, derived from the cap price.
74
+ *
75
+ * A `maxBorrowRate` below `estBorrowRate` yields `maxUnits < newUnits` — the borrow would revert on-chain.
76
+ * Compare the two before submitting and tell the user their ceiling is under the market rate.
77
+ */
78
+ export declare const getMorphoMidnightBorrowQuote: (marketId: string, assetsRaw: string, slippagePercent: Dec.Value, maturity: number, maxBorrowRate?: Dec.Value) => Promise<MorphoMidnightBorrowQuote>;
@@ -1,13 +1,25 @@
1
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
+ };
2
11
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
13
  };
5
14
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getMorphoMidnightAggregatedPositionData = void 0;
15
+ exports.getMorphoMidnightBorrowQuote = exports.getMorphoMidnightUserBorrowInfo = exports.midnightSlippageParam = exports.midnightPriceFromApy = exports.midnightApyFromPrice = exports.midnightTimeToMaturityDays = exports.getMorphoMidnightAggregatedPositionData = void 0;
7
16
  const decimal_js_1 = __importDefault(require("decimal.js"));
17
+ const tokens_1 = require("@defisaver/tokens");
8
18
  const moneymarket_1 = require("../../moneymarket");
9
19
  const staking_1 = require("../../staking");
10
20
  const common_1 = require("../../types/common");
21
+ const constants_1 = require("../../constants");
22
+ const utils_1 = require("../../services/utils");
11
23
  /**
12
24
  * Aggregate a Morpho Midnight position. Midnight markets are multi-collateral, so the borrow limit is
13
25
  * the sum of each collateral's USD value times its own lltv (Aave-v4 style), rather than a single pair.
@@ -66,3 +78,146 @@ const getMorphoMidnightAggregatedPositionData = ({ usedAssets, assetsData, marke
66
78
  return payload;
67
79
  };
68
80
  exports.getMorphoMidnightAggregatedPositionData = getMorphoMidnightAggregatedPositionData;
81
+ // ── Off-chain order-book rate helpers ──────────────────────────────────────────────────────────────
82
+ // notion: https://app.notion.com/p/defisaver/Estimate-borrow-rate-and-slippage-before-execution-3a70be682adc80c783c8c11fdb761dd2
83
+ // the borrow rate is not exposed on-chain (MidnightView only stores total debt at maturity in `units`).
84
+ // derive the rate + interest from Morpho's public keyless Midnight API
85
+ // Quote prices are WAD-scaled
86
+ // loan-per-unit ratios (< 1 for a discounted fixed-term borrow); annualizing them yields the borrow APY.
87
+ const MIDNIGHT_API_BASE = 'https://api.morpho.org/v0/midnight';
88
+ const nowInSeconds = () => Math.floor(Date.now() / 1000);
89
+ // The quote endpoint's `slippage` query param is validated as a string: 0.1–100, at most one decimal
90
+ // place (`0.50` is rejected even though `0.5` passes). See `midnightSlippageParam`.
91
+ const MIDNIGHT_SLIPPAGE_MIN = 0.1;
92
+ const MIDNIGHT_SLIPPAGE_MAX = 100;
93
+ // Days remaining until maturity, optionally measured at a past timestamp (for historical fills).
94
+ const midnightTimeToMaturityDays = (maturity, atSeconds = nowInSeconds()) => new decimal_js_1.default(maturity).sub(atSeconds).div(constants_1.SECONDS_PER_DAY).toNumber();
95
+ exports.midnightTimeToMaturityDays = midnightTimeToMaturityDays;
96
+ // Annualize a fixed-term discount price into an APY percent: (1 / price)^(365 / ttmDays) − 1.
97
+ // `price` is loan-per-unit (assets received / units owed), so 1/price ≥ 1.
98
+ const midnightApyFromPrice = (price, ttmDays) => {
99
+ const p = new decimal_js_1.default(price);
100
+ const ttm = new decimal_js_1.default(ttmDays);
101
+ if (p.lte(0) || ttm.lte(0))
102
+ return '0';
103
+ return new decimal_js_1.default(1).div(p).pow(new decimal_js_1.default(365).div(ttm)).sub(1)
104
+ .mul(100)
105
+ .toString();
106
+ };
107
+ exports.midnightApyFromPrice = midnightApyFromPrice;
108
+ /**
109
+ * Inverse of `midnightApyFromPrice`: the loan-per-unit price a borrow APY implies,
110
+ * price = (1 + rate)^(−ttmDays / 365).
111
+ *
112
+ * This is what turns an absolute rate ceiling into an on-chain `maxUnits` cap (units = assets / price),
113
+ * and equally the principal a unit of borrow power is worth — Midnight debt is recorded at its maturity
114
+ * face value, so borrowing the full limit as principal would overshoot it by the interest.
115
+ */
116
+ const midnightPriceFromApy = (ratePercent, ttmDays) => {
117
+ const rate = new decimal_js_1.default(ratePercent);
118
+ const ttm = new decimal_js_1.default(ttmDays);
119
+ if (rate.lte(0) || ttm.lte(0))
120
+ return '1';
121
+ return new decimal_js_1.default(1).div(new decimal_js_1.default(1).add(rate.div(100)).pow(ttm.div(365))).toString();
122
+ };
123
+ exports.midnightPriceFromApy = midnightPriceFromApy;
124
+ /**
125
+ * Coerce a slippage into what the quote endpoint accepts: 0.1–100 with at most one decimal place. The
126
+ * validation is lexical, so a computed value (`4.15066671050631467`) is rejected outright — without this
127
+ * the request 400s and the quote looks unavailable.
128
+ *
129
+ * Rounded **down**, since a wider slippage is a looser cap than the caller asked for.
130
+ */
131
+ 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();
132
+ exports.midnightSlippageParam = midnightSlippageParam;
133
+ /**
134
+ * Current borrower rate + debt breakdown from the Midnight transactions API. On-chain we can only read the
135
+ * total debt at maturity (`units`); the base-vs-interest split and the effective borrow rate require the
136
+ * fill history. Per fill the rate is (units / seller_assets)^(365 / ttmAtFill) − 1, weighted by base amount.
137
+ * The caller swallows errors — a missing rate must never block position rendering.
138
+ */
139
+ const getMorphoMidnightUserBorrowInfo = (account, marketId, maturity, loanTokenSymbol) => __awaiter(void 0, void 0, void 0, function* () {
140
+ const res = yield fetch(`${MIDNIGHT_API_BASE}/users/${account}/transactions`, { signal: AbortSignal.timeout(utils_1.LONGER_TIMEOUT) });
141
+ const json = yield res.json();
142
+ const borrows = ((json === null || json === void 0 ? void 0 : json.data) || []).filter((t) => { var _a; return t.event_type === 'borrow' && ((_a = t.market_id) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === marketId.toLowerCase(); });
143
+ let sumSeller = new decimal_js_1.default(0); // Σ seller_assets (base), raw
144
+ let sumUnits = new decimal_js_1.default(0); // Σ units (debt at maturity), raw
145
+ let weightedApy = new decimal_js_1.default(0); // Σ seller_assets × APYᵢ
146
+ borrows.forEach((t) => {
147
+ var _a, _b;
148
+ const sellerAssets = new decimal_js_1.default(((_a = t.data) === null || _a === void 0 ? void 0 : _a.seller_assets) || 0);
149
+ const units = new decimal_js_1.default(((_b = t.data) === null || _b === void 0 ? void 0 : _b.units) || 0);
150
+ if (sellerAssets.lte(0) || units.lte(0))
151
+ return;
152
+ const ttmDays = (0, exports.midnightTimeToMaturityDays)(maturity, t.created_at);
153
+ const apy = (0, exports.midnightApyFromPrice)(sellerAssets.div(units), ttmDays); // price = seller_assets / units
154
+ sumSeller = sumSeller.add(sellerAssets);
155
+ sumUnits = sumUnits.add(units);
156
+ weightedApy = weightedApy.add(sellerAssets.mul(apy));
157
+ });
158
+ const borrowRate = sumSeller.lte(0) ? '0' : weightedApy.div(sumSeller).toString();
159
+ const debtBase = (0, tokens_1.assetAmountInEth)(sumSeller.toFixed(0), loanTokenSymbol);
160
+ const debtTotal = (0, tokens_1.assetAmountInEth)(sumUnits.toFixed(0), loanTokenSymbol);
161
+ const debtInterest = decimal_js_1.default.max(new decimal_js_1.default(debtTotal).sub(debtBase), 0).toString();
162
+ return {
163
+ borrowRate, debtBase, debtInterest, debtTotal,
164
+ };
165
+ });
166
+ exports.getMorphoMidnightUserBorrowInfo = getMorphoMidnightUserBorrowInfo;
167
+ // The API says why a quote failed — NOT_FOUND (market matured or not open yet), INSUFFICIENT_LIQUIDITY
168
+ // (book can't fill the size), VALIDATION_ERROR (bad param, with the offending field in `details`).
169
+ // Callers surface this to the user, so keep the reason rather than collapsing everything into one string.
170
+ const midnightQuoteError = (error) => {
171
+ const detail = ((error === null || error === void 0 ? void 0 : error.details) || []).map(({ issue }) => issue).filter(Boolean).join('; ');
172
+ const reason = detail || (error === null || error === void 0 ? void 0 : error.message) || (error === null || error === void 0 ? void 0 : error.code);
173
+ return reason ? `Morpho Midnight quote unavailable: ${reason}` : 'Morpho Midnight quote unavailable';
174
+ };
175
+ /**
176
+ * Quote a prospective borrow against the Midnight order book: the estimated rate, the debt units it adds,
177
+ * and the `maxUnits` cap sent on-chain to protect the user if better offers get filled first. `assetsRaw`
178
+ * (and the returned `newUnits`/`maxUnits`) are raw loan-token base units — callers convert to/from human
179
+ * amounts. Throws if the book can't fill the amount (caller handles).
180
+ *
181
+ * Two ways to set the cap:
182
+ * - `maxBorrowRate` — an absolute APY ceiling, honoured **exactly**: the cap price is derived locally via
183
+ * `midnightPriceFromApy`. Prefer this when a user pins a max rate.
184
+ * - otherwise `slippagePercent`, the API's own knob. Note it is a **price**-level slippage, not APY points:
185
+ * near maturity the annualisation factor (365 / ttmDays) multiplies it heavily, so on a 22-day market a
186
+ * slippage of 0.5 permitted an APY ~9pp above the estimate, not 0.5pp. It also saturates at the book's
187
+ * cheapest bid. `maxRate` therefore reports what the cap actually permits, derived from the cap price.
188
+ *
189
+ * A `maxBorrowRate` below `estBorrowRate` yields `maxUnits < newUnits` — the borrow would revert on-chain.
190
+ * Compare the two before submitting and tell the user their ceiling is under the market rate.
191
+ */
192
+ const getMorphoMidnightBorrowQuote = (marketId, assetsRaw, slippagePercent, maturity, maxBorrowRate) => __awaiter(void 0, void 0, void 0, function* () {
193
+ const url = `${MIDNIGHT_API_BASE}/books/${marketId}/bids/quote?assets=${assetsRaw}&slippage=${(0, exports.midnightSlippageParam)(slippagePercent)}`;
194
+ const res = yield fetch(url, { signal: AbortSignal.timeout(utils_1.LONGER_TIMEOUT) });
195
+ const json = yield res.json();
196
+ const d = json === null || json === void 0 ? void 0 : json.data;
197
+ if (!(d === null || d === void 0 ? void 0 : d.average_best_price))
198
+ throw new Error(midnightQuoteError(json === null || json === void 0 ? void 0 : json.error));
199
+ const bestPrice = new decimal_js_1.default(d.average_best_price).div(constants_1.WAD).toString();
200
+ const worstPrice = new decimal_js_1.default(d.average_worst_price || 0).div(constants_1.WAD).toString();
201
+ const ttmDays = (0, exports.midnightTimeToMaturityDays)(maturity);
202
+ const estBorrowRate = (0, exports.midnightApyFromPrice)(bestPrice, ttmDays);
203
+ // Price the cap sits at, and the rate that price represents — one derivation, so `maxRate` and
204
+ // `maxUnits` can never disagree about what the user is protected at.
205
+ const capPrice = maxBorrowRate !== undefined && new decimal_js_1.default(maxBorrowRate).gt(0)
206
+ ? (0, exports.midnightPriceFromApy)(maxBorrowRate, ttmDays)
207
+ : worstPrice;
208
+ const maxRate = (0, exports.midnightApyFromPrice)(capPrice, ttmDays);
209
+ const newUnits = new decimal_js_1.default(bestPrice).lte(0) ? '0' : new decimal_js_1.default(assetsRaw).div(bestPrice).toFixed(0);
210
+ const maxUnits = new decimal_js_1.default(capPrice).lte(0) ? '0' : new decimal_js_1.default(assetsRaw).div(capPrice).toFixed(0);
211
+ return {
212
+ bestPrice,
213
+ worstPrice,
214
+ estBorrowRate,
215
+ maxRate,
216
+ newUnits,
217
+ maxUnits,
218
+ availableAssets: d.available_assets || '0',
219
+ availableUnits: d.available_units || '0',
220
+ takeableOffers: d.takeable_offers || [],
221
+ };
222
+ });
223
+ exports.getMorphoMidnightBorrowQuote = getMorphoMidnightBorrowQuote;
@@ -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;