Skip to content
Business logic Audit finding Intermediate

User can avoid paying high premium price by correctly timing his bond call

The bond premium calculation uses the time remaining until the next funding payment, so a user can time their bond to just after a funding update and pay a much lower premium for the same bond amount and price. This lets users avoid paying the higher premium that would apply earlier in the funding period.

said Follow with qpzm, Tendency and 7 others

Originally disclosed on Code4rena

Submitted by said, also found by qpzm, 141345 (1, 2), Tendency, nirlin, carrotsmuggler, wallstreetvilkas, Nyx, 0xWaitress, RED-LOTUS-REACH, and peakbolt

https://github.com/code-423n4/2023-08-dopex/blob/main/contracts/core/RdpxV2Core.sol#L481-L483

https://github.com/code-423n4/2023-08-dopex/blob/main/contracts/perp-vault/PerpetualAtlanticVault.sol#L283-L286

When user execute bond operations and putOptionsRequired is true, the premium that they will pay is depend on time when the bond operations will be executed. This will cause the premium paid by user will be less despite bond the same amount at the same price if they time it correctly.

Proof of Concept

When user trigger bond or bondWithDelegate, it will call calculateBondCost to calculate rdpxRequired and wethRequired.

https://github.com/code-423n4/2023-08-dopex/blob/main/contracts/core/RdpxV2Core.sol#L904-L907

  function bond(
    uint256 _amount,
    uint256 rdpxBondId,
    address _to
  ) public returns (uint256 receiptTokenAmount) {
    _whenNotPaused();
    // Validate amount
    _validate(_amount > 0, 4);

    // Compute the bond cost
>>> (uint256 rdpxRequired, uint256 wethRequired) = calculateBondCost(
      _amount,
      rdpxBondId
    );

    IERC20WithBurn(weth).safeTransferFrom(
      msg.sender,
      address(this),
      wethRequired
    );

    // update weth reserve
    reserveAsset[reservesIndex["WETH"]].tokenBalance += wethRequired;

    // purchase options
    uint256 premium;
    if (putOptionsRequired) {
      premium = _purchaseOptions(rdpxRequired);
    }

    _transfer(rdpxRequired, wethRequired - premium, _amount, rdpxBondId);

    // Stake the ETH in the ReceiptToken contract
    receiptTokenAmount = _stake(_to, _amount);

    // reLP
    if (isReLPActive) IReLP(addresses.reLPContract).reLP(_amount);

    emit LogBond(rdpxRequired, wethRequired, receiptTokenAmount);
  }

If putOptionsRequired is true, calculateBondCost will calculate the premium users need to pay and add it to wethRequired :

https://github.com/code-423n4/2023-08-dopex/blob/main/contracts/core/RdpxV2Core.sol#L1192-L1198

  function calculateBondCost(
    uint256 _amount,
    uint256 _rdpxBondId
  ) public view returns (uint256 rdpxRequired, uint256 wethRequired) {
    uint256 rdpxPrice = getRdpxPrice();

    if (_rdpxBondId == 0) {
      uint256 bondDiscount = (bondDiscountFactor *
        Math.sqrt(IRdpxReserve(addresses.rdpxReserve).rdpxReserve()) *
        1e2) / (Math.sqrt(1e18)); // 1e8 precision

      _validate(bondDiscount < 100e8, 14);

      rdpxRequired =
        ((RDPX_RATIO_PERCENTAGE - (bondDiscount / 2)) *
          _amount *
          DEFAULT_PRECISION) /
        (DEFAULT_PRECISION * rdpxPrice * 1e2);

      wethRequired =
        ((ETH_RATIO_PERCENTAGE - (bondDiscount / 2)) * _amount) /
        (DEFAULT_PRECISION * 1e2);
    } else {
      // if rdpx decaying bonds are being used there is no discount
      rdpxRequired =
        (RDPX_RATIO_PERCENTAGE * _amount * DEFAULT_PRECISION) /
        (DEFAULT_PRECISION * rdpxPrice * 1e2);

      wethRequired =
        (ETH_RATIO_PERCENTAGE * _amount) /
        (DEFAULT_PRECISION * 1e2);
    }

    uint256 strike = IPerpetualAtlanticVault(addresses.perpetualAtlanticVault)
      .roundUp(rdpxPrice - (rdpxPrice / 4)); // 25% below the current price

>>> uint256 timeToExpiry = IPerpetualAtlanticVault(
      addresses.perpetualAtlanticVault
    ).nextFundingPaymentTimestamp() - block.timestamp;
    if (putOptionsRequired) {
>>>   wethRequired += IPerpetualAtlanticVault(addresses.perpetualAtlanticVault)
        .calculatePremium(strike, rdpxRequired, timeToExpiry, 0);
    }
  }

