Skip to content

Mokee Protocol TVL adapter#18721

Open
henrymikel wants to merge 9 commits intoDefiLlama:mainfrom
henrymikel:main
Open

Mokee Protocol TVL adapter#18721
henrymikel wants to merge 9 commits intoDefiLlama:mainfrom
henrymikel:main

Conversation

@henrymikel
Copy link
Copy Markdown

@henrymikel henrymikel commented Apr 11, 2026

MOKEE Protocol is the first non-custodial crypto fail-safe protocol. Users deposit native tokens into personal vaults, designate heirs, and set an inactivity threshold. Live on BSC, Base, Ethereum, Polygon, Arbitrum, and Optimism. Contracts verified on all block explorers.

Summary by CodeRabbit

New Features

  • Added comprehensive TVL (Total Value Locked) tracking for MOKEE contracts across six major blockchain networks: BSC, Base, Ethereum, Polygon, Arbitrum, and Optimism. The system monitors deposits, withdrawals, and inheritance claims to calculate accurate network-specific TVL metrics, enabling real-time visibility into total protocol value distribution and liquidity across all supported blockchains.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 11, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

A new TVL computation module for MOKEE contracts has been created. It fetches deposit, withdrawal, and inheritance-claim events from blockchain logs across six chains, calculates total value locked using the formula (totalDeposited - totalWithdrawn - totalClaimed), and exports chain-specific adapters.

Changes

Cohort / File(s) Summary
MOKEE TVL Module
index (4).js
New TVL calculator for MOKEE contracts featuring per-chain metadata (contract addresses, fromBlock), event ABIs for deposits/withdrawals/claims, a getChainTVL function that aggregates events via getLogs, computes TVL with BigInt arithmetic, and per-chain adapters for BSC, Base, Ethereum, Polygon, Arbitrum, and Optimism.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as API Caller
    participant Handler as getChainTVL
    participant Blockchain as Blockchain Logs
    participant Calc as TVL Calculator

    Caller->>Handler: call with api.chain
    Handler->>Handler: select contract by chain
    
    par Parallel Event Fetching
        Handler->>Blockchain: getLogs(deposit events)
        Handler->>Blockchain: getLogs(withdrawal events)
        Handler->>Blockchain: getLogs(claim events)
    end
    
    Blockchain-->>Handler: deposit amounts
    Blockchain-->>Handler: withdrawal amounts
    Blockchain-->>Handler: claim amounts
    
    Handler->>Calc: sum all amounts (BigInt)
    Calc->>Calc: calculate TVL = deposits - withdrawals - claims
    Calc->>Calc: clamp negative to 0
    Calc->>Calc: convert from 18-decimal units
    Calc-->>Handler: numeric TVL value
    
    Handler-->>Caller: return TVL for native token
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

🐰 Across six chains the MOKEE spreads,
With logs and claims and coins widespread,
We sum the deposits, subtract the dust,
TVL calculated—in BigInt we trust! ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides protocol context (non-custodial fail-safe, vaults, heirs, inactivity threshold) and deployment chains, but is largely incomplete relative to the template's extensive new listing requirements. Complete the template sections: name, Twitter link, audit links, website, logo, TVL, treasury addresses, chain list, Coingecko/Coinmarketcap IDs, description, token details, category, oracle info, forked-from, methodology, and Github org.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Mokee Protocol TVL adapter' clearly and concisely summarizes the main change: adding a TVL adapter for the MOKEE Protocol across multiple chains.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

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: 2

🧹 Nitpick comments (1)
index.js (1)

42-61: Run log reads concurrently to reduce RPC latency and timeout risk.

These three calls are independent and can be awaited via Promise.all.

Refactor
-  const deposits = await getLogs({
-    api,
-    target: address,
-    fromBlock,
-    eventAbi: DEPOSIT_EVENT,
-  });
-
-  const withdrawals = await getLogs({
-    api,
-    target: address,
-    fromBlock,
-    eventAbi: WITHDRAW_EVENT,
-  });
-
-  const claims = await getLogs({
-    api,
-    target: address,
-    fromBlock,
-    eventAbi: CLAIMED_EVENT,
-  });
+  const [deposits, withdrawals, claims] = await Promise.all([
+    getLogs({ api, target: address, fromBlock, eventAbi: DEPOSIT_EVENT }),
+    getLogs({ api, target: address, fromBlock, eventAbi: WITHDRAW_EVENT }),
+    getLogs({ api, target: address, fromBlock, eventAbi: CLAIMED_EVENT }),
+  ]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@index.js` around lines 42 - 61, The three independent getLogs calls (for
DEPOSIT_EVENT, WITHDRAW_EVENT, CLAIMED_EVENT) should be executed concurrently to
reduce RPC latency: replace the sequential awaits for deposits, withdrawals, and
claims with a Promise.all that invokes getLogs for each event (referencing
getLogs and the variables deposits, withdrawals, claims and constants
DEPOSIT_EVENT, WITHDRAW_EVENT, CLAIMED_EVENT) and destructure the resulting
array into those three variables; ensure errors are still caught/propagated as
before.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@index.js`:
- Line 79: The computed tvl (const tvl = totalDeposited - totalWithdrawn -
totalClaimed) can become negative; add a guard immediately after that
calculation to prevent writing invalid balances: detect if tvl < 0 and handle it
(e.g., set tvl = 0 or skip/persist no-update and emit a warning/log) before any
subsequent balance write operations; update the code paths that consume tvl so
they use the guarded value and include a descriptive log mentioning
totalDeposited, totalWithdrawn, and totalClaimed when the guard triggers.
- Line 93: The import at the top uses a non-existent "../helper/balance" and the
sumSingleBalance call on line with sumSingleBalance(balances, nativeToken,
tvl.toString(), 18) is wrong: update the import to the correct helper (e.g.,
"../helper/balances" or the SDK helper you actually use) and change the call to
convert the BigInt wei `tvl` into a human token amount before summing (divide by
1e18), then call the proper helper signature—either
sdk.util.sumSingleBalance(balances, chainString, tokenSymbol, amountString) if
using SDK (supply a chain string as the 4th arg) or sumSingleBalance(balances,
nativeToken, amountString) if using the local helper (remove the numeric 4th
arg). Ensure you pass the computed decimal amount as a string (e.g.,
(Number(tvl) / 1e18).toString() or use BigInt-safe division/formatting) and
reference the symbols sumSingleBalance, sdk.util.sumSingleBalance, balances,
nativeToken, and tvl when making the fixes.

---

Nitpick comments:
In `@index.js`:
- Around line 42-61: The three independent getLogs calls (for DEPOSIT_EVENT,
WITHDRAW_EVENT, CLAIMED_EVENT) should be executed concurrently to reduce RPC
latency: replace the sequential awaits for deposits, withdrawals, and claims
with a Promise.all that invokes getLogs for each event (referencing getLogs and
the variables deposits, withdrawals, claims and constants DEPOSIT_EVENT,
WITHDRAW_EVENT, CLAIMED_EVENT) and destructure the resulting array into those
three variables; ensure errors are still caught/propagated as before.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6c7babbf-f38e-4cfc-9633-eea96e64b774

📥 Commits

Reviewing files that changed from the base of the PR and between 93edba3 and 6d7424d.

📒 Files selected for processing (1)
  • index.js

Comment thread index.js Outdated
totalClaimed += BigInt(log.amount.toString());
});

const tvl = totalDeposited - totalWithdrawn - totalClaimed;
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

Add a guard for negative TVL before writing balances.

If event/accounting assumptions drift, this can go negative and emit invalid balances. Guard explicitly.

Safety guard
   const tvl = totalDeposited - totalWithdrawn - totalClaimed;
+  if (tvl < 0n) {
+    throw new Error(`Negative TVL computed for ${chain}: ${tvl.toString()}`);
+  }
📝 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
const tvl = totalDeposited - totalWithdrawn - totalClaimed;
const tvl = totalDeposited - totalWithdrawn - totalClaimed;
if (tvl < 0n) {
throw new Error(`Negative TVL computed for ${chain}: ${tvl.toString()}`);
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@index.js` at line 79, The computed tvl (const tvl = totalDeposited -
totalWithdrawn - totalClaimed) can become negative; add a guard immediately
after that calculation to prevent writing invalid balances: detect if tvl < 0
and handle it (e.g., set tvl = 0 or skip/persist no-update and emit a
warning/log) before any subsequent balance write operations; update the code
paths that consume tvl so they use the guarded value and include a descriptive
log mentioning totalDeposited, totalWithdrawn, and totalClaimed when the guard
triggers.

Comment thread index.js Outdated
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: 1

🧹 Nitpick comments (2)
index (1).js (2)

44-52: Consider using api.chain instead of passing chain separately.

The api object already contains chain information via api.chain. This would eliminate the need to pass the chain parameter explicitly and reduce the chance of mismatches.

♻️ Proposed refactor
-async function getChainTVL(api, chain) {
-  const contract = CONTRACTS[chain];
+async function getChainTVL(api) {
+  const chain = api.chain;
+  const contract = CONTRACTS[chain];

And update the exports:

   bsc: {
-    tvl: (api) => getChainTVL(api, "bsc"),
+    tvl: getChainTVL,
   },

Apply similarly for all other chains.

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

In `@index` (1).js around lines 44 - 52, The getChainTVL function currently
accepts a chain parameter but the api object already carries chain info; update
getChainTVL to read the chain from api.chain instead of the chain argument
(remove the chain parameter usage), use api.chain when looking up
CONTRACTS[chain] and anywhere else chain is passed to helper calls like getLogs,
and update any call sites/exports that pass chain explicitly to instead pass
only api (or adjust calls to stop passing chain) to avoid mismatches between the
passed chain and api.chain; ensure function signature and all references to the
removed parameter (function getChainTVL, CONTRACTS lookup, getLogs invocations)
are updated accordingly.

79-83: Potential precision loss for very large TVL values.

Number(tvl) converts the BigInt to a JavaScript Number, which can only safely represent integers up to 2^53 (~9 million ETH). For most realistic protocols this is fine, but for safety, consider performing integer division in BigInt space first:

♻️ Safer precision handling
-  // Convert from Wei (18 decimals) to human readable
-  const tvlInEther = Number(tvl) / 1e18;
+  // Convert from Wei (18 decimals) to human readable
+  // Perform integer division in BigInt space to preserve precision
+  const wholePart = Number(tvl / 10n ** 18n);
+  const fractionalPart = Number(tvl % 10n ** 18n) / 1e18;
+  const tvlInEther = wholePart + fractionalPart;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@index` (1).js around lines 79 - 83, The code converts tvl (a BigInt) to a JS
Number causing precision loss for large values; instead perform arithmetic in
BigInt and only convert to a safe representation: compute const tvlBig =
BigInt(tvl), const intPart = tvlBig / 10n**18n, const frac = tvlBig % 10n**18n
and then set balances[NATIVE_TOKENS[chain]] to a string like
`${intPart}.${frac.toString().padStart(18,'0')}` (or use a small utility to
produce a decimal string) so tvlInEther precision is preserved when assigning to
balances.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@index` (1).js:
- Around line 3-28: The CONTRACTS map contains unverified or missing addresses
(see keys bsc, ethereum, optimism) and potentially incorrect fromBlock values;
please verify each contract address on the respective chain explorer (BscScan,
Etherscan, Optimistic Etherscan) and update CONTRACTS with the verified on-chain
address and the actual deployment block for fromBlock (or replace with a
verified address), and if source code cannot be verified add a clear comment or
flag next to the corresponding key (e.g., bsc, ethereum, optimism) indicating
"unverified" so consumers of CONTRACTS know not to trust it.

---

Nitpick comments:
In `@index` (1).js:
- Around line 44-52: The getChainTVL function currently accepts a chain
parameter but the api object already carries chain info; update getChainTVL to
read the chain from api.chain instead of the chain argument (remove the chain
parameter usage), use api.chain when looking up CONTRACTS[chain] and anywhere
else chain is passed to helper calls like getLogs, and update any call
sites/exports that pass chain explicitly to instead pass only api (or adjust
calls to stop passing chain) to avoid mismatches between the passed chain and
api.chain; ensure function signature and all references to the removed parameter
(function getChainTVL, CONTRACTS lookup, getLogs invocations) are updated
accordingly.
- Around line 79-83: The code converts tvl (a BigInt) to a JS Number causing
precision loss for large values; instead perform arithmetic in BigInt and only
convert to a safe representation: compute const tvlBig = BigInt(tvl), const
intPart = tvlBig / 10n**18n, const frac = tvlBig % 10n**18n and then set
balances[NATIVE_TOKENS[chain]] to a string like
`${intPart}.${frac.toString().padStart(18,'0')}` (or use a small utility to
produce a decimal string) so tvlInEther precision is preserved when assigning to
balances.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: a47e373a-c1c7-40b7-bc9a-a6cc8086b9ea

📥 Commits

Reviewing files that changed from the base of the PR and between 6d7424d and 62cbbc6.

📒 Files selected for processing (1)
  • index (1).js

Comment thread index (1).js
@henrymikel
Copy link
Copy Markdown
Author

All contracts are verified V11 deployments on their respective block explorers. Links added as comments in the code. BSC, ETH, and Optimism addresses are confirmed deployed and verified.

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: 1

🧹 Nitpick comments (1)
index (2).js (1)

54-56: Add defensive guard for unsupported chain keys

Destructuring contract without a guard will throw if api.chain is unexpected. Low risk in normal flow, but easy to harden.

Small defensive patch
   const chain = api.chain;
   const contract = CONTRACTS[chain];
+  if (!contract) throw new Error(`Unsupported chain for mokee adapter: ${chain}`);
   const { address, fromBlock } = contract;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@index` (2).js around lines 54 - 56, The code destructures CONTRACTS[chain]
into address and fromBlock without checking the lookup; add a defensive guard
around CONTRACTS[chain] (the variables CONTRACTS, chain, and contract) so if
CONTRACTS[chain] is undefined you bail out (throw a clear error or return early)
before trying to destructure, then proceed to const { address, fromBlock } =
contract; to avoid runtime exceptions when api.chain/chain is unsupported.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@index` (2).js:
- Around line 67-77: The code iterates deposits/withdrawals/claims and does
BigInt(log.amount.toString()), but when logs come from getLogs({ eventAbi })
they are LogDescription objects whose parsed params live under log.args, so
change the accesses to use log.args.amount (e.g.,
BigInt(log.args.amount.toString())) or alternatively request parsed args by
calling getLogs with onlyArgs: true; also add a null/undefined guard before
toString() to avoid runtime TypeError and keep variables
totalDeposited/totalWithdrawn/totalClaimed unchanged.

---

Nitpick comments:
In `@index` (2).js:
- Around line 54-56: The code destructures CONTRACTS[chain] into address and
fromBlock without checking the lookup; add a defensive guard around
CONTRACTS[chain] (the variables CONTRACTS, chain, and contract) so if
CONTRACTS[chain] is undefined you bail out (throw a clear error or return early)
before trying to destructure, then proceed to const { address, fromBlock } =
contract; to avoid runtime exceptions when api.chain/chain is unsupported.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: b596e139-3160-40f7-bd6f-f14fe971b176

📥 Commits

Reviewing files that changed from the base of the PR and between 62cbbc6 and 320e534.

📒 Files selected for processing (1)
  • index (2).js

Comment thread index (2).js
Comment on lines +67 to +77
deposits.forEach((log) => {
totalDeposited += BigInt(log.amount.toString());
});

withdrawals.forEach((log) => {
totalWithdrawn += BigInt(log.amount.toString());
});

claims.forEach((log) => {
totalClaimed += BigInt(log.amount.toString());
});
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 | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "1) Verify getLogs return shape"
GETLOGS_FILE="$(fd -p getLogs.js | head -n1)"
echo "getLogs file: ${GETLOGS_FILE}"
sed -n '1,140p' "${GETLOGS_FILE}" | nl -ba | sed -n '1,140p'

echo
echo "2) Find direct event-field access patterns in adapters"
rg -nP --type=js '\blog\.amount\b'

echo
echo "3) Find args-based event access patterns in adapters"
rg -nP --type=js '\blog\.args\.amount\b'

Repository: DefiLlama/DefiLlama-Adapters

Length of output: 209


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== 1) Find and read getLogs.js ==="
GETLOGS_FILE="$(fd -p getLogs.js | head -n1)"
echo "getLogs file: ${GETLOGS_FILE}"
if [ -n "$GETLOGS_FILE" ]; then
  echo "Content:"
  cat -n "$GETLOGS_FILE" | head -n 150
fi

echo ""
echo "=== 2) Locate index (2).js ==="
INDEX_FILE="$(fd -p 'index.*2.*\.js$' | head -n1)"
echo "Found index file: ${INDEX_FILE}"
if [ -n "$INDEX_FILE" ]; then
  echo "Content (lines 60-85):"
  sed -n '60,85p' "$INDEX_FILE" | cat -n
fi

echo ""
echo "=== 3) Find log.amount patterns in adapters ==="
rg -n 'log\.amount' --type=js | head -n 20

echo ""
echo "=== 4) Find log.args.amount patterns in adapters ==="
rg -n 'log\.args\.amount' --type=js | head -n 20

Repository: DefiLlama/DefiLlama-Adapters

Length of output: 7723


log.amount access is incorrect and will break TVL parsing

At Line 68, Line 72, and Line 76, log.amount is accessed directly. With getLogs({ eventAbi }) called without onlyArgs: true, the returned objects are ethers LogDescription instances where parsed event parameters are nested under the .args property. Accessing log.amount returns undefined, causing .toString() to throw TypeError: Cannot read property 'toString' of undefined.

✅ Suggested fix
-  deposits.forEach((log) => {
-    totalDeposited += BigInt(log.amount.toString());
-  });
+  deposits.forEach((log) => {
+    totalDeposited += BigInt(log.args.amount.toString());
+  });

-  withdrawals.forEach((log) => {
-    totalWithdrawn += BigInt(log.amount.toString());
-  });
+  withdrawals.forEach((log) => {
+    totalWithdrawn += BigInt(log.args.amount.toString());
+  });

-  claims.forEach((log) => {
-    totalClaimed += BigInt(log.amount.toString());
-  });
+  claims.forEach((log) => {
+    totalClaimed += BigInt(log.args.amount.toString());
+  });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@index` (2).js around lines 67 - 77, The code iterates
deposits/withdrawals/claims and does BigInt(log.amount.toString()), but when
logs come from getLogs({ eventAbi }) they are LogDescription objects whose
parsed params live under log.args, so change the accesses to use log.args.amount
(e.g., BigInt(log.args.amount.toString())) or alternatively request parsed args
by calling getLogs with onlyArgs: true; also add a null/undefined guard before
toString() to avoid runtime TypeError and keep variables
totalDeposited/totalWithdrawn/totalClaimed unchanged.

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: 1

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

Inline comments:
In `@index` (3).js:
- Around line 92-97: The code silently clamps negative net TVL (tvl) to zero in
the if (tvl < 0n) block which masks data-integrity issues; instead fail fast by
throwing an error (or returning a rejected Promise) that includes identifying
context (chain, totalDeposited, totalWithdrawn, totalClaimed, and any block
range or source identifiers) so callers/CI see the failure and you can
investigate mis-set fromBlock/ABI/missing events; update the negative check in
the tvl calculation path (the if (tvl < 0n) branch) to construct and throw a
descriptive Error (or call a centralized assertion/logger that raises) rather
than setting tvl = 0n.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 8308fc7b-49aa-4ac6-9bbd-607489476d00

📥 Commits

Reviewing files that changed from the base of the PR and between 320e534 and 3dcc06b.

📒 Files selected for processing (1)
  • index (3).js

Comment thread index (3).js
Comment on lines +92 to +97
if (tvl < 0n) {
console.warn(
`Negative TVL for ${chain}: deposited=${totalDeposited}, withdrawn=${totalWithdrawn}, claimed=${totalClaimed}. Setting to 0.`
);
tvl = 0n;
}
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

Fail fast on negative net TVL instead of silently clamping.

Clamping to zero can mask data-integrity bugs (mis-set fromBlock, ABI mismatch, or missing events) and publish incorrect TVL without surfacing the root cause.

Suggested fix
-  if (tvl < 0n) {
-    console.warn(
-      `Negative TVL for ${chain}: deposited=${totalDeposited}, withdrawn=${totalWithdrawn}, claimed=${totalClaimed}. Setting to 0.`
-    );
-    tvl = 0n;
-  }
+  if (tvl < 0n) {
+    throw new Error(
+      `Negative TVL for ${chain}: deposited=${totalDeposited}, withdrawn=${totalWithdrawn}, claimed=${totalClaimed}`
+    );
+  }
📝 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
if (tvl < 0n) {
console.warn(
`Negative TVL for ${chain}: deposited=${totalDeposited}, withdrawn=${totalWithdrawn}, claimed=${totalClaimed}. Setting to 0.`
);
tvl = 0n;
}
if (tvl < 0n) {
throw new Error(
`Negative TVL for ${chain}: deposited=${totalDeposited}, withdrawn=${totalWithdrawn}, claimed=${totalClaimed}`
);
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@index` (3).js around lines 92 - 97, The code silently clamps negative net TVL
(tvl) to zero in the if (tvl < 0n) block which masks data-integrity issues;
instead fail fast by throwing an error (or returning a rejected Promise) that
includes identifying context (chain, totalDeposited, totalWithdrawn,
totalClaimed, and any block range or source identifiers) so callers/CI see the
failure and you can investigate mis-set fromBlock/ABI/missing events; update the
negative check in the tvl calculation path (the if (tvl < 0n) branch) to
construct and throw a descriptive Error (or call a centralized assertion/logger
that raises) rather than setting tvl = 0n.

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: 1

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

Inline comments:
In `@index` (4).js:
- Around line 99-106: The current BigInt-to-Number conversion for tvl (variables
tvl, wholePart, fractionalPart, tvlInEther) can lose precision; replace the
manual Number(...) math with a safe decimal conversion using a library helper
(e.g., ethers.formatUnits) to convert the BigInt tvl to a JS number/string with
correct decimals, then assign that result to balances[NATIVE_TOKENS[chain]];
ensure the final value type matches the SDK expectation (numeric) — if the SDK
only accepts numbers, parse the formatted string safely (or use a decimal
library that returns a Number without precision loss) so large wei remainders
are handled correctly.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2cd6ca28-4c29-416b-9c0d-eb5e9b1e335a

📥 Commits

Reviewing files that changed from the base of the PR and between 3dcc06b and b3a1b96.

📒 Files selected for processing (1)
  • index (4).js

Comment thread index (4).js
Comment on lines +99 to +106
// Safe BigInt division to avoid precision loss
const wholePart = Number(tvl / 10n ** 18n);
const fractionalPart = Number(tvl % 10n ** 18n) / 1e18;
const tvlInEther = wholePart + fractionalPart;

const balances = {};
balances[NATIVE_TOKENS[chain]] = tvlInEther;

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

🧩 Analysis chain

🌐 Web query:

In JavaScript, does converting BigInt values larger than Number.MAX_SAFE_INTEGER to Number lose precision? Please provide a concise example.

💡 Result:

Yes, converting BigInt values larger than Number.MAX_SAFE_INTEGER to Number loses precision. Concise example: const big = 9007199254740993n; // Larger than Number.MAX_SAFE_INTEGER (9007199254740991) const num = Number(big); console.log(num); // 9007199254740992 (precision lost) console.log(Number(big) === 9007199254740992); // true console.log(BigInt(num) === big); // false (original precision not recoverable) Number.MAX_SAFE_INTEGER is the largest integer (2^53 - 1) that Number can represent exactly due to IEEE 754 double-precision limits. Larger BigInts lose least significant bits when converted.

Citations:


🏁 Script executed:

# Find the file named index (4).js or similar
find . -name "*index*" -type f | grep -E "\.js$" | head -20

Repository: DefiLlama/DefiLlama-Adapters

Length of output: 601


🏁 Script executed:

# Search for MOKEE adapter references
rg -l "MOKEE\|mokee" --type js -i

Repository: DefiLlama/DefiLlama-Adapters

Length of output: 54


🏁 Script executed:

# Search for files containing the exact code pattern from the review
rg "wholePart.*Number.*tvl.*10n" --type js -A 5 -B 5

Repository: DefiLlama/DefiLlama-Adapters

Length of output: 514


🏁 Script executed:

cat -n "./index (4).js"

Repository: DefiLlama/DefiLlama-Adapters

Length of output: 4658


🏁 Script executed:

# Look for how other adapters handle BigInt to Number conversion for TVL
rg "tvl.*toString\(\)\|tvlInEther\|tvlInNative" --type js -B 2 -A 2 | head -60

Repository: DefiLlama/DefiLlama-Adapters

Length of output: 54


🏁 Script executed:

# Check if there are examples of returning string values for TVL in adapters
rg "balances\[.*\]\s*=\s*['\"]" --type js | head -20

Repository: DefiLlama/DefiLlama-Adapters

Length of output: 54


🏁 Script executed:

# Search for ethers.formatEther or similar decimal/ether formatting in adapters
rg "formatEther\|parseEther\|toFixed" --type js | head -30

Repository: DefiLlama/DefiLlama-Adapters

Length of output: 54


🏁 Script executed:

# Look for adapters that return balances with native tokens
rg "balances\[.*coingecko" --type js -A 1 -B 1 | head -50

Repository: DefiLlama/DefiLlama-Adapters

Length of output: 1678


🏁 Script executed:

# Check a couple of simple adapters for TVL patterns
ls -la projects/ | head -10
find ./projects -maxdepth 2 -name "index.js" -type f | head -5 | xargs head -100

Repository: DefiLlama/DefiLlama-Adapters

Length of output: 6291


🏁 Script executed:

# Check if there's SDK documentation or type definitions for TVL structure
find . -name "*.d.ts" -o -name "*.ts" | grep -i "tvl\|balance" | head -10

Repository: DefiLlama/DefiLlama-Adapters

Length of output: 54


Fix the BigInt-to-Number conversion to preserve precision or use a proper decimal library.

Line 101 can lose precision when converting large fractional parts: Number(tvl % 10n ** 18n) produces incorrect results for remainders exceeding ~9×10^15 wei. However, returning strings (as suggested in the diff) would break the SDK interface, which expects numeric values. Use a library like ethers.formatUnits() for correct decimal handling, or accept this trade-off if typical TVL values stay within safe ranges.

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

In `@index` (4).js around lines 99 - 106, The current BigInt-to-Number conversion
for tvl (variables tvl, wholePart, fractionalPart, tvlInEther) can lose
precision; replace the manual Number(...) math with a safe decimal conversion
using a library helper (e.g., ethers.formatUnits) to convert the BigInt tvl to a
JS number/string with correct decimals, then assign that result to
balances[NATIVE_TOKENS[chain]]; ensure the final value type matches the SDK
expectation (numeric) — if the SDK only accepts numbers, parse the formatted
string safely (or use a decimal library that returns a Number without precision
loss) so large wei remainders are handled correctly.

@henrymikel
Copy link
Copy Markdown
Author

Acknowledged. Given MOKEE's current and near-term TVL will remain well within safe integer ranges (far below 9×10^15 ETH), the current BigInt division approach is acceptable. This is consistent with how other adapters in this repo handle similar conversions. Will revisit if TVL grows to require higher precision.

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.

1 participant