Skip to content

Implement onchain attribution for embed partners using ERC-8021 format - #661

Merged
Dprof-in-tech merged 6 commits into
mainfrom
KAN-723-feat-onchain-embed-host-attribution-via-erc-8021-parent-origin-code
Aug 24, 2026
Merged

Implement onchain attribution for embed partners using ERC-8021 format#661
Dprof-in-tech merged 6 commits into
mainfrom
KAN-723-feat-onchain-embed-host-attribution-via-erc-8021-parent-origin-code

Conversation

@Dprof-in-tech

@Dprof-in-tech Dprof-in-tech commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator

Description

  • Introduced deterministic embed code generation based on partner origin, enabling transaction volume tracking without middleware reliance.
  • Extended core attribution logic with new functions for computing and appending embed codes.
  • Updated transaction paths to incorporate embed codes in various transaction scenarios.
  • Added comprehensive tests for embed code generation and attribution suffix handling.
  • Enhanced documentation to explain the new onchain attribution mechanism and its implications for partners.

References

Testing

  • This change adds test coverage for new/changed/fixed functionality

Checklist

  • I have added documentation and tests for new/changed functionality in this PR
  • All active GitHub checks for tests, formatting, and security are passing
  • The correct base branch is being used, if not main
  • If this PR adds a database migration, it follows expand/contract: the new code works against the pre-migration schema, the currently deployed code keeps working against the post-migration schema, and destructive changes (drops, renames, tightened constraints) are deferred until the old application version is no longer serving — migrations are applied around the deploy, not strictly before or after it

By submitting a PR, I agree to Paycrest's Contributor Code of Conduct and Contribution Guide.

Summary by CodeRabbit

  • New Features

    • Added deterministic on-chain attribution for supported widget transactions using embed codes.
    • Preserved Base builder attribution while supporting combined builder and embed attribution.
    • Extended attribution across approvals, orders, smart-wallet actions, sponsored transactions, and batch operations.
    • Improved bridge routing with fallback quotes and clearer route availability status.
  • Bug Fixes

    • Invalid embed codes are rejected with a clear request error.
    • Improved refund-account validation when currencies or transaction flows change.
  • Documentation

    • Added guidance on attribution coverage, origin handling, privacy, partner tracking, and referrer-policy requirements.

- Introduced deterministic embed code generation based on partner origin, enabling transaction volume tracking without middleware reliance.
- Extended core attribution logic with new functions for computing and appending embed codes.
- Updated transaction paths to incorporate embed codes in various transaction scenarios.
- Added comprehensive tests for embed code generation and attribution suffix handling.
- Enhanced documentation to explain the new onchain attribution mechanism and its implications for partners.
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

No new commits to review since the last review.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8324c641-fcc6-4c1d-b924-53c2fb413c43

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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
  • No new commits to review - use @coderabbitai full review for a full pass

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c0c2241e-4ce2-47bb-a607-67021d585570

📥 Commits

Reviewing files that changed from the base of the PR and between f9c5e9b and eb11f46.

📒 Files selected for processing (2)
  • app/hooks/bridge.ts
  • app/pages/TransactionPreview.tsx

Included review availability: 2 reviews are currently available. Your included PR review attempts over the past 7 days set your current allowance at 3 reviews per hour.


📝 Walkthrough

Walkthrough

The PR adds deterministic origin-based embed codes, validates and encodes them as ERC-8021 attribution suffixes, and propagates them through wallet, bridge, smart-wallet, and sponsored transaction flows. It also updates quote handling, refund-account validation, tests, and widget documentation.

Changes

Embed attribution

Layer / File(s) Summary
Embed-code generation and context
app/lib/baseBuilderCode.ts, app/context/EmbedContext.tsx
Origins are normalized and hashed into deterministic embed codes. The embed context computes, clears, and exposes the current code.
ERC-8021 suffix construction
app/lib/baseBuilderCode.ts, __tests__/baseBuilderCode.test.ts
Validated schema-0 suffixes support Base builder codes, embed codes, combined attribution, embed-only attribution, and input validation.
Transaction-path integration
app/pages/TransactionPreview.tsx, app/hooks/bridge.ts, app/lib/bridge.ts, app/lib/bundler/executeSponsored.ts, app/api/bundler/execute-sponsored/route.ts
Transaction, bridge, batch, and sponsored bundler flows pass embed codes into attribution handling. Bridge quote handling adds LI.FI fallback and exposes isFetched. Sponsored requests reject invalid embed codes. Refund-account state and currency checks are tightened.
Validation and attribution documentation
__tests__/baseBuilderCode.test.ts, docs/embed-widget.md
Tests cover suffix structure, origin normalization, deterministic codes, and validation. The documentation describes derivation, supported calldata, privacy, and referrer-policy requirements.

