bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 17쪽 중 6쪽
ve(Copy, Clone)]
struct Point { x: i16, y: i16 }
```
See [Types](/developers/arcis/types) for complete reference.
## Control flow
```rust theme={null}
// if/else: when condition is not a compile-time constant, both branches execute
let result = if condition { a } else { b };
// if without else (for side effects)
if should_update {
counter += 1;
}
// else if chains work normally
let category = if value < 10 {
0
} else if value < 100 {
1
} else {
2
};
// for loops: fixed iteration count required
for i in 0..10 {
process(arr[i]);
}
// match expressions with literal, range, struct, tuple, array patterns and guards
let bucket = match x {
v if v < 5 => 0,
v if v < 10 => 1,
_ => 2,
};
// plain if let
if let Point { x: 0, y } = p {
y
} else {
-1
}
// if let combined with && requires edition = "2024" in encrypted-ixs/Cargo.toml
if let Point { x: 0, y } = p && y > 0 {
y
} else {
-1
}
// matches! macro
let in_range = matches!(x, 0..=9);
let is_small = matches!(x, 0 | 1 | 2);
```
## Functions
```rust theme={null}
// Helper function
fn helper(a: u8, b: u8) -> u16 {
a as u16 + b as u16
}
// Closures
let double = |x: u8| x * 2;
// Generics
fn set_zero<T: ArcisType + Copy>(a: &mut T) {
*a = make_zero(*a);
}
```
See [Operations](/developers/arcis/operations#generics) for generics and traits.
## Arrays
```rust theme={null}
let arr: [u8; 10] = [0; 10];
// Constant index: O(1)
let x = arr[5];
// Secret index: O(n)
let y = arr[secret_idx];
// Methods
arr.swap(0, 1);
arr.reverse();
arr.fill(42);
arr.sort(); // O(n·log²(n)·bit_size)
```
## Iterators
```rust theme={null}
// Basic iteration
for val in arr.iter() {
sum += *val;
}
// Chaining
arr.iter().map(|x| *x * 2).sum()
```
See [Operations](/developers/arcis/operations#iterators) for complete iterator support. Note: `.filter()` is not supported.
## Encryption patterns
```rust theme={null}
// Shared: client + MXE can decrypt
fn process(input: Enc<Shared, u64>) -> Enc<Shared, u64>
// MXE-owned: only MXE can decrypt
fn process_state(state: Enc<Mxe, GameState>) -> Enc<Mxe, GameState>
// Reveal (use carefully)
let plain = secret.reveal();
// Create MXE-owned data
let mxe_data = Mxe::get().from_arcis(value);
// EncData output (smaller callback payload)
fn verify(a: Enc<Shared, T>, observer: Shared) -> EncData<bool> {
observer.from_arcis(result).data
}
```
See [Input/Output](/developers/arcis/input-output) for details. For `EncData` usage, see [Types](/developers/arcis/types#advanced-encdata%3Ct%3E).
## Randomness
```rust theme={null}
let coin = ArcisRNG::bool();
let num = ArcisRNG::gen_integer_from_width(64);
let uniform = ArcisRNG::gen_uniform::<[u8; 32]>();
ArcisRNG::shuffle(&mut arr);
let (val, ok) = ArcisRNG::gen_integer_in_range(1, 100, 24);
```
See [Primitives](/developers/arcis/primitives#random-number-generation) for complete RNG reference.
## Cryptography
```rust theme={null}
// Hashing
let hash = SHA3_256::new().digest(&data).reveal();
// Signature verification
let valid = vk.verify(&message, &signature).reveal();
// Key generation
let sk = SecretKey::new_rand();
let vk = VerifyingKey::from_secret_key(&sk);
// MXE signing
let sig = MXESigningKey::sign(&message).reveal();
```
See [Primitives](/developers/arcis/primitives#cryptographic-operations) for complete crypto reference.
## Field arithmetic
```rust theme={null}
// Construct
let a = BaseField25519::from_u64(42);
let b = BaseField25519::power_of_two(8); // 256
// Arithmetic (mod 2^255 - 19)
let c = a + b;
let d = a * b;
let e = -a;
// Division (no / operator: use methods)
let inv = b.safe_inverse(); // 0 if b == 0
let quot = a.field_division(b); // 0 if b == 0
let euc = a.euclidean_division(b); // panics if b == 0
// Extract
let n: u64 = c.to_u64_unchecked(); // incorrect result if value exceeds u64 range
let bytes = c.to_le_bytes(); // [u8; 32]
```
See [Primitives](/developers/arcis/primitives#basefield25519-operations) for complete reference.
## Data packing
```rust theme={null}
// Pack for efficient storage
let packed = Pack::new(data);
// Unpack to use
let data: [u8; 64] = packed.unpack();
```
See [Primitives](/developers/arcis/primitives#data-packing) for details.
## Debugging
```rust theme={null}
println!("value = {}", x);
debug_assert!(x > 0, "x must be positive");
```
See [Best practices](/developers/arcis/best-practices#debugging) for debugging strategies.
## Testing
```rust theme={null}
#[cfg(test)]
mod tests {
#[test]
fn test_helper() {
// Only non-#[instruction] functions can be unit tested
assert_eq!(helper(1, 2), 3);
}
}
```
See [Best practices](/developers/arcis/best-practices#testing) for testing strategies.
## What's next?
Ready to build? Start here:
<CardGroup>
<Card title="Hello World" icon="rocket" href="/developers/hello-world">
Build your first Arcis circuit step-by-step.
</Card>
<Card title="Solana integration" icon="link" href="/developers/program">
Invoke circuits from your Solana program.
</Card>
<Card title="JavaScript client" icon="js" href="/developers/js-client-library">
Call circuits from TypeScript.
</Card>
</CardGroup>
# Types
Source: https://docs.arcium.com/developers/arcis/types
Supported types in Arcis: integers, floats, arrays, structs, and encrypted types
The following types are supported:
* `u8`, `u16`, `u32`, `u64`, `u128`, `usize`, `i8`, `i16`, `i32`, `i64`, `i128`, `isize`
* `f64`, `f32` (emulated as fixed-point with 52 fractional bits; supported range is `[-2^75, 2^75)`. Values outside this range are unsupported.)
* tuples of supported types, including `()`
* fixed-length arrays of a supported type
* slices with compile-time known length (e.g., `&arr[..]` from fixed arrays, or `&[u8]` parameters in stdlib APIs like SHA3)
* compile-time known ranges
* (mutable) references to a supported type
* user-defined structs of supported types
* user-defined enums of supported types (but not as input or output of an encrypted instruction; explicit discriminants are unsupported)
* `Option<T>` of a supported type (but not as input or output of an encrypted instruction)
* functions (but not as input or output of an encrypted instruction)
* `ArcisX25519Pubkey`, an Arcis public key wrapper.
* Arcis-defined `Enc`, `Mxe` and `Shared`.
* `Pack<T>`, a wrapper for bit-packing data into fewer field elements for onchain storage.
* `EncData<T>`, encrypted data without embedded cipher info. Use with `.to_arcis_with_pubkey_and_nonce()` when multiple values share the same key.
* `BaseField25519`, integers modulo `2^255 - 19`. The native field element for Arcis MPC circuits. Supports arithmetic (`+`, `-`, `*`, negation), unsigned comparisons, and field division methods. Construct via `BaseField25519::from_u64(x)` (and similar `from_*` methods); extract via `.to_u64_unchecked()` (only when the value fits the target type -- out-of-range values silently produce incorrect results). See [Primitives](/developers/arcis/primitives#basefield25519-operations).
<Warning>
**Float emulation**: Arcis emulates `f64`/`f32` as fixed-point with 52 fractional bits. This differs from IEEE 754 floats:
* Different precision characteristics than standard floats
* Supported range: `[-2^75, 2^75)`
* **Float literals outside this range produce a compile-time error:** `"Arcis only supports inputs in the range [-2**75, 2**75)"`
* **Computed values outside this range are silently clamped** to the boundary values
</Warning>
## Encryption types
| Type | Description |
| ---------------- | -------------------------------------------- |
| `Enc<Shared, T>` | Encrypted data shared between client and MXE |
| `Enc<Mxe, T>` | Encrypted data for MXE only |
| `EncData<T>` | Raw encrypted data (advanced use, see below) |
| `Shared` | Owner type for client-shared encryption |
| `Mxe` | Owner type for MXE-only encryption |
The `Owner` type parameter determines who can decrypt:
* **`Shared`**: Both client and MXE can decrypt. Use for user inputs/outputs that need client-side verification.
* **`Mxe`**: Only the MXE cluster can decrypt. Use for internal protocol state that users should not access.
## Public key types
| Type | Description |
| --------------------------- | -------------------------------------------- |
| `ArcisX25519Pubkey` | Arcis X25519 public key wrapper |
| `SolanaPublicKey` | Solana public key (32 bytes) |
| `SerializedSolanaPublicKey` | Serialized form using `{lo: u128, hi: u128}` |
## Example
```rust theme={null}
use arcis::*;
#[encrypted]
mod types_example {
use arcis::*;
#[derive(Copy, Clone)]
struct GameState {
score: u64,
level: u8,
}
#[instruction]
fn example(
user_data: Enc<Shared, u64>,
state: Enc<Mxe, GameState>,
) -> Enc<Shared, u64> {
let value = user_data.to_arcis();
user_data.owner.from_arcis(value * 2)
}
}
```
## Advanced: EncData\<T>
`EncData<T>` stores just the encrypted ciphertext without encryption metadata (pubkey + nonce).
| Type | Contains | Size |
| ------------------- | --------------------------------------------- | ---------- |
| `Enc<Shared, bool>` | pubkey (32B) + nonce (16B) + ciphertext (32B) | \~80 bytes |
| `EncData<bool>` | ciphertext only | \~32 bytes |
`EncData<T>` omits pubkey and nonce metadata, useful for multiple outputs where callback payload size matters.
### Primary use: smaller callback payloads
Use `EncData<T>` when returning encrypted data to observers to reduce callback payload size:
```rust theme={null}
#[instruction]
pub fn check_solana_public_key_equality(
encrypted_pk1: Enc<Shared, SerializedSolanaPublicKey>,
encrypted_pk2: Enc<Shared, SerializedSolanaPublicKey>,
observer: Shared,
) -> EncData<bool> {
let pk1 = SolanaPublicKey::from_serialized(encrypted_pk1.to_arcis());
let pk2 = SolanaPublicKey::from_serialized(encrypted_pk2.to_arcis());
let res = pk1 == pk2;
observer.from_arcis(res).data // Extract .data from Enc
}
```
**When to use `EncData` output:** Multiple return values where encryption metadata would be redundant.
<Note>
When returned from circuits, `EncData<T>` generates `EncDataStruct<N>` in your Solana program, where N is the number of field elements in T (e.g., `EncData<bool>` → `EncDataStruct<1>`). See [Callback type generation](/developers/program/callback-type-generation).
</Note>
<Tip>
The MXE encrypts outputs with `nonce + 1`. See [Encryption overview](/developers/encryption) for nonce handling.
</Tip>
### Secondary use: shared key input optimization
When multiple inputs share the same encryption key, `Enc<Shared, T>` duplicates the key-derivation circuit for each input. Use `EncData<T>` with explicit key/nonce to avoid this:
```rust theme={null}
#[instruction]
fn optimized_sum(
key: ArcisX25519Pubkey,
t_nonce: u128, t: EncData<u64>,
u_nonce: u128, u: EncData<u64>,
) -> u64 {
let t_val = t.to_arcis_with_pubkey_and_nonce(key, t_nonce);
let u_val = u.to_arcis_with_pubkey_and_nonce(key, u_nonce);
(t_val + u_val).reveal()
}
```
<Warning>
`EncData<T>` is an advanced optimization with security implications:
* **Nonce uniqueness:** Each (key, nonce) pair must be unique. Reusing nonces compromises security.
* **Silent failures:** Using the wrong key or nonce produces garbage data without error; MPC cannot add runtime validation since that would leak information.
For most use cases, use `Enc<Shared, T>` or `Enc<Mxe, T>`, which handle key management automatically.
</Warning>
## Unsupported types
Arcis does not currently support `HashMap`, `Vec`, or `String` because these types have variable length. Constant-size byte strings, such as `b"hello_world"`, are supported.
The `Enc` type defines encrypted data input as `Enc<Owner, T>`, where `Owner` can be either `Mxe` or `Shared`. `Owner` determines which party can decrypt data of type `T`. See [Input/output](/developers/arcis/input-output) for encrypted input and output patterns.
<Note>
**Storage representation:** All values are stored as 256-bit Curve25519 field elements. A `u8` uses the same storage as a `u128`; integer type bounds are enforced at compile time, not by storage size. Use `Pack<T>` to compress multiple small values into fewer field elements for onchain efficiency.
</Note>
## What's next?
<CardGroup>
<Card title="Input/output" icon="arrow-right-arrow-left" href="/developers/arcis/input-output">
Working with `Enc<Owner, T>` for encrypted inputs and outputs.
</Card>
<Card title="Thinking in MPC" icon="brain" href="/developers/arcis/mental-model">
MPC constraints and the operation cost model.
</Card>
</CardGroup>
# Arcium.toml
Source: https://docs.arcium.com/developers/arcium-toml
Configuration reference for the Arcium CLI tooling suite
`Arcium.toml` is auto-generated by `arcium init` and configures the Arcium CLI tooling. It lives at the root of your project alongside `Anchor.toml`.
Most projects only need to edit this file when changing localnet behavior or adding a cluster offset for devnet or mainnet testing.
## Localnet configuration
The `[localnet]` section controls your local development cluster. All required fields are auto-generated by `arcium init` with sensible defaults.
| Field | Type | Required | Default | Description |
| ----------------------- | ------------------ | -------- | ------------------------------ | --------------------------------------------------- |
| `nodes` | integer | Yes | `2` | Number of MPC nodes. Minimum: 2 |
| `nodes_ips` | array of `[u8; 4]` | No | Sequential from `172.20.0.100` | IPv4 addresses for each node |
| `localnet_timeout_secs` | integer | Yes | `60` | Seconds to wait for localnet startup |
| `backends` | array of string | No | Ignored | Written by the init template but ignored by the CLI |
Use the default values unless you need to test against a larger local cluster or a custom Docker network setup.
## Choose a local validator
The CLI uses the legacy validator by default. To preview Surfpool after completing the [optional installation](/developers/installation), select it for each local command:
```bash theme={null}
arcium test --validator surfpool
arcium localnet --validator surfpool
```
The validator choice is not stored in `Arcium.toml`. `--validator` takes precedence over `ARCIUM_LOCAL_VALIDATOR`; both accept `legacy` or `surfpool`. The CLI rejects `--validator` with a non-local `--cluster`.
## Cluster configuration
The `[clusters.<name>]` sections map network names to cluster offsets. These entries are used by `arcium test --cluster <name>` to resolve the cluster offset for testing.
| Field | Type | Required | Description |
| -------- | ------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `offset` | integer | Yes | Cluster offset for PDA derivation. See [Deployment - Cluster offsets](/developers/deployment#understanding-cluster-offsets) for current values. |
The CLI reads these entries when you run commands such as:
```bash theme={null}
arcium test --cluster devnet
```
For local tests without a `--cluster` argument, the CLI uses the `[localnet]` configuration.
## Full example
```toml theme={null}
[localnet]
nodes = 2
nodes_ips = [
[172, 20, 0, 100],
[172, 20, 0, 101]
]
localnet_timeout_secs = 60
backends = ["Cerberus"] # Ignored by the CLI
[clusters.devnet]
offset = 456
[clusters.mainnet]
offset = 2026
```
## Common mistakes
| Issue | Fix |
| ---------------------------------------------------- | -------------------------------------------------------------------- |
| `arcium test --cluster <name>` cannot find a cluster | Add `[clusters.<name>]` with an `offset` field |
| Tests derive the wrong cluster account | Check that the offset matches the target network |
| Localnet startup times out | Increase `localnet_timeout_secs` or reduce local resource contention |
| Custom node IPs do not work | Keep `nodes` and `nodes_ips` lengths aligned |
# Computation lifecycle
Source: https://docs.arcium.com/developers/computation-lifecycle
How computations flow from client-side encryption through MPC execution to callback
Before diving into the details of the tooling, it's useful to understand the general architecture of Arcium. The below diagram gives a high-level overview of the lifecycle of a typical interaction with Arcium (we call these "computations").
```mermaid theme={null}
sequenceDiagram
participant Client
participant MXE Program
participant Arcium Program
participant MPC Cluster
Client->>Client: Encrypt params
Client->>MXE Program: Invoke computation with encrypted params
MXE Program->>Arcium Program: Handle & format params and send to Arcium Program
Arcium Program->>Arcium Program: Queue Computation in Cluster's Mempool
MPC Cluster->>Arcium Program: Fetch new computation from mempool
MPC Cluster->>MPC Cluster: Compute using MPC
MPC Cluster->>Arcium Program: Callback with Result
Arcium Program->>Arcium Program: Verify Result
Arcium Program->>MXE Program: Invoke callback instruction with result
MXE Program->>MXE Program: Handle Result
MXE Program->>Client: Notify of completion
```
We have 4 key actors here:
* The client: The party that wants to perform a computation, usually the user of your MXE. This is implemented using the [Arcium TypeScript client library](/developers/js-client-library).
* The MXE Program: Your app. An MXE (MPC eXecution Environment) consists of everything needed to perform computations and is implemented using the [Arcium program tooling](/developers/program):
* A smart contract that is deployed on the blockchain and is used to format and submit computations to Arcium.
* A set of encrypted instructions (we call these "computation definitions") that are used to define what parameters are needed for the computation and what the computation is. Writing these is done using [Arcis](/developers/arcis).
* Some metadata about the MXE, most importantly the MPC cluster we would like to use to compute our computations.
* The Arcium Program: The program in charge of assigning, scheduling, and verifying computations for the various MPC clusters to perform.
* The MPC Cluster: The parties that are performing the client's computations using MPC.
The MXE and its computation definitions are onchain accounts with their own lifecycle. When you no longer need them, you can close them and reclaim rent. See [Account lifecycle and closing](/developers/program/account-lifecycle).
## What's next?
<CardGroup>
<Card title="Write encrypted instructions" icon="code" href="/developers/arcis">
Learn the Arcis framework for encrypted business logic.
</Card>
<Card title="Encryption" icon="binary-lock" href="/developers/encryption">
How X25519 key exchange and Rescue cipher protect your data.
</Card>
<Card title="Invoke from Solana" icon="link" href="/developers/program">
Queue computations from your Solana program.
</Card>
</CardGroup>
# Continuous integration
Source: https://docs.arcium.com/developers/continuous-integration
Build and test Arcium projects in GitHub Actions with a pinned setup-arcium toolchain
The [`arcium-hq/setup-arcium`](https://github.com/arcium-hq/setup-arcium) action installs the Arcium CLI, Anchor, Solana CLI, Node.js, and Yarn so you can build and test an MXE in GitHub Actions.
## Add the workflow
```yaml theme={null}
name: arcium
on:
push:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: arcium-hq/setup-arcium@v0.15.0
with:
runner-arch-os: x86_64_linux
arcium-version: "0.15.0"
anchor-version: "1.0.2"
solana-cli-version: "3.1.10"
node-version: "24.10.0"
- name: Install dependencies
run: yarn install --frozen-lockfile
shell: bash
- name: Build
run: arcium build
shell: bash
- name: Test
run: |
sudo prlimit --pid $$ --nofile=1048576:1048576
arcium test
shell: bash
```
Pin the action and each tool to versions that match your project. Check the [setup-arcium releases](https://github.com/arcium-hq/setup-arcium/releases) before changing the action version.
## Co프로젝트로 돌아가기