Farseen0/scar-pairs huggingface dataset:
MEDIUM severity: The vulnerability allows a malicious operator to manipulate the denominator of the Vault's numerator. The vulnerability allows a malicious operator to manipulate the denominator of the Vault's numerator, leading to the theft of user deposits. This is achieved by exploiting the initial deposit mechanism, which sums the initial denominators of all tokens to determine the denominator. The attacker can...

Vulnerable code:
```\nif (D == 0) {\n    uint256 sumDenoms = 0;\n    for (uint256 i = 0; i < tkns.length; i++) {\n        sumDenoms += AI.getAllowedTokenInfo(tkns[i]).initialDenominator;\n    }\n    require(sumDenoms > 0 && sumDenoms <= maxInitialDenominator, "invalid sumDenoms");\n    deltaN = sumDenoms;\n    // this ensures precision in the vault's balances. User Balance = (N*T)/D will have rounding errors always 1 wei or less.\n} else {\n    // deltaN = (amt * D)/T;\n    deltaN = Arithmetic.overflowResistantFraction(amt, D, T);\n}\n```
MEDIUM severity: The `update()` function in the `OracleFactory` contract is vulnerable to privilege control issues. S. The `update()` function in the `OracleFactory` contract is vulnerable to privilege control issues. Specifically, the function calls the `update()` method of an `IOracle` object, which requires permission from the `OracleFactory` owner. However, the `update()` function is currently restricted to only...

Vulnerable code:
```\ncontract OracleFactory is IOracleFactory, Factory {\n    function update(bytes32 id, IOracleProviderFactory factory) external onlyOwner {\n        if (!factories[factory]) {\n            revert OracleFactoryNotRegisteredError();\n        }\n        if (oracles[id] == IOracleProvider(address(0))) {\n            revert OracleFactoryNotCreatedError();\n        }\n\n        IOracleProvider oracleProvider = factory.oracles(id);\n        if (oracleProvider == IOracleProvider(address(0))) {\n            revert OracleFactoryInvalidIdError();\n        }\n\n        IOracle oracle = IOracle(address(oracles[id]));\n        oracle.update(oracleProvider);\n    }\n}\n```\n```\nfunction update(IOracleProvider newProvider) external {\n    modifier onlyOwner {\n        if (msg.sender!= factory().owner()) revert InstanceNotOwnerError(msg.sender);\n        _;\n    }\n    _updateCurrent(newProvider);\n    _updateLatest(newProvider.latest());\n}\n```
MEDIUM severity: The RocketNetworkPrices function, responsible for updating the price feed, lacks a crucial sanity ch. The RocketNetworkPrices function, responsible for updating the price feed, lacks a crucial sanity check on the block number provided. Specifically, it does not verify whether the specified block number is within a valid range, potentially leading to unexpected behavior.\n\nWhen a trusted node submit...