It can be observed that the provided timeToExpiry is depend on nextFundingPaymentTimestamp and current block.timestamp.

This has potential leak value issue, since with providing the same amount at the same price (assume the rdpx price will not be that volatile), the user paid less premium by timing the bond near to nextFundingPaymentTimestamp.

Foundry PoC :

The goal of this PoC is we try to compare the option price we get, using OptionPricingSimple, providing the same amount and price, with different time. OptionPricingSimple configured with 0.05% minimum price, funding duration 7 days and current rdpxPriceInEth is 2e7.

Compared time 7 days, 6 days, and 1 day before next funding payment.

Add this test to Unit contract inside /tests/rdpxV2-core/Unit.t.sol, also add import "forge-std/console.sol"; and import {OptionPricingSimple} from "contracts/libraries/OptionPricingSimple.sol"; in the contract:

    function testOptionPricingTiming() public {
        OptionPricingSimple optionPricingSimple;
        // 5e6
        optionPricingSimple = new OptionPricingSimple(100, 5e6);

        (uint256 rdpxRequired, uint256 wethRequired) = rdpxV2Core
            .calculateBondCost(1 * 1e18, 0);

        uint256 currentPrice = vault.getUnderlyingPrice(); // price
        uint256 strike = vault.roundUp(currentPrice - (currentPrice / 4)); // 25% below the current price
        console.log("What is the current price");
        console.log(currentPrice);
        console.log("What is the strike");
        console.log(strike);

        // 7 days before next funding payment
        uint256 timeToExpiry = vault.nextFundingPaymentTimestamp() -
            block.timestamp;
        console.log("What is time to expiry initial :");
        console.log(timeToExpiry);
        uint256 optionPrice = optionPricingSimple.getOptionPrice(
            strike,
            currentPrice,
            100,
            timeToExpiry
        );
        console.log("What is option pricing initial :");
        console.log(optionPrice);

        // 1 day afters
        vm.warp(block.timestamp + 1 days);
        uint256 timeToExpiryAfter1Day = vault.nextFundingPaymentTimestamp() -
            block.timestamp;
        console.log("What is time to expiry after 1 day :");
        console.log(timeToExpiryAfter1Day);
        optionPrice = optionPricingSimple.getOptionPrice(
            strike,
            currentPrice,
            100,
            timeToExpiryAfter1Day
        );
        console.log("What is option pricing after 1 day :");
        console.log(optionPrice);

        // after 6 days
        vm.warp(block.timestamp + 5 days);
        uint256 timeToExpiryAfter6Day = vault.nextFundingPaymentTimestamp() -
            block.timestamp;
        console.log("What is time to expiry after 6 day :");
        console.log(timeToExpiryAfter6Day);

        optionPrice = optionPricingSimple.getOptionPrice(
            strike,
            currentPrice,
            100,
            timeToExpiryAfter6Day
        );
        console.log("What is option pricing after 6 day :");
        console.log(optionPrice);
    }

Run the PoC :

forge test --match-contract Unit --match-test testOptionPricingTiming -vvv

Log Output :

Logs:
  What is the current price
  20000000
  What is the strike
  15000000

  What is time to expiry initial :
  604800
  What is option pricing initial :
  16481

  What is time to expiry after 1 day :
  518400
  What is option pricing after 1 day :
  10000

  What is time to expiry after 6 day :
  86400
  What is option pricing after 6 day :
  10000

It can be observed that users will pay minimum price (0.05%) even only after 1 day updating funding time pointer!

Recommended Mitigation Steps

