# getAccountInfo Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/er/getAccountInfo pages/ephemeral-rollups-ers/api-reference/er/openapi/openapi-getAccountInfo.json POST / Get AccountInfo for a single account. # getBlockhashForAccounts Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/er/getBlockhashForAccounts pages/ephemeral-rollups-ers/api-reference/er/openapi/openapi-getBlockhashForAccounts.json POST / Get blockhash for multiple account addresses. # getDelegationStatus Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/er/getDelegationStatus pages/ephemeral-rollups-ers/api-reference/er/openapi/openapi-getDelegationStatus.json POST / Get delegation status for a single account from Magic Router. # getIdentity Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/er/getIdentity pages/ephemeral-rollups-ers/api-reference/er/openapi/openapi-getIdentity.json POST / Get the identity information of the current ER Validator # getRoutes Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/er/getRoutes pages/ephemeral-rollups-ers/api-reference/er/openapi/openapi-getRoutes.json POST / Get available ephemeral rollup nodes from the Magic Router # getSignatureStatuses Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/er/getSignatureStatuses pages/ephemeral-rollups-ers/api-reference/er/openapi/openapi-getSignatureStatuses.json POST / Returns the confirmation status for one or more signatures # Introduction Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/er/introduction MagicBlock Router API documentation ## Overview The MagicBlock Router API is a JSON-RPC API that implements almost all standard Solana RPC methods and adds router-specific methods. It simplifies multi-node setups by handling node selection and routing behind a single endpoint. It can be used to retrieve delegation status for accounts and identify the closest node for request execution. For example, `getBlockhashForAccounts` returns a blockhash from the appropriate node based on the provided accounts and their delegation status. **Mainnet URL:** `https://router.magicblock.app` **Devnet URL:** `https://devnet-router.magicblock.app` **API Version:** 2.0 ## Main Operations ### Network Information * [**Get Routes**](/pages/ephemeral-rollups-ers/api-reference/er/getRoutes) - Query available routing information * [**Get Identity**](/pages/ephemeral-rollups-ers/api-reference/er/getIdentity) - Retrieve identity information ### Account Operations * [**Get Account Info**](/pages/ephemeral-rollups-ers/api-reference/er/getAccountInfo) - Fetch account information * [**Get Blockhash For Accounts**](/pages/ephemeral-rollups-ers/api-reference/er/getBlockhashForAccounts) - Get blockhash for specific accounts ### Status & Delegation * [**Get Signature Statuses**](/pages/ephemeral-rollups-ers/api-reference/er/getSignatureStatuses) - Check transaction signature statuses * [**Get Delegation Status**](/pages/ephemeral-rollups-ers/api-reference/er/getDelegationStatus) - Query delegation information ## Key Features * **Solana RPC Coverage** - Implements almost all standard Solana RPC methods through the router * **Router-Specific Methods** - Adds methods such as `getBlockhashForAccounts` and `getDelegationStatus` * **Simplified Multi-Node Setup** - Use one router endpoint instead of manually managing multiple node endpoints * **Fast Route Query** - Efficiently determine routing paths for transactions * **Account State** - Access current account information and balances * **Transaction Tracking** - Monitor transaction status and confirmation * **Delegation Queries** - Check delegation relationships through the router ## Use Cases * Retrieve account balances and state * Check transaction confirmation status * Query route information for transaction routing * Verify delegation configurations * Avoid manual multi-node endpoint management # getAccountInfo Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getAccountInfo pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getAccountInfo.json POST / Returns all information associated with an account of provided Pubkey. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "method": "getAccountInfo", "jsonrpc": "2.0", "params": [ "5RgeA5P8bRaynJovch3zQURfJxXL3QK2JYg1YamSvyLb", { "encoding": "base64" } ], "id": 0 }' ``` # getBalance Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getBalance pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getBalance.json POST / Solana JSON-RPC method getBalance. # getBlock Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getBlock pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getBlock.json POST / Returns identity and transaction information about a confirmed block in the ledger. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getBlock", "params": [ 378967388, { "commitment": "finalized", "encoding": "json", "transactionDetails": "full", "maxSupportedTransactionVersion": 0, "rewards": false } ] }' ``` # getBlockCommitment Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getBlockCommitment pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getBlockCommitment.json POST / Returns commitment for particular block. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getBlockCommitment", "params": [ 5 ] }' ``` # getBlockHeight Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getBlockHeight pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getBlockHeight.json POST / Returns the current block height of the node. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getBlockHeight", "params": [ { "commitment": "finalized" } ] }' ``` # getBlockTime Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getBlockTime pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getBlockTime.json POST / Returns the estimated production time of a block. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getBlockTime", "params": [ 5 ] }' ``` # getBlocks Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getBlocks pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getBlocks.json POST / Returns a list of confirmed blocks between two slots. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getBlocks", "params": [ 5, 10, { "commitment": "finalized" } ] }' ``` # getBlocksWithLimit Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getBlocksWithLimit pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getBlocksWithLimit.json POST / Returns a list of confirmed blocks starting at the given slot for a given limit. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getBlocksWithLimit", "params": [ 5, 3 ] }' ``` # getFirstAvailableBlock Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getFirstAvailableBlock pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getFirstAvailableBlock.json POST / Solana JSON-RPC method getFirstAvailableBlock. # getGenesisHash Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getGenesisHash pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getGenesisHash.json POST / Solana JSON-RPC method getGenesisHash. # getHealth Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getHealth pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getHealth.json POST / Solana JSON-RPC method getHealth. # getIdentity Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getIdentity pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getIdentity.json POST / Solana JSON-RPC method getIdentity. # getLargestAccounts Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getLargestAccounts pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getLargestAccounts.json POST / Returns the 20 largest accounts, by lamport balance. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getLargestAccounts", "params": [ { "commitment": "finalized" } ] }' ``` # getLatestBlockhash Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getLatestBlockhash pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getLatestBlockhash.json POST / Returns the latest blockhash. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getLatestBlockhash", "params": [ { "commitment": "processed" } ] }' ``` # getLeaderSchedule Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getLeaderSchedule pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getLeaderSchedule.json POST / Returns the leader schedule for an epoch. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getLeaderSchedule", "params": [ null, { "commitment": "processed", "identity": "dv2eQHeP4RFrJZ6UeiZWoc3XTtmtZCUKxxCApCDcRNV" } ] }' ``` # getMinimumBalanceForRentExemption Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getMinimumBalanceForRentExemption pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getMinimumBalanceForRentExemption.json POST / Returns minimum balance required to make account rent exempt. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getMinimumBalanceForRentExemption", "params": [ 50, { "commitment": "processed" } ] }' ``` # getMultipleAccounts Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getMultipleAccounts pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getMultipleAccounts.json POST / Returns the account information for a list of Pubkeys. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getMultipleAccounts", "params": [ [ "vines1vzrYbzLMRdu58ou5XTby4qAqVRLmqo36NKPTg", "4fYNw3dojWmQ4dXtSGE9epjRGy9pFSx62YypT7avPYvA" ], { "encoding": "base58", "commitment": "finalized" } ] }' ``` # getProgramAccounts Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getProgramAccounts pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getProgramAccounts.json POST / Returns all accounts owned by the provided program Pubkey. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getProgramAccounts", "params": [ "4Nd1mBQtrMJVYVfKf2PJy9NZUZdTAsp7D4xWLs4gDB4T", { "commitment": "finalized", "filters": [ { "dataSize": 17 }, { "memcmp": { "offset": 4, "bytes": "3Mc6vR" } } ] } ] }' ``` # getRecentPerformanceSamples Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getRecentPerformanceSamples pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getRecentPerformanceSamples.json POST / Returns a list of recent performance samples, in reverse slot order. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getRecentPerformanceSamples", "params": [ 2 ] }' ``` # getSignatureStatuses Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getSignatureStatuses pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getSignatureStatuses.json POST / Returns the statuses of a list of signatures. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getSignatureStatuses", "params": [ [ "4cdd1oX7cfVALfr26tP52BZ6cSzrgnNGtYD7BFhm6FFeZV5sPTnRvg6NRn8yC6DbEikXcrNChBM5vVJnTgKhGhVu" ], { "searchTransactionHistory": true } ] }' ``` # getSignaturesForAddress Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getSignaturesForAddress pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getSignaturesForAddress.json POST / Returns signatures for confirmed transactions that include the given address. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getSignaturesForAddress", "params": [ "Vote111111111111111111111111111111111111111", { "commitment": "finalized", "limit": 1 } ] }' ``` # getSlot Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getSlot pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getSlot.json POST / Returns the slot that has reached the given or default commitment level. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getSlot", "params": [ { "commitment": "finalized" } ] }' ``` # getTokenAccountBalance Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getTokenAccountBalance pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getTokenAccountBalance.json POST / Returns the token balance of an SPL Token account. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getTokenAccountBalance", "params": [ "7fUAJdStEuGbc3sM84cKRL6yYaaSstyLSU4ve5oovLS7", { "commitment": "finalized" } ] }' ``` # getTokenAccountsByDelegate Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getTokenAccountsByDelegate pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getTokenAccountsByDelegate.json POST / Returns all SPL Token accounts by approved Delegate. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getTokenAccountsByDelegate", "params": [ "4Nd1mBQtrMJVYVfKf2PJy9NZUZdTAsp7D4xWLs4gDB4T", { "programId": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" }, { "commitment": "finalized", "encoding": "jsonParsed" } ] }' ``` # getTokenAccountsByOwner Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getTokenAccountsByOwner pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getTokenAccountsByOwner.json POST / Returns all SPL Token accounts by token owner. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getTokenAccountsByOwner", "params": [ "A1TMhSGzQxMr1TboBKtgixKz1sS6REASMxPo1qsyTSJd", { "programId": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA" }, { "commitment": "finalized", "encoding": "jsonParsed" } ] }' ``` # getTokenLargestAccounts Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getTokenLargestAccounts pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getTokenLargestAccounts.json POST / Returns the 20 largest accounts of a particular SPL Token type. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getTokenLargestAccounts", "params": [ "3wyAj7Rt1TWVPZVteFJPLa26JmLvdb1CAKEFZm3NY75E", { "commitment": "finalized" } ] }' ``` # getTokenSupply Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getTokenSupply pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getTokenSupply.json POST / Returns the total supply of an SPL Token type. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getTokenSupply", "params": [ "3wyAj7Rt1TWVPZVteFJPLa26JmLvdb1CAKEFZm3NY75E", { "commitment": "finalized" } ] }' ``` # getTransaction Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getTransaction pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getTransaction.json POST / Returns transaction details for a confirmed transaction. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getTransaction", "params": [ "4ReKprwf3WdLHRrzp4ctPWNBsQDPL3VZz3zMmoZfcGJMJCHh5Vq937mPdyxhCbw54wNnA6hZ7KfNpQdpt13yY7A9", { "commitment": "confirmed", "maxSupportedTransactionVersion": 0, "encoding": "json" } ] }' ``` # getTransactionCount Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getTransactionCount pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getTransactionCount.json POST / Returns the current transaction count from the ledger. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "getTransactionCount", "params": [ { "commitment": "finalized" } ] }' ``` # getVersion Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/getVersion pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-getVersion.json POST / Solana JSON-RPC method getVersion. # RPC API Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/introduction Solana JSON-RPC HTTP methods on MagicBlock devnet RPC endpoints. This section documents the Solana JSON-RPC HTTP method catalog on MagicBlock endpoints: **Devnet:** * `https://devnet-as.magicblock.app/` * `https://devnet-us.magicblock.app/` * `https://devnet-eu.magicblock.app/` * `https://devnet-tee.magicblock.app/` **Mainnet:** * `https://as.magicblock.app/` * `https://us.magicblock.app/` * `https://eu.magicblock.app/` * `https://as-tyo.magicblock.app/` * `https://sa.magicblock.app/` * `https://mainnet-tee.magicblock.app/` The method catalog is aligned with Solana RPC HTTP methods: * [Solana RPC HTTP Methods](https://solana.com/docs/rpc/http) > [!NOTE] > > TEE RPC endpoints may require an authentication token for certain methods. See > [Authorization > guide](/pages/private-ephemeral-rollups-pers/how-to-guide/quickstart#4-authorize) > for details. # isBlockhashValid Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/isBlockhashValid pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-isBlockhashValid.json POST / Returns whether a blockhash is still valid or not. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "isBlockhashValid", "params": [ "J7rBdM6AecPDEZp8aPq5iPSNKVkU5Q76F3oAV4eW5wsW", { "commitment": "processed" } ] }' ``` # sendTransaction Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/sendTransaction pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-sendTransaction.json POST / Submits a signed transaction to the cluster for processing. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "sendTransaction", "params": [ "4hXTCkRzt9WyecNzV1XPgCDfGAZzQKNxLXgynz5QDuWWPSAZBZSHptvWRL3BjCvzUXRdKvHL2b7yGrRQcWyaqsaBCncVG7BFggS8w9snUts67BSh3EqKpXLUm5UMHfD7ZBe9GhARjbNQMLJ1QD3Spr6oMTBU6EhdB4RD8CP2xUxr2u3d6fos36PD98XS6oX8TQjLpsMwncs5DAMiD4nNnR8NBfyghGCWvCVifVwvA8B8TJxE1aiyiv2L429BCWfyzAme5sZW8rDb14NeCQHhZbtNqfXhcp2tAnaAT" ] }' ``` # simulateTransaction Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/api-reference/rpc/simulateTransaction pages/ephemeral-rollups-ers/api-reference/rpc/openapi/openapi-rpc-simulateTransaction.json POST / Simulate sending a transaction. ```bash cURL theme={null} curl --request POST \ --url https://devnet-as.magicblock.app/ \ --header 'Content-Type: application/json' \ --data '{ "jsonrpc": "2.0", "id": 1, "method": "simulateTransaction", "params": [ "AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAEEjNmKiZGiOtSZ+g0//wH5kEQo3+UzictY+KlLV8hjXcs44M/Xnr+1SlZsqS6cFMQc46yj9PIsxqkycxJmXT+veJjIvefX4nhY9rY+B5qreeqTHu4mG6Xtxr5udn4MN8PnBt324e51j94YQl285GzN2rYa/E2DuQ0n/r35KNihi/zamQ6EeyeeVDvPVgUO2W3Lgt9hT+CfyqHvIa11egFPCgEDAwIBAAkDZAAAAAAAAAA=", { "commitment": "confirmed", "encoding": "base64", "replaceRecentBlockhash": true } ] }' ``` # Anchor Guide Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/how-to-guide/anchor Learn how to write a simple Anchor program that increments a counter on Solana > [!TIP] > > **Building with an AI coding agent?** Install the MagicBlock Dev Skill to give your agent MagicBlock-specific patterns — delegation flows, Magic Actions, cranks, VRF, and more. > > **Hit an error?** Ask your coding agent with the skill installed, not the docs assistant. The assistant only sees the docs, so it cannot debug your code. > > Quick install for Claude Code: > > ```bash theme={null} > npx skills add https://github.com/magicblock-labs/magicblock-dev-skill > ``` > > Using Cursor, Codex, Windsurf, Cline, or another agent? See the [AI Dev Skill](/pages/overview/additional-information/ai-dev-skill) page for all install targets. [Build a real-time Anchor Counter on Solana with MagicBlock's Ephemeral Rollup | Tutorial](https://www.youtube.com/embed/qwu2RBKyFiw?si=PMg-3UbRfvvbrs7C\&list=PLWR_ZQiGMS8mIe1kPZe8OfHIbhvZqaM8V) This guide will walk you through the process of writing a simple Anchor program that increments a counter. You'll learn how to deploy this program on Solana and interact with it using a React client. ## Software Packages This program is developed and tested with the following software packages. Other versions may also be compatible. | Software | Version | Installation Guide | | - | - | - | | **Solana** | 3.1.9 | [Install Solana](https://docs.anza.xyz/cli/install) | | **Rust** | 1.89.0 | [Install Rust](https://www.rust-lang.org/tools/install) | | **Anchor** | 1.0.2 | [Install Anchor](https://www.anchor-lang.com/docs/installation) | ## Quick Access to Source Code If you prefer to dive straight into the code: > [card] [Source Code: Anchor Counter Program](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/anchor-counter) > [card] [Live Example App](https://counter-example.magicblock.app/) ## Writing the Anchor Program Let's break down the key components of our counter program: ## Core Functionality The program implements two main instructions: 1. `initialize`: Sets the counter to 0 2. `increment`: Increments the counter by 1 Here's the core structure of our program: ```rust theme={null} #[ephemeral] #[program] pub mod public_counter { use super::*; /// Initialize the counter. pub fn initialize(ctx: Context) -> Result<()> { let counter = &mut ctx.accounts.counter; counter.count = 0; Ok(()) } /// Increment the counter. pub fn increment(ctx: Context) -> Result<()> { let counter = &mut ctx.accounts.counter; counter.count += 1; Ok(()) } // ... Additional instructions will be added here } ``` Nothing special here, just a simple Anchor program that increments a counter. The only difference is that we're adding the `delegate` macro to inject some useful logic to interact with the delegation program. ### Delegating the Counter PDA In order to delegate the counter PDA, and make it writable in an Ephemeral Rollup session, we need to add an instruction which internally calls the `delegate_account` function. `delegate_account` will CPI to the delegation program, which upon validation will gain ownership of the account. After this step, an ephemeral validator can start processing transactions on the counter PDA and propose state diff trough the delegation program. > [card] [Transaction (Base Layer): Delegate](https://solscan.io/tx/5tyEk8gkdP88xe8GL7X12f9WGZfYZtmDbuXozvqkpea4rphXPiNp91vAzmSjsyUR399wimBYazEszKSH35sidPRH?cluster=devnet) > > Inspect transactions details on Solana Explorer ```rust theme={null} /// Add delegate function to the context #[delegate] #[derive(Accounts)] pub struct DelegateInput<'info> { pub payer: Signer<'info>, /// CHECK The pda to delegate #[account(mut, del)] pub pda: AccountInfo<'info>, } ``` ```rust theme={null} /// Delegate the account to the delegation program /// Set specific validator based on ER, see https://docs.magicblock.gg/pages/ephemeral-rollups-ers/how-to-guide/local-development pub fn delegate(ctx: Context) -> Result<()> { ctx.accounts.delegate_pda( &ctx.accounts.payer, &[COUNTER_SEED], DelegateConfig { // Optionally set a specific validator from the first remaining account validator: ctx.remaining_accounts.first().map(|acc| acc.key()), ..Default::default() }, )?; Ok(()) } ``` ### Committing while the PDA is delegated The ephemeral runtime allows committing the state of the PDA while it is delegated. This is done by building a `MagicIntentBundleBuilder` with the `commit` intent and invoking it. > [card] [Transaction (ER): Commit](https://solscan.io/tx/335F5UcgAW3P8wSaVoEPiBoxeykw9wR1kcJLWUnd9sHmxymCgGvLtxaGDy6ZKDgJw2ku9jtRqwVNY85DuAHvs9GT?cluster=custom\&customUrl=https://devnet.magicblock.app) > > Inspect transaction details on Solana Explorer > [card] [Transaction (Base layer): Commit](https://solscan.io/tx/3xzMGbj2fwFCnGp6r7wyMv5LExmL6SXaEbt52DmxA3Wx1LyksuXpPJS4AAPtqoSeJe3aF7oY3jFNiEhBQKwhzRGN?cluster=devnet) > > Inspect transaction details on Solana Explorer ```rust theme={null} use ephemeral_rollups_sdk::ephem::MagicIntentBundleBuilder; /// Increment the counter and manually commit the account in the Ephemeral Rollup session. pub fn increment_and_commit(ctx: Context) -> Result<()> { let counter = &mut ctx.accounts.counter; counter.count += 1; // Serialize the Anchor account before the CPI sees it counter.exit(&crate::ID)?; MagicIntentBundleBuilder::new( ctx.accounts.payer.to_account_info(), ctx.accounts.magic_context.to_account_info(), ctx.accounts.magic_program.to_account_info(), ) .commit(&[ctx.accounts.counter.to_account_info()]) .build_and_invoke()?; Ok(()) } ``` ### Undelegating the PDA Undelegating the PDA is done by building a `MagicIntentBundleBuilder` with the `commit_and_undelegate` intent. This commits the latest state and returns ownership of the PDA to the owner program. > [card] [Transaction (ER): Undelegate](https://solscan.io/tx/3MN6Avygk3FwsuQPoKHzpLo9kBBommHwRHTdgxBooDwsaNHgSYr1yaDXYEe63Eii5DCVbtaK89Yyrhy3dSGhHmvw?cluster=custom\&customUrl=https://devnet.magicblock.app) > > Inspect transaction details on Solana Explorer > [card] [Transaction (Base layer): Undelegate](https://solscan.io/tx/2YwzNQh632bJu8TSP9GPsXmh7o78KgMMM9QPNbdaAzamtjGZfmT4o7bkG2PtpCWp7aJmmxpxTXr4Qo36k5EjgPab?cluster=devnet) > > Inspect transaction details on Solana Explorer ```rust theme={null} use ephemeral_rollups_sdk::ephem::MagicIntentBundleBuilder; /// Undelegate the account from the delegation program pub fn undelegate(ctx: Context) -> Result<()> { MagicIntentBundleBuilder::new( ctx.accounts.payer.to_account_info(), ctx.accounts.magic_context.to_account_info(), ctx.accounts.magic_program.to_account_info(), ) .commit_and_undelegate(&[ctx.accounts.counter.to_account_info()]) .build_and_invoke()?; Ok(()) } ``` ## Connecting the React Client The React client is a simple interface that allows you to interact with the Anchor program. It uses the Anchor bindings to interact with the program and the MagicBlock SDK to interact with the Ephemeral Rollup session. Source lives alongside the program at [`anchor-counter/app`](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/anchor-counter/app). > [card] [Live Example App](https://counter-example.magicblock.app/) [https://counter-example.magicblock.app/](https://counter-example.magicblock.app/) > [!WARNING] > > Iframes only work with some wallets (e.g. Backpack). Alternatively, try the > deployed demo here: [https://counter-example.magicblock.app/](https://counter-example.magicblock.app/) ### Ephemeral Endpoint Configuration To interact with the Ephemeral Rollup session, you need to configure the appropriate endpoint: * For devnet, use the following ephemeral endpoint: [https://devnet.magicblock.app](https://devnet.magicblock.app) * For mainnet, please reach out to the MagicBlock team to receive the appropriate endpoint. * For [localhost](/pages/ephemeral-rollups-ers/how-to-guide/local-development), download, install, and run the ephemeral validator locally with the appropriate environment variables. Make sure to update your client configuration to use the correct endpoint based on your development or production environment. > [!NOTE] > > These public RPC endpoints are currently free and supported for development: > \ > Magic Router Devnet: [https://devnet-router.magicblock.app](https://devnet-router.magicblock.app) \\ > > Solana Devnet: [https://api.devnet.solana.com](https://api.devnet.solana.com) \\ > > ER Devnet (Asia): [https://devnet-as.magicblock.app](https://devnet-as.magicblock.app) \\ > > ER Devnet (EU): [https://devnet-eu.magicblock.app](https://devnet-eu.magicblock.app) \\ > > ER Devnet (US): [https://devnet-us.magicblock.app](https://devnet-us.magicblock.app) \\ > > TEE Devnet: [https://devnet-tee.magicblock.app/](https://devnet-tee.magicblock.app/) \\ > > Find out more details > [here](/pages/ephemeral-rollups-ers/how-to-guide/local-development) > . > [card] [Source Code: Anchor Counter Program](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/anchor-counter) > [card] [Live Example App](https://counter-example.magicblock.app/) # Local Development Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/how-to-guide/local-development Run and test your Native Rust or Anchor programs with a fully local Ephemeral Rollup stack, Surfpool, or a local VRF oracle. *** ### Quick Access Explore program and test scripts for both Anchor and Native Rust: > [card] [GitHub](/pages/ephemeral-rollups-ers/how-to-guide/quickstart) > > Anchor Implementation > [card] [GitHub](/pages/ephemeral-rollups-ers/how-to-guide/rust-program) > > Native Rust Implementation *** ## Local Setup Options You can run Ephemeral Rollups locally in three ways: * A fully local stack with `mb-test-validator` as the base layer and a local `ephemeral-validator`. * A local Surfpool instance as the base layer alternative, while still running the rollup locally. * A local `ephemeral-validator` connected directly to a public base layer such as Devnet. Use the fully local path when you want everything on your machine. Use Surfpool when you want to keep the Surfpool workflow while testing against a local Ephemeral Rollup. Use the Devnet option when you want a local rollup process without running a local Solana validator. ### Important: upgrade your program with the correct validator identity When using a local ER validator, connect it to the base layer where the accounts are delegated. If you delegate your PDA to a specific ER validator identity, update the delegation config in your program so commits and undelegations can complete correctly on the base layer. > [!NOTE] > > These public validators are supported for development. Make sure to add the > specific ER validator in your delegation instruction: > > **Mainnet** > >
    >
  • > Asia (as.magicblock.app): > `MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57` >
  • > >
  • > EU (eu.magicblock.app): > `MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e` >
  • > >
  • > US (us.magicblock.app): > `MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd` >
  • > >
  • > TEE (mainnet-tee.magicblock.app): > `MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo` >
  • > >
  • > Asia Tokyo (as-tyo.magicblock.app): > `MSHuBweMkNp4yPLDkPLA8bLRHbDmURWjYzsxrcBjix8` >
  • > >
  • > South America (sa.magicblock.app): > `MSARyz2yVTkqiYQWWgaEtUKug7oCF7PphE9GjEYHtDh` >
  • >
> > **Devnet** > >
    >
  • > Asia (devnet-as.magicblock.app): > `MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57` >
  • > >
  • > EU (devnet-eu.magicblock.app): > `MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e` >
  • > >
  • > US (devnet-us.magicblock.app): > `MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd` >
  • > >
  • > TEE (devnet-tee.magicblock.app): > `MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo` >
  • >
> > **Localnet** > >
    >
  • > Local ER (localhost:7799): > `mAGicPQYBMvcYveUZA5F5UNNwyHvfYh5xkLS2Fr1mev` >
  • >
> [tab] Fully local > > **1. Install the Ephemeral Validator CLI** > > ```bash theme={null} > npm install -g @magicblock-labs/ephemeral-validator@latest > ``` > > **2. Start the local Solana base layer** > > `mb-test-validator` starts a local Solana validator you can use as the base layer for a fully local setup. > > ```bash theme={null} > mb-test-validator --reset > ``` > > This setup uses `http://localhost:8899` for RPC and `ws://localhost:8900` for WebSocket connections. > > **3. Deploy or upgrade your program on localhost** > > > [tab] Rust Native > > > > ```bash theme={null} > > cargo build-sbf > > solana config set --url localhost > > solana program deploy YOUR_PROGRAM_PATH > > ``` > > > [tab] Anchor > > > > ```bash theme={null} > > anchor build && anchor deploy \ > > --provider.cluster localnet > > ``` > > **4. Start the local ephemeral validator** > > Connect the local Ephemeral Rollup to the local Solana validator: > > ```bash theme={null} > ephemeral-validator --remotes "http://localhost:8899" --remotes "ws://localhost:8900" -l "7799" --lifecycle ephemeral > ``` > > **5. Run tests against the local rollup** > > The local rollup is exposed on `http://localhost:7799` for RPC and `ws://localhost:7800` for WebSocket connections. > > > [tab] Rust Native > > > > ```bash theme={null} > > EPHEMERAL_PROVIDER_ENDPOINT=http://localhost:7799 \ > > EPHEMERAL_WS_ENDPOINT=ws://localhost:7800 \ > > PROVIDER_ENDPOINT=http://localhost:8899 \ > > WS_ENDPOINT=ws://localhost:8900 \ > > yarn test > > ``` > > > [tab] Anchor > > > > ```bash theme={null} > > EPHEMERAL_PROVIDER_ENDPOINT="http://localhost:7799" \ > > EPHEMERAL_WS_ENDPOINT="ws://localhost:7800" \ > > anchor test \ > > --provider.cluster localnet \ > > --skip-local-validator \ > > --skip-build \ > > --skip-deploy > > ``` > [tab] Surfpool > > **1. Install Surfpool** > > ```bash theme={null} > curl -sL https://run.surfpool.run/ | bash > ``` > > **2. Install the Ephemeral Validator CLI** > > ```bash theme={null} > npm install -g @magicblock-labs/ephemeral-validator@latest > ``` > > **3. Start Surfpool** > > This example keeps Surfpool local while using Solana Devnet as the upstream base layer: > > ```bash theme={null} > surfpool start --rpc-url https://api.devnet.solana.com > ``` > > Surfpool exposes the local RPC and WebSocket endpoints that the ephemeral validator connects to. > > **4. Start the ephemeral validator** > > Point the validator to Surfpool's local RPC and WebSocket endpoints: > > ```bash theme={null} > ephemeral-validator --remotes "http://localhost:8899" --remotes "ws://localhost:8900" -l "7799" --lifecycle ephemeral > ``` > > **5. Send a test transaction to the rollup** > > ```bash theme={null} > solana transfer 0 -u "http://localhost:7799" > ``` > > **6. Inspect the transaction** > > The transaction should appear in the ER TUI, where you can inspect it and open it in the explorer. > > This flow is based on [Running Ephemeral Rollups locally with Surfpool](https://x.com/PiccoGabriele/status/2030045550230524212). > [tab] Devnet > > **1. Deploy or upgrade your program on Devnet** > > Upgrade your program with MagicBlock delegation and deploy it to Devnet: > > > [tab] Rust Native > > > > ```bash theme={null} > > cargo build-sbf > > solana config set --url devnet > > solana program deploy YOUR_PROGRAM_PATH > > ``` > > > [tab] Anchor > > > > ```bash theme={null} > > anchor build && anchor deploy \ > > --provider.cluster devnet > > ``` > > **2. Install and run the local ephemeral validator** > > ```bash theme={null} > npm install -g @magicblock-labs/ephemeral-validator@latest > ``` > > ```bash theme={null} > RUST_LOG=info ephemeral-validator \ > --lifecycle ephemeral \ > --remote-url "https://rpc.magicblock.app/devnet" \ > --rpc-port 7799 > ``` > > **3. Run tests against the local rollup** > > > [tab] Rust Native > > > > ```bash theme={null} > > EPHEMERAL_PROVIDER_ENDPOINT=http://localhost:7799 \ > > EPHEMERAL_WS_ENDPOINT=ws://localhost:7800 \ > > yarn test > > ``` > > > [tab] Anchor > > > > ```bash theme={null} > > EPHEMERAL_PROVIDER_ENDPOINT="http://localhost:7799" \ > > EPHEMERAL_WS_ENDPOINT="ws://localhost:7800" \ > > anchor test \ > > --provider.cluster devnet \ > > --skip-local-validator \ > > --skip-build \ > > --skip-deploy > > ``` ## Run the VRF Oracle Locally If you also need to test VRF end to end, run a local `vrf-oracle` against a local test queue. **1. Install the latest Ephemeral Validator CLI** ```bash theme={null} npm install -g @magicblock-labs/ephemeral-validator@latest ``` **2. Start the local Solana validator** ```bash theme={null} mb-test-validator --reset ``` **3. Start the ephemeral validator** ```bash theme={null} ephemeral-validator --remote-url "http://localhost:8899" --rpc-port 7799 --lifecycle ephemeral ``` **4. Start the local VRF oracle** This oracle adds requests to the local test queue: ```bash theme={null} VRF_ORACLE_SKIP_PREFLIGHT="true" RPC_URL="http://localhost:8899" WEBSOCKET_URL="ws://localhost:8999" RUST_LOG=info vrf-oracle ``` If your local validator exposes a different WebSocket port, update `WEBSOCKET_URL` accordingly. *** # Quickstart Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/how-to-guide/quickstart Any Solana program can be upgraded with Ephemeral Rollups by adding delegation capabilities. *** > [!TIP] > > **Building with an AI coding agent?** Install the MagicBlock Dev Skill to give your agent MagicBlock-specific patterns — delegation flows, Magic Actions, cranks, VRF, and more. > > **Hit an error?** Ask your coding agent with the skill installed, not the docs assistant. The assistant only sees the docs, so it cannot debug your code. > > Quick install for Claude Code: > > ```bash theme={null} > npx skills add https://github.com/magicblock-labs/magicblock-dev-skill > ``` > > Using Cursor, Codex, Windsurf, Cline, or another agent? See the [AI Dev Skill](/pages/overview/additional-information/ai-dev-skill) page for all install targets. ### Quick Access Check out basic counter example: > [card] [GitHub](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/counter/anchor) > > Anchor Implementation > [card] [GitHub](https://github.com/GabrielePicco/ephemeral-counter-ui) > > React Implementation *** [Build a real-time Anchor Counter on Solana with MagicBlock's Ephemeral Rollup | Tutorial](https://www.youtube.com/embed/qwu2RBKyFiw?si=PMg-3UbRfvvbrs7C\&list=PLWR_ZQiGMS8mIe1kPZe8OfHIbhvZqaM8V) *** ## Step-By-Step Guide Build your program and upgrade it with delegation hooks with MagicBlock's Delegation Program `DELeGGvXpWV2fqJUhqcF5ZSYMS4JTLjteaAMARRSaeSh`: **1. [Write your program](#1-write-program)** Write your Solana program as you normally would. **2. [Add delegation and undelegation hooks in your program](#2-delegate)** Add CPI hooks to delegate, commit and undelegate state accounts through Ephemeral Rollup sessions. > [!NOTE] > > These public validators are supported for development. Make sure to add the > specific ER validator in your delegation instruction: > > **Mainnet** > >
    >
  • > Asia (as.magicblock.app): > `MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57` >
  • > >
  • > EU (eu.magicblock.app): > `MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e` >
  • > >
  • > US (us.magicblock.app): > `MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd` >
  • > >
  • > TEE (mainnet-tee.magicblock.app): > `MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo` >
  • > >
  • > Asia Tokyo (as-tyo.magicblock.app): > `MSHuBweMkNp4yPLDkPLA8bLRHbDmURWjYzsxrcBjix8` >
  • > >
  • > South America (sa.magicblock.app): > `MSARyz2yVTkqiYQWWgaEtUKug7oCF7PphE9GjEYHtDh` >
  • >
> > **Devnet** > >
    >
  • > Asia (devnet-as.magicblock.app): > `MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57` >
  • > >
  • > EU (devnet-eu.magicblock.app): > `MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e` >
  • > >
  • > US (devnet-us.magicblock.app): > `MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd` >
  • > >
  • > TEE (devnet-tee.magicblock.app): > `MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo` >
  • >
> > **Localnet** > >
    >
  • > Local ER (localhost:7799): > `mAGicPQYBMvcYveUZA5F5UNNwyHvfYh5xkLS2Fr1mev` >
  • >
**3. [Deploy your program on Solana.](#3-deploy)** Deploy your program directly on Solana using Anchor or Solana CLI. **4. [Ready to execute transactions for delegation and real-time speed](#4-test)** Send transactions without modifications on-chain and off-chain that also comply with the SVM RPC specification. *** ## Counter Example ![Counter GIF](https://mintcdn.com/magicblock-42/iteauKFqxDKE2Vln/images/gifs/counter-420w.gif?s=f6feee67754b5b0b90c94ad159d4e630) The following software packages may be required, other versions may also be compatible: | Software | Version | Installation Guide | | - | - | - | | **Solana** | 3.1.9 | [Install Solana](https://docs.anza.xyz/cli/install) | | **Rust** | 1.89.0 | [Install Rust](https://www.rust-lang.org/tools/install) | | **Anchor** | 1.0.2 | [Install Anchor](https://www.anchor-lang.com/docs/installation) | | **Node** | 24.10.0 | [Install Node](https://nodejs.org/en/download/current) | ### Code Snippets > [tab] 1. Write program > > The program implements two main instructions: > > 1. `initialize`: Sets the counter to 0 > 2. `increment`: Increments the counter by 1 > > The program implements specific instructions for delegating and undelegating the counter: > > 1. `Delegate`: Delegates counter from Base Layer to ER (called on Base Layer) > 2. `CommitAndUndelegate`: Schedules sync of counter from ER to Base Layer, and undelegates counter on ER (called on ER) > 3. `Commit`: Schedules sync of counter from ER to Base Layer (called on ER) > 4. `Undelegate`: > * Schedules sync and undelegation of counter (called on ER) > > * Undelegation triggered through callback instruction injected through #\[ephemeral] (called on Base Layer through validator CPI) > > > [!NOTE] > > > > The undelegation callback discriminator `[196, 28, 41, 206, 48, 37, 51, 167]` > > and its instruction processor must be specified in your program. This > > instruction triggered by Delegation Program reverts account ownership on the > > Base Layer after calling undelegation on ER. > > > > With [`[#ephemeral]`](/pages/ephemeral-rollups-ers/how-to-guide/quickstart#1-write-program) Anchor macro from MagicBlock's Ephemeral Rollup SDK, the undelegation callback discriminator and processor are injected into your program. > > ```rust theme={null} > #[ephemeral] > #[program] > pub mod public_counter { > use super::*; > > /// Initialize the counter. > pub fn initialize(ctx: Context) -> Result<()> { > let counter = &mut ctx.accounts.counter; > counter.count = 0; > Ok(()) > } > > /// Increment the counter. > pub fn increment(ctx: Context) -> Result<()> { > let counter = &mut ctx.accounts.counter; > counter.count += 1; > Ok(()) > } > > /// Delegate the account to the delegation program > /// Set specific validator based on ER, see https://docs.magicblock.gg/pages/get-started/how-integrate-your-program/local-setup > pub fn delegate(ctx: Context) -> Result<()> { > // ... > } > > /// Manually commit the counter state in the Ephemeral Rollup session. > pub fn commit(ctx: Context) -> Result<()> { > // ... > } > > /// Increment the counter and commit in the same instruction. > pub fn increment_and_commit(ctx: Context) -> Result<()> { > // ... > } > > /// Undelegate the account from the delegation program. > pub fn undelegate(ctx: Context) -> Result<()> { > // ... > } > } > > pub const COUNTER_SEED: &[u8] = b"counter"; > > /// Context for initializing counter > #[derive(Accounts)] > pub struct Initialize<'info> { > #[account(init_if_needed, payer = user, space = 8 + 8, seeds = [COUNTER_SEED], bump)] > pub counter: Account<'info, Counter>, > #[account(mut)] > pub user: Signer<'info>, > pub system_program: Program<'info, System>, > } > > /// Context for incrementing counter > #[derive(Accounts)] > pub struct Increment<'info> { > #[account(mut, seeds = [COUNTER_SEED], bump)] > pub counter: Account<'info, Counter>, > } > > /// Counter struct > #[account] > pub struct Counter { > pub count: u64, > } > > /// Other context for delegation > ``` > > Nothing special here, just a simple Anchor program that increments a counter. The only difference is that we're adding the `ephemeral` macro for undelegation and `delegate` macro to inject some useful logic to interact with the delegation program. > > [⬆️ Back to Top](#code-snippets) > [tab] 2. Delegate > > > [!NOTE] > > > > These public validators are supported for development. Make sure to add the > > specific ER validator in your delegation instruction: > > > > **Mainnet** > > > >
    > >
  • > > Asia (as.magicblock.app): > > `MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57` > >
  • > > > >
  • > > EU (eu.magicblock.app): > > `MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e` > >
  • > > > >
  • > > US (us.magicblock.app): > > `MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd` > >
  • > > > >
  • > > TEE (mainnet-tee.magicblock.app): > > `MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo` > >
  • > > > >
  • > > Asia Tokyo (as-tyo.magicblock.app): > > `MSHuBweMkNp4yPLDkPLA8bLRHbDmURWjYzsxrcBjix8` > >
  • > > > >
  • > > South America (sa.magicblock.app): > > `MSARyz2yVTkqiYQWWgaEtUKug7oCF7PphE9GjEYHtDh` > >
  • > >
> > > > **Devnet** > > > >
    > >
  • > > Asia (devnet-as.magicblock.app): > > `MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57` > >
  • > > > >
  • > > EU (devnet-eu.magicblock.app): > > `MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e` > >
  • > > > >
  • > > US (devnet-us.magicblock.app): > > `MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd` > >
  • > > > >
  • > > TEE (devnet-tee.magicblock.app): > > `MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo` > >
  • > >
> > > > **Localnet** > > > >
    > >
  • > > Local ER (localhost:7799): > > `mAGicPQYBMvcYveUZA5F5UNNwyHvfYh5xkLS2Fr1mev` > >
  • > >
> > 1. Add `ephemeral-rollups-sdk` with Anchor features to your program > > ```bash theme={null} > cargo add ephemeral-rollups-sdk --features anchor > ``` > > Import `delegate`, `commit`, `ephemeral`, `DelegateConfig`, and `MagicIntentBundleBuilder` (which replaces the deprecated `commit_accounts` and `commit_and_undelegate_accounts` helpers): > > ```rust theme={null} > use ephemeral_rollups_sdk::anchor::{ > commit, > delegate, > ephemeral > }; > use ephemeral_rollups_sdk::cpi::DelegateConfig; > use ephemeral_rollups_sdk::ephem::MagicIntentBundleBuilder; > ``` > > 2. Add `delegate` macro and instruction, `ephemeral` macro, and `undelegate` instruction to your program. Specify your preferred delegation config such as auto commits and specific ER validator: > > ```rust theme={null} > /// Add delegate function to the context > #[delegate] > #[derive(Accounts)] > pub struct DelegateInput<'info> { > pub payer: Signer<'info>, > /// CHECK: The pda to delegate > #[account(mut, del)] > pub pda: AccountInfo<'info>, > } > ``` > > ```rust theme={null} > /// Delegate the account to the delegation program > /// Set specific validator based on ER, see https://docs.magicblock.gg/pages/get-started/how-integrate-your-program/local-setup > pub fn delegate(ctx: Context) -> Result<()> { > ctx.accounts.delegate_pda( > &ctx.accounts.payer, > &[COUNTER_SEED], > DelegateConfig { > // Optionally set a specific validator from the first remaining account > validator: ctx.remaining_accounts.first().map(|acc| acc.key()), > ..Default::default() > }, > )?; > Ok(()) > } > ``` > > ```rust theme={null} > use ephemeral_rollups_sdk::ephem::MagicIntentBundleBuilder; > > /// Manually commit the counter state in the Ephemeral Rollup session. > pub fn commit(ctx: Context) -> Result<()> { > MagicIntentBundleBuilder::new( > ctx.accounts.payer.to_account_info(), > ctx.accounts.magic_context.to_account_info(), > ctx.accounts.magic_program.to_account_info(), > ) > .commit(&[ctx.accounts.counter.to_account_info()]) > .build_and_invoke()?; > Ok(()) > } > > /// Increment the counter and commit the new state in the same instruction. > pub fn increment_and_commit(ctx: Context) -> Result<()> { > let counter = &mut ctx.accounts.counter; > counter.count += 1; > // Serialize the Anchor account before the CPI sees it > counter.exit(&crate::ID)?; > MagicIntentBundleBuilder::new( > ctx.accounts.payer.to_account_info(), > ctx.accounts.magic_context.to_account_info(), > ctx.accounts.magic_program.to_account_info(), > ) > .commit(&[ctx.accounts.counter.to_account_info()]) > .build_and_invoke()?; > Ok(()) > } > ``` > > ```rust theme={null} > use ephemeral_rollups_sdk::ephem::MagicIntentBundleBuilder; > > /// Undelegate the account from the delegation program. > /// Commits the latest state and returns ownership of the PDA back to the owner program. > pub fn undelegate(ctx: Context) -> Result<()> { > MagicIntentBundleBuilder::new( > ctx.accounts.payer.to_account_info(), > ctx.accounts.magic_context.to_account_info(), > ctx.accounts.magic_program.to_account_info(), > ) > .commit_and_undelegate(&[ctx.accounts.counter.to_account_info()]) > .build_and_invoke()?; > Ok(()) > } > ``` > > > `Delegation` is the process of transferring ownership of one or more of your program's `PDAs` to the delegation program. Ephemeral Validators will then be able to use the `PDAs` to perform transactions in the SVM runtime. > > > `Commit` is the process of updating the state of the `PDAs` from ER to the base layer. After the finalization process, the `PDAs` remain locked on base layer. > > > `Undelegation` is the process of transferring ownership of the `PDAs` back to your program. On undelegation, the state is committed and it trigger the finalization process. Once state it validated, the `PDAs` are unlocked and can be used as normal on base layer. > > [⬆️ Back to Top](#code-snippets) > [tab] 3. Deploy > > Now you’re program is upgraded and ready! Fund your deployer wallet, then build and deploy to the > desired cluster: > > ```bash theme={null} > # Devnet: airdrop SOL to your configured keypair before deploying > solana airdrop 2 --url https://api.devnet.solana.com > > anchor build && anchor deploy > ``` > > [⬆️ Back to Top](#code-snippets) > [tab] 4. Test > > Ready to execute transactions for delegation and real-time speed. > > > [!NOTE] > > > > These public validators are supported for development. Make sure to add the > > specific ER validator in your delegation instruction: > > > > **Mainnet** > > > >
    > >
  • > > Asia (as.magicblock.app): > > `MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57` > >
  • > > > >
  • > > EU (eu.magicblock.app): > > `MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e` > >
  • > > > >
  • > > US (us.magicblock.app): > > `MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd` > >
  • > > > >
  • > > TEE (mainnet-tee.magicblock.app): > > `MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo` > >
  • > > > >
  • > > Asia Tokyo (as-tyo.magicblock.app): > > `MSHuBweMkNp4yPLDkPLA8bLRHbDmURWjYzsxrcBjix8` > >
  • > > > >
  • > > South America (sa.magicblock.app): > > `MSARyz2yVTkqiYQWWgaEtUKug7oCF7PphE9GjEYHtDh` > >
  • > >
> > > > **Devnet** > > > >
    > >
  • > > Asia (devnet-as.magicblock.app): > > `MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57` > >
  • > > > >
  • > > EU (devnet-eu.magicblock.app): > > `MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e` > >
  • > > > >
  • > > US (devnet-us.magicblock.app): > > `MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd` > >
  • > > > >
  • > > TEE (devnet-tee.magicblock.app): > > `MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo` > >
  • > >
> > > > **Localnet** > > > >
    > >
  • > > Local ER (localhost:7799): > > `mAGicPQYBMvcYveUZA5F5UNNwyHvfYh5xkLS2Fr1mev` > >
  • > >
> > ```bash theme={null} > anchor test --skip-build --skip-deploy --skip-local-validator > ``` > > Run the following test: > > ```typescript theme={null} > const COUNTER_SEED = "counter"; > > // Set Anchor providers > const provider = new anchor.AnchorProvider( > new anchor.web3.Connection( > process.env.PROVIDER_ENDPOINT || "https://api.devnet.solana.com", > { > wsEndpoint: process.env.PROVIDER_WS_ENDPOINT || undefined, > commitment: "confirmed", > }, > ), > anchor.Wallet.local(), > ); > anchor.setProvider(provider); > > const providerEphemeralRollup = new anchor.AnchorProvider( > new anchor.web3.Connection( > process.env.EPHEMERAL_PROVIDER_ENDPOINT || > "https://devnet-as.magicblock.app/", > { > wsEndpoint: > process.env.EPHEMERAL_WS_ENDPOINT || "wss://devnet-as.magicblock.app/", > commitment: "confirmed", > }, > ), > anchor.Wallet.local(), > ); > > // Set program and PDA > const program = anchor.workspace.PublicCounter as Program; > const [counterPDA] = anchor.web3.PublicKey.findProgramAddressSync( > [Buffer.from(COUNTER_SEED)], > program.programId, > ); > > // Initialize counter on base layer > let initTx = await program.methods > .initialize() > .accounts({ > user: provider.wallet.publicKey, > }) > .transaction(); > const initTxHash = await provider.sendAndConfirm(initTx, [ > provider.wallet.payer, > ]); > > // Increment counter on base layer > let incBaseTx = await program.methods > .increment() > .accounts({ > counter: counterPDA, > }) > .transaction(); > const incBaseTxHash = await provider.sendAndConfirm(incBaseTx, [ > provider.wallet.payer, > ]); > > // Delegate counter to ER > // Pin a specific validator by passing it in remaining_accounts > const ER_VALIDATOR = new anchor.web3.PublicKey( > "MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57", // Asia ER validator > ); > let delTx = await program.methods > .delegate() > .accounts({ > payer: provider.wallet.publicKey, > pda: counterPDA, > }) > .remainingAccounts([ > { pubkey: ER_VALIDATOR, isSigner: false, isWritable: false }, > ]) > .transaction(); > const delTxHash = await provider.sendAndConfirm(delTx, [ > provider.wallet.payer, > ]); > > // Increment counter in real time on ER > let incErTx = await program.methods > .increment() > .accounts({ > counter: counterPDA, > }) > .transaction(); > incErTx.feePayer = providerEphemeralRollup.wallet.publicKey; > incErTx.recentBlockhash = ( > await providerEphemeralRollup.connection.getLatestBlockhash() > ).blockhash; > incErTx = await providerEphemeralRollup.wallet.signTransaction(incErTx); > const incErTxHash = await providerEphemeralRollup.sendAndConfirm(incErTx); > > // Commit and undelegate counter from ER back to base layer > let undelTx = await program.methods > .undelegate() > .accounts({ > payer: providerEphemeralRollup.wallet.publicKey, > }) > .transaction(); > undelTx.feePayer = providerEphemeralRollup.wallet.publicKey; > undelTx.recentBlockhash = ( > await providerEphemeralRollup.connection.getLatestBlockhash() > ).blockhash; > undelTx = await providerEphemeralRollup.wallet.signTransaction(undelTx); > const undelTxHash = await providerEphemeralRollup.sendAndConfirm(undelTx); > ``` > > To make it easier to integrate via the frontend, we created the [Magic Router](/pages/ephemeral-rollups-ers/introduction/magic-router). You send transactions directly to the magic router, and we can determine for you whether it should be routed to the [Ephemeral Rollup](/pages/ephemeral-rollups-ers/introduction/ephemeral-rollup) or base layer. > > > [!NOTE] > > > > These public RPC endpoints are currently free and supported for development: > > \ > > Magic Router Devnet: [https://devnet-router.magicblock.app](https://devnet-router.magicblock.app) \\ > > > > Solana Devnet: [https://api.devnet.solana.com](https://api.devnet.solana.com) \\ > > > > ER Devnet (Asia): [https://devnet-as.magicblock.app](https://devnet-as.magicblock.app) \\ > > > > ER Devnet (EU): [https://devnet-eu.magicblock.app](https://devnet-eu.magicblock.app) \\ > > > > ER Devnet (US): [https://devnet-us.magicblock.app](https://devnet-us.magicblock.app) \\ > > > > TEE Devnet: [https://devnet-tee.magicblock.app/](https://devnet-tee.magicblock.app/) \\ > > > > Find out more details > > [here](/pages/ephemeral-rollups-ers/how-to-guide/local-development) > > . > > [⬆️ Back to Top](#code-snippets) *** ### Advanced Code Snippets > [tab] Resize PDA > > When resizing a delegated PDA: > > * PDA must have enough lamports to remain rent-exempt for the new account size. > * If additional lamports are needed, the **payer account must be delegated** to provide the difference. > * PDA must be owned by the program, and the transaction must include any signer(s) required for transferring lamports. > * Use `system_instruction::allocate` > > ```rust theme={null} > #[account] > pub struct Counter { > pub count: u64, > pub extra_data: Vec, > } > > #[derive(Accounts)] > pub struct ResizeCounter<'info> { > #[account(mut)] > pub counter: Account<'info, Counter>, > #[account(mut)] > pub payer: Signer<'info>, > pub system_program: Program<'info, System>, > } > > // Resize the counter (e.g., to store more extra_data) > pub fn resize_counter(ctx: Context, new_size: usize) -> Result<()> { > let account_to_resize = &mut ctx.accounts.counter.to_account_info(); > let payer = &mut ctx.accounts.payer.to_account_info(); > > // Calculate rent-exemption for the new size > let rent = Rent::get()?; > let min_balance = rent.minimum_balance(new_size); > > // Top up lamports if needed > let current_lamports = **account_to_resize.lamports.borrow(); > if current_lamports < min_balance { > let to_transfer = min_balance - current_lamports; > **payer.try_borrow_mut_lamports()? -= to_transfer; > **account_to_resize.try_borrow_mut_lamports()? += to_transfer; > } > > // Resize account > account_to_resize.resize(new_size)?; > > Ok(()) > } > ``` > > [⬆️ Back to Top](#advanced-code-snippets) > [tab] Magic Router > > Initialize connection with Magic Router before you send transactions dynamically. > > > [!NOTE] > > > > These public RPC endpoints are currently free and supported for development: > > \ > > Magic Router Devnet: [https://devnet-router.magicblock.app](https://devnet-router.magicblock.app) \\ > > Choose your preferred SDK to initialize, send and confirm transactions: > > * `ephemeral-rollups-kit` for `@solana/kit` > * `ephemeral-rollups-sdk` for `@solana/web.js` > > ```typescript Kit theme={null} > import { Connection } from "@magicblock-labs/ephemeral-rollups-kit"; > > // Initialize connection > const connection = await Connection.create( > "https://devnet-router.magicblock.app", > "wss://devnet-router.magicblock.app" > ); > > // ... create transaction > > // Send and confirm transaction > const txHash = await connection.sendAndConfirmTransaction( > transactionMessage, > [userKeypair], > { commitment: "confirmed", skipPreflight: true } > ); > ``` > > ```typescript Web3.js theme={null} > import { sendAndConfirmTransaction } from "@solana/web3.js"; > import { ConnectionMagicRouter } from "@magicblock-labs/ephemeral-rollups-sdk"; > > // Initialize connection > const connection = new ConnectionMagicRouter( > "https://devnet-router.magicblock.app/", > { wsEndpoint: "wss://devnet-router.magicblock.app/" } > ); > > // ... create transaction > > // Send and confirm transaction > const txHash = await sendAndConfirmTransaction(connection, tx, [payer], { > skipPreflight: true, > commitment: "confirmed", > }); > ``` > > [Learn more about Magic Router](/pages/ephemeral-rollups-ers/introduction/magic-router) > > [⬆️ Back to Top](#advanced-code-snippets) > [tab] Magic Action > > ### Quick Access > > > [card] [Magic Actions Example](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/magic-actions/anchor) > > > > Explore reference implementation on GitHub > > Attach one or more instructions that run automatically on the Solana base layer immediately after an Ephemeral Rollup > (ER) commit. > [Learn more about Magic Action](/pages/ephemeral-rollups-ers/magic-actions/overview) > > ### 1) Create action instruction > > The instruction `update_leaderboard` runs on the base layer immediately after the commit lands. The `#[action]` attribute on its accounts context marks it as callable from a post-commit action. > > > [!WARNING] > > > > `#[action]` makes the instruction **callable from** a post-commit action — it > > does not make it callable **only** that way. The handler is an ordinary > > base-layer instruction, so anyone can invoke it directly with a wallet. > > Address, `seeds`, and `owner` constraints only pin *which* accounts are passed; > > they do not authenticate *who* called it. Any handler that moves value or > > changes authoritative state must verify the injected `escrow` signer — see > > [Authenticate the caller](/pages/ephemeral-rollups-ers/magic-actions/troubleshooting#security-authenticate-the-caller). > > ```rust theme={null} > // program instruction > pub fn update_leaderboard(ctx: Context) -> Result<()> { > let leaderboard = &mut ctx.accounts.leaderboard; > let counter_info = &mut ctx.accounts.counter.to_account_info(); > let mut data: &[u8] = &counter_info.try_borrow_data()?; > let counter = Counter::try_deserialize(&mut data)?; > > if counter.count > leaderboard.high_score { > leaderboard.high_score = counter.count; > } > > msg!( > "Leaderboard updated! High score: {}", > leaderboard.high_score > ); > Ok(()) > } > > // instruction context > #[action] > #[derive(Accounts)] > pub struct UpdateLeaderboard<'info> { > #[account(mut, seeds = [LEADERBOARD_SEED], bump)] > pub leaderboard: Account<'info, Leaderboard>, > /// CHECK: PDA owner depends on: 1) Delegated: Delegation Program; 2) Undelegated: Your program ID > pub counter: UncheckedAccount<'info>, > } > ``` > > ### 2) Build the commit instruction with the action > > The commit instruction `commit_and_update_leaderboard` runs on the ER. It uses `MagicIntentBundleBuilder` to schedule both the commit and the post-commit action onto `magic_context` — both are applied together when the ER transaction is sealed back to the base layer. > > ```rust theme={null} > // commit action instruction on ER > pub fn commit_and_update_leaderboard(ctx: Context) -> Result<()> { > // Build the post-commit action that updates the leaderboard on base layer > let instruction_data = > anchor_lang::InstructionData::data(&crate::instruction::UpdateLeaderboard {}); > let action_args = ActionArgs::new(instruction_data); > let action_accounts = vec![ > ShortAccountMeta { > pubkey: ctx.accounts.leaderboard.key(), > is_writable: true, > }, > ShortAccountMeta { > pubkey: ctx.accounts.counter.key(), > is_writable: false, > }, > ]; > let action = CallHandler { > destination_program: crate::ID, > accounts: action_accounts, > args: action_args, > // Signer that pays transaction fees for the action from its escrow PDA > escrow_authority: ctx.accounts.payer.to_account_info(), > compute_units: 200_000, > }; > > // Schedule commit + post-commit action on magic_context > MagicIntentBundleBuilder::new( > ctx.accounts.payer.to_account_info(), > ctx.accounts.magic_context.to_account_info(), > ctx.accounts.magic_program.to_account_info(), > ) > .commit(&[ctx.accounts.counter.to_account_info()]) > .add_post_commit_actions([action]) > .build_and_invoke()?; > > Ok(()) > } > > // commit action context on ER > #[commit] > #[derive(Accounts)] > pub struct CommitAndUpdateLeaderboard<'info> { > #[account(mut)] > pub payer: Signer<'info>, > > #[account(mut, seeds = [COUNTER_SEED], bump)] > pub counter: Account<'info, Counter>, > > /// CHECK: Leaderboard PDA - not mut here, writable set in handler > #[account(seeds = [LEADERBOARD_SEED], bump)] > pub leaderboard: UncheckedAccount<'info>, > > /// CHECK: Your program ID > pub program_id: AccountInfo<'info>, > } > ``` > > ### Execute multiple actions > > You can commit multiple accounts and chain several actions in one call. Actions execute sequentially in the order they're passed to `add_post_commit_actions`. > > ```rust theme={null} > // Chain several actions — they execute sequentially on base layer after the commit lands. > MagicIntentBundleBuilder::new( > ctx.accounts.payer.to_account_info(), > ctx.accounts.magic_context.to_account_info(), > ctx.accounts.magic_program.to_account_info(), > ) > .commit(&[ > ctx.accounts.counter.to_account_info(), > // ... additional committed accounts > ]) > .add_post_commit_actions([action_1, action_2, action_3]) > .build_and_invoke()?; > ``` > > ### Undelegate with actions > > Actions can also be chained onto an undelegation — the counter commits, undelegates, and the actions run, all atomically in one ER transaction. > > ```rust theme={null} > // Commit, undelegate, AND execute actions — all atomically on base layer after the ER transaction seals. > MagicIntentBundleBuilder::new( > ctx.accounts.payer.to_account_info(), > ctx.accounts.magic_context.to_account_info(), > ctx.accounts.magic_program.to_account_info(), > ) > .commit_and_undelegate(&[ctx.accounts.counter.to_account_info()]) > .add_post_commit_actions([action]) > .build_and_invoke()?; > ``` > > [⬆️ Back to Top](#advanced-code-snippets) > [tab] Top-up delegated account > > Top up a delegated account's lamports on the ER side. The transaction is submitted on the **base layer** and uses the Ephemeral SPL Token program to shuttle lamports to the destination's delegated balance via a single-use lamports PDA. > > Common use case: keeping a delegated fee payer funded for a long session. Without a fee payer, an account stops after 10 commits. With a fee payer and `magic_fee_vault`, it can keep committing, and the payer starts paying live commit fees on commit 26. > > Notes: > > * Generate a fresh 32-byte salt per top-up via `crypto.getRandomValues` — re-using a salt collides with an existing PDA. > * Submit to the base-layer RPC, not the ER. > * The destination must already be delegated. > > ```typescript theme={null} > import { > Connection, > Keypair, > PublicKey, > Transaction, > sendAndConfirmTransaction, > } from "@solana/web3.js"; > import { > lamportsDelegatedTransferIx, > deriveLamportsPda, > } from "@magicblock-labs/ephemeral-rollups-sdk"; > > /** > * Top up a delegated account with lamports. > * > * The transaction is submitted on the BASE LAYER. The Ephemeral SPL Token > * program creates a single-use lamports PDA, funds it from the payer, and > * delegates it so the ER credits the destination's delegated balance. > */ > async function topUpDelegatedAccount( > connection: Connection, // base-layer connection > payer: Keypair, > destination: PublicKey, // delegated account to top up > amountLamports: bigint, > ) { > // Generate a fresh 32-byte salt per top-up. > // Re-using a salt collides with an existing lamports PDA and the call fails. > const salt = crypto.getRandomValues(new Uint8Array(32)); > > const [lamportsPda] = deriveLamportsPda(payer.publicKey, destination, salt); > > const ix = await lamportsDelegatedTransferIx( > payer.publicKey, > destination, > amountLamports, > salt, > ); > > const tx = new Transaction().add(ix); > tx.feePayer = payer.publicKey; > > // CRITICAL: send to the base-layer RPC, not the ER. > const sig = await sendAndConfirmTransaction(connection, tx, [payer], { > commitment: "confirmed", > skipPreflight: true, > }); > > return { sig, lamportsPda }; > } > ``` > > [⬆️ Back to Top](#advanced-code-snippets) > [tab] On-Curve Delegation > > ### Quick Access > > > [card] [GitHub](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/oncurve-delegation/client) > > > > On-Curve Delegation > > Required signers for delegating an on-curve account: > > 1. On-curve account to be delegated > 2. Fee payer > > Required instructions for delegating on-curve accounts: > > 1. Assign System Account to Delegation Program > 2. Delegate to Delegation Program > > ```typescript Kit theme={null} > // Create assign instruction > // The on-curve account must sign this instruction to change its owner > const accountSigner = await cryptoKeyPairToTransactionSigner(userKeypair); > const delegationProgramAddress = address(DELEGATION_PROGRAM_ID.toString()); > const assignInstruction = getAssignInstruction({ > account: accountSigner, > programAddress: delegationProgramAddress, > }); > > // Create delegate instruction > const delegateInstruction = await createDelegateInstruction({ > payer: feePayerAddress, > delegatedAccount: userAddress, > ownerProgram: ownerProgramAddress, > validator: validatorAddress, > }); > > // Prepare transaction > const transactionMessage = pipe( > createTransactionMessage({ version: 0 }), > (tx) => setTransactionMessageFeePayer(feePayerAddress, tx), > (tx) => > appendTransactionMessageInstructions( > [assignInstruction, delegateInstruction], > tx > ) > ); > // Send and confirm transaction (fee payer need to sign, on-curve account cannot be signer since delegated) > const txHash = await connection.sendAndConfirmTransaction( > transactionMessage, > [userKeypair, feePayerKeypair], > { commitment: "confirmed", skipPreflight: true } > ); > ``` > > ```typescript Web3.js theme={null} > // Create assign instruction > const assignInstruction = SystemProgram.assign({ > accountPubkey: userPubkey, > programId: DELEGATION_PROGRAM_ID, > }); > > // Create delegate instruction > const delegateInstruction = createDelegateInstruction({ > payer: feePayerKeypair.publicKey, > delegatedAccount: userPubkey, > ownerProgram: ownerProgram, > validator: validator, > }); > > // Create and send transaction (fee payer need to sign, on-curve account cannot be signer since delegated) > const tx = new Transaction().add(assignInstruction, delegateInstruction); > tx.feePayer = feePayerKeypair.publicKey; > const txSignature = await sendAndConfirmTransaction( > connectionBaseLayer, > tx, > [userKeypair, feePayerKeypair], > { > skipPreflight: true, > } > ); > ``` > > Direct commit and undelegate through Magic Program only. > > ```typescript Kit theme={null} > // Create commit and undelegate instruction > const commitAndUndelegateInstruction = createCommitAndUndelegateInstruction( > userAddress, > [userAddress] > ); > > // Prepare transaction > const transactionMessage = pipe( > createTransactionMessage({ version: 0 }), > (tx) => setTransactionMessageFeePayer(feePayerAddress, tx), > (tx) => > appendTransactionMessageInstructions([commitAndUndelegateInstruction], tx) > ); > > // Send and confirm transaction on ephemeral connection > const txHash = await ephemeralConnection.sendAndConfirmTransaction( > transactionMessage, > [userKeypair, feePayerKeypair], > { commitment: "confirmed", skipPreflight: true } > ); > ``` > > ```typescript Web3.js theme={null} > // Create commit and undelegate instruction > const commitAndUndelegateInstruction = createCommitAndUndelegateInstruction( > userPubkey, > [userPubkey] > ); > > // Send and confirm transaction on ephemeral connection > const tx = new Transaction().add(commitAndUndelegateInstruction); > tx.feePayer = feePayerKeypair.publicKey; > const txSignature = await sendAndConfirmTransaction( > ephemeralConnection, > tx, > [userKeypair, feePayerKeypair], > { > skipPreflight: true, > } > ); > ``` > > [⬆️ Back to Top](#advanced-code-snippets) > [tab] Delegation Actions > > ### Quick Access > > > [card] [Delegation Actions Example](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/delegation-actions/anchor) > > > > Explore reference implementation on GitHub > > Attach instructions to a delegation that the ER validator runs automatically > inside the rollup, right after the account is delegated — no extra transaction: > > * Build the action(s) as standard `Instruction`s and convert them to the > compact payload with `.cleartext()` (public) — encrypted actions are built > off-chain by a client holding the validator key. > * The base-layer delegation program stores the payload in the delegation > record; the ER validator executes it once the account lands in the rollup. > * CPI with `delegate_account_with_actions` instead of the plain `delegate_pda` > helper; the `#[delegate]` macro still provides the buffer/record/metadata > accounts. > > ```rust theme={null} > /// Reuse the same accounts context as a normal delegation > #[delegate] > #[derive(Accounts)] > pub struct DelegateInput<'info> { > pub payer: Signer<'info>, > /// CHECK: The pda to delegate > #[account(mut, del)] > pub pda: AccountInfo<'info>, > } > ``` > > ```rust theme={null} > use anchor_lang::solana_program::instruction::{AccountMeta, Instruction}; > use anchor_lang::InstructionData; > use ephemeral_rollups_sdk::cpi::{ > delegate_account_with_actions, DelegateAccounts, DelegateConfig, > }; > use ephemeral_rollups_sdk::dlp_api::compact::ClearText; > > /// Delegate the account AND attach a post-delegation action. The action is stored > /// in the delegation record on the base layer and executed automatically by the ER > /// validator inside the rollup, right after the account is delegated — no extra > /// transaction. Here the action is a self-CPI back into `increment`. > pub fn delegate_with_actions(ctx: Context) -> Result<()> { > let counter_key = ctx.accounts.pda.key(); > > // The instruction the ER validator runs post-delegation, inside the rollup. > let increment_action = Instruction { > program_id: crate::ID, > accounts: vec![AccountMeta::new(counter_key, false)], > data: crate::instruction::Increment {}.data(), > }; > > // Convert to the compact, cleartext post-delegation actions payload. > // (Use `cleartext` for public actions; encrypted actions are built off-chain > // by a client that holds the validator key.) > let actions = vec![increment_action].cleartext(); > > let payer = ctx.accounts.payer.to_account_info(); > let pda = ctx.accounts.pda.to_account_info(); > let delegate_accounts = DelegateAccounts { > payer: &payer, > pda: &pda, > owner_program: &ctx.accounts.owner_program, > buffer: &ctx.accounts.buffer_pda, > delegation_record: &ctx.accounts.delegation_record_pda, > delegation_metadata: &ctx.accounts.delegation_metadata_pda, > delegation_program: &ctx.accounts.delegation_program, > system_program: &ctx.accounts.system_program, > }; > > delegate_account_with_actions( > delegate_accounts, > &[COUNTER_SEED], > DelegateConfig { > // Optionally set a specific validator from the first remaining account > validator: ctx.remaining_accounts.first().map(|acc| acc.key()), > ..Default::default() > }, > actions, > // No extra signers are required by the increment action. > &[], > )?; > Ok(()) > } > ``` > > [⬆️ Back to Top](#advanced-code-snippets) *** ### Quick Access Learn more about private ER, Rust Native implementation, and local development: > [card] [Private Ephemeral Rollups (PER)](/pages/private-ephemeral-rollups-pers/how-to-guide/quickstart) > > Quickstart > [card] [Rust Native](/pages/ephemeral-rollups-ers/how-to-guide/rust-program) > > Quickstart > [card] [Guide](/pages/ephemeral-rollups-ers/how-to-guide/local-development) > > Local Development *** ## Solana Explorer Get insights about your transactions and accounts on Solana: > [card] [Solana Explorer](https://explorer.solana.com/) > > Official Solana Explorer > [card] [Solscan](https://solscan.io/) > > Explore Solana Blockchain ## Solana RPC Providers Send transactions and requests through existing RPC providers: > [card] [Solana](https://solana.com/docs/references/clusters#on-a-high-level) > > Free Public Nodes > [card] [Helius](https://www.helius.dev/solana-rpc-nodes) > > Free Shared Nodes > [card] [Triton](https://triton.one/solana) > > Dedicated High-Performance Nodes ## Solana Validator Dashboard Find real-time updates on Solana's validator infrastructure: > [card] [Solana Beach](https://solanabeach.io/) > > Get Validator Insights > [card] [Validators App](https://www.validators.app/) > > Discover Validator Metrics ## Server Status Subscribe to Solana's and MagicBlock's server status: > [card] [Solana Status](https://status.solana.com/) > > Subscribe to Solana Server Updates > [card] [MagicBlock Status](/pages/overview/additional-information/system-status) > > Subscribe to MagicBlock Server Status *** ## MagicBlock Products > [card] [Ephemeral Rollup (ER)](/pages/ephemeral-rollups-ers/how-to-guide/quickstart) > > Execute real-time, zero-fee transactions securely on Solana. > [card] [Private Ephemeral Rollup (PER)](/pages/private-ephemeral-rollups-pers/how-to-guide/quickstart) > > Protect sensitive data with compliance — built on top of Ephemeral Rollups. > [card] [Ephemeral SPL Token](/pages/ephemeral-spl-token/overview) > > Move SPL tokens at rollup speed — public or private transfers, swaps, and private payments for trading and DeFi apps. > [card] [Prediction Markets & Trading](/pages/solutions/prediction-markets) > > Combine real-time execution, session keys, token custody, price feeds, automation, and settlement. > [card] [Solana VRF](/pages/verifiable-randomness-functions-vrfs/introduction/solana-vrf) > > Add provably fair onchain randomness to games, raffles, and real-time apps. > [card] [Pricing Oracle](/pages/tools/oracle/introduction) > > Access low-latency onchain price feeds for trading and DeFi. *** # Solana Program Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/how-to-guide/rust-program Learn how to write a simple Rust program that delegates and increments a counter on Solana > [!TIP] > > **Building with an AI coding agent?** Install the MagicBlock Dev Skill to give your agent MagicBlock-specific patterns — delegation flows, Magic Actions, cranks, VRF, and more. > > **Hit an error?** Ask your coding agent with the skill installed, not the docs assistant. The assistant only sees the docs, so it cannot debug your code. > > Quick install for Claude Code: > > ```bash theme={null} > npx skills add https://github.com/magicblock-labs/magicblock-dev-skill > ``` > > Using Cursor, Codex, Windsurf, Cline, or another agent? See the [AI Dev Skill](/pages/overview/additional-information/ai-dev-skill) page for all install targets. *** ### Quick Access Check out basic counter example in other implementations: > [card] [GitHub](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/counter/native-rust) > > Native Rust Implementation > [card] [GitHub](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/counter/pinocchio) > > Pinocchio Implementation > [card] [Guide](/pages/ephemeral-rollups-ers/how-to-guide/local-development) > > Local Development *** [Build a real-time Rust Counter on Solana with MagicBlock's Ephemeral Rollup | Tutorial](https://www.youtube.com/embed/b77bwSGDHK0?si=Oknc5f8CuC17WBnV\&list=PLWR_ZQiGMS8mIe1kPZe8OfHIbhvZqaM8V) *** ## Step-By-Step Guide Build your program and upgrade it with delegation hooks with MagicBlock’s Delegation Program `DELeGGvXpWV2fqJUhqcF5ZSYMS4JTLjteaAMARRSaeSh`: **1. [Write program and add delegation instructions](#1-write-program)** Write your Solana program as you normally would. **2. [Delegate PDA on Base Layer](#2-delegate)** Add CPI hooks to delegate, commit and undelegate state accounts through Ephemeral Rollup sessions. > [!NOTE] > > These public validators are supported for development. Make sure to add the > specific ER validator in your delegation instruction: > > **Mainnet** > >
    >
  • > Asia (as.magicblock.app): > `MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57` >
  • > >
  • > EU (eu.magicblock.app): > `MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e` >
  • > >
  • > US (us.magicblock.app): > `MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd` >
  • > >
  • > TEE (mainnet-tee.magicblock.app): > `MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo` >
  • > >
  • > Asia Tokyo (as-tyo.magicblock.app): > `MSHuBweMkNp4yPLDkPLA8bLRHbDmURWjYzsxrcBjix8` >
  • > >
  • > South America (sa.magicblock.app): > `MSARyz2yVTkqiYQWWgaEtUKug7oCF7PphE9GjEYHtDh` >
  • >
> > **Devnet** > >
    >
  • > Asia (devnet-as.magicblock.app): > `MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57` >
  • > >
  • > EU (devnet-eu.magicblock.app): > `MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e` >
  • > >
  • > US (devnet-us.magicblock.app): > `MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd` >
  • > >
  • > TEE (devnet-tee.magicblock.app): > `MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo` >
  • >
> > **Localnet** > >
    >
  • > Local ER (localhost:7799): > `mAGicPQYBMvcYveUZA5F5UNNwyHvfYh5xkLS2Fr1mev` >
  • >
**3. [Commit PDA on ER](#3-commit)** Deploy your program directly on Solana using Solana CLI. **4. [Undelegate PDA on ER](#4-undelegate)** Send transactions without modifications on-chain and off-chain that also comply with the SVM RPC specification. *** ## Counter Example The following software packages may be required, other versions may also be compatible: | Software | Version | Installation Guide | | - | - | - | | **Solana** | 3.1.9 | [Install Solana](https://docs.anza.xyz/cli/install) | | **Rust** | 1.89.0 | [Install Rust](https://www.rust-lang.org/tools/install) | | **Node** | 24.10.0 | [Install Node](https://nodejs.org/en/download/current) | ### Code Snippets > [tab] 1. Write Program > > The program implements two main instructions: > > 1. `InitializeCounter`: Initialize and sets the counter to 0 (called on Base Layer) > 2. `IncreaseCounter`: Increments the initialized counter by X amount (called on Base Layer or ER) > > The program implements specific instructions for delegating and undelegating the counter: > > 1. `Delegate`: Delegates counter from Base Layer to ER (called on Base Layer) > > 2. `CommitAndUndelegate`: Schedules sync of counter from ER to Base Layer, and undelegates counter on ER (called on ER) > > 3. `Commit`: Schedules sync of counter from ER to Base Layer (called on ER) > > 4. `Undelegate`: Undelegates counter on the Base Layer (called on Base Layer through validator CPI) > > 5. `IncrementAndCommit`: Increments and commits in a single ER transaction (called on ER) > > 6. `IncrementAndUndelegate`: Increments, commits, and undelegates in a single ER transaction (called on ER) > > > [!NOTE] > > > > The undelegation callback discriminator `[196, 28, 41, 206, 48, 37, 51, 167]` > > and its instruction processor must be specified in your program. This > > instruction triggered by Delegation Program reverts account ownership on the > > Base Layer after calling undelegation on ER. > > > > With [`[#ephemeral]`](/pages/ephemeral-rollups-ers/how-to-guide/quickstart#1-write-program) Anchor macro from MagicBlock's Ephemeral Rollup SDK, the undelegation callback discriminator and processor are injected into your program. > > Here's the core structure of our program: > > > > ```rust theme={null} > use borsh::BorshDeserialize; > use solana_program::program_error::ProgramError; > > pub enum ProgramInstruction { > InitializeCounter, > IncreaseCounter { increase_by: u64 }, > Delegate, > CommitAndUndelegate, > Commit, > Undelegate { pda_seeds: Vec> }, > IncrementAndCommit { increase_by: u64 }, > IncrementAndUndelegate { increase_by: u64 }, > } > > #[derive(BorshDeserialize)] > struct IncreaseCounterPayload { > increase_by: u64, > } > > impl ProgramInstruction { > pub fn unpack(input: &[u8]) -> Result { > // Ensure the input has at least 8 bytes for the variant > if input.len() < 8 { > return Err(ProgramError::InvalidInstructionData); > } > > // Extract the first 8 bytes as variant > let (ix_discriminator, rest) = input.split_at(8); > > // Match instruction discriminator with process and deserialize payload > Ok(match ix_discriminator { > [0, 0, 0, 0, 0, 0, 0, 0] => Self::InitializeCounter, > [1, 0, 0, 0, 0, 0, 0, 0] => { > let payload = IncreaseCounterPayload::try_from_slice(rest)?; > Self::IncreaseCounter { > increase_by: payload.increase_by, > } > } > [2, 0, 0, 0, 0, 0, 0, 0] => Self::Delegate, > [3, 0, 0, 0, 0, 0, 0, 0] => Self::CommitAndUndelegate, > [4, 0, 0, 0, 0, 0, 0, 0] => Self::Commit, > [5, 0, 0, 0, 0, 0, 0, 0] => { > let payload = IncreaseCounterPayload::try_from_slice(rest)?; > Self::IncrementAndCommit { > increase_by: payload.increase_by, > } > } > [6, 0, 0, 0, 0, 0, 0, 0] => { > let payload = IncreaseCounterPayload::try_from_slice(rest)?; > Self::IncrementAndUndelegate { > increase_by: payload.increase_by, > } > } > [196, 28, 41, 206, 48, 37, 51, 167] => { > let pda_seeds: Vec> = Vec::>::try_from_slice(rest)?; > Self::Undelegate { pda_seeds } > } > _ => return Err(ProgramError::InvalidInstructionData), > }) > } > } > ``` > > > [!NOTE] > > > > Your "Undelegate" instruction must have the exact discriminator. It is never > > called by you, instead the validator on the Base Layer will callback with a > > CPI into your program after undelegating your account on ER. > > [⬆️ Back to Top](#code-snippets) > [tab] 2. Delegate > > ### Delegating the Counter PDA > > In order to delegate the counter PDA, and make it writable in an Ephemeral Rollup session, we need to add an instruction which > internally calls the `delegate_account` function. `delegate_account` will CPI to the delegation program, which upon validation will gain ownership of the account. > After this step, an ephemeral validator can start processing transactions on the counter PDA and propose state diff trough the delegation program. > > > [card] [Transaction (Base Layer): Delegate](https://solscan.io/tx/5jUdf5rsfQsbLYAahS9axrnLnEjdbUqtXUmGfgGuS7QqbYJ4FZHgXTNoT1bxPXp7XQu78r8Ebpp1RT2u9V6qsc1r?cluster=devnet) > > > > Inspect transactions details on Solana Explorer > > ```rust theme={null} > use solana_program::{ > account_info::{next_account_info, AccountInfo}, > entrypoint::ProgramResult, > msg, > pubkey::Pubkey, > }; > use ephemeral_rollups_sdk::cpi::{delegate_account, DelegateAccounts, DelegateConfig}; > > // For Base Layer only > // Set specific validator based on ER, see https://docs.magicblock.gg/pages/get-started/how-integrate-your-program/local-setup > pub fn process_delegate(_program_id: &Pubkey, accounts: &[AccountInfo]) -> ProgramResult { > // Get accounts > let account_info_iter = &mut accounts.iter(); > let initializer = next_account_info(account_info_iter)?; > let system_program = next_account_info(account_info_iter)?; > let pda_to_delegate = next_account_info(account_info_iter)?; > let owner_program = next_account_info(account_info_iter)?; > let delegation_buffer = next_account_info(account_info_iter)?; > let delegation_record = next_account_info(account_info_iter)?; > let delegation_metadata = next_account_info(account_info_iter)?; > let delegation_program = next_account_info(account_info_iter)?; > let validator_account = account_info_iter.next(); > > // Optional: client-provided validator or default validator > let validator_pubkey: Option = validator_account.map(|acc_info| acc_info.key.clone()); > > // Prepare counter pda seeds > let seed_1 = b"counter"; > let seed_2 = initializer.key.as_ref(); > let pda_seeds: &[&[u8]] = &[seed_1, seed_2]; > > let delegate_accounts = DelegateAccounts { > payer: initializer, > pda: pda_to_delegate, > owner_program, > buffer: delegation_buffer, > delegation_record, > delegation_metadata, > delegation_program, > system_program, > }; > > let delegate_config = DelegateConfig { > validator: validator_pubkey, // Set delegating ER validator > ..Default::default() > }; > > delegate_account(delegate_accounts, pda_seeds, delegate_config)?; > > Ok(()) > } > ``` > > [⬆️ Back to Top](#code-snippets) > [tab] 3. Commit > > ### Committing while the PDA is delegated > > The ephemeral runtime allows committing the state of the PDA while it is delegated. This is done by building a `MagicIntentBundleBuilder` with the `commit` intent. > > > [card] [Transaction (ER): Commit](https://solscan.io/tx/5GiFGyrnJPkEQbhE8EHVYczoj2RPGe1YSnoq1DzcUHAxpyzMUKtxG2Tc7TLkxtcCHr72ftnvmkAVMfecTaf6TCK8?cluster=custom\&customUrl=https://devnet.magicblock.app) > > > > Inspect transaction details on Solana Explorer > > > [card] [Transaction (Base layer): Commit](https://solscan.io/tx/5fHBADq99LAEBzGoeDXGtN3ut8RBf2s5UhbDM1N6TMTpvADNeYLz8e8vinNWj1VhLhrR7UxFoW7bo2u6pBR3YRjj?cluster=devnet) > > > > Inspect transaction details on Solana Explorer > > ```rust theme={null} > use solana_program::{ > account_info::{next_account_info, AccountInfo}, > entrypoint::ProgramResult, > msg, > program_error::ProgramError, > pubkey::Pubkey, > }; > use ephemeral_rollups_sdk::ephem::{FoldableIntentBuilder, MagicIntentBundleBuilder}; > > // For ER only > pub fn process_commit( > _program_id: &Pubkey, > accounts: &[AccountInfo], > ) -> ProgramResult { > // Get accounts > let account_info_iter = &mut accounts.iter(); > let initializer = next_account_info(account_info_iter)?; > let counter_account = next_account_info(account_info_iter)?; > let magic_program = next_account_info(account_info_iter)?; > let magic_context = next_account_info(account_info_iter)?; > > // Signer should be the same as the initializer > if !initializer.is_signer { > msg!("Initializer {} should be the signer", initializer.key); > return Err(ProgramError::MissingRequiredSignature); > } > > MagicIntentBundleBuilder::new( > initializer.clone(), > magic_context.clone(), > magic_program.clone(), > ) > .commit(&[counter_account.clone()]) > .build_and_invoke()?; > > Ok(()) > } > ``` > > [⬆️ Back to Top](#code-snippets) > [tab] 4. Undelegate > > ### Undelegating the PDA > > Undelegating the PDA is done by building a `MagicIntentBundleBuilder` with the `commit_and_undelegate` intent as part of some instruction. > This commits the latest state and returns ownership of the PDA to the owner program. After undelegating and finalizing the state, the validator will create a callback CPI into `undelegate` on the base layer. > > > [!NOTE] > > > > The undelegation callback discriminator `[196, 28, 41, 206, 48, 37, 51, 167]` > > and its instruction processor must be specified in your program. This > > instruction triggered by Delegation Program reverts account ownership on the > > Base Layer after calling undelegation on ER. > > > > With [`[#ephemeral]`](/pages/ephemeral-rollups-ers/how-to-guide/quickstart#1-write-program) Anchor macro from MagicBlock's Ephemeral Rollup SDK, the undelegation callback discriminator and processor are injected into your program. > > > [card] [Transaction (ER): Undelegate](https://solscan.io/tx/bMN6AhXrGH93Uc6ALibGgjnE39hcnY57mBhYkZ8TRaKxNRvyFaweaQPBmDxPv81cgR47WTTzzhfziTUEgAT8Y5m?cluster=custom\&customUrl=https://devnet.magicblock.app) > > > > Inspect transaction details on Solana Explorer > > > [card] [Transaction (Base layer): Undelegate](https://solscan.io/tx/8JafYWiXmd4CHc2E97WKYnaNPmChZeg8aGYY7UUWaQ7Z54N5WoMcAVivyv2vdn9wKirMkR3y4UcmFPdXYqBtKAa?cluster=devnet) > > > > Inspect transaction details on Solana Explorer > > ```rust theme={null} > use solana_program::{ > account_info::{next_account_info, AccountInfo}, > entrypoint::ProgramResult, > msg, > program_error::ProgramError, > pubkey::Pubkey, > }; > use ephemeral_rollups_sdk::cpi::undelegate_account; > use ephemeral_rollups_sdk::ephem::{FoldableIntentBuilder, MagicIntentBundleBuilder}; > > // For ER only > pub fn process_commit_and_undelegate( > _program_id: &Pubkey, > accounts: &[AccountInfo], > ) -> ProgramResult { > // Get accounts > let account_info_iter = &mut accounts.iter(); > let initializer = next_account_info(account_info_iter)?; > let counter_account = next_account_info(account_info_iter)?; > let magic_program = next_account_info(account_info_iter)?; > let magic_context = next_account_info(account_info_iter)?; > > // Signer should be the same as the initializer > if !initializer.is_signer { > msg!("Initializer {} should be the signer", initializer.key); > return Err(ProgramError::MissingRequiredSignature); > } > > // Commit and undelegate counter_account on ER > MagicIntentBundleBuilder::new( > initializer.clone(), > magic_context.clone(), > magic_program.clone(), > ) > .commit_and_undelegate(&[counter_account.clone()]) > .build_and_invoke()?; > > Ok(()) > } > > // For Base Layer CPI callback > pub fn process_undelegate( > program_id: &Pubkey, > accounts: &[AccountInfo], > pda_seeds: Vec>, > ) -> ProgramResult { > // Get accounts > let account_info_iter = &mut accounts.iter(); > let delegated_pda = next_account_info(account_info_iter)?; > let delegation_buffer = next_account_info(account_info_iter)?; > let initializer = next_account_info(account_info_iter)?; > let system_program = next_account_info(account_info_iter)?; > > // CPI on Solana > undelegate_account( > delegated_pda, > program_id, > delegation_buffer, > initializer, > system_program, > pda_seeds, > )?; > > Ok(()) > } > ``` > > [⬆️ Back to Top](#code-snippets) *** ### Advanced Code Snippets > [tab] Resize PDA > > When resizing a delegated PDA: > > * PDA must have enough lamports to remain rent-exempt for the new account size. > * If additional lamports are needed, the **payer account must be delegated** to provide the difference. > * PDA must be owned by the program, and the transaction must include any signer(s) required for transferring lamports. > * Use `system_instruction::allocate` > > ```rust theme={null} > #[derive(BorshSerialize, BorshDeserialize, Debug)] > pub struct Counter { > pub count: u64, > } > > // Resize counter account > pub fn resize_counter_account( > counter_acc: &AccountInfo, > payer: &AccountInfo, > program_id: &Pubkey, > new_size: usize, > bump: u8, > ) -> ProgramResult { > let rent = Rent::get()?; > let lamports_required = rent.minimum_balance(new_size); > > let current_lamports = counter_acc.lamports(); > if lamports_required > current_lamports { > let lamports_to_add = lamports_required - current_lamports; > invoke_signed( > &system_instruction::transfer( > &payer.key, > &counter_acc.key, > lamports_to_add, > ), > &[payer.clone(), counter_acc.clone()], > &[&[COUNTER_SEED, &[bump]]], > )?; > } > > // Allocate new size > invoke_signed( > &system_instruction::allocate(&counter_acc.key, new_size as u64), > &[counter_acc.clone()], > &[&[COUNTER_SEED, &[bump]]], > )?; > > // Assign back to program > invoke_signed( > &system_instruction::assign(&counter_acc.key, program_id), > &[counter_acc.clone()], > &[&[COUNTER_SEED, &[bump]]], > )?; > > msg!("Counter account resized to {} bytes", new_size); > Ok(()) > } > ``` > > [⬆️ Back to Top](#advanced-code-snippets) > [tab] Magic Router > > Initialize connection with Magic Router before you send transactions dynamically. > > > [!NOTE] > > > > These public RPC endpoints are currently free and supported for development: > > \ > > Magic Router Devnet: [https://devnet-router.magicblock.app](https://devnet-router.magicblock.app) \\ > > Choose your preferred SDK to initialize, send and confirm transactions: > > * `ephemeral-rollups-kit` for `@solana/kit` > * `ephemeral-rollups-sdk` for `@solana/web.js` > > ```typescript Kit theme={null} > import { Connection } from "@magicblock-labs/ephemeral-rollups-kit"; > > // Initialize connection > const connection = await Connection.create( > "https://devnet-router.magicblock.app", > "wss://devnet-router.magicblock.app" > ); > > // ... create transaction > > // Send and confirm transaction > const txHash = await connection.sendAndConfirmTransaction( > transactionMessage, > [userKeypair], > { commitment: "confirmed", skipPreflight: true } > ); > ``` > > ```typescript Web3.js theme={null} > import { sendAndConfirmTransaction } from "@solana/web3.js"; > import { ConnectionMagicRouter } from "@magicblock-labs/ephemeral-rollups-sdk"; > > // Initialize connection > const connection = new ConnectionMagicRouter( > "https://devnet-router.magicblock.app/", > { wsEndpoint: "wss://devnet-router.magicblock.app/" } > ); > > // ... create transaction > > // Send and confirm transaction > const txHash = await sendAndConfirmTransaction(connection, tx, [payer], { > skipPreflight: true, > commitment: "confirmed", > }); > ``` > > [Learn more about Magic Router](/pages/ephemeral-rollups-ers/introduction/magic-router) > > [⬆️ Back to Top](#advanced-code-snippets) > [tab] Magic Action > > Attach one or more instructions that run automatically on the Solana base > layer immediately after an ER commit, scheduled with `MagicIntentBundleBuilder`. > [Learn more about Magic Action](/pages/ephemeral-rollups-ers/magic-actions/overview) > > ```rust theme={null} > use solana_program::{ > account_info::{next_account_info, AccountInfo}, > entrypoint::ProgramResult, > pubkey::Pubkey, > }; > use ephemeral_rollups_sdk::ephem::{CallHandler, MagicIntentBundleBuilder}; > use ephemeral_rollups_sdk::{ActionArgs, ShortAccountMeta}; > > // Runs on the ER. Commits the counter to the base layer and attaches a > // post-commit action (`update_leaderboard`) that the base layer executes > // automatically once the commit lands — both applied in one ER transaction. > pub fn process_commit_with_action( > program_id: &Pubkey, > accounts: &[AccountInfo], > ) -> ProgramResult { > let account_info_iter = &mut accounts.iter(); > let payer = next_account_info(account_info_iter)?; > let counter = next_account_info(account_info_iter)?; > let leaderboard = next_account_info(account_info_iter)?; > let magic_context = next_account_info(account_info_iter)?; > let magic_program = next_account_info(account_info_iter)?; > > // The instruction that runs on the base layer after the commit. > // `args` is your program's own instruction payload (e.g. update_leaderboard). > let action = CallHandler { > destination_program: *program_id, > accounts: vec![ > ShortAccountMeta { pubkey: *leaderboard.key, is_writable: true }, > ShortAccountMeta { pubkey: *counter.key, is_writable: false }, > ], > args: ActionArgs::new(update_leaderboard_instruction_data()), > // Signer that pays the action's fees from its escrow PDA. > escrow_authority: payer.clone(), > compute_units: 200_000, > }; > > // Schedule the commit + post-commit action on magic_context. > MagicIntentBundleBuilder::new( > payer.clone(), > magic_context.clone(), > magic_program.clone(), > ) > .commit(&[counter.clone()]) > .add_post_commit_actions([action]) > .build_and_invoke()?; > > Ok(()) > } > ``` > > [⬆️ Back to Top](#advanced-code-snippets) > [tab] Top-up delegated account > > Top up a delegated account's lamports on the ER side. The transaction is submitted on the **base layer** and uses the Ephemeral SPL Token program to shuttle lamports to the destination's delegated balance via a single-use lamports PDA. > > Common use case: keeping a delegated fee payer funded for a long session. Without a fee payer, an account stops after 10 commits. With a fee payer and `magic_fee_vault`, it can keep committing, and the payer starts paying live commit fees on commit 26. > > Notes: > > * Generate a fresh 32-byte salt per top-up via `crypto.getRandomValues` — re-using a salt collides with an existing PDA. > * Submit to the base-layer RPC, not the ER. > * The destination must already be delegated. > > ```typescript theme={null} > import { > Connection, > Keypair, > PublicKey, > Transaction, > sendAndConfirmTransaction, > } from "@solana/web3.js"; > import { > lamportsDelegatedTransferIx, > deriveLamportsPda, > } from "@magicblock-labs/ephemeral-rollups-sdk"; > > /** > * Top up a delegated account with lamports. > * > * The transaction is submitted on the BASE LAYER. The Ephemeral SPL Token > * program creates a single-use lamports PDA, funds it from the payer, and > * delegates it so the ER credits the destination's delegated balance. > */ > async function topUpDelegatedAccount( > connection: Connection, // base-layer connection > payer: Keypair, > destination: PublicKey, // delegated account to top up > amountLamports: bigint, > ) { > // Generate a fresh 32-byte salt per top-up. > // Re-using a salt collides with an existing lamports PDA and the call fails. > const salt = crypto.getRandomValues(new Uint8Array(32)); > > const [lamportsPda] = deriveLamportsPda(payer.publicKey, destination, salt); > > const ix = await lamportsDelegatedTransferIx( > payer.publicKey, > destination, > amountLamports, > salt, > ); > > const tx = new Transaction().add(ix); > tx.feePayer = payer.publicKey; > > // CRITICAL: send to the base-layer RPC, not the ER. > const sig = await sendAndConfirmTransaction(connection, tx, [payer], { > commitment: "confirmed", > skipPreflight: true, > }); > > return { sig, lamportsPda }; > } > ``` > > [⬆️ Back to Top](#advanced-code-snippets) > [tab] On-Curve Delegation > > ### Quick Access > > > [card] [GitHub](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/oncurve-delegation/client) > > > > On-Curve Delegation > > Required signers for delegating an on-curve account: > > 1. On-curve account to be delegated > 2. Fee payer > > Required instructions for delegating on-curve accounts: > > 1. Assign System Account to Delegation Program > 2. Delegate to Delegation Program > > ```typescript Kit theme={null} > // Create assign instruction > // The on-curve account must sign this instruction to change its owner > const accountSigner = await cryptoKeyPairToTransactionSigner(userKeypair); > const delegationProgramAddress = address(DELEGATION_PROGRAM_ID.toString()); > const assignInstruction = getAssignInstruction({ > account: accountSigner, > programAddress: delegationProgramAddress, > }); > > // Create delegate instruction > const delegateInstruction = await createDelegateInstruction({ > payer: feePayerAddress, > delegatedAccount: userAddress, > ownerProgram: ownerProgramAddress, > validator: validatorAddress, > }); > > // Prepare transaction > const transactionMessage = pipe( > createTransactionMessage({ version: 0 }), > (tx) => setTransactionMessageFeePayer(feePayerAddress, tx), > (tx) => > appendTransactionMessageInstructions( > [assignInstruction, delegateInstruction], > tx > ) > ); > // Send and confirm transaction (fee payer need to sign, on-curve account cannot be signer since delegated) > const txHash = await connection.sendAndConfirmTransaction( > transactionMessage, > [userKeypair, feePayerKeypair], > { commitment: "confirmed", skipPreflight: true } > ); > ``` > > ```typescript Web3.js theme={null} > // Create assign instruction > const assignInstruction = SystemProgram.assign({ > accountPubkey: userPubkey, > programId: DELEGATION_PROGRAM_ID, > }); > > // Create delegate instruction > const delegateInstruction = createDelegateInstruction({ > payer: feePayerKeypair.publicKey, > delegatedAccount: userPubkey, > ownerProgram: ownerProgram, > validator: validator, > }); > > // Create and send transaction (fee payer need to sign, on-curve account cannot be signer since delegated) > const tx = new Transaction().add(assignInstruction, delegateInstruction); > tx.feePayer = feePayerKeypair.publicKey; > const txSignature = await sendAndConfirmTransaction( > connectionBaseLayer, > tx, > [userKeypair, feePayerKeypair], > { > skipPreflight: true, > } > ); > ``` > > Direct commit and undelegate through Magic Program only. > > ```typescript Kit theme={null} > // Create commit and undelegate instruction > const commitAndUndelegateInstruction = createCommitAndUndelegateInstruction( > userAddress, > [userAddress] > ); > > // Prepare transaction > const transactionMessage = pipe( > createTransactionMessage({ version: 0 }), > (tx) => setTransactionMessageFeePayer(feePayerAddress, tx), > (tx) => > appendTransactionMessageInstructions([commitAndUndelegateInstruction], tx) > ); > > // Send and confirm transaction on ephemeral connection > const txHash = await ephemeralConnection.sendAndConfirmTransaction( > transactionMessage, > [userKeypair, feePayerKeypair], > { commitment: "confirmed", skipPreflight: true } > ); > ``` > > ```typescript Web3.js theme={null} > // Create commit and undelegate instruction > const commitAndUndelegateInstruction = createCommitAndUndelegateInstruction( > userPubkey, > [userPubkey] > ); > > // Send and confirm transaction on ephemeral connection > const tx = new Transaction().add(commitAndUndelegateInstruction); > tx.feePayer = feePayerKeypair.publicKey; > const txSignature = await sendAndConfirmTransaction( > ephemeralConnection, > tx, > [userKeypair, feePayerKeypair], > { > skipPreflight: true, > } > ); > ``` > > [⬆️ Back to Top](#advanced-code-snippets) > [tab] Delegation Actions > > ### Quick Access > > > [card] [Delegation Actions Example](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/delegation-actions/anchor) > > > > Explore reference implementation on GitHub > > Attach instructions to a delegation that the ER validator runs automatically > inside the rollup, right after the account is delegated — no extra transaction: > > * Build the action(s) as standard `Instruction`s and convert them to the > compact payload with `.cleartext()` (public) — encrypted actions are built > off-chain by a client holding the validator key. > * The base-layer delegation program stores the payload in the delegation > record; the ER validator executes it once the account lands in the rollup. > * CPI with `delegate_account_with_actions` (same `DelegateAccounts` / > `DelegateConfig` as a normal delegation, plus the actions payload). > > ```rust theme={null} > use solana_program::{ > account_info::{next_account_info, AccountInfo}, > entrypoint::ProgramResult, > instruction::{AccountMeta, Instruction}, > pubkey::Pubkey, > }; > use ephemeral_rollups_sdk::cpi::{ > delegate_account_with_actions, DelegateAccounts, DelegateConfig, > }; > use ephemeral_rollups_sdk::dlp_api::compact::ClearText; > > // Delegate a PDA AND attach a post-delegation action. The action is stored in the > // delegation record on the base layer and executed automatically by the ER > // validator inside the rollup, right after the account is delegated — no extra > // transaction. Here the action is a self-CPI back into the program's increment. > pub fn process_delegate_with_actions( > _program_id: &Pubkey, > accounts: &[AccountInfo], > ) -> ProgramResult { > let account_info_iter = &mut accounts.iter(); > let initializer = next_account_info(account_info_iter)?; > let system_program = next_account_info(account_info_iter)?; > let pda_to_delegate = next_account_info(account_info_iter)?; > let owner_program = next_account_info(account_info_iter)?; > let delegation_buffer = next_account_info(account_info_iter)?; > let delegation_record = next_account_info(account_info_iter)?; > let delegation_metadata = next_account_info(account_info_iter)?; > let delegation_program = next_account_info(account_info_iter)?; > let validator_account = account_info_iter.next(); > > let pda_seeds: &[&[u8]] = &[b"counter", initializer.key.as_ref()]; > > // The instruction the ER validator runs post-delegation, inside the rollup. > // `data` is your program's own instruction payload (e.g. the increment ix). > let increment_action = Instruction { > program_id: *owner_program.key, > accounts: vec![AccountMeta::new(*pda_to_delegate.key, false)], > data: increment_instruction_data(), > }; > > // Convert to the compact, cleartext post-delegation actions payload. > // (Use `cleartext` for public actions; encrypted actions are built off-chain > // by a client that holds the validator key.) > let actions = vec![increment_action].cleartext(); > > let delegate_accounts = DelegateAccounts { > payer: initializer, > pda: pda_to_delegate, > owner_program, > buffer: delegation_buffer, > delegation_record, > delegation_metadata, > delegation_program, > system_program, > }; > > let delegate_config = DelegateConfig { > validator: validator_account.map(|acc| *acc.key), > ..Default::default() > }; > > delegate_account_with_actions( > delegate_accounts, > pda_seeds, > delegate_config, > actions, > // No extra signers are required by the increment action. > &[], > )?; > > Ok(()) > } > ``` > > [⬆️ Back to Top](#advanced-code-snippets) *** ## Solana Explorer Get insights about your transactions and accounts on Solana: > [card] [Solana Explorer](https://explorer.solana.com/) > > Official Solana Explorer > [card] [Solscan](https://solscan.io/) > > Explore Solana Blockchain ## Solana RPC Providers Send transactions and requests through existing RPC providers: > [card] [Solana](https://solana.com/docs/references/clusters#on-a-high-level) > > Free Public Nodes > [card] [Helius](https://www.helius.dev/solana-rpc-nodes) > > Free Shared Nodes > [card] [Triton](https://triton.one/solana) > > Dedicated High-Performance Nodes ## Solana Validator Dashboard Find real-time updates on Solana's validator infrastructure: > [card] [Solana Beach](https://solanabeach.io/) > > Get Validator Insights > [card] [Validators App](https://www.validators.app/) > > Discover Validator Metrics ## Server Status Subscribe to Solana's and MagicBlock's server status: > [card] [Solana Status](https://status.solana.com/) > > Subscribe to Solana Server Updates > [card] [MagicBlock Status](/pages/overview/additional-information/system-status) > > Subscribe to MagicBlock Server Status *** # Test Your Program Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/how-to-guide/rust-tests Learn how to test a simple Rust program *** ### Quick Access If you prefer to dive straight into the code: > [card] [GitHub](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/counter/native-rust/tests) > > Tests for Rust Counter > [card] [GitHub](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/counter/pinocchio/tests) > > Tests for Pinocchio Counter > [card] [Guide](/pages/ephemeral-rollups-ers/how-to-guide/local-development) > > Local Development *** ## Step-By-Step Guide Build valid transactions that calls your program instructions for delegation and undelegation. The complete test for this project can be found in the [Typescript Test Script](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/counter/native-rust/tests). **1. [Import SDK and initialize Connection](#1-connection)** Set up connection and accounts **2. [Delegate PDA on Base Layer](#2-delegate)** Test CPI hook to delegate state account on Base Layer > [!NOTE] > > These public validators are supported for development. Make sure to add the > specific ER validator in your delegation instruction: > > **Mainnet** > >
    >
  • > Asia (as.magicblock.app): > `MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57` >
  • > >
  • > EU (eu.magicblock.app): > `MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e` >
  • > >
  • > US (us.magicblock.app): > `MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd` >
  • > >
  • > TEE (mainnet-tee.magicblock.app): > `MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo` >
  • > >
  • > Asia Tokyo (as-tyo.magicblock.app): > `MSHuBweMkNp4yPLDkPLA8bLRHbDmURWjYzsxrcBjix8` >
  • > >
  • > South America (sa.magicblock.app): > `MSARyz2yVTkqiYQWWgaEtUKug7oCF7PphE9GjEYHtDh` >
  • >
> > **Devnet** > >
    >
  • > Asia (devnet-as.magicblock.app): > `MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57` >
  • > >
  • > EU (devnet-eu.magicblock.app): > `MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e` >
  • > >
  • > US (devnet-us.magicblock.app): > `MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd` >
  • > >
  • > TEE (devnet-tee.magicblock.app): > `MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo` >
  • >
> > **Localnet** > >
    >
  • > Local ER (localhost:7799): > `mAGicPQYBMvcYveUZA5F5UNNwyHvfYh5xkLS2Fr1mev` >
  • >
**3. [Commit PDA on ER](#3-commit)** Test CPI hook to commit state account on ER **4. [Undelegate PDA on ER](#4-undelegate)** Test CPI hook to undelegate state account on ER *** ## Counter Example The following software packages may be required, other versions may also be compatible: | Software | Version | Installation Guide | | - | - | - | | **Solana** | 3.1.9 | [Install Solana](https://docs.anza.xyz/cli/install) | | **Rust** | 1.89.0 | [Install Rust](https://www.rust-lang.org/tools/install) | | **Node** | 24.10.0 | [Install Node](https://nodejs.org/en/download/current) | ### Code Snippets > [tab] 1. Connection > > ### Import SDK and create Connection > > Import relevant libraries `@magicblock-labs/ephemeral-rollups-sdk` or `@magicblock-labs/ephemeral-rollups-kit`. Initialize connection before testing and sending transactions. > > ```bash kit theme={null} > yarn add @magicblock-labs/ephemeral-rollups-kit@latest > ``` > > ```bash web3.js theme={null} > yarn add @magicblock-labs/ephemeral-rollups-sdk@latest > ``` > > > [!NOTE] > > > > These public RPC endpoints are currently free and supported for development: > > \ > > Magic Router Devnet: [https://devnet-router.magicblock.app](https://devnet-router.magicblock.app) \\ > > > > Solana Devnet: [https://api.devnet.solana.com](https://api.devnet.solana.com) \\ > > > > ER Devnet (Asia): [https://devnet-as.magicblock.app](https://devnet-as.magicblock.app) \\ > > > > ER Devnet (EU): [https://devnet-eu.magicblock.app](https://devnet-eu.magicblock.app) \\ > > > > ER Devnet (US): [https://devnet-us.magicblock.app](https://devnet-us.magicblock.app) \\ > > > > TEE Devnet: [https://devnet-tee.magicblock.app/](https://devnet-tee.magicblock.app/) \\ > > > > Find out more details > > [here](/pages/ephemeral-rollups-ers/how-to-guide/local-development) > > . > > ```typescript Kit theme={null} > import { > Instruction, > getAddressEncoder, > getProgramDerivedAddress, > AccountRole, > createKeyPairFromBytes, > getAddressFromPublicKey, > address, > createTransactionMessage, > appendTransactionMessageInstructions, > pipe, > setTransactionMessageFeePayer, > } from "@solana/kit"; > > import { > Connection, > DELEGATION_PROGRAM_ID, > delegationRecordPdaFromDelegatedAccount, > delegationMetadataPdaFromDelegatedAccount, > delegateBufferPdaFromDelegatedAccountAndOwnerProgram, > MAGIC_CONTEXT_ID, > MAGIC_PROGRAM_ID, > } from "@magicblock-labs/ephemeral-rollups-kit"; > > // Set up a base and ephemeral connection (alternatively use router, see Magic Router) > const connection = await Connection.create( > process.env.PROVIDER_ENDPOINT || "https://api.devnet.solana.com", > process.env.WS_ENDPOINT || "wss://api.devnet.solana.com" > ); > const ephemeralConnection = await Connection.create( > process.env.EPHEMERAL_PROVIDER_ENDPOINT || "https://devnet-as.magicblock.app", > process.env.EPHEMERAL_WS_ENDPOINT || "wss://devnet-as.magicblock.app" > ); > > // Prepare user > const userKeypair = await initializeSolSignerKeypair(); > const userPubkey = await getAddressFromPublicKey(userKeypair.publicKey); > > // Get PDA > const addressEncoder = getAddressEncoder(); > const [counterPda, bump] = await getProgramDerivedAddress({ > programAddress: PROGRAM_ID, > seeds: [Buffer.from("counter"), addressEncoder.encode(userPubkey)], > }); > ``` > > ```typescript Web3.js theme={null} > import { > Keypair, > PublicKey, > SystemProgram, > Transaction, > TransactionInstruction, > Connection, > sendAndConfirmTransaction, > } from "@solana/web3.js"; > > import { > DELEGATION_PROGRAM_ID, > delegationRecordPdaFromDelegatedAccount, > delegationMetadataPdaFromDelegatedAccount, > delegateBufferPdaFromDelegatedAccountAndOwnerProgram, > MAGIC_CONTEXT_ID, > MAGIC_PROGRAM_ID, > GetCommitmentSignature, > } from "@magicblock-labs/ephemeral-rollups-sdk"; > > // Set up a base and ephemeral connection (alternatively use router, see Magic Router) > const connectionBaseLayer = new Connection( > process.env.PROVIDER_ENDPOINT || "https://api.devnet.solana.com", > { wsEndpoint: process.env.WS_ENDPOINT || "wss://api.devnet.solana.com" } > ); > const connectionEphemeralRollup = new Connection( > process.env.EPHEMERAL_PROVIDER_ENDPOINT || > "https://devnet-as.magicblock.app/", > { > wsEndpoint: > process.env.EPHEMERAL_WS_ENDPOINT || "wss://devnet-as.magicblock.app/", > } > ); > > // Create user keypair and airdrop SOL if needed > const userKeypair = initializeSolSignerKeypair(); > > // Get pda > let [counterPda, bump] = PublicKey.findProgramAddressSync( > [Buffer.from("counter"), userKeypair.publicKey.toBuffer()], > PROGRAM_ID > ); > ``` > > [⬆️ Back to Top](#code-snippets) > [tab] 2. Delegate > > ### Test `delegation` transaction > > Create a instruction with the right order and attributes of accounts, and the instruction discriminator for `delegation` of your program. Send the transaction with the instruction to Base Layer (Solana) network. > > > [card] [Transaction (Base Layer): Delegate](https://solscan.io/tx/5jUdf5rsfQsbLYAahS9axrnLnEjdbUqtXUmGfgGuS7QqbYJ4FZHgXTNoT1bxPXp7XQu78r8Ebpp1RT2u9V6qsc1r?cluster=devnet) > > > > Inspect transactions details on Solana Explorer > > ```typescript Kit theme={null} > // "Delegate" transaction > > // Add local validator identity to the remaining accounts if running on localnet > const remainingAccounts = > connection.clusterUrlHttp.includes("localhost") || > connection.clusterUrlHttp.includes("127.0.0.1") > ? [ > { > address: address("mAGicPQYBMvcYveUZA5F5UNNwyHvfYh5xkLS2Fr1mev"), > role: AccountRole.READONLY, > }, > ] > : []; > const accounts = [ > { address: userPubkey, role: AccountRole.WRITABLE_SIGNER }, > { address: SYSTEM_PROGRAM_ADDRESS, role: AccountRole.READONLY }, > { address: counterPda, role: AccountRole.WRITABLE }, > { address: PROGRAM_ID, role: AccountRole.READONLY }, > { > address: await delegateBufferPdaFromDelegatedAccountAndOwnerProgram( > counterPda, > PROGRAM_ID > ), > role: AccountRole.WRITABLE, > }, > { > address: await delegationRecordPdaFromDelegatedAccount(counterPda), > role: AccountRole.WRITABLE, > }, > { > address: await delegationMetadataPdaFromDelegatedAccount(counterPda), > role: AccountRole.WRITABLE, > }, > { address: DELEGATION_PROGRAM_ID, role: AccountRole.READONLY }, > ...remainingAccounts, > ]; > const serializedInstructionData = Buffer.from( > CounterInstruction.Delegate, > "hex" > ); > const delegateIx: Instruction = { > accounts, > programAddress: PROGRAM_ID, > data: serializedInstructionData, > }; > const transactionMessage = pipe( > createTransactionMessage({ version: 0 }), > (tx) => setTransactionMessageFeePayer(userPubkey, tx), > (tx) => appendTransactionMessageInstructions([delegateIx], tx) > ); > > // Send and confirm transaction on base layer > const txHash = await connection.sendAndConfirmTransaction( > transactionMessage, > [userKeypair], > { commitment: "confirmed", skipPreflight: true } > ); > ``` > > ```typescript Web3.js theme={null} > // "Delegate" transaction > > // Add local validator identity to the remaining accounts if running on localnet > const remainingAccounts = > connectionEphemeralRollup.rpcEndpoint.includes("localhost") || > connectionEphemeralRollup.rpcEndpoint.includes("127.0.0.1") > ? [ > { > pubkey: new PublicKey("mAGicPQYBMvcYveUZA5F5UNNwyHvfYh5xkLS2Fr1mev"), > isSigner: false, > isWritable: false, > }, > ] > : []; > > const tx = new web3.Transaction(); > const keys = [ > // Initializer > { > pubkey: userKeypair.publicKey, > isSigner: true, > isWritable: true, > }, > // System Program > { > pubkey: web3.SystemProgram.programId, > isSigner: false, > isWritable: false, > }, > // Counter Account > { > pubkey: counterPda, > isSigner: false, > isWritable: true, > }, > // Owner Program > { > pubkey: PROGRAM_ID, > isSigner: false, > isWritable: false, > }, > // Delegation Buffer > { > pubkey: getDelegationBufferPda(counterPda, PROGRAM_ID), > isSigner: false, > isWritable: true, > }, > // Delegation Record > { > pubkey: getDelegationRecordPda(counterPda), > isSigner: false, > isWritable: true, > }, > // Delegation Metadata > { > pubkey: getDelegationMetadataPda(counterPda), > isSigner: false, > isWritable: true, > }, > // Delegation Program > { > pubkey: DELEGATION_PROGRAM_ID, > isSigner: false, > isWritable: false, > }, > // ER Validator > ...remainingAccounts, > ]; > const serializedInstructionData = Buffer.from( > CounterInstruction.Delegate, > "hex" > ); > const delegateIx = new web3.TransactionInstruction({ > keys: keys, > programId: PROGRAM_ID, > data: serializedInstructionData, > }); > tx.add(delegateIx); > > // Send and confirm transaction to Base Layer > const txHash = await sendAndConfirmTransaction( > connectionBaseLayer, > tx, > [userKeypair], > { > skipPreflight: true, > commitment: "confirmed", > } > ); > ``` > > [⬆️ Back to Top](#code-snippets) > [tab] 3. Commit > > ### Test `commit` transaction > > Create a instruction with the right order and attributes of accounts, and the instruction discriminator for `commit` of your program. Send the transaction with the instruction to ER network. > > > [card] [Transaction (ER): Commit](https://solscan.io/tx/5GiFGyrnJPkEQbhE8EHVYczoj2RPGe1YSnoq1DzcUHAxpyzMUKtxG2Tc7TLkxtcCHr72ftnvmkAVMfecTaf6TCK8?cluster=custom\&customUrl=https://devnet.magicblock.app) > > > > Inspect transaction details on Solana Explorer > > > [card] [Transaction (Base layer): Commit](https://solscan.io/tx/5fHBADq99LAEBzGoeDXGtN3ut8RBf2s5UhbDM1N6TMTpvADNeYLz8e8vinNWj1VhLhrR7UxFoW7bo2u6pBR3YRjj?cluster=devnet) > > > > Inspect transaction details on Solana Explorer > > ```typescript Kit theme={null} > // "Commit" transaction > > const accounts = [ > { address: userPubkey, role: AccountRole.WRITABLE_SIGNER }, > { address: counterPda, role: AccountRole.WRITABLE }, > { address: address(MAGIC_PROGRAM_ID.toString()), role: AccountRole.READONLY }, > { address: address(MAGIC_CONTEXT_ID.toString()), role: AccountRole.WRITABLE }, > ]; > const serializedInstructionData = Buffer.from(CounterInstruction.Commit, "hex"); > const commitIx: Instruction = { > accounts, > programAddress: PROGRAM_ID, > data: serializedInstructionData, > }; > const transactionMessage = pipe( > createTransactionMessage({ version: 0 }), > (tx) => setTransactionMessageFeePayer(userPubkey, tx), > (tx) => appendTransactionMessageInstructions([commitIx], tx) > ); > > // Send and confirm transaction on ER > const txHash = await ephemeralConnection.sendAndConfirmTransaction( > transactionMessage, > [userKeypair], > { commitment: "confirmed", skipPreflight: true } > ); > ``` > > ```typescript Web3.js theme={null} > // "Commit" transaction > > const tx = new web3.Transaction(); > const keys = [ > // Initializer > { > pubkey: userKeypair.publicKey, > isSigner: true, > isWritable: true, > }, > // Counter Account > { > pubkey: counterPda, > isSigner: false, > isWritable: true, > }, > // Magic Program > { > pubkey: MAGIC_PROGRAM_ID, > isSigner: false, > isWritable: false, > }, > // Magic Context > { > pubkey: MAGIC_CONTEXT_ID, > isSigner: false, > isWritable: true, > }, > ]; > const serializedInstructionData = Buffer.from(CounterInstruction.Commit, "hex"); > const commitIx = new web3.TransactionInstruction({ > keys: keys, > programId: PROGRAM_ID, > data: serializedInstructionData, > }); > tx.add(commitIx); > > // Send and confirm transaction to ER > const txHash = await sendAndConfirmTransaction( > connectionEphemeralRollup, > tx, > [userKeypair], > { > skipPreflight: true, > commitment: "confirmed", > } > ); > ``` > > [⬆️ Back to Top](#code-snippets) > [tab] 4. Undelegate > > ### Test `undelegation` transaction > > Create a instruction with the right order and attributes of accounts, and the instruction discriminator for `undelegation` of your program. Send the transaction with the instruction to ER network. > > > [card] [Transaction (ER): Undelegate](https://solscan.io/tx/bMN6AhXrGH93Uc6ALibGgjnE39hcnY57mBhYkZ8TRaKxNRvyFaweaQPBmDxPv81cgR47WTTzzhfziTUEgAT8Y5m?cluster=custom\&customUrl=https://devnet.magicblock.app) > > > > Inspect transaction details on Solana Explorer > > > [card] [Transaction (Base layer): Undelegate](https://solscan.io/tx/8JafYWiXmd4CHc2E97WKYnaNPmChZeg8aGYY7UUWaQ7Z54N5WoMcAVivyv2vdn9wKirMkR3y4UcmFPdXYqBtKAa?cluster=devnet) > > > > Inspect transaction details on Solana Explorer > > ```typescript Kit theme={null} > // "Undelegate" transaction > > const accounts = [ > { address: userPubkey, role: AccountRole.WRITABLE_SIGNER }, > { address: counterPda, role: AccountRole.WRITABLE }, > { address: address(MAGIC_PROGRAM_ID.toString()), role: AccountRole.READONLY }, > { address: address(MAGIC_CONTEXT_ID.toString()), role: AccountRole.WRITABLE }, > ]; > const serializedInstructionData = Buffer.from( > CounterInstruction.CommitAndUndelegate, > "hex" > ); > const undelegateIx: Instruction = { > accounts, > programAddress: PROGRAM_ID, > data: serializedInstructionData, > }; > const transactionMessage = pipe( > createTransactionMessage({ version: 0 }), > (tx) => setTransactionMessageFeePayer(userPubkey, tx), > (tx) => appendTransactionMessageInstructions([undelegateIx], tx) > ); > > // Send and confirm transaction on ER > const txHash = await ephemeralConnection.sendAndConfirmTransaction( > transactionMessage, > [userKeypair], > { commitment: "confirmed", skipPreflight: true } > ); > ``` > > ```typescript Web3.js theme={null} > // "Undelegate" transaction > > const tx = new web3.Transaction(); > const keys = [ > // Initializer > { > pubkey: userKeypair.publicKey, > isSigner: true, > isWritable: true, > }, > // Counter Account > { > pubkey: counterPda, > isSigner: false, > isWritable: true, > }, > // Magic Program > { > pubkey: MAGIC_PROGRAM_ID, > isSigner: false, > isWritable: false, > }, > // Magic Context > { > pubkey: MAGIC_CONTEXT_ID, > isSigner: false, > isWritable: true, > }, > ]; > const serializedInstructionData = Buffer.from( > CounterInstruction.CommitAndUndelegate, > "hex" > ); > const undelegateIx = new web3.TransactionInstruction({ > keys: keys, > programId: PROGRAM_ID, > data: serializedInstructionData, > }); > tx.add(undelegateIx); > > // Send and confirm transaction to ER. Afterwards CPI callback will be triggered to "Undelegate" instruction of your program on the Base Layer. > const txHash = await sendAndConfirmTransaction( > connectionEphemeralRollup, > tx, > [userKeypair], > { > skipPreflight: true, > commitment: "confirmed", > } > ); > ``` > > [⬆️ Back to Top](#code-snippets) *** ## Solana Explorer Get insights about your transactions and accounts on Solana: > [card] [Solana Explorer](https://explorer.solana.com/) > > Official Solana Explorer > [card] [Solscan](https://solscan.io/) > > Explore Solana Blockchain ## Solana RPC Providers Send transactions and requests through existing RPC providers: > [card] [Solana](https://solana.com/docs/references/clusters#on-a-high-level) > > Free Public Nodes > [card] [Helius](https://www.helius.dev/solana-rpc-nodes) > > Free Shared Nodes > [card] [Triton](https://triton.one/solana) > > Dedicated High-Performance Nodes ## Solana Validator Dashboard Find real-time updates on Solana's validator infrastructure: > [card] [Solana Beach](https://solanabeach.io/) > > Get Validator Insights > [card] [Validators App](https://www.validators.app/) > > Discover Validator Metrics ## Server Status Subscribe to Solana's and MagicBlock's server status: > [card] [Solana Status](https://status.solana.com/) > > Subscribe to Solana Server Updates > [card] [MagicBlock Status](/pages/overview/additional-information/system-status) > > Subscribe to MagicBlock Server Status *** # Ephemeral Accounts Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/introduction/ephemeral-accounts Create, resize, and close accounts that live entirely on the Ephemeral Rollup. Ephemeral accounts are accounts that exist only within the Ephemeral Rollup. A **sponsor** account (which is delegated to the ER) pays rent on behalf of ephemeral accounts at **32 lamports/byte** — 109x cheaper than Solana's base rent. **Key properties:** * Born, live, and die entirely on the ER * Owned by the calling program (inferred from CPI context) * Funded by a sponsor account's lamports * Can be created, resized, and closed *** ## The `#[ephemeral_accounts]` Macro This proc-macro attribute goes on an Anchor `Accounts` struct. It recognizes two custom markers inside `#[account(...)]`: | Marker | Purpose | | - | - | | `sponsor` | Marks the account that pays rent for ephemeral accounts | | `eph` | Marks an account as ephemeral (ER-only) | ### Validation Rules * At least one `sponsor` is required if any `eph` fields exist * Only **one** `sponsor` is allowed per struct * `eph` cannot be combined with `init` or `init_if_needed` (use the generated methods instead) * If the sponsor is a PDA (not a `Signer`), it must have `seeds` for PDA signing ### Generated Methods For a field named `conversation`, the macro generates: | Method | Signature | Description | | - | - | - | | `create_ephemeral_conversation` | `(data_len: u32) -> Result<()>` | Creates the ephemeral account | | `init_if_needed_ephemeral_conversation` | `(data_len: u32) -> Result<()>` | Creates only if `data_len == 0` | | `resize_ephemeral_conversation` | `(new_data_len: u32) -> Result<()>` | Grows or shrinks the account | | `close_ephemeral_conversation` | `() -> Result<()>` | Closes account, refunds rent to sponsor | *** ## Signing Requirements * **Sponsor**: Must be a signer for all operations (create, resize, close) * **Ephemeral**: Must be a signer **only on create** (prevents pubkey squatting). Not required for resize or close. * For PDA accounts, the macro auto-derives signer seeds via `find_program_address` *** ## Rent Model ```rust theme={null} pub const EPHEMERAL_RENT_PER_BYTE: u64 = 32; const ACCOUNT_OVERHEAD: u32 = 60; // rent = (data_len + 60) * 32 pub const fn rent(data_len: u32) -> u64 { (data_len as u64 + ACCOUNT_OVERHEAD as u64) * EPHEMERAL_RENT_PER_BYTE } ``` * **Growing**: sponsor pays additional rent to vault * **Shrinking**: vault refunds excess rent to sponsor * **Close**: all rent refunded from vault to sponsor *** ## Create an Ephemeral Account ```rust theme={null} use ephemeral_rollups_sdk::anchor::ephemeral_accounts; pub fn create_conversation(ctx: Context) -> Result<()> { ctx.accounts .create_ephemeral_conversation((8 + Conversation::space_for_message_count(0)) as u32)?; let conversation = Conversation { handle_owner: ctx.accounts.profile_owner.handle.clone(), handle_other: ctx.accounts.profile_other.handle.clone(), bump: ctx.bumps.conversation, messages: Vec::new(), }; let mut data = ctx.accounts.conversation.try_borrow_mut_data()?; conversation.try_serialize(&mut &mut data[..])?; Ok(()) } #[ephemeral_accounts] #[derive(Accounts)] pub struct CreateConversation<'info> { #[account(mut)] pub authority: Signer<'info>, #[account( mut, sponsor, seeds = [b"profile", profile_owner.handle.as_bytes()], bump = profile_owner.bump, has_one = authority )] pub profile_owner: Account<'info, Profile>, #[account( seeds = [b"profile", profile_other.handle.as_bytes()], bump = profile_other.bump, )] pub profile_other: Account<'info, Profile>, /// CHECK: Ephemeral conversation PDA sponsored by the profile. #[account( mut, eph, seeds = [b"conversation", profile_owner.handle.as_bytes(), profile_other.handle.as_bytes()], bump )] pub conversation: AccountInfo<'info>, // vault and magic_program are auto-injected by the macro } ``` > [!WARNING] > > After calling `create_ephemeral_*`, you must manually serialize your data struct into the raw account data. The macro allocates space but does not initialize the data. *** ## Resize an Ephemeral Account ```rust theme={null} pub fn extend_conversation( ctx: Context, additional_messages: u32, ) -> Result<()> { let current_capacity = Conversation::message_capacity(ctx.accounts.conversation.to_account_info().data_len()); let new_capacity = current_capacity + additional_messages as usize; ctx.accounts.resize_ephemeral_conversation( (8 + Conversation::space_for_message_count(new_capacity)) as u32, )?; Ok(()) } #[ephemeral_accounts] #[derive(Accounts)] pub struct ExtendConversation<'info> { #[account(mut)] pub authority: Signer<'info>, #[account(mut, sponsor, seeds = [...], bump = ..., has_one = authority)] pub profile_sender: Account<'info, Profile>, #[account(seeds = [...], bump = ...)] pub profile_other: Account<'info, Profile>, /// CHECK: Ephemeral conversation PDA #[account(mut, eph, seeds = [...], bump)] pub conversation: AccountInfo<'info>, } ``` *** ## Close an Ephemeral Account ```rust theme={null} pub fn close_conversation(ctx: Context) -> Result<()> { let profile = &mut ctx.accounts.profile_owner; profile.active_conversation_count = profile .active_conversation_count .checked_sub(1) .ok_or(ChatError::ConversationCountUnderflow)?; ctx.accounts.close_ephemeral_conversation()?; Ok(()) } #[ephemeral_accounts] #[derive(Accounts)] pub struct CloseConversation<'info> { #[account(mut)] pub authority: Signer<'info>, #[account(mut, sponsor, seeds = [...], bump = ..., has_one = authority)] pub profile_owner: Account<'info, Profile>, #[account(seeds = [...], bump = ...)] pub profile_other: Account<'info, Profile>, /// CHECK: Ephemeral conversation PDA #[account(mut, eph, seeds = [...], bump)] pub conversation: AccountInfo<'info>, } ``` *** ## Using a Wallet as Sponsor A `Signer` can be used directly as the sponsor instead of a PDA: ```rust theme={null} #[ephemeral_accounts] #[derive(Accounts)] pub struct CreateGame<'info> { #[account(mut, sponsor)] pub payer: Signer<'info>, /// CHECK: Ephemeral PDA #[account(mut, eph, seeds = [b"game", payer.key().as_ref()], bump)] pub game_state: AccountInfo<'info>, } ``` *** ## TypeScript Client Usage All ephemeral account operations are sent to the **ER connection**, not the base layer: ```typescript theme={null} // Create await erProgram.methods .createConversation() .accounts({ authority: userA.publicKey, profileOwner: profileAPda, profileOther: profileBPda, conversation: conversationPda, systemProgram: SystemProgram.programId, }) .rpc(); // Resize await erProgram.methods .extendConversation(5) .accounts({ authority: userA.publicKey, profileSender: profileAPda, profileOther: profileBPda, }) .rpc(); // Close await erProgram.methods .closeConversation() .accounts({ authority: userA.publicKey, profileOwner: profileAPda, profileOther: profileBPda, conversation: conversationPda, }) .rpc(); ``` *** ## Common Gotchas > [accordion] eph fields must use AccountInfo, not Account > > `eph` fields must use `AccountInfo<'info>`, not `Account<'info, T>`. The account doesn't exist yet at validation time, so Anchor cannot deserialize it. > [accordion] Manual serialization is required after create > > After calling `create_ephemeral_*`, you must serialize your data struct into the raw account data yourself. The macro allocates space but does not write any data. > [accordion] Cannot combine eph with init > > The macro enforces this at compile time. Use the generated `create_ephemeral_*` method instead of Anchor's `init` constraint. > [accordion] Sponsor must be delegated first > > The sponsor account needs lamports on the ER to pay ephemeral rent. It must be delegated before creating ephemeral accounts. > [accordion] Top up the sponsor before delegation > > Transfer extra SOL to the sponsor account before delegating it, so it has enough lamports to fund ephemeral accounts on the ER. > [accordion] vault and magic\_program are auto-injected > > You don't need to declare them in your struct, but they appear in the IDL and must be passed from the client. Anchor resolves them automatically if named correctly. *** ## Learn More > [card] [Ephemeral Accounts Demo](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/ephemeral-account-chats/anchor/programs/ephemeral-account-chats) > > Full example program on GitHub > [card] [Delegation & Undelegation](/pages/ephemeral-rollups-ers/introduction/ephemeral-rollup) > > How delegation and state synchronization work > [card] [Quickstart](/pages/ephemeral-rollups-ers/how-to-guide/quickstart) > > Build your first program with Ephemeral Rollups # Delegation, Commitment & Undelegation Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/introduction/ephemeral-rollup Execute Transactions, Synchronize States, all in real-time. ![](https://mintcdn.com/magicblock-42/5iyVpKJBt1PkwHw4/images/architecture_overview.png?fit=max\&auto=format\&n=5iyVpKJBt1PkwHw4\&q=85\&s=49ab1e3257a554ea6ce7d2b8cba9b1e8) [Magicblock's Ephemeral Rollup](/pages/overview/additional-information/whitepaper) **leverages the Solana Virtual Machine (SVM)’s account-based structure and parallel execution** to optimize state management. By structuring the state into **clusters**, users can **lock one or multiple accounts** and temporarily shift state execution to a **dedicated auxiliary layer**— "Ephemeral Rollup (ER)". A dynamic fraud-proof mechanism enables fast state finalization through a decentralized Security Committee, see [whitepaper](/public/Ephemeral_Rollups_Fraud_Proof.pdf). *** ## Account Lifecycle for executing transactions in real-time with ER: ![](https://mintcdn.com/magicblock-42/Thv8LjyS00pp5fQ2/images/magicblock-delegation-lifecycle.png?fit=max\&auto=format\&n=Thv8LjyS00pp5fQ2\&q=85\&s=7e3dc70c29cedb2485d4610e446137b4) **1. Delegate Account** State accounts must be delegated to an specific ER validator first by changing the account owner to the [Delegation Program](https://github.com/magicblock-labs/delegation-program) `DELeGGvXpWV2fqJUhqcF5ZSYMS4JTLjteaAMARRSaeSh` and specifying parameters like ER validator, account lifetime and synchronization frequency. > [!NOTE] > > These public validators are supported for development. Make sure to add the > specific ER validator in your delegation instruction: > > **Mainnet** > >
    >
  • > Asia (as.magicblock.app): > `MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57` >
  • > >
  • > EU (eu.magicblock.app): > `MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e` >
  • > >
  • > US (us.magicblock.app): > `MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd` >
  • > >
  • > TEE (mainnet-tee.magicblock.app): > `MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo` >
  • > >
  • > Asia Tokyo (as-tyo.magicblock.app): > `MSHuBweMkNp4yPLDkPLA8bLRHbDmURWjYzsxrcBjix8` >
  • > >
  • > South America (sa.magicblock.app): > `MSARyz2yVTkqiYQWWgaEtUKug7oCF7PphE9GjEYHtDh` >
  • >
> > **Devnet** > >
    >
  • > Asia (devnet-as.magicblock.app): > `MAS1Dt9qreoRMQ14YQuhg8UTZMMzDdKhmkZMECCzk57` >
  • > >
  • > EU (devnet-eu.magicblock.app): > `MEUGGrYPxKk17hCr7wpT6s8dtNokZj5U2L57vjYMS8e` >
  • > >
  • > US (devnet-us.magicblock.app): > `MUS3hc9TCw4cGC12vHNoYcCGzJG1txjgQLZWVoeNHNd` >
  • > >
  • > TEE (devnet-tee.magicblock.app): > `MTEWGuqxUpYZGFJQcp8tLN7x5v9BSeoFHYWQQ3n3xzo` >
  • >
> > **Localnet** > >
    >
  • > Local ER (localhost:7799): > `mAGicPQYBMvcYveUZA5F5UNNwyHvfYh5xkLS2Fr1mev` >
  • >
**2. Execute Transaction in real-time** Delegated state accounts are updated in real-time with transactions on the ER directly or via [Magic Router](/pages/ephemeral-rollups-ers/introduction/magic-router). The **initial transaction on ER clones the delegated account** from base layer to the ephemeral rollup. **3. Commit State** The operator commits the ephemeral state to the base layer **periodically or on-demand**, including new state and relevant pointers. The account state is finalized using a fraud-proof mechanism as detailed in the paper. **4. Execute Transaction in real-time continuously** Delegated account states can continuously be updated in real-time on the ER directly or via [Magic Router](/pages/ephemeral-rollups-ers/introduction/magic-router). **5. Undelegate Account** Delegated account states are committed through ER validator to the base layer and the account owner are reversed from the [Delegation Program](https://github.com/magicblock-labs/delegation-program) `DELeGGvXpWV2fqJUhqcF5ZSYMS4JTLjteaAMARRSaeSh` to the original owner. # FAQ Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/introduction/faq Execute Transactions, Synchronize States, all in real-time. > [accordion] Can delegated accounts be created on ER? > > **No.** Delegated account must exist on Solana beforehand. Delegated accounts are cloned after requesting the account on ER or submitting a transaction with the delegated account. > [accordion] Can programs be delegated to ER? > > **No.** Program accounts are never delegated. Only state accounts can be delegated, while **program accounts are cloned** when a transaction is submitted on ER and subscribed for updates thereafter. > [accordion] Can delegated accounts compose with all programs on Solana? > > **Yes.** Delegated accounts can benefit from all Solana programs and accounts. Every account on Solana is readable on ER, while only delegated account can be changed on ER within an atomic transaction. > [accordion] Are compute unit limits and account size caps the same on ER as on Solana? > > **Mostly yes.** The ER runs the SVM, so the default **200k CU per instruction**, the **1.4M CU per transaction** cap (via `SetComputeUnitLimit`), and the **10 MiB max account size** all match Solana. The exception is transaction size: the ER accepts serialized transactions up to **64 KB**, versus 1,232 bytes on the base layer. See [Runtime Limits](/pages/ephemeral-rollups-ers/introduction/runtime-limits). > [accordion] Should developers use slot time as a reliable timing mechanism? > > **No.** As of 2026-08-05, Solana uses a **400 ms slot time**, while MagicBlock’s Execution Runtime (ER) operates with a **10 ms slot time**. Developers may be tempted to rely on slot time as a fixed-duration measure; however, **slot times are not guaranteed and may change over time**. Code or logic that depends on a specific slot duration should therefore be written with caution. # Fees, Commits, and Refunds Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/introduction/fees-and-commit-economics A plain-language guide to ER fees, commit limits, delegation deposits, and refunds This page explains what your app pays when it delegates an account to an Ephemeral Rollup (ER), commits that account back to Solana, and later undelegates it. ## The short version There are two separate fee systems: 1. **A deposit on Solana.** You fund this deposit when you delegate an account. When you undelegate, MagicBlock takes the session and commit charges from it and returns anything left over. 2. **A live commit limit inside the ER.** Without a delegated fee payer, an account can commit 10 times. For a longer session, add a delegated fee payer and `magic_fee_vault`. This removes the 10-commit stop. The fee payer starts paying an extra live fee on commit 26. These systems work together. A commit with no immediate fee can still be charged against the Solana deposit when the account is undelegated. > [!NOTE] > > The values on this page were checked against the source on August 20, 2026. ## Current prices One SOL contains 1 billion lamports. | What you pay for | Price | When you pay | | :- | -: | :- | | Normal ER transaction | `0` in the current release | No charge | | One delegation session | `3,000,000` lamports (`0.003 SOL`) | Taken from the Solana deposit when you undelegate | | Commits after the first | `1,000,000` lamports (`0.001 SOL`) each | Taken from the Solana deposit when you undelegate | | Live commits starting with commit 26 | `100,000` lamports per account | Taken immediately from the delegated fee payer | | Base Actions | Based on the requested compute units | Taken immediately from the delegated fee payer | | Adding a callback | `5,000` lamports | Taken immediately from the delegated fee payer | | Temporary Ephemeral Account storage | Based on account size; refundable | Reserved when the account is created or grows | Normal ER transactions cost `0` in the current release. Solana transaction fees are separate from the prices above. ## 1. The deposit you fund on Solana Delegating an account creates two small Solana accounts: a **delegation record** and **delegation metadata**. The delegation payer funds both accounts so they are rent-exempt. Think of that money as a refundable balance, not a one-time fee that buys unlimited commits. When you undelegate, MagicBlock calculates the charge: ```text theme={null} session charge = 3,000,000 lamports commit charge = 1,000,000 lamports for each commit after commit 1 total charge = session charge + commit charge ``` MagicBlock takes no more than the amount held in the two deposit accounts. It sends the unused amount back to the wallet recorded as the `rent_payer` when the account was delegated. In practical terms: * even a session with no commit can use up to `3,000,000` lamports from the deposit; * commit 1 adds no commit charge; * commits 2, 3, 4, and so on add `1,000,000` lamports each; * if the calculated charge is larger than the deposit, MagicBlock takes the deposit but does not create a debt or fail undelegation; * any money left in the deposit is refunded. The exact deposit size varies because it depends on Solana rent, the account's stored seeds, and any actions included with the delegation. ## 2. Committing without a fee payer * Commits 1 through 10 are accepted. * Commit 11 fails with custom error `0xA0000000`. * The accepted commits are still included in the deposit charge when you undelegate. A final **commit-and-undelegate** can still run after the limit so the account is not trapped inside the ER. It does not allow more normal commits. ## 3. Committing with a fee payer For a longer session, provide: * a delegated account that will pay the fees; and * the `magic_fee_vault` that belongs to the ER validator you are using. This path does not stop after 10 commits. Instead: * commits 1 through 25 have no **extra live commit fee**; * commit 26 is the first live commit fee; * commit 26 and every later commit cost `100,000` lamports per committed account. Live fees are taken from the delegated fee payer when the bundle is scheduled. Deposit charges are calculated separately when the account is undelegated, so your app may pay both. If one bundle commits several accounts, MagicBlock checks each account separately. For example, a bundle that contains two accounts on commit 26 costs `200,000` lamports in live commit fees. If the fee payer cannot cover the full charge, the instruction fails with `InsufficientFunds`. No partial payment is taken. > [!NOTE] > > The committed account and the fee payer do not have to be the same account. If your app pays for > users, set spending limits and rate limits so one user cannot drain the shared payer. ## Worked examples The examples below do not include normal Solana transaction fees. `D` means the deposit balance just before undelegation. ### One commit, then undelegate ```text theme={null} calculated deposit charge = 3,000,000 lamports amount taken = the smaller of D and 3,000,000 refund = D - amount taken live commit fee = 0 ``` ### Ten simple commits, then undelegate ```text theme={null} session charge = 3,000,000 commit charge = 9 * 1,000,000 calculated deposit charge = 12,000,000 lamports amount taken = the smaller of D and 12,000,000 refund = D - amount taken live commit fee = 0 ``` An 11th simple commit fails before it is scheduled. ### Twenty-six commits with a delegated fee payer ```text theme={null} calculated deposit charge at undelegation = 3,000,000 + (25 * 1,000,000) = 28,000,000 lamports amount taken from deposit = the smaller of D and 28,000,000 live fee taken on commit 26 = 100,000 lamports refund = D - amount taken from deposit ``` ## Keeping the fee payer funded Use `lamportsDelegatedTransferIx` to add lamports to a delegated fee payer. You submit the top-up transaction on Solana, and the Ephemeral SPL Token program moves the balance into the ER. See the [top-up example](/pages/ephemeral-rollups-ers/how-to-guide/quickstart#top-up-delegated-account). Include these costs in your budget: * the lamports you are transferring; * the top-up helper's current `300,000`-lamport setup charge; * the normal Solana transaction fee. The top-up setup charge and the `3,000,000`-lamport delegation session charge are different charges. ## Base Actions and callbacks A Base Action is an instruction that the ER asks MagicBlock to execute on Solana after a commit. On the fee-payer path, its price depends on the compute units requested by the action: ```text theme={null} price = round up(requested compute units * 50,000 / 1,000,000) lamports ``` For example: * one action requesting `200,000` compute units costs `10,000` lamports; * two such actions cost `20,000` lamports. Adding a callback costs another `5,000` lamports. The callback's requested compute units are not included in the Base Action calculation above. ## Refundable Ephemeral Account storage Ephemeral Accounts exist only inside the ER and never commit to Solana. They use a separate, refundable storage balance: ```text theme={null} storage balance = (account data bytes + 60) * 32 lamports ``` The sponsor provides this balance when the account is created or grows. The corresponding amount is returned to the sponsor when the account shrinks or closes. For example: * an account with no data reserves `1,920` lamports; * an account with 1,000 bytes of data reserves `33,920` lamports. See [Ephemeral Accounts](/pages/ephemeral-rollups-ers/introduction/ephemeral-accounts) for the full account lifecycle. ## Other balance movements that are not app fees When a commit changes an account's lamport balance, MagicBlock must make the ER balance and Solana balance match. Lamports may move between the account and the validator during this settlement. This is balance reconciliation, not an extra fixed or percentage fee. The older two-step commit path also uses temporary Solana accounts. The validator funds them and gets the unused balance back after finalization. These are validator operating costs, not additional app fees. Validators also pay Solana priority fees when submitting commit transactions. Those operator costs are separate from the Base Action price charged to an app. If a delegated account has no data and no lamports, the Delegation Program may add `890,880` lamports to keep it rent-exempt. That money funds the account; it is not protocol revenue. ## Common errors | What happened | Result | | :- | :- | | You try a normal 11th commit without the fee-payer path | Custom error `0xA0000000` | | MagicBlock cannot find the account's commit number | Custom error `0xA0000001` | | The validator's `magic_fee_vault` is missing or incorrect | `MissingAccount` | | The fee vault is not writable and delegated | `IllegalOwner` | | The delegated fee payer cannot cover the whole charge | `InsufficientFunds` | | An Ephemeral Account sponsor cannot fund storage | `InsufficientFunds` | | The Solana deposit is smaller than the undelegation charge | MagicBlock takes at most the deposit; no debt is created | ## Where the fees go When the deposit is settled, about 10% of the collected amount goes to the protocol fee vault and about 90% goes to the validator fee vault. Small rounding differences are possible. When a validator later withdraws its accumulated fees, 10% of that withdrawal goes to the protocol and the validator receives the rest. Validators wait until their vault balance is above `100,000,000` lamports before automatically withdrawing. This threshold is only for batching; it is not an app fee. ## Verify the current numbers The fee rules are split between two repositories. Check both when verifying production behavior: | Repository | What to check | | :- | :- | | [Delegation Program](https://github.com/magicblock-labs/delegation-program/tree/6898ef4b82ba1f2b6fbb5d91eca578729edbbeb8) | Fee constants, deposit settlement, refunds, and validator fee withdrawals | | [MagicBlock validator](https://github.com/magicblock-labs/magicblock-validator/tree/cec4cf574ace267029e9487b61780d5218256b42) | Commit limits, live fees, Base Action charges, callback charges, and Ephemeral Account storage | # Magic Router Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/introduction/magic-router Learn how Magicblock's Magic Router accelerates transactions by routing them to the right execution environment. [Why Build with MagicBlock? Solve Scaling & UX Pain Points with Ephemeral Rollups](https://www.youtube.com/embed/Wc2XMAKtEug?si=bjitIDG7w5fY5zmK\&list=PLWR_ZQiGMS8mIe1kPZe8OfHIbhvZqaM8V) *** ## Dynamic Transaction Routing **Magicblock's Magic Router** is an dynamic transaction routing engine that accelerates transactions by intelligently deciding where they should be executed — either on **Ephemeral Rollups** or **Solana** — based on transaction metadata. This eliminates the need for manual routing logic from the developer, providing significant benefits in transaction speed and development experience. * ✅ **Simple Integration with Single Endpoint**: Just connect to a single RPC endpoint. * ✅ **Seamless Wallet Experience**: Connect, sign, and submit — no need to know what’s happening behind the scenes. * ✅ **Faster Confirmations**: Magic Router routes to the fastest available endpoint. ![](https://mintcdn.com/magicblock-42/5iyVpKJBt1PkwHw4/images/magic-router.png?fit=max\&auto=format\&n=5iyVpKJBt1PkwHw4\&q=85\&s=89797c78d3081846949e7e8ad36fd3fb) *** ## Quick Access > [card] [Anchor](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/counter/anchor) > > Integrate with an Anchor program > [card] [Native Rust](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/counter/native-rust) > > Integrate with a Native Rust program > [card] [API](/pages/ephemeral-rollups-ers/api-reference/er/getRoutes) > > Experiment with Magic Router API *** ## Code Snippets Initialize connection with Magic Router before you send transactions dynamically. > [!NOTE] > > These public RPC endpoints are currently free and supported for development: > \ > Magic Router Devnet: [https://devnet-router.magicblock.app](https://devnet-router.magicblock.app) \\ Choose your preferred SDK to initialize, send and confirm transactions: * `ephemeral-rollups-kit` for `@solana/kit` * `ephemeral-rollups-sdk` for `@solana/web.js` ```typescript Kit theme={null} import { Connection } from "@magicblock-labs/ephemeral-rollups-kit"; // Initialize connection const connection = await Connection.create( "https://devnet-router.magicblock.app", "wss://devnet-router.magicblock.app" ); // ... create transaction // Send and confirm transaction const txHash = await connection.sendAndConfirmTransaction( transactionMessage, [userKeypair], { commitment: "confirmed", skipPreflight: true } ); ``` ```typescript Web3.js theme={null} import { sendAndConfirmTransaction } from "@solana/web3.js"; import { ConnectionMagicRouter } from "@magicblock-labs/ephemeral-rollups-sdk"; // Initialize connection const connection = new ConnectionMagicRouter( "https://devnet-router.magicblock.app/", { wsEndpoint: "wss://devnet-router.magicblock.app/" } ); // ... create transaction // Send and confirm transaction const txHash = await sendAndConfirmTransaction(connection, tx, [payer], { skipPreflight: true, commitment: "confirmed", }); ``` The Magic Router analyzes each transaction’s metadata (e.g. writable accounts, owner, and signer) and automatically routes it to the closest dedicated endpoint: ![](https://mintcdn.com/magicblock-42/5iyVpKJBt1PkwHw4/images/magic-router-scenarios.png?fit=max\&auto=format\&n=5iyVpKJBt1PkwHw4\&q=85\&s=4ef8b83ef98061f9073bb11f834d7cc2) 1. **Client - Transaction Submission** The dApp or user sends a transaction to the Magic Router RPC endpoint. 2. **RPC - Metadata Inspection** The Magic Router inspects the transaction metadata and checks the owner of writable accounts. 3. **Validator - Smart Routing and Execution** Based on the metadata, the router determines whether to send it to: * **Ephemeral Rollup** for fast, low-latency, zero-cost execution * **Solana** for persistent, high-throughput execution *** # Runtime Limits Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/introduction/runtime-limits Compute, transaction size, and account size limits on the Ephemeral Rollup compared to Solana The Ephemeral Rollup (ER) runs the **Solana Virtual Machine (SVM)**, so programs execute under the same runtime rules as on the base layer. The key difference is the transaction size limit, which the ER raises significantly. | Limit | Solana Base Layer | Ephemeral Rollup | | :- | :- | :- | | Compute units per instruction (default) | 200,000 CU | 200,000 CU | | Compute units per transaction (max, via `SetComputeUnitLimit`) | 1,400,000 CU | 1,400,000 CU | | Serialized transaction size (max) | 1,232 bytes | **64 KB** | | Account size (max) | 10 MiB | 10 MiB | | Slot time | \~400 ms | \~10 ms | > [!NOTE] > > Slot times are not guaranteed and may change over time. Avoid writing logic > that depends on a specific slot duration — see the > [FAQ](/pages/ephemeral-rollups-ers/introduction/faq). ## Requesting more compute As on Solana, the default compute budget is 200,000 CU per instruction. Request a higher limit (up to 1.4M CU per transaction) by prepending a `SetComputeUnitLimit` instruction: ```typescript theme={null} import { ComputeBudgetProgram, Transaction } from "@solana/web3.js"; const tx = new Transaction().add( ComputeBudgetProgram.setComputeUnitLimit({ units: 1_400_000 }), yourProgramInstruction ); ``` ## Larger transactions The ER accepts serialized transactions up to **64 KB**, compared to the 1,232-byte packet limit on the base layer. This removes the need for address lookup tables or transaction splitting in most cases, and allows instructions with many accounts or large instruction data to execute in a single transaction. > [!WARNING] > > The 64 KB limit only applies to transactions executed on the ER (i.e. all > writable accounts are delegated). Transactions routed to the base layer — > including delegation and undelegation transactions — remain subject to the > 1,232-byte Solana limit. # Ephemeral Rollup Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/introduction/why The high-performance engine for real-time applications on Solana [Why Build with MagicBlock? Solve Scaling & UX Pain Points with Ephemeral Rollups](https://www.youtube.com/embed/yfgDZJJvydU?si=3k8ndg9Z69sv6_LE\&list=PLWR_ZQiGMS8mIe1kPZe8OfHIbhvZqaM8V) > [card] > > [MagicBlock' Ephemeral > Rollup](/pages/ephemeral-rollups-ers/introduction/ephemeral-rollup) is an > extension of the Solana network designed for high-performance decentralized > applications. It enhances Solana’s capabilities while preserving its > composability and integrity. *** ## Why Ephemeral Rollups? While blockchain technology is revolutionizing decentralized applications, it still faces fundamental challenges in: * **Latency** – Blockchain transaction speeds are too slow for real-time applications. * **Cost** – Even "low-fee" blockchains can become expensive at scale. * **Scalability** – Current architectures struggle to handle high-throughput applications. * **Privacy** – Blockchains are by default public, meaning all data onchain can be read. ## **Benefits of MagicBlock's Ephemeral Rollup** The ephemeral rollup functions as a **specialized SVM runtime** and can be **customized** to include: * ✅ **Gasless Transactions** – Zero fees enabling scalability and mass adoption. * ✅ **Faster Block Times** – Sub 10ms latency for seamless UX. * ✅ **High-precision Scheduling** – Built-in automation to execute transactions. * ✅ **Program and States Synchronization** – No fragmentation, composable and upgradable. * ✅ **Horizontal Scaling** – Multiple rollups on-demand for millions of transactions. * ✅ **Familiar Tooling** – Reusability of existing and familiar programming language, libraries and testing tools. > [card] [Ephemeral Rollup](/pages/ephemeral-rollups-ers/introduction/ephemeral-rollup) > > Learn how Ephemeral Rollups works > [card] [Magic Router](/pages/ephemeral-rollups-ers/introduction/magic-router) > > Learn how Magic Router works > [card] [Quickstart](/pages/ephemeral-rollups-ers/how-to-guide/quickstart) > > Try out with Rust, Anchor, and Typescript > [card] [Privacy](/pages/private-ephemeral-rollups-pers/introduction/onchain-privacy) > > Build private, verifiable applications with TEEs # Client Implementation Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/magic-actions/client Client-side guide to building with Magic Actions *** ### Quick Access > [card] [Magic Actions Example](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/magic-actions/anchor) > > Explore reference implementation on GitHub *** ### Setup Router Connection Use Magic Router to route and send transactions to ER and base layer. ```typescript Kit theme={null} import { Connection } from "@magicblock-labs/ephemeral-rollups-kit"; // Initialize connection const connection = await Connection.create( "https://devnet-router.magicblock.app", "wss://devnet-router.magicblock.app" ); // ... create transaction // Send and confirm transaction const txHash = await connection.sendAndConfirmTransaction( transactionMessage, [userKeypair], { commitment: "confirmed", skipPreflight: true } ); ``` ```typescript Web3.js theme={null} import { sendAndConfirmTransaction } from "@solana/web3.js"; import { ConnectionMagicRouter } from "@magicblock-labs/ephemeral-rollups-sdk"; // Initialize connection const connection = new ConnectionMagicRouter( "https://devnet-router.magicblock.app/", { wsEndpoint: "wss://devnet-router.magicblock.app/" } ); // ... create transaction // Send and confirm transaction const txHash = await sendAndConfirmTransaction(connection, tx, [payer], { skipPreflight: true, commitment: "confirmed", }); ``` ### Transaction Flow 1. Delegate counter to ER ```ts theme={null} const delegateTx = await program.methods .delegate() .accounts({ payer: anchor.Wallet.local().publicKey, pda: pda, }) .transaction(); ``` 2. Increment counter on ER in real-time ```ts theme={null} const incrementTx = await program.methods .increment() .accounts({ counter: pda, }) .transaction(); ``` 3. Commit with Magic Action ```ts theme={null} const commitTx = await program.methods .commitAndUpdateLeaderboard() .accounts({ payer: wallet.publicKey /* your accounts */ }) .transaction(); ``` ### Examples > [card] [Quickstart Ephemeral Rollups](/pages/ephemeral-rollups-ers/how-to-guide/quickstart) > > End-to-end walkthrough on ER usage > [card] [Magic Router](/pages/ephemeral-rollups-ers/introduction/magic-router) > > Router overview and flow # Program Implementation Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/magic-actions/implementation Program-side guide to building with Magic Actions *** ### Quick Access > [card] [Magic Actions Example](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/magic-actions/anchor) > > Explore reference implementation on GitHub *** ### 1) Create action instruction The instruction `update_leaderboard` runs on the base layer immediately after the commit lands. The `#[action]` attribute on its accounts context marks it as callable from a post-commit action. > [!WARNING] > > `#[action]` makes the instruction **callable from** a post-commit action — it > does not make it callable **only** that way. The handler is an ordinary > base-layer instruction, so anyone can invoke it directly with a wallet. > Address, `seeds`, and `owner` constraints only pin *which* accounts are passed; > they do not authenticate *who* called it. Any handler that moves value or > changes authoritative state must verify the injected `escrow` signer — see > [Authenticate the caller](/pages/ephemeral-rollups-ers/magic-actions/troubleshooting#security-authenticate-the-caller). ```rust theme={null} // program instruction pub fn update_leaderboard(ctx: Context) -> Result<()> { let leaderboard = &mut ctx.accounts.leaderboard; let counter_info = &mut ctx.accounts.counter.to_account_info(); let mut data: &[u8] = &counter_info.try_borrow_data()?; let counter = Counter::try_deserialize(&mut data)?; if counter.count > leaderboard.high_score { leaderboard.high_score = counter.count; } msg!( "Leaderboard updated! High score: {}", leaderboard.high_score ); Ok(()) } // instruction context #[action] #[derive(Accounts)] pub struct UpdateLeaderboard<'info> { #[account(mut, seeds = [LEADERBOARD_SEED], bump)] pub leaderboard: Account<'info, Leaderboard>, /// CHECK: PDA owner depends on: 1) Delegated: Delegation Program; 2) Undelegated: Your program ID pub counter: UncheckedAccount<'info>, } ``` ### 2) Build the commit instruction with the action The commit instruction `commit_and_update_leaderboard` runs on the ER. It uses `MagicIntentBundleBuilder` to schedule both the commit and the post-commit action onto `magic_context` — both are applied together when the ER transaction is sealed back to the base layer. ```rust theme={null} // commit action instruction on ER pub fn commit_and_update_leaderboard(ctx: Context) -> Result<()> { // Build the post-commit action that updates the leaderboard on base layer let instruction_data = anchor_lang::InstructionData::data(&crate::instruction::UpdateLeaderboard {}); let action_args = ActionArgs::new(instruction_data); let action_accounts = vec![ ShortAccountMeta { pubkey: ctx.accounts.leaderboard.key(), is_writable: true, }, ShortAccountMeta { pubkey: ctx.accounts.counter.key(), is_writable: false, }, ]; let action = CallHandler { destination_program: crate::ID, accounts: action_accounts, args: action_args, // Signer that pays transaction fees for the action from its escrow PDA escrow_authority: ctx.accounts.payer.to_account_info(), compute_units: 200_000, }; // Schedule commit + post-commit action on magic_context MagicIntentBundleBuilder::new( ctx.accounts.payer.to_account_info(), ctx.accounts.magic_context.to_account_info(), ctx.accounts.magic_program.to_account_info(), ) .commit(&[ctx.accounts.counter.to_account_info()]) .add_post_commit_actions([action]) .build_and_invoke()?; Ok(()) } // commit action context on ER #[commit] #[derive(Accounts)] pub struct CommitAndUpdateLeaderboard<'info> { #[account(mut)] pub payer: Signer<'info>, #[account(mut, seeds = [COUNTER_SEED], bump)] pub counter: Account<'info, Counter>, /// CHECK: Leaderboard PDA - not mut here, writable set in handler #[account(seeds = [LEADERBOARD_SEED], bump)] pub leaderboard: UncheckedAccount<'info>, /// CHECK: Your program ID pub program_id: AccountInfo<'info>, } ``` ### Execute multiple actions You can commit multiple accounts and chain several actions in one call. Actions execute sequentially in the order they're passed to `add_post_commit_actions`. ```rust theme={null} // Chain several actions — they execute sequentially on base layer after the commit lands. MagicIntentBundleBuilder::new( ctx.accounts.payer.to_account_info(), ctx.accounts.magic_context.to_account_info(), ctx.accounts.magic_program.to_account_info(), ) .commit(&[ ctx.accounts.counter.to_account_info(), // ... additional committed accounts ]) .add_post_commit_actions([action_1, action_2, action_3]) .build_and_invoke()?; ``` ### Undelegate with actions Actions can also be chained onto an undelegation — the counter commits, undelegates, and the actions run, all atomically in one ER transaction. ```rust theme={null} // Commit, undelegate, AND execute actions — all atomically on base layer after the ER transaction seals. MagicIntentBundleBuilder::new( ctx.accounts.payer.to_account_info(), ctx.accounts.magic_context.to_account_info(), ctx.accounts.magic_program.to_account_info(), ) .commit_and_undelegate(&[ctx.accounts.counter.to_account_info()]) .add_post_commit_actions([action]) .build_and_invoke()?; ``` *** # Introduction Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/magic-actions/overview Automatically execute base-layer actions while Delegated > [!TIP] > > **Building with an AI coding agent?** Install the MagicBlock Dev Skill to give your agent MagicBlock-specific patterns — delegation flows, Magic Actions, cranks, VRF, and more. > > **Hit an error?** Ask your coding agent with the skill installed, not the docs assistant. The assistant only sees the docs, so it cannot debug your code. > > Quick install for Claude Code: > > ```bash theme={null} > npx skills add https://github.com/magicblock-labs/magicblock-dev-skill > ``` > > Using Cursor, Codex, Windsurf, Cline, or another agent? See the [AI Dev Skill](/pages/overview/additional-information/ai-dev-skill) page for all install targets. *** ### Quick Access > [card] [Magic Actions Example](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/magic-actions/anchor) > > Explore reference implementation on GitHub > [card] [Prediction-market settlement](/pages/solutions/prediction-markets) > > Compare ER custody with post-commit base-layer payouts in a complete protocol flow. *** ### What are Magic Actions? Magic Actions let you attach one or more call instructions that run automatically on the Solana base layer immediately after an Ephemeral Rollup (ER) commit. Use committed state as inputs to orchestrate multi-step workflows in a single transaction. * **State sync**: propagate ER changes to base-layer accounts * **Cross-program composition**: invoke other programs after commit * **Automated workflows**: chain complex operations from one commit * **Event-driven actions**: branch logic based on committed state ### How it works 1. Delegate accounts to an Ephemeral Rollup 2. Execute low-latency transactions on Ephemeral Rollup 3. Commit to base layer with attached instruction actions while staying delegated 4. Handlers execute automatically using the freshly committed state *** ### See also Magic Action work along with Ephemeral Rollups. > [card] [Ephemeral Rollups](/pages/ephemeral-rollups-ers/introduction/ephemeral-rollup) > > Delegation, Commitment & Undelegation # Troubleshooting Source: https://docs.magicblock.gg/pages/ephemeral-rollups-ers/magic-actions/troubleshooting Diagnose common issues with Magic Actions ### Handler not executing * Verify `instruction discriminator` * Allocate sufficient `compute_units` ### Deserialization errors * Use `UncheckedAccount` for committed accounts in action context * Manually deserialize via `try_deserialize` on borrowed data * Check account discriminator matches expected type ### Transaction failures * Ensure all action accounts are listed in `ShortAccountMeta` * Match `is_writable` flags to actual usage * Increase compute budget for all actions in the commit ### Security: authenticate the caller An action is a delegation-program instruction the committor runs on the base layer after a commit; the validator pays its transaction fee. The handler may still need an on-chain payer for any **rent** it creates (e.g. initializing an ATA). For that the delegation program uses an **ephemeral balance escrow** — a SOL-holding PDA derived from `[b"balance", escrow_auth, escrow_index]` — and injects two accounts into your `#[action]` context: `escrow_auth` (the payer identity that owns the balance — a user wallet or a program PDA) and `escrow` (the SOL PDA itself, which the delegation program **signs via `invoke_signed`** when it runs the action, so the handler can spend it for rent). That escrow signature is also the authentication anchor. A `#[action]` handler is otherwise a normal base-layer instruction — for **any** work it performs (writing a PDA it owns, leaderboard updates, mints, settlements, token transfers; no action type is special). The attribute makes it dispatchable from a post-commit action, **not** exclusively so — anyone can invoke it directly. `#[account(address = ...)]`, `seeds`, and `owner` constraints only pin *which* accounts are passed; only the injected `escrow` signer proves the delegation program dispatched the call (no wallet or other program can sign for that PDA). `ActionArgs::new` defaults `escrow_index` to `255`. On every handler, require `escrow` as `signer` pinned to its derivation. When the handler acts with a program-owned PDA, also bind `escrow_auth` to that PDA: ```rust theme={null} pub const ACTION_ESCROW_INDEX: u8 = 255; // ActionArgs::new default // In the #[action] accounts context: /// CHECK: payer identity the action was scheduled with. When the handler acts /// with a program-owned PDA, bind this to that PDA so only actions *your* /// program scheduled — not a foreign program's — can drive the handler. #[account(address = vault_authority.key())] pub escrow_auth: UncheckedAccount<'info>, /// CHECK: only the delegation program can sign for this PDA, so `signer` /// proves the call arrived through the real post-commit path. #[account( signer, address = ephemeral_rollups_sdk::pda::ephemeral_balance_pda_from_payer( &escrow_auth.key(), ACTION_ESCROW_INDEX, ), )] pub escrow: UncheckedAccount<'info>, ``` `signer` alone is not enough — a different program could still schedule an action into your handler with its own escrow authority; binding `escrow_auth` to your program's PDA closes that. For user-paid actions (escrow authority = the user's wallet) the signer + derivation check is the guarantee, and there is no fixed PDA to bind against. **Need the same logic callable outside an action too** (an admin settlement, the user directly)? The escrow constraints above make the instruction action-only. The default fix is **two thin instructions over one shared function**: keep the `#[action]` entrypoint with its escrow checks, add a normal `Signer`-authorized entrypoint, and have both call the same internal function. A single dual-mode instruction is possible — declare `escrow`/`escrow_auth` as `Option<...>`, add an optional authority, and branch in the handler requiring exactly one path (`via_action ^ via_direct`) — but injected/optional accounts are positional (the delegation program appends its accounts last), so two instructions is the cleaner default. ### Limitations & considerations * Handlers execute on base layer and consume base-layer fees * Standard Solana limits apply (compute, account locks) * Atomicity: any action failure reverts the commit * First two action accounts are injected (`escrow`, `escrow_auth`) ### Helpful links > [card] [Ephemeral Rollups](/pages/ephemeral-rollups-ers/introduction/ephemeral-rollup) > > Delegation, Commitment & Undelegation > [card] [Magic Router](/pages/ephemeral-rollups-ers/introduction/magic-router) > > Router overview and flow > [card] [Magic Actions Example](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/magic-actions/anchor) > > Explore reference implementation on GitHub > [card] [Community Support](https://t.me/+78KHQkUsy0ViMzQ6) > > Chat with the team and community # Balance Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/api-reference/balance pages/ephemeral-spl-token/api-reference/openapi/balance.openapi.json GET /v1/spl/balance Reads the owner's associated token account on the base RPC. # Challenge Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/api-reference/challenge pages/ephemeral-spl-token/api-reference/openapi/challenge.openapi.json GET /v1/spl/challenge Returns a challenge string that the wallet must sign. The signature is then submitted to `/v1/spl/login` in exchange for a bearer token used to read private data. # Deposit SPL Tokens Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/api-reference/deposit pages/ephemeral-spl-token/api-reference/openapi/deposit.openapi.json POST /v1/spl/deposit Wraps the SDK `delegateSpl(...)` flow. The API generates `shuttleId` server-side and pins `escrowIndex` to `0`. # Initialize Mint Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/api-reference/initialize-mint pages/ephemeral-spl-token/api-reference/openapi/initialize-mint.openapi.json POST /v1/spl/initialize-mint # Introduction Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/api-reference/introduction Ephemeral SPL Token API documentation > [card] [Ephemeral SPL Token Program](https://github.com/magicblock-labs/ephemeral-spl-token) > > The on-chain Ephemeral SPL Token program > [card] [Private Payment Example](https://one.magicblock.app/) > > Explore the example private payments application and API flow ## Overview The Ephemeral SPL Token API builds unsigned SPL token transactions for deposits, transfers, withdrawals, swaps, and mint initialization across Solana and MagicBlock ephemeral rollups. It also exposes balance queries, mint-initialization status, stealth pools, and a wallet challenge/login flow that issues bearer tokens for reading private data. The canonical public reference is available at [payments.magicblock.app/reference](https://payments.magicblock.app/reference). ### Meta * [**Health**](/pages/ephemeral-spl-token/api-reference/health) - Check API health and availability * [**Send Transaction**](/pages/ephemeral-spl-token/api-reference/transaction-send) - Submit a signed transaction to the base layer or ephemeral RPC ### Auth * [**Challenge**](/pages/ephemeral-spl-token/api-reference/challenge) - Generate a challenge string for the wallet to sign * [**Login**](/pages/ephemeral-spl-token/api-reference/login) - Exchange a signed challenge for a bearer token ### SPL * [**Deposit SPL Tokens**](/pages/ephemeral-spl-token/api-reference/deposit) - Build an unsigned deposit transaction from Solana into an ephemeral rollup * [**Transfer SPL Tokens**](/pages/ephemeral-spl-token/api-reference/transfer) - Build an unsigned public or private SPL transfer * [**Withdraw SPL Tokens**](/pages/ephemeral-spl-token/api-reference/withdraw) - Build an unsigned withdrawal transaction back to Solana * [**Undelegate Ephemeral ATA**](/pages/ephemeral-spl-token/api-reference/undelegate-ephemeral-ata) - Build an unsigned transaction that undelegates a wallet's eATA for a mint * [**Initialize Mint**](/pages/ephemeral-spl-token/api-reference/initialize-mint) - Build an unsigned transaction that initializes a validator-scoped transfer queue for a mint * [**Ensure Transfer Queue Crank**](/pages/ephemeral-spl-token/api-reference/transfer-queue-ensure-crank) - Verify a mint's transfer queue and force one crank attempt * [**Balance**](/pages/ephemeral-spl-token/api-reference/balance) - Get the base-chain SPL token balance for an address * [**Private Balance**](/pages/ephemeral-spl-token/api-reference/private-balance) - Get the ephemeral-rollup SPL token balance for an address (auth required) * [**Is Mint Initialized**](/pages/ephemeral-spl-token/api-reference/is-mint-initialized) - Check whether a mint has a validator-scoped transfer queue on the ephemeral RPC ### Stealth Pools * [**Create Stealth Pool**](/pages/ephemeral-spl-token/api-reference/stealth-pool) - Map a handle to destination keys for private transfers (auth required) * [**Get Stealth Pool Status**](/pages/ephemeral-spl-token/api-reference/stealth-pool-status) - Check whether a handle's stealth pool exists ### Swap * [**Swap Quote**](/pages/ephemeral-spl-token/api-reference/quote) - Get a swap quote between two SPL mints * [**Swap**](/pages/ephemeral-spl-token/api-reference/swap) - Build an unsigned swap transaction (public pass-through or private with scheduled transfer) ### MCP * [**MCP**](/pages/ephemeral-spl-token/api-reference/mcp) - Access the stateless Streamable HTTP MCP endpoint ``` ┌────────────────────────────────────────────┐ │ 1. Deposit │ ├────────────────────────────────────────────┤ │ • Build an unsigned deposit transaction │ │ • Solana base balance → ephemeral rollup │ └────────────────────────────────────────────┘ ↓ ┌────────────────────────────────────────────┐ │ 2. Transfer / Swap │ ├────────────────────────────────────────────┤ │ • Build SPL transfer or swap │ │ • base/ephemeral → base/ephemeral │ │ • public or private (delayed + split) │ └────────────────────────────────────────────┘ ↓ ┌────────────────────────────────────────────┐ │ 3. Withdraw │ ├────────────────────────────────────────────┤ │ • Build an unsigned withdrawal │ │ • ephemeral rollup → Solana base balance │ └────────────────────────────────────────────┘ ``` ## Auth Flow Endpoints that read private data inside the Private Ephemeral Rollup require a bearer token: 1. `GET /v1/spl/challenge?pubkey=` returns a `challenge` string 2. The wallet signs the challenge 3. `POST /v1/spl/login` with `{ pubkey, challenge, signature }` returns a `token` 4. Pass `Authorization: Bearer ` on `/v1/spl/private-balance` (required) and on `/v1/spl/transfer` requests that need to connect to the Private Ephemeral Rollup (optional) ## Response Format Successful transaction-building endpoints return an unsigned transaction payload: ```json theme={null} { "kind": "deposit", "version": "legacy", "transactionBase64": "base64-encoded-transaction", "sendTo": "base", "recentBlockhash": "blockhash", "lastValidBlockHeight": 284512337, "instructionCount": 3, "requiredSigners": ["3rXKwQ1kpjBd5tdcco32qsvqUh1BnZjcYnS5kYrP7AYE"] } ``` The expected client flow is: 1. Call the API 2. Decode `transactionBase64` 3. Optionally adjust the transaction if the client needs to 4. Sign with the required wallet(s) 5. Send to the RPC indicated by `sendTo` (`"base"` or `"ephemeral"`) # Is Mint Initialized Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/api-reference/is-mint-initialized pages/ephemeral-spl-token/api-reference/openapi/is-mint-initialized.openapi.json GET /v1/spl/is-mint-initialized # Login Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/api-reference/login pages/ephemeral-spl-token/api-reference/openapi/login.openapi.json POST /v1/spl/login Verifies the wallet's signature over the challenge issued by `/v1/spl/challenge` and returns an authentication token. Pass the token as `Authorization: Bearer ` on `/v1/spl/private-balance` and on `/v1/spl/transfer` requests that need to connect to the Private Ephemeral Rollup. # Private Balance Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/api-reference/private-balance pages/ephemeral-spl-token/api-reference/openapi/private-balance.openapi.json GET /v1/spl/private-balance Reads the owner's associated token account on the ephemeral RPC. Requires an `Authorization: Bearer ` header obtained from `/v1/spl/login`. # Create Stealth Pool Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/api-reference/stealth-pool pages/ephemeral-spl-token/api-reference/openapi/stealth-pool.openapi.json POST /v1/spl/stealth-pool Build unsigned stealth-pool setup and ER update transactions that map a handle to 1-10 destination owner keys. Requires an `Authorization: Bearer ` header from the `/v1/spl/login` flow. Once initialized, the handle can be used as the `to` value of a private `/v1/spl/transfer`. # Get Stealth Pool Status Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/api-reference/stealth-pool-status pages/ephemeral-spl-token/api-reference/openapi/stealth-pool.openapi.json GET /v1/spl/stealth-pool Derive a stealth-pool PDA from an exact handle and report whether the base account exists. Does not return the destination keys. # Send Transaction Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/api-reference/transaction-send pages/ephemeral-spl-token/api-reference/openapi/transaction-send.openapi.json POST /v1/transaction/send Submit a signed, serialized transaction. Use the `sendTo` value returned by a build endpoint (deposit / transfer / withdraw / stealth-pool) to route the transaction to the base layer or the ephemeral RPC. Accepts an optional `Authorization: Bearer ` header for ephemeral submissions that require it. # Transfer SPL Tokens Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/api-reference/transfer pages/ephemeral-spl-token/api-reference/openapi/transfer.openapi.json POST /v1/spl/transfer Transfer SPL tokens publicly or privately through an ephemeral rollup. Accepts an optional `Authorization: Bearer ` header obtained from the `/v1/spl/login` flow when the request needs to read or write data inside the Private Ephemeral Rollup. # Undelegate Ephemeral ATA Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/api-reference/undelegate-ephemeral-ata pages/ephemeral-spl-token/api-reference/openapi/undelegate-ephemeral-ata.openapi.json POST /v1/spl/undelegate-ephemeral-ata Build an unsigned ephemeral-rollup transaction that undelegates a wallet's ephemeral ATA (eATA) for a mint, committing its balance back toward the base layer. Accepts an optional `Authorization: Bearer ` header. # Withdraw SPL Tokens Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/api-reference/withdraw pages/ephemeral-spl-token/api-reference/openapi/withdraw.openapi.json POST /v1/spl/withdraw Wraps the SDK `withdrawSpl(...)` flow. The API generates `shuttleId` server-side. # Ephemeral SPL Tokens Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/overview Move SPL tokens at Ephemeral Rollup speed with the Ephemeral SPL Token program — learn the eATA, Global Vault, delegation, custody, and private-payment models. *** ## Overview **Ephemeral SPL Tokens** let you hold and move SPL tokens inside a [MagicBlock Ephemeral Rollup (ER)](/pages/ephemeral-rollups-ers/introduction/ephemeral-rollup) with the same low latency as any other delegated state, then settle back to Solana's base layer. They are the token primitive behind MagicBlock's **private payments** — but the primitive itself is general: a transfer can be **public or private**. Everything is powered by the on-chain **Ephemeral SPL Token program** (`SPLxh1LVZzEkX99H6rqYizhytLWPZVV296zyYDPagv2`), which implements [MIMD 0013](https://github.com/magicblock-labs/magicblock-validator/discussions/550). > [card] [Ephemeral SPL Token program](https://github.com/magicblock-labs/ephemeral-spl-token) > > On-chain program + hosted API. `SPLxh1LV…` > [card] [Quickstart](/pages/ephemeral-spl-token/quickstart) > > Delegate a token account, transfer on the ER, withdraw — end to end. > [card] [Building a prediction market or trading protocol?](/pages/solutions/prediction-markets) > > See how token custody fits with session keys, price oracles, cranks, and settlement. *** ## The model A normal SPL token account lives on Solana's base layer. To move tokens at ER speed, the Ephemeral SPL Token program introduces two account types. ### Ephemeral ATA (eATA) An **ephemeral ATA** is a program-owned PDA derived from `[owner, mint]` that holds a single `u64` balance. It is **not** a real SPL token account — it is a lightweight balance record that can be delegated to the ER and mutated there at high speed. ### Global Vault The real tokens are custodied in a per-mint **Global Vault** — a PDA derived from `[mint]` that owns the SPL token account backing **every** eATA of that mint. Depositing moves real tokens into the vault and credits your eATA's `u64`; withdrawing does the reverse. > [!NOTE] > > An eATA tracks a balance; the Global Vault holds the actual tokens. One vault backs all eATAs for a > given mint. *** ## Delegation lifecycle eATAs follow the standard Ephemeral Rollup lifecycle: **1. Deposit & delegate** Real tokens move into the mint's Global Vault, your eATA is credited, and the eATA is delegated to a MagicBlock validator so it can be mutated inside the ER. **2. Transact on the ER** Transfer between eATAs inside the rollup at low latency. Transfers can be **public** or **private** (`visibility`). **3. Undelegate & commit** The eATA is committed and undelegated back to the base layer. **4. Withdraw** Tokens move out of the Global Vault back to a standard base-layer SPL token account. *** ## Public vs. private The primitive supports both: * **Public** — a normal fast transfer between eATAs on the ER. * **Private (Private Payments)** — the destination and settlement are shielded: private `visibility`, encrypted/queued settlement, and **stealth handles** (a human-readable name such as `alice@magicblock.id` that resolves to one or more destination keys). This is the use case behind the [Private Payments guide](/pages/ephemeral-spl-token/private-payments). *** ## Two ways to integrate > [card] [On-chain / SDK](/pages/ephemeral-spl-token/quickstart) > > Integrate directly in your own Anchor program and client with > `@magicblock-labs/ephemeral-rollups-sdk` — delegate a token account, transfer on the ER, withdraw. > [card] [Hosted REST / MCP API](/pages/ephemeral-spl-token/api-reference/introduction) > > Let the hosted API build unsigned transactions for deposit, transfer, withdraw, balances, swap, and > private payments. # Private Payments with Ephemeral SPL Tokens Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/private-payments Use Ephemeral SPL Tokens for private deposits, transfers, and withdrawals — private visibility, stealth handles, and queued settlement over the hosted API. *** ### Quick Access Check out example: > [card] [GitHub](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/spl-tokens) > > SPL Tokens Anchor Implementation > [card] [Live Example App](https://spl-demo.magicblock.app/) > > Try the SPL Tokens demo > [card] [Live Example App](https://one.magicblock.app/) > > Try private payments *** ## Overview **Private Payments** are the privacy use case built on top of [SPL tokens on ER](/pages/ephemeral-spl-token/overview). The same deposit / transfer / withdraw primitive runs with **private visibility**, so the amount, destination, and timing of a payment are shielded rather than broadcast publicly. > [!NOTE] > > New to the primitive? Read the [Ephemeral SPL Tokens > overview](/pages/ephemeral-spl-token/overview) first — this guide > assumes the eATA / Global Vault / delegation model. The easiest way to build private payments is the hosted **Ephemeral SPL Token API**, which returns unsigned transactions you sign and submit. > [card] [API reference](/pages/ephemeral-spl-token/api-reference/introduction) > > Endpoints for deposit, transfer, withdraw, balances, stealth pools, and auth. > [card] [Reference program](https://github.com/magicblock-labs/ephemeral-spl-token) > > The on-chain Ephemeral SPL Token program. *** ## Privacy model Private payments rely on: * **Private visibility** — transfers execute inside the Ephemeral Rollup with `visibility: "private"`, so the transfer is not broadcast publicly. * **Stealth handles** — send to a human-readable name (e.g. `alice@magicblock.id`) instead of a raw public key. The handle resolves to one or more destination keys via a **stealth pool**, breaking the direct sender → recipient link on-chain. * **Queued settlement** — private transfers can settle through the program's transfer queue rather than a direct, immediately-linkable movement. > [!WARNING] > > Privacy here reduces **linkability**, not total observability. Amounts and timing may still be > inferable at the network level. Threat-model your assumptions. *** ## Authentication Private reads and stealth-pool operations require a bearer token. Obtain one with the challenge/login flow before calling protected endpoints: **1. Request a challenge** `GET /v1/spl/challenge` returns a message for the user to sign. **2. Log in** `POST /v1/spl/login` exchanges the signed challenge for a bearer token. **3. Call protected endpoints** Send `Authorization: Bearer ` on `GET /v1/spl/private-balance` and `POST /v1/spl/stealth-pool`. *** ## Deposits Move tokens into the mint's Global Vault and credit the depositor's ephemeral ATA. * `POST /v1/spl/deposit` — builds the deposit transaction. Set `private: true` to keep the deposited balance private. The response is an unsigned transaction plus a `sendTo` field (`base` or `ephemeral`). Sign it and submit via [`POST /v1/transaction/send`](/pages/ephemeral-spl-token/api-reference/transaction-send) or your own RPC. *** ## Private transfers * `POST /v1/spl/transfer` with `visibility: "private"`. Two destination modes: | Destination | `to` value | Requirements | | - | - | - | | Direct | recipient public key | `visibility: "private"` | | Stealth handle | an initialized handle string | `visibility: "private"`, `fromBalance: "base"`, `toBalance: "base"` | To use a stealth handle, initialize it first: * `POST /v1/spl/stealth-pool` — map a handle (≤255 UTF-8 bytes; **not** normalized, so `Alice@…` ≠ `alice@…`) to 1–10 destination owner keys, optionally splitting payments across them. * `GET /v1/spl/stealth-pool?handle=…` — check whether a handle's pool exists. > [!NOTE] > > Handles are stored as their exact UTF-8 bytes. `GET` returns only whether the pool exists — never the > destination keys. *** ## Fees and gasless transfers `visibility` and `gasless` are independent request fields: `visibility` controls how the transfer is routed, while `gasless` controls who pays gas. The cost of a private transfer is the sum of a **privacy fee**, which always applies, and the chosen **gas payment mode**. Every private base → base transfer pays a **0.1% (10 bps) privacy fee**, charged in the token being transferred — not in SOL. Gas can be paid in either of two modes: | | Self-paid | Gasless (`gasless: true`) | | - | - | - | | SOL transaction fee | sender pays (needs SOL) | sponsor pays (sender needs no SOL) | | Relay fee | none | flat 0.2 USDC/USDT to the sponsor | | 0.1% privacy fee | yes, in tokens | yes, in tokens | | Minimum amount | none | 0.5 USDC/USDT | | Supported mints | any | mainnet USDC/USDT, devnet USDC | With `gasless: true`, the configured sponsor becomes the transaction fee payer and co-signs, and the API prepends a token-transfer instruction that reimburses the sponsor with a flat **0.2 USDC/USDT relay fee** from the sender's balance. Because the relay fee is flat, gasless transfers require a minimum of **0.5 USDC/USDT**; the minimum applies only to the gasless mode, not to private transfers in general. Amounts below it can still be sent with `visibility: "private"` by omitting `gasless`. A first private transfer may also include a one-time **\~0.00204 SOL** of rent to set up the ephemeral token account. All token-denominated fees are reported in the transfer response as `fees.tokens`, and SOL-denominated costs as `fees.lamports`. > [!NOTE] > > A `gasless: true` request below the minimum, or with an unsupported mint, is rejected with a `400` > error (`INVALID_GASLESS_TRANSFER_AMOUNT` / `INVALID_GASLESS_TRANSFER_MINT`). The API never changes > the requested `visibility`: a transfer is only public when the request says so. Clients that handle > gasless errors by rebuilding the request should preserve `visibility: "private"` if privacy is > intended. `gasless: true` is ignored when `from` is an off-curve PDA owner (gasless requires a wallet sender); the transfer still executes with the requested visibility, with the sender as fee payer. *** ## Withdrawals Move a balance back out of the Global Vault to a standard base-layer SPL token account. * `POST /v1/spl/withdraw` — builds the withdrawal transaction. Check balances any time: * `GET /v1/spl/balance` — public balance. * `GET /v1/spl/private-balance` — private balance (requires the bearer token). *** ## Developer notes * **Privacy is a spectrum.** Ephemeral SPL tokens reduce linkability; they do not hide amounts, timing, or protect against network-level analysis. * **Handles aren't normalized.** Casing/whitespace matter — display and store handles consistently. * **Match the flow.** Stealth-handle transfers require `visibility: "private"`, `fromBalance: "base"`, `toBalance: "base"` (these are also the omitted-field defaults). * **Sign then send.** Builder endpoints return unsigned transactions; submit them with `POST /v1/transaction/send` and honor the returned `sendTo`. *** ## Next steps > [card] [Ephemeral SPL Tokens — Overview](/pages/ephemeral-spl-token/overview) > > The primitive behind private payments. > [card] [SDK Quickstart](/pages/ephemeral-spl-token/quickstart) > > The on-chain/SDK integration path. # Ephemeral SPL Token Quickstart Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/quickstart Delegate an SPL token account to an Ephemeral Rollup, transfer on the ER, and withdraw back to the base layer — with the ephemeral-rollups-sdk. *** > [!TIP] > > **Building with an AI coding agent?** Install the MagicBlock Dev Skill to give your agent MagicBlock-specific patterns — delegation flows, Magic Actions, cranks, VRF, and more. > > **Hit an error?** Ask your coding agent with the skill installed, not the docs assistant. The assistant only sees the docs, so it cannot debug your code. > > Quick install for Claude Code: > > ```bash theme={null} > npx skills add https://github.com/magicblock-labs/magicblock-dev-skill > ``` > > Using Cursor, Codex, Windsurf, Cline, or another agent? See the [AI Dev Skill](/pages/overview/additional-information/ai-dev-skill) page for all install targets. ### Quick Access Check out example: > [card] [GitHub](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/spl-tokens) > > SPL Tokens Anchor Implementation > [card] [Live Example App](https://spl-demo.magicblock.app/) > > Try the SPL Tokens demo > [card] [Live Example App](https://one.magicblock.app/) > > Try private payments > [!NOTE] > > Snippets target `@magicblock-labs/ephemeral-rollups-sdk` **v0.14.3** with the legacy-vault path. The > idempotent-shuttle path targets v0.15.3 — keep the same path across `delegateSpl` / `undelegateIx` / > `withdrawSpl` within one lifecycle. *** ## Step-By-Step Guide Move SPL tokens through the full lifecycle against the Ephemeral SPL Token program `SPLxh1LVZzEkX99H6rqYizhytLWPZVV296zyYDPagv2` — [delegate](/pages/ephemeral-rollups-ers/introduction/ephemeral-accounts), transact on the [ER](/pages/ephemeral-rollups-ers/introduction/ephemeral-rollup), then settle back to Solana: **1. [Delegate the token account](#1-delegate)** Delegate an owner's balance to a validator on the base layer. The first delegation for a mint creates the shared Global Vault. **2. [Transfer on the ER](#2-transfer)** Move tokens between eATAs inside the rollup — public or private. **3. [Undelegate & commit](#3-undelegate)** Undelegate on the ER and wait for the commit back to base. **4. [Withdraw to base](#4-withdraw)** Move the balance out of the Global Vault to a base-layer token account. *** ## Ephemeral SPL Token Example The following software packages may be required, other versions may also be compatible: | Software | Version | Installation Guide | | - | - | - | | **Solana** | 3.1.9 | [Install Solana](https://docs.anza.xyz/cli/install) | | **Rust** | 1.89.0 | [Install Rust](https://www.rust-lang.org/tools/install) | | **Anchor** | 1.0.2 | [Install Anchor](https://www.anchor-lang.com/docs/installation) | | **Node** | 24.10.0 | [Install Node](https://nodejs.org/en/download/current) | Install the SDK: ```bash theme={null} yarn add @magicblock-labs/ephemeral-rollups-sdk@0.14.3 ``` ### Code Snippets > [tab] 1. Delegate > > `delegateSpl` delegates an owner's balance to a validator. The first delegation for a mint creates > the shared Global Vault (`initVaultIfMissing: true`); later ones reuse it. Send on the **base > layer**, and fund the rent sponsor (`deriveRentPda()`) before delegating. > > ```typescript theme={null} > // Legacy vault flow — keep the same idempotent setting across > // delegateSpl / undelegateIx / withdrawSpl within one lifecycle. > const delegateOpts = { validator, idempotent: false as const, payer: admin.publicKey }; > > const ixs = await delegateSpl(owner.publicKey, mint.publicKey, amount, { > ...delegateOpts, > initVaultIfMissing, // true for the first owner of this mint, false after > }); > > await provider.sendAndConfirm( > new anchor.web3.Transaction().add(...ixs), > [owner, admin], > { commitment: "confirmed", skipPreflight: true }, > ); > ``` > > [⬆️ Back to Top](#code-snippets) > [tab] 2. Transfer > > `transferSpl` moves tokens between eATAs inside the rollup. Send on the **ephemeral** provider. Set > `visibility: "private"` for a private payment or `"public"` for a normal fast transfer. > > ```typescript theme={null} > // Delegation confirms on base before the ER clones the account — > // poll the ER view before transferring. > await waitForErTokenAccount(ata, expectedAmount); > > const transferIxs = await transferSpl( > recipientA.publicKey, > recipientB.publicKey, > mint.publicKey, > 2n, > { visibility: "public", fromBalance: "ephemeral", toBalance: "ephemeral" }, > ); > > await providerEphemeralRollup.sendAndConfirm( > new anchor.web3.Transaction().add(...transferIxs), > [recipientA], > { commitment: "confirmed", skipPreflight: true }, > ); > ``` > > [⬆️ Back to Top](#code-snippets) > [tab] 3. Undelegate > > Undelegate each owner on the ER (one per transaction), then wait for the commit back to base with > `GetCommitmentSignature` before withdrawing. > > ```typescript theme={null} > const sgn = await providerEphemeralRollup.sendAndConfirm( > new anchor.web3.Transaction().add(undelegateIx(owner.publicKey, mint.publicKey)), > [owner], > { commitment: "confirmed", skipPreflight: true }, > ); > > // Wait for the commit back to base before withdrawing, or the withdraw > // races the commit and fails with InvalidAccountOwner. > const commit = await GetCommitmentSignature(sgn, providerEphemeralRollup.connection); > await connection.confirmTransaction(commit, "confirmed"); > ``` > > [⬆️ Back to Top](#code-snippets) > [tab] 4. Withdraw > > `withdrawSpl` moves the balance out of the Global Vault back to the owner's base-layer ATA. > > ```typescript theme={null} > const withdrawIxs = await withdrawSpl(owner.publicKey, mint.publicKey, amount, { > idempotent: false, > }); > > await provider.sendAndConfirm( > new anchor.web3.Transaction().add(...withdrawIxs), > [owner], > { commitment: "confirmed" }, > ); > ``` > > [⬆️ Back to Top](#code-snippets) > [tab] ER-aware program > > To route the ER-side transfer through your own program instead of the SDK helper, add the > `#[ephemeral]` attribute — the instruction is a plain SPL Token CPI. See > [Smart Contract Integration](/pages/ephemeral-spl-token/smart-contract-integration) for custody > and PDA-signed transfers. > > ```rust theme={null} > use anchor_lang::prelude::*; > use anchor_spl::token::{self, Token, TokenAccount, Transfer as SplTransfer}; > use ephemeral_rollups_sdk::anchor::ephemeral; > > #[ephemeral] > #[program] > pub mod spl_tokens { > use super::*; > > /// Transfer `amount` of SPL tokens from `from` to `to`. > pub fn transfer(ctx: Context, amount: u64) -> Result<()> { > require!(amount > 0, ErrorCode::InvalidAmount); > let cpi_accounts = SplTransfer { > from: ctx.accounts.from.to_account_info(), > to: ctx.accounts.to.to_account_info(), > authority: ctx.accounts.payer.to_account_info(), > }; > let cpi_ctx = CpiContext::new(ctx.accounts.token_program.to_account_info(), cpi_accounts); > token::transfer(cpi_ctx, amount)?; > Ok(()) > } > } > ``` > > [⬆️ Back to Top](#code-snippets) > [!NOTE] > > **Run it locally:** `yarn` → `yarn build` → `yarn setup` (boots the local base + ER cluster; leave > running) → `yarn test:local` in a second terminal. *** ## Solana Explorer Get insights about your transactions and accounts on Solana: > [card] [Solana Explorer](https://explorer.solana.com/) > > Official Solana Explorer > [card] [Solscan](https://solscan.io/) > > Explore Solana Blockchain ## Solana RPC Providers Send transactions and requests through existing RPC providers: > [card] [Solana](https://solana.com/docs/references/clusters#on-a-high-level) > > Free Public Nodes > [card] [Helius](https://www.helius.dev/solana-rpc-nodes) > > Free Shared Nodes > [card] [Triton](https://triton.one/solana) > > Dedicated High-Performance Nodes ## Solana Validator Dashboard Find real-time updates on Solana's validator infrastructure: > [card] [Solana Beach](https://solanabeach.io/) > > Get Validator Insights > [card] [Validators App](https://www.validators.app/) > > Discover Validator Metrics ## Server Status Subscribe to Solana's and MagicBlock's server status: > [card] [Solana Status](https://status.solana.com/) > > Subscribe to Solana Server Updates > [card] [MagicBlock Status](/pages/overview/additional-information/system-status) > > Subscribe to MagicBlock Server Status *** ## MagicBlock Products > [card] [Ephemeral Rollup (ER)](/pages/ephemeral-rollups-ers/how-to-guide/quickstart) > > Execute real-time, zero-fee transactions securely on Solana. > [card] [Private Ephemeral Rollup (PER)](/pages/private-ephemeral-rollups-pers/how-to-guide/quickstart) > > Protect sensitive data with compliance — built on top of Ephemeral Rollups. > [card] [Ephemeral SPL Token](/pages/ephemeral-spl-token/overview) > > Move SPL tokens at rollup speed — public or private transfers, swaps, and private payments for trading and DeFi apps. > [card] [Prediction Markets & Trading](/pages/solutions/prediction-markets) > > Combine real-time execution, session keys, token custody, price feeds, automation, and settlement. > [card] [Solana VRF](/pages/verifiable-randomness-functions-vrfs/introduction/solana-vrf) > > Add provably fair onchain randomness to games, raffles, and real-time apps. > [card] [Pricing Oracle](/pages/tools/oracle/introduction) > > Access low-latency onchain price feeds for trading and DeFi. *** # Smart Contract Integration Source: https://docs.magicblock.gg/pages/ephemeral-spl-token/smart-contract-integration Custody and move SPL tokens from your own Solana program on an Ephemeral Rollup — PDA-signed transfers, delegation, and commit/undelegate. > [!TIP] > > **Building with an AI coding agent?** Install the MagicBlock Dev Skill to give your agent MagicBlock-specific patterns — delegation flows, Magic Actions, cranks, VRF, and more. > > **Hit an error?** Ask your coding agent with the skill installed, not the docs assistant. The assistant only sees the docs, so it cannot debug your code. > > Quick install for Claude Code: > > ```bash theme={null} > npx skills add https://github.com/magicblock-labs/magicblock-dev-skill > ``` > > Using Cursor, Codex, Windsurf, Cline, or another agent? See the [AI Dev Skill](/pages/overview/additional-information/ai-dev-skill) page for all install targets. *** ### Quick Access > [card] [binary-prediction](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/binary-prediction) > > eATA custody end to end > [card] [rewards-delegated-vrf](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/rewards-delegated-vrf) > > Base-layer post-commit payouts > [card] [spl-tokens](https://github.com/magicblock-labs/magicblock-engine-examples/tree/main/spl-tokens) > > Non-custody transfers This guide is for on-chain programs — a DEX, AMM, prediction market, escrow, or game — that hold user funds and move them at [Ephemeral Rollup](/pages/ephemeral-rollups-ers/introduction/ephemeral-rollup) speed. The core pattern: a program-owned account, delegated to the ER, with your program signing token transfers as a PDA. > [!NOTE] > > Moving tokens from a client instead of on-chain? See the > [Quickstart](/pages/ephemeral-spl-token/quickstart). ### Two custody models | Model | You delegate… | Tokens move… | Use when | | - | - | - | - | | **eATA custody** | a program-owned **ephemeral ATA (eATA)** | **on the ER**, PDA-signed | you settle or pay out inside the rollup (e.g. a market fill) | | **State PDA + post-commit payout** | only a **state PDA**; real ATAs stay on base | **on the base layer**, as a post-commit action | funds stay on L1 and settle on commit | The walkthrough below covers **eATA custody**, with the post-commit variant in the advanced snippets. *** ## Step-By-Step Guide Give your program authority over an eATA, delegate it, move funds PDA-signed on the ER, then settle back to Solana: **1. [Make your program ER-aware](#1-er-aware-program)** Add the `#[ephemeral]` attribute and import the SDK helpers. **2. [Create the custody PDA and eATA](#2-create-eata)** Own an eATA under the Ephemeral SPL Token program from your custody PDA. **3. [Delegate the eATA](#3-delegate-eata)** CPI into the Ephemeral SPL Token program to delegate it to the ER. **4. [Move tokens PDA-signed](#4-pda-signed-transfer)** Sign the transfer as the custody PDA inside the rollup. **5. [Commit & undelegate](#5-commit-undelegate)** Return the account to the base layer. *** ## Custody Example The following software packages may be required, other versions may also be compatible: | Software | Version | Installation Guide | | - | - | - | | **Solana** | 3.1.9 | [Install Solana](https://docs.anza.xyz/cli/install) | | **Rust** | 1.89.0 | [Install Rust](https://www.rust-lang.org/tools/install) | | **Anchor** | 1.0.2 | [Install Anchor](https://www.anchor-lang.com/docs/installation) | | **Node** | 24.10.0 | [Install Node](https://nodejs.org/en/download/current) | ### Code Snippets #### 1. ER-aware program Wrap `#[program]` with `#[ephemeral]` and import the SDK helpers you need. ```rust theme={null} use ephemeral_rollups_sdk::anchor::{commit, delegate, ephemeral}; use ephemeral_rollups_sdk::cpi::DelegateConfig; use ephemeral_rollups_sdk::ephem::MagicIntentBundleBuilder; #[ephemeral] #[program] pub mod your_program { use super::*; // ... } ``` [⬆️ Back to Top](#code-snippets) #### 2. Create eATA Your program owns a state PDA (for example, a `Pool`) that is the authority over the funds. Custody on the ER uses an **ephemeral ATA (eATA)** owned by that PDA, derived from `[owner, mint]` under the Ephemeral SPL Token program (`SPLxh1LVZzEkX99H6rqYizhytLWPZVV296zyYDPagv2`). ```rust theme={null} // The eATA is owned by your custody PDA (e.g. a Pool), derived under the // Ephemeral SPL Token program from [owner, mint]. let (eata, _bump) = Pubkey::find_program_address( &[owner.as_ref(), mint.as_ref()], &EPHEMERAL_SPL_TOKEN_PROGRAM_ID, ); // At initialize, create the eATA (InitializeEphemeralAta) and the per-mint // global vault that backs every eATA (InitializeGlobalVault), then fund it. ``` [⬆️ Back to Top](#code-snippets) #### 3. Delegate eATA Delegate the eATA with a CPI to the Ephemeral SPL Token program (`DelegateEphemeralAta`, discriminator `4`). > [!WARNING] > > Delegating a plain PDA-owned ATA directly to the ER is not supported — token custody on the ER > goes through an eATA. To delegate program *state* (not a token account), use the SDK's > `#[delegate]` macro instead. ```rust theme={null} // Delegate the eATA with a CPI to the Ephemeral SPL Token program. // An optional trailing validator pubkey routes to a specific validator. let mut data = vec![4]; // DelegateEphemeralAta if let Some(validator) = validator { data.extend_from_slice(validator.as_ref()); } let instruction = Instruction { program_id: EPHEMERAL_SPL_TOKEN_PROGRAM_ID, accounts: vec![ AccountMeta::new(payer.key(), true), AccountMeta::new(ephemeral_ata.key(), false), AccountMeta::new_readonly(EPHEMERAL_SPL_TOKEN_PROGRAM_ID, false), AccountMeta::new(buffer.key(), false), AccountMeta::new(record.key(), false), AccountMeta::new(metadata.key(), false), AccountMeta::new_readonly(delegation_program.key(), false), AccountMeta::new_readonly(system_program.key(), false), ], data, }; invoke(&instruction, &account_infos)?; ``` [⬆️ Back to Top](#code-snippets) #### 4. PDA-signed transfer With the eATA delegated, move tokens inside the rollup with an SPL Token CPI signed by the custody PDA via `CpiContext::new_with_signer`. The signer seeds are `[POOL_SEED, bump]` — the program authorizes the payout itself, with no user signature. ```rust theme={null} use anchor_spl::token::{self, Transfer as SplTransfer}; // The custody PDA signs the transfer — no user signature required. let bump_seed = [pool_bump]; let signer_seeds: &[&[&[u8]]] = &[&[POOL_SEED, &bump_seed]]; let cpi_accounts = SplTransfer { from, to, authority: pool, // the Pool PDA }; let cpi_ctx = CpiContext::new_with_signer(token_program.to_account_info(), cpi_accounts, signer_seeds); token::transfer(cpi_ctx, amount)?; ``` [⬆️ Back to Top](#code-snippets) #### Commit & undelegate Commit the ER state and return the account to the base layer with `MagicIntentBundleBuilder`. ```rust theme={null} // The #[commit] attribute on the accounts context supplies // magic_context and magic_program. MagicIntentBundleBuilder::new( ctx.accounts.payer.to_account_info(), ctx.accounts.magic_context.to_account_info(), ctx.accounts.magic_program.to_account_info(), ) .commit_and_undelegate(&[ctx.accounts.pool.to_account_info()]) .build_and_invoke()?; ``` [⬆️ Back to Top](#code-snippets) *** ### Advanced Code Snippets > [tab] Non-custody transfer > > If your program doesn't custody funds — it moves tokens between two already-delegated accounts on a > user's behalf — no PDA signer is needed. The authority is the user's `Signer`, with a plain > `CpiContext::new`. > > ```rust theme={null} > // No PDA signer — the authority is the user's Signer. > let cpi_accounts = SplTransfer { > from: ctx.accounts.from.to_account_info(), > to: ctx.accounts.to.to_account_info(), > authority: ctx.accounts.payer.to_account_info(), > }; > token::transfer(CpiContext::new(ctx.accounts.token_program.to_account_info(), cpi_accounts), amount)?; > ``` > > [⬆️ Back to Top](#advanced-code-snippets) > [tab] Base-layer post-commit payout > > To keep real token accounts on the base layer and delegate only program state, schedule the payout > as a post-commit action that runs PDA-signed on the base layer right after a commit — using > `transfer_checked` (Token-2022 compatible) and committing with the action attached. > > ```rust theme={null} > // Keep real token accounts on base, delegate only program state, and pay out > // PDA-signed on the base layer right after the commit. Use the PDA AccountInfo > // as the payer and pass its seeds to build_and_invoke_signed. > MagicIntentBundleBuilder::new( > payer_pda.to_account_info(), > magic_context.to_account_info(), > magic_program.to_account_info(), > ) > .magic_fee_vault(magic_fee_vault.to_account_info()) > .commit(&[state_pda.to_account_info()]) > .add_post_commit_actions([action]) > .build_and_invoke_signed(&[payer_seeds])?; > ``` > > > [!WARNING] > > > > The post-commit handler is a normal base-layer instruction — anyone can > > call it directly, not only the delegation program. Because it signs the > > transfer with your PDA, it **must authenticate the caller**; otherwise any > > wallet can invoke it directly and move your program's tokens without > > authorization. Require the injected `escrow` account as a `signer` and pin it > > to `ephemeral_balance_pda_from_payer(escrow_auth, 255)`, and bind > > `escrow_auth` to your paying PDA. See > > [Authenticate the caller](/pages/ephemeral-rollups-ers/magic-actions/troubleshooting#security-authenticate-the-caller). > > [⬆️ Back to Top](#advanced-code-snippets) *** ## Solana Explorer Get insights about your transactions and accounts on Solana: > [card] [Solana Explorer](https://explorer.solana.com/) > > Official Solana Explorer > [card] [Solscan](https://solscan.io/) > > Explore Solana Blockchain ## Solana RPC Providers Send transactions and requests through existing RPC providers: > [card] [Solana](https://solana.com/docs/references/clusters#on-a-high-level) > > Free Public Nodes > [card] [Helius](https://www.helius.dev/solana-rpc-nodes) > > Free Shared Nodes > [card] [Triton](https://triton.one/solana) > > Dedicated High-Performance Nodes ## Solana Validator Dashboard Find real-time updates on Solana's validator infrastructure: > [card] [Solana Beach](https://solanabeach.io/) > > Get Validator Insights > [card] [Validators App](https://www.validators.app/) > > Discover Validator Metrics ## Server Status Subscribe to Solana's and MagicBlock's server status: > [card] [Solana Status](https://status.solana.com/) > > Subscribe to Solana Server Updates > [card] [MagicBlock Status](/pages/overview/additional-information/system-status) > > Subscribe to MagicBlock Server Status *** # Why MagicBlock? Source: https://docs.magicblock.gg/pages/get-started/introduction/why-magicblock The high-performance engine for real-time applications on Solana [Why Build with MagicBlock? Solve Scaling & UX Pain Points with Ephemeral Rollups](https://www.youtube.com/embed/yfgDZJJvydU?si=3k8ndg9Z69sv6_LE\&list=PLWR_ZQiGMS8mIe1kPZe8OfHIbhvZqaM8V) > [card] > > MagicBlock is an extension of the Solana network designed for high-performance > decentralized applications. It enhances Solana’s capabilities while preserving > its composability and integrity. ## Why MagicBlock? While blockchain technology is revolutionizing decentralized applications, it still faces fundamental challenges in: * **Latency** – Blockchain transaction speeds are too slow for real-time applications. * **Cost** – Even "low-fee" blockchains can become expensive at scale. * **Scalability** – Current architectures struggle to handle high-throughput applications. * **Privacy** – Blockchains are by default public, meaning all data onchain can be read. MagicBlock solves these issues with an **ephemeral rollup**, enabling developers to build dApps that require **10 ms state transitions**, **gasless transactions**, and **horizontal scaling**. Here's how: #### Built on Solana's Ecosystem and Performance MagicBlock operates as a specialized **Solana Virtual Machine (SVM) runtime**, seamlessly integrating with Solana’s base layer. Developers deploying programs on Solana are fully compatible with the ephemeral rollup down to the bytecode, benefiting from the SVM’s high performance and robust ecosystem. ![](https://mintcdn.com/magicblock-42/5iyVpKJBt1PkwHw4/images/magicblock-solana.png?fit=max\&auto=format\&n=5iyVpKJBt1PkwHw4\&q=85\&s=a6a7ff9062fcd9cf190642db11def3ed) #### Overcoming Limitations in Scaling and Cost Traditional rollups and Solana’s current execution model have inherent constraints when handling resource-intensive applications. MagicBlock removes these limitations by enabling: * **Ultra-Low Latency (10 ms Block Time)**: Solana's default 400 ms block time is too slow for real-time applications. MagicBlock allows developers to customize execution environments while maintaining full compatibility. * **State Integrity Without Fragmentation**: Traditional rollups fragment application states across multiple environments, making interoperability difficult. MagicBlock prevents this by utilizing specialized RPC providers that **route and process transactions in parallel** between Solana’s base layer and ephemeral rollups. * **Near-Zero Transaction Fees**: Even Solana’s low fees (\~\$0.01 per transaction) can be expensive at scale. MagicBlock drastically reduces costs, enabling minimal or **zero-fee transactions**. * **Horizontal Scalability**: Standard rollups struggle to scale efficiently. MagicBlock enables **horizontal auto-scaling**, seamlessly spinning up multiple ephemeral rollups to process millions of transactions per second. ### Where do I start? > [card] [Ephemeral Rollup](/pages/ephemeral-rollups-ers/introduction/ephemeral-rollup) > > Learn how Ephemeral Rollups works > [card] [Magic Router](/pages/ephemeral-rollups-ers/introduction/magic-router) > > Learn how Magic Router works > [card] [Build](/pages/ephemeral-rollups-ers/how-to-guide/quickstart) > > Try out with Rust, Anchor, and Typescript > [card] [Use Cases](/pages/get-started/use-cases/introduction) > > Discover new ideas from examples > [card] [Frameworks and SDKs](/pages/tools/introduction) > > Dive into Frameworks and SDKs > [card] [Privacy](/pages/get-started/use-cases/privacy) > > Build private, verifiable applications with TEEs # AI Agents Source: https://docs.magicblock.gg/pages/get-started/use-cases/ai Unlock the next era of real-time on-chain AI #### 🔴 Problems with AI * **Centralized Control** – AI models are closed-source and biased. * **Opaque Decision-Making** – Users cannot verify AI logic or data. * **Monopoly on AI Access** – Only big tech controls AI resources. #### ⛓️ Current Blockchain Limitations * **Computational Cost** – On-chain AI execution is expensive. * **Data Availability** – Limited high-speed on-chain data for AI. * **Scalability** – AI models struggle with real-time blockchain inference. #### ⚡ MagicBlock's Solution * **Decentralized AI Models** – Open-source, auditable AI with trustless execution. * **Real-Time On-Chain Data** – AI can interact with verifiable blockchain state. * **Scalable AI Execution** – Optimized engine for fast, low-cost inference. ## Example: Ultra-Low Latency Decentralized AI Agent > [card] [Source Code](https://github.com/GabrielePicco/super-smart-contracts) > > Learn more about building and integrating Decentralized AI with MagicBlock! # DePIN Source: https://docs.magicblock.gg/pages/get-started/use-cases/depin Unlock the next era of real-time decentralized physical infrastructure networks #### 🔴 Problems with Infrastructure * **Centralized Control & Single Points of Failure** – Networks, supply chains, and financial systems rely on centralized entities, making them vulnerable to outages, corruption, or censorship. * **High Costs & Inefficiencies** – Multiple intermediaries slow down operations, increase costs, and introduce human errors. * **Lack of Transparency & Trust** – Data manipulation and fraud thrive in closed systems, making it hard to verify authenticity. #### ⛓️ Current Blockchain Limitations * **Scalability Challenges** – Most blockchains struggle with high transaction loads, limiting their use for real-time infrastructure needs. * **High Costs** – Rising gas fees make microtransactions and IoT integrations impractical. * **Latency & Finality Delays** – Many blockchains require multiple confirmations, preventing instant execution in critical applications. #### ⚡ MagicBlock’s Solution * **Real-Time, Low-Cost Transactions** – Eliminates bottlenecks, enabling seamless on-chain infrastructure. * **Scalable & Efficient** – Optimized for **high throughput** and **low fees**, making microtransactions viable. * **Verifiable & Trustless** – Provides a tamper-proof, open ledger for **transparent** and **decentralized** infrastructure. ## Example: Ultra-Low Latency On-Chain Payments > [card] [Source Code](https://github.com/magicblock-labs/magicblock-engine-examples) > > Learn more about building and integrating on-chain payments with MagicBlock! # Finance Source: https://docs.magicblock.gg/pages/get-started/use-cases/finance Unlock the next era of real-time decentralized finance ![](https://mintcdn.com/magicblock-42/5iyVpKJBt1PkwHw4/images/realtime-price-tracker.gif?s=0d92814394cb0978dcb9f84ec4b2b4e8) #### 🔴 Problems with Finance * **Slow Settlement** – Transactions take days to finalize due to intermediaries. * **Opaque Systems** – Users rely on centralized entities with limited visibility. * **Limited Composability** – Financial platforms operate in silos, restricting innovation. #### ⛓️ Current Blockchain Limitations * **High Latency** – Transactions take seconds or minutes to confirm. * **Scalability Issues** – Congestion leads to high gas fees and slow execution. * **Off-Chain Dependencies** – Many DeFi platforms rely on centralized price oracles. #### ⚡ MagicBlock's Solution * **Real-Time Settlement** – Transactions finalize instantly with low latency. * **Fully Transparent** – Programs provide auditable, tamper-proof execution. * **Seamless Composability** – Financial applications interconnect permissionlessly. ## Example: Ultra-Low Latency DeFi > [card] [Source Code: Real-Time Pricing Oracle](https://github.com/magicblock-labs/real-time-pricing-oracle) > > Learn more about building and integrating DeFi with MagicBlock! > [card] [Pyth Price Data Demo](https://pyth-template.magicblock.app/) > > Try out our live demo showcasing Pyth price data streams with MagicBlock # Games Source: https://docs.magicblock.gg/pages/get-started/use-cases/games Unlock the next era of real-time on-chain gaming