President Elector

First Flight #24
Beginner FriendlyFoundry
100 EXP
View results
Submission Details
Severity: low
Invalid

Calldata should be used as data location instead of memory when passing dynamic array as function argument, leading to increased gas savings.

Description

Calldata is useful for passing large amounts of data to a function without having to copy the data into memory, which can be expensive in terms of gas usage. By using calldata, you can avoid the overhead of copying data into memory and reduce the amount of gas needed to execute the function.

Impact

Reduce the computation cost of the function resulting in less gas being used.

Proof of Concept

Add below snippet to RankedChoiceTest.t.sol and run the test case before and after updating the RankedChoice::rankCandidates() function like shown.

function testRankCandidatesGasUsed() public {
for (uint8 i = 0; i < 10; i++) {
orderedCandidates.push(candidates[i]);
}
vm.prank(voters[0]);
uint256 initialGas = gasleft();
rankedChoice.rankCandidates(orderedCandidates);
uint256 finalGas = gasleft();
console.log("Gas used:", initialGas - finalGas);
}
- function rankCandidates(address[] memory orderedCandidates) external {
+ function rankCandidates(address[] calldata orderedCandidates) external {
forge test --mt testRankCandidatesGasUsed -vvv
# Gas used with memory: 476329
# Gas used with calldata: 474804

Recommended Mitigation

Replace memory data location with calldata in functions that accept array inputs.

- function rankCandidates(address[] memory orderedCandidates) external {
+ function rankCandidates(address[] calldata orderedCandidates) external {
function rankCandidatesBySig(
- address[] memory orderedCandidates,
+ address[] calldata orderedCandidates,

Tools used

  • Foundry

Updates

Lead Judging Commences

inallhonesty Lead Judge about 1 year ago
Submission Judgement Published
Invalidated
Reason: Non-acceptable severity

Support

FAQs

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