Skip to content

Conversation

@outerlook
Copy link
Collaborator

@outerlook outerlook commented Oct 20, 2025

Description

  • Introduced TrufAttestationConsumer.sol contract for verifying and storing TrufNetwork attestations.
  • Added comprehensive tests in TrufAttestationConsumer.test.ts to validate attestation consumption and error handling.
  • Updated package.json to include a test script for the new consumer contract.
  • Enhanced documentation to include details about the new contract and its usage.

Related Problem

How Has This Been Tested?

Summary by CodeRabbit

  • New Features

    • Added TrufAttestationConsumer contract for verifying attestations from designated leaders and storing the latest datapoint with owner-based access control.
  • Documentation

    • Updated Attestation Library documentation with example contract implementation and best practices for leader management before mainnet deployment.

- Introduced TrufAttestationConsumer.sol contract for verifying and storing TrufNetwork attestations.
- Added comprehensive tests in TrufAttestationConsumer.test.ts to validate attestation consumption and error handling.
- Updated package.json to include a test script for the new consumer contract.
- Enhanced documentation to include details about the new contract and its usage.
@outerlook outerlook self-assigned this Oct 20, 2025
@coderabbitai
Copy link

coderabbitai bot commented Oct 20, 2025

Walkthrough

This PR introduces a new TrufAttestationConsumer contract for verifying TrufNetwork attestations, adds comprehensive test suites for both the consumer and attestation library with edge-case coverage, implements test fixtures via a golden constants module, documents the attestation library with example contract guidance, and updates build configuration to include the new tests.

Changes

Cohort / File(s) Summary
Attestation Consumer Contract
contracts/attestation/TrufAttestationConsumer.sol
New contract that verifies TrufNetwork attestations against a designated leader, parses payloads, decodes datapoints, and stores the latest attestation state; includes owner-controlled leadership management and custom error types.
Test Suites
test/attestation/TrufAttestation.test.ts, test/attestation/TrufAttestationConsumer.test.ts
Enhanced attestation library tests with edge cases (truncated bytes, signature tampering, varying array sizes) and new end-to-end consumer tests validating successful consumption, error paths, access control, and state updates.
Test Fixtures & Helpers
test/attestation/golden.ts
New helper module that imports and exports golden fixture constants (canonical, signature, payload) from JSON, replacing filesystem-based fixture loading in tests.
Documentation
docs/AttestationLibrary.md
Added Example Contract subsection documenting the minimal consumer contract, its tests, and guidance to customize governance/allowlist logic before mainnet deployment.
Configuration
package.json
Added test script to run both attestation test suites under scripts.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Consumer as TrufAttestationConsumer
    participant TrufAttest as TrufAttestation (lib)
    participant State as Contract State

    User->>Consumer: consume(payload)
    Note over Consumer: Validate leader is set
    Consumer->>TrufAttest: parse(payload)
    TrufAttest-->>Consumer: Attestation struct
    Note over Consumer: Extract signer, data
    alt Signer matches leader
        Consumer->>TrufAttest: decodeDataPoints(data)
        TrufAttest-->>Consumer: DataPoint[]
        alt Array not empty
            Consumer->>State: Update lastValidator, lastBlockHeight,<br/>lastStreamId, lastActionId,<br/>lastTimestamp, lastValue
            Consumer->>Consumer: emit AttestationConsumed
            Consumer-->>User: Success
        else Array empty
            Consumer-->>User: revert AttestationConsumerEmptyResult
        end
    else Signer mismatch
        Consumer-->>User: revert AttestationConsumerInvalidSigner
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

The PR spans multiple file types with consistent, well-structured patterns (new contract, test suites, helpers, docs). The TrufAttestationConsumer contract is straightforward with clear ownership and access control logic. Test coverage is comprehensive but follows a repetitive structure across test files. Documentation and configuration changes are minimal. The main review burden lies in validating the consumer contract's integration with the TrufAttestation library and ensuring test assertions correctly exercise all specified behaviors.

Possibly related issues

Possibly related PRs

  • feat: attestations #9: The TrufAttestationConsumer contract directly uses types (Attestation, DataPoint) and functions (parse, verify, decodeDataPoints) from the TrufAttestation library, indicating tight integration with the library implementation.

Suggested reviewers

  • MicBun

Poem

