Skip to content

add Priority Trade fees/volume adapter (MegaETH)#6395

Open
thomasxpx wants to merge 1 commit intoDefiLlama:masterfrom
thomasxpx:master
Open

add Priority Trade fees/volume adapter (MegaETH)#6395
thomasxpx wants to merge 1 commit intoDefiLlama:masterfrom
thomasxpx:master

Conversation

@thomasxpx
Copy link
Copy Markdown

Name (to be shown on DefiLlama):
Priority

Twitter Link:
https://x.com/PriorityTrade_

List of audit links if any:
Website Link:
https://t.me/prioritytradebot

Logo (High resolution, will be shown with rounded borders):
priority

Current TVL:
Treasury Addresses (if the protocol has treasury) :
0xaA8995eA9d805089aCF102A2a80Dc92CA7a5c9fB

Chain:
MegaETH

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):
The fastest Telegram trading bot designed for MegaETH.

Token address and ticker if any:
Category (full list at https://defillama.com/categories) *Please choose only one:
Telegram Bot

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:
https://docs.prioritytrade.xyz/

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):
Does this project have a referral program?
yes

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 14, 2026

Summary by CodeRabbit

  • New Features
    • Added support for tracking daily trading volume and trading fees for Priority Trade on the MEGAETH chain.

Walkthrough

Added a new adapter module for computing daily ETH trading volume and trading fees for the MEGAETH Priority Trade flow. The adapter performs timestamp-to-block conversion via binary search, fetches router event logs, ABI-decodes buy/sell events, and aggregates trading volume and fee metrics.

Changes

Cohort / File(s) Summary
Priority Trade Fees Adapter
fees/priority-trade/index.ts
New SimpleAdapter (v2) that converts timestamps to Ethereum block numbers via binary search, fetches router event logs for buy/sell transactions, decodes events to extract trading amounts, and calculates daily trading volume and fee metrics with separate logic for buy (ethIn / 100) and sell (gross - net) fee calculations.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

fees, new-adapter

🚥 Pre-merge checks | ✅ 3 | ❌ 3

❌ Failed checks (3 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning The title 'add Priority Trade fees/volume adapter (MegaETH)' clearly summarizes the main change, though it does not follow the specified format of [type] protocol-name - description. Revise title to follow format [type] protocol-name - description, e.g., '[adapter] Priority Trade - add fees/volume adapter for MegaETH'.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 50.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Income Statement Compliance ⚠️ Warning The adapter sets dailyRevenue equal to dailyFees without calculating or deducting dailySupplySideRevenue, violating the income statement compliance relationship: dailyRevenue = dailyFees - dailySupplySideRevenue. Identify if Priority Trade has supplier payments or costs. If yes, implement dailySupplySideRevenue and set dailyRevenue = dailyFees - dailySupplySideRevenue. If no, add documentation explaining why all fees are protocol revenue.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed The PR description includes most required form fields but is missing methodology section and other fields are incomplete or left blank.
Breakdown Methodology Check ✅ Passed The adapter correctly includes all breakdown labels used in .add() calls within the breakdownMethodology object and exports it properly.
Version 2 Required ✅ Passed The new Priority Trade adapter correctly exports version: 2 on line 106, satisfying the requirement for new adapters.

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

✨ Finishing Touches
✨ Simplify code
  • Create PR with simplified code

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.

@github-actions
Copy link
Copy Markdown

The priority-trade adapter exports:

> adapters@1.0.0 test
> ts-node --transpile-only cli/testAdapter.ts fees priority-trade

🦙 Running PRIORITY-TRADE adapter 🦙
---------------------------------------------------
Start Date:	Mon, 13 Apr 2026 11:56:29 GMT
End Date:	Tue, 14 Apr 2026 11:56:29 GMT
---------------------------------------------------

MEGAETH 👇
Backfill start time: 4/2/2026
Daily volume: 1.29 k
Daily fees: 13.00
Daily revenue: 13.00
Daily protocol revenue: 13.00
End timestamp: 1776167788 (2026-04-14T11:56:28.000Z)

@bheluga bheluga self-assigned this Apr 14, 2026
Copy link
Copy Markdown
Member

@bheluga bheluga left a comment

Choose a reason for hiding this comment

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

@thomasxpx thanks for the PR.
We have getLogs helper function , so you need not write so much code to get event logs. You can refer https://github.com/DefiLlama/dimension-adapters/blob/master/aggregators/liquidswap/index.ts for example.
Also try to use eventAbi instead of topic, its easy to read and doesnt need to be decoded

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 14, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
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: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@fees/priority-trade/index.ts`:
- Around line 25-36: The custom binary-search helper getBlockAtTimestamp is
redundant and should be removed; update fetch_ to call
FetchOptions.getFromBlock(timestamp) and FetchOptions.getToBlock(timestamp) (or
the appropriate getFromBlock()/getToBlock() overloads on the provided
FetchOptions instance) instead of invoking getBlockAtTimestamp and performing
RPCs directly, ensuring you rely on the framework’s caching/optimizations and
handle any returned block numbers/Promised values the same way fetch_ used the
result from getBlockAtTimestamp.
- Around line 38-59: The code is calling rpc/getBlockAtTimestamp via a custom
fetchLogs function inside fetch_ instead of using the framework's
FetchOptions.getLogs; replace the custom log fetching by removing fetchLogs, rpc
and getBlockAtTimestamp usage and call options.getLogs(...) to fetch logs for
ROUTER with topics TOPIC_BUY and TOPIC_SELL (use
options.startTimestamp/options.endTimestamp or their block equivalents per
getLogs API), then parse the returned logs into buyRaw/sellRaw and continue
using dailyFees/dailyVolume as before; update references to fetchLogs, rpc, and
getBlockAtTimestamp so only options.getLogs and fetch_ remain.
- Around line 93-112: The breakdownMethodology uses a non-existent key
METRIC.SPOT_TRADING_VOLUME; fix by checking the METRIC enum and either add
SPOT_TRADING_VOLUME to the enum or replace METRIC.SPOT_TRADING_VOLUME with the
correct existing metric constant used elsewhere (e.g., the project’s canonical
volume metric), and update the description accordingly in breakdownMethodology;
also verify the adapter object matches the SimpleAdapter type (confirm whether
fetch should be named fetch or fetch_ and whether chains should be an array or a
single CHAIN value) and adjust the adapter properties (adapter.version,
adapter.fetch, adapter.chains, adapter.start, adapter.methodology,
adapter.breakdownMethodology) to the expected shape.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: b3aa5b8a-e82f-49c4-a77d-7e1f560f640d

📥 Commits

Reviewing files that changed from the base of the PR and between f2747e3 and 7d07e4f.

📒 Files selected for processing (1)
  • fees/priority-trade/index.ts

Comment on lines +25 to +36
async function getBlockAtTimestamp(timestamp: number): Promise<number> {
const latestHex: string = await rpc("eth_blockNumber", []);
let lo = 0, hi = parseInt(latestHex, 16);

while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
const block: any = await rpc("eth_getBlockByNumber", ["0x" + mid.toString(16), false]);
const ts = parseInt(block.timestamp, 16);
if (ts < timestamp) lo = mid + 1; else hi = mid;
}
return lo;
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Use FetchOptions.getFromBlock() and getToBlock() instead of custom binary search.

The FetchOptions object already provides getFromBlock() and getToBlock() methods that handle timestamp-to-block conversion. This custom binary search:

  1. Makes O(log n) RPC calls unnecessarily
  2. Bypasses framework's caching and optimizations
  3. May fail on chains with irregular block times (edge cases not handled)
Proposed fix
- async function getBlockAtTimestamp(timestamp: number): Promise<number> {
-   const latestHex: string = await rpc("eth_blockNumber", []);
-   let lo = 0, hi = parseInt(latestHex, 16);
-
-   while (lo < hi) {
-     const mid = Math.floor((lo + hi) / 2);
-     const block: any = await rpc("eth_getBlockByNumber", ["0x" + mid.toString(16), false]);
-     const ts = parseInt(block.timestamp, 16);
-     if (ts < timestamp) lo = mid + 1; else hi = mid;
-   }
-   return lo;
- }

Then in fetch_:

- const [fromBlock, toBlock] = await Promise.all([
-   getBlockAtTimestamp(options.startTimestamp),
-   getBlockAtTimestamp(options.endTimestamp),
- ]);
+ const [fromBlock, toBlock] = await Promise.all([
+   options.getFromBlock(),
+   options.getToBlock(),
+ ]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@fees/priority-trade/index.ts` around lines 25 - 36, The custom binary-search
helper getBlockAtTimestamp is redundant and should be removed; update fetch_ to
call FetchOptions.getFromBlock(timestamp) and FetchOptions.getToBlock(timestamp)
(or the appropriate getFromBlock()/getToBlock() overloads on the provided
FetchOptions instance) instead of invoking getBlockAtTimestamp and performing
RPCs directly, ensuring you rely on the framework’s caching/optimizations and
handle any returned block numbers/Promised values the same way fetch_ used the
result from getBlockAtTimestamp.

Comment on lines +38 to +59
async function fetchLogs(fromBlock: number, toBlock: number, topic: string): Promise<any[]> {
return rpc("eth_getLogs", [{
address: ROUTER,
fromBlock: "0x" + fromBlock.toString(16),
toBlock: "0x" + toBlock.toString(16),
topics: [topic],
}]);
}

const fetch_ = async (options: FetchOptions) => {
const dailyFees = options.createBalances();
const dailyVolume = options.createBalances();

const [fromBlock, toBlock] = await Promise.all([
getBlockAtTimestamp(options.startTimestamp),
getBlockAtTimestamp(options.endTimestamp),
]);

const [buyRaw, sellRaw] = await Promise.all([
fetchLogs(fromBlock, toBlock, TOPIC_BUY),
fetchLogs(fromBlock, toBlock, TOPIC_SELL),
]);
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Use options.getLogs() instead of custom RPC log fetching.

The FetchOptions object provides a getLogs() method that should be used instead of direct RPC calls. This ensures consistency with the framework and benefits from built-in optimizations.

Proposed fix using options.getLogs()
- async function fetchLogs(fromBlock: number, toBlock: number, topic: string): Promise<any[]> {
-   return rpc("eth_getLogs", [{
-     address: ROUTER,
-     fromBlock: "0x" + fromBlock.toString(16),
-     toBlock:   "0x" + toBlock.toString(16),
-     topics: [topic],
-   }]);
- }

// In fetch_:
- const [buyRaw, sellRaw] = await Promise.all([
-   fetchLogs(fromBlock, toBlock, TOPIC_BUY),
-   fetchLogs(fromBlock, toBlock, TOPIC_SELL),
- ]);
+ const [buyRaw, sellRaw] = await Promise.all([
+   options.getLogs({ target: ROUTER, topics: [TOPIC_BUY] }),
+   options.getLogs({ target: ROUTER, topics: [TOPIC_SELL] }),
+ ]);

This eliminates the need for custom rpc(), fetchLogs(), and getBlockAtTimestamp() functions entirely.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@fees/priority-trade/index.ts` around lines 38 - 59, The code is calling
rpc/getBlockAtTimestamp via a custom fetchLogs function inside fetch_ instead of
using the framework's FetchOptions.getLogs; replace the custom log fetching by
removing fetchLogs, rpc and getBlockAtTimestamp usage and call
options.getLogs(...) to fetch logs for ROUTER with topics TOPIC_BUY and
TOPIC_SELL (use options.startTimestamp/options.endTimestamp or their block
equivalents per getLogs API), then parse the returned logs into buyRaw/sellRaw
and continue using dailyFees/dailyVolume as before; update references to
fetchLogs, rpc, and getBlockAtTimestamp so only options.getLogs and fetch_
remain.

Comment on lines +93 to +112
const breakdownMethodology = {
Volume: {
[METRIC.SPOT_TRADING_VOLUME]: "ETH volume from token buys and sells executed via the Priority Trade Telegram bot.",
},
Fees: {
[METRIC.TRADING_FEES]: "1% trading fee charged on each swap executed through Priority Trade.",
},
Revenue: {
[METRIC.TRADING_FEES]: "Trading fees collected by the Priority Trade protocol.",
},
};

const adapter: SimpleAdapter = {
version: 2,
fetch: fetch_,
chains: [CHAIN.MEGAETH],
start: "2026-02-04",
methodology,
breakdownMethodology,
};
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

breakdownMethodology references non-existent METRIC.SPOT_TRADING_VOLUME.

The breakdownMethodology object uses METRIC.SPOT_TRADING_VOLUME as a key, which doesn't exist in the METRIC enum. This will either fail at compile time or result in undefined as the key.

Additionally, the adapter structure uses fetch and chains at the top level. Verify this matches the expected SimpleAdapter structure for single-chain adapters.

Proposed fix aligned with METRIC enum changes

If adding SPOT_TRADING_VOLUME to the METRIC enum:

// No changes needed to breakdownMethodology

If removing metric labels for volume:

 const breakdownMethodology = {
-  Volume: {
-    [METRIC.SPOT_TRADING_VOLUME]: "ETH volume from token buys and sells executed via the Priority Trade Telegram bot.",
-  },
+  Volume: "ETH volume from token buys and sells executed via the Priority Trade Telegram bot.",
   Fees: {
     [METRIC.TRADING_FEES]: "1% trading fee charged on each swap executed through Priority Trade.",
   },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@fees/priority-trade/index.ts` around lines 93 - 112, The breakdownMethodology
uses a non-existent key METRIC.SPOT_TRADING_VOLUME; fix by checking the METRIC
enum and either add SPOT_TRADING_VOLUME to the enum or replace
METRIC.SPOT_TRADING_VOLUME with the correct existing metric constant used
elsewhere (e.g., the project’s canonical volume metric), and update the
description accordingly in breakdownMethodology; also verify the adapter object
matches the SimpleAdapter type (confirm whether fetch should be named fetch or
fetch_ and whether chains should be an array or a single CHAIN value) and adjust
the adapter properties (adapter.version, adapter.fetch, adapter.chains,
adapter.start, adapter.methodology, adapter.breakdownMethodology) to the
expected shape.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants