Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughA 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
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
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Poem
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
| totalClaimed += BigInt(log.amount.toString()); | ||
| }); | ||
|
|
||
| const tvl = totalDeposited - totalWithdrawn - totalClaimed; |
There was a problem hiding this comment.
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.
| 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.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
index (1).js (2)
44-52: Consider usingapi.chaininstead of passing chain separately.The
apiobject already contains chain information viaapi.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
|
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. |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
index (2).js (1)
54-56: Add defensive guard for unsupported chain keysDestructuring
contractwithout a guard will throw ifapi.chainis 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
| deposits.forEach((log) => { | ||
| totalDeposited += BigInt(log.amount.toString()); | ||
| }); | ||
|
|
||
| withdrawals.forEach((log) => { | ||
| totalWithdrawn += BigInt(log.amount.toString()); | ||
| }); | ||
|
|
||
| claims.forEach((log) => { | ||
| totalClaimed += BigInt(log.amount.toString()); | ||
| }); |
There was a problem hiding this comment.
🧩 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 20Repository: 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.
There was a problem hiding this comment.
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
| if (tvl < 0n) { | ||
| console.warn( | ||
| `Negative TVL for ${chain}: deposited=${totalDeposited}, withdrawn=${totalWithdrawn}, claimed=${totalClaimed}. Setting to 0.` | ||
| ); | ||
| tvl = 0n; | ||
| } |
There was a problem hiding this comment.
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.
| 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.
There was a problem hiding this comment.
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
| // 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; | ||
|
|
There was a problem hiding this comment.
🧩 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:
- 1: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt
- 2: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/bigint
- 3: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
- 4: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/Number
🏁 Script executed:
# Find the file named index (4).js or similar
find . -name "*index*" -type f | grep -E "\.js$" | head -20Repository: DefiLlama/DefiLlama-Adapters
Length of output: 601
🏁 Script executed:
# Search for MOKEE adapter references
rg -l "MOKEE\|mokee" --type js -iRepository: 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 5Repository: 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 -60Repository: 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 -20Repository: 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 -30Repository: 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 -50Repository: 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 -100Repository: 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 -10Repository: 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.
|
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. |
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