Skip to content

fix: add swap refund skipping logic to Moralis deposit processing - #658

Open
sundayonah wants to merge 2 commits into
mainfrom
fix/noblocks-refund-duplicate-history-and-email
Open

fix: add swap refund skipping logic to Moralis deposit processing#658
sundayonah wants to merge 2 commits into
mainfrom
fix/noblocks-refund-duplicate-history-and-email

Conversation

@sundayonah

@sundayonah sundayonah commented Jul 29, 2026

Copy link
Copy Markdown
Collaborator

Description

When a Noblocks swap fails and Paycrest refunds crypto to the user’s wallet, two systems were handling the same on-chain transfer:

  1. Swap flow — correctly updates the original order row to refunded.
  2. Moralis deposit flow — treats the inbound transfer as a new deposit, inserts a credit transaction (shown as “Funded” in history), and sends a deposit email via Activepieces → Brevo.

Users saw duplicate history rows and an unwanted “you received funds” email for money that was already tied to a failed swap.

This PR adds refund detection in Moralis deposit processing so failed-swap refunds are not recorded as deposits and not emailed.

Implementation

  • app/lib/moralis-skip-swap-refund.tsshouldSkipMoralisDepositAsSwapRefund() skips when:
    • from is a known Paycrest gateway contract (isPaycrestGatewayAddress in utils.ts)
    • the tx hash is already stored on an order-backed row (onramp, offramp, bridge, swap via SWAP_ORDER_TRANSACTION_TYPES in types.ts)
    • the wallet has a swap in refunding status (in-flight refund)
  • app/lib/moralis-deposit-processing.ts — calls the skip helper before triggerActivepiecesDeposit and the credit insert for both native and ERC-20 transfers.
  • app/utils.ts — extracts GATEWAY_CONTRACT_ADDRESSES as the single source of truth for gateway addresses; getGatewayContractAddress() behavior is unchanged for existing callers (TransactionPreview).
  • app/types.ts — adds SWAP_ORDER_TRANSACTION_TYPES, a typed subset of TransactionHistoryType for order rows that can refund.

Impacts

  • Normal user-initiated deposits are unchanged.
  • On DB lookup errors in the skip helper, processing falls through to the existing deposit path (fail-open for real deposits).
  • Existing duplicate credit rows created before this fix are not removed (prevention only).

Breaking changes: None.

Alternatives considered

  • UI-only filter to hide duplicate credits — would not stop deposit emails.
  • Matching only on refunded status — too late if Moralis fires before status update; gateway + refunding + tx-hash checks cover timing gaps.

API / contracts / DB: No changes.

References

KAN-731

Testing

Manual (staging)

  1. Run a swap that fails and triggers a crypto refund to the user’s embedded wallet (e.g. failed offramp).
  2. Confirm transaction history shows one row for the swap with status Refunded — no extra Funded / credit row for the same tx hash.
  3. Confirm the user does not receive a Moralis deposit email (Activepieces/Brevo) for the refund transfer.
  4. Send a normal supported-token deposit to the same wallet and confirm it still creates a Funded row and deposit email.

Environment: Noblocks (@paycrest/noblocks), Next.js 15, TypeScript, Node.js on Windows (local dev); Moralis Streams webhook + Supabase.

  • 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 (N/A — no migration)

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

Summary by CodeRabbit

  • Bug Fixes
    • Prevented failed-swap refunds from creating duplicate Moralis deposit notifications or credit records for both native and ERC-20 transfers.
    • Improved swap-refund detection using known Paycrest gateway refund sender addresses (case- and wallet-safe handling).
  • Tests
    • Added Jest coverage to ensure gateway refund sender addresses are correctly recognized, and invalid, missing, or empty inputs are rejected.

- Introduced a check to skip processing deposits that are identified as swap refunds, enhancing the handling of transactions.
- Added logging for development environment to indicate when a deposit is skipped due to being a swap refund.
- Updated both native and ERC20 deposit processing functions to include this new logic, ensuring consistent behavior across transaction types.
@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

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: d3773087-1187-4946-ab51-cb29156eb03c

