set-custom-gas-limits.mdx 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. ---
  2. title: Set Custom Gas Limits
  3. description: How to set custom gas limits for Entropy callbacks
  4. ---
  5. import { Step, Steps } from "fumadocs-ui/components/steps";
  6. import { DynamicCodeBlock } from "fumadocs-ui/components/dynamic-codeblock";
  7. 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.
  8. ## Prerequisites
  9. 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:
  10. - Installed the Pyth Entropy Solidity SDK
  11. - Set up your contract with the `IEntropyConsumer` interface
  12. - Implemented the basic `entropyCallback` function
  13. ## When to Use Custom Gas Limits
  14. You might need custom gas limits in these scenarios:
  15. - **Complex callback logic**: Your `entropyCallback` function performs computationally expensive operations
  16. - **Gas optimization**: You want to use less gas for simple callbacks to reduce fees
  17. - **Multiple operations**: Your callback needs to perform multiple state changes or external calls
  18. - **Integration requirements**: Your application has specific gas requirements for reliability
  19. ## Implementation
  20. ### 1. Use requestV2 with Gas Limit Parameter
  21. Instead of the basic `requestV2()` method, use the variant that accepts a `gasLimit` parameter:
  22. <DynamicCodeBlock lang="solidity"
  23. code={`function requestRandomNumberWithCustomGas(
  24. uint32 customGasLimit
  25. ) external payable {
  26. // Calculate the fee for the custom gas limit
  27. uint256 fee = entropy.getFeeV2(customGasLimit);
  28. // Request random number with custom gas limit
  29. uint64 sequenceNumber = entropy.requestV2{ value: fee }(customGasLimit);
  30. // Store the sequence number for tracking if needed
  31. }
  32. `} />
  33. ### 2. Calculate Fees with Custom Gas Limit
  34. When using custom gas limits, you must use the `getFeeV2` variant that accepts a `gasLimit` parameter:
  35. <DynamicCodeBlock lang="solidity"
  36. code={`// Get fee for custom gas limit
  37. uint256 fee = entropy.getFeeV2(customGasLimit);
  38. // NOT: uint256 fee = entropy.getFeeV2(); // This uses default gas limit
  39. `} />
  40. ### 3. Complete Example
  41. Here's a complete example showing how to implement custom gas limits:
  42. <DynamicCodeBlock lang="solidity"
  43. code={`pragma solidity ^0.8.0;
  44. import { IEntropyConsumer } from "@pythnetwork/entropy-sdk-solidity/IEntropyConsumer.sol";
  45. import { IEntropyV2 } from "@pythnetwork/entropy-sdk-solidity/IEntropyV2.sol";
  46. contract CustomGasLimitExample is IEntropyConsumer {
  47. IEntropyV2 public entropy;
  48. mapping(uint64 => bool) public processedRequests;
  49. constructor(address entropyAddress) {
  50. entropy = IEntropyV2(entropyAddress);
  51. }
  52. // Request with custom gas limit for complex callback
  53. function requestComplexRandomNumber() external payable {
  54. uint32 customGasLimit = 200000; // Higher limit for complex operations
  55. uint256 fee = entropy.getFeeV2(customGasLimit);
  56. require(msg.value >= fee, "Insufficient fee");
  57. uint64 sequenceNumber = entropy.requestV2{ value: fee }(customGasLimit);
  58. // Store sequence number if needed for tracking
  59. }
  60. // Request with lower gas limit for simple callback
  61. function requestSimpleRandomNumber() external payable {
  62. uint32 customGasLimit = 50000; // Lower limit for simple operations
  63. uint256 fee = entropy.getFeeV2(customGasLimit);
  64. require(msg.value >= fee, "Insufficient fee");
  65. uint64 sequenceNumber = entropy.requestV2{ value: fee }(customGasLimit);
  66. }
  67. // Complex callback that requires more gas
  68. function entropyCallback(
  69. uint64 sequenceNumber,
  70. address provider,
  71. bytes32 randomNumber
  72. ) internal override {
  73. // Prevent duplicate processing
  74. require(!processedRequests[sequenceNumber], "Already processed");
  75. processedRequests[sequenceNumber] = true;
  76. // Complex operations that require more gas
  77. for (uint i = 0; i < 10; i++) {
  78. // Simulate complex state changes
  79. // This would require more gas than the default limit
  80. }
  81. // Use the random number for your application logic
  82. uint256 randomValue = uint256(randomNumber);
  83. // Your application logic here...
  84. }
  85. function getEntropy() internal view override returns (address) {
  86. return address(entropy);
  87. }
  88. }
  89. `} />
  90. ## Gas Limit Constraints
  91. When setting custom gas limits, be aware of these constraints:
  92. <Callout variant="info" header="Gas Limit Rules">
  93. Gas limits are automatically rounded up to the nearest multiple of **10,000**.
  94. Example: 19,000 becomes 20,000 25,500 becomes 30,000. The minimum gas limit is
  95. the provider's configured default limit. The maximum gas limit is 655,350,000
  96. (`uint16.max` \* 10,000).
  97. </Callout>
  98. ### Recommended Gas Limits
  99. - **Simple callbacks**: 50,000 - 100,000 gas
  100. - **Moderate complexity**: 100,000 - 200,000 gas
  101. - **Complex operations**: 200,000 - 500,000 gas
  102. - **Very complex logic**: 500,000+ gas (use with caution)
  103. ## Best Practices
  104. ### 1. Estimate Gas Usage
  105. Test your callback function to determine the actual gas usage:
  106. <DynamicCodeBlock
  107. lang="solidity"
  108. code={`// In your tests, measure gas usage
  109. uint256 gasStart = gasleft();
  110. // Your callback logic here
  111. uint256 gasUsed = gasStart - gasleft();
  112. console.log("Gas used:", gasUsed);
  113. `}
  114. />
  115. ### 2. Add Safety Buffer
  116. Always add a safety buffer to your estimated gas usage:
  117. <DynamicCodeBlock
  118. lang="solidity"
  119. code={`uint32 estimatedGas = 150000;
  120. uint32 safetyBuffer = 20000;
  121. uint32 customGasLimit = estimatedGas + safetyBuffer;
  122. `}
  123. />
  124. ### 3. Handle Gas Limit Errors
  125. Be prepared to handle cases where your gas limit is insufficient:
  126. <Callout variant="warning">
  127. If your callback **runs out of gas**, the entropy provider will **not** be
  128. able to complete the callback. Always test your gas limits thoroughly and
  129. include adequate safety margins.
  130. </Callout>
  131. ### 4. Consider Fee Implications
  132. Higher gas limits result in higher fees. Balance your gas needs with cost considerations:
  133. <DynamicCodeBlock
  134. lang="solidity"
  135. code={`// Compare fees for different gas limits
  136. uint256 defaultFee = entropy.getFeeV2();
  137. uint256 customFee = entropy.getFeeV2(customGasLimit);
  138. uint256 additionalCost = customFee - defaultFee;
  139. `}
  140. />
  141. ## Troubleshooting
  142. If you're experiencing issues with custom gas limits:
  143. 1. **Callback not executing**: Your gas limit might be too low
  144. 2. **High fees**: Consider optimizing your callback or using a lower gas limit
  145. 3. **Reverts**: Check that your gas limit doesn't exceed the maximum allowed
  146. For more debugging help, see the [Debug Callback Failures](/entropy/debug-callback-failures) guide.
  147. ## Additional Resources
  148. - [Generate Random Numbers in EVM Contracts](/entropy/generate-random-numbers/evm) - Basic setup guide
  149. - [Best Practices](/entropy/best-practices) - General optimization tips
  150. - [Current Fees](/entropy/current-fees) - Fee information for different chains
  151. - [Contract Addresses](/entropy/contract-addresses) - Entropy contract deployments