Vulnerable code:
```\nrequire(_block.getPricesBlock(), "Network prices for an equal or higher block are set")\n```
MEDIUM severity: The vulnerability arises from the use of a FILO (first-in, last-out) stack structure in the `mintDep. The vulnerability arises from the use of a FILO (first-in, last-out) stack structure in the `mintDepositInQueue` function, which can lead to a situation where user deposits may never be processed from the deposit queue. This occurs when the queue is dequeued in a way that the first few entries are n...

Vulnerable code:
```\nwhile ((length - _operations) <= i) {\n    _mintShares(\n        queue[i].receiver,\n        _epochId,\n        queue[i].assets - relayerFee\n    );\n    emit Deposit(\n        msg.sender,\n        queue[i].receiver,\n        _epochId,\n        queue[i].assets - relayerFee\n    );\n    depositQueue.pop();\n    if (i == 0) break;\n    unchecked {\n        i--;\n    }\n}\n```
MEDIUM severity: The `mTOFT` contract is vulnerable to token lockup due to a lack of enforcement of pool IDs during t. The `mTOFT` contract is vulnerable to token lockup due to a lack of enforcement of pool IDs during the rebalancing process. This vulnerability arises from the `Stargate` functionality, which allows for the swapping of one token on the source chain to another token on the destination chain. Specifica...

Vulnerable code:
```\nfunction _sendToken(\n    address payable _oft,\n    uint256 _amount,\n    uint16 _dstChainId,\n    uint256 _slippage,\n    bytes memory _data\n) private {\n    address erc20 = ITOFT(_oft).erc20();\n    if (IERC20Metadata(erc20).balanceOf(address(this)) < _amount) {\n        revert ExceedsBalance();\n    }\n    (\n        uint256 _srcPoolId,\n        uint256 _dstPoolId\n    ) = abi.decode(_data, (uint256, uint256));\n    _routerSwap(_dstChainId, _srcPoolId, _dstPoolId, _amount, _slippage, _oft, erc20);\n}\n```
MEDIUM severity: The vulnerability lies in the implementation of origin checks in the RPC access of the Solflare, Apt. The vulnerability lies in the implementation of origin checks in the RPC access of the Solflare, Aptos, and Sui snaps. Specifically, the code allows development and localhost origins to bypass the origin checks, which can lead to unintended exposure of the snaps' RPC interfaces.\n\nThe code snippets...

Vulnerable code:
```\nmodule.exports.onRpcRequest = async ({ origin, request }) => {\n  if (\n   !origin ||\n    (\n     !origin.match(/^https?:\/\/localhost:[0-9]{1,4}$/) &&\n     !origin.match(/^https?:\/\/(?:\S+\.)?solflare\.com$/) &&\n     !origin.match(/^https?:\/\/(?:\S+\.)?solflare\.dev$/)\n    )\n  ) {\n    throw new Error('Invalid origin');\n  }\n};\n```\n```\nmodule.exports.onRpcRequest = async ({ origin, request }) => {\n  if (\n   !origin ||\n    (\n     !origin.match(/^https?:\/\/localhost:[0-9]{1,4}$/) &&\n     !origin.match(/^https?:\/\/(?:\S+\.)?risewallet\.dev$/)\n    )\n  ) {\n    throw new Error('Invalid origin');\n  }\n};\n```\n```\nmodule.exports.onRpcRequest = async ({ origin, request }) => {\n  if (\n   !origin ||\n    (\n     !origin.match(/^https?:\/\/localhost:[0-9]{1,4}$/) &&\n     !origin.match(/^https?:\/\/(?:\S+\.)?elliwallet\.dev$/)\n    )\n  ) {\n    throw new Error('Invalid origin');\n  }\n};\n```
MEDIUM severity: The vulnerability lies in the `change_gauge_weight` function, which updates the `points_weight` and . The vulnerability lies in the `change_gauge_weight` function, which updates the `points_weight` and `time_weight` arrays without adjusting the slope (`m`) of the gauge's decay equation. This can lead to an accounting error when the gauge's weight is reduced to zero, causing the global weight to beco...

Vulnerable code:
```\ndef _change_gauge_weight(addr: address, weight: uint256):\n    gauge_type: int128 = self.gauge_types_[addr] - 1\n    old_gauge_weight: uint256 = self._get_weight(addr)\n    type_weight: uint256 = self._get_type_weight(gauge_type)\n    old_sum: uint256 = self._get_sum(gauge_type)\n    _total_weight: uint256 = self._get_total()\n    next_time: uint256 = (block.timestamp + WEEK) / WEEK * WEEK\n\n    self.points_weight[addr][next_time].bias = weight\n    self.time_weight[addr] = next_time\n\n    new_sum: uint256 = old_sum + weight - old_gauge_weight\n    self.points_sum[gauge_type][next_time].bias = new_sum\n    self.time_sum[gauge_type] = next_time\n\n    _total_weight = _total_weight + new_sum * type_weight - old_sum * type_weight\n    self.points_total[next_time] = _total_weight\n    self.time_total = next_time\n\n    log(NewGaugeWeight(addr, block.timestamp, weight, _total_weight))\n```
MEDIUM severity: The `createGauge4Pool` function is a publicly accessible function that allows anyone to create a Gau. The `createGauge4Pool` function is a publicly accessible function that allows anyone to create a Gauge for a special pool, specifically the 4pool. This function takes five parameters: `_4pool`, `_dai`, `_usdc`, `_usdt`, and `_cash`. However, none of these parameters are properly sanitized, which mea...

Vulnerable code:
```\nfunction createGauge4pool(\n    address _4pool,\n    address _dai,\n    address _usdc,\n    address _usdt,\n    address _cash\n) external returns (address) {\n```
MEDIUM severity: The absence of validation to ensure the Arbitrum sequencer is down before retrieving prices from the. The absence of validation to ensure the Arbitrum sequencer is down before retrieving prices from the Chainlink oracles can lead to inaccurate and potentially malicious data being used in the system. This vulnerability allows malicious actors to manipulate the system by exploiting the sequencer downt...

Vulnerable code:
```\nint256 rawCollateralPrice = strategy.collateralPriceOracle.latestAnswer();\nrebalanceInfo.collateralPrice = rawCollateralPrice.toUint256().mul(10 ** strategy.collateralDecimalAdjustment);\n\nint256 rawBorrowPrice = strategy.borrowPriceOracle.latestAnswer();\nrebalanceInfo.borrowPrice = rawBorrowPrice.toUint256().mul(10 ** strategy.borrowDecimalAdjustment);\n```
MEDIUM severity: The `claimForAccount()` function in the GMX Reward Router is vulnerable to an incorrect addition of . The `claimForAccount()` function in the GMX Reward Router is vulnerable to an incorrect addition of Wrapped Ether (WETH) to the user's tokensIn. This occurs when the `claimFees()` function is called, which automatically adds WETH to the user's account. However, if no fees have accrued yet, the WETH...

Vulnerable code:
```\nfunction canCallClaimFees()\n    internal\n    view\n    returns (bool, address[] memory, address[] memory)\n{\n    return (true, WETH, new address[](0));\n}\n```
MEDIUM severity: This vulnerability occurs when the `_redeemMoneyMarketIfRequired` function in the `TokenHandler.sol`. This vulnerability occurs when the `_redeemMoneyMarketIfRequired` function in the `TokenHandler.sol` contract fails to accurately calculate the required amount of funds to be withdrawn from the money market. Specifically, when the `withdrawAmountExternal` exceeds the current balance of the underlyin...

Vulnerable code:
```\nFile: TokenHandler.sol\n\nfunction _redeemMoneyMarketIfRequired(\n    uint16 currencyId,\n    Token memory underlying,\n    uint256 withdrawAmountExternal\n) private {\n    mapping(address => uint256) storage store = LibStorage.getStoredTokenBalances();\n    uint256 currentBalance = store[underlying.tokenAddress];\n    if (withdrawAmountExternal <= currentBalance) {\n        return;\n    }\n\n    IPrimeCashHoldingsOracle oracle = PrimeCashExchangeRate.getPrimeCashHoldingsOracle(currencyId);\n    (RedeemData[] memory data) = oracle.getRedemptionCalldata(withdrawAmountExternal);\n\n    uint256 totalUnderlyingRedeemed = executeMoneyMarketRedemptions(underlying, data);\n\n    require(withdrawAmountExternal <= currentBalance.add(totalUnderlyingRedeemed)); // dev: insufficient redeem\n```
MEDIUM severity: The `PlasmaFramework` contract is responsible for storing plasma block hashes and timestamps. Howeve. The `PlasmaFramework` contract is responsible for storing plasma block hashes and timestamps. However, the exit game libraries, which interact with this contract, fail to perform existence checks on the returned values from these queries. This oversight can lead to potential issues and errors in the...

Vulnerable code:
```\n(controller, uint256 blockTimestamp) = controller.framework.blocks(utxoPos.blockNum());\n```\n```\n(bytes32 root,) = self.framework.blocks(utxoPos.blockNum())\n```\n```\n(controller, uint256 blockTimestamp) = controller.framework.blocks(utxoPos.blockNum());\n```\n```\n(bytes32 root,) = data.framework.blocks(data.txPos.blockNum());\n```
MEDIUM severity: The Balancer's `_routerSwap` function utilizes the `safeApprove` function from the `oz` library to s. The Balancer's `_routerSwap` function utilizes the `safeApprove` function from the `oz` library to set an allowance for the `router` contract. However, the `convertRate` variable, which is obtained from the `pool` contract, is used to round down the incoming quantity. This behavior may lead to the a...

Vulnerable code:
```\nfunction _routerSwap(\n    uint16 _dstChainId,\n    uint256 _srcPoolId,\n    uint256 _dstPoolId,\n    uint256 _amount,\n    uint256 _slippage,\n    address payable _oft,\n    address _erc20\n) private {\n    bytes memory _dst = abi.encodePacked(connectedOFTs[_oft][_dstChainId].dstOft);\n    IERC20(_erc20).safeApprove(address(router), _amount);\n    router.swap{value: msg.value}(\n        _dstChainId,\n        _srcPoolId,\n        _dstPoolId,\n        payable(this),\n        _amount,\n        _computeMinAmount(_amount, _slippage),\n        IStargateRouterBase.lzTxObj({\n            dstGasForCall: 0,\n            dstNativeAmount: 0,\n            dstNativeAddr: "0x0"\n        }),\n        _dst,\n        "0x"\n    );\n```\n```\nfunction swap(\n    uint16 _dstChainId,\n    uint256 _srcPoolId,\n    uint256 _dstPoolId,\n    address payable _refundAddress,\n    uint256 _amountLD,\n    uint256 _minAmountLD,\n    lzTxObj memory _lzTxParams,\n    bytes calldata _to,\n    bytes calldata _payload\n) external payable override nonReentrant {\n    require(_amountLD > 0, "Stargate: cannot swap 0");\n    require(_refundAddress!= address(0x0), "Stargate: _refundAddress cannot be 0x0");\n\n    Pool.SwapObj memory s;\n    Pool.CreditObj memory c;\n\n    {\n        Pool pool = _getPool(_srcPoolId);\n\n        uint256 convertRate = pool.convertRate();\n        _amountLD = _amountLD / convertRate * convertRate;\n\n        s = pool.swap(_dstChainId, _dstPoolId, msg.sender, _amountLD, _minAmountLD, true);\n        _safeTransferFrom(pool.token(), msg.sender, address(pool), _amountLD);\n\n        c = pool.sendCredits(_dstChainId, _dstPoolId);\n    }\n\n    bridge.swap{value: msg.value}(_dstChainId, _srcPoolId, _dstPoolId, _refundAddress, c, s, _lzTxParams, _to, _payload);\n}\n```
MEDIUM severity: The vulnerability lies in the default setting of the `rollable` flag to `true` when creating a new l. The vulnerability lies in the default setting of the `rollable` flag to `true` when creating a new loan. This allows borrowers to extend the loan's expiration date at any time before the specified deadline, giving them an unfair advantage over the lender. \n\nBy defaulting the `rollable` flag to `tr...

Vulnerable code:
```\nloans.push(\n    Loan(\n        req,\n        req.amount + interest,\n        collat,\n        expiration,\n        true,\n        msg.sender\n    )\n);\n```\n```\nfunction roll(uint256 loanID) external {\n    Loan storage loan = loans[loanID];\n    Request memory req = loan.request;\n\n    if (block.timestamp > loan.expiry) \n        revert Default();\n\n    if (!loan.rollable)\n        revert NotRollable();\n```\n```\nfunction toggleRoll(uint256 loanID) external returns (bool) {\n    loan.rollable =!loan.rollable;\n}\n```
MEDIUM severity: The ERC4626 oracle is susceptible to price manipulation due to its design, which allows an attacker . The ERC4626 oracle is susceptible to price manipulation due to its design, which allows an attacker to artificially inflate or deflate the price of the LP token within a single transaction or block. This vulnerability arises from the `getPrice` function, which relies on the `ERC4626.previewRedeem` a...

Vulnerable code:
```\nFile: ERC4626Oracle.sol\n\nfunction getPrice(address token) external view returns (uint) {\n    uint decimals = IERC4626(token).decimals();\n    return IERC4626(token).previewRedeem(10 ** decimals).mulDivDown(\n        oracleFacade.getPrice(IERC4626(token).asset()),\n        10 ** decimals\n    );\n}\n```\n```\nFile: ERC4626.sol\n\nfunction previewRedeem(uint256 shares) public view virtual returns (uint256) {\n    return convertToAssets(shares);\n}\n```\n```\nFile: ERC4626.sol\n\nfunction convertToAssets(uint256 shares) public view virtual returns (uint256) {\n    uint256 supply = totalSupply;  # Saves an extra SLOAD if totalSupply is non-zero.\n\n    return supply == 0? shares : shares.mulDivDown(totalAssets(), supply);\n}\n```
MEDIUM severity: The LSP6 protocol allows for the relaying of calls using a supplied signature, which enables the enc. The LSP6 protocol allows for the relaying of calls using a supplied signature, which enables the encoding of a message as a bytes array. The message structure is defined as a concatenation of several components, including the LSP6 version, the blockchain chain ID, a nonce, the message value, and the...

Vulnerable code:
```\nbytes memory encodedMessage = abi.encodePacked(\n    LSP6_VERSION,\n    block.chainId,\n    nonce,\n    msgValue,\n    payload\n);\n```
MEDIUM severity: The `BondAggregator.findMarketFor` function in the `BondAggregator` contract is vulnerable to a pote. The `BondAggregator.findMarketFor` function in the `BondAggregator` contract is vulnerable to a potential reversion when the `BondBaseSDA.payoutFor` function within the for-loop reverts under certain conditions. This occurs when the computed payout for a market exceeds the market's maximum payout, c...

Vulnerable code:
```\nFile: BondBaseSDA.sol\n\nfunction payoutFor(\n    uint256 amount_,\n    uint256 id_,\n    address referrer_\n) public view override returns (uint256) {\n    uint256 fee = amount_.mulDiv(_teller.getFee(referrer_), 1e5);\n    uint256 payout = (amount_ - fee).mulDiv(markets[id_].scale, marketPrice(id_));\n\n    if (payout > markets[id_].maxPayout) {\n        revert Auctioneer_MaxPayoutExceeded();\n    } else {\n        return payout;\n    }\n}\n```\n```\nFile: BondAggregator.sol\n\n/// @inheritdoc IBondAggregator\nfunction findMarketFor(\n    address payout_,\n    address quote_,\n    uint256 amountIn_,\n    uint256 minAmountOut_,\n    uint256 maxExpiry_\n) external view returns (uint256) {\n    uint256[] memory ids = marketsFor(payout_, quote_);\n    uint256 len = ids.length;\n    uint256[] memory payouts = new uint256[](len);\n\n    uint256 highestOut;\n    uint256 id = type(uint256).max; // set to max so an empty set doesn't return 0, the first index\n    uint48 vesting;\n    uint256 maxPayout;\n    IBondAuctioneer auctioneer;\n\n    for (uint256 i = 0; i < len; i++) {\n        auctioneer = marketsToAuctioneers[ids[i]];\n        (,,,, vesting, maxPayout) = auctioneer.getMarketInfoForPurchase(ids[i]);\n\n        uint256 expiry = (vesting <= MAX_FIXED_TERM)? block.timestamp + vesting : vesting;\n\n        if (expiry <= maxExpiry_) {\n            payouts[i] = minAmountOut_ <= maxPayout\n               ? payoutFor(amountIn_, ids[i], address(0))\n                : 0;\n\n            if (payouts[i] > highestOut) {\n                highestOut = payouts[i];\n                id = ids[i];\n            }\n        }\n    }\n\n    return id;\n```
MEDIUM severity: The Liquidator can manipulate the referral process by exploiting a vulnerability in the system's ref. The Liquidator can manipulate the referral process by exploiting a vulnerability in the system's referral setup mechanism. Specifically, when a user has met the liquidation criteria and does not have a referrer, a malicious liquidator can specify a referrer in the liquidation order. This allows the...

Vulnerable code:
```\nfunction _loadUpdateContext(\n    Context memory context,\n    address account,\n    address referrer\n) private view returns (UpdateContext memory updateContext) {\n    updateContext.referrer = referrers[account][context.local.currentId];\n    updateContext.referralFee = IMarketFactory(address(factory())).referralFee(referrer);\n}\n\nfunction _processReferrer(\n    UpdateContext memory updateContext,\n    Order memory newOrder,\n    address referrer\n) private pure {\n    if (newOrder.makerReferral.isZero() && newOrder.takerReferral.isZero()) return;\n    if (updateContext.referrer == address(0)) updateContext.referrer = referrer;\n    if (updateContext.referrer == referrer) return;\n\n    revert MarketInvalidReferrerError();\n}\n\nfunction _storeUpdateContext(\n    Context memory context,\n    UpdateContext memory updateContext,\n    address account\n) private {\n    referrers[account][context.local.currentId] = updateContext.referrer;\n}\n```
MEDIUM severity: This vulnerability occurs when a player is marked as wounded in a specific round, but is unable to i. This vulnerability occurs when a player is marked as wounded in a specific round, but is unable to invoke the `heal` function in the subsequent round. The issue arises when the game is advanced to the next round, and the player attempts to heal their wounded agent. However, the `heal` function is no...

Vulnerable code:
```\nfunction test_heal_in_next_round_v1() public {\n    _startGameAndDrawOneRound();\n\n    _drawXRounds(11);\n\n    (uint256[] memory woundedAgentIds,) = infiltration.getRoundInfo({roundId: 12});\n\n    address agentOwner = _ownerOf(woundedAgentIds[0]);\n    looks.mint(agentOwner, HEAL_BASE_COST);\n\n    vm.startPrank(agentOwner);\n    _grantLooksApprovals();\n    looks.approve(TRANSFER_MANAGER, HEAL_BASE_COST);\n\n    uint256[] memory agentIds = new uint256[](1);\n    agentIds[0] = woundedAgentIds[0];\n\n    uint256[] memory costs = new uint256[](1);\n    costs[0] = HEAL_BASE_COST;\n\n    (,,,,, uint40 currentRoundId,,,,,) = infiltration.gameInfo();\n    assert(currentRoundId == 13);\n\n    IInfiltration.Agent memory agentInfo = infiltration.getAgent(woundedAgentIds[0]);\n    assert(agentInfo.woundedAt == 12);\n\n    vm.expectRevert(IInfiltration.HealingMustWaitAtLeastOneRound.selector);\n    infiltration.heal(agentIds);\n}\n```
MEDIUM severity: The `verifyHash256Merkle` function in the `BTCUtils` module is responsible for validating the existe. The `verifyHash256Merkle` function in the `BTCUtils` module is responsible for validating the existence of a transaction in a Bitcoin block by verifying a Merkle proof. The function accepts a `_proof` and an `_index` as input. The `_proof` consists of a transaction hash, a list of intermediate nodes...

Vulnerable code:
```\nuint _idx = _index;\nbytes32 _root = _proof.slice(_proof.length - 32, 32).toBytes32();\nbytes32 _current = _proof.slice(0, 32).toBytes32();\n\nfor (uint i = 1; i < (_proof.length / 32) - 1; i++) {\n    if (_idx % 2 == 1) {\n        _current = _hash256MerkleStep(_proof.slice(i * 32, 32), abi.encodePacked(_current));\n    } else {\n        _current = _hash256MerkleStep(abi.encodePacked(_current), _proof.slice(i * 32, 32));\n    }\n    _idx = _idx + 1;\n}\nreturn _current == _root;\n```\n```\nit('verifies a bitcoin merkle root', async () => {\n  for (let i = 0; i < verifyHash256Merkle.length; i += 1) {\n    const res = await instance.verifyHash256Merkle(\n      verifyHash256Merkle[i].input.proof,\n      verifyHash256Merkle[i].input.index\n    ); // 0-indexed\n    assert.strictEqual(res, verifyHash256Merkle[i].output);\n\n    let pLen = verifyHash256Merkle[i].input.proof.length;\n    let height = Math.floor((pLen - 2) / 64) - 2;\n\n    if (verifyHash256Merkle[i].output && height >= 1) {\n      let altIdx = 2 ** height + verifyHash256Merkle[i].input.index;\n\n      const resNext = await instance.verifyHash256Merkle(\n        verifyHash256Merkle[i].input.proof,\n        altIdx\n      );\n\n      assert.strictEqual(resNext, verifyHash256Merkle[i].output);\n\n      console.log('Verified transaction twice!');\n    }\n  }\n});\n```
MEDIUM severity: When an order is cancelled, the refund process in Dinari's current implementation is flawed. Instead. When an order is cancelled, the refund process in Dinari's current implementation is flawed. Instead of returning the refund to the order creator, who is responsible for paying the payment token or dShares, the refund is sent to the order recipient. This is contrary to the standard practice in many...

Vulnerable code:
```\nfunction _cancelOrderAccounting(OrderRequest calldata orderRequest, bytes32 orderId, OrderState memory orderState)\n    internal\n    virtual\n    override\n{\n    uint256 refund = orderState.remainingOrder + feeState.remainingPercentageFees;\n\n    if (refund + feeState.feesEarned == orderRequest.quantityIn) {\n        _closeOrder(orderId, orderRequest.paymentToken, 0);\n        refund = orderRequest.quantityIn;\n    } else {\n        _closeOrder(orderId, orderRequest.paymentToken, feeState.feesEarned);\n    }\n\n    IERC20(orderRequest.paymentToken).safeTransfer(orderRequest.recipient, refund);\n}\n```