📥 Commits

Reviewing files that changed from the base of the PR and between 2a799f6 and 33dab98.

📒 Files selected for processing (1)
  • app/lib/moralis-skip-swap-refund.ts

📝 Walkthrough

Walkthrough

Moralis deposit processing now skips transfers identified as swap refunds. The change adds shared gateway address detection, swap-order transaction matching, and tests for Paycrest gateway address recognition.

Changes

Moralis swap-refund filtering

Layer / File(s) Summary
Gateway address contracts
app/utils.ts, app/types.ts
Shared Paycrest gateway addresses, the GatewayNetwork type, and swap-order transaction types are defined for reuse.
Swap-refund decision logic
app/lib/moralis-skip-swap-refund.ts
Refund detection normalizes addresses, checks gateway senders, and queries Supabase for matching swap-order transactions.
Moralis processing integration
app/lib/moralis-deposit-processing.ts, __tests__/moralis-skip-swap-refund.test.ts
Native and ERC-20 deposits are skipped before notifications and transaction inserts when identified as refunds; gateway address behavior is tested.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant DepositProcessor
  participant SwapRefundHelper
  participant Supabase
  DepositProcessor->>SwapRefundHelper: Check wallet, tx hash, and sender
  SwapRefundHelper->>Supabase: Query matching swap-order transactions
  Supabase-->>SwapRefundHelper: Query result
  SwapRefundHelper-->>DepositProcessor: Skip or continue
Loading

Possibly related PRs

Suggested labels: bug

Suggested reviewers: chibie

Poem

I’m a rabbit guarding coins in flight,
Refund hops vanish before moonlight.
Gateway paths are neatly known,
Swap-back trails are safely shown.
No extra credits in my burrow tonight! 🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: skipping swap refunds in Moralis deposit processing.
Description check ✅ Passed The description follows the template well with purpose, implementation, impacts, references, testing, and checklist details.
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

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

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

🧹 Nitpick comments (1)
__tests__/moralis-skip-swap-refund.test.ts (1)

3-20: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Cover the actual refund-skip decision paths.

Add mocked-Supabase tests for matching tx_hash, lookup errors failing open, and the intended refunding correlation; add native and ERC-20 assertions that skipped transfers do not trigger Activepieces or insert a credit row.

🤖 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 `@__tests__/moralis-skip-swap-refund.test.ts` around lines 3 - 20, Expand the
tests around isPaycrestGatewayAddress and the refund-skip flow with mocked
Supabase cases for matching tx_hash, lookup errors failing open, and the
intended refunding correlation. Add native and ERC-20 assertions verifying
skipped transfers neither trigger Activepieces nor insert a credit row, while
preserving the existing address-validation coverage.
🤖 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/lib/moralis-skip-swap-refund.ts`:
- Around line 50-52: Update the refund-skip condition around swapOrderExists so
it matches the specific refund associated with the inbound transfer, using the
expected sender or refund transaction identifier rather than wallet-level
refunding status alone. Ensure unrelated deposits continue through the existing
notification and credit flow unchanged.

---

Nitpick comments:
In `@__tests__/moralis-skip-swap-refund.test.ts`:
- Around line 3-20: Expand the tests around isPaycrestGatewayAddress and the
refund-skip flow with mocked Supabase cases for matching tx_hash, lookup errors
failing open, and the intended refunding correlation. Add native and ERC-20
assertions verifying skipped transfers neither trigger Activepieces nor insert a
credit row, while preserving the existing address-validation coverage.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 218715c8-e47b-4738-a200-79a8d2a64eb2

📥 Commits

Reviewing files that changed from the base of the PR and between 2291c96 and 2a799f6.

📒 Files selected for processing (5)
  • __tests__/moralis-skip-swap-refund.test.ts
  • app/lib/moralis-deposit-processing.ts
  • app/lib/moralis-skip-swap-refund.ts
  • app/types.ts
  • app/utils.ts

Comment thread app/lib/moralis-skip-swap-refund.ts Outdated
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