Repository: cowprotocol/cowswap
Pull request #5495: fix: issue #5490
Author: login: cowdan
Created: 2025-03-10T14:53:52Z | Merged: 2025-03-13T13:20:05Z

# Summary

Fixes [#5490](https://github.com/cowprotocol/cowswap/issues/5490)



<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit

- **New Features**
  - Introduced a new function for creating limit orders with fees, enhancing order structure.
  - Added a new test suite to verify calculations of remainder amounts under various conditions.

- **Refactor**
  - Simplified surplus amount calculations by encapsulating logic in a new helper function.
  - Streamlined handling of executed amounts for improved clarity and maintainability.

- **Tests**
  - Expanded test coverage to validate the new functionality and ensure accurate order amount computations.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->


Diff:
diff --git a/apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts b/apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts
index 0c18ee21f46..c3ef39f13aa 100644
--- a/apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts
+++ b/apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts
@@ -1,36 +1,160 @@
 import { USDC_MAINNET, WETH_MAINNET } from '@cowprotocol/common-const'
-import { OrderClass } from '@cowprotocol/cow-sdk'
+import { OrderClass, OrderKind, SigningScheme } from '@cowprotocol/cow-sdk'
 import { Price } from '@uniswap/sdk-core'
 
-import { Order } from './actions'
-import { getEstimatedExecutionPrice } from './utils'
+import BigNumber from 'bignumber.js'
+import JSBI from 'jsbi'
 
-const getOrderWithFee = (sellAmountBeforeFee: number, buyAmount: number, fee: number): Order => ({
+import { Order, OrderStatus } from './actions'
+import { getEstimatedExecutionPrice, getRemainderAmountsWithoutSurplus } from './utils'
+
+
+const getLimitOrderWithFee = (
+  sellAmountBeforeFee: string,
+  buyAmount: string,
+  fee: string,
+  orderKind: OrderKind = OrderKind.SELL,
+): Order => ({
+  owner: '',
+  status: OrderStatus.CREATING,
+  summary: '',
+  creationTime: '',
+  sellToken: '',
+  buyToken: '',
+  validTo: 0,
+  feeAmount: '',
+  kind: orderKind,
+  partiallyFillable: false,
   id: '',
   inputToken: WETH_MAINNET,
   outputToken: USDC_MAINNET,
-  sellAmountBeforeFee: sellAmountBeforeFee.toString(),
-  sellAmount: (sellAmountBeforeFee - fee).toString(),
-  buyAmount: buyAmount.toString(),
+  sellAmountBeforeFee,
+  sellAmount: new BigNumber(sellAmountBeforeFee).minus(new BigNumber(fee)).toString(),
+  buyAmount: new BigNumber(buyAmount).toString(),
   class: OrderClass.LIMIT,
+  appData: '',
+  signingScheme: SigningScheme.EIP712,
+  signature: '',
 })
 
 describe('getEstimatedExecutionPrice()', () => {
   it('Should take the fee into account for the estimated execution price calculation', () => {
-    const fee = 0.00021 * 10 ** WETH_MAINNET.decimals
-    const sellAmountBeforeFee = 100 * 10 ** WETH_MAINNET.decimals
-    const buyAmount = 182000 * 10 ** USDC_MAINNET.decimals
+    const fee = new BigNumber(0.00021).times(10 ** WETH_MAINNET.decimals).toString()
+    const sellAmountBeforeFee = new BigNumber(100).times(10 ** WETH_MAINNET.decimals).toString()
+    const buyAmount = new BigNumber(182000).times(10 ** USDC_MAINNET.decimals).toString()
 
     const fillPrice = new Price(WETH_MAINNET, USDC_MAINNET, '10000000000', '1')
 
-    const orderWithFee = getOrderWithFee(sellAmountBeforeFee, buyAmount, fee)
+    const orderWithFee = getLimitOrderWithFee(sellAmountBeforeFee, buyAmount, fee)
     const executionPriceWithFee = getEstimatedExecutionPrice(orderWithFee, fillPrice, fee.toString())
 
-    const zeroFee = 0
-    const orderWithoutFee = getOrderWithFee(sellAmountBeforeFee, buyAmount, zeroFee)
+    const zeroFee = new BigNumber(0).toString()
+    const orderWithoutFee = getLimitOrderWithFee(sellAmountBeforeFee, buyAmount, zeroFee)
     const executionPriceWithoutFee = getEstimatedExecutionPrice(orderWithoutFee, fillPrice, zeroFee.toString())
 
     expect(executionPriceWithFee?.toFixed(12)).toEqual('1820.007835117276')
     expect(executionPriceWithoutFee?.toFixed(12)).toEqual('1820.000000000000')
   })
 })
+
+describe('getRemainderAmountsWithoutSurplus()', () => {
+  it('Should return the remainder amounts without the surplus', () => {
+    const fee = new BigNumber(0.00016).times(10 ** WETH_MAINNET.decimals).toString()
+    const sellAmountBeforeFee = new BigNumber(99).times(10 ** WETH_MAINNET.decimals).toString()
+    const buyAmount = new BigNumber(17345).times(10 ** USDC_MAINNET.decimals).toString()
+
+    const order = getLimitOrderWithFee(sellAmountBeforeFee, buyAmount, fee, OrderKind.SELL)
+    const remainderAmounts = getRemainderAmountsWithoutSurplus(order)
+
+    expect(remainderAmounts.buyAmount).toEqual('17345000000')
+    expect(remainderAmounts.sellAmount).toEqual('99000000000000000000')
+  })
+
+  it('should return the full amount if there is no surplus', () => {
+    const fee = new BigNumber(0).toString()
+    const sellAmountBeforeFee = new BigNumber(100).times(10 ** WETH_MAINNET.decimals).toString()
+    const buyAmount = new BigNumber(100).times(10 ** USDC_MAINNET.decimals).toString()
+
+    const order = getLimitOrderWithFee(sellAmountBeforeFee, buyAmount, fee)
+    const remainderAmounts = getRemainderAmountsWithoutSurplus(order)
+
+    expect(remainderAmounts.buyAmount).toEqual('100000000')
+    expect(remainderAmounts.sellAmount).toEqual('100000000000000000000')
+  })
+
+  it('should return the remainder amounts if there is a surplus when passing a SELL ParsedOrder', () => {
+    const fee = new BigNumber(0.1).times(10 ** WETH_MAINNET.decimals).toString()
+    const sellAmountBeforeFee = new BigNumber(101).times(10 ** WETH_MAINNET.decimals).toString()
+    const buyAmount = new BigNumber(12345567).times(10 ** USDC_MAINNET.decimals).toString()
+
+    const order = getLimitOrderWithFee(sellAmountBeforeFee, buyAmount, fee, OrderKind.SELL)
+
+    ;(order as any).executionData = {
+      executedSellAmount: new BigNumber(99 * 10 ** WETH_MAINNET.decimals),
+      executedBuyAmount: new BigNumber(12345566 * 10 ** USDC_MAINNET.decimals),
+      surplusAmount: new BigNumber(3 * 10 ** WETH_MAINNET.decimals),
+    }
+
+    const remainderAmounts = getRemainderAmountsWithoutSurplus(order)
+
+    expect(remainderAmounts.buyAmount).toEqual('-2999999999999000000')
+    expect(remainderAmounts.sellAmount).toEqual('1900000000000000000')
+  })
+
+  it('should return the remainder amounts if there is a surplus when passing a BUY ParsedOrder', () => {
+    const fee = new BigNumber(0.1).times(10 ** WETH_MAINNET.decimals).toString()
+    const sellAmountBeforeFee = new BigNumber(101).times(10 ** WETH_MAINNET.decimals).toString()
+    const buyAmount = new BigNumber(12345567).times(10 ** USDC_MAINNET.decimals).toString()
+
+    const order = getLimitOrderWithFee(sellAmountBeforeFee, buyAmount, fee, OrderKind.BUY)
+
+    ;(order as any).executionData = {
+      executedSellAmount: new BigNumber(101 * 10 ** WETH_MAINNET.decimals),
+      executedBuyAmount: new BigNumber(12345566 * 10 ** USDC_MAINNET.decimals),
+      surplusAmount: new BigNumber(2 * 10 ** WETH_MAINNET.decimals),
+    }
+
+    const remainderAmounts = getRemainderAmountsWithoutSurplus(order)
+
+    expect(remainderAmounts.buyAmount).toEqual('1000000')
+    expect(remainderAmounts.sellAmount).toEqual('1900000000000000000')
+  })
+
+  it('should return the remainder amounts if there is surplus when passing a SELL Order', () => {
+    const fee = new BigNumber(0.02).times(10 ** WETH_MAINNET.decimals).toString()
+    const sellAmountBeforeFee = new BigNumber(304).times(10 ** WETH_MAINNET.decimals).toString()
+    const buyAmount = new BigNumber(6763849).times(10 ** USDC_MAINNET.decimals).toString()
+
+    const order = getLimitOrderWithFee(sellAmountBeforeFee, buyAmount, fee, OrderKind.SELL)
+
+    ;(order as any).apiAdditionalInfo = {
+      executedSellAmountBeforeFees: JSBI.BigInt(17),
+      executedBuyAmount: JSBI.BigInt(16),
+      partiallyFillable: true,
+    }
+
+    const remainderAmounts = getRemainderAmountsWithoutSurplus(order)
+
+    expect(remainderAmounts.buyAmount).toEqual('6763848999984')
+    expect(remainderAmounts.sellAmount).toEqual('303999999999999999983')
+  })
+
+  it('should return the remainder amounts if there is surplus when passing a BUY Order', () => {
+    const fee = new BigNumber(1.1).times(10 ** WETH_MAINNET.decimals).toString()
+    const sellAmountBeforeFee = new BigNumber(10.3).times(10 ** WETH_MAINNET.decimals).toString()
+    const buyAmount = new BigNumber(11224).times(10 ** USDC_MAINNET.decimals).toString()
+
+    const order = getLimitOrderWithFee(sellAmountBeforeFee, buyAmount, fee, OrderKind.BUY)
+
+    ;(order as any).apiAdditionalInfo = {
+      executedSellAmountBeforeFees: JSBI.BigInt(3),
+      executedBuyAmount: JSBI.BigInt(2),
+      partiallyFillable: true,
+    }
+
+    const remainderAmounts = getRemainderAmountsWithoutSurplus(order)
+
+    expect(remainderAmounts.buyAmount).toEqual('11223999998')
+    expect(remainderAmounts.sellAmount).toEqual('19499999999999999994')
+  })
+})
diff --git a/apps/cowswap-frontend/src/legacy/state/orders/utils.ts b/apps/cowswap-frontend/src/legacy/state/orders/utils.ts
index 84884fc2e5b..3e1f2bcfde6 100644
--- a/apps/cowswap-frontend/src/legacy/state/orders/utils.ts
+++ b/apps/cowswap-frontend/src/legacy/state/orders/utils.ts
@@ -387,21 +387,13 @@ export function getRemainderAmountsWithoutSurplus(order: Order | ParsedOrder): {
 } {
   const sellRemainder = getRemainderAmount(OrderKind.SELL, order)
   const buyRemainder = getRemainderAmount(OrderKind.BUY, order)
-
-  let surplusAmountBigNumber: BigNumber
-  if ('executionData' in order) {
-    // ParsedOrder
-    surplusAmountBigNumber = order.executionData.surplusAmount
-  } else {
-    // Order
-    surplusAmountBigNumber = getOrderSurplus(order).amount
-  }
+  const surplusAmountBigNumber = getSurplusAmountBigNumber(order)
 
   if (surplusAmountBigNumber.isZero()) {
     return { sellAmount: sellRemainder, buyAmount: buyRemainder }
   }
 
-  const surplusAmount = JSBI.BigInt(surplusAmountBigNumber.decimalPlaces(0).toString())
+  const surplusAmount = JSBI.BigInt(`0x${surplusAmountBigNumber.decimalPlaces(0).toString(16)}`)
 
   if (isSellOrder(order.kind)) {
     const buyAmount = JSBI.subtract(JSBI.BigInt(buyRemainder), surplusAmount).toString()
@@ -414,6 +406,15 @@ export function getRemainderAmountsWithoutSurplus(order: Order | ParsedOrder): {
   }
 }
 
+function getSurplusAmountBigNumber(order: Order | ParsedOrder): BigNumber {
+  if ('executionData' in order) {
+    // ParsedOrder
+    return order.executionData.surplusAmount
+  }
+  // Order
+  return getOrderSurplus(order).amount
+}
+
 /**
  * Get the remainder `kind` amount, based on executed amounts from the `apiAdditionalInfo`, if any
  *
@@ -425,6 +426,21 @@ export function getRemainderAmountsWithoutSurplus(order: Order | ParsedOrder): {
  */
 export function getRemainderAmount(kind: OrderKind, order: Order | ParsedOrder): string {
   const buyAmount = order.buyAmount.toString()
+
+  const { sellAmount, executedSellAmount, executedBuyAmount } = getExecutedAmounts(order)
+
+  const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
+
+  if (!executedSellAmount || !executedBuyAmount || executedSellAmount === '0' || executedBuyAmount === '0') {
+    return fullAmount
+  }
+
+  const executedAmount = JSBI.BigInt((isSellOrder(kind) ? executedSellAmount : executedBuyAmount) || 0)
+
+  return JSBI.subtract(JSBI.BigInt(fullAmount), executedAmount).toString()
+}
+
+function getExecutedAmounts(order: Order | ParsedOrder) {
   let sellAmount: string
   let executedSellAmount: string | undefined
   let executedBuyAmount: string | undefined
@@ -441,15 +457,7 @@ export function getRemainderAmount(kind: OrderKind, order: Order | ParsedOrder):
     executedBuyAmount = order.apiAdditionalInfo?.executedBuyAmount
   }
 
-  const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
-
-  if (!executedSellAmount || !executedBuyAmount || executedSellAmount === '0' || executedBuyAmount === '0') {
-    return fullAmount
-  }
-
-  const executedAmount = JSBI.BigInt((isSellOrder(kind) ? executedSellAmount : executedBuyAmount) || 0)
-
-  return JSBI.subtract(JSBI.BigInt(fullAmount), executedAmount).toString()
+  return { sellAmount, executedSellAmount, executedBuyAmount }
 }
 
 function extrapolatePriceBasedOnFeeAmount<T extends Currency>(


Reviews:
user: login: coderabbitai[bot]
body: **Actionable comments posted: 2**

<details>
<summary>📜 Review details</summary>

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

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 41354f816418900d21e77dca1228a66fba9027d5 and ebfe124e101297d0439a67d9cc8bdf63e8883909.

</details>

<details>
<summary>📒 Files selected for processing (2)</summary>

* `apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts` (2 hunks)
* `apps/cowswap-frontend/src/legacy/state/orders/utils.ts` (1 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🪛 Biome (1.9.4)</summary>

<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts</summary>

[error] 48-48: This number literal will lose precision at runtime.

The value at runtime will be 642619072256475100000000

(lint/correctness/noPrecisionLoss)

---

[error] 49-49: This number literal will lose precision at runtime.

The value at runtime will be 412319564256475900000000

(lint/correctness/noPrecisionLoss)

</details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (2)</summary>

* GitHub Check: Cypress
* GitHub Check: Setup

</details>

<details>
<summary>🔇 Additional comments (1)</summary><blockquote>

<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts (1)</summary>

`8-23`: **LGTM: Clear improvement with additional order kind parameter**

The new `getLimitOrderWithFee` function enhances flexibility by adding the `orderKind` parameter with a sensible default to `OrderKind.SELL`.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-10T15:03:03Z
user: login: shoom3301
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-03-10T15:15:35Z
user: login: alfetopito
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-03-10T16:02:42Z
user: login: coderabbitai[bot]
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-10T16:03:12Z
user: login: shoom3301
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-03-10T16:12:55Z
user: login: anxolin
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-10T17:16:43Z
user: login: coderabbitai[bot]
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-10T17:16:49Z
user: login: elena-zh
body: I've been trying to test the changes and find any token's combination and a trade amount that will lead to crash, but I've not been able to. 
Based on the [sentry errors logging](https://cowprotocol.sentry.io/issues/6338603447/events/?end=2025-03-11T23%3A59%3A59&environment=production&project=5905822&referrer=issue-stream&start=2025-03-09T00%3A00%3A00&stream_index=0&utc=true), we have a lot of crashes with different token pairs, and more than often the crash happens on navigation from Swap to Limit orders page. 
 Anyways, might it be possible to help me to 'emulate' a way to reproduce the issue to test the PR? 

Thanks
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-11T10:16:17Z
user: login: cowdan
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-11T11:16:49Z
user: login: shoom3301
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-03-11T11:23:44Z
user: login: coderabbitai[bot]
body: **Actionable comments posted: 0**

<details>
<summary>🔭 Outside diff range comments (2)</summary><blockquote>

<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts (2)</summary><blockquote>

`25-43`: _⚠️ Potential issue_

**Duplicate describe block for 'getEstimatedExecutionPrice()'.**

There are two identical describe blocks for the same test (lines 25-28 and 28-43). Remove the first empty block to avoid confusion.

```diff
- describe('getEstimatedExecutionPrice()', () => {
-   it('Should take the fee into account for the estimated execution price calculation', () => {
-
```

---

`59-61`: _⚠️ Potential issue_

**Text outside of test blocks.**

Line 59-61 contains test expectations outside any test block. This code might be a remnant from incomplete edits and should be removed.

```diff
- expect(remainderAmounts.sellAmount).toEqual('6.426190722564751e+23')
-  })
```

</blockquote></details>

</blockquote></details>

<details>
<summary>♻️ Duplicate comments (1)</summary><blockquote>

<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts (1)</summary><blockquote>

`45-57`: _⚠️ Potential issue_

**Precision loss in test number literals.**

The test values in lines 48-49 are extremely large scientific notation numbers that will lose precision at runtime when converted to JavaScript numbers.

To maintain precision in these large test values, use string representation:

```diff
- 6.42619072256475129773952e23,
- 4.12319564256475887773621e23,
+ "642619072256475129773952",
+ "412319564256475887773621",
```

Alternatively, you could use BigInt literals (with `n` suffix) if your environment supports them.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 Biome (1.9.4)</summary>

[error] 51-51: This number literal will lose precision at runtime.

The value at runtime will be 642619072256475100000000

(lint/correctness/noPrecisionLoss)

---

[error] 52-52: This number literal will lose precision at runtime.

The value at runtime will be 412319564256475900000000

(lint/correctness/noPrecisionLoss)

</details>

</details>

</blockquote></details>

</blockquote></details>

<details>
<summary>🧹 Nitpick comments (1)</summary><blockquote>

<details>
<summary>apps/cowswap-frontend/src/modules/swap/containers/TradeButtons/swapTradeButtonsMap.tsx (1)</summary><blockquote>

`61-71`: **Missing parameter in SellNativeInHooks function signature.**

While this function ignores the `isDisabled` parameter (since it's always disabled), its signature should be updated for consistency with the other implementations and to match the type definition.

```diff
- [SwapFormState.SellNativeInHooks]: (props: SwapTradeButtonsContext) => {
+ [SwapFormState.SellNativeInHooks]: (props: SwapTradeButtonsContext, isDisabled: boolean) => {
```

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

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

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between ebfe124e101297d0439a67d9cc8bdf63e8883909 and 7ef378a416b321760103efa6e5cdaedbd8a874db.

</details>

<details>
<summary>📒 Files selected for processing (18)</summary>

* `apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts` (2 hunks)
* `apps/cowswap-frontend/src/legacy/state/orders/utils.ts` (1 hunks)
* `.release-please-manifest.json` (1 hunks)
* `apps/cowswap-frontend/CHANGELOG.md` (1 hunks)
* `apps/cowswap-frontend/package.json` (1 hunks)
* `.release-please-manifest.json` (1 hunks)
* `apps/cowswap-frontend/CHANGELOG.md` (1 hunks)
* `apps/cowswap-frontend/package.json` (1 hunks)
* `apps/cowswap-frontend/src/modules/swap/containers/TradeButtons/index.tsx` (1 hunks)
* `apps/cowswap-frontend/src/modules/swap/containers/TradeButtons/swapTradeButtonsMap.tsx` (1 hunks)
* `apps/cowswap-frontend/src/modules/swap/containers/Warnings/index.tsx` (2 hunks)
* `apps/cowswap-frontend/src/modules/ordersTable/containers/OrderRow/EstimatedExecutionPrice.tsx` (1 hunks)
* `apps/cowswap-frontend/src/modules/ordersTable/containers/OrderRow/styled.tsx` (1 hunks)
* `apps/cowswap-frontend/src/modules/ordersTable/pure/OrderFillsAt/index.tsx` (1 hunks)
* `apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts` (2 hunks)
* `apps/cowswap-frontend/src/legacy/state/orders/utils.ts` (2 hunks)
* `apps/cowswap-frontend/src/modules/volumeFee/state/cowswapFeeAtom.ts` (1 hunks)
* `libs/ui/src/consts.ts` (1 hunks)

</details>

<details>
<summary>✅ Files skipped from review due to trivial changes (5)</summary>

* apps/cowswap-frontend/package.json
* libs/ui/src/consts.ts
* .release-please-manifest.json
* .release-please-manifest.json
* apps/cowswap-frontend/package.json

</details>

<details>
<summary>🚧 Files skipped from review as they are similar to previous changes (2)</summary>

* apps/cowswap-frontend/src/legacy/state/orders/utils.ts
* apps/cowswap-frontend/src/legacy/state/orders/utils.ts

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🪛 Biome (1.9.4)</summary>

<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts</summary>

[error] 72-72: This number literal will lose precision at runtime.

The value at runtime will be 1242619072256475000000000

(lint/correctness/noPrecisionLoss)

---

[error] 73-73: This number literal will lose precision at runtime.

The value at runtime will be 2312319564256475900000000

(lint/correctness/noPrecisionLoss)

---

[error] 92-92: This number literal will lose precision at runtime.

The value at runtime will be 4542619072256475300000000

(lint/correctness/noPrecisionLoss)

---

[error] 93-93: This number literal will lose precision at runtime.

The value at runtime will be 4112319564256476000000000

(lint/correctness/noPrecisionLoss)

---

[error] 112-112: This number literal will lose precision at runtime.

The value at runtime will be 1742619072256475000000000

(lint/correctness/noPrecisionLoss)

---

[error] 113-113: This number literal will lose precision at runtime.

The value at runtime will be 1612319564256475800000000

(lint/correctness/noPrecisionLoss)

---

[error] 132-132: This number literal will lose precision at runtime.

The value at runtime will be 1142619072256475100000000

(lint/correctness/noPrecisionLoss)

---

[error] 133-133: This number literal will lose precision at runtime.

The value at runtime will be 1012319564256475900000000

(lint/correctness/noPrecisionLoss)

---

[error] 51-51: This number literal will lose precision at runtime.

The value at runtime will be 642619072256475100000000

(lint/correctness/noPrecisionLoss)

---

[error] 52-52: This number literal will lose precision at runtime.

The value at runtime will be 412319564256475900000000

(lint/correctness/noPrecisionLoss)

</details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (3)</summary>

* GitHub Check: Test
* GitHub Check: Lint
* GitHub Check: Cypress

</details>

<details>
<summary>🔇 Additional comments (13)</summary><blockquote>

<details>
<summary>apps/cowswap-frontend/src/modules/volumeFee/state/cowswapFeeAtom.ts (1)</summary>

`27-27`: **Simplification of fee application logic**

The code now only destructures `chainId` from the `walletInfoAtom` instead of both `chainId` and `account`. This change aligns with the removal of the `shouldApplyFee` function mentioned in the summary, simplifying the fee application logic by eliminating account-based checks.

</details>
<details>
<summary>apps/cowswap-frontend/src/modules/ordersTable/containers/OrderRow/styled.tsx (1)</summary>

`218-221`: **Good addition of the warning component for consistent styling.**

The new `ExecuteInformationTooltipWarning` styled component provides a consistent styling for warning messages in tooltips, with appropriate font weight and spacing.

</details>
<details>
<summary>apps/cowswap-frontend/src/modules/swap/containers/Warnings/index.tsx (2)</summary>

`9-9`: **Clean import addition for the new banner component.**

The import statement correctly adds the `BundleTxWrapBanner` along with existing components from the same module.

---

`37-37`: **Good enhancement to user warnings system.**

Adding the `BundleTxWrapBanner` component alongside other warning components enhances the user feedback system for transaction-related warnings.

</details>
<details>
<summary>apps/cowswap-frontend/src/modules/ordersTable/pure/OrderFillsAt/index.tsx (1)</summary>

`163-165`: **Excellent transparency improvement for price data.**

Adding this warning message clearly informs users about the potential limitations of the price data being displayed, which is important for making informed trading decisions.

</details>
<details>
<summary>apps/cowswap-frontend/src/modules/ordersTable/containers/OrderRow/EstimatedExecutionPrice.tsx (1)</summary>

`261-263`: **Great consistency in price data warnings.**

This warning message maintains consistency with the one added to the `OrderFillsAt` component, ensuring users receive the same important information about price data reliability across different parts of the interface.

</details>
<details>
<summary>apps/cowswap-frontend/CHANGELOG.md (2)</summary>

`3-4`: **New Version Entry Added**

A new version entry for **[1.103.4]** (dated 2025‑03‑10) has been added. The entry follows the established changelog style with a clear URL to compare versions. Please double-check that the version number and release date accurately reflect the intended fix, and that it is consistent with other associated version updates (e.g. in package.json or release manifests).

---

`6-9`: **Bug Fix Entry: Swap Quote Update**

The changelog now includes a “Bug Fixes” section under the new version, documenting the update to the quote in the confirm screen (with issue [#5485] and the corresponding commit hash). This entry clearly communicates the fix related to the swap functionality. However, note that the pull request title references issue #5490. Please verify that the changelog entry correctly reflects the change (or if multiple issues are interrelated) and consider clarifying the reference if necessary.

</details>
<details>
<summary>apps/cowswap-frontend/src/modules/swap/containers/TradeButtons/index.tsx (2)</summary>

`67-68`: **Good update to handle button disabled state.**

The addition of the `isDisabled` parameter to the `swapTradeButtonsMap` function call ensures consistent disabled state management across different trade button types. This aligns with the disabled state already being passed to `TradeFormButtons` on line 76.

---

`63-63`: **Well-defined disabled state logic.**

The `isDisabled` variable properly combines three important conditions that should prevent user interaction: trade context readiness, fee warning acceptance, and no-impact warning acceptance.

</details>
<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts (1)</summary>

`8-24`: **Good enhancement with `getLimitOrderWithFee` function.**

The new function properly extends functionality by adding the `orderKind` parameter with a sensible default value. This improves API flexibility while maintaining backward compatibility.

</details>
<details>
<summary>apps/cowswap-frontend/src/modules/swap/containers/TradeButtons/swapTradeButtonsMap.tsx (2)</summary>

`30-30`: **Good type definition update.**

The `SwapTradeButton` type is correctly updated to include the `isDisabled` parameter, ensuring type safety across the codebase.

---

`33-60`: **Consistent disabled state implementation.**

The implementations for `SwapWithWrappedToken`, `WrapAndSwap`, and `RegularEthFlowSwap` now properly accept and utilize the `isDisabled` parameter, ensuring consistent button behavior.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-11T11:23:51Z
user: login: shoom3301
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-03-11T11:24:36Z
user: login: cowdan
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-11T11:27:40Z
user: login: elena-zh
body: Thanks @cowdan !
Since I cannot test, approving. I will start monitoring sentry errors after the PR is merged. I will let you know once I notice these errors appearing again there. 
state: APPROVED
author_association: CONTRIBUTOR
submitted_at: 2025-03-11T13:42:04Z
user: login: alfetopito
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-03-11T14:49:07Z
user: login: cowdan
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-12T17:00:47Z
user: login: cowdan
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-12T17:05:24Z
user: login: shoom3301
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-03-13T08:39:45Z
user: login: shoom3301
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-03-13T08:50:05Z
user: login: shoom3301
state: COMMENTED
author_association: COLLABORATOR
submitted_at: 2025-03-13T08:50:39Z
user: login: coderabbitai[bot]
body: **Actionable comments posted: 1**

<details>
<summary>♻️ Duplicate comments (1)</summary><blockquote>

<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts (1)</summary><blockquote>

`129-131`: _⚠️ Potential issue_

**Fix precision loss in large number literals**

Similar to the previous issue, these scientific notation numbers will lose precision at runtime.

```diff
-      11.42619072256475129773952e23,
-      10.12319564256475887773621e23,
+      "1142619072256475129773952000",
+      "1012319564256475887773621000",
```

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 Biome (1.9.4)</summary>

[error] 129-129: This number literal will lose precision at runtime.

The value at runtime will be 1142619072256475100000000

(lint/correctness/noPrecisionLoss)

---

[error] 130-130: This number literal will lose precision at runtime.

The value at runtime will be 1012319564256475900000000

(lint/correctness/noPrecisionLoss)

</details>

</details>

</blockquote></details>

</blockquote></details>

<details>
<summary>🧹 Nitpick comments (2)</summary><blockquote>

<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts (2)</summary><blockquote>

`5-6`: **Unused import**

The `BigNumber` import is defined but never used in this file.

```diff
-import BigNumber from 'bignumber.js'
 import JSBI from 'jsbi'
```

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 ESLint</summary>

[error] 5-5: 'BigNumber' is defined but never used.

(unused-imports/no-unused-imports)

</details>

</details>

---

`48-146`: **Enable the skipped tests**

Several test cases are marked with `it.skip` which means they aren't being executed. After fixing the precision issues, these tests should be enabled to ensure complete coverage.

```diff
-  it.skip('should return the remainder amounts if there is a surplus when passing a BUY ParsedOrder', () => {
+  it('should return the remainder amounts if there is a surplus when passing a BUY ParsedOrder', () => {

-  it.skip('should return the remainder amounts if there is surplus when passing a SELL Order', () => {
+  it('should return the remainder amounts if there is surplus when passing a SELL Order', () => {

-  it.skip('should return the remainder amounts if there is surplus when passing a BUY Order', () => {
+  it('should return the remainder amounts if there is surplus when passing a BUY Order', () => {
```

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 Biome (1.9.4)</summary>

[error] 109-109: This number literal will lose precision at runtime.

The value at runtime will be 1742619072256475000000000

(lint/correctness/noPrecisionLoss)

---

[error] 110-110: This number literal will lose precision at runtime.

The value at runtime will be 1612319564256475800000000

(lint/correctness/noPrecisionLoss)

---

[error] 129-129: This number literal will lose precision at runtime.

The value at runtime will be 1142619072256475100000000

(lint/correctness/noPrecisionLoss)

---

[error] 130-130: This number literal will lose precision at runtime.

The value at runtime will be 1012319564256475900000000

(lint/correctness/noPrecisionLoss)

</details>

</details>

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

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

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between 78deac41d9f4eb1f1ad2f27abb942fc015bae7d0 and d06887f5d63848e92c7529ff776dede51be381a7.

</details>

<details>
<summary>📒 Files selected for processing (2)</summary>

* `apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts` (2 hunks)
* `apps/cowswap-frontend/src/legacy/state/orders/utils.ts` (4 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🧠 Learnings (1)</summary>

<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/utils.ts (1)</summary>

```
Learnt from: alfetopito
PR: cowprotocol/cowswap#5495
File: apps/cowswap-frontend/src/legacy/state/orders/utils.ts:444-452
Timestamp: 2025-03-12T14:18:53.253Z
Learning: When working with large numbers in JavaScript, especially token amounts with many decimals, avoid conversions through Number() before BigInt to prevent precision loss. Instead, pass string representations directly to JSBI.BigInt().
```

</details>

</details><details>
<summary>🪛 ESLint</summary>

<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts</summary>

[error] 5-5: 'BigNumber' is defined but never used.

(unused-imports/no-unused-imports)

</details>

</details>
<details>
<summary>🪛 Biome (1.9.4)</summary>

<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts</summary>

[error] 109-109: This number literal will lose precision at runtime.

The value at runtime will be 1742619072256475000000000

(lint/correctness/noPrecisionLoss)

---

[error] 110-110: This number literal will lose precision at runtime.

The value at runtime will be 1612319564256475800000000

(lint/correctness/noPrecisionLoss)

---

[error] 129-129: This number literal will lose precision at runtime.

The value at runtime will be 1142619072256475100000000

(lint/correctness/noPrecisionLoss)

---

[error] 130-130: This number literal will lose precision at runtime.

The value at runtime will be 1012319564256475900000000

(lint/correctness/noPrecisionLoss)

</details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (3)</summary>

* GitHub Check: Test
* GitHub Check: Lint
* GitHub Check: Cypress

</details>

<details>
<summary>🔇 Additional comments (10)</summary><blockquote>

<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts (5)</summary>

`11-26`: **Well-structured function implementation**

The new `getLimitOrderWithFee` function properly extends the previous functionality by adding the `orderKind` parameter with a default value, making it backward compatible while supporting the additional use cases needed for testing.

---

`36-41`: **Correctly updated test cases**

The existing tests are properly updated to use the new `getLimitOrderWithFee` function.

---

`48-59`: **Good coverage of base case**

The test case provides good coverage for the basic scenario without surplus amounts.

---

`61-67`: **Testing the edge case**

This test verifies the function behaves correctly when there is no surplus, an important edge case.

---

`84-86`: **Precision issue in test constants**

The expected values here are extremely large and may need to be represented as strings to avoid precision loss.

```diff
-    expect(remainderAmounts.buyAmount).toEqual('2312319564256475852308472')
-    expect(remainderAmounts.sellAmount).toEqual('1242619072256475131805692')
+    expect(remainderAmounts.buyAmount).toEqual('2312319564256475852308472')
+    expect(remainderAmounts.sellAmount).toEqual('1242619072256475131805692')
```

</details>
<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/utils.ts (5)</summary>

`390-391`: **Good abstraction of surplus calculation**

Extracting the surplus amount calculation to a dedicated function improves code organization and readability.

---

`396-396`: **Improved BigInt conversion using hexadecimal**

Converting the BigNumber to a hexadecimal string before creating a BigInt is a more robust approach to handle large numbers without precision loss.

---

`409-416`: **Well-structured utility function**

The new `getSurplusAmountBigNumber` function properly handles both ParsedOrder and Order types, making the code more maintainable.

---

`429-441`: **Fixed precision loss by removing Number conversion**

The refactored code now avoids converting string amounts to Number before creating BigInt, which prevents precision loss with large token amounts.


This improvement aligns with the retrieved learning: "When working with large numbers in JavaScript, especially token amounts with many decimals, avoid conversions through Number() before BigInt to prevent precision loss."

---

`443-461`: **Good separation of concerns**

Extracting the common logic for getting executed amounts into a separate function improves code organization and reduces duplication.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-13T09:50:38Z
user: login: coderabbitai[bot]
body: **Actionable comments posted: 0**

<details>
<summary>♻️ Duplicate comments (1)</summary><blockquote>

<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts (1)</summary><blockquote>

`109-110`: _⚠️ Potential issue_

**Fix precision loss in large number literals.**

The scientific notation numbers will lose precision at runtime. These should be represented as strings.

```diff
-      17.42619072256475129773952e23,
-      16.12319564256475887773621e23,
+      "1742619072256475129773952000",
+      "1612319564256475887773621000",
```

```diff
-      11.42619072256475129773952e23,
-      10.12319564256475887773621e23,
+      "1142619072256475129773952000",
+      "1012319564256475887773621000",
```




Also applies to: 129-130

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 Biome (1.9.4)</summary>

[error] 109-109: This number literal will lose precision at runtime.

The value at runtime will be 1742619072256475000000000

(lint/correctness/noPrecisionLoss)

---

[error] 110-110: This number literal will lose precision at runtime.

The value at runtime will be 1612319564256475800000000

(lint/correctness/noPrecisionLoss)

</details>

</details>

</blockquote></details>

</blockquote></details>

<details>
<summary>🧹 Nitpick comments (3)</summary><blockquote>

<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts (3)</summary><blockquote>

`48-146`: **Add documentation for complex test cases.**

The test cases for `getRemainderAmountsWithoutSurplus` would benefit from explanatory comments, especially around:
1. The purpose of each test case
2. How the expected values were derived
3. What each test is specifically verifying

This would make the tests more maintainable and easier to understand for other developers.

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 Biome (1.9.4)</summary>

[error] 109-109: This number literal will lose precision at runtime.

The value at runtime will be 1742619072256475000000000

(lint/correctness/noPrecisionLoss)

---

[error] 110-110: This number literal will lose precision at runtime.

The value at runtime will be 1612319564256475800000000

(lint/correctness/noPrecisionLoss)

---

[error] 129-129: This number literal will lose precision at runtime.

The value at runtime will be 1142619072256475100000000

(lint/correctness/noPrecisionLoss)

---

[error] 130-130: This number literal will lose precision at runtime.

The value at runtime will be 1012319564256475900000000

(lint/correctness/noPrecisionLoss)

</details>

</details>

---

`95-99`: **Inconsistent data representation in test fixtures.**

There's inconsistency in how values are represented in the test data:
- Some use hexadecimal strings with BigInt (lines 77-80)
- Some use plain numbers (lines 96-99)
- Some use JSBI.BigInt (lines 116-118, 136-138)

Consider standardizing on a consistent approach for better maintainability.



Also applies to: 115-119, 135-139

---

`76-80`: **Consider extracting test data setup to helper functions.**

The setup for execution data and API additional info is repeated across multiple tests with slight variations. Consider extracting this to helper functions for improved readability and maintenance.

```javascript
function createExecutionData(executedSellAmount, executedBuyAmount, surplusAmount) {
  return {
    executedSellAmount: typeof executedSellAmount === 'string' 
      ? executedSellAmount 
      : '0x' + BigInt(executedSellAmount).toString(16),
    executedBuyAmount: typeof executedBuyAmount === 'string'
      ? executedBuyAmount
      : '0x' + BigInt(executedBuyAmount).toString(16),
    surplusAmount: surplusAmount instanceof BigNumber 
      ? surplusAmount 
      : new BigNumber(typeof surplusAmount === 'string' ? surplusAmount : '0x' + BigInt(surplusAmount).toString(16))
  }
}
```



Also applies to: 95-99, 115-119, 135-139

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

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

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between d06887f5d63848e92c7529ff776dede51be381a7 and d425b77b27962be90329612c1ef54f86def9721c.

</details>

<details>
<summary>📒 Files selected for processing (1)</summary>

* `apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts` (2 hunks)

</details>

<details>
<summary>🧰 Additional context used</summary>

<details>
<summary>🪛 Biome (1.9.4)</summary>

<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts</summary>

[error] 109-109: This number literal will lose precision at runtime.

The value at runtime will be 1742619072256475000000000

(lint/correctness/noPrecisionLoss)

---

[error] 110-110: This number literal will lose precision at runtime.

The value at runtime will be 1612319564256475800000000

(lint/correctness/noPrecisionLoss)

---

[error] 129-129: This number literal will lose precision at runtime.

The value at runtime will be 1142619072256475100000000

(lint/correctness/noPrecisionLoss)

---

[error] 130-130: This number literal will lose precision at runtime.

The value at runtime will be 1012319564256475900000000

(lint/correctness/noPrecisionLoss)

</details>

</details>

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (3)</summary>

* GitHub Check: Test
* GitHub Check: Lint
* GitHub Check: Cypress

</details>

<details>
<summary>🔇 Additional comments (6)</summary><blockquote>

<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts (6)</summary>

`2-2`: **Clean imports and proper organization.**

The new imports are correctly added to support the new functionality being tested. Good job organizing related imports together.



Also applies to: 5-6, 9-9

---

`11-26`: **Well-structured test helper function.**

The `getLimitOrderWithFee` function is a good abstraction that makes the tests more readable and maintainable. It correctly handles the conversion of numeric values to hexadecimal strings using BigInt and includes the necessary order properties.

---

`36-36`: **Good refactoring of test to use the new helper function.**

The test was effectively updated to use the new `getLimitOrderWithFee` function, maintaining the same test logic and assertions.



Also applies to: 40-40

---

`48-67`: **Good test coverage for basic functionality.**

These initial test cases for `getRemainderAmountsWithoutSurplus` effectively verify the core functionality with and without surplus. The test cases are well structured with clear expectations.

---

`69-86`: **Good test for SELL orders with surplus.**

This test case properly verifies the remainder amount calculations for SELL orders with surplus. The test data setup and assertions are clear.

---

`88-105`: **Skipped tests need attention.**

These tests are currently skipped with `.skip`. This may be intentional during development, but should be addressed before finalizing the PR.

Consider either:
1. Enabling these tests if they're working correctly
2. Adding comments explaining why they're skipped
3. Removing them if they're not needed


Could you clarify why these tests are skipped? Are there known issues that need to be resolved?


Also applies to: 107-125, 127-145

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->
state: COMMENTED
author_association: CONTRIBUTOR
submitted_at: 2025-03-13T09:56:09Z
user: login: shoom3301
state: APPROVED
author_association: COLLABORATOR
submitted_at: 2025-03-13T12:25:04Z
user: login: alfetopito
body: Great tests 👍 
state: APPROVED
author_association: COLLABORATOR
submitted_at: 2025-03-13T13:19:49Z

Review comments:
diff_hunk: @@ -442,14 +442,14 @@ export function getRemainderAmount(kind: OrderKind, order: Order | ParsedOrder):
   }
 
   const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
-
+  const fullAmountBN = JSBI.BigInt(Number(fullAmount))
   if (!executedSellAmount || !executedBuyAmount || executedSellAmount === '0' || executedBuyAmount === '0') {
-    return fullAmount
+    return fullAmountBN.toString()
   }
 
-  const executedAmount = JSBI.BigInt((isSellOrder(kind) ? executedSellAmount : executedBuyAmount) || 0)
+  const executedAmount = JSBI.BigInt((isSellOrder(kind) ? Number(executedSellAmount) : Number(executedBuyAmount)) || 0)
 
-  return JSBI.subtract(JSBI.BigInt(fullAmount), executedAmount).toString()
+  return JSBI.subtract(fullAmountBN, executedAmount).toString()
path: apps/cowswap-frontend/src/legacy/state/orders/utils.ts
user: login: coderabbitai[bot]
body: _⚠️ Potential issue_

**Potential precision loss when converting amounts to numbers before BigInt**

The changes to `getRemainderAmount` function improve type consistency by using BigInt for all calculations. However, converting through `Number()` in line 450 could cause precision loss with very large token amounts (those exceeding ~53 bits), which is common in token amounts with many decimals.


Consider using direct string-to-BigInt conversion instead:

```diff
- const executedAmount = JSBI.BigInt((isSellOrder(kind) ? Number(executedSellAmount) : Number(executedBuyAmount)) || 0)
+ const executedAmount = JSBI.BigInt(isSellOrder(kind) ? executedSellAmount : executedBuyAmount)
```


<!-- suggestion_start -->

<details>
<summary>📝 Committable suggestion</summary>

> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

`````suggestion
  const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
  const fullAmountBN = JSBI.BigInt(Number(fullAmount))
  if (!executedSellAmount || !executedBuyAmount || executedSellAmount === '0' || executedBuyAmount === '0') {
    return fullAmountBN.toString()
  }

  const executedAmount = JSBI.BigInt(isSellOrder(kind) ? executedSellAmount : executedBuyAmount)

  return JSBI.subtract(fullAmountBN, executedAmount).toString()
`````

</details>

<!-- suggestion_end -->

<!-- This is an auto-generated reply by CodeRabbit -->
created_at: 2025-03-10T15:03:02Z
author_association: CONTRIBUTOR
diff_hunk: @@ -23,14 +30,29 @@ describe('getEstimatedExecutionPrice()', () => {
 
     const fillPrice = new Price(WETH_MAINNET, USDC_MAINNET, '10000000000', '1')
 
-    const orderWithFee = getOrderWithFee(sellAmountBeforeFee, buyAmount, fee)
+    const orderWithFee = getLimitOrderWithFee(sellAmountBeforeFee, buyAmount, fee)
     const executionPriceWithFee = getEstimatedExecutionPrice(orderWithFee, fillPrice, fee.toString())
 
     const zeroFee = 0
-    const orderWithoutFee = getOrderWithFee(sellAmountBeforeFee, buyAmount, zeroFee)
+    const orderWithoutFee = getLimitOrderWithFee(sellAmountBeforeFee, buyAmount, zeroFee)
     const executionPriceWithoutFee = getEstimatedExecutionPrice(orderWithoutFee, fillPrice, zeroFee.toString())
 
     expect(executionPriceWithFee?.toFixed(12)).toEqual('1820.007835117276')
     expect(executionPriceWithoutFee?.toFixed(12)).toEqual('1820.000000000000')
   })
 })
+
+describe('getRemainderAmountsWithoutSurplus()', () => {
+  it('Should return the remainder amounts without the surplus', () => {
+    const order = getLimitOrderWithFee(
+      6.42619072256475129773952e23,
+      4.12319564256475887773621e23,
+      0.00021,
+      OrderKind.SELL,
+    )
+    const remainderAmounts = getRemainderAmountsWithoutSurplus(order)
+
+    expect(remainderAmounts.buyAmount).toEqual('412319564256475911028736')
+    expect(remainderAmounts.sellAmount).toEqual('642619072256475115028480')
+  })
+})
path: apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts
user: login: coderabbitai[bot]
body: _⚠️ Potential issue_

**Precision loss in test number literals**

The test values in lines 48-49 are extremely large scientific notation numbers that will lose precision at runtime when converted to JavaScript numbers.


To maintain precision in these large test values, use string representation:

```diff
- 6.42619072256475129773952e23,
- 4.12319564256475887773621e23,
+ "642619072256475129773952",
+ "412319564256475887773621",
```

Alternatively, you could use BigInt literals (with `n` suffix) if your environment supports them:

```
642619072256475129773952n,
412319564256475887773621n,
```


<!-- suggestion_start -->

<details>
<summary>📝 Committable suggestion</summary>

> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

`````suggestion
describe('getRemainderAmountsWithoutSurplus()', () => {
  it('Should return the remainder amounts without the surplus', () => {
    const order = getLimitOrderWithFee(
      "642619072256475129773952",
      "412319564256475887773621",
      0.00021,
      OrderKind.SELL,
    )
    const remainderAmounts = getRemainderAmountsWithoutSurplus(order)

    expect(remainderAmounts.buyAmount).toEqual('412319564256475911028736')
    expect(remainderAmounts.sellAmount).toEqual('642619072256475115028480')
  })
})
`````

</details>

<!-- suggestion_end -->

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 Biome (1.9.4)</summary>

[error] 48-48: This number literal will lose precision at runtime.

The value at runtime will be 642619072256475100000000

(lint/correctness/noPrecisionLoss)

---

[error] 49-49: This number literal will lose precision at runtime.

The value at runtime will be 412319564256475900000000

(lint/correctness/noPrecisionLoss)

</details>

</details>

<!-- This is an auto-generated comment by CodeRabbit -->
created_at: 2025-03-10T15:03:02Z
author_association: CONTRIBUTOR
diff_hunk: @@ -442,14 +442,14 @@ export function getRemainderAmount(kind: OrderKind, order: Order | ParsedOrder):
   }
 
   const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
-
+  const fullAmountBN = JSBI.BigInt(Number(fullAmount))
path: apps/cowswap-frontend/src/legacy/state/orders/utils.ts
user: login: shoom3301
body: Sorry, I'm not sure this is a right place of the fix.
Corresponding to the error log, it comes from:
```
 at getRemainderAmountsWithoutSurplus (https://swap.cow.fi/assets/index-DU2ddb8t.js:605:20164)
```

If you look at the place where it points you will find:
```
JSBI.BigInt(Pt.decimalPlaces(0).toString())
```

Which is supposed to be:
```
const surplusAmount = JSBI.BigInt(surplusAmountBigNumber.decimalPlaces(0).toString())
```

So, the problem is related to `surplusAmountBigNumber` in `getRemainderAmountsWithoutSurplus` function.

created_at: 2025-03-10T15:15:35Z
author_association: COLLABORATOR
diff_hunk: @@ -442,14 +442,14 @@ export function getRemainderAmount(kind: OrderKind, order: Order | ParsedOrder):
   }
 
   const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
-
+  const fullAmountBN = JSBI.BigInt(Number(fullAmount))
   if (!executedSellAmount || !executedBuyAmount || executedSellAmount === '0' || executedBuyAmount === '0') {
-    return fullAmount
+    return fullAmountBN.toString()
   }
 
-  const executedAmount = JSBI.BigInt((isSellOrder(kind) ? executedSellAmount : executedBuyAmount) || 0)
+  const executedAmount = JSBI.BigInt((isSellOrder(kind) ? Number(executedSellAmount) : Number(executedBuyAmount)) || 0)
 
-  return JSBI.subtract(JSBI.BigInt(fullAmount), executedAmount).toString()
+  return JSBI.subtract(fullAmountBN, executedAmount).toString()
path: apps/cowswap-frontend/src/legacy/state/orders/utils.ts
user: login: alfetopito
body: I second mr rabbit.
Is it possible to avoid number conversions?
created_at: 2025-03-10T16:02:42Z
author_association: COLLABORATOR
diff_hunk: @@ -442,14 +442,14 @@ export function getRemainderAmount(kind: OrderKind, order: Order | ParsedOrder):
   }
 
   const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
-
+  const fullAmountBN = JSBI.BigInt(Number(fullAmount))
   if (!executedSellAmount || !executedBuyAmount || executedSellAmount === '0' || executedBuyAmount === '0') {
-    return fullAmount
+    return fullAmountBN.toString()
   }
 
-  const executedAmount = JSBI.BigInt((isSellOrder(kind) ? executedSellAmount : executedBuyAmount) || 0)
+  const executedAmount = JSBI.BigInt((isSellOrder(kind) ? Number(executedSellAmount) : Number(executedBuyAmount)) || 0)
 
-  return JSBI.subtract(JSBI.BigInt(fullAmount), executedAmount).toString()
+  return JSBI.subtract(fullAmountBN, executedAmount).toString()
path: apps/cowswap-frontend/src/legacy/state/orders/utils.ts
user: login: coderabbitai[bot]
body: @alfetopito Yes, it's definitely possible to avoid all number conversions. JSBI.BigInt can directly accept string representations, which prevents any potential precision loss that might occur with large token amounts.

Here's how you could modify both instances:

```diff
  const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
- const fullAmountBN = JSBI.BigInt(Number(fullAmount))
+ const fullAmountBN = JSBI.BigInt(fullAmount)
  if (!executedSellAmount || !executedBuyAmount || executedSellAmount === '0' || executedBuyAmount === '0') {
    return fullAmountBN.toString()
  }

- const executedAmount = JSBI.BigInt((isSellOrder(kind) ? Number(executedSellAmount) : Number(executedBuyAmount)) || 0)
+ const executedAmount = JSBI.BigInt(isSellOrder(kind) ? executedSellAmount : executedBuyAmount)

  return JSBI.subtract(fullAmountBN, executedAmount).toString()
```

This approach eliminates the potential precision loss by removing all `Number()` conversions and passing string values directly to JSBI.BigInt.

---

<details>
<summary>✏️ Learnings added</summary>

```
Learnt from: alfetopito
PR: cowprotocol/cowswap#5495
File: apps/cowswap-frontend/src/legacy/state/orders/utils.ts:444-452
Timestamp: 2025-03-10T16:03:11.450Z
Learning: When working with large numbers in JavaScript, especially token amounts with many decimals, avoid conversions through Number() before BigInt to prevent precision loss. Instead, pass string representations directly to JSBI.BigInt().
```

> Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure [review instructions](https://docs.coderabbit.ai/guides/review-instructions). You can manage existing learnings in the [app](https://app.coderabbit.ai/learnings).

</details>

<!-- This is an auto-generated reply by CodeRabbit -->
created_at: 2025-03-10T16:03:12Z
author_association: CONTRIBUTOR
diff_hunk: @@ -442,14 +442,14 @@ export function getRemainderAmount(kind: OrderKind, order: Order | ParsedOrder):
   }
 
   const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
-
+  const fullAmountBN = JSBI.BigInt(Number(fullAmount))
path: apps/cowswap-frontend/src/legacy/state/orders/utils.ts
user: login: shoom3301
body: Or does it lead to the place where you added the fix?
created_at: 2025-03-10T16:12:55Z
author_association: COLLABORATOR
diff_hunk: @@ -442,14 +442,14 @@ export function getRemainderAmount(kind: OrderKind, order: Order | ParsedOrder):
   }
 
   const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
-
+  const fullAmountBN = JSBI.BigInt(Number(fullAmount))
   if (!executedSellAmount || !executedBuyAmount || executedSellAmount === '0' || executedBuyAmount === '0') {
-    return fullAmount
+    return fullAmountBN.toString()
   }
 
-  const executedAmount = JSBI.BigInt((isSellOrder(kind) ? executedSellAmount : executedBuyAmount) || 0)
+  const executedAmount = JSBI.BigInt((isSellOrder(kind) ? Number(executedSellAmount) : Number(executedBuyAmount)) || 0)
 
-  return JSBI.subtract(JSBI.BigInt(fullAmount), executedAmount).toString()
+  return JSBI.subtract(fullAmountBN, executedAmount).toString()
path: apps/cowswap-frontend/src/legacy/state/orders/utils.ts
user: login: anxolin
body: Cool, so coderabbit is not so dumb. It catches things and makes suggestions!
created_at: 2025-03-10T17:16:43Z
author_association: CONTRIBUTOR
diff_hunk: @@ -442,14 +442,14 @@ export function getRemainderAmount(kind: OrderKind, order: Order | ParsedOrder):
   }
 
   const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
-
+  const fullAmountBN = JSBI.BigInt(Number(fullAmount))
   if (!executedSellAmount || !executedBuyAmount || executedSellAmount === '0' || executedBuyAmount === '0') {
-    return fullAmount
+    return fullAmountBN.toString()
   }
 
-  const executedAmount = JSBI.BigInt((isSellOrder(kind) ? executedSellAmount : executedBuyAmount) || 0)
+  const executedAmount = JSBI.BigInt((isSellOrder(kind) ? Number(executedSellAmount) : Number(executedBuyAmount)) || 0)
 
-  return JSBI.subtract(JSBI.BigInt(fullAmount), executedAmount).toString()
+  return JSBI.subtract(fullAmountBN, executedAmount).toString()
path: apps/cowswap-frontend/src/legacy/state/orders/utils.ts
user: login: coderabbitai[bot]
body: > Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

<!-- This is an auto-generated mute comment by CodeRabbit -->
created_at: 2025-03-10T17:16:49Z
author_association: CONTRIBUTOR
diff_hunk: @@ -442,14 +442,14 @@ export function getRemainderAmount(kind: OrderKind, order: Order | ParsedOrder):
   }
 
   const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
-
+  const fullAmountBN = JSBI.BigInt(Number(fullAmount))
path: apps/cowswap-frontend/src/legacy/state/orders/utils.ts
user: login: cowdan
body: as discussed, I updated the code
created_at: 2025-03-11T11:16:49Z
author_association: CONTRIBUTOR
diff_hunk: @@ -442,14 +442,13 @@ export function getRemainderAmount(kind: OrderKind, order: Order | ParsedOrder):
   }
 
   const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
-
   if (!executedSellAmount || !executedBuyAmount || executedSellAmount === '0' || executedBuyAmount === '0') {
     return fullAmount
   }
 
   const executedAmount = JSBI.BigInt((isSellOrder(kind) ? executedSellAmount : executedBuyAmount) || 0)
 
-  return JSBI.subtract(JSBI.BigInt(fullAmount), executedAmount).toString()
+  return JSBI.subtract(JSBI.BigInt(Number(fullAmount)), executedAmount).toString()
path: apps/cowswap-frontend/src/legacy/state/orders/utils.ts
user: login: shoom3301
body: Casting to `Number` looks redundant here
created_at: 2025-03-11T11:23:44Z
author_association: COLLABORATOR
diff_hunk: @@ -23,14 +33,117 @@ describe('getEstimatedExecutionPrice()', () => {
 
     const fillPrice = new Price(WETH_MAINNET, USDC_MAINNET, '10000000000', '1')
 
-    const orderWithFee = getOrderWithFee(sellAmountBeforeFee, buyAmount, fee)
+    const orderWithFee = getLimitOrderWithFee(sellAmountBeforeFee, buyAmount, fee)
     const executionPriceWithFee = getEstimatedExecutionPrice(orderWithFee, fillPrice, fee.toString())
 
     const zeroFee = 0
-    const orderWithoutFee = getOrderWithFee(sellAmountBeforeFee, buyAmount, zeroFee)
+    const orderWithoutFee = getLimitOrderWithFee(sellAmountBeforeFee, buyAmount, zeroFee)
     const executionPriceWithoutFee = getEstimatedExecutionPrice(orderWithoutFee, fillPrice, zeroFee.toString())
 
     expect(executionPriceWithFee?.toFixed(12)).toEqual('1820.007835117276')
     expect(executionPriceWithoutFee?.toFixed(12)).toEqual('1820.000000000000')
   })
 })
