Set Custom Gas Limits
How to set custom gas limits for Entropy callbacks
Custom gas limits are useful when your callback function requires more gas than the default provider limit, or when you want to optimize gas costs for simpler callbacks.
Prerequisites
Before following this guide, you should first complete the basic setup from the Generate Random Numbers in EVM Contracts guide. This guide builds upon that foundation and assumes you have:
- Installed the Pyth Entropy Solidity SDK
- Set up your contract with the
IEntropyConsumerinterface - Implemented the basic
entropyCallbackfunction
When to Use Custom Gas Limits
You might need custom gas limits in these scenarios:
- Complex callback logic: Your
entropyCallbackfunction performs computationally expensive operations - Gas optimization: You want to use less gas for simple callbacks to reduce fees
- Multiple operations: Your callback needs to perform multiple state changes or external calls
- Integration requirements: Your application has specific gas requirements for reliability
Implementation
1. Use requestV2 with Gas Limit Parameter
Instead of the basic requestV2() method, use the variant that accepts a gasLimit parameter:
function requestRandomNumberWithCustomGas(
uint32 customGasLimit
) external payable {
// Calculate the fee for the custom gas limit
uint256 fee = entropy.getFeeV2(customGasLimit);
// Request random number with custom gas limit
uint64 sequenceNumber = entropy.requestV2{ value: fee }(customGasLimit);
// Store the sequence number for tracking if needed
}2. Calculate Fees with Custom Gas Limit
When using custom gas limits, you must use the getFeeV2 variant that accepts a gasLimit parameter:
// Get fee for custom gas limit
uint256 fee = entropy.getFeeV2(customGasLimit);
// NOT: uint256 fee = entropy.getFeeV2(); // This uses default gas limit3. Complete Example
Here's a complete example showing how to implement custom gas limits:
pragma solidity ^0.8.0;
import { IEntropyConsumer } from "@pythnetwork/entropy-sdk-solidity/IEntropyConsumer.sol";
import { IEntropyV2 } from "@pythnetwork/entropy-sdk-solidity/IEntropyV2.sol";
contract CustomGasLimitExample is IEntropyConsumer {
IEntropyV2 public entropy;
mapping(uint64 => bool) public processedRequests;
constructor(address entropyAddress) {
entropy = IEntropyV2(entropyAddress);
}
// Request with custom gas limit for complex callback
function requestComplexRandomNumber() external payable {
uint32 customGasLimit = 200000; // Higher limit for complex operations
uint256 fee = entropy.getFeeV2(customGasLimit);
require(msg.value >= fee, "Insufficient fee");
uint64 sequenceNumber = entropy.requestV2{ value: fee }(customGasLimit);
// Store sequence number if needed for tracking
}
// Request with lower gas limit for simple callback
function requestSimpleRandomNumber() external payable {
uint32 customGasLimit = 50000; // Lower limit for simple operations
uint256 fee = entropy.getFeeV2(customGasLimit);
require(msg.value >= fee, "Insufficient fee");
uint64 sequenceNumber = entropy.requestV2{ value: fee }(customGasLimit);
}
// Complex callback that requires more gas
function entropyCallback(
uint64 sequenceNumber,
address provider,
bytes32 randomNumber
) internal override {
// Prevent duplicate processing
require(!processedRequests[sequenceNumber], "Already processed");
processedRequests[sequenceNumber] = true;
// Complex operations that require more gas
for (uint i = 0; i < 10; i++) {
// Simulate complex state changes
// This would require more gas than the default limit
}
// Use the random number for your application logic
uint256 randomValue = uint256(randomNumber);
// Your application logic here...
}
function getEntropy() internal view override returns (address) {
return address(entropy);
}
}Gas Limit Constraints
When setting custom gas limits, be aware of these constraints:
Gas Limit Rules
Gas limits are automatically rounded up to the nearest multiple of 10,000.
Example: 19,000 becomes 20,000 25,500 becomes 30,000. The minimum gas limit is
the provider's configured default limit. The maximum gas limit is 655,350,000
(uint16.max * 10,000).
Recommended Gas Limits
- Simple callbacks: 50,000 - 100,000 gas
- Moderate complexity: 100,000 - 200,000 gas
- Complex operations: 200,000 - 500,000 gas
- Very complex logic: 500,000+ gas (use with caution)
Best Practices
1. Estimate Gas Usage
Test your callback function to determine the actual gas usage:
// In your tests, measure gas usage
uint256 gasStart = gasleft();
// Your callback logic here
uint256 gasUsed = gasStart - gasleft();
console.log("Gas used:", gasUsed);2. Add Safety Buffer
Always add a safety buffer to your estimated gas usage:
uint32 estimatedGas = 150000;
uint32 safetyBuffer = 20000;
uint32 customGasLimit = estimatedGas + safetyBuffer;3. Handle Gas Limit Errors
Be prepared to handle cases where your gas limit is insufficient:
If your callback runs out of gas, the entropy provider will not be able to complete the callback. Always test your gas limits thoroughly and include adequate safety margins.
4. Consider Fee Implications
Higher gas limits result in higher fees. Balance your gas needs with cost considerations:
// Compare fees for different gas limits
uint256 defaultFee = entropy.getFeeV2();
uint256 customFee = entropy.getFeeV2(customGasLimit);
uint256 additionalCost = customFee - defaultFee;Troubleshooting
If you're experiencing issues with custom gas limits:
- Callback not executing: Your gas limit might be too low
- High fees: Consider optimizing your callback or using a lower gas limit
- Reverts: Check that your gas limit doesn't exceed the maximum allowed
For more debugging help, see the Debug Callback Failures guide.
Additional Resources
- Generate Random Numbers in EVM Contracts - Basic setup guide
- Transform Entropy Results - General optimization tips
- Contract Addresses and Fee Details - Entropy contract deployments and fee details