Skip to content

Lunar Finance Adapter, For Fees#5792

Open
collinpowell wants to merge 1 commit intoDefiLlama:masterfrom
Lunarfi-eclipse:master
Open

Lunar Finance Adapter, For Fees#5792
collinpowell wants to merge 1 commit intoDefiLlama:masterfrom
Lunarfi-eclipse:master

Conversation

@collinpowell
Copy link

@collinpowell collinpowell commented Feb 1, 2026

NOTE

Please enable "Allow edits by maintainers" while putting up the PR.


  • If you would like to add a tvl adapter please submit the PR here.
  1. Once your adapter has been merged, it takes time to show on the UI. If more than 24 hours have passed, please let us know in Discord.
  2. Please fill the form below only if the PR is for listing a new protocol else it can be ignored/replaced with reason/details about the PR
  3. For updating listing info It is a different repo, you can find your listing in this file: https://github.com/DefiLlama/defillama-server/blob/master/defi/src/protocols/data4.ts, you can edit it there and put up a PR
  4. Do not edit/push package.json/package-lock.json file as part of your changes
  5. No need to go to our discord/other channel and announce that you've created a PR, we monitor all PRs and will review it asap

Name (to be shown on DefiLlama): Lunar Finance
Twitter Link: https://x.com/lunar_finance?s=21&t=brmp0afQquLddEH-rPBHvQ
List of audit links if any:
Website Link: https://lunarfinance.io
Logo (High resolution, will be shown with rounded borders): https://lunarfinance.io/logo.png
Current TVL:
Treasury Addresses (if the protocol has treasury); 0x658F5a6D5A82506c712eE6B7B6F5e5Bb52996701,
Chain: multichain
Coingecko ID (so your TVL can appear on Coingecko, leave empty if not listed): (https://api.coingecko.com/api/v3/coins/list)
Coinmarketcap ID (so your TVL can appear on Coinmarketcap, leave empty if not listed): (https://api.coinmarketcap.com/data-api/v3/map/all?listing_status=active,inactive,untracked&start=1&limit=10000)
Short Description (to be shown on DefiLlama): Lunar finance is a multichain aggregator that allows users to swap and bridge on 40+ chains
Token address and ticker if any:
Category (full list at https://defillama.com/categories) *Please choose only one: Dexes
Oracle Provider(s): Specify the oracle(s) used (e.g., Chainlink, Band, API3, TWAP, etc.):
Implementation Details: Briefly describe how the oracle is integrated into your project:
Documentation/Proof: Provide links to documentation or any other resources that verify the oracle's usage:
forkedFrom (Does your project originate from another project): no
methodology (what is being counted as tvl, how is tvl being calculated): its calculated by the number of approved swaps
Github org/user (Optional, if your code is open source, we can track activity):
Does this project have a referral program? no
Implementation Details: Briefly describe how the oracle is integrated into your project:
Documentation/Proof: Provide links to documentation or any other resources that verify the oracle's usage:
forkedFrom (Does your project originate from another project):
methodology (what is being counted as tvl, how is tvl being calculated):
Github org/user (Optional, if your code is open source, we can track activity): Lunarfi-eclipse
Does this project have a referral program? no

Summary by CodeRabbit

  • New Features
    • Integrated Luna Finance analytics for Solana, tracking bridge transfer and swap activity.
    • Provides daily metrics including volume, fees, and revenue across bridge and swap operations.
    • Includes separate adapters for bridge-only and swap-only analysis, plus combined metrics.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 1, 2026

📝 Walkthrough

Walkthrough

Introduces a new Luna Finance adapter module for Solana with three adapters: a default combined adapter tracking both bridge and DEX swap metrics, a bridge-specific adapter, and a swap-specific adapter. Includes API integration, data transformation, and timestamp resolution utilities.

Changes

Cohort / File(s) Summary
Luna Finance Adapters
dexs/lunar-finance/index.ts
New module with Luna Finance data adapters supporting combined bridge+DEX swap analytics and individual bridge/swap tracking on Solana. Includes API endpoints, TypeScript interfaces, helper functions for data fetching and conversion, error handling with fallbacks, and three exported adapter variants (default, bridge-only, swap-only).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Hopping through chains with lunar delight,
Bridge and swap data, shining so bright!
Three adapters dancing on Solana's stage,
Analytics wisdom, page by page!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Lunar Finance Adapter, For Fees' directly matches the PR's main objective of adding a Lunar Finance adapter for fee reporting, clearly summarizing the primary change.
Description check ✅ Passed The PR description follows the template structure and fills in most required fields for a new protocol listing (name, Twitter, website, logo, chain, category, methodology, etc.), though some optional fields like Coingecko/Coinmarketcap IDs and current TVL remain blank.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@llamabutler
Copy link

The lunar-finance adapter exports:

> adapters@1.0.0 test
> ts-node --transpile-only cli/testAdapter.ts dexs lunar-finance

🦙 Running LUNAR-FINANCE adapter 🦙
---------------------------------------------------
Start Date:	Sat, 31 Jan 2026 00:00:00 GMT
End Date:	Sun, 01 Feb 2026 00:00:00 GMT
---------------------------------------------------

Error fetching Luna Finance data for timestamp 1769903999: [Error: Request failed with status code 404] {
  url: 'https://api.lunarfinance.io/api/analytics/fees?startTime=1769817600&endTime=1769904000',
  method: 'GET',
  axiosError: 'Application not found'
}
SOLANA 👇
Backfill start time: 1/2/2026
Daily volume: 0.00
End timestamp: 1769817600 (2026-01-31T00:00:00.000Z)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Fix all issues with AI agents
In `@dexs/lunar-finance/index.ts`:
- Around line 165-176: The fallback Unix timestamp 1640995200 used in the error
and default-return branches should be replaced with Lunar Finance's real launch
timestamp; locate the function that returns the earliest historical timestamp
(the block that returns response.data.timeSeries[0].timestamp and the fallback
returns of 1640995200) and update both the primary fallback and catch fallback
to the correct Unix epoch seconds for Lunar Finance's launch, and update the
inline comment to state the actual launch date (human-readable) so both the
value and comment are accurate.
- Around line 88-94: The catch block that currently does console.error(...) and
returns { dailyVolume: 0, timestamp: dayTimestamp } must not mask API failures;
update the error handling in the fetch routine (the try/catch that references
timestamp and dayTimestamp and returns dailyVolume) to propagate the error
instead of returning a zero result — e.g., after logging rethrow the caught
error (throw error) or return undefined if your adapter framework expects that;
remove the hard-coded { dailyVolume: 0, timestamp: dayTimestamp } return so
callers can distinguish real zero-volume days from API failures and adjust
types/signature of the fetch function accordingly.
- Around line 178-213: Remove the unused named exports bridgeAdapter and
dexAdapter to avoid dead code: delete the bridgeAdapter and dexAdapter
declarations (they reference fetchBridge and fetchSwap) and keep only the
default exported adapter; if you intend to keep them for future use instead, add
a short comment above each explaining they're placeholders for future per-chain
adapters and why they are exported so reviewers know they are intentional.
- Line 8: The line defining LUNA_API_BASE currently contains a placeholder
comment; remove that comment and make the constant follow the project's pattern
by using an environment override with a fallback: replace the current definition
of LUNA_API_BASE with a value derived from process.env (e.g.,
process.env.LUNA_API_BASE ?? "https://api.lunarfinance.io") or simply remove the
trailing comment if you confirm the hardcoded URL is final; update the symbol
LUNA_API_BASE accordingly.
🧹 Nitpick comments (2)
dexs/lunar-finance/index.ts (2)

37-42: Unused interface field.

The transactions field in TimeSeriesPoint is defined but never used in the codebase. Consider removing it or adding usage if transaction counts are needed.


6-11: Naming inconsistency: "Luna" vs "Lunar".

The PR and website reference "Lunar Finance" but the code uses "Luna" prefix (LUNA_API_BASE, LunaAnalyticsResponse). Consider using consistent naming (LUNAR_API_BASE, LunarAnalyticsResponse) to match the protocol's branding.


// Luna Finance API endpoints

const LUNA_API_BASE = "https://api.lunarfinance.io"; // Replace with your actual API URL
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# Check if the file exists and read the relevant section
cat -n dexs/lunar-finance/index.ts | head -30

Repository: DefiLlama/dimension-adapters

Length of output: 1168


🏁 Script executed:

# Check other DEX adapters to see if similar patterns exist
fd "index.ts" dexs/ -type f | head -5 | xargs -I {} sh -c 'echo "=== {} ===" && head -15 {}'

Repository: DefiLlama/dimension-adapters

Length of output: 242


🏁 Script executed:

# Search for similar API base URL patterns across the codebase
rg "Replace with your actual" --type ts --type js

Repository: DefiLlama/dimension-adapters

Length of output: 188


🏁 Script executed:

# Search for API endpoint patterns in other adapters to understand the standard approach
rg "const.*_BASE.*=" dexs/ -A 1 | head -40

Repository: DefiLlama/dimension-adapters

Length of output: 2239


🏁 Script executed:

# Check a few other adapter files to see their structure
ls dexs/ | head -10 | xargs -I {} sh -c 'echo "=== {} ===" && head -15 dexs/{}/index.ts' | head -100

Repository: DefiLlama/dimension-adapters

Length of output: 3927


🏁 Script executed:

# Search for comments about API URLs in the codebase
rg "API.*URL|api.*url" dexs/ -i | head -20

Repository: DefiLlama/dimension-adapters

Length of output: 1911


Remove the placeholder comment on line 8.

The comment // Replace with your actual API URL is unusual for production code. Unlike other adapters in the repository which use either hardcoded endpoints without commentary or environment variable overrides with fallbacks, this file contains a placeholder suggestion for customization. Either confirm the API URL is correct and remove the comment, or restructure it to match the pattern used elsewhere (e.g., process.env.LUNA_API_BASE ?? "https://api.lunarfinance.io").

🤖 Prompt for AI Agents
In `@dexs/lunar-finance/index.ts` at line 8, The line defining LUNA_API_BASE
currently contains a placeholder comment; remove that comment and make the
constant follow the project's pattern by using an environment override with a
fallback: replace the current definition of LUNA_API_BASE with a value derived
from process.env (e.g., process.env.LUNA_API_BASE ??
"https://api.lunarfinance.io") or simply remove the trailing comment if you
confirm the hardcoded URL is final; update the symbol LUNA_API_BASE accordingly.

Comment on lines +88 to +94
} catch (error) {
console.error(`Error fetching Luna Finance data for timestamp ${timestamp}:`, error);
return {
dailyVolume: 0,
timestamp: dayTimestamp,
};
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Silent error handling may corrupt data.

Returning { dailyVolume: 0, timestamp } on API failure makes it impossible to distinguish between "no trading activity" and "API error." This can pollute historical records with false zeros.

Consider throwing the error to let the adapter framework handle retries/failures, or return undefined if the framework supports it.

Proposed fix: propagate errors instead of masking them
   } catch (error) {
     console.error(`Error fetching Luna Finance data for timestamp ${timestamp}:`, error);
-    return {
-      dailyVolume: 0,
-      timestamp: dayTimestamp,
-    };
+    throw error;
   }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch (error) {
console.error(`Error fetching Luna Finance data for timestamp ${timestamp}:`, error);
return {
dailyVolume: 0,
timestamp: dayTimestamp,
};
}
} catch (error) {
console.error(`Error fetching Luna Finance data for timestamp ${timestamp}:`, error);
throw error;
}
🤖 Prompt for AI Agents
In `@dexs/lunar-finance/index.ts` around lines 88 - 94, The catch block that
currently does console.error(...) and returns { dailyVolume: 0, timestamp:
dayTimestamp } must not mask API failures; update the error handling in the
fetch routine (the try/catch that references timestamp and dayTimestamp and
returns dailyVolume) to propagate the error instead of returning a zero result —
e.g., after logging rethrow the caught error (throw error) or return undefined
if your adapter framework expects that; remove the hard-coded { dailyVolume: 0,
timestamp: dayTimestamp } return so callers can distinguish real zero-volume
days from API failures and adjust types/signature of the fetch function
accordingly.

Comment on lines +165 to +176
// Fallback to a default launch date if API fails
return 1640995200; // January 1, 2022 (replace with actual launch date)
}

