Skip to content

fix hardcoded event#1411

Open
alexcos20 wants to merge 1 commit into
mainfrom
bug/fix_hardcoded_event_number
Open

fix hardcoded event#1411
alexcos20 wants to merge 1 commit into
mainfrom
bug/fix_hardcoded_event_number

Conversation

@alexcos20

@alexcos20 alexcos20 commented Jul 9, 2026

Copy link
Copy Markdown
Member

Fix: don't assume the metadata event is the first log in the transaction

Summary

DecryptDdoHandler.decryptDDO() resolved the encrypted document from a transactionId by
parsing receipt.logs[0] and requiring it to be MetadataCreated/MetadataUpdated.
That assumption only holds for plain EOA transactions. For transactions sent through
account-abstraction wallets (ERC-4337), multisigs (e.g. Safe) or relayers, other events
(EntryPoint/wallet/token events) precede the metadata event, so decryption failed with
Decrypt DDO: Failed to process transaction id even though the transaction contains a
perfectly valid metadata event.

What changed

  • New helper findMetadataEventInLogs(logs, dataNftAddress) in
    src/components/core/handler/ddoHandler.ts:
    • scans all receipt logs instead of only logs[0],
    • only considers logs emitted by the data NFT contract itself (case-insensitive
      address match) — so batched AA transactions that touch multiple NFTs resolve the event
      of the correct contract,
    • reuses the existing fetchEventFromTransaction() util from src/utils/util.ts for the
      actual log parsing/matching (no shared-util changes needed; logs are pre-filtered by
      NFT address before delegating),
    • returns the parsed MetadataCreated or MetadataUpdated event, or null.
  • decryptDDO() now uses the helper; also guards against a null receipt. Arg extraction
    (args[3]/args[4]/args[5] = flags / encrypted document / document hash) and the
    error contract (HTTP 400 Failed to process transaction id, specific reason logged) are
    unchanged.

Note: getEventFromTx() from src/utils/util.ts could not be reused here — it matches
on log.fragment.name, which is only populated on receipts obtained from an ethers
Contract (tx.wait()). provider.getTransactionReceipt() returns plain logs without
fragment, so it would never match.

Audit: other hard-coded event positions in the codebase

The rest of the codebase was audited for the same class of bug:

  • src/components/Indexer/ChainIndexer.ts (receipt.logs[reindexTask.eventIndex]) —
    numeric index, but eventIndex is optional, never set by its only producer
    (reindexTxHandler), and falls back to scanning all logs when undefined. Intentional
    targeted-reindex feature; left as is.
  • Everything else is already position-independent: getEventFromTx /
    fetchEventFromTransaction filter all logs; BaseProcessor.getEventData and the main
    indexer loop match topics[0] event-signature hashes across all logs; remaining
    topics[N] usages are standard indexed-argument access.

Tests

  • New unit suite src/test/unit/ddoEventLog.test.ts (6 tests) using synthetic receipts
    built with Interface.encodeEventLog:
    • finds MetadataCreated when it is not the first log (the AA/multisig scenario),
    • finds MetadataUpdated,
    • matches the NFT address case-insensitively,
    • ignores metadata events emitted by other contracts in the same transaction,
    • returns null when no metadata event exists / on an empty logs array.

Summary by CodeRabbit

  • Bug Fixes
    • Improved detection of metadata events in transaction logs, making decrypt-related flows more reliable.
    • Better handles transactions with multiple logs, different event types, or events emitted from matching contract addresses.
    • Added clearer failures when transaction receipts are missing logs or no relevant metadata event is found.

@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 3451025d-338c-4db8-8828-335b382af1e3

📥 Commits

Reviewing files that changed from the base of the PR and between 60c161b and 555b63b.

📒 Files selected for processing (2)
  • src/components/core/handler/ddoHandler.ts
  • src/test/unit/ddoEventLog.test.ts

📝 Walkthrough

Walkthrough

Adds a findMetadataEventInLogs helper in ddoHandler.ts that filters transaction logs by data NFT address and parses MetadataCreated/MetadataUpdated events. DecryptDdoHandler.handle now uses this helper instead of manual ABI parsing, with updated validation and error handling. New unit tests cover the helper's behavior.

Changes

Metadata Event Lookup

Layer / File(s) Summary
findMetadataEventInLogs helper and handler integration
src/components/core/handler/ddoHandler.ts
Expands util.js imports to include fetchEventFromTransaction; adds exported findMetadataEventInLogs to filter logs by NFT address and locate a parsed metadata event; reworks DecryptDdoHandler.handle's transactionId path to use this helper with explicit receipt/log/event validation and error messages.
Unit tests for metadata event lookup
src/test/unit/ddoEventLog.test.ts
New test suite builds synthetic logs from the ERC721Template ABI and verifies correct event selection, case-insensitive address matching, filtering by emitter address, and null returns for missing/empty logs.

Estimated code review effort: 2 (Simple) | ~12 minutes

Sequence Diagram(s)

sequenceDiagram
  participant DecryptDdoHandler
  participant findMetadataEventInLogs
  participant fetchEventFromTransaction

  DecryptDdoHandler->>DecryptDdoHandler: validate receipt and logs exist
  DecryptDdoHandler->>findMetadataEventInLogs: filter logs by dataNftAddress
  findMetadataEventInLogs->>fetchEventFromTransaction: parse MetadataCreated/MetadataUpdated event
  fetchEventFromTransaction-->>findMetadataEventInLogs: parsed event or null
  findMetadataEventInLogs-->>DecryptDdoHandler: matching event or null
  DecryptDdoHandler->>DecryptDdoHandler: throw if null, else extract flags/encryptedDocument/documentHash
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title is related to the change but too vague to clearly describe the main fix. Use a more specific title like "Scan receipt logs for metadata events in decryptDDO".
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch bug/fix_hardcoded_event_number

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.

@alexcos20

Copy link
Copy Markdown
Member Author

/run-security-scan

@alexcos20 alexcos20 left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

AI automated code review (Gemini 3).

Overall risk: low

Summary:
This PR fixes a bug where the handler blindly assumed the MetadataCreated or MetadataUpdated event would always be the first log in a transaction receipt. By searching through all logs and filtering by the Data NFT address, the code now correctly handles transactions originating from smart wallets (ERC-4337, multisigs) or other complex contracts that emit multiple events. The implementation is robust and well-tested. LGTM!

Comments:
• [INFO][performance] It's a minor optimization, but you could define const abiInterface = new ethers.Interface(ERC721Template.abi) outside of the findMetadataEventInLogs function (e.g., at the module level). This avoids re-instantiating the ethers.Interface on every call, which parses the ABI JSON every time. Given that this function is not called in a tight loop, the performance impact is negligible, but it's a good practice.
• [INFO][style] Since you added a check for !receipt, the error message 'receipt logs 0' might be slightly misleading if the receipt itself is null (which can happen if the transaction hasn't been mined or doesn't exist on the provider). Consider updating it to something more accurate.

-            throw new Error('receipt logs 0')
+            throw new Error('Transaction receipt not found or has no logs')

• [INFO][other] Excellent unit tests! You clearly mocked the foreign log scenarios (such as those from ERC-4337 entry points) and thoroughly tested case-insensitivity and other edge cases. Great job on the test coverage here.

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