Skip to content

refactor(sender, order): enhance rate validation logic and introduce …#735

Merged
onahprosper merged 3 commits intomainfrom
fix-multipleorder-creation-and-rate-assertion
Mar 20, 2026
Merged

refactor(sender, order): enhance rate validation logic and introduce …#735
onahprosper merged 3 commits intomainfrom
fix-multipleorder-creation-and-rate-assertion

Conversation

@onahprosper
Copy link
Collaborator

@onahprosper onahprosper commented Mar 20, 2026

…cancellation handling for indexed orders

  • Updated rate validation logic to use symmetric tolerance for market rate comparisons, improving accuracy in payment order processing.
  • Enhanced error messages to provide clearer feedback on rate validation failures.
  • Introduced a new function, handleCancellationForIndexedOrder, to streamline cancellation handling for existing payment orders, ensuring proper order management during validation failures.
  • Refactored existing cancellation calls to utilize the new function, improving code clarity and maintainability.

Description

Describe the purpose of this PR along with any background information and the impacts of the proposed change. For the benefit of the community, please do not assume prior context.

Provide details that support your chosen implementation, including: breaking changes, alternatives considered, changes to the API, contracts etc.

References

Include any links supporting this change such as a:

If there are no references, simply delete this section.

Testing

Describe how this can be tested by reviewers. Be specific about anything not tested and reasons why. If this project has unit and/or integration testing, tests should be added for new functionality and existing tests should complete without errors.

Please include any manual steps for testing end-to-end or functionality not covered by unit/integration tests.

Also include details of the environment this PR was developed in (language/platform/browser version).

  • 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

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

Summary by CodeRabbit

  • Bug Fixes

    • Rate validation now uses a symmetric tolerance and clearer "outside 0.1% tolerance of market rate" messaging.
    • Cancellation handling and error reporting improved when providers are unavailable.
  • Tests

    • Adjusted test setups and assertions to reflect direct-match rate normalization and settlement/fulfillment behavior.
  • Chores

    • Improved test helper token lookup and provider order token/payout address handling.

…cancellation handling for indexed orders

- Updated rate validation logic to use symmetric tolerance for market rate comparisons, improving accuracy in payment order processing.
- Enhanced error messages to provide clearer feedback on rate validation failures.
- Introduced a new function, handleCancellationForIndexedOrder, to streamline cancellation handling for existing payment orders, ensuring proper order management during validation failures.
- Refactored existing cancellation calls to utilize the new function, improving code clarity and maintainability.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 20, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9e67f785-0d57-4121-98d4-6781ba95e03e

📥 Commits

Reviewing files that changed from the base of the PR and between 7dd7d53 and 9c1d782.

📒 Files selected for processing (3)
  • controllers/provider/provider_test.go
  • controllers/sender/sender_test.go
  • utils/test/db.go

📝 Walkthrough

Walkthrough

Updated rate validation to use symmetric absolute-tolerance checks across sender/order flows and introduced a cancellation helper that prefers updating existing indexed PaymentOrders; adjusted error responses and tightened cancellation error handling.

Changes

Cohort / File(s) Summary
Rate validation (controllers)
controllers/sender/sender.go
Replaced one-sided rate comparisons with symmetric absolute-tolerance check (abs(providedRate - achievableRate) > tolerance) across InitiatePaymentOrder and V2 order flows; updated error messages to state "outside 0.1% tolerance of market rate."
Cancellation handling & order validation (services)
services/common/order.go
Added handleCancellationForIndexedOrder(...) to prefer cancelling/updating an existing indexed PaymentOrder when GatewayID matches; reordered rate-validation to check rateErr first; replaced ignored cancellation errors with explicit returns on failure.
Tests (provider & sender)
controllers/provider/provider_test.go, controllers/sender/sender_test.go
Test setup adjusted to reuse test token; expectations updated for onramp promotion/status; sender tests changed to use normalized direct-match rate "1" and updated comments/assertions.
Test utilities (db helpers)
utils/test/db.go
CreateTestSenderProfile: token lookup supports token_id (int variants) or symbol+optional network filter; non-singular token queries fall back to ordered first result; provider order token creation now derives payout address from payout_address with fallback to settlement_address.

