Skip to content
Business logic Audit finding Intermediate

Change of fundingDuration causes “time travel” of PerpetualAtlanticVault.nextFundingPaymentTimestamp()

0xTheC0der Follow with nirlin, __141345__ and 20 others

Originally disclosed on Code4rena

Submitted by 0xTheC0der, also found by nirlin, 141345, QiuhaoLi (1, 2), bin2chen, 0xbranded, jasonxiale, 0Kage, pep7siup, 836541, joaovwfreire, bart1e, ABA, alexfilippov314, peakbolt, ayden, 0xDING99YA, T1MOH, chaduke, SpicyMeatball, degensec, Kow, rvierdiiev, 0xHelium, and tnquanghuy0512

The return value of PerpetualAtlanticVault.nextFundingPaymentTimestamp(), which marks the beginning of the next funding epoch, scales linearly with the current fundingDuration. (Note that latestFundingPaymentPointer is strictly monotonically increasing with each epoch.) Therefore, epochs are separated by a period of fundingDuration.

  function nextFundingPaymentTimestamp()
    public
    view
    returns (uint256 timestamp)
  {
    return genesis + (latestFundingPaymentPointer * fundingDuration);
  }

However, the owner can change the fundingDuration at any time via PerpetualAtlanticVault.updateFundingDuration(…) which is an intended feature of the contract, otherwise the funding duration would be immutable.

First order consequences

Assume the owner changes the fundingDuration by a value delta, such that: new fundingDuration = old fundingDuration + delta. As a result, the return value of PerpetualAtlanticVault.nextFundingPaymentTimestamp() moves by a value of latestFundingPaymentPointer * delta into the future or past (depending on the sign of delta).

Numerical example: The fundingDuration = 7 days and is slightly reduced by delta = -1 hour. The protocol is alread live for nearly 2 years, therefore latestFundingPaymentPointer = 96. Consequently, the next funding epoch “begins” latestFundingPaymentPointer * delta = -96 hours = -4 days in the past.

The PerpetualAtlanticVault.nextFundingPaymentTimestamp() is called at 14 instances throughout the PerpetualAtlanticVault contract and once by the RdpxV2Core contract for bonding cost calculation, see RdpxV2Core.calculateBondCost(…).

Second order consequences

Due the scattered impacts of the present bug, there arise multiple problems. Nevertheless, this report solely focuses on the following consquences in order to emphasize the severity of this issue.

PerpetualAtlanticVault.updateFundingPaymentPointer()

This helper method is (implicitly) called by the updateFunding(), purchase(...), settle(...) and calculateFunding(...) methods, but not by the payFunding() method of the contract. It is responsible for iteratively bringing the latestFundingPaymentPointer into the present while funding the LP with collateral for each epoch.

In case of “time travel” by changing the fundingDuration it will do the following:

  • nextFundingPaymentTimestamp() lies in the past: It will iterarte until nextFundingPaymentTimestamp() lies in the future, thereby immediately ending the current epoch and skipping the following ones, see PoC.
  • nextFundingPaymentTimestamp() lies in the future: Once the overly long epoch old fundingDuration + delta * latestFundingPaymentPointer expires, it will overpay collateral for this epoch to the LP, see L473-L477.

PerpetualAtlanticVault.purchase(…)

This method is called by the core contract when bonding in order to buy options. Thereby the option premium is heavily dependent on the return value of nextFundingPaymentTimestamp(), see L283-L286.

In case of an overly long epoch old fundingDuration + delta * latestFundingPaymentPointer due to an increase of the fundingDuration by delta, the option premium is excessively increased leading to a loss of funds for the user/protocol by using up a great part of the reserve WETH for the option, see core contract L918-L924 and PoC. Subsequently the bonding gets more expensive, i.e. the user has to supply more WETH, see also RdpxV2Core.calculateBondCost(…).

For reference, the correct epoch duration in this case should be old fundingDuration + delta. The affected entry point methods are RdpxV2Core.bond(…) and RdpxV2Core.bondWithDelegate(…). This is also time critical in another way, since the user cannot know if the fundingDuration was changed after calculating the bonding cost via RdpxV2Core.calculateBondCost(…), but before his bonding transaction.

Conclusion

The resulting funding period / epoch inconsistencies by jumping in time, as well as the execessivley overpriced options, which do lead to loss of funds when bought during that epoch, are sufficient to strongly disincentivize users from bonding. This consequently endagers the peg which can be considered the most valuable asset of the protocol.

Futhermore, the user cannot know if the fundingDuration was changed before his transaction is executed which poses an additional risk.

Proof of Concept

In order to prove the above claims, three new test cases were added. The last assertion in each of those cases fails in order to demonstrate the issues.

  • testUpdateFundingPaymentPointerPast(): The return value of nextFundingPaymentTimestamp() lies in the past and multiple epochs are skipped on updateFundingPaymentPointer().
  • testUpdateFundingPaymentPointerPast(): The return value of nextFundingPaymentTimestamp() lies in the future, therefore the current epoch is overly long and won’t change on updateFundingPaymentPointer() after waiting for new fundingDuration.
  • testPurchaseExtendedEpoch(): Shows the excessive increase in option premium on a slight increase of fundingDuration, i.e. unjustified overuse/loss of funds.

Just apply the diff below and run the test cases with forge test -vv --match-test testUpdateFundingPaymentPointer and forge test -vv --match-test testPurchaseExtendedEpoch:

diff --git a/contracts/mocks/MockOptionPricing.sol b/contracts/mocks/MockOptionPricing.sol
index 5b77b16..c8e92f1 100644
--- a/contracts/mocks/MockOptionPricing.sol
+++ b/contracts/mocks/MockOptionPricing.sol
@@ -8,8 +8,8 @@ contract MockOptionPricing is IOptionPricing {
     uint256,
     uint256,
     uint256,
-    uint256
+    uint256 timeToExpiry
   ) external pure override returns (uint256) {
-    return 5e6; // 0.05 weth
+    return 5e6 * timeToExpiry / 1 days; // 0.05 weth
   }
 }
diff --git a/tests/perp-vault/Unit.t.sol b/tests/perp-vault/Unit.t.sol
index c8016e0..dcfd72a 100644
--- a/tests/perp-vault/Unit.t.sol
+++ b/tests/perp-vault/Unit.t.sol
@@ -108,6 +108,33 @@ contract Unit is ERC721Holder, Setup {
     vault.purchase(300 ether, address(this));
   }

+  function testPurchaseExtendedEpoch() external {
+    testDeposit();
+
+    skip(vault.fundingDuration() * 10); // expire 10 epochs
+    vault.updateFundingPaymentPointer();
+
+    uint256 timeTillExpiry = vault.nextFundingPaymentTimestamp() -
+      block.timestamp;
+
+    // uses calculates expected option premium
+    uint256 expectedPremium = vault.calculatePremium(
+      0.015 gwei,
+      500 ether,
+      timeTillExpiry,
+      0.02 gwei
+    );
+
+    // owner happends to extend funding duration --> severely increases option premium
+    vault.updateFundingDuration(vault.fundingDuration() + 1 hours);  // comment this line to see test case pass
+
+    // user doesn't know about the bug and funding duration change --> overpays for option
+    (uint256 paidPremium, ) = vault.purchase(500 ether, address(this));
+
+    assertEq(paidPremium, expectedPremium);
+  }
+
+
   function testCalculatePremium() external {
     uint256 pnl = vault.calculatePnl(0.01 gwei, 0.015 gwei, 1 ether);
     assertEq(pnl, 0.05 ether);
@@ -291,6 +318,47 @@ contract Unit is ERC721Holder, Setup {
     assertEq(pointer, 2);
   }

+  function testUpdateFundingPaymentPointerPast() external {
+    uint256 pointer = vault.latestFundingPaymentPointer();
+    assertEq(pointer, 0);
+    skip(vault.fundingDuration()); // expire
+    vault.updateFundingPaymentPointer();
+    pointer = vault.latestFundingPaymentPointer();
+    assertEq(pointer, 1);
+
+    skip(vault.fundingDuration()*95);
+    purchaseOneOption(); // updates payment pointer if block.timestamp > nextFundingPaymentTimestamp
+    pointer = vault.latestFundingPaymentPointer();
+    assertEq(pointer, 96);
+
+    vault.updateFundingDuration(vault.fundingDuration() - 1 hours); // reduce funding duration by 1 hour
+    skip(vault.fundingDuration()); // expire
+    vault.updateFundingPaymentPointer();  // updates payment pointer if block.timestamp > nextFundingPaymentTimestamp
+    pointer = vault.latestFundingPaymentPointer();
+    assertEq(pointer, 97); // fails: we would expect 97 but actually skipped 4 epochs due to "time traveling"
+  }
+
+  function testUpdateFundingPaymentPointerFuture() external {
+    uint256 pointer = vault.latestFundingPaymentPointer();
+    assertEq(pointer, 0);
+    skip(vault.fundingDuration()); // expire
+    vault.updateFundingPaymentPointer();
+    pointer = vault.latestFundingPaymentPointer();
+    assertEq(pointer, 1);
+
+    skip(vault.fundingDuration()*95);
+    purchaseOneOption(); // updates payment pointer if block.timestamp > nextFundingPaymentTimestamp
+    pointer = vault.latestFundingPaymentPointer();
+    assertEq(pointer, 96);
+
+    vault.updateFundingDuration(vault.fundingDuration() + 1 hours); // increase funding duration by 1 hour
+    skip(vault.fundingDuration()); // expire
+    vault.updateFundingPaymentPointer();  // updates payment pointer if block.timestamp > nextFundingPaymentTimestamp
+    pointer = vault.latestFundingPaymentPointer();
+    assertEq(pointer, 97); // fails: we would expect 97 but it's still 96 because the next epoch lies 4 days in the future
+  }
+
+
   function testMockups() external {
     deposit(1 ether, address(this));
     assertEq(vaultLp.totalCollateral(), 1 ether);

Recommended Mitigation Steps

Option 1 - Complete Fix: Reconsider if it is really necessary for the protocol to change the funding duration throughout its lifecycle. If no, declare the fundingDuration as immutable.

Option 2 - Mitigation: Store the lastFundingPaymentTimestamp and incease it by fundingDuration in updateFundingPaymentPointer() on each new epoch to accomplish the expected timing behaviour. Note that the scaling issue does not only appear in PerpetualAtlanticVault.nextFundingPaymentTimestamp(), but also in L426-427.

Alex the Entreprenerd (Judge) decreased severity to Medium and commented:

Good discussion of consequences + POC.

witherblock (Dopex) confirmed via duplicate issue 980


The original report as published on Code4rena, by 0xTheC0der. 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.

What is known

A medium-severity business logic bug in Dopex. Code4rena made it public on 29 December 2023. Found in the 2023-08-dopex audit contest (finding M-10), also found by 22 other wardens.

About Business logic

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

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

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 0xTheC0der

View all

11 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.