// Return the earliest timestamp from historical data
return response.data.timeSeries[0].timestamp;
} catch (error) {
console.error("Error fetching start timestamp:", error);
// Fallback date
return 1640995200;
}
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Update placeholder launch date.

The fallback timestamp 1640995200 (January 1, 2022) has a comment indicating it should be replaced with the actual launch date. Please update this to Lunar Finance's actual launch date to ensure accurate historical data boundaries.

Suggested fix structure
-      return 1640995200; // January 1, 2022 (replace with actual launch date)
+      return ACTUAL_LAUNCH_TIMESTAMP; // Lunar Finance launch date
-    return 1640995200;
+    return ACTUAL_LAUNCH_TIMESTAMP;
🤖 Prompt for AI Agents
In `@dexs/lunar-finance/index.ts` around lines 165 - 176, The fallback Unix
timestamp 1640995200 used in the error and default-return branches should be
replaced with Lunar Finance's real launch timestamp; locate the function that
returns the earliest historical timestamp (the block that returns
response.data.timeSeries[0].timestamp and the fallback returns of 1640995200)
and update both the primary fallback and catch fallback to the correct Unix
epoch seconds for Lunar Finance's launch, and update the inline comment to state
the actual launch date (human-readable) so both the value and comment are
accurate.

Comment on lines +178 to +213
// Main adapter for combined volume (bridges + dexs)
const adapter: SimpleAdapter = {
adapter: {
[CHAIN.SOLANA]: {
fetch,
start: getStartTimestamp,
},
// Add support for other chains as Luna Finance expands
// [CHAIN.ETHEREUM]: {
// fetch,
// start: getStartTimestamp,
// },
},
};