Sequence Diagram(s)

sequenceDiagram
participant Client
participant SenderController as Sender Controller
participant OrderService as Order Service
participant ProviderPool as Provider/Rate Lookup
participant DB as Database

Client->>SenderController: InitiatePaymentOrder(request with providedRate)
SenderController->>ProviderPool: Fetch achievableRate for bucket
ProviderPool-->>SenderController: rateResult (achievableRate) or rateErr
alt rateErr
    SenderController->>OrderService: handleCancellationForIndexedOrder(ctx, indexedOrder?, cancellationFields)
    OrderService-->>DB: find indexed order / create cancellation row
    OrderService-->>SenderController: cancellation result / error
    SenderController-->>Client: return error (wrapped)
else have achievableRate
    SenderController->>SenderController: compute tolerance = achievableRate * 0.001
    SenderController->>SenderController: check abs(providedRate - achievableRate) <= tolerance
    alt outside tolerance
        SenderController->>OrderService: handleCancellationForIndexedOrder(...)
        OrderService-->>DB: update/create cancellation
        SenderController-->>Client: return "outside 0.1% tolerance of market rate" error
    else within tolerance
        SenderController->>OrderService: proceed with order creation/assignment
        OrderService-->>DB: create/lock order
        OrderService->>ProviderPool: assign provider / verify current or prev rate
        OrderService-->>Client: success response
    end
end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

codex

Suggested reviewers

  • chibie
  • 5ran6

Poem

🐇 I hopped through rates both old and new,
I checked the gap — a tolerant view.
If orders wobble, I softly mend,
Prefer the indexed friend to end.
Tiny paws, big fixes — cheers! ✨

🚥 Pre-merge checks | ❌ 5

❌ Failed checks (3 warnings, 2 inconclusive)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning Changes to rate validation logic and cancellation handling partially address issue #407, but previous queue fallback implementation is absent from the changeset. The PR must implement the core requirement from #407: persist previous priority queue rates to Redis and update AssignLockPaymentOrder to check both current and previous rates before order assignment.
Out of Scope Changes check ⚠️ Warning Changes to test utilities (CreateTestSenderProfile token resolution, payout address handling) and test data updates are not directly related to the #407 objective of managing previous priority queue rates. Clarify whether test utility changes are essential to the linked issue. If not, they should be moved to a separate PR or the PR scope should be redefined to include these refactoring improvements.
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is incomplete and truncated with ellipsis ('…'), making it unclear what the full scope of changes includes. Complete the PR title to clearly convey the full purpose. The truncated title should specify the main changes, e.g., 'refactor(sender, order): enhance rate validation and improve cancellation handling for indexed orders'.
Description check ❓ Inconclusive The description includes a summary of changes and a template, but critical sections (References and Testing) are not completed or marked as done. Complete the References section with related issue/PR links, and detail the testing approach. Mark testing checklist item as complete or explain why tests were not added.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 fix-multipleorder-creation-and-rate-assertion
📝 Coding Plan
  • Generate coding plan for human review comments

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.

…ct direct NGN/NGN match

- Modified test cases to use a rate of "1" for NGN/NGN direct matches, ensuring consistency with the updated validation logic.
- Enhanced comments in the test setup to clarify the rationale behind rate normalization and bucket range calculations.
- Improved clarity in test payloads to align with the new rate validation expectations.
…ogic

- Updated test setup to reuse existing tokens, preventing duplicate entries and ensuring consistency in test execution.
- Enhanced the CreateTestSenderProfile function to support token retrieval by ID and improved handling of network associations.
- Adjusted the AddProviderOrderTokenToProvider function to streamline payout address assignment, enhancing clarity and maintainability.
@onahprosper onahprosper merged commit 3f747ee into main Mar 20, 2026
2 checks passed
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.

Save previous provider rates in priority queue to reduce order failures

1 participant