Estimated code review effort: 4 (Complex) | ~45 minutes

Merge Risk: ⚪ Minimal · up to eb11f

This PR adds deterministic onchain attribution for embed partners across transaction flows, with corresponding tests and documentation; no actionable merge-blocking risk remains.

Sequence Diagram(s)

sequenceDiagram
  participant EmbedContext
  participant TransactionPreview
  participant useBridgeExecute
  participant executeSponsored
  participant appendAttributionSuffix
  EmbedContext->>TransactionPreview: provide embedCode
  EmbedContext->>useBridgeExecute: provide embedCode
  TransactionPreview->>appendAttributionSuffix: append attribution to calldata
  useBridgeExecute->>appendAttributionSuffix: append attribution to bridge calls
  TransactionPreview->>executeSponsored: send embedCode
  executeSponsored->>appendAttributionSuffix: append attribution to sponsored calldata
Loading

Suggested reviewers: chibie

Poem

A rabbit hashes origins bright,
Then stamps the code in calldata light.
Wallets and bridges carry the trail,
Sponsored calls pass the detail.
Invalid codes stay outside—
ERC-8021 hops with pride.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the implementation but omits the Jira Issue, Self-review, and Staging sections and lacks specific testing and environment details. Add the missing template sections and describe reviewer test steps, untested areas, and the development environment.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring check was indeterminate for this PR — some files could not be analyzed in time. Not blocking.
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.
Title check ✅ Passed The title clearly summarizes the main change: implementing ERC-8021 on-chain attribution for embed partners.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

Comment @coderabbitai help to get the list of available commands.

- Simplified the hash generation process by removing the fallback for older Node versions, ensuring consistent use of the Web Crypto API for SHA-256 hashing.
- Updated the computeEmbedCode function to directly utilize crypto.subtle.digest, enhancing code clarity and maintainability.

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

🧹 Nitpick comments (1)
docs/embed-widget.md (1)

319-321: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a language tag to the fenced example.

markdownlint-cli2 reports MD040 for Line 319. Mark this pseudo-code block as text.

Proposed fix
-```
+```text
 embedCode = "e_" + first 8 hex chars of sha256(normalizedOrigin)
-```
+```
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/embed-widget.md` around lines 319 - 321, Add the text language tag to
the fenced pseudo-code block containing the embedCode example in the
documentation, changing its opening fence to ```text while preserving the
example content and closing fence.

Source: Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@app/context/EmbedContext.tsx`:
- Around line 284-290: Update the EmbedProvider effect around parentOrigin and
computeEmbedCode so that when isEmbed becomes false, both parentOrigin and
embedCode are cleared or exposed as null. Include isEmbed in the relevant
dependency handling, and ensure later transactions cannot reuse attribution from
the previous embed partner.

In `@app/hooks/bridge.ts`:
- Around line 331-336: Update the sponsored bridge execution flows in
evmBatchExecute and LI.FI executeBatchCalls to accept and forward
embedCodeRef.current through their helper APIs, then include it in the
sponsored-execution payload consumed by executeSponsored so attribution suffixes
are appended.

In `@app/lib/baseBuilderCode.ts`:
- Around line 13-15: Update the marker-count comment in baseBuilderCode.ts to
state that 0x8021 repeats eight times, matching the suffix literal and
ERC8021_MARKER definition. Do not change the implementation.
- Around line 95-116: Validate body.embedCode at the sponsored-route boundary
before passing it to executeSponsored: require the e_ prefix followed by exactly
eight hexadecimal characters, then verify it against the allowlisted origin
using the existing validation mechanism. Reject invalid or unauthorized codes
and only forward validated values into appendAttributionSuffix.

In `@docs/embed-widget.md`:
- Around line 310-312: Update the attribution statement in the widget
documentation to limit the guarantee to supported EVM contract transactions with
calldata, rather than every transaction. Replace “onchain” with “on-chain” and
preserve the explanation that the attribution code identifies embedding partners
for Paycrest volume and activity tracking.
- Around line 342-344: Update the Privacy statement in the embed widget
documentation to accurately describe the unsalted 32-bit SHA-256 prefix: state
that it does not directly encode the origin but can be matched when a candidate
origin is known or guessed, while retaining the existing reproducibility
qualification.

In `@EMBED_ATTRIBUTION_IMPLEMENTATION.md`:
- Around line 91-112: Update the “Onchain Calldata Format” and “Aggregator
Parser Requirements” sections to document the rebuilt suffix schema: ASCII-hex
encoded codes, followed by a length byte, 00 schema byte, and 8021 marker
repeated eight times. Specify that Base uses codes “bc_julg9gbq,<embedCode>”
while other chains use only “<embedCode>”, and revise parser guidance to decode
and validate this complete layout instead of stripping or appending to
BASE_BUILDER_CODE_SUFFIX.

---

Nitpick comments:
In `@docs/embed-widget.md`:
- Around line 319-321: Add the text language tag to the fenced pseudo-code block
containing the embedCode example in the documentation, changing its opening
fence to ```text while preserving the example content and closing fence.
🪄 Autofix

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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c453a035-66f2-49c1-93ae-e0b431cd5734

📥 Commits

Reviewing files that changed from the base of the PR and between 4d3db6b and 384d8d3.

📒 Files selected for processing (11)
  • EMBED_ATTRIBUTION_IMPLEMENTATION.md
  • __tests__/attributionSuffix.test.ts
  • __tests__/embedCode.test.ts
  • app/api/bundler/execute-sponsored/route.ts
  • app/context/EmbedContext.tsx
  • app/hooks/bridge.ts
  • app/lib/baseBuilderCode.ts
  • app/lib/bundler/executeSponsored.ts
  • app/lib/embedCode.ts
  • app/pages/TransactionPreview.tsx
  • docs/embed-widget.md

Comment thread app/context/EmbedContext.tsx Outdated
Comment thread app/hooks/bridge.ts
Comment thread app/lib/baseBuilderCode.ts Outdated
Comment thread app/lib/baseBuilderCode.ts
Comment thread docs/embed-widget.md Outdated
Comment thread docs/embed-widget.md Outdated
Comment thread EMBED_ATTRIBUTION_IMPLEMENTATION.md Outdated
Dprof-in-tech and others added 2 commits August 5, 2026 07:45
- Introduced `isValidEmbedCode` function to validate the shape of embed codes, ensuring only correctly formatted codes are accepted in transaction requests.
- Updated the bundler's sponsored execution route to reject invalid embed codes and provide clear error messages.
- Revised documentation to clarify the on-chain attribution process and the structure of embed codes.
- Improved the embed code generation logic to ensure consistency across different transaction scenarios.
sundayonah
sundayonah previously approved these changes Aug 17, 2026

@sundayonah sundayonah left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

looks good

Comment thread app/lib/embedCode.ts Outdated
…e aggregator reference

The bc_julg9gbq builder code was reverted out of the aggregator, so the
'must match aggregator/services/builder_code.go' note no longer points at
anything. Replaced with what the code actually is.

- merge app/lib/embedCode.ts into app/lib/baseBuilderCode.ts
- embedCodeToHex now delegates to the existing stringToHex helper
- consolidate the three attribution test files into baseBuilderCode.test.ts
- remove EMBED_ATTRIBUTION_IMPLEMENTATION.md, superseded by docs/embed-widget.md;
  its warning about rebuilding multi-code suffixes moved into a code comment
@Dprof-in-tech
Dprof-in-tech merged commit 0fbb2fa into main Aug 24, 2026
3 checks passed
@Dprof-in-tech
Dprof-in-tech deleted the KAN-723-feat-onchain-embed-host-attribution-via-erc-8021-parent-origin-code branch August 24, 2026 04:35
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.

4 participants