Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/test-examples.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@ jobs:
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
node-version: "20"

- name: Enable Corepack
run: corepack enable

- name: Setup Rust
uses: actions-rs/toolchain@v1
with:
toolchain: "1.85.0"
toolchain: stable
override: true

- name: Install Solana
Expand Down
2 changes: 2 additions & 0 deletions pinocchio-ephemeral-permission-counter/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Private Key (optional - will be generated if not provided)
# PRIVATE_KEY=[...]
13 changes: 13 additions & 0 deletions pinocchio-ephemeral-permission-counter/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/target
**/*.rs.bk
.DS_Store
Cargo.lock
.env
node_modules/
dist/
build/
*.log
.vscode
.idea
.pnp.cjs
.pnp.loader.mjs
1 change: 1 addition & 0 deletions pinocchio-ephemeral-permission-counter/.yarnrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
nodeLinker: node-modules
17 changes: 17 additions & 0 deletions pinocchio-ephemeral-permission-counter/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "pinocchio-ephemeral-permission-counter"
version = "0.1.0"
edition = "2021"

[lib]
crate-type = ["cdylib"]

[features]
logging = []

[dependencies]
pinocchio = { version = "0.10.1", features = ["cpi", "copy"] }
pinocchio-log = { version = "0.5.1" }
pinocchio-system = { version = "0.5" }
solana-address = { version = "2.6", features = ["syscalls"] }
ephemeral-rollups-pinocchio = { git = "https://github.com/magicblock-labs/ephemeral-rollups-sdk.git", rev = "a8ecea450d3bbe5bac119a3f4c55cd9f96b4837b" }
21 changes: 21 additions & 0 deletions pinocchio-ephemeral-permission-counter/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 MagicBlock Labs

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
96 changes: 96 additions & 0 deletions pinocchio-ephemeral-permission-counter/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Pinocchio Ephemeral Permission Counter

A minimal Solana counter program built with [Pinocchio](https://github.com/anza-xyz/pinocchio) and MagicBlock Ephemeral Rollups. The example shows how to initialize a counter PDA, delegate it to an Ephemeral Rollup, protect it with ephemeral permissions, and commit the final state back to the base layer.

The program is `no_std`, does not use Borsh, and keeps account data in a fixed-size `Counter` struct.

## Requirements

| Software | Version | Installation Guide |
| ---------- | ------- | ----------------------------------------------------------- |
| Solana CLI | 2.3.13 | [Install Solana](https://docs.anza.xyz/cli/install) |
| Rust | 1.87.0 | [Install Rust](https://www.rust-lang.org/tools/install) |
| Node.js | 24.10.0 | [Install Node](https://nodejs.org/en/download/current) |
| Yarn | 4.x | [Install Yarn](https://yarnpkg.com/getting-started/install) |

## Setup

Install the TypeScript test dependencies:

```bash
yarn install
```

The tests read `PRIVATE_KEY` from the environment, or fall back to `~/.config/solana/id.json`.

```bash
cp .env.example .env
```

Optional RPC overrides:

- `PROVIDER_ENDPOINT`
- `WS_ENDPOINT`
- `EPHEMERAL_PROVIDER_ENDPOINT`
- `EPHEMERAL_WS_ENDPOINT`

## Build

```bash
yarn build
```

This runs:

```bash
cargo build-sbf
```

## Test

Run the Vitest integration flow:

```bash
yarn test
```

The test initializes the counter on Solana devnet, delegates it to the Ephemeral Rollup, increments it on both layers, creates/updates/closes a permission account, and commits the delegated state back to Solana.

## Program Model

The counter PDA is derived with:

```text
["counter", id]
```

where `id` is a 32-byte client-provided public key. The account stores:

| Field | Size | Description |
| ------- | -------- | --------------------------------- |
| `id` | 32 bytes | Identifier used in the PDA seeds |
| `count` | 8 bytes | Little-endian `u64` counter value |
| `bump` | 1 byte | PDA bump |
| `_pad` | 7 bytes | Alignment padding |

Total size: 48 bytes.

## Instructions

Each instruction starts with an 8-byte little-endian discriminator.

| Discriminator | Instruction | Payload | Description |
| ------------- | --------------------- | --------------------- | ---------------------------------------------------------------------- |
| `0` | `InitializeCounter` | `id` (`[u8; 32]`) | Creates the counter PDA and initializes `count` to `0`. |
| `1` | `IncreaseCounter` | `increase_by` (`u64`) | Adds `increase_by` to the counter with overflow checking. |
| `2` | `Delegate` | None | Delegates the counter PDA to the Ephemeral Rollups delegation program. |
| `3` | `CommitAndUndelegate` | None | Commits the counter state and undelegates it back to the base layer. |
| `4` | `CreatePermission` | None | Creates a private ephemeral permission for the counter. |
| `5` | `UpdatePermission` | None | Updates the counter permission membership. |
| `6` | `ClosePermission` | None | Closes the counter permission account. |

The delegation program also invokes the undelegation callback discriminator:

```text
[196, 28, 41, 206, 48, 37, 51, 167]
```
35 changes: 35 additions & 0 deletions pinocchio-ephemeral-permission-counter/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "pinocchio-ephemeral-permission-counter",
"version": "0.1.0",
"description": "Tests for pinocchio-ephemeral-permission-counter program",
"main": "index.js",
"scripts": {
"test": "vitest run tests/",
"test:watch": "vitest watch tests/",
"build": "cargo build-sbf",
"check": "cargo check"
},
"keywords": [
"solana",
"pinocchio",
"ephemeral",
"permission",
"counter",
"program"
],
"author": "",
"license": "MIT",
"devDependencies": {
"@magicblock-labs/ephemeral-rollups-sdk": "^0.11.1",
"@solana-program/system": "^0.10.0",
"@solana/kit": "^5.4.0",
"@solana/web3.js": "^1.93.0",
"@types/node": "^20.0.0",
"borsh": "^0.7.0",
"dotenv": "^16.0.0",
"ts-node": "^10.9.0",
"tweetnacl": "^1.0.3",
"typescript": "^5.0.0",
"vitest": "^3.0.0"
}
}
178 changes: 178 additions & 0 deletions pinocchio-ephemeral-permission-counter/src/entrypoint.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
use crate::processor::{
process_close_permission, process_commit_and_undelegate, process_create_permission,
process_delegate, process_increase_counter, process_initialize_counter,
process_undelegation_callback, process_update_permission,
};
use core::{mem::MaybeUninit, slice::from_raw_parts};
use pinocchio::{
entrypoint::deserialize, error::ProgramError, no_allocator, nostd_panic_handler, AccountView,
Address, ProgramResult, MAX_TX_ACCOUNTS, SUCCESS,
};

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum InstructionDiscriminator {
InitializeCounter,
IncreaseCounter,
Delegate,
CommitAndUndelegate,
CreatePermission,
UpdatePermission,
ClosePermission,
UndelegationCallback,
}

impl InstructionDiscriminator {
const INITIALIZE_COUNTER: [u8; 8] = [0, 0, 0, 0, 0, 0, 0, 0];
const INCREASE_COUNTER: [u8; 8] = [1, 0, 0, 0, 0, 0, 0, 0];
const DELEGATE: [u8; 8] = [2, 0, 0, 0, 0, 0, 0, 0];
const COMMIT_AND_UNDELEGATE: [u8; 8] = [3, 0, 0, 0, 0, 0, 0, 0];
const CREATE_PERMISSION: [u8; 8] = [4, 0, 0, 0, 0, 0, 0, 0];
const UPDATE_PERMISSION: [u8; 8] = [5, 0, 0, 0, 0, 0, 0, 0];
const CLOSE_PERMISSION: [u8; 8] = [6, 0, 0, 0, 0, 0, 0, 0];
// Undelegation callback called by the delegation program
const UNDELEGATION_CALLBACK: [u8; 8] = [196, 28, 41, 206, 48, 37, 51, 167];

fn from_bytes(bytes: [u8; 8]) -> Result<Self, ProgramError> {
match bytes {
Self::INITIALIZE_COUNTER => Ok(Self::InitializeCounter),
Self::INCREASE_COUNTER => Ok(Self::IncreaseCounter),
Self::DELEGATE => Ok(Self::Delegate),
Self::COMMIT_AND_UNDELEGATE => Ok(Self::CommitAndUndelegate),
Self::CREATE_PERMISSION => Ok(Self::CreatePermission),
Self::UPDATE_PERMISSION => Ok(Self::UpdatePermission),
Self::CLOSE_PERMISSION => Ok(Self::ClosePermission),
Self::UNDELEGATION_CALLBACK => Ok(Self::UndelegationCallback),
_ => Err(ProgramError::InvalidInstructionData),
}
}
}

// Do not allocate memory.
no_allocator!();
// Use the no_std panic handler.
nostd_panic_handler!();

#[no_mangle]
#[allow(clippy::arithmetic_side_effects)]
pub unsafe extern "C" fn entrypoint(input: *mut u8) -> u64 {
const UNINIT: MaybeUninit<AccountView> = MaybeUninit::<AccountView>::uninit();
let mut accounts = [UNINIT; { MAX_TX_ACCOUNTS }];

let (program_id, count, instruction_data) =
deserialize::<MAX_TX_ACCOUNTS>(input, &mut accounts);

match process_instruction(
program_id,
from_raw_parts(accounts.as_ptr() as _, count),
instruction_data,
) {
Ok(()) => SUCCESS,
Err(error) => error.into(),
}
}

/// Log an error.
#[cold]
fn log_error(_error: &ProgramError) {
#[cfg(feature = "logging")]
pinocchio_log::log!("Program error");
}

/// Process an instruction.
#[inline(always)]
pub fn process_instruction(
program_id: &Address,
accounts: &[AccountView],
instruction_data: &[u8],
) -> ProgramResult {
let result = inner_process_instruction(program_id, accounts, instruction_data);
result.inspect_err(log_error)
}

/// Process an instruction.
#[inline(always)]
pub(crate) fn inner_process_instruction(
_program_id: &Address,
accounts: &[AccountView],
instruction_data: &[u8],
) -> ProgramResult {
if instruction_data.len() < 8 {
return Err(ProgramError::InvalidInstructionData);
}

let discriminator: [u8; 8] = instruction_data[..8]
.try_into()
.map_err(|_| ProgramError::InvalidInstructionData)?;
let discriminator = InstructionDiscriminator::from_bytes(discriminator)?;
let payload = instruction_data
.get(8..)
.ok_or(ProgramError::InvalidInstructionData)?;

#[cfg(feature = "logging")]
log_instruction(discriminator);

match discriminator {
InstructionDiscriminator::InitializeCounter => {
let id = Address::new_from_array(
payload
.get(..32)
.ok_or(ProgramError::InvalidInstructionData)?
.try_into()
.map_err(|_| ProgramError::InvalidInstructionData)?,
);
process_initialize_counter(accounts, &id)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
InstructionDiscriminator::IncreaseCounter => {
let increase_by = read_u64(payload)?;
process_increase_counter(accounts, increase_by)
}
InstructionDiscriminator::Delegate => process_delegate(accounts),
InstructionDiscriminator::CommitAndUndelegate => process_commit_and_undelegate(accounts),
InstructionDiscriminator::CreatePermission => process_create_permission(accounts),
InstructionDiscriminator::UpdatePermission => process_update_permission(accounts),
InstructionDiscriminator::ClosePermission => process_close_permission(accounts),
InstructionDiscriminator::UndelegationCallback => {
process_undelegation_callback(accounts, payload)
}
}
}

fn read_u64(input: &[u8]) -> Result<u64, ProgramError> {
if input.len() < 8 {
return Err(ProgramError::InvalidInstructionData);
}
let mut bytes = [0u8; 8];
bytes.copy_from_slice(&input[..8]);
Ok(u64::from_le_bytes(bytes))
}

#[allow(unused_variables)]
#[cfg(feature = "logging")]
fn log_instruction(discriminator: InstructionDiscriminator) {
match discriminator {
InstructionDiscriminator::InitializeCounter => {
pinocchio_log::log!("InitializeCounter");
}
InstructionDiscriminator::IncreaseCounter => {
pinocchio_log::log!("IncreaseCounter");
}
InstructionDiscriminator::Delegate => {
pinocchio_log::log!("Delegate");
}
InstructionDiscriminator::CommitAndUndelegate => {
pinocchio_log::log!("CommitAndUndelegate");
}
InstructionDiscriminator::CreatePermission => {
pinocchio_log::log!("CreatePermission");
}
InstructionDiscriminator::UpdatePermission => {
pinocchio_log::log!("UpdatePermission");
}
InstructionDiscriminator::ClosePermission => {
pinocchio_log::log!("ClosePermission");
}
InstructionDiscriminator::UndelegationCallback => {
pinocchio_log::log!("UndelegationCallback");
}
}
}
Loading
Loading