OrderBook

First Flight #43
Beginner FriendlySolidity
100 EXP
View results
Submission Details
Impact: low
Likelihood: high
Invalid

Redundant String Initialization Increases Gas Usage

Root + Impact

Description

  • The contract initializes the string memory status variable at the time of declaration, even though its value is always reassigned in subsequent conditional branches. This results in unnecessary memory allocation and increased gas consumption.

// Root cause in the codebase with @> marks to highlight the relevant section

Risk

Likelihood:

  • This will occur every time the getOrderDetailsString function is called, as the string variable is always initialized before being conditionally assigned.

Impact:

  • Increased gas costs for every call to the function due to unnecessary memory allocation.

  • Reduced overall efficiency, especially when the function is called frequently or in a loop.

Proof of Concept

the script for comparing difference in gas cost.

function test_gas_getOrderDetailsString_vs_Optimized() public {
// bob creates sell order for weth
vm.startPrank(bob);
weth.approve(address(book), 2e18);
uint256 bobId = book.createSellOrder(address(weth), 2e18, 5_000e6, 2 days);
vm.stopPrank();
// Measure gas for original
uint256 gasStart = gasleft();
book.getOrderDetailsString(bobId);
uint256 gasUsedOriginal = gasStart - gasleft();
// Measure gas for optimized
gasStart = gasleft();
book.getOrderDetailsStringOptimized(bobId);
uint256 gasUsedOptimized = gasStart - gasleft();
emit log_named_uint("Gas used (Original)", gasUsedOriginal);
emit log_named_uint("Gas used (Optimized)", gasUsedOptimized);
assertLe(gasUsedOptimized, gasUsedOriginal);
}

Recommended Mitigation

- string memory status = order.isActive
- ? (block.timestamp < order.deadlineTimestamp ? "Active" : "Expired (Active but past deadline)")
- : "Inactive (Filled/Cancelled)";
+string memory status;
if (order.isActive && block.timestamp >= order.deadlineTimestamp) {
status = "Expired (Awaiting Cancellation)";
} else if (!order.isActive) {
status = "Inactive (Filled/Cancelled)";
} else {
status = "Active";
}
Updates

Lead Judging Commences

yeahchibyke Lead Judge about 1 month ago
Submission Judgement Published
Invalidated
Reason: Non-acceptable severity

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.