+
+describe('getRemainderAmountsWithoutSurplus()', () => {
path: apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts
user: login: shoom3301
body: Awesome tests, thank you!
created_at: 2025-03-11T11:24:36Z
author_association: COLLABORATOR
diff_hunk: @@ -442,14 +442,13 @@ export function getRemainderAmount(kind: OrderKind, order: Order | ParsedOrder):
   }
 
   const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
-
   if (!executedSellAmount || !executedBuyAmount || executedSellAmount === '0' || executedBuyAmount === '0') {
     return fullAmount
   }
 
   const executedAmount = JSBI.BigInt((isSellOrder(kind) ? executedSellAmount : executedBuyAmount) || 0)
 
-  return JSBI.subtract(JSBI.BigInt(fullAmount), executedAmount).toString()
+  return JSBI.subtract(JSBI.BigInt(Number(fullAmount)), executedAmount).toString()
path: apps/cowswap-frontend/src/legacy/state/orders/utils.ts
user: login: cowdan
body: I added as one of the test was failing there
created_at: 2025-03-11T11:27:40Z
author_association: CONTRIBUTOR
diff_hunk: @@ -442,14 +442,13 @@ export function getRemainderAmount(kind: OrderKind, order: Order | ParsedOrder):
   }
 
   const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
-
   if (!executedSellAmount || !executedBuyAmount || executedSellAmount === '0' || executedBuyAmount === '0') {
     return fullAmount
   }
 
   const executedAmount = JSBI.BigInt((isSellOrder(kind) ? executedSellAmount : executedBuyAmount) || 0)
 
-  return JSBI.subtract(JSBI.BigInt(fullAmount), executedAmount).toString()
+  return JSBI.subtract(JSBI.BigInt(Number(fullAmount)), executedAmount).toString()
path: apps/cowswap-frontend/src/legacy/state/orders/utils.ts
user: login: alfetopito
body: Are we really sure we need the cast to Number here?
It should work fine with strings https://github.com/GoogleChromeLabs/jsbi, provided the number is an integer.

What was the failing test?
Could it be that the input that was the culprit? Maybe we need to treat the `fullAmount` to not have decimals instead.
created_at: 2025-03-11T14:49:07Z
author_association: COLLABORATOR
diff_hunk: @@ -442,14 +442,13 @@ export function getRemainderAmount(kind: OrderKind, order: Order | ParsedOrder):
   }
 
   const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
-
   if (!executedSellAmount || !executedBuyAmount || executedSellAmount === '0' || executedBuyAmount === '0') {
     return fullAmount
   }
 
   const executedAmount = JSBI.BigInt((isSellOrder(kind) ? executedSellAmount : executedBuyAmount) || 0)
 
-  return JSBI.subtract(JSBI.BigInt(fullAmount), executedAmount).toString()
+  return JSBI.subtract(JSBI.BigInt(Number(fullAmount)), executedAmount).toString()
path: apps/cowswap-frontend/src/legacy/state/orders/utils.ts
user: login: cowdan
body: If we don't cast `fullAmount` to a `Number`, all tests related to `getRemainderAmountsWithoutSurplus()` are failing, the error being always `Cannot convert someValue...e+24 to a BigInt`
created_at: 2025-03-12T17:00:47Z
author_association: CONTRIBUTOR
diff_hunk: @@ -442,14 +442,13 @@ export function getRemainderAmount(kind: OrderKind, order: Order | ParsedOrder):
   }
 
   const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
-
   if (!executedSellAmount || !executedBuyAmount || executedSellAmount === '0' || executedBuyAmount === '0') {
     return fullAmount
   }
 
   const executedAmount = JSBI.BigInt((isSellOrder(kind) ? executedSellAmount : executedBuyAmount) || 0)
 
-  return JSBI.subtract(JSBI.BigInt(fullAmount), executedAmount).toString()
+  return JSBI.subtract(JSBI.BigInt(Number(fullAmount)), executedAmount).toString()
path: apps/cowswap-frontend/src/legacy/state/orders/utils.ts
user: login: cowdan
body: `fullAmount` comes from `order.buyAmount` or `order.sellAmount` or `order.sellAmountBeforeFee`. 
created_at: 2025-03-12T17:05:24Z
author_association: CONTRIBUTOR
diff_hunk: @@ -414,6 +406,19 @@ export function getRemainderAmountsWithoutSurplus(order: Order | ParsedOrder): {
   }
 }
 
+function getSurplusAmountBigNumber(order: Order | ParsedOrder): BigNumber {
+  let surplusAmountBigNumber: BigNumber
path: apps/cowswap-frontend/src/legacy/state/orders/utils.ts
user: login: shoom3301
body: Nitpick: Excessive let, we can do just return in if and else.
p.s. I'm immutable code nazi :) 
created_at: 2025-03-13T08:39:45Z
author_association: COLLABORATOR
diff_hunk: @@ -442,14 +442,13 @@ export function getRemainderAmount(kind: OrderKind, order: Order | ParsedOrder):
   }
 
   const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
-
   if (!executedSellAmount || !executedBuyAmount || executedSellAmount === '0' || executedBuyAmount === '0') {
     return fullAmount
   }
 
   const executedAmount = JSBI.BigInt((isSellOrder(kind) ? executedSellAmount : executedBuyAmount) || 0)
 
-  return JSBI.subtract(JSBI.BigInt(fullAmount), executedAmount).toString()
+  return JSBI.subtract(JSBI.BigInt(Number(fullAmount)), executedAmount).toString()
path: apps/cowswap-frontend/src/legacy/state/orders/utils.ts
user: login: shoom3301
body: They fail due to invalid mocked data.
Order sellAmount and buyAmount ar always hex decimals values. It's impossible to have values with e-notations here.

<img width="499" alt="image" src="https://github.com/user-attachments/assets/90775cb3-e841-42fd-a30c-e5d803513780" />

