@defisaver/positions-sdk 2.1.141 → 2.1.142-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 (50) hide show
  1. package/cjs/aaveV3/merkl.js +9 -5
  2. package/cjs/aaveV4/merkl.js +1 -1
  3. package/cjs/compoundV3/index.d.ts +1 -0
  4. package/cjs/compoundV3/index.js +8 -2
  5. package/cjs/compoundV3/merkl.d.ts +16 -0
  6. package/cjs/compoundV3/merkl.js +79 -0
  7. package/cjs/fluid/index.d.ts +1 -0
  8. package/cjs/fluid/index.js +28 -8
  9. package/cjs/fluid/merkl.d.ts +29 -0
  10. package/cjs/fluid/merkl.js +97 -0
  11. package/cjs/morphoBlue/index.d.ts +1 -0
  12. package/cjs/morphoBlue/index.js +16 -10
  13. package/cjs/morphoBlue/merkl.d.ts +33 -0
  14. package/cjs/morphoBlue/merkl.js +101 -0
  15. package/cjs/staking/eligibility.d.ts +4 -0
  16. package/cjs/staking/eligibility.js +11 -1
  17. package/cjs/types/common.d.ts +2 -1
  18. package/cjs/types/common.js +1 -0
  19. package/cjs/types/merkl.d.ts +8 -0
  20. package/esm/aaveV3/merkl.js +9 -5
  21. package/esm/aaveV4/merkl.js +1 -1
  22. package/esm/compoundV3/index.d.ts +1 -0
  23. package/esm/compoundV3/index.js +5 -1
  24. package/esm/compoundV3/merkl.d.ts +16 -0
  25. package/esm/compoundV3/merkl.js +74 -0
  26. package/esm/fluid/index.d.ts +1 -0
  27. package/esm/fluid/index.js +23 -7
  28. package/esm/fluid/merkl.d.ts +29 -0
  29. package/esm/fluid/merkl.js +91 -0
  30. package/esm/morphoBlue/index.d.ts +1 -0
  31. package/esm/morphoBlue/index.js +11 -9
  32. package/esm/morphoBlue/merkl.d.ts +33 -0
  33. package/esm/morphoBlue/merkl.js +95 -0
  34. package/esm/staking/eligibility.d.ts +4 -0
  35. package/esm/staking/eligibility.js +9 -0
  36. package/esm/types/common.d.ts +2 -1
  37. package/esm/types/common.js +1 -0
  38. package/esm/types/merkl.d.ts +8 -0
  39. package/package.json +1 -1
  40. package/src/aaveV3/merkl.ts +5 -2
  41. package/src/aaveV4/merkl.ts +1 -1
  42. package/src/compoundV3/index.ts +6 -1
  43. package/src/compoundV3/merkl.ts +77 -0
  44. package/src/fluid/index.ts +29 -7
  45. package/src/fluid/merkl.ts +97 -0
  46. package/src/morphoBlue/index.ts +24 -9
  47. package/src/morphoBlue/merkl.ts +120 -0
  48. package/src/staking/eligibility.ts +10 -0
  49. package/src/types/common.ts +1 -0
  50. package/src/types/merkl.ts +6 -0
@@ -40,7 +40,9 @@ const formatAaveAsset = (_symbol) => {
40
40
  exports.formatAaveAsset = formatAaveAsset;
41
41
  const getMerkleCampaigns = (chainId) => __awaiter(void 0, void 0, void 0, function* () {
42
42
  try {
43
- const res = yield fetch('https://fe.defisaver.com/api/merkl/opportunities?mainProtocolId=aave', {
43
+ // status/items narrow the query because Merkl paginates at 20 items by default — an
44
+ // unfiltered query silently drops live campaigns once the protocol has enough opportunities
45
+ const res = yield fetch('https://fe.defisaver.com/api/merkl/opportunities?mainProtocolId=aave&status=LIVE&items=100', {
44
46
  signal: AbortSignal.timeout(utils_1.LONGER_TIMEOUT),
45
47
  });
46
48
  if (!res.ok)
@@ -50,11 +52,13 @@ const getMerkleCampaigns = (chainId) => __awaiter(void 0, void 0, void 0, functi
50
52
  .filter((o) => o.chainId === chainId)
51
53
  .filter((o) => o.status === types_1.OpportunityStatus.LIVE);
52
54
  return relevantOpportunities.reduce((acc, opportunity) => {
53
- var _a, _b;
54
- const rewardToken = opportunity.rewardsRecord.breakdowns[0].token;
55
+ var _a, _b, _c, _d, _e;
56
+ const rewardToken = (_c = (_b = (_a = opportunity.rewardsRecord) === null || _a === void 0 ? void 0 : _a.breakdowns) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.token;
57
+ if (!rewardToken)
58
+ return acc;
55
59
  const description = `Eligible for ${(0, exports.formatAaveAsset)(rewardToken.symbol)} rewards through Merkl. ${opportunity.description ? `\n${opportunity.description}` : ''}`;
56
60
  if (opportunity.action === types_1.OpportunityAction.LEND && opportunity.explorerAddress) {
57
- const supplyAToken = (_a = opportunity.explorerAddress) === null || _a === void 0 ? void 0 : _a.toLowerCase();
61
+ const supplyAToken = (_d = opportunity.explorerAddress) === null || _d === void 0 ? void 0 : _d.toLowerCase();
58
62
  if (!acc[supplyAToken])
59
63
  acc[supplyAToken] = {};
60
64
  acc[supplyAToken].supply = {
@@ -66,7 +70,7 @@ const getMerkleCampaigns = (chainId) => __awaiter(void 0, void 0, void 0, functi
66
70
  };
67
71
  }
68
72
  if (opportunity.action === types_1.OpportunityAction.BORROW && opportunity.explorerAddress) {
69
- const borrowAToken = (_b = opportunity.explorerAddress) === null || _b === void 0 ? void 0 : _b.toLowerCase();
73
+ const borrowAToken = (_e = opportunity.explorerAddress) === null || _e === void 0 ? void 0 : _e.toLowerCase();
70
74
  if (!acc[borrowAToken])
71
75
  acc[borrowAToken] = {};
72
76
  acc[borrowAToken].borrow = {
@@ -67,7 +67,7 @@ const buildAaveV4MerklRewardMap = (opportunities, chainId) => {
67
67
  exports.buildAaveV4MerklRewardMap = buildAaveV4MerklRewardMap;
68
68
  const getAaveV4MerkleCampaigns = (chainId) => __awaiter(void 0, void 0, void 0, function* () {
69
69
  try {
70
- const res = yield fetch('https://fe.defisaver.com/api/merkl/opportunities?mainProtocolId=aave&type=AAVE_V4_HUB_SUPPLY,AAVE_V4_HUB_BORROW,AAVE_V4_SPOKE_SUPPLY,AAVE_V4_SPOKE_BORROW', {
70
+ const res = yield fetch('https://fe.defisaver.com/api/merkl/opportunities?mainProtocolId=aave&type=AAVE_V4_HUB_SUPPLY,AAVE_V4_HUB_BORROW,AAVE_V4_SPOKE_SUPPLY,AAVE_V4_SPOKE_BORROW&status=LIVE&items=100', {
71
71
  signal: AbortSignal.timeout(utils_1.LONGER_TIMEOUT),
72
72
  });
73
73
  if (!res.ok)
@@ -1,6 +1,7 @@
1
1
  import { Client } from 'viem';
2
2
  import { CompoundMarketData, CompoundV3AssetsData, CompoundV3MarketsData, CompoundV3PositionData } from '../types';
3
3
  import { Blockish, EthAddress, EthereumProvider, NetworkNumber, PositionBalances } from '../types/common';
4
+ export { getCompoundV3MerklOpportunities, attachCompoundV3MerklIncentives } from './merkl';
4
5
  export declare const _getCompoundV3MarketsData: (provider: Client, network: NetworkNumber, selectedMarket: CompoundMarketData, defaultProvider: Client) => Promise<CompoundV3MarketsData>;
5
6
  export declare const getCompoundV3MarketsData: (provider: EthereumProvider, network: NetworkNumber, selectedMarket: CompoundMarketData, defaultProvider: EthereumProvider) => Promise<CompoundV3MarketsData>;
6
7
  export declare const EMPTY_COMPOUND_V3_DATA: {
@@ -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.getCompoundV3FullPositionData = exports.getCompoundV3AccountData = exports._getCompoundV3AccountData = exports.getCompoundV3AccountBalances = exports._getCompoundV3AccountBalances = exports.EMPTY_USED_ASSET = exports.EMPTY_COMPOUND_V3_DATA = exports.getCompoundV3MarketsData = exports._getCompoundV3MarketsData = void 0;
15
+ exports.getCompoundV3FullPositionData = exports.getCompoundV3AccountData = exports._getCompoundV3AccountData = exports.getCompoundV3AccountBalances = exports._getCompoundV3AccountBalances = exports.EMPTY_USED_ASSET = exports.EMPTY_COMPOUND_V3_DATA = exports.getCompoundV3MarketsData = exports._getCompoundV3MarketsData = exports.attachCompoundV3MerklIncentives = exports.getCompoundV3MerklOpportunities = void 0;
16
16
  const decimal_js_1 = __importDefault(require("decimal.js"));
17
17
  const tokens_1 = require("@defisaver/tokens");
18
18
  const contracts_1 = require("../contracts");
@@ -25,6 +25,10 @@ const compoundHelpers_1 = require("../helpers/compoundHelpers");
25
25
  const compound_1 = require("../markets/compound");
26
26
  const priceService_1 = require("../services/priceService");
27
27
  const viem_1 = require("../services/viem");
28
+ const merkl_1 = require("./merkl");
29
+ var merkl_2 = require("./merkl");
30
+ Object.defineProperty(exports, "getCompoundV3MerklOpportunities", { enumerable: true, get: function () { return merkl_2.getCompoundV3MerklOpportunities; } });
31
+ Object.defineProperty(exports, "attachCompoundV3MerklIncentives", { enumerable: true, get: function () { return merkl_2.attachCompoundV3MerklIncentives; } });
28
32
  const getSupportedAssetsAddressesForMarket = (selectedMarket, network) => selectedMarket.collAssets.map(asset => (0, tokens_1.getAssetInfo)((0, utils_1.ethToWeth)(asset), network)).map(addr => addr.address.toLowerCase());
29
33
  const getBaseAssetPriceFunction = (asset) => {
30
34
  switch (asset) {
@@ -38,12 +42,13 @@ const getBaseAssetPriceFunction = (asset) => {
38
42
  };
39
43
  const _getCompoundV3MarketsData = (provider, network, selectedMarket, defaultProvider) => __awaiter(void 0, void 0, void 0, function* () {
40
44
  const contract = (0, contracts_1.CompV3ViewContractViem)(provider, network);
41
- const [baseAssetPrice, compPrice, baseTokenInfo, collInfos, govInfo] = yield Promise.all([
45
+ const [baseAssetPrice, compPrice, baseTokenInfo, collInfos, govInfo, merklOpportunities] = yield Promise.all([
42
46
  getBaseAssetPriceFunction(selectedMarket.baseAsset)(defaultProvider),
43
47
  (0, priceService_1.getCompPrice)(defaultProvider),
44
48
  contract.read.getFullBaseTokenInfo([selectedMarket.baseMarketAddress]),
45
49
  contract.read.getFullCollInfos([selectedMarket.baseMarketAddress]),
46
50
  contract.read.getGovernanceInfoFull([selectedMarket.baseMarketAddress]),
51
+ (0, merkl_1.getCompoundV3MerklOpportunities)(),
47
52
  ]);
48
53
  const { isSupplyPaused, isWithdrawPaused } = govInfo;
49
54
  const supportedAssetsAddresses = getSupportedAssetsAddressesForMarket(selectedMarket, network);
@@ -63,6 +68,7 @@ const _getCompoundV3MarketsData = (provider, network, selectedMarket, defaultPro
63
68
  const base = (0, compoundHelpers_1.formatBaseData)(baseTokenInfo, network, baseAssetPrice, isSupplyPaused, isWithdrawPaused);
64
69
  const payload = {};
65
70
  const baseObj = Object.assign(Object.assign({}, base), (yield (0, compoundHelpers_1.getIncentiveApys)(base, compPrice)));
71
+ (0, merkl_1.attachCompoundV3MerklIncentives)(baseObj, colls, selectedMarket.baseMarketAddress, network, merklOpportunities);
66
72
  const allAssets = [baseObj, ...colls];
67
73
  allAssets
68
74
  .sort((a, b) => {
@@ -0,0 +1,16 @@
1
+ import { CompoundV3AssetData, MerklOpportunity, NetworkNumber } from '../types';
2
+ /**
3
+ * Merkl tags Compound V3 reward campaigns with COMPOUND_V3_* opportunity types (e.g.
4
+ * COMPOUND_V3_BORROW_FROM_COLLATERAL) and identifies the comet via `explorerAddress`. Campaign
5
+ * identifiers are opaque hashes, passed through as `eligibilityId` so conditional campaigns —
6
+ * like borrow-from-collateral ones, whose reward is min(collateral * LTV, borrow amount) — can
7
+ * be gated and sized by a curated check in EligibilityMapping; unknown ids apply
8
+ * unconditionally, mirroring Aave V3.
9
+ */
10
+ export declare const getCompoundV3MerklOpportunities: () => Promise<MerklOpportunity[]>;
11
+ /**
12
+ * Appends the comet's Merkl campaigns to its assets' incentive arrays (mutating them, like the
13
+ * staking incentives are attached). BORROW campaigns land on the base asset — the only borrowable
14
+ * one — while LEND campaigns land on the asset the campaign's first token resolves to.
15
+ */
16
+ export declare const attachCompoundV3MerklIncentives: (baseAsset: CompoundV3AssetData, collAssets: CompoundV3AssetData[], baseMarketAddress: string, chainId: NetworkNumber, opportunities: MerklOpportunity[]) => void;
@@ -0,0 +1,79 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.attachCompoundV3MerklIncentives = exports.getCompoundV3MerklOpportunities = void 0;
13
+ const tokens_1 = require("@defisaver/tokens");
14
+ const moneymarket_1 = require("../moneymarket");
15
+ const utils_1 = require("../services/utils");
16
+ const types_1 = require("../types");
17
+ /**
18
+ * Merkl tags Compound V3 reward campaigns with COMPOUND_V3_* opportunity types (e.g.
19
+ * COMPOUND_V3_BORROW_FROM_COLLATERAL) and identifies the comet via `explorerAddress`. Campaign
20
+ * identifiers are opaque hashes, passed through as `eligibilityId` so conditional campaigns —
21
+ * like borrow-from-collateral ones, whose reward is min(collateral * LTV, borrow amount) — can
22
+ * be gated and sized by a curated check in EligibilityMapping; unknown ids apply
23
+ * unconditionally, mirroring Aave V3.
24
+ */
25
+ const getCompoundV3MerklOpportunities = () => __awaiter(void 0, void 0, void 0, function* () {
26
+ try {
27
+ const res = yield fetch('https://fe.defisaver.com/api/merkl/opportunities?mainProtocolId=compound-v3&status=LIVE&items=100', {
28
+ signal: AbortSignal.timeout(utils_1.LONGER_TIMEOUT),
29
+ });
30
+ if (!res.ok)
31
+ throw new Error('Failed to fetch Compound V3 Merkl campaigns');
32
+ const data = yield res.json();
33
+ return Array.isArray(data) ? data : [];
34
+ }
35
+ catch (e) {
36
+ console.error('Failed to fetch Compound V3 Merkl campaigns', e);
37
+ return [];
38
+ }
39
+ });
40
+ exports.getCompoundV3MerklOpportunities = getCompoundV3MerklOpportunities;
41
+ const buildMerklIncentive = (opportunity) => {
42
+ var _a, _b, _c, _d, _e, _f;
43
+ const token = ((_d = (_c = (_b = (_a = opportunity.rewardsRecord) === null || _a === void 0 ? void 0 : _a.breakdowns) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.token) === null || _d === void 0 ? void 0 : _d.symbol) || ((_f = (_e = opportunity.tokens) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.symbol) || '';
44
+ return {
45
+ apy: (0, moneymarket_1.aprToApy)(opportunity.apr),
46
+ token,
47
+ incentiveKind: types_1.IncentiveKind.Reward,
48
+ description: `Eligible for ${token} rewards through Merkl.${opportunity.description ? `\n${opportunity.description}` : ''}`,
49
+ eligibilityId: opportunity.identifier,
50
+ };
51
+ };
52
+ /**
53
+ * Appends the comet's Merkl campaigns to its assets' incentive arrays (mutating them, like the
54
+ * staking incentives are attached). BORROW campaigns land on the base asset — the only borrowable
55
+ * one — while LEND campaigns land on the asset the campaign's first token resolves to.
56
+ */
57
+ const attachCompoundV3MerklIncentives = (baseAsset, collAssets, baseMarketAddress, chainId, opportunities) => {
58
+ opportunities
59
+ .filter((o) => o.chainId === chainId
60
+ && o.status === types_1.OpportunityStatus.LIVE
61
+ && typeof o.type === 'string' && o.type.startsWith('COMPOUND_V3')
62
+ && o.explorerAddress && (0, utils_1.compareAddresses)(o.explorerAddress, baseMarketAddress))
63
+ .forEach((o) => {
64
+ var _a, _b;
65
+ const incentive = buildMerklIncentive(o);
66
+ if (o.action === types_1.OpportunityAction.BORROW) {
67
+ baseAsset.borrowIncentives.push(incentive);
68
+ }
69
+ else if (o.action === types_1.OpportunityAction.LEND) {
70
+ const campaignTokenAddress = (_b = (_a = o.tokens) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.address;
71
+ if (!campaignTokenAddress)
72
+ return;
73
+ const campaignSymbol = (0, utils_1.wethToEth)((0, tokens_1.getAssetInfoByAddress)(campaignTokenAddress, chainId).symbol);
74
+ const target = [baseAsset, ...collAssets].find((asset) => asset.symbol === campaignSymbol);
75
+ target === null || target === void 0 ? void 0 : target.supplyIncentives.push(incentive);
76
+ }
77
+ });
78
+ };
79
+ exports.attachCompoundV3MerklIncentives = attachCompoundV3MerklIncentives;
@@ -1,6 +1,7 @@
1
1
  import { Client, PublicClient } from 'viem';
2
2
  import { EthAddress, EthereumProvider, NetworkNumber } from '../types/common';
3
3
  import { FluidAssetsData, FluidMarketData, FluidMarketInfo, FluidUsedAssets, FluidVaultData, InnerFluidMarketData } from '../types';
4
+ export { FLUID_MERKL_OPPORTUNITY_TYPES, buildFluidMerklRewardMap, getFluidMerklCampaigns, attachFluidMerklIncentives, } from './merkl';
4
5
  export declare const EMPTY_USED_ASSET: {
5
6
  isSupplied: boolean;
6
7
  isBorrowed: boolean;
@@ -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._getUserPositionsPortfolio = exports.getUserPositions = exports._getUserPositions = exports.getAllUserEarnPositionsWithFTokens = exports._getAllUserEarnPositionsWithFTokens = exports.getFluidDepositData = exports._getFluidDepositData = exports.getFluidTokenData = exports._getFluidTokenData = exports.getAllFluidMarketDataChunked = exports._getAllFluidMarketDataChunked = exports.getFluidPositionWithMarket = exports._getFluidPositionWithMarket = exports.getFluidPosition = exports._getFluidPosition = exports.getFluidVaultIdsForUser = exports._getFluidVaultIdsForUser = exports.getFluidMarketData = exports._getFluidMarketData = exports.EMPTY_FLUID_DATA = exports.EMPTY_USED_ASSET = void 0;
15
+ exports._getUserPositionsPortfolio = exports.getUserPositions = exports._getUserPositions = exports.getAllUserEarnPositionsWithFTokens = exports._getAllUserEarnPositionsWithFTokens = exports.getFluidDepositData = exports._getFluidDepositData = exports.getFluidTokenData = exports._getFluidTokenData = exports.getAllFluidMarketDataChunked = exports._getAllFluidMarketDataChunked = exports.getFluidPositionWithMarket = exports._getFluidPositionWithMarket = exports.getFluidPosition = exports._getFluidPosition = exports.getFluidVaultIdsForUser = exports._getFluidVaultIdsForUser = exports.getFluidMarketData = exports._getFluidMarketData = exports.EMPTY_FLUID_DATA = exports.EMPTY_USED_ASSET = exports.attachFluidMerklIncentives = exports.getFluidMerklCampaigns = exports.buildFluidMerklRewardMap = exports.FLUID_MERKL_OPPORTUNITY_TYPES = void 0;
16
16
  const decimal_js_1 = __importDefault(require("decimal.js"));
17
17
  const tokens_1 = require("@defisaver/tokens");
18
18
  const common_1 = require("../types/common");
@@ -25,6 +25,12 @@ const constants_1 = require("../constants");
25
25
  const priceService_1 = require("../services/priceService");
26
26
  const staking_1 = require("../staking");
27
27
  const viem_1 = require("../services/viem");
28
+ const merkl_1 = require("./merkl");
29
+ var merkl_2 = require("./merkl");
30
+ Object.defineProperty(exports, "FLUID_MERKL_OPPORTUNITY_TYPES", { enumerable: true, get: function () { return merkl_2.FLUID_MERKL_OPPORTUNITY_TYPES; } });
31
+ Object.defineProperty(exports, "buildFluidMerklRewardMap", { enumerable: true, get: function () { return merkl_2.buildFluidMerklRewardMap; } });
32
+ Object.defineProperty(exports, "getFluidMerklCampaigns", { enumerable: true, get: function () { return merkl_2.getFluidMerklCampaigns; } });
33
+ Object.defineProperty(exports, "attachFluidMerklIncentives", { enumerable: true, get: function () { return merkl_2.attachFluidMerklIncentives; } });
28
34
  exports.EMPTY_USED_ASSET = {
29
35
  isSupplied: false,
30
36
  isBorrowed: false,
@@ -1106,8 +1112,12 @@ const parseUserData = (userPositionData, vaultData) => {
1106
1112
  };
1107
1113
  const _getFluidMarketData = (provider, network, market) => __awaiter(void 0, void 0, void 0, function* () {
1108
1114
  const view = (0, contracts_1.FluidViewContractViem)(provider, network);
1109
- const data = yield view.read.getVaultData([market.marketAddress]);
1110
- return parseMarketData(provider, data, network);
1115
+ const [data, merklCampaigns] = yield Promise.all([
1116
+ view.read.getVaultData([market.marketAddress]),
1117
+ (0, merkl_1.getFluidMerklCampaigns)(network),
1118
+ ]);
1119
+ const marketData = yield parseMarketData(provider, data, network);
1120
+ return marketData ? (0, merkl_1.attachFluidMerklIncentives)(marketData, merklCampaigns) : marketData;
1111
1121
  });
1112
1122
  exports._getFluidMarketData = _getFluidMarketData;
1113
1123
  const getFluidMarketData = (provider, network, market) => __awaiter(void 0, void 0, void 0, function* () { return (0, exports._getFluidMarketData)((0, viem_1.getViemProvider)(provider, network), network, market); });
@@ -1130,11 +1140,15 @@ const getFluidPosition = (provider, network, vaultId, extractedState) => __await
1130
1140
  exports.getFluidPosition = getFluidPosition;
1131
1141
  const _getFluidPositionWithMarket = (provider, network, vaultId) => __awaiter(void 0, void 0, void 0, function* () {
1132
1142
  const view = (0, contracts_1.FluidViewContractViem)(provider, network);
1133
- const data = yield view.read.getPositionByNftId([BigInt(vaultId)]);
1134
- const marketData = yield parseMarketData(provider, data[1], network);
1135
- if (!marketData) {
1143
+ const [data, merklCampaigns] = yield Promise.all([
1144
+ view.read.getPositionByNftId([BigInt(vaultId)]),
1145
+ (0, merkl_1.getFluidMerklCampaigns)(network),
1146
+ ]);
1147
+ const parsedMarketData = yield parseMarketData(provider, data[1], network);
1148
+ if (!parsedMarketData) {
1136
1149
  return;
1137
1150
  }
1151
+ const marketData = (0, merkl_1.attachFluidMerklIncentives)(parsedMarketData, merklCampaigns);
1138
1152
  const userData = parseUserData(data[0], marketData);
1139
1153
  return {
1140
1154
  userData,
@@ -1147,8 +1161,14 @@ exports.getFluidPositionWithMarket = getFluidPositionWithMarket;
1147
1161
  const _getAllFluidMarketDataChunked = (network, provider) => __awaiter(void 0, void 0, void 0, function* () {
1148
1162
  const versions = (0, markets_1.getFluidVersionsDataForNetwork)(network);
1149
1163
  const view = (0, contracts_1.FluidViewContractViem)(provider, network);
1150
- const data = yield Promise.all(versions.map((version) => view.read.getVaultData([version.marketAddress])));
1151
- return Promise.all(data.map((item, i) => __awaiter(void 0, void 0, void 0, function* () { return parseMarketData(provider, item, network); })));
1164
+ const [data, merklCampaigns] = yield Promise.all([
1165
+ Promise.all(versions.map((version) => view.read.getVaultData([version.marketAddress]))),
1166
+ (0, merkl_1.getFluidMerklCampaigns)(network),
1167
+ ]);
1168
+ return Promise.all(data.map((item) => __awaiter(void 0, void 0, void 0, function* () {
1169
+ const marketData = yield parseMarketData(provider, item, network);
1170
+ return marketData ? (0, merkl_1.attachFluidMerklIncentives)(marketData, merklCampaigns) : marketData;
1171
+ })));
1152
1172
  });
1153
1173
  exports._getAllFluidMarketDataChunked = _getAllFluidMarketDataChunked;
1154
1174
  const getAllFluidMarketDataChunked = (network, provider) => __awaiter(void 0, void 0, void 0, function* () { return (0, exports._getAllFluidMarketDataChunked)(network, (0, viem_1.getViemProvider)(provider, network, { batch: { multicall: true } })); });
@@ -0,0 +1,29 @@
1
+ import { FluidMarketData, FluidMerklRewardMap, MerklOpportunity, NetworkNumber } from '../types';
2
+ /**
3
+ * Merkl tags Fluid vault-scoped reward campaigns via the opportunity `type` field:
4
+ * - FLUIDVAULT_COLLATERAL → reward for supplying collateral to the vault
5
+ * - FLUIDVAULT_BORROW → reward for borrowing from the vault
6
+ * (ERC20LOGPROCESSOR campaigns target fToken earn positions rather than vaults, so they don't
7
+ * belong on vault market data.)
8
+ *
9
+ * A campaign identifies its vault via `identifier` — the vault address. Conditional campaigns
10
+ * append a marker to it (e.g. `0x5668…eeaBORROW_BL`, excluding holders who borrow the reward
11
+ * asset elsewhere); those are still attached, with the full identifier passed through as
12
+ * `eligibilityId` so a curated check in EligibilityMapping can gate them in net APY — unknown
13
+ * ids apply unconditionally, mirroring Aave V3. Whitelist-gated campaigns only accrue to
14
+ * whitelisted addresses, so they are skipped rather than advertised to every user.
15
+ */
16
+ export declare const FLUID_MERKL_OPPORTUNITY_TYPES: readonly ["FLUIDVAULT_COLLATERAL", "FLUIDVAULT_BORROW"];
17
+ export declare const buildFluidMerklRewardMap: (opportunities: MerklOpportunity[], chainId: NetworkNumber) => FluidMerklRewardMap;
18
+ /**
19
+ * Fetches live vault-scoped Fluid campaigns for the chain, keyed by vault address. Never throws —
20
+ * on any failure it returns an empty map, so Merkl being down can't break market data. The query
21
+ * is narrowed by `type=` and capped at `items=100` because Merkl paginates at 20 items by default.
22
+ */
23
+ export declare const getFluidMerklCampaigns: (chainId: NetworkNumber) => Promise<FluidMerklRewardMap>;
24
+ /**
25
+ * Appends the vault's Merkl campaigns to its assets' incentive arrays — supply rewards on every
26
+ * suppliable asset and borrow rewards on every borrowable one. Smart collateral/debt vaults hold
27
+ * the position across both pair tokens, so the pro-rata reward APY applies to each side's value.
28
+ */
29
+ export declare const attachFluidMerklIncentives: (marketData: FluidMarketData, campaigns: FluidMerklRewardMap) => FluidMarketData;
@@ -0,0 +1,97 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.attachFluidMerklIncentives = exports.getFluidMerklCampaigns = exports.buildFluidMerklRewardMap = exports.FLUID_MERKL_OPPORTUNITY_TYPES = void 0;
13
+ const moneymarket_1 = require("../moneymarket");
14
+ const utils_1 = require("../services/utils");
15
+ const types_1 = require("../types");
16
+ /**
17
+ * Merkl tags Fluid vault-scoped reward campaigns via the opportunity `type` field:
18
+ * - FLUIDVAULT_COLLATERAL → reward for supplying collateral to the vault
19
+ * - FLUIDVAULT_BORROW → reward for borrowing from the vault
20
+ * (ERC20LOGPROCESSOR campaigns target fToken earn positions rather than vaults, so they don't
21
+ * belong on vault market data.)
22
+ *
23
+ * A campaign identifies its vault via `identifier` — the vault address. Conditional campaigns
24
+ * append a marker to it (e.g. `0x5668…eeaBORROW_BL`, excluding holders who borrow the reward
25
+ * asset elsewhere); those are still attached, with the full identifier passed through as
26
+ * `eligibilityId` so a curated check in EligibilityMapping can gate them in net APY — unknown
27
+ * ids apply unconditionally, mirroring Aave V3. Whitelist-gated campaigns only accrue to
28
+ * whitelisted addresses, so they are skipped rather than advertised to every user.
29
+ */
30
+ exports.FLUID_MERKL_OPPORTUNITY_TYPES = ['FLUIDVAULT_COLLATERAL', 'FLUIDVAULT_BORROW'];
31
+ // '0x' + 20-byte vault address; conditional campaigns append a marker after it
32
+ const VAULT_ADDRESS_LENGTH = 42;
33
+ const buildMerklIncentive = (opportunity) => {
34
+ var _a, _b, _c, _d, _e, _f;
35
+ const token = ((_d = (_c = (_b = (_a = opportunity.rewardsRecord) === null || _a === void 0 ? void 0 : _a.breakdowns) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.token) === null || _d === void 0 ? void 0 : _d.symbol) || ((_f = (_e = opportunity.tokens) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.symbol) || '';
36
+ return {
37
+ apy: (0, moneymarket_1.aprToApy)(opportunity.apr),
38
+ token,
39
+ incentiveKind: types_1.IncentiveKind.Reward,
40
+ description: `Eligible for ${token} rewards through Merkl.${opportunity.description ? `\n${opportunity.description}` : ''}`,
41
+ eligibilityId: opportunity.identifier,
42
+ };
43
+ };
44
+ const buildFluidMerklRewardMap = (opportunities, chainId) => {
45
+ const result = {};
46
+ opportunities
47
+ .filter((o) => o.chainId === chainId)
48
+ .filter((o) => o.status === types_1.OpportunityStatus.LIVE)
49
+ .filter((o) => exports.FLUID_MERKL_OPPORTUNITY_TYPES.includes(o.type))
50
+ .filter((o) => { var _a; return !((_a = o.identifier) === null || _a === void 0 ? void 0 : _a.includes('WHITELIST')); })
51
+ .forEach((o) => {
52
+ var _a;
53
+ const vaultAddress = (_a = o.identifier) === null || _a === void 0 ? void 0 : _a.slice(0, VAULT_ADDRESS_LENGTH).toLowerCase();
54
+ if (!vaultAddress || vaultAddress.length !== VAULT_ADDRESS_LENGTH)
55
+ return;
56
+ if (!result[vaultAddress])
57
+ result[vaultAddress] = { supply: [], borrow: [] };
58
+ result[vaultAddress][o.type === 'FLUIDVAULT_BORROW' ? 'borrow' : 'supply'].push(buildMerklIncentive(o));
59
+ });
60
+ return result;
61
+ };
62
+ exports.buildFluidMerklRewardMap = buildFluidMerklRewardMap;
63
+ /**
64
+ * Fetches live vault-scoped Fluid campaigns for the chain, keyed by vault address. Never throws —
65
+ * on any failure it returns an empty map, so Merkl being down can't break market data. The query
66
+ * is narrowed by `type=` and capped at `items=100` because Merkl paginates at 20 items by default.
67
+ */
68
+ const getFluidMerklCampaigns = (chainId) => __awaiter(void 0, void 0, void 0, function* () {
69
+ try {
70
+ const res = yield fetch(`https://fe.defisaver.com/api/merkl/opportunities?mainProtocolId=fluid&type=${exports.FLUID_MERKL_OPPORTUNITY_TYPES.join(',')}&status=LIVE&items=100`, {
71
+ signal: AbortSignal.timeout(utils_1.LONGER_TIMEOUT),
72
+ });
73
+ if (!res.ok)
74
+ throw new Error('Failed to fetch Fluid Merkl campaigns');
75
+ const opportunities = yield res.json();
76
+ return (0, exports.buildFluidMerklRewardMap)(Array.isArray(opportunities) ? opportunities : [], chainId);
77
+ }
78
+ catch (e) {
79
+ console.error('Failed to fetch Fluid Merkl campaigns', e);
80
+ return {};
81
+ }
82
+ });
83
+ exports.getFluidMerklCampaigns = getFluidMerklCampaigns;
84
+ /**
85
+ * Appends the vault's Merkl campaigns to its assets' incentive arrays — supply rewards on every
86
+ * suppliable asset and borrow rewards on every borrowable one. Smart collateral/debt vaults hold
87
+ * the position across both pair tokens, so the pro-rata reward APY applies to each side's value.
88
+ */
89
+ const attachFluidMerklIncentives = (marketData, campaigns) => {
90
+ var _a;
91
+ const vaultCampaigns = campaigns[(_a = marketData.marketData.marketAddress) === null || _a === void 0 ? void 0 : _a.toLowerCase()];
92
+ if (!vaultCampaigns || (!vaultCampaigns.supply.length && !vaultCampaigns.borrow.length))
93
+ return marketData;
94
+ const assetsData = Object.fromEntries(Object.entries(marketData.assetsData).map(([symbol, asset]) => [symbol, Object.assign(Object.assign({}, asset), { supplyIncentives: asset.canBeSupplied ? [...asset.supplyIncentives, ...vaultCampaigns.supply] : asset.supplyIncentives, borrowIncentives: asset.canBeBorrowed ? [...asset.borrowIncentives, ...vaultCampaigns.borrow] : asset.borrowIncentives })]));
95
+ return Object.assign(Object.assign({}, marketData), { assetsData });
96
+ };
97
+ exports.attachFluidMerklIncentives = attachFluidMerklIncentives;
@@ -1,6 +1,7 @@
1
1
  import { Client } from 'viem';
2
2
  import { Blockish, EthAddress, EthereumProvider, NetworkNumber, PositionBalances } from '../types/common';
3
3
  import { MorphoBlueEarnData, MorphoBlueMarketData, MorphoBlueMarketInfo, MorphoBlueMarketRewards, MorphoBluePositionData } from '../types';
4
+ export { MORPHO_BLUE_MERKL_OPPORTUNITY_TYPES, addMorphoBlueMerklOpportunitiesToMarketInfo, getMorphoBlueMerklOpportunities, addMorphoBlueMerklRewardsToMarketInfo, } from './merkl';
4
5
  export declare const addMorphoBlueRewardsToMarketInfo: (marketInfo: MorphoBlueMarketInfo, rewards: MorphoBlueMarketRewards) => MorphoBlueMarketInfo;
5
6
  export declare function _getMorphoBlueMarketData(provider: Client, network: NetworkNumber, selectedMarket: MorphoBlueMarketData): Promise<MorphoBlueMarketInfo>;
6
7
  export declare function _getMorphoBluePortfolioMarketData(provider: Client, network: NetworkNumber, selectedMarket: MorphoBlueMarketData): Promise<MorphoBlueMarketInfo>;
@@ -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.getMorphoBlueAccountBalances = exports._getMorphoBlueAccountBalances = exports.getMorphoEarnDataWithMarketInfo = exports.getMorphoBluePositionDataWithMarketInfo = exports.addMorphoBlueRewardsToMarketInfo = void 0;
15
+ exports.getMorphoBlueAccountBalances = exports._getMorphoBlueAccountBalances = exports.getMorphoEarnDataWithMarketInfo = exports.getMorphoBluePositionDataWithMarketInfo = exports.addMorphoBlueRewardsToMarketInfo = exports.addMorphoBlueMerklRewardsToMarketInfo = exports.getMorphoBlueMerklOpportunities = exports.addMorphoBlueMerklOpportunitiesToMarketInfo = exports.MORPHO_BLUE_MERKL_OPPORTUNITY_TYPES = void 0;
16
16
  exports._getMorphoBlueMarketData = _getMorphoBlueMarketData;
17
17
  exports._getMorphoBluePortfolioMarketData = _getMorphoBluePortfolioMarketData;
18
18
  exports.getMorphoBlueMarketData = getMorphoBlueMarketData;
@@ -31,6 +31,12 @@ const utils_1 = require("../services/utils");
31
31
  const morphoBlueHelpers_1 = require("../helpers/morphoBlueHelpers");
32
32
  const priceService_1 = require("../services/priceService");
33
33
  const viem_1 = require("../services/viem");
34
+ const merkl_1 = require("./merkl");
35
+ var merkl_2 = require("./merkl");
36
+ Object.defineProperty(exports, "MORPHO_BLUE_MERKL_OPPORTUNITY_TYPES", { enumerable: true, get: function () { return merkl_2.MORPHO_BLUE_MERKL_OPPORTUNITY_TYPES; } });
37
+ Object.defineProperty(exports, "addMorphoBlueMerklOpportunitiesToMarketInfo", { enumerable: true, get: function () { return merkl_2.addMorphoBlueMerklOpportunitiesToMarketInfo; } });
38
+ Object.defineProperty(exports, "getMorphoBlueMerklOpportunities", { enumerable: true, get: function () { return merkl_2.getMorphoBlueMerklOpportunities; } });
39
+ Object.defineProperty(exports, "addMorphoBlueMerklRewardsToMarketInfo", { enumerable: true, get: function () { return merkl_2.addMorphoBlueMerklRewardsToMarketInfo; } });
34
40
  const HARDCODED_USD_STABLE_PRICE = '100000000'; // $1 with 8 decimals
35
41
  const getMorphoRewardIncentives = (apy) => [{
36
42
  token: 'MORPHO',
@@ -134,15 +140,15 @@ function getMorphoBlueMarketDataInternal(provider, network, selectedMarket) {
134
140
  }
135
141
  function _getMorphoBlueMarketData(provider, network, selectedMarket) {
136
142
  return __awaiter(this, void 0, void 0, function* () {
137
- const marketInfo = yield getMorphoBlueMarketDataInternal(provider, network, selectedMarket);
138
- try {
139
- const rewards = yield (0, morphoBlueHelpers_1.getRewardsForMarket)(selectedMarket.marketId, network);
140
- return (0, exports.addMorphoBlueRewardsToMarketInfo)(marketInfo, rewards);
141
- }
142
- catch (error) {
143
- console.error(error);
144
- return (0, exports.addMorphoBlueRewardsToMarketInfo)(marketInfo, { supplyApy: '0', borrowApy: '0' });
145
- }
143
+ const [marketInfo, rewards, merklOpportunities] = yield Promise.all([
144
+ getMorphoBlueMarketDataInternal(provider, network, selectedMarket),
145
+ (0, morphoBlueHelpers_1.getRewardsForMarket)(selectedMarket.marketId, network).catch((error) => {
146
+ console.error(error);
147
+ return { supplyApy: '0', borrowApy: '0' };
148
+ }),
149
+ (0, merkl_1.getMorphoBlueMerklOpportunities)(),
150
+ ]);
151
+ return (0, merkl_1.addMorphoBlueMerklOpportunitiesToMarketInfo)((0, exports.addMorphoBlueRewardsToMarketInfo)(marketInfo, rewards), selectedMarket, network, merklOpportunities);
146
152
  });
147
153
  }
148
154
  function _getMorphoBluePortfolioMarketData(provider, network, selectedMarket) {
@@ -0,0 +1,33 @@
1
+ import { MerklOpportunity, MorphoBlueMarketData, MorphoBlueMarketInfo, NetworkNumber } from '../types';
2
+ /**
3
+ * Merkl tags Morpho Blue market-level reward campaigns via the opportunity `type` field:
4
+ * - MORPHOSUPPLY → reward for supplying the market's loan asset
5
+ * - MORPHOCOLLATERAL → reward for depositing the market's collateral asset
6
+ * - MORPHOBORROW → reward for borrowing the market's loan asset
7
+ * (MORPHOVAULT/ERC20LOGPROCESSOR are MetaMorpho vault campaigns and MORPHOSUPPLY_SINGLETOKEN is
8
+ * token-wide rather than market-scoped, so none of them belong on per-market data.)
9
+ *
10
+ * A campaign identifies its market via `identifier` — the first 20 bytes of the 32-byte Morpho
11
+ * market id, formatted as a checksummed address. Whitelist-gated campaigns append a marker to that
12
+ * identifier (e.g. `0x54cf…c46WHITELIST_CAMPAIGN`); their rewards only accrue to whitelisted
13
+ * addresses, so they are skipped rather than advertised to every user.
14
+ */
15
+ export declare const MORPHO_BLUE_MERKL_OPPORTUNITY_TYPES: readonly ["MORPHOSUPPLY", "MORPHOCOLLATERAL", "MORPHOBORROW"];
16
+ /**
17
+ * Appends the given live Merkl campaigns for the market to its `assetsData` incentive arrays
18
+ * (collateral supply / loan supply / loan borrow). Existing Merkl incentives are replaced rather
19
+ * than duplicated, so re-applying on refreshed data is safe.
20
+ */
21
+ export declare const addMorphoBlueMerklOpportunitiesToMarketInfo: (marketInfo: MorphoBlueMarketInfo, selectedMarket: MorphoBlueMarketData, chainId: NetworkNumber, opportunities: MerklOpportunity[]) => MorphoBlueMarketInfo;
22
+ /**
23
+ * Fetches live market-scoped Morpho Blue campaigns for all chains. Never throws — on any failure
24
+ * it returns an empty list, so Merkl being down can't break market data. The query is narrowed by
25
+ * `type=` and capped at `items=100` because Merkl paginates at 20 items by default — an
26
+ * unfiltered protocol query would silently drop campaigns once Morpho has enough opportunities.
27
+ */
28
+ export declare const getMorphoBlueMerklOpportunities: () => Promise<MerklOpportunity[]>;
29
+ /**
30
+ * Fetches live Merkl campaigns and appends the ones for the market to its `assetsData` incentive
31
+ * arrays. Never throws — on any failure the market info is returned unchanged.
32
+ */
33
+ export declare const addMorphoBlueMerklRewardsToMarketInfo: (marketInfo: MorphoBlueMarketInfo, selectedMarket: MorphoBlueMarketData, network: NetworkNumber) => Promise<MorphoBlueMarketInfo>;
@@ -0,0 +1,101 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.addMorphoBlueMerklRewardsToMarketInfo = exports.getMorphoBlueMerklOpportunities = exports.addMorphoBlueMerklOpportunitiesToMarketInfo = exports.MORPHO_BLUE_MERKL_OPPORTUNITY_TYPES = void 0;
13
+ const moneymarket_1 = require("../moneymarket");
14
+ const utils_1 = require("../services/utils");
15
+ const types_1 = require("../types");
16
+ /**
17
+ * Merkl tags Morpho Blue market-level reward campaigns via the opportunity `type` field:
18
+ * - MORPHOSUPPLY → reward for supplying the market's loan asset
19
+ * - MORPHOCOLLATERAL → reward for depositing the market's collateral asset
20
+ * - MORPHOBORROW → reward for borrowing the market's loan asset
21
+ * (MORPHOVAULT/ERC20LOGPROCESSOR are MetaMorpho vault campaigns and MORPHOSUPPLY_SINGLETOKEN is
22
+ * token-wide rather than market-scoped, so none of them belong on per-market data.)
23
+ *
24
+ * A campaign identifies its market via `identifier` — the first 20 bytes of the 32-byte Morpho
25
+ * market id, formatted as a checksummed address. Whitelist-gated campaigns append a marker to that
26
+ * identifier (e.g. `0x54cf…c46WHITELIST_CAMPAIGN`); their rewards only accrue to whitelisted
27
+ * addresses, so they are skipped rather than advertised to every user.
28
+ */
29
+ exports.MORPHO_BLUE_MERKL_OPPORTUNITY_TYPES = ['MORPHOSUPPLY', 'MORPHOCOLLATERAL', 'MORPHOBORROW'];
30
+ const MERKL_DESCRIPTION_MARKER = 'through Merkl';
31
+ // '0x' + first 20 bytes of the market id
32
+ const MARKET_ID_PREFIX_LENGTH = 42;
33
+ const buildMerklIncentive = (opportunity) => {
34
+ var _a, _b, _c, _d, _e, _f;
35
+ const token = ((_d = (_c = (_b = (_a = opportunity.rewardsRecord) === null || _a === void 0 ? void 0 : _a.breakdowns) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.token) === null || _d === void 0 ? void 0 : _d.symbol) || ((_f = (_e = opportunity.tokens) === null || _e === void 0 ? void 0 : _e[0]) === null || _f === void 0 ? void 0 : _f.symbol) || '';
36
+ return {
37
+ apy: (0, moneymarket_1.aprToApy)(opportunity.apr),
38
+ token,
39
+ incentiveKind: types_1.IncentiveKind.Reward,
40
+ description: `Eligible for ${token} rewards through Merkl.${opportunity.description ? `\n${opportunity.description}` : ''}`,
41
+ };
42
+ };
43
+ const withoutMerklIncentives = (incentives = []) => incentives
44
+ .filter(({ description }) => !(description === null || description === void 0 ? void 0 : description.includes(MERKL_DESCRIPTION_MARKER)));
45
+ /**
46
+ * Appends the given live Merkl campaigns for the market to its `assetsData` incentive arrays
47
+ * (collateral supply / loan supply / loan borrow). Existing Merkl incentives are replaced rather
48
+ * than duplicated, so re-applying on refreshed data is safe.
49
+ */
50
+ const addMorphoBlueMerklOpportunitiesToMarketInfo = (marketInfo, selectedMarket, chainId, opportunities) => {
51
+ const marketIdPrefix = (selectedMarket.marketId || '').slice(0, MARKET_ID_PREFIX_LENGTH).toLowerCase();
52
+ const collateralAsset = marketInfo.assetsData[marketInfo.collateralToken];
53
+ const loanAsset = marketInfo.assetsData[marketInfo.loanToken];
54
+ if (marketIdPrefix.length !== MARKET_ID_PREFIX_LENGTH || !collateralAsset || !loanAsset)
55
+ return marketInfo;
56
+ const relevant = opportunities.filter((o) => {
57
+ var _a;
58
+ return o.chainId === chainId
59
+ && o.status === types_1.OpportunityStatus.LIVE
60
+ && exports.MORPHO_BLUE_MERKL_OPPORTUNITY_TYPES.includes(o.type)
61
+ // a suffixed identifier marks a whitelist-gated campaign — skip those
62
+ && ((_a = o.identifier) === null || _a === void 0 ? void 0 : _a.length) === MARKET_ID_PREFIX_LENGTH
63
+ && o.identifier.toLowerCase() === marketIdPrefix;
64
+ });
65
+ if (!relevant.length)
66
+ return marketInfo;
67
+ const incentivesByType = (type) => relevant.filter((o) => o.type === type).map(buildMerklIncentive);
68
+ const collateralSupply = incentivesByType('MORPHOCOLLATERAL');
69
+ const loanSupply = incentivesByType('MORPHOSUPPLY');
70
+ const loanBorrow = incentivesByType('MORPHOBORROW');
71
+ return Object.assign(Object.assign({}, marketInfo), { assetsData: Object.assign(Object.assign({}, marketInfo.assetsData), { [marketInfo.collateralToken]: Object.assign(Object.assign({}, collateralAsset), { supplyIncentives: [...withoutMerklIncentives(collateralAsset.supplyIncentives), ...collateralSupply] }), [marketInfo.loanToken]: Object.assign(Object.assign({}, loanAsset), { supplyIncentives: [...withoutMerklIncentives(loanAsset.supplyIncentives), ...loanSupply], borrowIncentives: [...withoutMerklIncentives(loanAsset.borrowIncentives), ...loanBorrow] }) }) });
72
+ };
73
+ exports.addMorphoBlueMerklOpportunitiesToMarketInfo = addMorphoBlueMerklOpportunitiesToMarketInfo;
74
+ /**
75
+ * Fetches live market-scoped Morpho Blue campaigns for all chains. Never throws — on any failure
76
+ * it returns an empty list, so Merkl being down can't break market data. The query is narrowed by
77
+ * `type=` and capped at `items=100` because Merkl paginates at 20 items by default — an
78
+ * unfiltered protocol query would silently drop campaigns once Morpho has enough opportunities.
79
+ */
80
+ const getMorphoBlueMerklOpportunities = () => __awaiter(void 0, void 0, void 0, function* () {
81
+ try {
82
+ const res = yield fetch(`https://fe.defisaver.com/api/merkl/opportunities?mainProtocolId=morpho&type=${exports.MORPHO_BLUE_MERKL_OPPORTUNITY_TYPES.join(',')}&status=LIVE&items=100`, {
83
+ signal: AbortSignal.timeout(utils_1.LONGER_TIMEOUT),
84
+ });
85
+ if (!res.ok)
86
+ throw new Error('Failed to fetch Morpho Blue Merkl campaigns');
87
+ const data = yield res.json();
88
+ return Array.isArray(data) ? data : [];
89
+ }
90
+ catch (e) {
91
+ console.error('Failed to fetch Morpho Blue Merkl campaigns', e);
92
+ return [];
93
+ }
94
+ });
95
+ exports.getMorphoBlueMerklOpportunities = getMorphoBlueMerklOpportunities;
96
+ /**
97
+ * Fetches live Merkl campaigns and appends the ones for the market to its `assetsData` incentive
98
+ * arrays. Never throws — on any failure the market info is returned unchanged.
99
+ */
100
+ const addMorphoBlueMerklRewardsToMarketInfo = (marketInfo, selectedMarket, network) => __awaiter(void 0, void 0, void 0, function* () { return (0, exports.addMorphoBlueMerklOpportunitiesToMarketInfo)(marketInfo, selectedMarket, network, yield (0, exports.getMorphoBlueMerklOpportunities)()); });
101
+ exports.addMorphoBlueMerklRewardsToMarketInfo = addMorphoBlueMerklRewardsToMarketInfo;
@@ -19,6 +19,10 @@ export declare const isEligibleForAaveV3ArbitrumETHLSBorrow: (usedAssets: MMUsed
19
19
  isEligible: boolean;
20
20
  eligibleUSDAmount: string;
21
21
  };
22
+ export declare const isEligibleForCompoundV3PufEthWethBorrow: (usedAssets: MMUsedAssets) => {
23
+ isEligible: boolean;
24
+ eligibleUSDAmount: string;
25
+ };
22
26
  export declare const EligibilityMapping: {
23
27
  [key in IncentiveEligibilityId]: (usedAssets: MMUsedAssets, optionalData: any) => {
24
28
  isEligible: boolean;