🐰 Attestations now verified with care,
Tests and examples everywhere,
Golden fixtures, consumer so bright,
Edge cases covered, all set right,
From byte to value, the truth does share! 🌟

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "chore: include attestation docs & example" directly refers to real components of the changeset: the documentation updates in AttestationLibrary.md and the new example consumer contract TrufAttestationConsumer.sol. While the title doesn't explicitly mention the significant test suite work or test fixture refactoring that comprise a substantial portion of the changes, it accurately captures the primary user-facing additions and is specific enough to communicate the main intent. The title is not misleading or off-topic; it reflects a genuine aspect of the work, though a broader framing would be more complete.
Linked Issues Check ✅ Passed The pull request fulfills the core requirements of issue #7. It includes a comprehensive test suite at test/attestation/TrufAttestation.test.ts covering malformed payloads (truncated canonical and signature bytes), signer mismatch verification, and datapoint decoding for varying array sizes. The example consumer contract TrufAttestationConsumer.sol demonstrates payload verification and data usage as required. Test fixtures are provided in test/attestation/golden.ts (a minor location deviation from the specified test/helpers/attestation.ts but functionally equivalent). Test integration with npm is completed via the new test script in package.json. The optional deployment helper requirement is not explicitly addressed, but all mandatory objectives are met.
Out of Scope Changes Check ✅ Passed All changes in this pull request are directly aligned with the stated objectives of issue #7. The additions include the example consumer contract, comprehensive test suite, test fixtures, documentation, and build configuration—all explicitly in scope. No changes appear to involve integration with main oracle contracts or on-chain deployment scripts, which were correctly identified as out of scope. The work is focused on testing and documentation of the attestation library components without extending into production deployment or oracle integration.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch chore/att-example

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

@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: 0

🧹 Nitpick comments (3)
package.json (1)

8-8: Consider using a glob pattern for better maintainability.

The explicit file listing works, but as more attestation tests are added, you'll need to update this script each time. Consider using a pattern like "hardhat test test/attestation/**/*.test.ts" for automatic inclusion of new tests.

Apply this diff if you prefer the glob approach:

-    "test": "hardhat test test/attestation/TrufAttestation.test.ts test/attestation/TrufAttestationConsumer.test.ts"
+    "test": "hardhat test test/attestation/**/*.test.ts"
test/attestation/TrufAttestation.test.ts (1)

165-169: Test name could be more precise.

The test truncates the payload by 130 hex characters (65 bytes), which removes the entire signature, leaving only canonical bytes. The test name says "truncated canonical bytes" but it's actually testing a payload missing the signature entirely. Consider renaming to "rejects payloads missing signature" for clarity.

Apply this diff for a more accurate test name:

-  it("rejects payloads with truncated canonical bytes", async function () {
+  it("rejects payloads missing signature", async function () {
     const harness = await deployHarness();
     const truncated = GOLDEN_PAYLOAD.slice(0, GOLDEN_PAYLOAD.length - 130);
     await expect(harness.parse(truncated)).to.be.revertedWithCustomError(harness, "AttestationInvalidLength");
contracts/attestation/TrufAttestationConsumer.sol (1)

41-46: Consider adding validation for production use.

While this is an example contract, you might want to demonstrate best practices:

 function setLeader(address newLeader) external {
     if (msg.sender != owner) revert AttestationConsumerOnlyOwner();
+    if (newLeader == address(0)) revert AttestationConsumerInvalidLeader();
+    if (newLeader == leader) return; // Skip if unchanged
     leader = newLeader;
     emit LeaderUpdated(newLeader);
 }

Note: Allowing address(0) might be intentional to "unset" the leader, so consider your use case.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dd34067 and e5f58d5.

📒 Files selected for processing (6)
  • contracts/attestation/TrufAttestationConsumer.sol (1 hunks)
  • docs/AttestationLibrary.md (1 hunks)
  • package.json (1 hunks)
  • test/attestation/TrufAttestation.test.ts (3 hunks)
  • test/attestation/TrufAttestationConsumer.test.ts (1 hunks)
  • test/attestation/golden.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: outerlook
PR: trufnetwork/evm-contracts#9
File: contracts/attestation/TrufAttestation.sol:151-161
Timestamp: 2025-10-20T15:59:08.048Z
Learning: The TrufAttestation library in contracts/attestation/TrufAttestation.sol intentionally does not impose upper bounds on decoded datapoints or other business logic constraints, leaving such validation to consumer contracts that have specific use-case requirements.
📚 Learning: 2025-10-20T15:59:08.048Z
Learnt from: outerlook
PR: trufnetwork/evm-contracts#9
File: contracts/attestation/TrufAttestation.sol:151-161
Timestamp: 2025-10-20T15:59:08.048Z
Learning: The TrufAttestation library in contracts/attestation/TrufAttestation.sol intentionally does not impose upper bounds on decoded datapoints or other business logic constraints, leaving such validation to consumer contracts that have specific use-case requirements.

Applied to files:

  • contracts/attestation/TrufAttestationConsumer.sol
  • docs/AttestationLibrary.md
🧬 Code graph analysis (2)
test/attestation/TrufAttestationConsumer.test.ts (1)
test/attestation/golden.ts (2)
  • goldenFixture (28-28)
  • GOLDEN_PAYLOAD (31-31)
test/attestation/TrufAttestation.test.ts (1)
test/attestation/golden.ts (2)
  • GOLDEN_PAYLOAD (31-31)
  • goldenFixture (28-28)
🔇 Additional comments (19)
docs/AttestationLibrary.md (1)

64-67: LGTM! Clear documentation with appropriate production warnings.

The example contract section provides helpful guidance and correctly references the new consumer contract and its test suite. The warning to replace leader management before mainnet deployment is important and well-placed.

test/attestation/golden.ts (3)

6-26: LGTM! Well-structured fixture type.

The GoldenFixture type provides clear structure for the test fixture data and aligns with the canonical attestation format.


28-31: LGTM! Clean fixture export pattern.

The golden fixture constants are properly formatted with 0x prefixes for use with ethers.js, and the synchronous file read is appropriate for test setup.


4-4: The fixture file exists at the expected path. No issues found.

test/attestation/TrufAttestation.test.ts (5)

4-9: LGTM! Good refactor with centralized fixtures and deployment helper.

The deployHarness helper and golden fixture imports reduce duplication and improve test maintainability.


82-82: LGTM! Consistent use of deployment helper.


171-180: LGTM! Good edge case coverage.

This test properly validates that truncated signatures are rejected, addressing the malformed payload requirement from issue #7.


182-191: LGTM! Proper verification of signature validation.

This test confirms that tampered payloads return false from verify() rather than reverting, which correctly validates the library's behavior for mismatched signatures as required by issue #7.


193-229: LGTM! Excellent coverage of varying array sizes.

This loop-based test provides fuzz-like coverage for different array sizes including the important edge case of empty results, directly addressing the requirement from issue #7 for varying array size tests.

test/attestation/TrufAttestationConsumer.test.ts (5)

7-38: LGTM! Comprehensive happy path test.

This test thoroughly validates successful attestation consumption by checking both event emission and state variable updates. The use of golden fixtures ensures consistent test data.


40-54: LGTM! Proper validation of untrusted signers.

This test confirms that the consumer correctly rejects attestations not signed by the trusted leader.


56-83: LGTM! Important edge case for consumer business logic.

This test validates that the consumer contract enforces non-empty results, which is appropriate business logic at the consumer level rather than in the library. Based on learnings.


85-92: LGTM! Proper access control validation.


94-100: LGTM! Validates prerequisite for consumption.

This test ensures that the consumer requires explicit leader configuration before accepting attestations.

contracts/attestation/TrufAttestationConsumer.sol (5)

1-10: LGTM! Clean contract structure and imports.


12-24: LGTM! Appropriate error definitions and state variables.

The custom errors and state variables are well-designed for tracking attestation metadata and the latest datapoint.


26-39: LGTM! Well-designed events and simple initialization.

The events provide good observability with appropriate indexed parameters, and the constructor correctly establishes ownership.


48-58: LGTM! Proper validation flow.

The function correctly validates prerequisites, parses the attestation, and verifies the signature before processing.


60-73: LGTM! Correct datapoint processing and state updates.

The function properly validates non-empty results, extracts the latest datapoint, updates state atomically, and emits the event. Note that replay protection and freshness checks are intentionally omitted as this is a minimal example—as documented, production implementations should add these safeguards.

@holdex
Copy link

holdex bot commented Oct 20, 2025

Time Submission Status

Member Status Time Action Last Update
@outerlook ❌ Missing - ⚠️ Submit time -
MicBun ✅ Submitted 15min Update time Oct 21, 2025, 1:55 PM

@outerlook outerlook requested a review from MicBun October 20, 2025 19:06
Copy link
Member

@MicBun MicBun left a comment

Choose a reason for hiding this comment

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

lgtm

@MicBun MicBun merged commit 22ca79d into main Oct 20, 2025
3 of 4 checks passed
@MicBun MicBun deleted the chore/att-example branch October 20, 2025 23:15
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.

Problem: Attestation contracts lack validation tests & examples

3 participants