Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimizing Gas Usage in Solidity: Improved Error Handling and Event Emission #25

Open
pradyumna14 opened this issue Oct 17, 2024 · 2 comments
Assignees
Labels

Comments

@pradyumna14
Copy link
Contributor

File: CarPooling.sol

Focusing on key improvements to enhance the gas efficiency and clarity of the smart contract:

1.⁠ ⁠Using require Instead of if for Reverts:

Instead of using if statements followed by manual revert calls to handle errors, we switch to using require directly. The require statement is a standard Solidity way of validating conditions before proceeding with function execution. It automatically reverts with a specified message when the condition fails.

This approach saves gas as require is optimized for validation checks in Solidity, reducing the overhead associated with custom if and revert logic.

Example:

require(msg.value >= rides[rideId].rideFare, "Money sent not equal to ride Fare");

This replaces:

if (msg.value < rides[rideId].rideFare)

if (msg.value < rides[rideId].rideFare) 
    revert ERROR_CarPooling({
        message: "Money sent not equal to ride Fare"
    });
  1. Conditionally Emitting Events:

To prevent emitting events unnecessarily, we introduce conditional checks before calling emit statements. Specifically, we verify if a state change has actually occurred before broadcasting it as an event.

This reduces gas consumption by avoiding the creation of event logs when no change has taken place, as events consume a considerable amount of gas.

Example:

if (completionStatus[rideId] != newStatus) {
    completionStatus[rideId] = newStatus;
    emit StatusUpdate(rideId, newStatus);
}

Here, we only emit the StatusUpdate event when the completion status of a ride has changed, optimizing the event handling process.

These Enhancements would definitely optimize the contract and will save us some gas prize

@StephCurry07
Copy link
Owner

Good work...you can raise a PR

@pradyumna14
Copy link
Contributor Author

@StephCurry07

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants