8000 feat(trade): slippage config for integrators by limitofzero · Pull Request #5906 · cowprotocol/cowswap · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat(trade): slippage config for integrators #5906

8000
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 38 commits into
base: develop
Choose a base branch
from

Conversation

limitofzero
Copy link
Contributor
@limitofzero 8000 limitofzero commented Jun 30, 2025

Summary

Resolves #5858

Implemented support for configuring slippage through widget params.

Screenshots with defaultValue equals to 7%:

image image
interface SlippageConfig {
  min?: number          // lower bound in bps
  max?: number          // upper bound in bps
  defaultValue?: number // default in bps
}

Example:

{
  "slippage": {
    "1": {         
      "min": 1,
      "max": 3900,
      "defaultValue": 3000
    },
    "8453": {       // Base
      "min": 500,
      "max": 5000,
      "defaultValue": 600
    }
  }
}
  • min / max — network-specific bounds; values outside the app’s hard limits are ignored.

  • defaultValue — starting value shown in the UI. Must satisfy min ≤ defaultValue ≤ max. If higher than auto slippage, it becomes the initial swap slippage.

  • Added validation in the Configurator:

    • min ≥ 0, max ≤ 50 %, min ≤ defaultValue ≤ 50 %
    • Invalid values shows a validation error in configurator.

When no slippage section is supplied, the widget uses defaults.

To Test

  1. Implement config
    Open the Configurator → paste the JSON above into “RAW JSON params” → click Update widget btn.

    • Slippage in Settings matches the network’s defaultValue if it's less than auto.
  2. Custom slippage warnings

    • Selecting a custom slippage above defaultValue shows “High slippage” warning.
    • Selecting a custom slippage below defaultValue shows “Low slippage – transaction may expire” warning.
  3. Auto-slippage behaviour

    • Auto slippage is applied only when it is greater than defaultValue.

    • Warning
      "Slippage adjusted to {auto}% to ensure quick execution"
      appears only if

      • autoSlippage > defaultValue, and
      • autoSlippage > 5 %(for ETH flow)/2% (for erc20 flow).
  4. ETH-Flow rule

    • If defaultValue < 2 %, ETH-Flow slippage is forced to 2 %.
  5. Scope

    • Configuration works both per-network and as a one for all networks .
  6. Validation

    • Configurator blocks invalid values (min ≥ 0, max ≤ 50 %, min ≤ defaultValue ≤ 50 %).

Summary by CodeRabbit

  • New Features

    • Introduced dynamic slippage configuration and validation, allowing customizable min, max, and default slippage per network and trade type.
    • Added new hooks and utilities for accessing and validating slippage settings in the frontend.
    • Added new utility functions for clamping values and converting slippage from basis points to percent.
    • Added a hook to determine slippage warning parameters dynamically based on user and trade context.
  • Improvements

    • Refactored slippage and fee validation logic for better flexibility and maintainability.
    • Enhanced slippage warning and input components to use dynamic configuration and improved warning logic.
    • Updated trade type mapping for better integration with external widget libraries.
    • Simplified slippage warning display logic and consolidated conditions for better user experience.
  • Bug Fixes

    • Improved accuracy and consistency of slippage warnings and validation across different trade flows.
  • Chores

    • Updated TypeScript interfaces and exports to support new configuration structures.
    • Cleaned up unused code and simplified import statements.
    • Removed deprecated linting rule suppressions for clearer code quality enforcement.

Copy link
vercel bot commented Jun 30, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
cowfi ✅ Ready (Inspect) Visit Preview Jul 3, 2025 11:50am
explorer-dev ✅ Ready (Inspect) Visit Preview Jul 3, 2025 11:50am
swap-dev ✅ Ready (Inspect) Visit Preview Jul 3, 2025 11:50am
widget-configurator ✅ Ready (Inspect) Visit Preview Jul 3, 2025 11:50am
2 Skipped Deployments
Name Status Preview Updated (UTC)
cosmos ⬜️ Ignored (Inspect) Visit Preview Jul 3, 2025 11:50am
sdk-tools ⬜️ Ignored (Inspect) Visit Preview Jul 3, 2025 11:50am

Copy link
Contributor
coderabbitai bot commented Jun 30, 2025

Walkthrough

This update implements a flexible, externally configurable slippage system for the COW widget. It introduces new types, utility functions, and hooks to support per-flow (ERC20/ETH) min, max, and default slippage settings, integrates slippage validation, and refactors components and state to use the new configuration throughout the frontend and widget configurator.

Changes

File(s) / Path(s) Change Summary
libs/widget-lib/src/types.ts, libs/widget-lib/src/flexibleConfig.ts, libs/widget-lib/src/index.ts, libs/widget-lib/src/resolveFlexibleConfigValues.ts Add SlippageConfig/FlexibleSlippageConfig types, flexible config utilities, and export helpers.
apps/widget-configurator/src/app/configurator/types.ts, apps/widget-configurator/src/app/configurator/hooks/useWidgetParamsAndSettings.ts Add slippage to configurator state and ensure it's included in widget params.
apps/cowswap-frontend/src/modules/injectedWidget/utils/validateSlippage.ts, apps/cowswap-frontend/src/modules/injectedWidget/utils/validateWidgetParams.ts Add slippage validation utility and integrate it into widget param validation.
apps/cowswap-frontend/src/modules/tradeSlippage/state/slippageValueAndTypeAtom.ts, apps/cowswap-frontend/src/modules/tradeSlippage/utils/slippage.ts, apps/cowswap-frontend/src/modules/tradeSlippage/utils/slippageBpsToPercent.ts Refactor slippage state to use flexible config and add conversion utilities.
apps/cowswap-frontend/src/modules/tradeSlippage/hooks/useSlippageConfig.ts, apps/cowswap-frontend/src/modules/tradeSlippage/index.tsx Add and export new hook for accessing slippage config.
apps/cowswap-frontend/src/modules/tradeSlippage/containers/HighSuggestedSlippageWarning/index.tsx, apps/cowswap-frontend/src/modules/tradeWidgetAddons/containers/TransactionSlippageInput/index.tsx, apps/cowswap-frontend/src/modules/tradeWidgetAddons/containers/TransactionSlippageInput/hooks/useSlippageWarningParams.ts Refactor slippage warning logic to use new config and hooks.
apps/cowswap-frontend/src/modules/tradeWidgetAddons/containers/TransactionSlippageInput/hooks/useSlippageInput.ts Refactor input validation to use dynamic min/max from config.
apps/cowswap-frontend/src/modules/trade/types/TradeType.ts, apps/cowswap-frontend/src/modules/trade/types/TradeTypeInfo.ts, apps/cowswap-frontend/src/modules/trade/types/index.ts, apps/cowswap-frontend/src/modules/volumeFee/state/volumeFeeAtom.ts Refactor trade type mapping and related exports.
libs/common-utils/src/clamp-value.ts, libs/common-utils/src/index.ts Add and export generic clamp utility.
apps/cowswap-frontend/src/modules/tradeWidgetAddons/containers/DeadlineTransactionSettings/hooks/useCustomDeadline.ts, apps/cowswap-frontend/src/modules/tradeWidgetAddons/containers/DeadlineTransactionSettings/utils/index.ts Replace custom clamp with shared utility and remove redundant code.
apps/cowswap-frontend/src/modules/swap/hooks/useSwapSettings.ts, apps/cowswap-frontend/src/modules/trade/containers/TradeWarnings/index.tsx Add explicit return types to hooks/components.
apps/cowswap-frontend/src/modules/permit/hooks/usePermitInfo.ts, apps/cowswap-frontend/src/modules/hooksStore/dapps/PermitHookApp/index.tsx, apps/cowswap-frontend/src/modules/swap/containers/SwapConfirmModal/useLabelsAndTooltips.tsx, apps/cowswap-frontend/src/modules/tradeSlippage/hooks/useTradeSlippage.ts, apps/cowswap-frontend/src/modules/tradeWidgetAddons/containers/RowSlippage/index.tsx Linting, refactors, and internal logic updates for slippage and smart slippage usage.

Sequence Diagram(s)

sequenceDiagram
    participant Integrator
    participant WidgetConfigurator
    participant WidgetFrontend
    participant SlippageConfig
    participant TradeComponent

    Integrator->>WidgetConfigurator: Set slippage (min, max, default) for ERC20/ETH
    WidgetConfigurator->>WidgetFrontend: Pass slippage config in widget params
    WidgetFrontend->>SlippageConfig: Load slippage config (per trade type/chain)
    TradeComponent->>SlippageConfig: Use hook to get min, max, default
    TradeComponent->>TradeComponent: Validate user input and show warnings based on config
Loading

Assessment against linked issues

Objective Addressed Explanation
Add ability to set default values for both flows: erc20/ETH flow (#5858)
Add ability to set min/max slippage ranges for erc20/ETH flow (#5858)
Configure warnings to match it with new configuration (#5858)
Allow external configuration of slippage in widget params (#5858)

Possibly related PRs

  • cowprotocol/cowswap#5880: Also modifies the HighSuggestedSlippageWarning component to use chain-specific or config-driven slippage thresholds.

Suggested reviewers

  • elena-zh
  • shoom3301
  • alfetopito

Poem

In the meadow where widgets hop,
Slippage bounds now never stop!
Min and max, both ETH and coin,
Configured by you, with code to join.
No more expired swaps, hooray—
This bunny brings smooth trades your way!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

yarn install v1.22.22
[1/4] Resolving packages...
(node:14897) [DEP0169] DeprecationWarning: url.parse() behavior is not standardized and prone to errors that have security implications. Use the WHATWG URL API instead. CVEs are not issued for url.parse() vulnerabilities.
(Use node --trace-deprecation ... to show where the warning was created)
[2/4] Fetching packages...
error nx@21.0.3: The engine "node" is incompatible with this module. Expected version "^20.19.0 || ^22.12.0". Got "24.3.0"
error Found incompatible module.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f7a5ac6 and 852a989.

📒 Files selected for processing (1)
  • apps/cowswap-frontend/src/modules/injectedWidget/utils/validateSlippage.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/cowswap-frontend/src/modules/injectedWidget/utils/validateSlippage.ts
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Cypress
  • GitHub Check: Setup
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@limitofzero
Copy link
Contributor Author

Great work, the PR description is very good.

Some feedback while testing:

  • While the max limit is respected for manual input, suggested slippage can go over it
    image
    image

I would expect it to cap also dynamic slippage, to be consistent. Otherwise, if we'd like to keep the behaviour and allow dynamic slippage to be uncapped, I would not add the max parameter at all.

That's the only thing I observed while testing. Will check the code now

Fixed, thx for highlighting!

@elena-zh
Copy link
Contributor
elena-zh commented Jul 3, 2025

And on Base (and other L2s) it is allowed to set a slippage lower than 0.5% for ETH-flow order

Not an issue! I've been able to reproduce this with a SC wallet, but it is an expected behavior for a SC wallet. Sorry about the noise.

Copy link
Contributor
@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 (1)
libs/widget-lib/src/resolveFlexibleConfigValues.ts (1)

13-13: Remove unnecessary type assertion.

The type assertion as T[] is redundant since TypeScript can infer that config is of type T when it's not a per-trade-type or per-network configuration.

-  return [config] as T[]
+  return [config]
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1192e6c and f7a5ac6.

📒 Files selected for processing (4)
  • apps/cowswap-frontend/src/modules/injectedWidget/utils/validatePartnerFee.ts (1 hunks)
  • apps/cowswap-frontend/src/modules/injectedWidget/utils/validateSlippage.ts (1 hunks)
  • libs/widget-lib/src/index.ts (1 hunks)
  • libs/widget-lib/src/resolveFlexibleConfigValues.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • libs/widget-lib/src/index.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/cowswap-frontend/src/modules/injectedWidget/utils/validatePartnerFee.ts
  • apps/cowswap-frontend/src/modules/injectedWidget/utils/validateSlippage.ts
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: alfetopito
PR: cowprotocol/cowswap#5830
File: apps/cowswap-frontend/src/modules/tradeQuote/hooks/useSmartSlippageFromQuote.ts:5-9
Timestamp: 2025-06-16T15:58:57.402Z
Learning: In the cowswap system, 0 bps will never be suggested as a slippage value, so falsy checks on suggested slippage values are safe and won't drop valid 0 values.
🧬 Code Graph Analysis (1)
libs/widget-lib/src/resolveFlexibleConfigValues.ts (2)
libs/widget-lib/src/types.ts (1)
  • FlexibleConfig (10-15)
libs/widget-lib/src/flexibleConfig.ts (2)
  • isPerTradeTypeConfig (27-31)
  • isPerNetworkConfig (35-39)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Setup
  • GitHub Check: Cypress
🔇 Additional comments (1)
libs/widget-lib/src/resolveFlexibleConfigValues.ts (1)

1-14: LGTM! Clean implementation with proper type safety.

The function correctly handles all variants of the FlexibleConfig<T> type, including nested configurations. The logic is clear and the use of flatMap efficiently flattens nested structures.

@limitofzero
Copy link
Contributor Author

@elena-zh I've fixed the case with min == max value in config, thx for catching that edge case!

Copy link
Contributor
@elena-zh elena-zh left a comment

Choose a reason for hiding this comment

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

Looks good, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Configuring slippage for COW widget
4 participants
0