Skip to content

feat(entropy): add Set Custom Gas Limits guide #765

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

Merged
merged 2 commits into from
Jul 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion pages/entropy/generate-random-numbers/_meta.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{
"evm": "in EVM contracts"
"evm": "in EVM contracts",
"set-custom-gas-limits": "Set Custom Gas Limits"
}
201 changes: 201 additions & 0 deletions pages/entropy/generate-random-numbers/set-custom-gas-limits.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
import { Tab, Tabs, Callout } from "nextra/components";

# Set Custom Gas Limits

This guide shows how to set custom gas limits when requesting random numbers from Pyth Entropy. 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](/entropy/generate-random-numbers/evm) 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:

```solidity copy
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:

```solidity copy
// 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:

```solidity copy
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 type="info" emoji="ℹ️">
**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:

```solidity copy
// 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:

```solidity copy
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 type="warning" emoji="⚠️">
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:

```solidity copy
// 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
Loading