diff --git a/apps/developer-hub/content/docs/entropy/best-practices.mdx b/apps/developer-hub/content/docs/entropy/best-practices.mdx new file mode 100644 index 0000000000..1daf41e6c4 --- /dev/null +++ b/apps/developer-hub/content/docs/entropy/best-practices.mdx @@ -0,0 +1,57 @@ +--- +title: Best Practices +description: Best practices for using Pyth Entropy in your applications +--- + +# Best Practices + +## Limit gas usage on the callback + +Keeping the callback function simple is crucial because the entropy providers limit gas usage. +This ensures gas usage is predictable and consistent, avoiding potential issues with the callback. + +For example, if you want to use entropy to generate a random number for each player in a round of game, +you need to make sure that the callback function works for the maximum number of players that can be in each round. +Otherwise, the callbacks will work for some rounds with fewer players, but will fail for rounds with more players. + +Multiple solutions are possible to address this problem. You can store the random number received from the callback and +either ask users to submit more transactions after the callback to continue the flow or run a background crank service +to submit the necessary transactions. + +The gas limit for each chain is listed on the [contract addresses](contract-addresses) page. + +## Handling callback failures + +While the default entropy provider is highly reliable, in rare cases a callback might not be received. This typically happens when there's an issue with your contract's callback implementation rather than with the provider itself. The most common causes are: + +1. The callback function is using more gas than the allowed limit +2. The callback function contains logic that throws an error + +If you're not receiving a callback, you can manually invoke it to identify the specific issue. This allows you to: + +- See if the transaction fails and why +- Check the gas usage against the chain's callback gas limit +- Debug your callback implementation + +For detailed instructions on how to manually invoke and debug callbacks, refer to the [Debug Callback Failures](debug-callback-failures) guide. + +## Generating random values within a specific range + +You can map the random number provided by Entropy into a smaller range using the solidity [modulo operator](https://docs.soliditylang.org/en/latest/types.html#modulo). +Here is a simple example of how to map a random number provided by Entropy into a range between `minRange` and `maxRange` (inclusive). + +```solidity +// Maps a random number into a range between minRange and maxRange (inclusive) +function mapRandomNumber( + bytes32 randomNumber, + int256 minRange, + int256 maxRange +) internal pure returns (int256) { + require(minRange <= maxRange, "Invalid range"); + + uint256 range = uint256(maxRange - minRange + 1); + uint256 randomUint = uint256(randomNumber); + + return minRange + int256(randomUint % range); +} +``` diff --git a/apps/developer-hub/content/docs/entropy/contract-addresses.mdx b/apps/developer-hub/content/docs/entropy/contract-addresses.mdx new file mode 100644 index 0000000000..4132bf935e --- /dev/null +++ b/apps/developer-hub/content/docs/entropy/contract-addresses.mdx @@ -0,0 +1,47 @@ +--- +title: Contract Addresses +description: Entropy contract addresses on different networks +--- + +# Entropy Contract Addresses on EVM + +## Mainnets + +The Entropy contract is deployed on the following mainnet chains: + +| Network | Contract Address | Gas Limit | Provider | +| --------- | -------------------------------------------- | --------- | -------------------------------------------- | +| Ethereum | `0x98046Bd286715D3B0BC227Dd7a956b83D8978603` | 100,000 | `0x52DeaA1c84233F7bb8C8A45baeDE41091c616506` | +| Arbitrum | `0x23f0e8FAeE7bbb405E7A7C3d60138FCfd43d7509` | 100,000 | `0x52DeaA1c84233F7bb8C8A45baeDE41091c616506` | +| Avalanche | `0x36825bf3Fbdf5a29E2d5148bfe7Dcf7B5639e320` | 100,000 | `0x52DeaA1c84233F7bb8C8A45baeDE41091c616506` | +| Base | `0x98046Bd286715D3B0BC227Dd7a956b83D8978603` | 100,000 | `0x52DeaA1c84233F7bb8C8A45baeDE41091c616506` | +| BNB Chain | `0x98046Bd286715D3B0BC227Dd7a956b83D8978603` | 100,000 | `0x52DeaA1c84233F7bb8C8A45baeDE41091c616506` | +| Optimism | `0x98046Bd286715D3B0BC227Dd7a956b83D8978603` | 100,000 | `0x52DeaA1c84233F7bb8C8A45baeDE41091c616506` | +| Polygon | `0x98046Bd286715D3B0BC227Dd7a956b83D8978603` | 100,000 | `0x52DeaA1c84233F7bb8C8A45baeDE41091c616506` | + +**The default provider for above mainnet chains is `0x52DeaA1c84233F7bb8C8A45baeDE41091c616506`.** + +The default provider on mainnet has a reveal delay to avoid changes on the outcome of the Entropy request because of block reorgs. +The reveal delay shows how many blocks should be produced after the block including the request transaction in order to reveal and submit a callback transaction. + +The default provider fulfills the request by sending a transaction with a gas limit as mentioned in above table. Entropy callbacks the consumer as part of this transaction. + +## Testnets + +The Entropy contract is deployed on the following testnet chains: + +| Network | Contract Address | Gas Limit | Provider | +| ---------------- | -------------------------------------------- | --------- | -------------------------------------------- | +| Ethereum Sepolia | `0x41c9e39574F40Ad34c79f1C99B66A45eFB830d4c` | 100,000 | `0x6CC14824Ea2918f5De5C2f75A9Da968ad4BD6344` | +| Arbitrum Sepolia | `0x36825bf3Fbdf5a29E2d5148bfe7Dcf7B5639e320` | 100,000 | `0x6CC14824Ea2918f5De5C2f75A9Da968ad4BD6344` | +| Avalanche Fuji | `0x36825bf3Fbdf5a29E2d5148bfe7Dcf7B5639e320` | 100,000 | `0x6CC14824Ea2918f5De5C2f75A9Da968ad4BD6344` | +| Base Sepolia | `0x41c9e39574F40Ad34c79f1C99B66A45eFB830d4c` | 100,000 | `0x6CC14824Ea2918f5De5C2f75A9Da968ad4BD6344` | +| BNB Testnet | `0x41c9e39574F40Ad34c79f1C99B66A45eFB830d4c` | 100,000 | `0x6CC14824Ea2918f5De5C2f75A9Da968ad4BD6344` | +| Optimism Sepolia | `0x41c9e39574F40Ad34c79f1C99B66A45eFB830d4c` | 100,000 | `0x6CC14824Ea2918f5De5C2f75A9Da968ad4BD6344` | +| Polygon Amoy | `0x41c9e39574F40Ad34c79f1C99B66A45eFB830d4c` | 100,000 | `0x6CC14824Ea2918f5De5C2f75A9Da968ad4BD6344` | + +**The default provider for above testnet chains is `0x6CC14824Ea2918f5De5C2f75A9Da968ad4BD6344`.** + +The default provider on testnet has reveal delays identical to the corresponding mainnet chains to ensure consistent environment. + +The default provider fulfills the request by sending a transaction with a gas limit as mentioned in above table. Entropy callbacks the consumer as part of this transaction. diff --git a/apps/developer-hub/content/docs/entropy/create-your-first-entropy-app.mdx b/apps/developer-hub/content/docs/entropy/create-your-first-entropy-app.mdx new file mode 100644 index 0000000000..c69e437bc0 --- /dev/null +++ b/apps/developer-hub/content/docs/entropy/create-your-first-entropy-app.mdx @@ -0,0 +1,108 @@ +--- +title: Create your first Entropy app on EVM +description: Build a coin flip application using Pyth Entropy +--- + +# Create your first Entropy app on EVM + +In this tutorial we will implement and deploy a coin flip contract which will use entropy to generate a random output. + +## Preliminaries + +Before we start, please make sure you have the following tools installed: + +- [Foundry](https://book.getfoundry.sh/getting-started/installation) +- [Node.js](https://nodejs.org/en/download) (version >= v18.0.0) + +## Getting Started + +Create a directory named `coin-flip` and initialize a new Foundry project: + +```bash +mkdir coin-flip +cd coin-flip +forge init contracts +``` + +Install the Pyth Entropy SDK: + +```bash +cd contracts +npm init -y +npm install @pythnetwork/entropy-sdk-solidity +``` + +Add a `remappings.txt` file to the `contracts` directory: + +```text +@pythnetwork/entropy-sdk-solidity/=node_modules/@pythnetwork/entropy-sdk-solidity +``` + +## Smart Contract Implementation + +Replace the content of `contracts/src/Counter.sol` with the following coin flip contract: + +```solidity +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +import "@pythnetwork/entropy-sdk-solidity/IEntropy.sol"; +import "@pythnetwork/entropy-sdk-solidity/IEntropyConsumer.sol"; + +contract CoinFlip is IEntropyConsumer { + IEntropy entropy; + + struct FlipRequest { + address player; + bool isHeads; + } + + mapping(uint64 => FlipRequest) public requests; + mapping(address => uint256) public results; // 0 = not played, 1 = won, 2 = lost + + constructor(address entropyAddress) { + entropy = IEntropy(entropyAddress); + } + + function flipCoin(bool isHeads) external payable { + uint256 fee = entropy.getFee(entropy.getDefaultProvider()); + require(msg.value >= fee, "Insufficient fee"); + + bytes32 userRandomNumber = keccak256(abi.encode(block.timestamp, msg.sender)); + uint64 sequenceNumber = entropy.requestWithCallback{value: fee}( + entropy.getDefaultProvider(), + userRandomNumber + ); + + requests[sequenceNumber] = FlipRequest(msg.sender, isHeads); + } + + function entropyCallback( + uint64 sequenceNumber, + address, + bytes32 randomNumber + ) internal override { + FlipRequest memory request = requests[sequenceNumber]; + bool coinIsHeads = uint256(randomNumber) % 2 == 0; + + if (coinIsHeads == request.isHeads) { + results[request.player] = 1; // won + } else { + results[request.player] = 2; // lost + } + } +} +``` + +## Deployment + +Create a deployment script and deploy to Optimism Sepolia testnet. Check the [contract addresses](contract-addresses) page for the Entropy contract address on your chosen network. + +## Next Steps + +- Add more complex game logic +- Implement proper error handling +- Add events for better tracking +- Consider gas optimization techniques + +For a complete example with deployment scripts and frontend integration, see the [Coin Flip example](https://github.com/pyth-network/pyth-examples/tree/main/entropy/coin_flip) in the Pyth examples repository. diff --git a/apps/developer-hub/content/docs/entropy/current-fees.mdx b/apps/developer-hub/content/docs/entropy/current-fees.mdx new file mode 100644 index 0000000000..57688fbd50 --- /dev/null +++ b/apps/developer-hub/content/docs/entropy/current-fees.mdx @@ -0,0 +1,39 @@ +--- +title: Current Fees +description: Current fees for using Pyth Entropy +--- + +# Current Fees + +The following tables shows the total fees payable when using the **default provider**. +Note that the fees shown below will vary over time with prevailing gas prices on each chain. + +## Mainnet + +> âš ī¸ **Warning** +> The fees for mainnet are dynamically set. Always use the on-chain method `entropy.getFeeV2()` to get the current fee. + +| Network | Fee (Native Token) | +| --------- | ------------------ | +| Ethereum | Dynamic | +| Arbitrum | Dynamic | +| Avalanche | Dynamic | +| Base | Dynamic | +| BNB Chain | Dynamic | +| Optimism | Dynamic | +| Polygon | Dynamic | + +## Testnet + +> â„šī¸ **Note** +> The fees for testnets kept deliberately low and different from the mainnet fees. + +| Network | Fee (Native Token) | +| ---------------- | ------------------ | +| Ethereum Sepolia | 0.0001 ETH | +| Arbitrum Sepolia | 0.0001 ETH | +| Avalanche Fuji | 0.01 AVAX | +| Base Sepolia | 0.0001 ETH | +| BNB Testnet | 0.001 BNB | +| Optimism Sepolia | 0.0001 ETH | +| Polygon Amoy | 0.01 MATIC | diff --git a/apps/developer-hub/content/docs/entropy/debug-callback-failures.mdx b/apps/developer-hub/content/docs/entropy/debug-callback-failures.mdx new file mode 100644 index 0000000000..c403d1ab31 --- /dev/null +++ b/apps/developer-hub/content/docs/entropy/debug-callback-failures.mdx @@ -0,0 +1,75 @@ +--- +title: Debug Callback Failures +description: How to identify and resolve issues with Entropy callbacks +--- + +# Debug Callback Failures + +> 🔍 **Quick Debug Tool** +> Use the [Entropy Explorer](https://entropy-debugger.pyth.network/) to quickly diagnose and resolve callback issues. + +This guide explains how to identify and resolve issues with the Entropy callback. +The intended audience for this guide is developers who have made an Entropy random number request, but their application hasn't received a callback. + +## Dependencies + +This guide uses [Foundry](https://book.getfoundry.sh/getting-started/installation) to submit transactions to the blockchain. +Please install Foundry before continuing. + +## Run the Callback + +Developers can run the Entropy callback themselves to see the reason for the failure. +To run the callback, invoke the `revealWithCallback` function on the Entropy contract on your blockchain. +The function has the following signature: + +```solidity +function revealWithCallback( + address provider, + uint64 sequenceNumber, + bytes32 userRandomNumber, + bytes32 providerRevelation +) +``` + +This call requires the chain ID, contract address, and four arguments. +The chain ID and contract address can be retrieved from [Contract Addresses](contract-addresses). +Export these values as environment variables for later use: + +```bash +export CHAIN_ID=blast +export ENTROPY_ADDRESS=0x5744Cbf430D99456a0A8771208b674F27f8EF0Fb +``` + +Three of the arguments can be retrieved from the request transaction's event logs. +Look at the event logs of the request transaction in a block explorer. +You should see a `RequestedWithCallback` event emitted from the Entropy contract. + +Copy the following values from the event into environment variables: + +```bash +export PROVIDER=0x52DeaA1c84233F7bb8C8A45baeDE41091c616506 +export SEQUENCE_NUMBER=12345 +export USER_RANDOM_NUMBER=0x1234... +``` + +The fourth argument (provider revelation) must be retrieved from the provider's API. +This value becomes available after the reveal delay has passed. + +## Common Issues + +### Gas Limit Exceeded + +If your callback function uses too much gas, the transaction will fail. Check the gas limit for your chain on the [contract addresses](contract-addresses) page and ensure your callback function uses less gas. + +### Callback Function Errors + +Your callback function might contain logic that throws an error. Review your callback implementation for: + +- Division by zero +- Array out of bounds access +- Failed require statements +- Insufficient contract balance for operations + +### Transaction Timing + +Make sure you're attempting the callback after the reveal delay has passed. The reveal delay varies by network and helps prevent MEV attacks. diff --git a/apps/developer-hub/content/docs/entropy/error-codes.mdx b/apps/developer-hub/content/docs/entropy/error-codes.mdx new file mode 100644 index 0000000000..932d583e7e --- /dev/null +++ b/apps/developer-hub/content/docs/entropy/error-codes.mdx @@ -0,0 +1,23 @@ +--- +title: Error Codes +description: Error codes and their meanings for Pyth Entropy +--- + +# Error Codes + +The following table contains the errors used in the Pyth Network's Entropy [EVM contracts](https://github.com/pyth-network/pyth-crosschain/blob/d290f4ec47a73636cf77711f5f68c3455bb8a8ca/target_chains/ethereum/contracts/contracts/entropy/Entropy.sol). +This information is derived from [EntropyErrors.sol](https://github.com/pyth-network/pyth-crosschain/blob/d290f4ec47a73636cf77711f5f68c3455bb8a8ca/target_chains/ethereum/entropy_sdk/solidity/EntropyErrors.sol) +in the Pyth EntropySDK and can be used to decode error codes programmatically. + +| Error Codes | Error | Error Description | +| ----------- | --------------------------- | --------------------------------------------------------- | +| 0xd82dd966 | AssertionFailure() | Contract invariant failed. | +| 0xda041bdf | ProviderAlreadyRegistered() | Provider already registered. | +| 0xdf51c431 | NoSuchProvider() | Requested Provider does not exist. | +| 0xc4237352 | NoSuchRequest() | Request does not exist or the request has been fulfilled. | +| 0x3e515085 | OutOfRandomness() | Provider is out of committed random numbers. | +| 0x025dbdd4 | InsufficientFee() | Request fee is insufficient. | +| 0xb8be1a8d | IncorrectRevelation() | Revelation does not match commitment. | +| 0x2763cc69 | RequestAlreadyRevealed() | Request has already been revealed. | +| 0xdb8b95b8 | RevealTooEarly() | Reveal delay has not passed. | +| 0x8f4eb604 | RandomnessNotRevealed() | Random number has not been revealed. | diff --git a/apps/developer-hub/content/docs/entropy/examples.mdx b/apps/developer-hub/content/docs/entropy/examples.mdx new file mode 100644 index 0000000000..86421c9577 --- /dev/null +++ b/apps/developer-hub/content/docs/entropy/examples.mdx @@ -0,0 +1,13 @@ +--- +title: Example Applications +description: Example applications using Pyth Entropy +--- + +# Example Applications + +The [Coin Flip](https://github.com/pyth-network/pyth-examples/tree/main/entropy/coin_flip) example demonstrates how to build a smart contract that +interacts with Pyth Entropy as well as a typescript client for that application. + +## Other Examples + +You can find more examples and tutorials in the [Pyth Examples repository](https://github.com/pyth-network/pyth-examples/tree/main/entropy). diff --git a/apps/developer-hub/content/docs/entropy/fees.mdx b/apps/developer-hub/content/docs/entropy/fees.mdx new file mode 100644 index 0000000000..a88aecc7b6 --- /dev/null +++ b/apps/developer-hub/content/docs/entropy/fees.mdx @@ -0,0 +1,21 @@ +--- +title: Fees +description: Understanding Pyth Entropy fee structure +--- + +# Fees + +The Entropy protocol has been designed to charge fees on a per-request basis. The total fee is +the sum of the provider fee, which is determined by the individual provider on a per-blockchain +basis, and the protocol fee, which is subject to Pyth governance decisions also on a per-chain +basis. These are accessible via the smart contract functions. + +Providers can withdraw their fees from the contract whenever they want. The allocation of the fees collected by the Entropy protocol +is governed by the collective decisions of its governance body. All fees are denominated in the native token +of the respective blockchain, ensuring a seamless and integrated operation. + +Note that protocols integrating with Entropy can pass these fees along to their users. Whenever a user +submits a transaction that requests a random number, the user can directly pay the entropy fees required +with the native blockchain token. There are no fees for revealing the random numbers. + +You can check the [current fees](current-fees) page to see the latest fees for each blockchain. diff --git a/apps/developer-hub/content/docs/entropy/generate-random-numbers.mdx b/apps/developer-hub/content/docs/entropy/generate-random-numbers.mdx new file mode 100644 index 0000000000..873f402744 --- /dev/null +++ b/apps/developer-hub/content/docs/entropy/generate-random-numbers.mdx @@ -0,0 +1,10 @@ +--- +title: How to Generate Random Numbers +description: Learn how to integrate Pyth Entropy to generate random numbers in your application +--- + +# How to Generate Random Numbers + +Integrating Pyth Entropy requires calling an onchain function to request a random number from Entropy. The function takes a random number that one can generate offchain and pass it to the Entropy contract which returns a sequence number. Pyth Entropy will then callback your contract with the generated random number once the request is fulfilled. + +See [How to Generate Random numbers in EVM dApps](generate-random-numbers/evm) to integrate your application with Pyth Entropy. diff --git a/apps/developer-hub/content/docs/entropy/index.mdx b/apps/developer-hub/content/docs/entropy/index.mdx index 04dbfae454..822353c1fa 100644 --- a/apps/developer-hub/content/docs/entropy/index.mdx +++ b/apps/developer-hub/content/docs/entropy/index.mdx @@ -1,10 +1,31 @@ --- -title: Overview -description: A placeholder landing page -icon: CardsThree +title: Entropy +description: Random number Generator for Ethereum smart contracts +icon: DiceSix full: true --- -# Secure On-Chain Randomness +# Entropy -Build secure smart contracts with provably random numbers from Pyth Entropy. Launch NFTs, games, and other unique experiences that your users trust with seamless UX. +Pyth Entropy allows developers to quickly and easily generate secure random numbers on the blockchain. +Entropy's rapid response time allows developers to build applications such as NFT mints and games with responsive UX. +Entropy also provides [strong security guarantees](protocol-design) to ensure that both users and application developers can trust that the results are random. + +Pyth Entropy is currently available on several [EVM networks](contract-addresses). +If you would like a deployment on another network, please [ask in Discord](https://discord.gg/invite/PythNetwork). + +## Getting Started + +Using Pyth Entropy is permissionless and developers can integrate in a few minutes. +Please see [How to Generate Random Numbers Using Pyth Entropy](generate-random-numbers) to start integrating Pyth Entropy into your application. + +## Additional Resources + +To learn more about how the protocol works, please see [Protocol design](protocol-design). + +## Reference Material + +- [Protocol design](protocol-design) +- [Contract Addresses](contract-addresses) +- [Error Codes](error-codes) +- [Entropy Debugger](https://entropy-debugger.pyth.network/) - Interactive tool for diagnosing callback issues diff --git a/apps/developer-hub/content/docs/entropy/meta.json b/apps/developer-hub/content/docs/entropy/meta.json index 24b6439855..7cbe03ce52 100644 --- a/apps/developer-hub/content/docs/entropy/meta.json +++ b/apps/developer-hub/content/docs/entropy/meta.json @@ -1,7 +1,24 @@ { "root": true, - "title": "Entropy", - "description": "Random numbers for smart contracts", - "icon": "Shuffle", - "pages": ["index", "---Guides---", "how-to-guides"] + "title": "Pyth Entropy", + "description": "Random number Generator for Ethereum smart contracts", + "icon": "DiceSix", + "pages": [ + "index", + "generate-random-numbers", + "create-your-first-entropy-app", + "protocol-design", + "contract-addresses", + "best-practices", + "fees", + "current-fees", + "error-codes", + "debug-callback-failures", + "examples", + "request-callback-variants", + "set-custom-gas-limits", + "whats-new-entropyv2", + "---Guides---", + "how-to-guides" + ] } diff --git a/apps/developer-hub/content/docs/entropy/protocol-design.mdx b/apps/developer-hub/content/docs/entropy/protocol-design.mdx new file mode 100644 index 0000000000..7d01f55387 --- /dev/null +++ b/apps/developer-hub/content/docs/entropy/protocol-design.mdx @@ -0,0 +1,42 @@ +--- +title: Protocol Design +description: Understanding how Pyth Entropy generates secure random numbers +--- + +# Protocol Design + +The Entropy protocol implements a secure 2-party random number generation procedure. The protocol +is an extension of a simple commit/reveal protocol. The original version has the following steps: + +1. Two parties A and B each randomly sample secret contributions to the random number, $x_A$ and $x_B$. +2. A commits to their number by sharing $h_A = \mathrm{hash}(x_A)$ +3. B reveals $x_B$ +4. A reveals $x_A$ +5. B verifies that $\mathrm{hash}(x_{A}) == h_A$ +6. The random number $r = \mathrm{hash}(x_A, x_B)$ + +This protocol has the property that the result is random as long as either A or B are honest. +Honesty means that (1) they draw their value at random, and (2) for A, they keep $x_A$ a secret until +step 4. Thus, neither party needs to trust the other -- as long as they are themselves honest, they can +ensure that the result $r$ is random. + +Entropy implements a version of this protocol that is optimized for on-chain usage. The +key difference is that one of the participants (the provider) commits to a sequence of random numbers +up-front using a hash chain. Users of the protocol then simply grab the next random number in the sequence. + +**Setup**: The provider P computes a sequence of $N$ random numbers, $x_i$ for $0 \leq i \leq N-1$: + +- $x_{N-1} = \mathrm{random}()$ +- $x_i = \mathrm{hash}(x_{i + 1})$ + +The provider commits to $x_0$ by posting it to the Entropy contract. +Each random number in the sequence can then be verified against the previous one in the sequence by hashing it, i.e., $\mathrm{hash}(x_i) = x_{i - 1}$ + +**Request**: To produce a random number, the following steps occur. + +1. The user randomly samples a secret value $x_u$ and sends a request to the Entropy contract containing $\mathrm{hash}(x_u)$. +2. The Entropy contract stores the request and assigns it a sequence number corresponding to the provider's next random number $x_i$. +3. The provider fulfills the request by revealing $x_i$ to the Entropy contract. +4. The Entropy contract verifies that $\mathrm{hash}(x_i) = x_{i-1}$ (the previous commitment), then computes the random number $r = \mathrm{hash}(x_u, x_i)$ and delivers it to the user's callback function. + +This approach ensures that the resulting random number is unpredictable as long as either the user or the provider is honest, while being efficiently verifiable on-chain. diff --git a/apps/developer-hub/content/docs/entropy/request-callback-variants.mdx b/apps/developer-hub/content/docs/entropy/request-callback-variants.mdx new file mode 100644 index 0000000000..0fc26f4308 --- /dev/null +++ b/apps/developer-hub/content/docs/entropy/request-callback-variants.mdx @@ -0,0 +1,82 @@ +--- +title: Request Callback Variants +description: Different ways to request random numbers with Pyth Entropy +--- + +# Request Callback Variants + +The [`IEntropyV2`](https://github.com/pyth-network/pyth-crosschain/blob/main/target_chains/ethereum/entropy_sdk/solidity/IEntropyV2.sol) interface provides multiple variants of the `requestV2` function: + +## 1. Basic Request + +```solidity +function requestV2() external payable returns (uint64 assignedSequenceNumber); +``` + +This is the simplest variant that requests entropy using the default provider and default gas settings. Uses in-contract PRNG for the user contribution to randomness. + +Use this when you want the most straightforward implementation and don't need to customize provider or gas parameters. + +### Example + +```solidity +function requestBasicRandomNumber() external payable { + // Get the fee for the default provider and gas limit + uint256 fee = entropy.getFeeV2(); + + require(msg.value >= fee, "Insufficient fee"); + + // Request randomness with default settings + uint64 sequenceNumber = entropy.requestV2{value: fee}(); +} +``` + +## 2. Request with Gas Limit + +```solidity +function requestV2( + uint32 gasLimit +) external payable returns (uint64 assignedSequenceNumber); +``` + +This variant allows you to specify a custom gas limit for the callback function execution. Uses in-contract PRNG for the user contribution. + +Use this when your `entropyCallback` function has complex logic that requires more gas than the default amount, or when you want to optimize gas usage by setting a lower limit for simple callbacks. + +### Example + +```solidity +function requestWithCustomGas() external payable { + uint32 customGasLimit = 150000; // Custom gas limit for callback + + // Get fee for the custom gas limit + uint256 fee = entropy.getFeeV2(customGasLimit); + + require(msg.value >= fee, "Insufficient fee"); + + // Request with custom gas limit + uint64 sequenceNumber = entropy.requestV2{value: fee}(customGasLimit); +} +``` + +## 3. Request with Provider + +```solidity +function requestV2( + address provider +) external payable returns (uint64 assignedSequenceNumber); +``` + +This variant allows you to specify a custom entropy provider instead of using the default one. + +## 4. Full Custom Request + +```solidity +function requestV2( + address provider, + uint32 gasLimit, + bytes32 userRandomNumber +) external payable returns (uint64 assignedSequenceNumber); +``` + +This is the most flexible variant that allows you to specify all parameters: custom provider, gas limit, and user random number. diff --git a/apps/developer-hub/content/docs/entropy/set-custom-gas-limits.mdx b/apps/developer-hub/content/docs/entropy/set-custom-gas-limits.mdx new file mode 100644 index 0000000000..57ddf20f44 --- /dev/null +++ b/apps/developer-hub/content/docs/entropy/set-custom-gas-limits.mdx @@ -0,0 +1,86 @@ +--- +title: Set Custom Gas Limits +description: How to set custom gas limits for Entropy callbacks +--- + +# Set Custom Gas Limits + +By default, Pyth Entropy uses a predefined gas limit for callback functions. However, you may need to adjust this limit based on the complexity of your callback implementation. + +## When to Use Custom Gas Limits + +### Use Higher Gas Limits When: + +- Your callback function performs complex calculations +- You need to update multiple storage variables +- Your callback interacts with other contracts +- You're implementing complex game logic + +### Use Lower Gas Limits When: + +- Your callback function is simple (e.g., just stores a single value) +- You want to optimize for cost +- You want to prevent potential gas griefing + +## Implementation + +### Using EntropyV2 Interface + +```solidity +import "@pythnetwork/entropy-sdk-solidity/IEntropyV2.sol"; + +contract MyContract is IEntropyConsumer { + IEntropyV2 entropy; + + function requestWithCustomGas() external payable { + uint32 customGasLimit = 200000; // Adjust based on your needs + + // Get fee for custom gas limit + uint256 fee = entropy.getFeeV2(customGasLimit); + require(msg.value >= fee, "Insufficient fee"); + + // Request with custom gas limit + uint64 sequenceNumber = entropy.requestV2{value: fee}(customGasLimit); + } +} +``` + +### Full Control Request + +```solidity +function requestWithFullControl() external payable { + address provider = entropy.getDefaultProvider(); + uint32 gasLimit = 150000; + bytes32 userRandomNumber = keccak256(abi.encode(block.timestamp, msg.sender)); + + uint256 fee = entropy.getFeeV2(provider, gasLimit); + require(msg.value >= fee, "Insufficient fee"); + + uint64 sequenceNumber = entropy.requestV2{value: fee}( + provider, + gasLimit, + userRandomNumber + ); +} +``` + +## Gas Limit Constraints + +Each network has different gas limit constraints: + +| Network | Min Gas Limit | Max Gas Limit | Default | +| --------- | ------------- | ------------- | ------- | +| Ethereum | 50,000 | 100,000 | 100,000 | +| Arbitrum | 50,000 | 100,000 | 100,000 | +| Avalanche | 50,000 | 100,000 | 100,000 | +| Base | 50,000 | 100,000 | 100,000 | +| BNB Chain | 50,000 | 100,000 | 100,000 | +| Optimism | 50,000 | 100,000 | 100,000 | +| Polygon | 50,000 | 100,000 | 100,000 | + +## Best Practices + +1. **Test your callback function** to estimate gas usage before setting custom limits +2. **Add a buffer** of 10-20% to your estimated gas usage for safety +3. **Use the minimum necessary** gas limit to reduce costs +4. **Consider network differences** - some networks may have different gas costs for similar operations diff --git a/apps/developer-hub/content/docs/entropy/whats-new-entropyv2.mdx b/apps/developer-hub/content/docs/entropy/whats-new-entropyv2.mdx new file mode 100644 index 0000000000..ca1c5e934b --- /dev/null +++ b/apps/developer-hub/content/docs/entropy/whats-new-entropyv2.mdx @@ -0,0 +1,55 @@ +--- +title: What's New in Entropy v2 +description: New features and improvements in Entropy v2 +--- + +# What's New in Entropy v2 + +Entropy v2 introduces several improvements and new features to make random number generation more flexible and efficient. + +## Key Improvements + +### 1. Multiple Request Variants + +Entropy v2 provides multiple ways to request random numbers: + +- **Basic Request**: Simplest implementation with default settings +- **Custom Gas Limit**: Specify gas limits for complex callbacks +- **Custom Provider**: Choose specific entropy providers +- **Full Control**: Specify all parameters (provider, gas limit, user random number) + +### 2. Improved Fee Structure + +The new version offers more granular fee calculation: + +```solidity +// Get fee for default provider and gas limit +uint256 basicFee = entropy.getFeeV2(); + +// Get fee for custom gas limit +uint256 customGasFee = entropy.getFeeV2(gasLimit); + +// Get fee for specific provider and gas limit +uint256 providerFee = entropy.getFeeV2(provider, gasLimit); +``` + +### 3. Better Error Handling + +Enhanced error messages and more specific error codes help developers debug issues more effectively. + +### 4. Gas Optimization + +Improved contract efficiency reduces overall gas costs for entropy requests. + +## Migration Guide + +If you're upgrading from Entropy v1 to v2: + +1. Update your imports to use `IEntropyV2` +2. Replace `request()` calls with `requestV2()` +3. Update fee calculation to use `getFeeV2()` +4. Test thoroughly with the new interface + +## Backward Compatibility + +Entropy v2 maintains backward compatibility with v1 for existing applications. However, we recommend migrating to v2 for new applications to take advantage of the improved features. diff --git a/apps/developer-hub/content/docs/pyth-core/_meta.json b/apps/developer-hub/content/docs/pyth-core/_meta.json deleted file mode 100644 index 8c2d4ea166..0000000000 --- a/apps/developer-hub/content/docs/pyth-core/_meta.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "documentation-home": { - "title": "← Documentation Home", - "href": "/home" - }, - - "-- Price Feeds": { - "title": "Price Feeds", - "type": "separator" - }, - "index": "Introduction", - "getting-started": "Getting Started", - - "-- Tutorials": { - "title": "Tutorials", - "type": "separator" - }, - - "create-your-first-pyth-app": "Create Your First Pyth App", - - "-- How-to Guides": { - "title": "How-To Guides", - "type": "separator" - }, - - "use-real-time-data": "Use Real-Time Price Data", - "fetch-price-updates": "Fetch Price Updates", - "schedule-price-updates": "Schedule Price Updates", - "migrate-an-app-to-pyth": "Migrate an App to Pyth", - "use-pyth-for-morpho": "Use Pyth for Morpho Markets", - "publish-data": "Publish Data", - "troubleshoot": "Troubleshoot Errors", - - "-- Reference Material": { - "title": "Reference Material", - "type": "separator" - }, - - "api-reference": "API Reference", - "price-feeds": "Price Feeds", - "current-fees": "Current Fees", - "sponsored-feeds": "Sponsored Feeds", - "market-hours": "Market Hours", - "best-practices": "Best Practices", - "error-codes": "Error Codes", - "api-instances-and-providers": "API Instances and Providers", - "contract-addresses": "Contract Addresses", - "pythnet-reference": "Pythnet Reference", - - "examples": { - "title": "Example Applications ↗", - "href": "https://github.com/pyth-network/pyth-examples/tree/main/price_feeds" - }, - "-- Understand Pyth": { - "title": "Understanding Pyth", - "type": "separator" - }, - - "pull-updates": "What is a Pull Oracle?", - "how-pyth-works": "How Pyth Works" -} diff --git a/apps/developer-hub/src/app/(docs)/layout.tsx b/apps/developer-hub/src/app/(docs)/layout.tsx index 85917a2d94..fa21b1c472 100644 --- a/apps/developer-hub/src/app/(docs)/layout.tsx +++ b/apps/developer-hub/src/app/(docs)/layout.tsx @@ -4,5 +4,9 @@ import type { ReactNode } from "react"; import { docsOptions } from "../../config/layout.config"; export default function Layout({ children }: { children: ReactNode }) { - return {children}; + return ( + + {children} + + ); } diff --git a/apps/developer-hub/src/app/(homepage)/layout.tsx b/apps/developer-hub/src/app/(homepage)/layout.tsx index 85274122b3..6a05991a71 100644 --- a/apps/developer-hub/src/app/(homepage)/layout.tsx +++ b/apps/developer-hub/src/app/(homepage)/layout.tsx @@ -4,5 +4,9 @@ import type { ReactNode } from "react"; import { baseOptions } from "../../config/layout.config"; export default function Layout({ children }: { children: ReactNode }) { - return {children}; + return ( + + {children} + + ); } diff --git a/apps/developer-hub/src/app/layout.ts b/apps/developer-hub/src/app/layout.ts deleted file mode 100644 index 47f8c23fd1..0000000000 --- a/apps/developer-hub/src/app/layout.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { Root as default } from "../components/Root"; -export { metadata, viewport } from "../metadata"; diff --git a/apps/developer-hub/src/app/layout.tsx b/apps/developer-hub/src/app/layout.tsx new file mode 100644 index 0000000000..5275c40c6c --- /dev/null +++ b/apps/developer-hub/src/app/layout.tsx @@ -0,0 +1,9 @@ +import type { ReactNode } from "react"; + +import { Root } from "../components/Root"; + +export { metadata, viewport } from "../metadata"; + +export default function RootLayout({ children }: { children: ReactNode }) { + return {children}; +} diff --git a/apps/developer-hub/src/source.ts b/apps/developer-hub/src/source.ts index 68dacccc7b..8d55e0c6f2 100644 --- a/apps/developer-hub/src/source.ts +++ b/apps/developer-hub/src/source.ts @@ -5,6 +5,7 @@ import { Gavel, Lightning, Shuffle, + DiceSix, } from "@phosphor-icons/react/dist/ssr"; import type { InferMetaType, InferPageType } from "fumadocs-core/source"; import { loader } from "fumadocs-core/source"; @@ -18,6 +19,7 @@ const icons: Record = { Gavel, Lightning, Shuffle, + DiceSix, }; export const source = loader({