// Bridge-specific adapter
export const bridgeAdapter: SimpleAdapter = {
adapter: {
[CHAIN.SOLANA]: {
fetch: fetchBridge,
start: getStartTimestamp,
},
},
};

// DEX/Swap-specific adapter
export const dexAdapter: SimpleAdapter = {
adapter: {
[CHAIN.SOLANA]: {
fetch: fetchSwap,
start: getStartTimestamp,
},
},
};

export default adapter; No newline at end of file
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

rg -l "export const.*Adapter.*SimpleAdapter" dexs/ | head -10 | xargs -I {} sh -c 'echo "=== {} ===" && grep -E "^export const.*Adapter|^const adapter|^export default" {} | head -15'

Repository: DefiLlama/dimension-adapters

Length of output: 253


🏁 Script executed:

# Check if bridgeAdapter and dexAdapter are imported/used anywhere
rg "bridgeAdapter|dexAdapter" --type ts --type tsx dexs/ --no-heading

Repository: DefiLlama/dimension-adapters

Length of output: 99


🏁 Script executed:

# Look for how the main adapter export is typically used
git ls-files dexs/ | head -20 | xargs wc -l | sort -rn | head -10

Repository: DefiLlama/dimension-adapters

Length of output: 339


🏁 Script executed:

# Search for adapter registry or configuration that might import these exports
rg -l "bridgeAdapter|dexAdapter|luna|lunar" dexs/ --type ts --type tsx

