Dynamic Fees
Objective
Dynamic fees allow app developers to monetize usage of their app without requiring users to pay an explicit fee. Instead, users pay a multiple of the normal gas cost, and the excess is automatically transferred to the app developer.
Solution
On Sonic, developers can enroll in the Fee Monetization program, which lets builders earn 90% of the network fees their apps generate. To benefit, developers simply need to increase the gas consumption of their contracts in a controlled manner.
The following examples outline best practices for safely increasing contract gas usage. Use the abstract contract below as a parent for your own contract:
abstract contract DynamicGasCharging {
uint256 private gasScalingFactor;
/**
* @dev Consume the given amount of gas.
* In contract code this function can be flexibly used at any place to add extra gas consumption
*/
function _consumeGas(uint256 gas) view internal {
uint256 initialGas = gasleft();
uint256 wantedGas = initialGas - gas;
while (gasleft() > wantedGas) {
// do nothing
}
}
// Modifier to increase the gas costs of a function by a configurable multiplier
modifier scaleGasCosts() {
uint256 initialGas = gasleft();
_;
uint256 gasUsed = initialGas - gasleft();
_consumeGas(gasUsed * (gasScalingFactor-1));
}
// Set the scaling factor (to be called by implementations)
function _setGasScalingFactor(uint256 newGasScalingFactor) internal {
gasScalingFactor = newGasScalingFactor;
}
}
Once integrated, the following changes must be applied to your contract:
Inherit from the
DynamicGasCharging
contract.Add the
scaleGasCosts
modifier to each function where dynamic gas charging should apply.Set the
gasScalingFactor
—either in the contract initializer or via anonlyOwner
function.
Example:
contract DynamicGasExample is DynamicGasCharging, Ownable {
function myMethod() external scaleGasCosts {
counter++; // code of your method
}
function setGasScalingFactor(uint256 newGasScalingFactor) external onlyOwner {
_setGasScalingFactor(newGasScalingFactor);
}
}
Last updated