Skip to content

Track fees for Chia Chains - #5454

Closed
PatelPrinci wants to merge 6 commits into
DefiLlama:masterfrom
LamprosDAO:Chia-fees
Closed

PatelPrinci wants to merge 6 commits into
DefiLlama:masterfrom
LamprosDAO:Chia-fees

Conversation

@PatelPrinci

@PatelPrinci PatelPrinci commented Jan 1, 2026

Copy link
Copy Markdown
Contributor

Addresses issue: #2622

Summary by CodeRabbit

  • New Features

    • Added Chia blockchain support with transaction fee tracking
    • Integrated multi-source fee data aggregation from external block explorers
  • Chores

    • Minor code formatting updates

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

@ghost

ghost commented Jan 1, 2026

Copy link
Copy Markdown

The chia.ts adapter exports:

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

🦙 Running CHIA.TS adapter 🦙
---------------------------------------------------
Start Date:	Wed, 31 Dec 2025 00:00:00 GMT
End Date:	Thu, 01 Jan 2026 00:00:00 GMT
---------------------------------------------------

------ ERROR ------
undefined
Request failed with status code 524

@bheluga bheluga self-assigned this Jan 5, 2026

@bheluga bheluga left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@PatelPrinci Thanks for the PR.
Its failing with 524 , probably website isnt functional/synced.
Any other alternative?

@ghost

ghost commented Jan 12, 2026

Copy link
Copy Markdown

The chia.ts adapter exports:

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

🦙 Running CHIA.TS adapter 🦙
---------------------------------------------------
Start Date:	Sun, 11 Jan 2026 00:00:00 GMT
End Date:	Mon, 12 Jan 2026 00:00:00 GMT
---------------------------------------------------

Trying Chia API: xchscan
Trying Chia API: chiaexplorer
Trying Chia API: spacefarmers
Trying Chia API: alltheblocks
All Chia APIs failed. Reasons: Request failed with status code 524; Request failed with status code 522; getaddrinfo ENOTFOUND api2.spacefarmers.io; Request failed with status code 404
Returning 0 fees for 2026-01-11 due to API unavailability
CHIA 👇
Backfill start time: 19/3/2021
Daily fees: 0.00

@ghost

ghost commented Jan 12, 2026

Copy link
Copy Markdown

The chia.ts adapter exports:

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

🦙 Running CHIA.TS adapter 🦙
---------------------------------------------------
Start Date:	Sun, 11 Jan 2026 00:00:00 GMT
End Date:	Mon, 12 Jan 2026 00:00:00 GMT
---------------------------------------------------

Trying Chia API: xchscan
Trying Chia API: chiaexplorer
Trying Chia API: spacefarmers
Trying Chia API: alltheblocks
All Chia APIs failed. Reasons: socket hang up; Request failed with status code 522; getaddrinfo ENOTFOUND api2.spacefarmers.io; Request failed with status code 404
Returning 0 fees for 2026-01-11 due to API unavailability
CHIA 👇
Backfill start time: 19/3/2021
Daily fees: 0.00

@ghost

ghost commented Jan 12, 2026

Copy link
Copy Markdown

The chia.ts adapter exports:

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

🦙 Running CHIA.TS adapter 🦙
---------------------------------------------------
Start Date:	Sun, 11 Jan 2026 00:00:00 GMT
End Date:	Mon, 12 Jan 2026 00:00:00 GMT
---------------------------------------------------

Trying Chia API: xchscan
Trying Chia API: chiaexplorer
Trying Chia API: spacefarmers
Trying Chia API: alltheblocks
All Chia APIs failed. Reasons: Request failed with status code 524; Request failed with status code 522; getaddrinfo ENOTFOUND api2.spacefarmers.io; Request failed with status code 404
Returning 0 fees for 2026-01-11 due to API unavailability
CHIA 👇
Backfill start time: 19/3/2021
Daily fees: 0.00

@PatelPrinci

Copy link
Copy Markdown
Contributor Author

@bheluga here i haven't modified liquidity.ts then why it shows error?

@bheluga

bheluga commented Jan 21, 2026

Copy link
Copy Markdown
Member

@bheluga here i haven't modified liquidity.ts then why it shows error?

@PatelPrinci mostly because the commit which was merged by other contributors had ts errors, you need not worry about that.
Also wrt chia, usually when data sources arent working, we try to find new sources . Catching error and showing as 0 isnt best solution

@coderabbitai

coderabbitai Bot commented Jan 22, 2026

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

The PR introduces Chia blockchain support by adding a new fee data adapter that aggregates transaction fees from multiple external block data APIs, and extends the chain enum to include CHIA as a supported chain.

Changes

Cohort / File(s) Summary
Chain Enumeration Support
helpers/chains.ts
Added CHIA = "chia" member to the CHAIN enum to register Chia as a supported blockchain.
Chia Fee Adapter
fees/chia.ts
New adapter implementation that aggregates XCH transaction fees from four external APIs (xchscan, chiaexplorer, spacefarmers, alltheblocks). Includes concurrent API querying with first-successful-result strategy, XCH unit conversion (dividing by 1e12), date window filtering with 14-day historical limit, and fallback error handling.
Minor Formatting
helpers/liquity.ts
Whitespace/line break adjustment around LiquityV2Config.stableTokenAbi declaration; no semantic changes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • g1nt0ki

Poem

🐰 Hops with glee, a Chia feast appears,
Four APIs queried without fears,
XCH fees dance in perfect formation,
Chains grow longer—blockchain elation!

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is severely incomplete. It only references an issue link without providing any substantive explanation of changes, implementation details, or context about the adapter. Provide a detailed description of the changes including what the Chia fee adapter does, which APIs it uses, the implementation approach, and any known limitations or issues (such as current API failures).
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Track fees for Chia Chains' clearly and concisely summarizes the main change, which is the addition of fee-tracking support for Chia chains as evidenced by the new fees/chia.ts adapter file.
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

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.

@ghost

ghost commented Jan 22, 2026

Copy link
Copy Markdown

The chia.ts adapter exports:

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

🦙 Running CHIA.TS adapter 🦙
---------------------------------------------------
Start Date:	Wed, 21 Jan 2026 00:00:00 GMT
End Date:	Thu, 22 Jan 2026 00:00:00 GMT
---------------------------------------------------

Trying Chia API: xchscan
Trying Chia API: chiaexplorer
Trying Chia API: spacefarmers
Trying Chia API: alltheblocks
All Chia APIs failed. Reasons: Request failed with status code 524; Request failed with status code 522; getaddrinfo ENOTFOUND api2.spacefarmers.io; Request failed with status code 404
Returning 0 fees for 2026-01-21 due to API unavailability
CHIA 👇
Backfill start time: 19/3/2021
Daily fees: 0.00

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@fees/chia.ts`:
- Around line 115-121: The adapter's declared start date ("start" on the adapter
object) is too old for the upstream APIs' ~14-day historical retention, causing
backfills to fail; update the adapter.start value in the adapter object (where
adapter, fetch, CHAIN.CHIA, and ProtocolType.CHAIN are defined) to a recent date
within the API retention window (e.g., within the last 14 days) or add a clear
comment/documentation next to the adapter.start field explaining the API
limitation and that only recent history is available so backfills beyond that
range will return empty/zero values.
- Around line 70-80: The code currently returns zero fees for dates older than
historicalLimit which masks missing data; replace the early-return block that
creates dailyFees (using historicalLimit, dailyFees, options.createBalances())
with throwing a descriptive Error (e.g., "Historical fee data unavailable for
YYYY-MM-DD: Chia APIs only expose ~14 days") so callers can handle/skip
backfills, and update the adapter start date (currently "2021-03-19") to a
realistic earliest-available date (or add adapter metadata documenting the
14-day limitation) to prevent attempts to backfill multi-year data.
- Around line 103-112: The code currently swallows API failures by logging and
returning zero fees (using results -> failedReasons and returning dailyFees from
options.createBalances() with addCGToken('chia', 0)); change this to throw an
error instead: build an informative Error (include failedReasons.join('; ') and
the dayStart date) and throw it so callers can handle retries/alerts rather than
receiving misleading zero fees; remove the return of dailyFees in the
all-APIs-failed branch.
🧹 Nitpick comments (3)
fees/chia.ts (3)

5-8: Remove unused Transaction interface.

The Transaction interface is defined but never used in this file. The code uses any[] for blocks and accesses fields dynamically via apiSource.timestampField and apiSource.feeField.

🧹 Proposed fix
 import { CHAIN } from "../helpers/chains";
 import { httpGet } from "../utils/fetchURL";
 
-interface Transaction {
-  fee: string;
-  timestamp: number;
-}
-
 // Multiple API sources for Chia block data

82-101: Consider sequential fallback instead of parallel calls to all APIs.

Currently, all 4 APIs are called simultaneously even though only one successful result is needed. This generates unnecessary load on external services. Consider using Promise.any() or a sequential fallback pattern that stops after the first success.

♻️ Proposed fix using sequential fallback
-  const apiPromises = API_SOURCES.map(apiSource =>
-    fetchFromApi(apiSource, dayStart, dayEnd).then(totalFeeXCH => ({
-      apiSource,
-      totalFeeXCH
-    }))
-  );
-
-  const results = await Promise.allSettled(apiPromises);
-
-  // Find the first fulfilled result
-  for (const result of results) {
-    if (result.status === 'fulfilled') {
-      const { apiSource, totalFeeXCH } = result.value;
-      console.log(`Successfully fetched fee data from ${apiSource.name}: ${totalFeeXCH} XCH`);
-
-      const dailyFees = options.createBalances();
-      dailyFees.addCGToken('chia', totalFeeXCH);
-      return { dailyFees };
-    }
-  }
+  const errors: string[] = [];
+  
+  for (const apiSource of API_SOURCES) {
+    try {
+      const totalFeeXCH = await fetchFromApi(apiSource, dayStart, dayEnd);
+      console.log(`Successfully fetched fee data from ${apiSource.name}: ${totalFeeXCH} XCH`);
+      
+      const dailyFees = options.createBalances();
+      dailyFees.addCGToken('chia', totalFeeXCH);
+      return { dailyFees };
+    } catch (error) {
+      const message = error instanceof Error ? error.message : String(error);
+      errors.push(`${apiSource.name}: ${message}`);
+      console.log(`${apiSource.name} failed: ${message}`);
+    }
+  }

42-63: Add timeout to API requests and improve fee parsing.

Two concerns:

  1. No timeout: httpGet calls could hang indefinitely if an API is unresponsive. Consider adding a timeout option.

  2. Fee parsing: parseInt(fee || 0) has issues:

    • Missing radix parameter (should be parseInt(fee, 10))
    • If fee is already a number, parseInt is unnecessary
    • parseInt(0) returns 0, but parseInt('0') also works, so fee || '0' would be clearer
  3. Block limit: The 50-block limit may not capture all blocks in a day if block production is high. Consider whether pagination is needed.

♻️ Proposed fix for timeout and parsing
 const fetchFromApi = async (apiSource: typeof API_SOURCES[0], dayStart: number, dayEnd: number): Promise<number> => {
   console.log(`Trying Chia API: ${apiSource.name}`);
-  const response = await httpGet(apiSource.url);
+  const response = await httpGet(apiSource.url, { timeout: 30000 });
 
   if (!response || !response[apiSource.dataPath]) {
     throw new Error(`No ${apiSource.dataPath} data available from ${apiSource.name} API`);
@@ const totalFeeMojos = dayBlocks.reduce((sum: number, block: any) => {
   const totalFeeMojos = dayBlocks.reduce((sum: number, block: any) => {
     const fee = block[apiSource.feeField];
-    return sum + parseInt(fee || 0);
+    return sum + (typeof fee === 'number' ? fee : parseInt(fee || '0', 10));
   }, 0);

Comment thread fees/chia.ts
Comment on lines +70 to +80
// API limitations for historical data
// Most Chia APIs only provide recent blocks (approximately last 10-14 days)
const historicalLimit = 14 * 24 * 60 * 60 * 1000; // 14 days in milliseconds

if (dayStart < now - historicalLimit) {
// For data older than 14 days, most APIs don't provide block data
console.log(`Historical fee data not available for ${new Date(dayStart).toISOString().slice(0, 10)} (API limitation - most Chia APIs only provide recent blocks)`);
const dailyFees = options.createBalances();
dailyFees.addCGToken('chia', 0);
return { dailyFees };
}

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

Historical data limitation should throw an error, not return 0.

Same concern as above — returning 0 fees for historical data masks the limitation and produces incorrect aggregate metrics. Consider either:

  1. Throwing an error indicating historical data is unavailable
  2. Documenting this limitation in the adapter metadata and having the system skip historical backfills

Additionally, the start date is set to "2021-03-19" (line 119), which will trigger backfill attempts for ~5 years of data that this adapter cannot provide.

🔧 Proposed fix — option 1: throw error
   if (dayStart < now - historicalLimit) {
-    // For data older than 14 days, most APIs don't provide block data
-    console.log(`Historical fee data not available for ${new Date(dayStart).toISOString().slice(0, 10)} (API limitation - most Chia APIs only provide recent blocks)`);
-    const dailyFees = options.createBalances();
-    dailyFees.addCGToken('chia', 0);
-    return { dailyFees };
+    throw new Error(`Historical fee data not available for ${new Date(dayStart).toISOString().slice(0, 10)} - Chia APIs only provide recent blocks (last ~14 days)`);
   }
📝 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
// API limitations for historical data
// Most Chia APIs only provide recent blocks (approximately last 10-14 days)
const historicalLimit = 14 * 24 * 60 * 60 * 1000; // 14 days in milliseconds
if (dayStart < now - historicalLimit) {
// For data older than 14 days, most APIs don't provide block data
console.log(`Historical fee data not available for ${new Date(dayStart).toISOString().slice(0, 10)} (API limitation - most Chia APIs only provide recent blocks)`);
const dailyFees = options.createBalances();
dailyFees.addCGToken('chia', 0);
return { dailyFees };
}
// API limitations for historical data
// Most Chia APIs only provide recent blocks (approximately last 10-14 days)
const historicalLimit = 14 * 24 * 60 * 60 * 1000; // 14 days in milliseconds
if (dayStart < now - historicalLimit) {
throw new Error(`Historical fee data not available for ${new Date(dayStart).toISOString().slice(0, 10)} - Chia APIs only provide recent blocks (last ~14 days)`);
}
🤖 Prompt for AI Agents
In `@fees/chia.ts` around lines 70 - 80, The code currently returns zero fees for
dates older than historicalLimit which masks missing data; replace the
early-return block that creates dailyFees (using historicalLimit, dailyFees,
options.createBalances()) with throwing a descriptive Error (e.g., "Historical
fee data unavailable for YYYY-MM-DD: Chia APIs only expose ~14 days") so callers
can handle/skip backfills, and update the adapter start date (currently
"2021-03-19") to a realistic earliest-available date (or add adapter metadata
documenting the 14-day limitation) to prevent attempts to backfill multi-year
data.

Comment thread fees/chia.ts
Comment on lines +103 to +112
// All APIs failed - log the reasons
const failedReasons = results
.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
.map(result => result.reason instanceof Error ? result.reason.message : String(result.reason));

console.log(`All Chia APIs failed. Reasons:`, failedReasons.join('; '));
console.log(`Returning 0 fees for ${new Date(dayStart).toISOString().slice(0, 10)} due to API unavailability`);
const dailyFees = options.createBalances();
dailyFees.addCGToken('chia', 0);
return { dailyFees };

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

Returning 0 fees on API failure masks data unavailability — throw an error instead.

Per reviewer feedback in the PR comments, "when existing APIs are unavailable, the preferred approach is to find new reliable data sources rather than simply catching the error and returning 0 fees. Returning 0 is not the best solution." Silently returning 0 produces misleading metrics and hides infrastructure issues.

The adapter should throw an error when all APIs fail, allowing the caller to handle it appropriately (retry, alert, etc.).

🔧 Proposed fix
   // All APIs failed - log the reasons
   const failedReasons = results
     .filter((result): result is PromiseRejectedResult => result.status === 'rejected')
     .map(result => result.reason instanceof Error ? result.reason.message : String(result.reason));
 
-  console.log(`All Chia APIs failed. Reasons:`, failedReasons.join('; '));
-  console.log(`Returning 0 fees for ${new Date(dayStart).toISOString().slice(0, 10)} due to API unavailability`);
-  const dailyFees = options.createBalances();
-  dailyFees.addCGToken('chia', 0);
-  return { dailyFees };
+  throw new Error(`All Chia APIs failed. Reasons: ${failedReasons.join('; ')}`);
 };
📝 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
// All APIs failed - log the reasons
const failedReasons = results
.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
.map(result => result.reason instanceof Error ? result.reason.message : String(result.reason));
console.log(`All Chia APIs failed. Reasons:`, failedReasons.join('; '));
console.log(`Returning 0 fees for ${new Date(dayStart).toISOString().slice(0, 10)} due to API unavailability`);
const dailyFees = options.createBalances();
dailyFees.addCGToken('chia', 0);
return { dailyFees };
// All APIs failed - log the reasons
const failedReasons = results
.filter((result): result is PromiseRejectedResult => result.status === 'rejected')
.map(result => result.reason instanceof Error ? result.reason.message : String(result.reason));
throw new Error(`All Chia APIs failed. Reasons: ${failedReasons.join('; ')}`);
🤖 Prompt for AI Agents
In `@fees/chia.ts` around lines 103 - 112, The code currently swallows API
failures by logging and returning zero fees (using results -> failedReasons and
returning dailyFees from options.createBalances() with addCGToken('chia', 0));
change this to throw an error instead: build an informative Error (include
failedReasons.join('; ') and the dayStart date) and throw it so callers can
handle retries/alerts rather than receiving misleading zero fees; remove the
return of dailyFees in the all-APIs-failed branch.

Comment thread fees/chia.ts
Comment on lines +115 to +121
const adapter: Adapter = {
version: 1,
fetch,
chains: [CHAIN.CHIA],
start: "2021-03-19", // Chia mainnet launch date
protocolType: ProtocolType.CHAIN,
};

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 | 🟡 Minor

LGTM on adapter structure, but start date conflicts with API limitations.

The adapter correctly uses CHAIN.CHIA and ProtocolType.CHAIN. However, the start date of "2021-03-19" spans ~5 years while the APIs only provide ~14 days of historical data. This will result in failed or zero-value backfills for most of the historical range. Consider setting start to a recent date or documenting this limitation clearly.

🤖 Prompt for AI Agents
In `@fees/chia.ts` around lines 115 - 121, The adapter's declared start date
("start" on the adapter object) is too old for the upstream APIs' ~14-day
historical retention, causing backfills to fail; update the adapter.start value
in the adapter object (where adapter, fetch, CHAIN.CHIA, and ProtocolType.CHAIN
are defined) to a recent date within the API retention window (e.g., within the
last 14 days) or add a clear comment/documentation next to the adapter.start
field explaining the API limitation and that only recent history is available so
backfills beyond that range will return empty/zero values.

@bheluga

bheluga commented Apr 7, 2026

Copy link
Copy Markdown
Member

closing as stale

@bheluga bheluga closed this Apr 7, 2026
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.

2 participants