Repository: DefiLlama/dimension-adapters

Length of output: 99


🏁 Script executed:

# Check if bridgeAdapter and dexAdapter are imported anywhere in the codebase
rg "from.*lunar-finance|import.*bridgeAdapter|import.*dexAdapter" --type ts

Repository: DefiLlama/dimension-adapters

Length of output: 125


🏁 Script executed:

# Look at a few other DEX adapters to see their export patterns
rg -A 5 "^export const.*Adapter.*SimpleAdapter|^export default" dexs/ --type ts -m 3 | head -100

Repository: DefiLlama/dimension-adapters

Length of output: 3405


🏁 Script executed:

# Check if there's an adapter registry or configuration file
fd "registry|config|index" dexs/ --type ts | grep -E "(registry|config|index\.ts$)" | head -10

Repository: DefiLlama/dimension-adapters

Length of output: 241


🏁 Script executed:

# Look at the entire lunar-finance/index.ts to understand context better
cat -n dexs/lunar-finance/index.ts | head -220 | tail -60

Repository: DefiLlama/dimension-adapters

Length of output: 1982


Consider removing unused exports or documenting their purpose.

The bridgeAdapter and dexAdapter are exported but not imported anywhere in the codebase. The framework appears to only use the default export (the main combined adapter), which is the standard pattern used by other DEX adapters in the repository. These named exports are either dead code or intended for future expansion, in which case a comment explaining their purpose would be helpful.

If they're not needed for external consumption, remove them to keep the file focused.

🤖 Prompt for AI Agents
In `@dexs/lunar-finance/index.ts` around lines 178 - 213, Remove the unused named
exports bridgeAdapter and dexAdapter to avoid dead code: delete the
bridgeAdapter and dexAdapter declarations (they reference fetchBridge and
fetchSwap) and keep only the default exported adapter; if you intend to keep
them for future use instead, add a short comment above each explaining they're
placeholders for future per-chain adapters and why they are exported so
reviewers know they are intentional.

@treeoflife2 treeoflife2 self-assigned this Feb 3, 2026
Copy link
Member

@treeoflife2 treeoflife2 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.


// Luna Finance API endpoints

const LUNA_API_BASE = "https://api.lunarfinance.io"; // Replace with your actual API URL
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

API url doesn't work

import { CHAIN } from "../../helpers/chains";
import { getUniqStartOfTodayTimestamp } from "../../helpers/getUniSubgraphVolume";

// Luna Finance API endpoints
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please remove these comments, we prefer clean adapter file


return {
dailyVolume: totalVolume,
dailyBridgeVolume: bridgeVol,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as i can see the project falls under the aggregator and bridge-aggregator category, so it should be better if you create two separate protocol files, one inside aggregtors(same chain swaps) and one inside bridge-aggregators(cross chain swap volumes)
and we prefer separate fees/revenue as well for both category, so if possible please create two separate fees adapters too. lmk if you need any help

dailyRevenue: totalRevenue,
timestamp: dayTimestamp,
};
} catch (error) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we prefer if adapter fails, so please remove the try/catch blocks


// Get the start timestamp (when Luna Finance launched)
const getStartTimestamp = async () => {
try {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please hardcode the startTimestamp onetime, instead of doing api call each time for each chains

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants