| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211 |
- ---
- title: Set Custom Gas Limits
- description: How to set custom gas limits for Entropy callbacks
- ---
- import { Step, Steps } from "fumadocs-ui/components/steps";
- import { DynamicCodeBlock } from "fumadocs-ui/components/dynamic-codeblock";
- Custom gas limits are useful when your callback function requires more gas than the [default provider limit]TODO(../contract-addresses), 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](./generate-random-numbers-evm.mdx) guide. This guide builds upon that foundation and assumes you have:
- - Installed the Pyth Entropy Solidity SDK
- - Set up your contract with the `IEntropyConsumer` interface
- - Implemented the basic `entropyCallback` function
- ## When to Use Custom Gas Limits
- You might need custom gas limits in these scenarios:
- - **Complex callback logic**: Your `entropyCallback` function 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:
- <DynamicCodeBlock lang="solidity"
- code={`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:
- <DynamicCodeBlock lang="solidity"
- code={`// Get fee for custom gas limit
- uint256 fee = entropy.getFeeV2(customGasLimit);
- // NOT: uint256 fee = entropy.getFeeV2(); // This uses default gas limit
- `} />
- ### 3. Complete Example
- Here's a complete example showing how to implement custom gas limits:
- <DynamicCodeBlock lang="solidity"
- code={`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:
- <Callout variant="info" header="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).
- </Callout>
- ### 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:
- <DynamicCodeBlock
- lang="solidity"
- code={`// 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:
- <DynamicCodeBlock
- lang="solidity"
- code={`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:
- <Callout variant="warning">
- 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.
- </Callout>
- ### 4. Consider Fee Implications
- Higher gas limits result in higher fees. Balance your gas needs with cost considerations:
- <DynamicCodeBlock
- lang="solidity"
- code={`// 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:
- 1. **Callback not executing**: Your gas limit might be too low
- 2. **High fees**: Consider optimizing your callback or using a lower gas limit
- 3. **Reverts**: Check that your gas limit doesn't exceed the maximum allowed
- For more debugging help, see the [Debug Callback Failures](/entropy/debug-callback-failures) guide.
- ## Additional Resources
- - [Generate Random Numbers in EVM Contracts](/entropy/generate-random-numbers/evm) - Basic setup guide
- - [Best Practices](/entropy/best-practices) - General optimization tips
- - [Current Fees](/entropy/current-fees) - Fee information for different chains
- - [Contract Addresses](/entropy/contract-addresses) - Entropy contract deployments
|