created_at: 2025-03-13T08:50:05Z
author_association: COLLABORATOR
diff_hunk: @@ -442,14 +442,13 @@ export function getRemainderAmount(kind: OrderKind, order: Order | ParsedOrder):
   }
 
   const fullAmount = isSellOrder(kind) ? sellAmount : buyAmount
-
   if (!executedSellAmount || !executedBuyAmount || executedSellAmount === '0' || executedBuyAmount === '0') {
     return fullAmount
   }
 
   const executedAmount = JSBI.BigInt((isSellOrder(kind) ? executedSellAmount : executedBuyAmount) || 0)
 
-  return JSBI.subtract(JSBI.BigInt(fullAmount), executedAmount).toString()
+  return JSBI.subtract(JSBI.BigInt(Number(fullAmount)), executedAmount).toString()
path: apps/cowswap-frontend/src/legacy/state/orders/utils.ts
user: login: shoom3301
body: I'm very confident that we should not cast to Number here
created_at: 2025-03-13T08:50:39Z
author_association: COLLABORATOR
diff_hunk: @@ -23,14 +33,114 @@ describe('getEstimatedExecutionPrice()', () => {
 
     const fillPrice = new Price(WETH_MAINNET, USDC_MAINNET, '10000000000', '1')
 
-    const orderWithFee = getOrderWithFee(sellAmountBeforeFee, buyAmount, fee)
+    const orderWithFee = getLimitOrderWithFee(sellAmountBeforeFee, buyAmount, fee)
     const executionPriceWithFee = getEstimatedExecutionPrice(orderWithFee, fillPrice, fee.toString())
 
     const zeroFee = 0
-    const orderWithoutFee = getOrderWithFee(sellAmountBeforeFee, buyAmount, zeroFee)
+    const orderWithoutFee = getLimitOrderWithFee(sellAmountBeforeFee, buyAmount, zeroFee)
     const executionPriceWithoutFee = getEstimatedExecutionPrice(orderWithoutFee, fillPrice, zeroFee.toString())
 
     expect(executionPriceWithFee?.toFixed(12)).toEqual('1820.007835117276')
     expect(executionPriceWithoutFee?.toFixed(12)).toEqual('1820.000000000000')
   })
 })
+
+describe('getRemainderAmountsWithoutSurplus()', () => {
+  it('Should return the remainder amounts without the surplus', () => {
+    const fee = 0.00016 * 10 ** WETH_MAINNET.decimals
+    const sellAmountBeforeFee = 99 * 10 ** WETH_MAINNET.decimals
+    const buyAmount = 17345 * 10 ** USDC_MAINNET.decimals
+
+    const order = getLimitOrderWithFee(sellAmountBeforeFee, buyAmount, fee, OrderKind.SELL)
+    const remainderAmounts = getRemainderAmountsWithoutSurplus(order)
+
+    expect(remainderAmounts.buyAmount).toEqual('17345000000')
+    expect(remainderAmounts.sellAmount).toEqual('99000000000000000000')
+  })
+
+  it('should return the full amount if there is no surplus', () => {
+    const order = getLimitOrderWithFee(100, 100, 0)
+    const remainderAmounts = getRemainderAmountsWithoutSurplus(order)
+
+    expect(remainderAmounts.buyAmount).toEqual('100')
+    expect(remainderAmounts.sellAmount).toEqual('100')
+  })
+
+  it('should return the remainder amounts if there is a surplus when passing a SELL ParsedOrder', () => {
+    const fee = 0.1 * 10 ** WETH_MAINNET.decimals
+    const sellAmountBeforeFee = 100001 * 10 ** WETH_MAINNET.decimals
+    const buyAmount = 12345567 * 10 ** USDC_MAINNET.decimals
+
+    const order = getLimitOrderWithFee(sellAmountBeforeFee, buyAmount, fee, OrderKind.SELL)
+
+    ;(order as any).executionData = {
+      executedSellAmount: 99999 * 10 ** WETH_MAINNET.decimals,
+      executedBuyAmount: 12345566 * 10 ** USDC_MAINNET.decimals,
+      surplusAmount: 3 * 10 ** WETH_MAINNET.decimals,
+    }
+
+    const remainderAmounts = getRemainderAmountsWithoutSurplus(order)
+
+    expect(remainderAmounts.buyAmount).toEqual('2312319564256475852308472')
+    expect(remainderAmounts.sellAmount).toEqual('1242619072256475131805692')
+  })
+
+  it.skip('should return the remainder amounts if there is a surplus when passing a BUY ParsedOrder', () => {
+    const fee = 0.1 * 10 ** WETH_MAINNET.decimals
+    const sellAmountBeforeFee = 100001 * 10 ** WETH_MAINNET.decimals
+    const buyAmount = 12345567 * 10 ** USDC_MAINNET.decimals
+
+    const order = getLimitOrderWithFee(sellAmountBeforeFee, buyAmount, fee, OrderKind.BUY)
+
+    ;(order as any).executionData = {
+      executedSellAmount: 100000 * 10 ** WETH_MAINNET.decimals,
+      executedBuyAmount: 12345566 * 10 ** USDC_MAINNET.decimals,
+      surplusAmount: 2 * 10 ** WETH_MAINNET.decimals,
+    }
+
+    const remainderAmounts = getRemainderAmountsWithoutSurplus(order)
+
+    expect(remainderAmounts.buyAmount).toEqual('4112319564256476036857852')
+    expect(remainderAmounts.sellAmount).toEqual('4542619072256475291189243')
+  })
+
+  it.skip('should return the remainder amounts if there is surplus when passing a SELL Order', () => {
+    const order = getLimitOrderWithFee(
+      17.42619072256475129773952e23,
+      16.12319564256475887773621e23,
+      0.3,
path: apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts
user: login: coderabbitai[bot]
body: _⚠️ Potential issue_

**Fix precision loss in large number literals**

The scientific notation numbers will lose precision at runtime. These should be represented as strings.

```diff
-      17.42619072256475129773952e23,
-      16.12319564256475887773621e23,
+      "1742619072256475129773952000",
+      "1612319564256475887773621000",
```


<!-- suggestion_start -->

<details>
<summary>📝 Committable suggestion</summary>

> ‼️ **IMPORTANT**
> Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

`````suggestion
      "1742619072256475129773952000",
      "1612319564256475887773621000",
      0.3,
`````

</details>

<!-- suggestion_end -->

<details>
<summary>🧰 Tools</summary>

<details>
<summary>🪛 Biome (1.9.4)</summary>

[error] 109-109: This number literal will lose precision at runtime.

The value at runtime will be 1742619072256475000000000

(lint/correctness/noPrecisionLoss)

---

[error] 110-110: This number literal will lose precision at runtime.

The value at runtime will be 1612319564256475800000000

(lint/correctness/noPrecisionLoss)

</details>

</details>

<!-- This is an auto-generated comment by CodeRabbit -->

✅ Fixed in commit 6d51eeb
created_at: 2025-03-13T09:50:37Z
author_association: CONTRIBUTOR

PR comments:
user: login: vercel[bot]
created_at: 2025-03-10T14:53:56Z
body: [vc]: #4ad1gIgVbwngb0nSFUCEWcAltRxnKL1N7nS3l74w5sI=:eyJpc01vbm9yZXBvIjp0cnVlLCJ0eXBlIjoiZ2l0aHViIiwicHJvamVjdHMiOlt7Im5hbWUiOiJzd2FwLWRldiIsInJvb3REaXJlY3RvcnkiOiJhcHBzL2Nvd3N3YXAtZnJvbnRlbmQiLCJpbnNwZWN0b3JVcmwiOiJodHRwczovL3ZlcmNlbC5jb20vY293c3dhcC1kZXYvc3dhcC1kZXYvSjlLYXFjSzJjU3pwQXRIRjVNc0tmMkFGYTVWTSIsInByZXZpZXdVcmwiOiJzd2FwLWRldi1naXQtZml4LWlzc3VlLTU0OTAtY293c3dhcC1kZXYudmVyY2VsLmFwcCIsIm5leHRDb21taXRTdGF0dXMiOiJERVBMT1lFRCJ9LHsibmFtZSI6ImV4cGxvcmVyLWRldiIsInJvb3REaXJlY3RvcnkiOm51bGwsImluc3BlY3RvclVybCI6Imh0dHBzOi8vdmVyY2VsLmNvbS9jb3dzd2FwLWRldi9leHBsb3Jlci1kZXYvODlNdndyMnBaYmdGY2dFNVRlRUJLWWI2a2d2eiIsInByZXZpZXdVcmwiOiJleHBsb3Jlci1kZXYtZ2l0LWZpeC1pc3N1ZS01NDkwLWNvd3N3YXAtZGV2LnZlcmNlbC5hcHAiLCJuZXh0Q29tbWl0U3RhdHVzIjoiREVQTE9ZRUQifSx7Im5hbWUiOiJ3aWRnZXQtY29uZmlndXJhdG9yIiwicm9vdERpcmVjdG9yeSI6bnVsbCwiaW5zcGVjdG9yVXJsIjoiaHR0cHM6Ly92ZXJjZWwuY29tL2Nvd3N3YXAvd2lkZ2V0LWNvbmZpZ3VyYXRvci8yRDNNa0ZDRDIyM0xaWDROV1JoOGhlZXNpVXhyIiwicHJldmlld1VybCI6IndpZGdldC1jb25maWd1cmF0b3ItZ2l0LWZpeC1pc3N1ZS01NDkwLWNvd3N3YXAudmVyY2VsLmFwcCIsIm5leHRDb21taXRTdGF0dXMiOiJJR05PUkVEIn0seyJuYW1lIjoiY29zbW9zIiwicm9vdERpcmVjdG9yeSI6bnVsbCwiaW5zcGVjdG9yVXJsIjoiaHR0cHM6Ly92ZXJjZWwuY29tL2Nvd3N3YXAtZGV2L2Nvc21vcy9FWWJhbm82Sng4SHgxRUdzYkVYVzd2cUdBbkU2IiwicHJldmlld1VybCI6ImNvc21vcy1naXQtZml4LWlzc3VlLTU0OTAtY293c3dhcC1kZXYudmVyY2VsLmFwcCIsIm5leHRDb21taXRTdGF0dXMiOiJJR05PUkVEIn0seyJuYW1lIjoic2RrLXRvb2xzIiwicm9vdERpcmVjdG9yeSI6bnVsbCwiaW5zcGVjdG9yVXJsIjoiaHR0cHM6Ly92ZXJjZWwuY29tL2Nvd3N3YXAtZGV2L3Nkay10b29scy9CQ1pwclNFSjc0VWVKUnRSWG5YUDJGQjJrN3ZjIiwicHJldmlld1VybCI6InNkay10b29scy1naXQtZml4LWlzc3VlLTU0OTAtY293c3dhcC1kZXYudmVyY2VsLmFwcCIsIm5leHRDb21taXRTdGF0dXMiOiJJR05PUkVEIn0seyJuYW1lIjoiY293ZmkiLCJyb290RGlyZWN0b3J5IjpudWxsLCJpbnNwZWN0b3JVcmwiOiJodHRwczovL3ZlcmNlbC5jb20vY293c3dhcC9jb3dmaS9BM2RyUWhMd1FOODdYS3FweWkzd3UzZlZid1M2IiwicHJldmlld1VybCI6ImNvd2ZpLWdpdC1maXgtaXNzdWUtNTQ5MC1jb3dzd2FwLnZlcmNlbC5hcHAiLCJuZXh0Q29tbWl0U3RhdHVzIjoiREVQTE9ZRUQifV19
**The latest updates on your projects**. Learn more about [Vercel for Git ↗︎](https://vercel.link/github-learn-more)

| Name | Status | Preview | Updated (UTC) |
| :--- | :----- | :------ | :------ |
| **cowfi** | ✅ Ready ([Inspect](https://vercel.com/cowswap/cowfi/A3drQhLwQN87XKqpyi3wu3fVbwS6)) | [Visit Preview](https://cowfi-git-fix-issue-5490-cowswap.vercel.app) | Mar 13, 2025 0:34am |
| **explorer-dev** | ✅ Ready ([Inspect](https://vercel.com/cowswap-dev/explorer-dev/89Mvwr2pZbgFcgE5TeEBKYb6kgvz)) | [Visit Preview](https://explorer-dev-git-fix-issue-5490-cowswap-dev.vercel.app) | Mar 13, 2025 0:34am |
| **swap-dev** | ✅ Ready ([Inspect](https://vercel.com/cowswap-dev/swap-dev/J9KaqcK2cSzpAtHF5MsKf2AFa5VM)) | [Visit Preview](https://swap-dev-git-fix-issue-5490-cowswap-dev.vercel.app) | Mar 13, 2025 0:34am |

<details><summary>3 Skipped Deployments</summary>

| Name | Status | Preview | Updated (UTC) |
| :--- | :----- | :------ | :------ |
| **cosmos** | ⬜️ Ignored ([Inspect](https://vercel.com/cowswap-dev/cosmos/EYbano6Jx8Hx1EGsbEXW7vqGAnE6)) | [Visit Preview](https://cosmos-git-fix-issue-5490-cowswap-dev.vercel.app) | Mar 13, 2025 0:34am |
| **sdk-tools** | ⬜️ Ignored ([Inspect](https://vercel.com/cowswap-dev/sdk-tools/BCZprSEJ74UeJRtRXnXP2FB2k7vc)) | [Visit Preview](https://sdk-tools-git-fix-issue-5490-cowswap-dev.vercel.app) | Mar 13, 2025 0:34am |
| **widget-configurator** | ⬜️ Ignored ([Inspect](https://vercel.com/cowswap/widget-configurator/2D3MkFCD223LZX4NWRh8heesiUxr)) | [Visit Preview](https://widget-configurator-git-fix-issue-5490-cowswap.vercel.app) | Mar 13, 2025 0:34am |
</details>







author_association: NONE
user: login: coderabbitai[bot]
created_at: 2025-03-10T14:53:59Z
body: <!-- This is an auto-generated comment: summarize by coderabbit.ai -->
<!-- walkthrough_start -->

## Walkthrough
This update introduces a new function, `getLimitOrderWithFee`, which replaces `getOrderWithFee` and includes an additional parameter, `orderKind`. The test suite for `getRemainderAmountsWithoutSurplus` has been expanded to validate various scenarios. Additionally, the surplus calculation logic has been refactored in utility functions, encapsulating it in a new helper function, `getSurplusAmountBigNumber`, and streamlining the handling of amounts.

## Changes

| Files                                               | Change Summary |
| --------------------------------------------------- | -------------- |
| `apps/cowswap-frontend/.../orderPrice.test.ts`      | Added new function `getLimitOrderWithFee` and updated test cases for `getRemainderAmountsWithoutSurplus`. Removed `getOrderWithFee`. |
| `apps/cowswap-frontend/.../utils.ts`                | Refactored `getRemainderAmountsWithoutSurplus` and `getRemainderAmount`, introduced `getSurplusAmountBigNumber`, and streamlined amount handling. |

## Sequence Diagram(s)

```mermaid
sequenceDiagram
    participant T as Test
    participant G as getLimitOrderWithFee
    participant O as Order
    T->>+G: Call getLimitOrderWithFee(sellAmount, buyAmount, fee, orderKind)
    G-->>-T: Return Order with fee adjustments
```

```mermaid
sequenceDiagram
    participant T as Test
    participant R as getRemainderAmountsWithoutSurplus
    participant S as getSurplusAmountBigNumber
    T->>+R: Call getRemainderAmountsWithoutSurplus(order, amounts)
    R->>+S: Compute surplus amount from order details
    S-->>-R: Return surplus as BigNumber
    R-->>-T: Return remainder amounts with surplus applied
```

## Suggested reviewers
- elena-zh

## Poem
> I'm a little rabbit, hopping in the code,  
> Nibbling on numbers and tests on the road.  
> New methods and helpers, tidy and clear,  
> Like fresh garden carrots, delightful and dear.  
> Happy coding leaps with each bug out the door!  
> 🐇💻

<!-- walkthrough_end -->

<!-- announcements_start -->

> [!TIP]
> <details>
> <summary>⚡🧪 Multi-step agentic review comment chat (experimental)</summary>
> 
> - We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
> 						- To enable this feature, set early_access to true under in the settings.
> 
> </details>

<!-- announcements_end -->

---

<details>
<summary>📜 Recent review details</summary>

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

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between d425b77b27962be90329612c1ef54f86def9721c and 6d51eebc5c1bda66c33d13de37ccd7e8b8f439ef.

</details>

<details>
<summary>📒 Files selected for processing (1)</summary>

* `apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts` (1 hunks)

</details>

<details>
<summary>⏰ Context from checks skipped due to timeout of 90000ms (3)</summary>

* GitHub Check: Test
* GitHub Check: Lint
* GitHub Check: Cypress

</details>

<details>
<summary>🔇 Additional comments (8)</summary><blockquote>

<details>
<summary>apps/cowswap-frontend/src/legacy/state/orders/orderPrice.test.ts (8)</summary>

`2-9`: **Good addition of necessary imports.**

The new imports properly support the changes in this file, including `OrderKind` for the order type parameter and `BigNumber` for precise calculations with currency values.

---

`12-38`: **Well-structured getLimitOrderWithFee function replacing the previous implementation.**

This new function properly handles:
- String parameters instead of numbers to prevent precision loss
- The additional `orderKind` parameter with appropriate default
- BigNumber operations for fee calculations

The approach of using BigNumber for financial calculations is excellent for preventing the precision issues that were flagged in previous reviews.

---

`40-58`: **Updated test using BigNumber correctly.**

The test for `getEstimatedExecutionPrice` has been properly refactored to use the new `getLimitOrderWithFee` function and BigNumber for calculations. The approach properly prevents precision loss in financial calculations while maintaining the same test logic.

---

`60-83`: **Good initial test cases for getRemainderAmountsWithoutSurplus.**

These test cases properly validate basic functionality:
1. A standard case with typical values
2. The edge case when there is no surplus

The tests cover important scenarios and properly construct test data using BigNumber.

---

`85-102`: **Thorough test for SELL order with surplus.**

This test properly mocks the execution data with surplus for a SELL order and validates the correct calculation of remainder amounts. The expected values appear to correctly account for the surplus in the sell amount.

---

`104-121`: **Comprehensive test for BUY order with surplus.**

Good coverage of the BUY order scenario with surplus amounts. The test properly verifies different behavior based on order type, which is important for ensuring correct surplus handling in both order types.

---

`123-140`: **Detailed test for SELL order using API additional info.**

This test properly verifies remainder calculations when using the API format with JSBI values, which is an important edge case to test. The test checks precise calculations down to very small units, which is excellent for financial calculation testing.

---

`142-159`: **Thorough validation of BUY order with API data.**

This test complements the previous one by testing BUY orders with API additional info. The comprehensive test suite ensures all combinations of order types and data sources are covered.

</details>

</blockquote></details>

</details>
<!-- internal state start -->


<!-- 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= -->

<!-- internal state end -->
<!-- finishing_touch_checkbox_start -->

<details>
<summary>✨ Finishing Touches</summary>

- [ ] <!-- {"checkboxId": "7962f53c-55bc-4827-bfbf-6a18da830691"} --> 📝 Generate Docstrings

</details>

<!-- finishing_touch_checkbox_end -->
<!-- tips_start -->

---



<details>
<summary>🪧 Tips</summary>

### Chat

There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=cowprotocol/cowswap&utm_content=5495):

- Review comments: Directly reply to a review comment made by CodeRabbit. Example:
  - `I pushed a fix in commit <commit_id>, please review it.`
  - `Generate unit testing code for this file.`
  - `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 generate unit testing code for this file.`
  -	`@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 generate unit testing code.`
  - `@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.`

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](https://docs.coderabbit.ai/finishing-touches/docstrings) for 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](https://docs.coderabbit.ai/guides/configure-coderabbit) 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](https://docs.coderabbit.ai) for detailed information on how to use CodeRabbit.
- Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback.
- Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.

</details>

<!-- tips_end -->
author_association: CONTRIBUTOR
user: login: cowdan
created_at: 2025-03-11T11:26:51Z
body: > I've been trying to test the changes and find any token's combination and a trade amount that will lead to crash, but I've not been able to. Based on the [sentry errors logging](https://cowprotocol.sentry.io/issues/6338603447/events/?end=2025-03-11T23%3A59%3A59&environment=production&project=5905822&referrer=issue-stream&start=2025-03-09T00%3A00%3A00&stream_index=0&utc=true), we have a lot of crashes with different token pairs, and more than often the crash happens on navigation from Swap to Limit orders page. Anyways, might it be possible to help me to 'emulate' a way to reproduce the issue to test the PR?
> 
> Thanks

I couldn't find a way to reproduce the issue, but I've added some extra unit tests that highlighted some potential problems, now fixed.
author_association: CONTRIBUTOR
user: login: shoom3301
created_at: 2025-03-13T09:35:28Z
body: @cowdan a kind reminder: please don't forget to make the commit message satisfy https://www.conventionalcommits.org/en/v1.0.0/ before merging.
I'm talking about it because the PR title (which usually goes as a message for squashed commit) is not valid.
author_association: COLLABORATOR