To avoid this, fix the provided Black-Scholes option price observation time to funding epoch duration windows :

  function calculateBondCost(
    uint256 _amount,
    uint256 _rdpxBondId
  ) public view returns (uint256 rdpxRequired, uint256 wethRequired) {
    uint256 rdpxPrice = getRdpxPrice();

    if (_rdpxBondId == 0) {
      uint256 bondDiscount = (bondDiscountFactor *
        Math.sqrt(IRdpxReserve(addresses.rdpxReserve).rdpxReserve()) *
        1e2) / (Math.sqrt(1e18)); // 1e8 precision

      _validate(bondDiscount < 100e8, 14);

      rdpxRequired =
        ((RDPX_RATIO_PERCENTAGE - (bondDiscount / 2)) *
          _amount *
          DEFAULT_PRECISION) /
        (DEFAULT_PRECISION * rdpxPrice * 1e2);

      wethRequired =
        ((ETH_RATIO_PERCENTAGE - (bondDiscount / 2)) * _amount) /
        (DEFAULT_PRECISION * 1e2);
    } else {
      // if rdpx decaying bonds are being used there is no discount
      rdpxRequired =
        (RDPX_RATIO_PERCENTAGE * _amount * DEFAULT_PRECISION) /
        (DEFAULT_PRECISION * rdpxPrice * 1e2);

      wethRequired =
        (ETH_RATIO_PERCENTAGE * _amount) /
        (DEFAULT_PRECISION * 1e2);
    }

    uint256 strike = IPerpetualAtlanticVault(addresses.perpetualAtlanticVault)
      .roundUp(rdpxPrice - (rdpxPrice / 4)); // 25% below the current price

-    uint256 timeToExpiry = IPerpetualAtlanticVault(
-      addresses.perpetualAtlanticVault
-    ).nextFundingPaymentTimestamp() - block.timestamp;
+    uint256 timeToExpiry = IPerpetualAtlanticVault(
+      addresses.perpetualAtlanticVault
+    ).nextFundingPaymentTimestamp() -
+      IPerpetualAtlanticVault(addresses.perpetualAtlanticVault).fundingDuration();
    if (putOptionsRequired) {
      wethRequired += IPerpetualAtlanticVault(addresses.perpetualAtlanticVault)
        .calculatePremium(strike, rdpxRequired, timeToExpiry, 0);
    }
  }

Also update the time expiry when purchase the options

  function purchase(
    uint256 amount,
    address to
  )
    external
    nonReentrant
    onlyRole(RDPXV2CORE_ROLE)
    returns (uint256 premium, uint256 tokenId)
  {
    _whenNotPaused();
    _validate(amount > 0, 2);

    updateFunding();

    uint256 currentPrice = getUnderlyingPrice(); // price of underlying wrt collateralToken
    uint256 strike = roundUp(currentPrice - (currentPrice / 4)); // 25% below the current price
    IPerpetualAtlanticVaultLP perpetualAtlanticVaultLp = IPerpetualAtlanticVaultLP(
        addresses.perpetualAtlanticVaultLP
      );

    // Check if vault has enough collateral to write the options
    uint256 requiredCollateral = (amount * strike) / 1e8;

    _validate(
      requiredCollateral <= perpetualAtlanticVaultLp.totalAvailableCollateral(),
      3
    );

-    uint256 timeToExpiry = nextFundingPaymentTimestamp() - block.timestamp;
+    uint256 timeToExpiry = nextFundingPaymentTimestamp() - fundingDuration
    // Get total premium for all options being purchased
    premium = calculatePremium(strike, amount, timeToExpiry, 0);

    // Transfer premium from msg.sender to PerpetualAtlantics vault
    collateralToken.safeTransferFrom(msg.sender, address(this), premium);

    perpetualAtlanticVaultLp.lockCollateral(requiredCollateral);
    _updateFundingRate(premium);

    // Mint the option tokens
    tokenId = _mintOptionToken();
    optionPositions[tokenId] = OptionPosition({
      strike: strike,
      amount: amount,
      positionId: tokenId
    });

    totalActiveOptions += amount;
    fundingPaymentsAccountedFor[latestFundingPaymentPointer] += amount;
    optionsPerStrike[strike] += amount;

    // record the number of options funding has been accounted for the epoch and strike
    fundingPaymentsAccountedForPerStrike[latestFundingPaymentPointer][
      strike
    ] += amount;

    emit Purchase(strike, amount, premium, to, msg.sender);
  }

witherblock (Dopex) confirmed


The original report as published on Code4rena, by said. Images and videos are our own copies; raw HTML is shown as text. View it on Code4rena.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

Likely the premium is calculated using the remaining time until the next funding payment instead of a fixed funding epoch duration, so the time-to-expiry shrinks as the epoch progresses.

Impact

A user could pay a lower premium for the same bond by timing the transaction, reducing the cost of the option component.

What the attacker needed

PutOptionsRequired is true; user can time bond transaction

The fix

The time to expiry should be fixed to the funding epoch duration rather than the remaining time until the next funding payment, and the same value should be used when purchasing options.

How it was found

  1. Observe that bond cost includes a premium based on time to next funding payment.
  2. Wait until shortly after a funding payment so the remaining time is small.
  3. Call bond or bondWithDelegate with the desired amount.
  4. Pay a reduced premium compared to bonding earlier in the epoch.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

When you bond, you also buy a kind of insurance (an option) whose price depends on how long the insurance lasts. The code measures that time from the moment you bond until the next scheduled payment, so if you bond right after a payment the insurance looks very short and cheap. You still get the same bond, but you pay much less for the insurance part.

What is Business logic?

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.

More by said

View all

21 more disclosed reports, best first.

More from Dopex

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.