bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 17쪽 중 14쪽
ruct ComplexOutputStruct0 {
pub field_0: SharedEncryptedStruct<1>,
pub field_1: MXEEncryptedStruct<1>,
}
```
### Why this approach works
This two-step approach provides several benefits:
* **Type safety**: You get compile-time type checking for encrypted results
* **No manual definition**: You don't need to define output structs yourself
* **Consistency**: All generated types follow the same predictable patterns
* **Automatic updates**: If you change your function's return type, re-run `arcium build` and the structs update automatically
The key insight is that these structs exist in your compiled program but not in your source code: `arcium build` produces the interface files, and `#[callback_accounts]` turns them into Rust types during compilation.
## Understanding LEN parameters
In our `add_together` example, you saw `SharedEncryptedStruct<1>`. The `<LEN>` number tells you how many encrypted scalar values are stored inside.
The `<LEN>` number represents the count of individual encrypted scalar values:
| Return Type | LEN Value | Why |
| -------------------------- | ----------- | --------------------------------- |
| `Enc<Shared, u32>` | 1 | Single scalar |
| `Enc<Shared, (u32, bool)>` | 2 | Two scalars |
| `Enc<Shared, [u32; 5]>` | 5 | Five array elements |
| `Enc<Shared, MyStruct>` | field count | Count all scalar fields in struct |
**For custom structs**, LEN equals total scalar fields:
```rust theme={null}
struct UserProfile {
id: u32, // 1 scalar
balance: u64, // 1 scalar
active: bool, // 1 scalar
}
// Result: SharedEncryptedStruct<3>
```
## Type availability and scope
### Where generated types live
Generated types are scoped to the module where `#[callback_accounts]` is used. After running `arcium build`, the types become available during program compilation:
```rust theme={null}
// In your Solana program: CalculateOutput is generated by #[callback_accounts]
// which reads build/calculate.idarc (produced by arcium build from your #[instruction] function)
#[callback_accounts("calculate")]
pub struct CalculateCallback<'info> { /* ... */ }
#[arcium_callback(encrypted_ix = "calculate")]
pub fn calculate_callback(
ctx: Context<CalculateCallback>,
output: SignedComputationOutputs<CalculateOutput>,
) -> Result<()> {
// CalculateOutput is available here
}
```
### No import required
Unlike external types, you don't need to import generated types. `#[callback_accounts]` injects them directly into your module's namespace:
```rust theme={null}
// No need for: use some_crate::CalculateOutput;
// The type just exists automatically
```
### Generated struct properties
All generated structs automatically receive standard derives that make them work with Anchor:
```rust theme={null}
// Every generated struct gets these automatically:
#[derive(AnchorSerialize, AnchorDeserialize, Debug, Clone)]
pub struct YourFunctionOutput {
// fields...
}
```
This is why you can use generated types in Anchor contexts without additional setup.
### Multiple instructions, multiple types
Each `#[instruction]` produces its own `.idarc` file, so `#[callback_accounts]` generates a separate output type per circuit:
```rust theme={null}
#[instruction] pub fn add() -> Enc<Shared, u32> // → AddOutput
#[instruction] pub fn multiply() -> Enc<Shared, u32> // → MultiplyOutput
#[instruction] pub fn divide() -> Enc<Shared, u32> // → DivideOutput
```
All generated types coexist in the same module scope without conflicts.
## Generation process
When you define an encrypted instruction:
1. `arcium build` compiles your circuit and writes a `.idarc` interface file describing its return type
2. `#[callback_accounts]` reads the `.idarc` file at compile time and generates corresponding Rust structs with predictable names
3. Encryption patterns are detected automatically and produce specialized types
4. The generated types are available in your `#[arcium_callback]` functions
## How the naming works
The naming follows predictable patterns:
### Your circuit gets an output struct
If your encrypted instruction is called `add_together`, you get a struct called `AddTogetherOutput`. Arcium converts your circuit name to PascalCase and adds "Output" at the end.
### Fields are numbered
Since Anchor doesn't support tuple structs (yet), Arcium uses numbered fields instead. So if your function returns multiple values, you'll get `field_0`, `field_1`, `field_2`, and so on. Not the prettiest names, but they're consistent and predictable.
### Complex types get their own structs
When your function returns complex nested data (like tuples or custom structs), Arcium generates additional helper structs with a unified naming convention:
* All output structs use `{CircuitName}OutputStruct{index}` pattern
* Nested structs within outputs use `{ParentName}OutputStruct{parent_index}{field_index}` pattern
* The naming ensures uniqueness while maintaining consistency
## Encryption types: Shared vs MXE
Arcium automatically detects different encryption patterns and generates the right struct type. Understanding when each type is used helps you predict the generated structs.
### SharedEncryptedStruct\<N>
When your circuit returns `Enc<Shared, T>`, Arcium knows this is data that both the client and the MXE can decrypt. It generates a struct that includes everything needed for decryption:
```rust theme={null}
pub struct SharedEncryptedStruct<const LEN: usize> {
pub encryption_key: [u8; 32], // The shared public key
pub nonce: u128, // Random nonce for security
pub ciphertexts: [[u8; 32]; LEN], // Your actual encrypted data
}
```
The `<N>` part tells you how many encrypted values are packed inside. So `SharedEncryptedStruct<1>` has one encrypted value, `SharedEncryptedStruct<3>` has three, and so on.
In your callback, you can access everything you need:
```rust theme={null}
let shared_key = result.encryption_key; // For key exchange
let nonce = result.nonce; // For decryption
let encrypted_value = result.ciphertexts[0]; // Your data
```
### MXEEncryptedStruct\<N>
For `Enc<Mxe, T>` data, only the MXE cluster can decrypt it - clients can't. Since there's no shared secret needed, the struct is simpler:
```rust theme={null}
pub struct MXEEncryptedStruct<const LEN: usize> {
pub nonce: u128, // Still need the nonce
pub ciphertexts: [[u8; 32]; LEN], // Your encrypted data
}
```
Notice there's no `encryption_key` field here - that's because clients don't get to decrypt MXE data.
```rust theme={null}
// Working with MXE-encrypted data
let nonce = result.nonce;
let encrypted_value = result.ciphertexts[0];
// Note: You can't decrypt this on the client side!
```
### EncDataStruct\<N>
For encrypted data without key exchange metadata (used when the observer tracks encryption context client-side):
```rust theme={null}
// Pattern: Only N Ciphertexts
pub struct EncDataStruct<const LEN: usize> {
pub ciphertexts: [[u8; 32]; LEN], // Raw encrypted values
}
```
**Note**: `EncDataStruct<N>` is used when only ciphertext data is needed without additional metadata. See [`EncData<T>`](/developers/arcis/types#advanced-encdata%3Ct%3E) for when to use this pattern. Most applications use `SharedEncryptedStruct<N>` or `MXEEncryptedStruct<N>` instead.
## Moving to real-world applications
Now that you understand the basics with our simple addition example, here's how this works in real applications. The key difference is that real apps often:
* **Return multiple values**: Functions return tuples or complex structs instead of single values
* **Mix encryption types**: Some data for users (`Shared`), some for MXE only (`Mxe`)
* **Handle complex data**: Custom structs with multiple fields instead of simple numbers
The type generation system handles all of this automatically - you just need to understand the patterns.
## Real-world examples
Here's how this type generation works in actual Arcium applications:
### Simple tuple example
Let's start with something in between - a function that returns two related values:
```rust theme={null}
#[instruction]
pub fn calculate_stats(value: u32) -> (Enc<Shared, u32>, Enc<Shared, u32>) {
// Calculate both the square and double of a number
(value.square(), value * 2)
}
```
Since this returns a tuple `(Enc<Shared, u32>, Enc<Shared, u32>)`, Arcium generates:
```rust theme={null}
pub struct CalculateStatsOutput {
pub field_0: CalculateStatsOutputStruct0, // The whole tuple becomes one field
}
pub struct CalculateStatsOutputStruct0 {
pub field_0: SharedEncryptedStruct<1>, // First u32 (the square)
pub field_1: SharedEncryptedStruct<1>, // Second u32 (the double)
}
```
Notice how tuples get wrapped: the tuple itself becomes `field_0`, and its elements become `field_0`, `field_1`, etc.
### Voting application
Now let's look at a more realistic example. The [encrypted voting example](https://github.com/arcium-hq/examples/tree/main/voting) shows a perfect use case. You have poll data that only the MXE should see, and a user's vote that should be shared between the user and the MXE:
```rust theme={null}
// Example poll data structure (would be defined in your program)
#[derive(AnchorSerialize, AnchorDeserialize)]
pub struct PollData {
pub vote_count_yes: u32,
pub vote_count_no: u32,
pub is_active: bool,
}
#[instruction]
pub fn vote(
poll_data: Enc<Mxe, PollData>, // Poll results stay private
vote_choice: Enc<Shared, u8> // User can verify their vote
) -> (Enc<Mxe, PollData>, Enc<Shared, bool>) {
// ... voting logic that maintains privacy
}
```
Since this function returns a tuple `(Enc<Mxe, PollData>, Enc<Shared, bool>)`, Arcium generates:
```rust theme={null}
pub struct VoteOutput {
pub field_0: VoteOutputStruct0, // The whole tuple wraps into one field
}
pub struct VoteOutputStruct0 {
pub field_0: MXEEncryptedStruct<3>, // The updated poll data (vote_count_yes + vote_count_no + is_active = 3)
pub field_1: SharedEncryptedStruct<1>, // The vote confirmation (boolean)
}
```
Now in your callback, you can work with properly typed data instead of raw bytes:
```rust theme={null}
#[arcium_callback(encrypted_ix = "vote")]
pub fn vote_callback(
ctx: Context<VoteCallback>,
output: SignedComputationOutputs<VoteOutput>,
) -> Result<()> {
let o = match output.verify_output(
&ctx.accounts.cluster_account,
&ctx.accounts.computation_account
) {
Ok(VoteOutput { field_0 }) => field_0,
Err(_) => return Err(ErrorCode::AbortedComputation.into()),
};
let poll_data = o.field_0; // The updated poll (MXE only)
let vote_confirmation = o.field_1; // User's confirmation (shared)
// Emit an event with the user's confirmation
emit!(VoteEvent {
confirmation: vote_confirmation.ciphertexts[0],
nonce: vote_confirmation.nonce.to_le_bytes(),
});
Ok(())
}
```
### Coinflip application: back to basics
After seeing complex tuples and mixed encryption types, let's look at the simplest possible case. The [coinflip example](https://github.com/arcium-hq/examples/tree/main/coinflip) returns just a single encrypted boolean:
```rust theme={null}
#[instruction]
pub fn flip() -> Enc<Shared, bool> {
// Generate secure randomness in MPC
// Return encrypted result that client can decrypt
}
```
Arcium sees this returns `Enc<Shared, bool>` and creates:
```rust theme={null}
pub struct FlipOutput {
pub field_0: SharedEncryptedStruct<1>, // Just one boolean
}
```
Your callback:
```rust theme={null}
#[arcium_callback(encrypted_ix = "flip")]
pub fn flip_callback(
ctx: Context<FlipCallback>,
output: SignedComputationOutputs<FlipOutput>,
) -> Result<()> {
let o = match output.verify_output(
&ctx.accounts.cluster_account,
&ctx.accounts.computation_account
) {
Ok(FlipOutput { field_0 }) => field_0,
Err(_) => return Err(ErrorCode::AbortedComputation.into()),
};
// Emit the encrypted result - client will decrypt to see heads/tails
emit!(FlipEvent {
result: o.ciphertexts[0],
nonce: o.nonce.to_le_bytes(),
});
Ok(())
}
```
### Blackjack application
From the [blackjack example](https://github.com/arcium-hq/examples/tree/main/blackjack) with complex game state:
```rust theme={null}
// Example structures (would be defined in your blackjack program)
#[derive(AnchorSerialize, AnchorDeserialize)]
pub struct GameState {
pub deck_cards: [u8; 52],
pub dealer_cards: [u8; 10],
pub round_number: u32,
pub game_active: bool,
pub house_balance: u64,
}
#[derive(AnchorSerialize, AnchorDeserialize)]
pub struct PlayerHand {
pub cards: [u8; 10],
pub card_count: u8,
pub bet_amount: u64,
}
#[instruction]
pub fn player_hit(
game_state: Enc<Mxe, GameState>,
player_hand: Enc<Shared, PlayerHand>
) -> (Enc<Mxe, GameState>, Enc<Shared, PlayerHand>, Enc<Shared, bool>) {
// ... game logic
}
```
**Generated types**:
```rust theme={null}
pub struct PlayerHitOutput {
pub field_0: PlayerHitOutputStruct0,
}
pub struct PlayerHitOutputStruct0 {
pub field_0: MXEEncryptedStruct<65>, // Updated game state (deck_cards[52] + dealer_cards[10] + round_number[1] + game_active[1] + house_balance[1] = 65)
pub field_1: SharedEncryptedStruct<12>, // Player's new hand (cards[10] + card_count[1] + bet_amount[1] = 12)
pub field_2: SharedEncryptedStruct<1>, // Is game over? (boolean)
}
```
## Complex nested structures
For more complex outputs with nested data structures:
```rust theme={null}
// Define the custom struct used in the circuit
#[derive(AnchorSerialize, AnchorDeserialize)]
pub struct UserData {
pub id: u32,
pub active: bool,
}
#[instruction]
pub fn complex_example() -> (
UserData,
Enc<Shared, u32>,
(u64, f32),
Enc<Mxe, bool>
) {
// ... complex logic
}
```
**Generated types**:
```rust theme={null}
pub struct ComplexExampleOutput {
pub field_0: ComplexExampleOutputStruct0, // Entire tuple as single field
}
pub struct ComplexExampleOutputStruct0 {
pub field_0: ComplexExampleOutputStruct00, // UserData
pub field_1: SharedEncryptedStruct<1>, // Enc<Shared, u32>
pub field_2: ComplexExampleOutputStruct02, // (u64, f32) tuple
pub field_3: MXEEncryptedStruct<1>, // Enc<Mxe, bool>
}
pub struct ComplexExampleOutputStruct00 {
pub field_0: u32, // UserData.id
pub field_1: bool, // UserData.active
}
pub struct ComplexExampleOutputStruct02 {
pub field_0: u64, // First tuple element
pub field_1: f32, // Second tuple element
}
```
**Notice the naming pattern**: We have `ComplexExampleOutputStruct00` and `ComplexExampleOutputStruct02`, but no `ComplexExampleOutputStruct01`. This is because:
* `field_0` (UserData) needs a custom struct → `ComplexExampleOutputStruct00`
* `field_1` (SharedEncryptedStruct) uses a predefined type → no custom struct needed
* `field_2` ((u64, f32) tuple) needs a custom struct → `ComplexExampleOutputStruct02`
* `field_3` (MXEEncryptedStruct) uses a predefined type → no custom struct needed
Only fields that contain custom structs or tuples get their own generated struct definitions.
## Working with generated types
### Pattern matching
Use destructuring to access nested data:
```rust theme={null}
let ComplexExampleOutputStruct0 {
field_0: user_data,
field_1: shared_encrypted,
field_2: tuple_data,
field_3: mxe_encrypted,
} = match output.verify_output(
&ctx.accounts.cluster_account,
&ctx.accounts.computation_account,
) {
Ok(ComplexExampleOutput { field_0 }) => field_0,
Err(_) => return Err(ErrorCode::AbortedComputation.into()),
};
// Access specific fields
let user_id = user_data.field_0;
let is_active = user_data.field_1;
let shared_value = shared_encrypted.ciphertexts[0];
let timestamp = tuple_data.field_0;
```
### Error handling
Always handle computation failures:
```rust theme={null}
let result = match output.verify_output(
&ctx.accounts.cluster_account,
&ctx.accounts.computation_account,
) {
Ok(data) => data,
Err(_) => return Err(ErrorCode::AbortedComputation.into()),
};
```
## Best practices
### 1. Use descriptive variable names
```rust theme={null}
// Good
let FlipOutput { field_0: coin_result } = result;
let is_heads = coin_result.ciphertexts[0];
// Less clear
let FlipOutput { field_0 } = result;
let result = field_0.ciphertexts[0];
```
### 2. Document your circuit interfaces
```rust theme={null}
/// Returns (updated_game_state, player_hand, is_game_over)
#[instruction]
pub fn player_hit(/* ... */) -> (Enc<Mxe, GameState>, Enc<Shared, PlayerHand>, Enc<Shared, bool>) {
// ...
}
```
### 3. Handle all computation states
```rust theme={null}
let result = match output.verify_output(
&ctx.accounts.cluster_account,
&ctx.accounts.computation_account,
) {
Ok(data) => data,
Err(_) => return Err(ErrorCode::AbortedComputation.into()),
};
```
### 4. Emit events for client tracking
```rust theme={null}
emit!(ComputationCompleteEvent {
computation_id: ctx.accounts.computation_account.key(),
success: true,
result_hash: result.ciphertexts[0], // or use a hash function if needed
});
```
## When things go wrong
Here are the most common issues and how to fix them:
### "Type not found" errors
```rust theme={null}
// Error: cannot find type `MyCircuitOutput` in this scope
output: SignedComputationOutputs<MyCircuitOutput>
```
This usually means one of two things:
1. **Typo in the circuit name** - Check that `MyCircuit` exactly matches your `#[instruction]` function name (case matters!)
2. **You forgot to rebuild** - Run `arcium build` again after making changes to your encrypted instructions
### "No field found" errors
```rust theme={null}
// Error: no field `result` on type `AddTogetherOutput`
let value = output.result;
```
Remember, the generated structs use numbered fields like `field_0`, `field_1`, etc. There's no field called `result` unless you specifically named your function that way.
Try this instead:
```rust theme={null}
let value = output.field_0; // First (and often only) field
```
### Encryption type mismatches
```rust theme={null}
// Error: expected `SharedEncryptedStruct<1>`, found `MXEEncryptedStruct<1>`
```
This happens when your circuit returns `Enc<Mxe, T>` but your callback expects `Enc<Shared, T>` (or vice versa). Double-check your encrypted instruction's return type - it needs to match what you're expecting in the callback.
## Callback not working? Check these:
* [ ] Circuit name matches exactly (case sensitive)
* [ ] Ran `arcium build` after changing circuit
* [ ] Handling `verify_output` Ok/Err
* [ ] Using correct field numbers (field\_0, field\_1, etc.)
* [ ] Array access within bounds (ciphertexts.len())
## Finding generated types
The best way to see generated types:
```bash theme={null}
# First install cargo-expand if you haven't already
cargo install cargo-expand
# In your program directory
cargo expand | grep "YourCircuitOutput" -A 20
```
This shows exactly what structs were generated for your circuit.
You can also search the full output:
```bash theme={null}
cargo expand > expanded.rs
# Then search expanded.rs for your circuit name
```
## Array and complex type handling
### Fixed-size arrays
When your circuit returns arrays, each element becomes a separate scalar in the LEN count:
```rust theme={null}
#[instruction]
pub fn process_batch() -> Enc<Shared, [u32; 3]> {
// Process multiple values at once
[result1, result2, result3]
}
```
This generates `SharedEncryptedStruct<3>` because the array has 3 elements:
```rust theme={null}
pub struct ProcessBatchOutput {
pub field_0: SharedEncryptedStruct<3>, // Array of 3 u32s
}
```
In your callback, access individual elements:
```rust theme={null}
let encrypted_array = result.field_0;
let first_element = encrypted_array.ciphertexts[0]; // result1
let second_element = encrypted_array.ciphertexts[1]; // result2
let third_element = encrypted_array.ciphertexts[2]; // result3
```
### Nested structures
For deeply nested data, LEN counts **all scalar values** at any depth:
```rust theme={null}
pub struct Position {
pub x: u32,
pub y: u32,
}
pub struct Entity {
pub position: Position, // 2 scalars (x, y)
pub health: u32, // 1 scalar
pub alive: bool, // 1 scalar
}
// Total: 2 + 1 + 1 = 4 s프로젝트로 돌아가기